blob: 73cbcfae3704d2531f3be43b1a71b3a9b705efb5 [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>> {
Jiyong Park753553b2021-07-12 21:21:09 +0900135 check_manage_access()?;
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000136 let state = &mut *self.state.lock().unwrap();
Andrew Scull527e5772022-02-11 15:43:28 +0000137 let console_fd = console_fd.map(clone_file).transpose()?;
138 let log_fd = log_fd.map(clone_file).transpose()?;
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000139 let requester_uid = ThreadState::get_calling_uid();
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000140 let requester_sid = get_calling_sid()?;
Andrew Walbran02034492021-04-13 15:05:07 +0000141 let requester_debug_pid = ThreadState::get_calling_pid();
Jiyong Parkd50a0242021-09-16 21:00:14 +0900142 let cid = next_cid().or(Err(ExceptionCode::ILLEGAL_STATE))?;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000143
144 // Counter to generate unique IDs for temporary image files.
145 let mut next_temporary_image_id = 0;
146 // Files which are referred to from composite images. These must be mapped to the crosvm
147 // child process, and not closed before it is started.
148 let mut indirect_files = vec![];
149
150 // Make directory for temporary files.
151 let temporary_directory: PathBuf = format!("{}/{}", TEMPORARY_DIRECTORY, cid).into();
152 create_dir(&temporary_directory).map_err(|e| {
Treehugger Robot3ffa8322021-11-22 12:06:47 +0000153 // At this point, we do not know the protected status of Vm
154 // setting it to false, though this may not be correct.
155 write_vm_creation_stats(false, false);
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000156 error!(
Andrew Walbran806f1542021-06-10 14:07:12 +0000157 "Failed to create temporary directory {:?} for VM files: {}",
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000158 temporary_directory, e
159 );
Andrew Walbran806f1542021-06-10 14:07:12 +0000160 new_binder_exception(
161 ExceptionCode::SERVICE_SPECIFIC,
162 format!(
163 "Failed to create temporary directory {:?} for VM files: {}",
164 temporary_directory, e
165 ),
166 )
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000167 })?;
168
Jiyong Park029977d2021-11-24 21:56:49 +0900169 let is_app_config = matches!(config, VirtualMachineConfig::AppConfig(_));
170
Jooyung Han21e9b922021-06-26 04:14:16 +0900171 let config = match config {
Jooyung Han35edb8f2021-07-01 16:17:16 +0900172 VirtualMachineConfig::AppConfig(config) => BorrowedOrOwned::Owned(
Jooyung Han9900f3d2021-07-06 10:27:54 +0900173 load_app_config(config, &temporary_directory).map_err(|e| {
174 error!("Failed to load app config from {}: {}", &config.configPath, e);
Andrew Walbran3994f002022-01-27 17:33:45 +0000175 write_vm_creation_stats(config.protectedVm, false);
Jooyung Han9900f3d2021-07-06 10:27:54 +0900176 new_binder_exception(
177 ExceptionCode::SERVICE_SPECIFIC,
178 format!("Failed to load app config from {}: {}", &config.configPath, e),
179 )
180 })?,
Jooyung Han35edb8f2021-07-01 16:17:16 +0900181 ),
182 VirtualMachineConfig::RawConfig(config) => BorrowedOrOwned::Borrowed(config),
Jooyung Han21e9b922021-06-26 04:14:16 +0900183 };
Jooyung Han35edb8f2021-07-01 16:17:16 +0900184 let config = config.as_ref();
Andrew Walbran3994f002022-01-27 17:33:45 +0000185 let protected = config.protectedVm;
186
Jiyong Park029977d2021-11-24 21:56:49 +0900187 // Check if partition images are labeled incorrectly. This is to prevent random images
188 // which are not protected by the Android Verified Boot (e.g. bits downloaded by apps) from
189 // being loaded in a pVM. Specifically, for images in the raw config, nothing is allowed
190 // to be labeled as app_data_file. For images in the app config, nothing but the instance
191 // partition is allowed to be labeled as such.
192 config
193 .disks
194 .iter()
195 .flat_map(|disk| disk.partitions.iter())
196 .filter(|partition| {
197 if is_app_config {
198 partition.label != "vm-instance"
199 } else {
200 true // all partitions are checked
201 }
202 })
203 .try_for_each(check_label_for_partition)
204 .map_err(|e| new_binder_exception(ExceptionCode::SERVICE_SPECIFIC, e.to_string()))?;
205
Jooyung Han95884632021-07-06 22:27:54 +0900206 let zero_filler_path = temporary_directory.join("zero.img");
Andrew Walbranfbb39d22021-07-28 17:01:25 +0000207 write_zero_filler(&zero_filler_path).map_err(|e| {
Jooyung Han95884632021-07-06 22:27:54 +0900208 error!("Failed to make composite image: {}", e);
Andrew Walbran3994f002022-01-27 17:33:45 +0000209 write_vm_creation_stats(protected, false);
Jooyung Han95884632021-07-06 22:27:54 +0900210 new_binder_exception(
211 ExceptionCode::SERVICE_SPECIFIC,
212 format!("Failed to make composite image: {}", e),
213 )
214 })?;
Jooyung Han95884632021-07-06 22:27:54 +0900215
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000216 // Assemble disk images if needed.
217 let disks = config
218 .disks
219 .iter()
220 .map(|disk| {
221 assemble_disk_image(
222 disk,
Jooyung Han95884632021-07-06 22:27:54 +0900223 &zero_filler_path,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000224 &temporary_directory,
225 &mut next_temporary_image_id,
226 &mut indirect_files,
227 )
228 })
229 .collect::<Result<Vec<DiskFile>, _>>()?;
230
231 // Actually start the VM.
232 let crosvm_config = CrosvmConfig {
Andrew Walbran02034492021-04-13 15:05:07 +0000233 cid,
Andrew Walbrand3a84182021-09-07 14:48:52 +0000234 bootloader: maybe_clone_file(&config.bootloader)?,
235 kernel: maybe_clone_file(&config.kernel)?,
236 initrd: maybe_clone_file(&config.initrd)?,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000237 disks,
238 params: config.params.to_owned(),
Jiyong Parkd2dc83f2021-12-20 18:40:52 +0900239 protected,
Andrew Walbrancc045902021-07-27 16:06:17 +0000240 memory_mib: config.memoryMib.try_into().ok().and_then(NonZeroU32::new),
Jiyong Park032615f2022-01-10 13:55:34 +0900241 cpus: config.numCpus.try_into().ok().and_then(NonZeroU32::new),
242 cpu_affinity: config.cpuAffinity.clone(),
Jiyong Parkb8182bb2021-10-26 22:53:08 +0900243 console_fd,
Andrew Walbran02034492021-04-13 15:05:07 +0000244 log_fd,
Andrew Walbrand3a84182021-09-07 14:48:52 +0000245 indirect_files,
Jiyong Parkdcf17412022-02-08 15:07:23 +0900246 platform_version: parse_platform_version_req(&config.platformVersion)?,
Andrew Walbrand3a84182021-09-07 14:48:52 +0000247 };
Andrew Walbranf8d94112021-09-07 11:45:36 +0000248 let instance = Arc::new(
249 VmInstance::new(
250 crosvm_config,
251 temporary_directory,
252 requester_uid,
253 requester_sid,
254 requester_debug_pid,
Andrew Walbran806f1542021-06-10 14:07:12 +0000255 )
Andrew Walbranf8d94112021-09-07 11:45:36 +0000256 .map_err(|e| {
257 error!("Failed to create VM with config {:?}: {}", config, e);
Andrew Walbran3994f002022-01-27 17:33:45 +0000258 write_vm_creation_stats(protected, false);
Andrew Walbranf8d94112021-09-07 11:45:36 +0000259 new_binder_exception(
260 ExceptionCode::SERVICE_SPECIFIC,
261 format!("Failed to create VM: {}", e),
262 )
263 })?,
264 );
Andrew Walbran320b5602021-03-04 16:11:12 +0000265 state.add_vm(Arc::downgrade(&instance));
Andrew Walbran3994f002022-01-27 17:33:45 +0000266 write_vm_creation_stats(protected, true);
Andrew Walbran320b5602021-03-04 16:11:12 +0000267 Ok(VirtualMachine::create(instance))
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000268 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000269
Andrew Walbrandff3b942021-06-09 15:20:36 +0000270 /// Initialise an empty partition image of the given size to be used as a writable partition.
271 fn initializeWritablePartition(
272 &self,
273 image_fd: &ParcelFileDescriptor,
274 size: i64,
Jiyong Park9dd389e2021-08-23 20:42:59 +0900275 partition_type: PartitionType,
Andrew Walbrandff3b942021-06-09 15:20:36 +0000276 ) -> binder::Result<()> {
Jiyong Park753553b2021-07-12 21:21:09 +0900277 check_manage_access()?;
Andrew Walbrandfc953d2021-06-10 13:59:56 +0000278 let size = size.try_into().map_err(|e| {
Andrew Walbran806f1542021-06-10 14:07:12 +0000279 new_binder_exception(
280 ExceptionCode::ILLEGAL_ARGUMENT,
281 format!("Invalid size {}: {}", size, e),
282 )
Andrew Walbrandff3b942021-06-09 15:20:36 +0000283 })?;
Andrew Walbrandfc953d2021-06-10 13:59:56 +0000284 let image = clone_file(image_fd)?;
Jooyung Han1edd5b92021-10-28 10:58:05 +0900285 // initialize the file. Any data in the file will be erased.
286 image.set_len(0).map_err(|e| {
287 new_binder_exception(
288 ExceptionCode::SERVICE_SPECIFIC,
289 format!("Failed to reset a file: {}", e),
290 )
291 })?;
Jiyong Park9dd389e2021-08-23 20:42:59 +0900292 let mut part = QcowFile::new(image, size).map_err(|e| {
Andrew Walbran806f1542021-06-10 14:07:12 +0000293 new_binder_exception(
294 ExceptionCode::SERVICE_SPECIFIC,
295 format!("Failed to create QCOW2 image: {}", e),
296 )
Andrew Walbrandfc953d2021-06-10 13:59:56 +0000297 })?;
Andrew Walbrandff3b942021-06-09 15:20:36 +0000298
Jiyong Park9dd389e2021-08-23 20:42:59 +0900299 match partition_type {
300 PartitionType::RAW => Ok(()),
301 PartitionType::ANDROID_VM_INSTANCE => format_as_android_vm_instance(&mut part),
302 _ => Err(Error::new(
303 ErrorKind::Unsupported,
304 format!("Unsupported partition type {:?}", partition_type),
305 )),
306 }
307 .map_err(|e| {
308 new_binder_exception(
309 ExceptionCode::SERVICE_SPECIFIC,
310 format!("Failed to initialize partition as {:?}: {}", partition_type, e),
311 )
312 })?;
313
Andrew Walbrandff3b942021-06-09 15:20:36 +0000314 Ok(())
315 }
316
Jiyong Park0a248432021-08-20 23:32:39 +0900317 /// Creates or update the idsig file by digesting the input APK file.
318 fn createOrUpdateIdsigFile(
319 &self,
320 input_fd: &ParcelFileDescriptor,
321 idsig_fd: &ParcelFileDescriptor,
322 ) -> binder::Result<()> {
323 // TODO(b/193504400): do this only when (1) idsig_fd is empty or (2) the APK digest in
324 // idsig_fd is different from APK digest in input_fd
325
326 let mut input = clone_file(input_fd)?;
327 let mut sig = V4Signature::create(&mut input, 4096, &[], HashAlgorithm::SHA256).unwrap();
328
329 let mut output = clone_file(idsig_fd)?;
330 output.set_len(0).unwrap();
331 sig.write_into(&mut output).unwrap();
332 Ok(())
333 }
334
Andrew Walbran320b5602021-03-04 16:11:12 +0000335 /// Get a list of all currently running VMs. This method is only intended for debug purposes,
336 /// and as such is only permitted from the shell user.
337 fn debugListVms(&self) -> binder::Result<Vec<VirtualMachineDebugInfo>> {
Andrew Walbran806f1542021-06-10 14:07:12 +0000338 check_debug_access()?;
Andrew Walbran320b5602021-03-04 16:11:12 +0000339
340 let state = &mut *self.state.lock().unwrap();
341 let vms = state.vms();
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000342 let cids = vms
343 .into_iter()
344 .map(|vm| VirtualMachineDebugInfo {
345 cid: vm.cid as i32,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000346 temporaryDirectory: vm.temporary_directory.to_string_lossy().to_string(),
Andrew Walbran1ef19ae2021-04-07 11:31:57 +0000347 requesterUid: vm.requester_uid as i32,
348 requesterSid: vm.requester_sid.clone(),
Andrew Walbran02034492021-04-13 15:05:07 +0000349 requesterPid: vm.requester_debug_pid,
Andrew Walbran6b650662021-09-07 13:13:23 +0000350 state: get_state(&vm),
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000351 })
352 .collect();
Andrew Walbran320b5602021-03-04 16:11:12 +0000353 Ok(cids)
354 }
David Brazdil3c2ddef2021-03-18 13:09:57 +0000355
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000356 /// Hold a strong reference to a VM in VirtualizationService. This method is only intended for
357 /// debug purposes, and as such is only permitted from the shell user.
Andrei Homescu1415c132021-03-24 02:39:55 +0000358 fn debugHoldVmRef(&self, vmref: &Strong<dyn IVirtualMachine>) -> binder::Result<()> {
Andrew Walbran806f1542021-06-10 14:07:12 +0000359 check_debug_access()?;
David Brazdil3c2ddef2021-03-18 13:09:57 +0000360
David Brazdil3c2ddef2021-03-18 13:09:57 +0000361 let state = &mut *self.state.lock().unwrap();
Andrei Homescu1415c132021-03-24 02:39:55 +0000362 state.debug_hold_vm(vmref.clone());
David Brazdil3c2ddef2021-03-18 13:09:57 +0000363 Ok(())
364 }
365
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000366 /// Drop reference to a VM that is being held by VirtualizationService. Returns the reference if
367 /// the VM was found and None otherwise. This method is only intended for debug purposes, and as
368 /// such is only permitted from the shell user.
David Brazdil3c2ddef2021-03-18 13:09:57 +0000369 fn debugDropVmRef(&self, cid: i32) -> binder::Result<Option<Strong<dyn IVirtualMachine>>> {
Andrew Walbran806f1542021-06-10 14:07:12 +0000370 check_debug_access()?;
David Brazdil3c2ddef2021-03-18 13:09:57 +0000371
372 let state = &mut *self.state.lock().unwrap();
373 Ok(state.debug_drop_vm(cid))
374 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000375}
376
Shikha Panwar7afc1392022-03-24 08:54:43 +0000377fn handle_stream_connection_tombstoned() -> Result<()> {
378 let listener =
379 VsockListener::bind_with_cid_port(VMADDR_CID_HOST, VM_TOMBSTONES_SERVICE_PORT as u32)?;
380 info!("Listening to tombstones from guests ...");
381 for incoming_stream in listener.incoming() {
382 let mut incoming_stream = match incoming_stream {
383 Err(e) => {
384 warn!("invalid incoming connection: {}", e);
385 continue;
386 }
387 Ok(s) => s,
388 };
389 std::thread::spawn(move || {
390 if let Err(e) = handle_tombstone(&mut incoming_stream) {
391 error!("Failed to write tombstone- {:?}", e);
392 }
393 });
394 }
395 Ok(())
396}
397
398fn handle_tombstone(stream: &mut VsockStream) -> Result<()> {
399 if let Ok(SockAddr::Vsock(addr)) = stream.peer_addr() {
400 info!("Vsock Stream connected to cid={} for tombstones", addr.cid());
401 }
402 let tb_connection =
403 TombstonedConnection::connect(std::process::id() as i32, DebuggerdDumpType::Tombstone)
404 .context("Failed to connect to tombstoned")?;
405 let mut text_output = tb_connection
406 .text_output
407 .as_ref()
408 .ok_or_else(|| anyhow!("Could not get file to write the tombstones on"))?;
409 let mut num_bytes_read = 0;
410 loop {
411 let mut chunk_recv = [0; CHUNK_RECV_MAX_LEN];
412 let n = stream
413 .read(&mut chunk_recv)
414 .context("Failed to read tombstone data from Vsock stream")?;
415 if n == 0 {
416 break;
417 }
418 num_bytes_read += n;
419 text_output.write_all(&chunk_recv[0..n]).context("Failed to write guests tombstones")?;
420 }
421 info!("Received {} bytes from guest & wrote to tombstone file", num_bytes_read);
422 tb_connection.notify_completion()?;
423 Ok(())
424}
425
Jiyong Park8611a6c2021-07-09 18:17:44 +0900426impl VirtualizationService {
427 pub fn init() -> VirtualizationService {
428 let service = VirtualizationService::default();
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900429
430 // server for payload output
Jiyong Park8611a6c2021-07-09 18:17:44 +0900431 let state = service.state.clone(); // reference to state (not the state itself) is copied
432 std::thread::spawn(move || {
Inseob Kim7f61fe72021-08-20 20:50:47 +0900433 handle_stream_connection_from_vm(state).unwrap();
Jiyong Park8611a6c2021-07-09 18:17:44 +0900434 });
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900435
Shikha Panwar7afc1392022-03-24 08:54:43 +0000436 std::thread::spawn(|| {
437 if let Err(e) = handle_stream_connection_tombstoned() {
438 warn!("Error receiving tombstone from guest or writing them. Error: {}", e);
439 }
440 });
441
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900442 // binder server for vm
Shikha Panwar7afc1392022-03-24 08:54:43 +0000443 // reference to state (not the state itself) is copied
444 let mut state = service.state.clone();
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900445 std::thread::spawn(move || {
Inseob Kimc7d28c72021-10-25 14:28:10 +0000446 let state_ptr = &mut state as *mut _ as *mut raw::c_void;
447
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900448 debug!("virtual machine service is starting as an RPC service.");
Inseob Kimc7d28c72021-10-25 14:28:10 +0000449 // SAFETY: factory function is only ever called by RunRpcServerWithFactory, within the
450 // lifetime of the state, with context taking the pointer value above (so a properly
451 // aligned non-null pointer to an initialized instance).
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900452 let retval = unsafe {
Inseob Kimc7d28c72021-10-25 14:28:10 +0000453 binder_rpc_unstable_bindgen::RunRpcServerWithFactory(
454 Some(VirtualMachineService::factory),
455 state_ptr,
Inseob Kimd0587562021-09-01 21:27:32 +0900456 VM_BINDER_SERVICE_PORT as u32,
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900457 )
458 };
459 if retval {
460 debug!("RPC server has shut down gracefully");
461 } else {
462 bail!("Premature termination of RPC server");
463 }
464
465 Ok(retval)
466 });
Jiyong Park8611a6c2021-07-09 18:17:44 +0900467 service
468 }
469}
470
Treehugger Robot3ffa8322021-11-22 12:06:47 +0000471/// Write the stats of VMCreation to statsd
472fn write_vm_creation_stats(protected: bool, success: bool) {
473 match stats_write(Hypervisor::Pkvm, protected, success) {
474 Err(e) => {
Andrew Walbranf6d600f2022-02-03 14:42:39 +0000475 warn!("statslog_rust failed with error: {}", e);
Treehugger Robot3ffa8322021-11-22 12:06:47 +0000476 }
Andrew Walbranf6d600f2022-02-03 14:42:39 +0000477 Ok(_) => trace!("statslog_rust succeeded for virtualization service"),
Treehugger Robot3ffa8322021-11-22 12:06:47 +0000478 }
479}
480
Andrew Walbran6b650662021-09-07 13:13:23 +0000481/// Waits for incoming connections from VM. If a new connection is made, stores the stream in the
482/// corresponding `VmInstance`.
Inseob Kim7f61fe72021-08-20 20:50:47 +0900483fn handle_stream_connection_from_vm(state: Arc<Mutex<State>>) -> Result<()> {
Inseob Kimd0587562021-09-01 21:27:32 +0900484 let listener =
485 VsockListener::bind_with_cid_port(VMADDR_CID_HOST, VM_STREAM_SERVICE_PORT as u32)?;
Jiyong Park8611a6c2021-07-09 18:17:44 +0900486 for stream in listener.incoming() {
487 let stream = match stream {
488 Err(e) => {
489 warn!("invalid incoming connection: {}", e);
490 continue;
491 }
492 Ok(s) => s,
493 };
494 if let Ok(SockAddr::Vsock(addr)) = stream.peer_addr() {
495 let cid = addr.cid();
496 let port = addr.port();
Inseob Kim7f61fe72021-08-20 20:50:47 +0900497 info!("payload stream connected from cid={}, port={}", cid, port);
Jiyong Park8611a6c2021-07-09 18:17:44 +0900498 if let Some(vm) = state.lock().unwrap().get_vm(cid) {
Chris Wailes8bbb8932021-09-10 14:14:19 -0700499 *vm.stream.lock().unwrap() = Some(stream);
Inseob Kim7f61fe72021-08-20 20:50:47 +0900500 } else {
501 error!("connection from cid={} is not from a guest VM", cid);
Jiyong Park8611a6c2021-07-09 18:17:44 +0900502 }
503 }
504 }
505 Ok(())
506}
507
Andrew Walbranfbb39d22021-07-28 17:01:25 +0000508fn write_zero_filler(zero_filler_path: &Path) -> Result<()> {
Jooyung Han95884632021-07-06 22:27:54 +0900509 let file = OpenOptions::new()
510 .create_new(true)
511 .read(true)
512 .write(true)
513 .open(zero_filler_path)
514 .with_context(|| "Failed to create zero.img")?;
515 file.set_len(ZERO_FILLER_SIZE)?;
Andrew Walbranfbb39d22021-07-28 17:01:25 +0000516 Ok(())
Jooyung Han95884632021-07-06 22:27:54 +0900517}
518
Jiyong Park9dd389e2021-08-23 20:42:59 +0900519fn format_as_android_vm_instance(part: &mut dyn Write) -> std::io::Result<()> {
520 part.write_all(ANDROID_VM_INSTANCE_MAGIC.as_bytes())?;
521 part.write_all(&ANDROID_VM_INSTANCE_VERSION.to_le_bytes())?;
522 part.flush()
523}
524
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000525/// Given the configuration for a disk image, assembles the `DiskFile` to pass to crosvm.
526///
527/// This may involve assembling a composite disk from a set of partition images.
528fn assemble_disk_image(
529 disk: &DiskImage,
Jooyung Han95884632021-07-06 22:27:54 +0900530 zero_filler_path: &Path,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000531 temporary_directory: &Path,
532 next_temporary_image_id: &mut u64,
533 indirect_files: &mut Vec<File>,
Andrew Walbran806f1542021-06-10 14:07:12 +0000534) -> Result<DiskFile, Status> {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000535 let image = if !disk.partitions.is_empty() {
536 if disk.image.is_some() {
537 warn!("DiskImage {:?} contains both image and partitions.", disk);
Andrew Walbran806f1542021-06-10 14:07:12 +0000538 return Err(new_binder_exception(
539 ExceptionCode::ILLEGAL_ARGUMENT,
540 "DiskImage contains both image and partitions.",
541 ));
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000542 }
543
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000544 let composite_image_filenames =
545 make_composite_image_filenames(temporary_directory, next_temporary_image_id);
546 let (image, partition_files) = make_composite_image(
547 &disk.partitions,
Jooyung Han95884632021-07-06 22:27:54 +0900548 zero_filler_path,
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000549 &composite_image_filenames.composite,
550 &composite_image_filenames.header,
551 &composite_image_filenames.footer,
552 )
553 .map_err(|e| {
554 error!("Failed to make composite image with config {:?}: {}", disk, e);
555 new_binder_exception(
556 ExceptionCode::SERVICE_SPECIFIC,
557 format!("Failed to make composite image: {}", e),
558 )
559 })?;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000560
561 // Pass the file descriptors for the various partition files to crosvm when it
562 // is run.
563 indirect_files.extend(partition_files);
564
565 image
566 } else if let Some(image) = &disk.image {
567 clone_file(image)?
568 } else {
569 warn!("DiskImage {:?} didn't contain image or partitions.", disk);
Andrew Walbran806f1542021-06-10 14:07:12 +0000570 return Err(new_binder_exception(
571 ExceptionCode::ILLEGAL_ARGUMENT,
572 "DiskImage didn't contain image or partitions.",
573 ));
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000574 };
575
576 Ok(DiskFile { image, writable: disk.writable })
577}
578
Jooyung Han21e9b922021-06-26 04:14:16 +0900579fn load_app_config(
580 config: &VirtualMachineAppConfig,
581 temporary_directory: &Path,
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900582) -> Result<VirtualMachineRawConfig> {
Andrew Walbrancc0db522021-07-12 17:03:42 +0000583 let apk_file = clone_file(config.apk.as_ref().unwrap())?;
584 let idsig_file = clone_file(config.idsig.as_ref().unwrap())?;
Jiyong Park8d081812021-07-23 17:45:04 +0900585 let instance_file = clone_file(config.instanceImage.as_ref().unwrap())?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900586 let config_path = &config.configPath;
587
Andrew Walbrancc0db522021-07-12 17:03:42 +0000588 let mut apk_zip = ZipArchive::new(&apk_file)?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900589 let config_file = apk_zip.by_name(config_path)?;
590 let vm_payload_config: VmPayloadConfig = serde_json::from_reader(config_file)?;
591
592 let os_name = &vm_payload_config.os.name;
Andrew Walbrancc0db522021-07-12 17:03:42 +0000593
Jooyung Han35edb8f2021-07-01 16:17:16 +0900594 // For now, the only supported "os" value is "microdroid"
595 if os_name != "microdroid" {
Andrew Walbrancc0db522021-07-12 17:03:42 +0000596 bail!("Unknown OS \"{}\"", os_name);
Jooyung Han35edb8f2021-07-01 16:17:16 +0900597 }
Andrew Walbrancc0db522021-07-12 17:03:42 +0000598
599 // It is safe to construct a filename based on the os_name because we've already checked that it
600 // is one of the allowed values.
Jooyung Han21e9b922021-06-26 04:14:16 +0900601 let vm_config_path = PathBuf::from(format!("/apex/com.android.virt/etc/{}.json", os_name));
602 let vm_config_file = File::open(vm_config_path)?;
Andrew Walbrancc0db522021-07-12 17:03:42 +0000603 let mut vm_config = VmConfig::load(&vm_config_file)?.to_parcelable()?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900604
Andrew Walbrancc045902021-07-27 16:06:17 +0000605 if config.memoryMib > 0 {
606 vm_config.memoryMib = config.memoryMib;
Andrew Walbran45bcb0c2021-07-14 15:02:06 +0000607 }
608
Andrew Walbran3994f002022-01-27 17:33:45 +0000609 vm_config.protectedVm = config.protectedVm;
Jiyong Park032615f2022-01-10 13:55:34 +0900610 vm_config.numCpus = config.numCpus;
611 vm_config.cpuAffinity = config.cpuAffinity.clone();
612
Andrew Walbrancc0db522021-07-12 17:03:42 +0000613 // Microdroid requires an additional payload disk image and the bootconfig partition.
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900614 if os_name == "microdroid" {
Andrew Walbrancc0db522021-07-12 17:03:42 +0000615 add_microdroid_images(
616 config,
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900617 temporary_directory,
Andrew Walbrancc0db522021-07-12 17:03:42 +0000618 apk_file,
619 idsig_file,
Jiyong Park8d081812021-07-23 17:45:04 +0900620 instance_file,
Jooyung Han5dc42172021-10-05 16:43:47 +0900621 &vm_payload_config,
Andrew Walbrancc0db522021-07-12 17:03:42 +0000622 &mut vm_config,
623 )?;
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900624 }
Jooyung Han21e9b922021-06-26 04:14:16 +0900625
Andrew Walbrancc0db522021-07-12 17:03:42 +0000626 Ok(vm_config)
Jooyung Han21e9b922021-06-26 04:14:16 +0900627}
628
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000629/// Generates a unique filename to use for a composite disk image.
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000630fn make_composite_image_filenames(
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000631 temporary_directory: &Path,
632 next_temporary_image_id: &mut u64,
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000633) -> CompositeImageFilenames {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000634 let id = *next_temporary_image_id;
635 *next_temporary_image_id += 1;
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000636 CompositeImageFilenames {
637 composite: temporary_directory.join(format!("composite-{}.img", id)),
638 header: temporary_directory.join(format!("composite-{}-header.img", id)),
639 footer: temporary_directory.join(format!("composite-{}-footer.img", id)),
640 }
641}
642
643/// Filenames for a composite disk image, including header and footer partitions.
644#[derive(Clone, Debug, Eq, PartialEq)]
645struct CompositeImageFilenames {
646 /// The composite disk image itself.
647 composite: PathBuf,
648 /// The header partition image.
649 header: PathBuf,
650 /// The footer partition image.
651 footer: PathBuf,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000652}
653
654/// Gets the calling SID of the current Binder thread.
Andrew Walbran806f1542021-06-10 14:07:12 +0000655fn get_calling_sid() -> Result<String, Status> {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000656 ThreadState::with_calling_sid(|sid| {
657 if let Some(sid) = sid {
658 match sid.to_str() {
659 Ok(sid) => Ok(sid.to_owned()),
660 Err(e) => {
Andrew Walbran806f1542021-06-10 14:07:12 +0000661 error!("SID was not valid UTF-8: {}", e);
662 Err(new_binder_exception(
663 ExceptionCode::ILLEGAL_ARGUMENT,
664 format!("SID was not valid UTF-8: {}", e),
665 ))
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000666 }
667 }
668 } else {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000669 error!("Missing SID on createVm");
670 Err(new_binder_exception(ExceptionCode::SECURITY, "Missing SID on createVm"))
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000671 }
672 })
673}
674
Jiyong Park753553b2021-07-12 21:21:09 +0900675/// Checks whether the caller has a specific permission
676fn check_permission(perm: &str) -> binder::Result<()> {
677 let calling_pid = ThreadState::get_calling_pid();
678 let calling_uid = ThreadState::get_calling_uid();
679 // Root can do anything
680 if calling_uid == 0 {
681 return Ok(());
682 }
683 let perm_svc: Strong<dyn IPermissionController::IPermissionController> =
684 binder::get_interface("permission")?;
685 if perm_svc.checkPermission(perm, calling_pid, calling_uid as i32)? {
Andrew Walbran806f1542021-06-10 14:07:12 +0000686 Ok(())
687 } else {
Jiyong Park753553b2021-07-12 21:21:09 +0900688 Err(new_binder_exception(
689 ExceptionCode::SECURITY,
690 format!("does not have the {} permission", perm),
691 ))
Andrew Walbran806f1542021-06-10 14:07:12 +0000692 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000693}
694
Jiyong Park753553b2021-07-12 21:21:09 +0900695/// Check whether the caller of the current Binder method is allowed to call debug methods.
696fn check_debug_access() -> binder::Result<()> {
697 check_permission("android.permission.DEBUG_VIRTUAL_MACHINE")
698}
699
700/// Check whether the caller of the current Binder method is allowed to manage VMs
701fn check_manage_access() -> binder::Result<()> {
702 check_permission("android.permission.MANAGE_VIRTUAL_MACHINE")
703}
704
Jiyong Park029977d2021-11-24 21:56:49 +0900705/// Check if a partition has selinux labels that are not allowed
706fn check_label_for_partition(partition: &Partition) -> Result<()> {
707 let ctx = getfilecon(partition.image.as_ref().unwrap().as_ref())?;
708 if ctx == SeContext::new("u:object_r:app_data_file:s0").unwrap() {
709 Err(anyhow!("Partition {} shouldn't be labeled as {}", &partition.label, ctx))
710 } else {
711 Ok(())
712 }
713}
714
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000715/// Implementation of the AIDL `IVirtualMachine` interface. Used as a handle to a VM.
716#[derive(Debug)]
717struct VirtualMachine {
718 instance: Arc<VmInstance>,
Alan Stokes0cc59ee2021-09-24 11:20:34 +0100719 /// Keeps our service process running as long as this VM instance exists.
Chris Wailes641fc4a2021-12-01 15:03:21 -0800720 #[allow(dead_code)]
Alan Stokes0cc59ee2021-09-24 11:20:34 +0100721 lazy_service_guard: LazyServiceGuard,
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000722}
723
724impl VirtualMachine {
725 fn create(instance: Arc<VmInstance>) -> Strong<dyn IVirtualMachine> {
Alan Stokes0cc59ee2021-09-24 11:20:34 +0100726 let binder = VirtualMachine { instance, lazy_service_guard: Default::default() };
Andrew Walbran4de28782021-04-13 14:51:43 +0000727 BnVirtualMachine::new_binder(binder, BinderFeatures::default())
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000728 }
729}
730
731impl Interface for VirtualMachine {}
732
733impl IVirtualMachine for VirtualMachine {
734 fn getCid(&self) -> binder::Result<i32> {
Jiyong Park753553b2021-07-12 21:21:09 +0900735 // Don't check permission. The owner of the VM might have passed this binder object to
736 // others.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000737 Ok(self.instance.cid as i32)
738 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000739
Andrew Walbran6b650662021-09-07 13:13:23 +0000740 fn getState(&self) -> binder::Result<VirtualMachineState> {
Jiyong Park753553b2021-07-12 21:21:09 +0900741 // Don't check permission. The owner of the VM might have passed this binder object to
742 // others.
Andrew Walbran6b650662021-09-07 13:13:23 +0000743 Ok(get_state(&self.instance))
Andrew Walbrandae07162021-03-12 17:05:20 +0000744 }
745
746 fn registerCallback(
747 &self,
748 callback: &Strong<dyn IVirtualMachineCallback>,
749 ) -> binder::Result<()> {
Jiyong Park753553b2021-07-12 21:21:09 +0900750 // Don't check permission. The owner of the VM might have passed this binder object to
751 // others.
752 //
Andrew Walbrandae07162021-03-12 17:05:20 +0000753 // TODO: Should this give an error if the VM is already dead?
754 self.instance.callbacks.add(callback.clone());
755 Ok(())
756 }
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000757
Andrew Walbranf8d94112021-09-07 11:45:36 +0000758 fn start(&self) -> binder::Result<()> {
759 self.instance.start().map_err(|e| {
760 error!("Error starting VM with CID {}: {:?}", self.instance.cid, e);
761 new_binder_exception(ExceptionCode::SERVICE_SPECIFIC, e.to_string())
762 })
763 }
764
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000765 fn connectVsock(&self, port: i32) -> binder::Result<ParcelFileDescriptor> {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000766 if !matches!(&*self.instance.vm_state.lock().unwrap(), VmState::Running { .. }) {
767 return Err(new_binder_exception(ExceptionCode::SERVICE_SPECIFIC, "VM is not running"));
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000768 }
769 let stream =
770 VsockStream::connect_with_cid_port(self.instance.cid, port as u32).map_err(|e| {
771 new_binder_exception(
772 ExceptionCode::SERVICE_SPECIFIC,
773 format!("Failed to connect: {}", e),
774 )
775 })?;
776 Ok(vsock_stream_to_pfd(stream))
777 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000778}
779
780impl Drop for VirtualMachine {
781 fn drop(&mut self) {
782 debug!("Dropping {:?}", self);
783 self.instance.kill();
784 }
785}
786
787/// A set of Binders to be called back in response to various events on the VM, such as when it
788/// dies.
789#[derive(Debug, Default)]
790pub struct VirtualMachineCallbacks(Mutex<Vec<Strong<dyn IVirtualMachineCallback>>>);
791
792impl VirtualMachineCallbacks {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900793 /// Call all registered callbacks to notify that the payload has started.
Inseob Kim7f61fe72021-08-20 20:50:47 +0900794 pub fn notify_payload_started(&self, cid: Cid, stream: Option<VsockStream>) {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900795 let callbacks = &*self.0.lock().unwrap();
Inseob Kim7f61fe72021-08-20 20:50:47 +0900796 let pfd = stream.map(vsock_stream_to_pfd);
Jiyong Park8611a6c2021-07-09 18:17:44 +0900797 for callback in callbacks {
Inseob Kim7f61fe72021-08-20 20:50:47 +0900798 if let Err(e) = callback.onPayloadStarted(cid as i32, pfd.as_ref()) {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900799 error!("Error notifying payload start event from VM CID {}: {}", cid, e);
800 }
801 }
802 }
803
Inseob Kim14cb8692021-08-31 21:50:39 +0900804 /// Call all registered callbacks to notify that the payload is ready to serve.
805 pub fn notify_payload_ready(&self, cid: Cid) {
806 let callbacks = &*self.0.lock().unwrap();
807 for callback in callbacks {
808 if let Err(e) = callback.onPayloadReady(cid as i32) {
809 error!("Error notifying payload ready event from VM CID {}: {}", cid, e);
810 }
811 }
812 }
813
Inseob Kim2444af92021-08-31 01:22:50 +0900814 /// Call all registered callbacks to notify that the payload has finished.
815 pub fn notify_payload_finished(&self, cid: Cid, exit_code: i32) {
816 let callbacks = &*self.0.lock().unwrap();
817 for callback in callbacks {
818 if let Err(e) = callback.onPayloadFinished(cid as i32, exit_code) {
819 error!("Error notifying payload finish event from VM CID {}: {}", cid, e);
820 }
821 }
822 }
823
Jooyung Handd0a1732021-11-23 15:26:20 +0900824 /// Call all registered callbacks to say that the VM encountered an error.
825 pub fn notify_error(&self, cid: Cid, error_code: i32, message: &str) {
826 let callbacks = &*self.0.lock().unwrap();
827 for callback in callbacks {
828 if let Err(e) = callback.onError(cid as i32, error_code, message) {
829 error!("Error notifying error event from VM CID {}: {}", cid, e);
830 }
831 }
832 }
833
Andrew Walbrandae07162021-03-12 17:05:20 +0000834 /// Call all registered callbacks to say that the VM has died.
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000835 pub fn callback_on_died(&self, cid: Cid, reason: DeathReason) {
Andrew Walbrandae07162021-03-12 17:05:20 +0000836 let callbacks = &*self.0.lock().unwrap();
837 for callback in callbacks {
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000838 if let Err(e) = callback.onDied(cid as i32, reason) {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900839 error!("Error notifying exit of VM CID {}: {}", cid, e);
Andrew Walbrandae07162021-03-12 17:05:20 +0000840 }
841 }
842 }
843
844 /// Add a new callback to the set.
845 fn add(&self, callback: Strong<dyn IVirtualMachineCallback>) {
846 self.0.lock().unwrap().push(callback);
847 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000848}
849
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000850/// The mutable state of the VirtualizationService. There should only be one instance of this
851/// struct.
Chris Wailes641fc4a2021-12-01 15:03:21 -0800852#[derive(Debug, Default)]
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000853struct State {
Andrew Walbran320b5602021-03-04 16:11:12 +0000854 /// The VMs which have been started. When VMs are started a weak reference is added to this list
855 /// while a strong reference is returned to the caller over Binder. Once all copies of the
856 /// Binder client are dropped the weak reference here will become invalid, and will be removed
857 /// from the list opportunistically the next time `add_vm` is called.
858 vms: Vec<Weak<VmInstance>>,
David Brazdil3c2ddef2021-03-18 13:09:57 +0000859
860 /// Vector of strong VM references held on behalf of users that cannot hold them themselves.
861 /// This is only used for debugging purposes.
862 debug_held_vms: Vec<Strong<dyn IVirtualMachine>>,
Andrew Walbran320b5602021-03-04 16:11:12 +0000863}
864
865impl State {
Andrew Walbrandae07162021-03-12 17:05:20 +0000866 /// Get a list of VMs which still have Binder references to them.
Andrew Walbran320b5602021-03-04 16:11:12 +0000867 fn vms(&self) -> Vec<Arc<VmInstance>> {
868 // Attempt to upgrade the weak pointers to strong pointers.
869 self.vms.iter().filter_map(Weak::upgrade).collect()
870 }
871
872 /// Add a new VM to the list.
873 fn add_vm(&mut self, vm: Weak<VmInstance>) {
874 // Garbage collect any entries from the stored list which no longer exist.
875 self.vms.retain(|vm| vm.strong_count() > 0);
876
877 // Actually add the new VM.
878 self.vms.push(vm);
879 }
David Brazdil3c2ddef2021-03-18 13:09:57 +0000880
Jiyong Park8611a6c2021-07-09 18:17:44 +0900881 /// Get a VM that corresponds to the given cid
882 fn get_vm(&self, cid: Cid) -> Option<Arc<VmInstance>> {
883 self.vms().into_iter().find(|vm| vm.cid == cid)
884 }
885
David Brazdil3c2ddef2021-03-18 13:09:57 +0000886 /// Store a strong VM reference.
887 fn debug_hold_vm(&mut self, vm: Strong<dyn IVirtualMachine>) {
888 self.debug_held_vms.push(vm);
889 }
890
891 /// Retrieve and remove a strong VM reference.
892 fn debug_drop_vm(&mut self, cid: i32) -> Option<Strong<dyn IVirtualMachine>> {
893 let pos = self.debug_held_vms.iter().position(|vm| vm.getCid() == Ok(cid))?;
Alan Stokes7e54e292021-09-09 11:37:56 +0100894 let vm = self.debug_held_vms.swap_remove(pos);
Alan Stokes7e54e292021-09-09 11:37:56 +0100895 Some(vm)
David Brazdil3c2ddef2021-03-18 13:09:57 +0000896 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000897}
898
Jiyong Parkd50a0242021-09-16 21:00:14 +0900899/// Get the next available CID, or an error if we have run out. The last CID used is stored in
900/// a system property so that restart of virtualizationservice doesn't reuse CID while the host
901/// Android is up.
902fn next_cid() -> Result<Cid> {
Andrew Walbran014efb52022-02-03 17:43:11 +0000903 let next = if let Some(val) = system_properties::read(SYSPROP_LAST_CID)? {
Jiyong Parkd50a0242021-09-16 21:00:14 +0900904 if let Ok(num) = val.parse::<u32>() {
905 num.checked_add(1).ok_or_else(|| anyhow!("run out of CID"))?
906 } else {
907 error!("Invalid last CID {}. Using {}", &val, FIRST_GUEST_CID);
908 FIRST_GUEST_CID
909 }
910 } else {
911 // First VM since the boot
912 FIRST_GUEST_CID
913 };
914 // Persist the last value for next use
915 let str_val = format!("{}", next);
916 system_properties::write(SYSPROP_LAST_CID, &str_val)?;
917 Ok(next)
918}
919
Andrew Walbran6b650662021-09-07 13:13:23 +0000920/// Gets the `VirtualMachineState` of the given `VmInstance`.
921fn get_state(instance: &VmInstance) -> VirtualMachineState {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000922 match &*instance.vm_state.lock().unwrap() {
923 VmState::NotStarted { .. } => VirtualMachineState::NOT_STARTED,
924 VmState::Running { .. } => match instance.payload_state() {
Andrew Walbran6b650662021-09-07 13:13:23 +0000925 PayloadState::Starting => VirtualMachineState::STARTING,
926 PayloadState::Started => VirtualMachineState::STARTED,
927 PayloadState::Ready => VirtualMachineState::READY,
928 PayloadState::Finished => VirtualMachineState::FINISHED,
Andrew Walbranf8d94112021-09-07 11:45:36 +0000929 },
930 VmState::Dead => VirtualMachineState::DEAD,
931 VmState::Failed => VirtualMachineState::DEAD,
Andrew Walbran6b650662021-09-07 13:13:23 +0000932 }
933}
934
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000935/// Converts a `&ParcelFileDescriptor` to a `File` by cloning the file.
Andrew Walbran806f1542021-06-10 14:07:12 +0000936fn clone_file(file: &ParcelFileDescriptor) -> Result<File, Status> {
937 file.as_ref().try_clone().map_err(|e| {
938 new_binder_exception(
939 ExceptionCode::BAD_PARCELABLE,
940 format!("Failed to clone File from ParcelFileDescriptor: {}", e),
941 )
942 })
943}
944
Andrew Walbrand3a84182021-09-07 14:48:52 +0000945/// Converts an `&Option<ParcelFileDescriptor>` to an `Option<File>` by cloning the file.
946fn maybe_clone_file(file: &Option<ParcelFileDescriptor>) -> Result<Option<File>, Status> {
947 file.as_ref().map(clone_file).transpose()
948}
949
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000950/// Converts a `VsockStream` to a `ParcelFileDescriptor`.
951fn vsock_stream_to_pfd(stream: VsockStream) -> ParcelFileDescriptor {
952 // SAFETY: ownership is transferred from stream to f
953 let f = unsafe { File::from_raw_fd(stream.into_raw_fd()) };
954 ParcelFileDescriptor::new(f)
955}
956
Jiyong Parkdcf17412022-02-08 15:07:23 +0900957/// Parses the platform version requirement string.
958fn parse_platform_version_req(s: &str) -> Result<VersionReq, Status> {
959 VersionReq::parse(s).map_err(|e| {
960 new_binder_exception(
961 ExceptionCode::BAD_PARCELABLE,
962 format!("Invalid platform version requirement {}: {}", s, e),
963 )
964 })
965}
966
Jooyung Han35edb8f2021-07-01 16:17:16 +0900967/// Simple utility for referencing Borrowed or Owned. Similar to std::borrow::Cow, but
968/// it doesn't require that T implements Clone.
969enum BorrowedOrOwned<'a, T> {
970 Borrowed(&'a T),
971 Owned(T),
972}
973
974impl<'a, T> AsRef<T> for BorrowedOrOwned<'a, T> {
975 fn as_ref(&self) -> &T {
976 match self {
977 Self::Borrowed(b) => b,
Chris Wailes68c39f82021-07-27 16:03:44 -0700978 Self::Owned(o) => o,
Jooyung Han35edb8f2021-07-01 16:17:16 +0900979 }
980 }
981}
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900982
983/// Implementation of `IVirtualMachineService`, the entry point of the AIDL service.
984#[derive(Debug, Default)]
985struct VirtualMachineService {
986 state: Arc<Mutex<State>>,
Inseob Kimc7d28c72021-10-25 14:28:10 +0000987 cid: Cid,
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900988}
989
990impl Interface for VirtualMachineService {}
991
992impl IVirtualMachineService for VirtualMachineService {
Inseob Kimc7d28c72021-10-25 14:28:10 +0000993 fn notifyPayloadStarted(&self) -> binder::Result<()> {
994 let cid = self.cid;
Inseob Kim7f61fe72021-08-20 20:50:47 +0900995 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
996 info!("VM having CID {} started payload", cid);
Andrew Walbran6b650662021-09-07 13:13:23 +0000997 vm.update_payload_state(PayloadState::Started)
998 .map_err(|e| new_binder_exception(ExceptionCode::ILLEGAL_STATE, e.to_string()))?;
Inseob Kim7f61fe72021-08-20 20:50:47 +0900999 let stream = vm.stream.lock().unwrap().take();
1000 vm.callbacks.notify_payload_started(cid, stream);
1001 Ok(())
1002 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09001003 error!("notifyPayloadStarted is called from an unknown CID {}", cid);
Inseob Kim7f61fe72021-08-20 20:50:47 +09001004 Err(new_binder_exception(
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001005 ExceptionCode::SERVICE_SPECIFIC,
Jooyung Handd0a1732021-11-23 15:26:20 +09001006 format!("cannot find a VM with CID {}", cid),
Inseob Kim7f61fe72021-08-20 20:50:47 +09001007 ))
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001008 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001009 }
Inseob Kim2444af92021-08-31 01:22:50 +09001010
Inseob Kimc7d28c72021-10-25 14:28:10 +00001011 fn notifyPayloadReady(&self) -> binder::Result<()> {
1012 let cid = self.cid;
Inseob Kim14cb8692021-08-31 21:50:39 +09001013 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
1014 info!("VM having CID {} payload is ready", cid);
Andrew Walbran6b650662021-09-07 13:13:23 +00001015 vm.update_payload_state(PayloadState::Ready)
1016 .map_err(|e| new_binder_exception(ExceptionCode::ILLEGAL_STATE, e.to_string()))?;
Inseob Kim14cb8692021-08-31 21:50:39 +09001017 vm.callbacks.notify_payload_ready(cid);
1018 Ok(())
1019 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09001020 error!("notifyPayloadReady is called from an unknown CID {}", cid);
Inseob Kim14cb8692021-08-31 21:50:39 +09001021 Err(new_binder_exception(
1022 ExceptionCode::SERVICE_SPECIFIC,
Jooyung Handd0a1732021-11-23 15:26:20 +09001023 format!("cannot find a VM with CID {}", cid),
Inseob Kim14cb8692021-08-31 21:50:39 +09001024 ))
1025 }
1026 }
1027
Inseob Kimc7d28c72021-10-25 14:28:10 +00001028 fn notifyPayloadFinished(&self, exit_code: i32) -> binder::Result<()> {
1029 let cid = self.cid;
Inseob Kim2444af92021-08-31 01:22:50 +09001030 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
1031 info!("VM having CID {} finished payload", cid);
Andrew Walbran6b650662021-09-07 13:13:23 +00001032 vm.update_payload_state(PayloadState::Finished)
1033 .map_err(|e| new_binder_exception(ExceptionCode::ILLEGAL_STATE, e.to_string()))?;
Inseob Kim2444af92021-08-31 01:22:50 +09001034 vm.callbacks.notify_payload_finished(cid, exit_code);
1035 Ok(())
1036 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09001037 error!("notifyPayloadFinished is called from an unknown CID {}", cid);
Inseob Kim2444af92021-08-31 01:22:50 +09001038 Err(new_binder_exception(
1039 ExceptionCode::SERVICE_SPECIFIC,
Jooyung Handd0a1732021-11-23 15:26:20 +09001040 format!("cannot find a VM with CID {}", cid),
1041 ))
1042 }
1043 }
1044
1045 fn notifyError(&self, error_code: i32, message: &str) -> binder::Result<()> {
1046 let cid = self.cid;
1047 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
1048 info!("VM having CID {} encountered an error", cid);
1049 vm.update_payload_state(PayloadState::Finished)
1050 .map_err(|e| new_binder_exception(ExceptionCode::ILLEGAL_STATE, e.to_string()))?;
1051 vm.callbacks.notify_error(cid, error_code, message);
1052 Ok(())
1053 } else {
1054 error!("notifyPayloadStarted is called from an unknown CID {}", cid);
1055 Err(new_binder_exception(
1056 ExceptionCode::SERVICE_SPECIFIC,
1057 format!("cannot find a VM with CID {}", cid),
Inseob Kim2444af92021-08-31 01:22:50 +09001058 ))
1059 }
1060 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001061}
1062
1063impl VirtualMachineService {
Inseob Kimc7d28c72021-10-25 14:28:10 +00001064 // SAFETY: Service ownership is held by state, and the binder objects are threadsafe.
1065 pub unsafe extern "C" fn factory(
1066 cid: Cid,
1067 context: *mut raw::c_void,
1068 ) -> *mut binder_rpc_unstable_bindgen::AIBinder {
1069 let state_ptr = context as *mut Arc<Mutex<State>>;
1070 let state = state_ptr.as_ref().unwrap();
1071 if let Some(vm) = state.lock().unwrap().get_vm(cid) {
1072 let mut vm_service = vm.vm_service.lock().unwrap();
1073 let service = vm_service.get_or_insert_with(|| Self::new_binder(state.clone(), cid));
1074 service.as_binder().as_native_mut() as *mut binder_rpc_unstable_bindgen::AIBinder
1075 } else {
1076 error!("connection from cid={} is not from a guest VM", cid);
1077 null_mut()
1078 }
1079 }
1080
1081 fn new_binder(state: Arc<Mutex<State>>, cid: Cid) -> Strong<dyn IVirtualMachineService> {
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001082 BnVirtualMachineService::new_binder(
Inseob Kimc7d28c72021-10-25 14:28:10 +00001083 VirtualMachineService { state, cid },
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001084 BinderFeatures::default(),
1085 )
1086 }
1087}