blob: d9825dc477218b20d8843736750a77faefe43e93 [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,
45 VM_STREAM_SERVICE_PORT,
46 },
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};
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();
Andrew Scull527e5772022-02-11 15:43:28 +0000134 let console_fd = console_fd.map(clone_file).transpose()?;
135 let 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 Park029977d2021-11-24 21:56:49 +0900166 let is_app_config = matches!(config, VirtualMachineConfig::AppConfig(_));
167
Jooyung Han21e9b922021-06-26 04:14:16 +0900168 let config = match config {
Jooyung Han35edb8f2021-07-01 16:17:16 +0900169 VirtualMachineConfig::AppConfig(config) => BorrowedOrOwned::Owned(
Jooyung Han9900f3d2021-07-06 10:27:54 +0900170 load_app_config(config, &temporary_directory).map_err(|e| {
171 error!("Failed to load app config from {}: {}", &config.configPath, e);
Andrew Walbran3994f002022-01-27 17:33:45 +0000172 write_vm_creation_stats(config.protectedVm, false);
Jooyung Han9900f3d2021-07-06 10:27:54 +0900173 new_binder_exception(
174 ExceptionCode::SERVICE_SPECIFIC,
175 format!("Failed to load app config from {}: {}", &config.configPath, e),
176 )
177 })?,
Jooyung Han35edb8f2021-07-01 16:17:16 +0900178 ),
179 VirtualMachineConfig::RawConfig(config) => BorrowedOrOwned::Borrowed(config),
Jooyung Han21e9b922021-06-26 04:14:16 +0900180 };
Jooyung Han35edb8f2021-07-01 16:17:16 +0900181 let config = config.as_ref();
Andrew Walbran3994f002022-01-27 17:33:45 +0000182 let protected = config.protectedVm;
183
Jiyong Park029977d2021-11-24 21:56:49 +0900184 // Check if partition images are labeled incorrectly. This is to prevent random images
185 // which are not protected by the Android Verified Boot (e.g. bits downloaded by apps) from
186 // being loaded in a pVM. Specifically, for images in the raw config, nothing is allowed
187 // to be labeled as app_data_file. For images in the app config, nothing but the instance
188 // partition is allowed to be labeled as such.
189 config
190 .disks
191 .iter()
192 .flat_map(|disk| disk.partitions.iter())
193 .filter(|partition| {
194 if is_app_config {
195 partition.label != "vm-instance"
196 } else {
197 true // all partitions are checked
198 }
199 })
200 .try_for_each(check_label_for_partition)
201 .map_err(|e| new_binder_exception(ExceptionCode::SERVICE_SPECIFIC, e.to_string()))?;
202
Jooyung Han95884632021-07-06 22:27:54 +0900203 let zero_filler_path = temporary_directory.join("zero.img");
Andrew Walbranfbb39d22021-07-28 17:01:25 +0000204 write_zero_filler(&zero_filler_path).map_err(|e| {
Jooyung Han95884632021-07-06 22:27:54 +0900205 error!("Failed to make composite image: {}", e);
Andrew Walbran3994f002022-01-27 17:33:45 +0000206 write_vm_creation_stats(protected, false);
Jooyung Han95884632021-07-06 22:27:54 +0900207 new_binder_exception(
208 ExceptionCode::SERVICE_SPECIFIC,
209 format!("Failed to make composite image: {}", e),
210 )
211 })?;
Jooyung Han95884632021-07-06 22:27:54 +0900212
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000213 // Assemble disk images if needed.
214 let disks = config
215 .disks
216 .iter()
217 .map(|disk| {
218 assemble_disk_image(
219 disk,
Jooyung Han95884632021-07-06 22:27:54 +0900220 &zero_filler_path,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000221 &temporary_directory,
222 &mut next_temporary_image_id,
223 &mut indirect_files,
224 )
225 })
226 .collect::<Result<Vec<DiskFile>, _>>()?;
227
228 // Actually start the VM.
229 let crosvm_config = CrosvmConfig {
Andrew Walbran02034492021-04-13 15:05:07 +0000230 cid,
Andrew Walbrand3a84182021-09-07 14:48:52 +0000231 bootloader: maybe_clone_file(&config.bootloader)?,
232 kernel: maybe_clone_file(&config.kernel)?,
233 initrd: maybe_clone_file(&config.initrd)?,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000234 disks,
235 params: config.params.to_owned(),
Jiyong Parkd2dc83f2021-12-20 18:40:52 +0900236 protected,
Andrew Walbrancc045902021-07-27 16:06:17 +0000237 memory_mib: config.memoryMib.try_into().ok().and_then(NonZeroU32::new),
Jiyong Park032615f2022-01-10 13:55:34 +0900238 cpus: config.numCpus.try_into().ok().and_then(NonZeroU32::new),
239 cpu_affinity: config.cpuAffinity.clone(),
Jiyong Parkb8182bb2021-10-26 22:53:08 +0900240 console_fd,
Andrew Walbran02034492021-04-13 15:05:07 +0000241 log_fd,
Andrew Walbrand3a84182021-09-07 14:48:52 +0000242 indirect_files,
Jiyong Parkdcf17412022-02-08 15:07:23 +0900243 platform_version: parse_platform_version_req(&config.platformVersion)?,
Andrew Walbrand3a84182021-09-07 14:48:52 +0000244 };
Andrew Walbranf8d94112021-09-07 11:45:36 +0000245 let instance = Arc::new(
246 VmInstance::new(
247 crosvm_config,
248 temporary_directory,
249 requester_uid,
250 requester_sid,
251 requester_debug_pid,
Andrew Walbran806f1542021-06-10 14:07:12 +0000252 )
Andrew Walbranf8d94112021-09-07 11:45:36 +0000253 .map_err(|e| {
254 error!("Failed to create VM with config {:?}: {}", config, e);
Andrew Walbran3994f002022-01-27 17:33:45 +0000255 write_vm_creation_stats(protected, false);
Andrew Walbranf8d94112021-09-07 11:45:36 +0000256 new_binder_exception(
257 ExceptionCode::SERVICE_SPECIFIC,
258 format!("Failed to create VM: {}", e),
259 )
260 })?,
261 );
Andrew Walbran320b5602021-03-04 16:11:12 +0000262 state.add_vm(Arc::downgrade(&instance));
Andrew Walbran3994f002022-01-27 17:33:45 +0000263 write_vm_creation_stats(protected, true);
Andrew Walbran320b5602021-03-04 16:11:12 +0000264 Ok(VirtualMachine::create(instance))
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000265 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000266
Andrew Walbrandff3b942021-06-09 15:20:36 +0000267 /// Initialise an empty partition image of the given size to be used as a writable partition.
268 fn initializeWritablePartition(
269 &self,
270 image_fd: &ParcelFileDescriptor,
271 size: i64,
Jiyong Park9dd389e2021-08-23 20:42:59 +0900272 partition_type: PartitionType,
Andrew Walbrandff3b942021-06-09 15:20:36 +0000273 ) -> binder::Result<()> {
Jiyong Park753553b2021-07-12 21:21:09 +0900274 check_manage_access()?;
Andrew Walbrandfc953d2021-06-10 13:59:56 +0000275 let size = size.try_into().map_err(|e| {
Andrew Walbran806f1542021-06-10 14:07:12 +0000276 new_binder_exception(
277 ExceptionCode::ILLEGAL_ARGUMENT,
278 format!("Invalid size {}: {}", size, e),
279 )
Andrew Walbrandff3b942021-06-09 15:20:36 +0000280 })?;
Andrew Walbrandfc953d2021-06-10 13:59:56 +0000281 let image = clone_file(image_fd)?;
Jooyung Han1edd5b92021-10-28 10:58:05 +0900282 // initialize the file. Any data in the file will be erased.
283 image.set_len(0).map_err(|e| {
284 new_binder_exception(
285 ExceptionCode::SERVICE_SPECIFIC,
286 format!("Failed to reset a file: {}", e),
287 )
288 })?;
Jiyong Park9dd389e2021-08-23 20:42:59 +0900289 let mut part = QcowFile::new(image, size).map_err(|e| {
Andrew Walbran806f1542021-06-10 14:07:12 +0000290 new_binder_exception(
291 ExceptionCode::SERVICE_SPECIFIC,
292 format!("Failed to create QCOW2 image: {}", e),
293 )
Andrew Walbrandfc953d2021-06-10 13:59:56 +0000294 })?;
Andrew Walbrandff3b942021-06-09 15:20:36 +0000295
Jiyong Park9dd389e2021-08-23 20:42:59 +0900296 match partition_type {
297 PartitionType::RAW => Ok(()),
298 PartitionType::ANDROID_VM_INSTANCE => format_as_android_vm_instance(&mut part),
299 _ => Err(Error::new(
300 ErrorKind::Unsupported,
301 format!("Unsupported partition type {:?}", partition_type),
302 )),
303 }
304 .map_err(|e| {
305 new_binder_exception(
306 ExceptionCode::SERVICE_SPECIFIC,
307 format!("Failed to initialize partition as {:?}: {}", partition_type, e),
308 )
309 })?;
310
Andrew Walbrandff3b942021-06-09 15:20:36 +0000311 Ok(())
312 }
313
Jiyong Park0a248432021-08-20 23:32:39 +0900314 /// Creates or update the idsig file by digesting the input APK file.
315 fn createOrUpdateIdsigFile(
316 &self,
317 input_fd: &ParcelFileDescriptor,
318 idsig_fd: &ParcelFileDescriptor,
319 ) -> binder::Result<()> {
320 // TODO(b/193504400): do this only when (1) idsig_fd is empty or (2) the APK digest in
321 // idsig_fd is different from APK digest in input_fd
322
323 let mut input = clone_file(input_fd)?;
324 let mut sig = V4Signature::create(&mut input, 4096, &[], HashAlgorithm::SHA256).unwrap();
325
326 let mut output = clone_file(idsig_fd)?;
327 output.set_len(0).unwrap();
328 sig.write_into(&mut output).unwrap();
329 Ok(())
330 }
331
Andrew Walbran320b5602021-03-04 16:11:12 +0000332 /// Get a list of all currently running VMs. This method is only intended for debug purposes,
333 /// and as such is only permitted from the shell user.
334 fn debugListVms(&self) -> binder::Result<Vec<VirtualMachineDebugInfo>> {
Andrew Walbran806f1542021-06-10 14:07:12 +0000335 check_debug_access()?;
Andrew Walbran320b5602021-03-04 16:11:12 +0000336
337 let state = &mut *self.state.lock().unwrap();
338 let vms = state.vms();
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000339 let cids = vms
340 .into_iter()
341 .map(|vm| VirtualMachineDebugInfo {
342 cid: vm.cid as i32,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000343 temporaryDirectory: vm.temporary_directory.to_string_lossy().to_string(),
Andrew Walbran1ef19ae2021-04-07 11:31:57 +0000344 requesterUid: vm.requester_uid as i32,
345 requesterSid: vm.requester_sid.clone(),
Andrew Walbran02034492021-04-13 15:05:07 +0000346 requesterPid: vm.requester_debug_pid,
Andrew Walbran6b650662021-09-07 13:13:23 +0000347 state: get_state(&vm),
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000348 })
349 .collect();
Andrew Walbran320b5602021-03-04 16:11:12 +0000350 Ok(cids)
351 }
David Brazdil3c2ddef2021-03-18 13:09:57 +0000352
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000353 /// Hold a strong reference to a VM in VirtualizationService. This method is only intended for
354 /// debug purposes, and as such is only permitted from the shell user.
Andrei Homescu1415c132021-03-24 02:39:55 +0000355 fn debugHoldVmRef(&self, vmref: &Strong<dyn IVirtualMachine>) -> binder::Result<()> {
Andrew Walbran806f1542021-06-10 14:07:12 +0000356 check_debug_access()?;
David Brazdil3c2ddef2021-03-18 13:09:57 +0000357
David Brazdil3c2ddef2021-03-18 13:09:57 +0000358 let state = &mut *self.state.lock().unwrap();
Andrei Homescu1415c132021-03-24 02:39:55 +0000359 state.debug_hold_vm(vmref.clone());
David Brazdil3c2ddef2021-03-18 13:09:57 +0000360 Ok(())
361 }
362
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000363 /// Drop reference to a VM that is being held by VirtualizationService. Returns the reference if
364 /// the VM was found and None otherwise. This method is only intended for debug purposes, and as
365 /// such is only permitted from the shell user.
David Brazdil3c2ddef2021-03-18 13:09:57 +0000366 fn debugDropVmRef(&self, cid: i32) -> binder::Result<Option<Strong<dyn IVirtualMachine>>> {
Andrew Walbran806f1542021-06-10 14:07:12 +0000367 check_debug_access()?;
David Brazdil3c2ddef2021-03-18 13:09:57 +0000368
369 let state = &mut *self.state.lock().unwrap();
370 Ok(state.debug_drop_vm(cid))
371 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000372}
373
Jiyong Park8611a6c2021-07-09 18:17:44 +0900374impl VirtualizationService {
375 pub fn init() -> VirtualizationService {
376 let service = VirtualizationService::default();
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900377
378 // server for payload output
Jiyong Park8611a6c2021-07-09 18:17:44 +0900379 let state = service.state.clone(); // reference to state (not the state itself) is copied
380 std::thread::spawn(move || {
Inseob Kim7f61fe72021-08-20 20:50:47 +0900381 handle_stream_connection_from_vm(state).unwrap();
Jiyong Park8611a6c2021-07-09 18:17:44 +0900382 });
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900383
384 // binder server for vm
Inseob Kimc7d28c72021-10-25 14:28:10 +0000385 let mut state = service.state.clone(); // reference to state (not the state itself) is copied
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900386 std::thread::spawn(move || {
Inseob Kimc7d28c72021-10-25 14:28:10 +0000387 let state_ptr = &mut state as *mut _ as *mut raw::c_void;
388
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900389 debug!("virtual machine service is starting as an RPC service.");
Inseob Kimc7d28c72021-10-25 14:28:10 +0000390 // SAFETY: factory function is only ever called by RunRpcServerWithFactory, within the
391 // lifetime of the state, with context taking the pointer value above (so a properly
392 // aligned non-null pointer to an initialized instance).
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900393 let retval = unsafe {
Inseob Kimc7d28c72021-10-25 14:28:10 +0000394 binder_rpc_unstable_bindgen::RunRpcServerWithFactory(
395 Some(VirtualMachineService::factory),
396 state_ptr,
Inseob Kimd0587562021-09-01 21:27:32 +0900397 VM_BINDER_SERVICE_PORT as u32,
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900398 )
399 };
400 if retval {
401 debug!("RPC server has shut down gracefully");
402 } else {
403 bail!("Premature termination of RPC server");
404 }
405
406 Ok(retval)
407 });
Jiyong Park8611a6c2021-07-09 18:17:44 +0900408 service
409 }
410}
411
Treehugger Robot3ffa8322021-11-22 12:06:47 +0000412/// Write the stats of VMCreation to statsd
413fn write_vm_creation_stats(protected: bool, success: bool) {
414 match stats_write(Hypervisor::Pkvm, protected, success) {
415 Err(e) => {
Andrew Walbranf6d600f2022-02-03 14:42:39 +0000416 warn!("statslog_rust failed with error: {}", e);
Treehugger Robot3ffa8322021-11-22 12:06:47 +0000417 }
Andrew Walbranf6d600f2022-02-03 14:42:39 +0000418 Ok(_) => trace!("statslog_rust succeeded for virtualization service"),
Treehugger Robot3ffa8322021-11-22 12:06:47 +0000419 }
420}
421
Andrew Walbran6b650662021-09-07 13:13:23 +0000422/// Waits for incoming connections from VM. If a new connection is made, stores the stream in the
423/// corresponding `VmInstance`.
Inseob Kim7f61fe72021-08-20 20:50:47 +0900424fn handle_stream_connection_from_vm(state: Arc<Mutex<State>>) -> Result<()> {
Inseob Kimd0587562021-09-01 21:27:32 +0900425 let listener =
426 VsockListener::bind_with_cid_port(VMADDR_CID_HOST, VM_STREAM_SERVICE_PORT as u32)?;
Jiyong Park8611a6c2021-07-09 18:17:44 +0900427 for stream in listener.incoming() {
428 let stream = match stream {
429 Err(e) => {
430 warn!("invalid incoming connection: {}", e);
431 continue;
432 }
433 Ok(s) => s,
434 };
435 if let Ok(SockAddr::Vsock(addr)) = stream.peer_addr() {
436 let cid = addr.cid();
437 let port = addr.port();
Inseob Kim7f61fe72021-08-20 20:50:47 +0900438 info!("payload stream connected from cid={}, port={}", cid, port);
Jiyong Park8611a6c2021-07-09 18:17:44 +0900439 if let Some(vm) = state.lock().unwrap().get_vm(cid) {
Chris Wailes8bbb8932021-09-10 14:14:19 -0700440 *vm.stream.lock().unwrap() = Some(stream);
Inseob Kim7f61fe72021-08-20 20:50:47 +0900441 } else {
442 error!("connection from cid={} is not from a guest VM", cid);
Jiyong Park8611a6c2021-07-09 18:17:44 +0900443 }
444 }
445 }
446 Ok(())
447}
448
Andrew Walbranfbb39d22021-07-28 17:01:25 +0000449fn write_zero_filler(zero_filler_path: &Path) -> Result<()> {
Jooyung Han95884632021-07-06 22:27:54 +0900450 let file = OpenOptions::new()
451 .create_new(true)
452 .read(true)
453 .write(true)
454 .open(zero_filler_path)
455 .with_context(|| "Failed to create zero.img")?;
456 file.set_len(ZERO_FILLER_SIZE)?;
Andrew Walbranfbb39d22021-07-28 17:01:25 +0000457 Ok(())
Jooyung Han95884632021-07-06 22:27:54 +0900458}
459
Jiyong Park9dd389e2021-08-23 20:42:59 +0900460fn format_as_android_vm_instance(part: &mut dyn Write) -> std::io::Result<()> {
461 part.write_all(ANDROID_VM_INSTANCE_MAGIC.as_bytes())?;
462 part.write_all(&ANDROID_VM_INSTANCE_VERSION.to_le_bytes())?;
463 part.flush()
464}
465
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000466/// Given the configuration for a disk image, assembles the `DiskFile` to pass to crosvm.
467///
468/// This may involve assembling a composite disk from a set of partition images.
469fn assemble_disk_image(
470 disk: &DiskImage,
Jooyung Han95884632021-07-06 22:27:54 +0900471 zero_filler_path: &Path,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000472 temporary_directory: &Path,
473 next_temporary_image_id: &mut u64,
474 indirect_files: &mut Vec<File>,
Andrew Walbran806f1542021-06-10 14:07:12 +0000475) -> Result<DiskFile, Status> {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000476 let image = if !disk.partitions.is_empty() {
477 if disk.image.is_some() {
478 warn!("DiskImage {:?} contains both image and partitions.", disk);
Andrew Walbran806f1542021-06-10 14:07:12 +0000479 return Err(new_binder_exception(
480 ExceptionCode::ILLEGAL_ARGUMENT,
481 "DiskImage contains both image and partitions.",
482 ));
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000483 }
484
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000485 let composite_image_filenames =
486 make_composite_image_filenames(temporary_directory, next_temporary_image_id);
487 let (image, partition_files) = make_composite_image(
488 &disk.partitions,
Jooyung Han95884632021-07-06 22:27:54 +0900489 zero_filler_path,
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000490 &composite_image_filenames.composite,
491 &composite_image_filenames.header,
492 &composite_image_filenames.footer,
493 )
494 .map_err(|e| {
495 error!("Failed to make composite image with config {:?}: {}", disk, e);
496 new_binder_exception(
497 ExceptionCode::SERVICE_SPECIFIC,
498 format!("Failed to make composite image: {}", e),
499 )
500 })?;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000501
502 // Pass the file descriptors for the various partition files to crosvm when it
503 // is run.
504 indirect_files.extend(partition_files);
505
506 image
507 } else if let Some(image) = &disk.image {
508 clone_file(image)?
509 } else {
510 warn!("DiskImage {:?} didn't contain image or partitions.", disk);
Andrew Walbran806f1542021-06-10 14:07:12 +0000511 return Err(new_binder_exception(
512 ExceptionCode::ILLEGAL_ARGUMENT,
513 "DiskImage didn't contain image or partitions.",
514 ));
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000515 };
516
517 Ok(DiskFile { image, writable: disk.writable })
518}
519
Jooyung Han21e9b922021-06-26 04:14:16 +0900520fn load_app_config(
521 config: &VirtualMachineAppConfig,
522 temporary_directory: &Path,
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900523) -> Result<VirtualMachineRawConfig> {
Andrew Walbrancc0db522021-07-12 17:03:42 +0000524 let apk_file = clone_file(config.apk.as_ref().unwrap())?;
525 let idsig_file = clone_file(config.idsig.as_ref().unwrap())?;
Jiyong Park8d081812021-07-23 17:45:04 +0900526 let instance_file = clone_file(config.instanceImage.as_ref().unwrap())?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900527 let config_path = &config.configPath;
528
Andrew Walbrancc0db522021-07-12 17:03:42 +0000529 let mut apk_zip = ZipArchive::new(&apk_file)?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900530 let config_file = apk_zip.by_name(config_path)?;
531 let vm_payload_config: VmPayloadConfig = serde_json::from_reader(config_file)?;
532
533 let os_name = &vm_payload_config.os.name;
Andrew Walbrancc0db522021-07-12 17:03:42 +0000534
Jooyung Han35edb8f2021-07-01 16:17:16 +0900535 // For now, the only supported "os" value is "microdroid"
536 if os_name != "microdroid" {
Andrew Walbrancc0db522021-07-12 17:03:42 +0000537 bail!("Unknown OS \"{}\"", os_name);
Jooyung Han35edb8f2021-07-01 16:17:16 +0900538 }
Andrew Walbrancc0db522021-07-12 17:03:42 +0000539
540 // It is safe to construct a filename based on the os_name because we've already checked that it
541 // is one of the allowed values.
Jooyung Han21e9b922021-06-26 04:14:16 +0900542 let vm_config_path = PathBuf::from(format!("/apex/com.android.virt/etc/{}.json", os_name));
543 let vm_config_file = File::open(vm_config_path)?;
Andrew Walbrancc0db522021-07-12 17:03:42 +0000544 let mut vm_config = VmConfig::load(&vm_config_file)?.to_parcelable()?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900545
Andrew Walbrancc045902021-07-27 16:06:17 +0000546 if config.memoryMib > 0 {
547 vm_config.memoryMib = config.memoryMib;
Andrew Walbran45bcb0c2021-07-14 15:02:06 +0000548 }
549
Andrew Walbran3994f002022-01-27 17:33:45 +0000550 vm_config.protectedVm = config.protectedVm;
Jiyong Park032615f2022-01-10 13:55:34 +0900551 vm_config.numCpus = config.numCpus;
552 vm_config.cpuAffinity = config.cpuAffinity.clone();
553
Andrew Walbrancc0db522021-07-12 17:03:42 +0000554 // Microdroid requires an additional payload disk image and the bootconfig partition.
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900555 if os_name == "microdroid" {
Andrew Walbrancc0db522021-07-12 17:03:42 +0000556 add_microdroid_images(
557 config,
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900558 temporary_directory,
Andrew Walbrancc0db522021-07-12 17:03:42 +0000559 apk_file,
560 idsig_file,
Jiyong Park8d081812021-07-23 17:45:04 +0900561 instance_file,
Jooyung Han5dc42172021-10-05 16:43:47 +0900562 &vm_payload_config,
Andrew Walbrancc0db522021-07-12 17:03:42 +0000563 &mut vm_config,
564 )?;
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900565 }
Jooyung Han21e9b922021-06-26 04:14:16 +0900566
Andrew Walbrancc0db522021-07-12 17:03:42 +0000567 Ok(vm_config)
Jooyung Han21e9b922021-06-26 04:14:16 +0900568}
569
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000570/// Generates a unique filename to use for a composite disk image.
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000571fn make_composite_image_filenames(
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000572 temporary_directory: &Path,
573 next_temporary_image_id: &mut u64,
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000574) -> CompositeImageFilenames {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000575 let id = *next_temporary_image_id;
576 *next_temporary_image_id += 1;
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000577 CompositeImageFilenames {
578 composite: temporary_directory.join(format!("composite-{}.img", id)),
579 header: temporary_directory.join(format!("composite-{}-header.img", id)),
580 footer: temporary_directory.join(format!("composite-{}-footer.img", id)),
581 }
582}
583
584/// Filenames for a composite disk image, including header and footer partitions.
585#[derive(Clone, Debug, Eq, PartialEq)]
586struct CompositeImageFilenames {
587 /// The composite disk image itself.
588 composite: PathBuf,
589 /// The header partition image.
590 header: PathBuf,
591 /// The footer partition image.
592 footer: PathBuf,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000593}
594
595/// Gets the calling SID of the current Binder thread.
Andrew Walbran806f1542021-06-10 14:07:12 +0000596fn get_calling_sid() -> Result<String, Status> {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000597 ThreadState::with_calling_sid(|sid| {
598 if let Some(sid) = sid {
599 match sid.to_str() {
600 Ok(sid) => Ok(sid.to_owned()),
601 Err(e) => {
Andrew Walbran806f1542021-06-10 14:07:12 +0000602 error!("SID was not valid UTF-8: {}", e);
603 Err(new_binder_exception(
604 ExceptionCode::ILLEGAL_ARGUMENT,
605 format!("SID was not valid UTF-8: {}", e),
606 ))
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000607 }
608 }
609 } else {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000610 error!("Missing SID on createVm");
611 Err(new_binder_exception(ExceptionCode::SECURITY, "Missing SID on createVm"))
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000612 }
613 })
614}
615
Jiyong Park753553b2021-07-12 21:21:09 +0900616/// Checks whether the caller has a specific permission
617fn check_permission(perm: &str) -> binder::Result<()> {
618 let calling_pid = ThreadState::get_calling_pid();
619 let calling_uid = ThreadState::get_calling_uid();
620 // Root can do anything
621 if calling_uid == 0 {
622 return Ok(());
623 }
624 let perm_svc: Strong<dyn IPermissionController::IPermissionController> =
625 binder::get_interface("permission")?;
626 if perm_svc.checkPermission(perm, calling_pid, calling_uid as i32)? {
Andrew Walbran806f1542021-06-10 14:07:12 +0000627 Ok(())
628 } else {
Jiyong Park753553b2021-07-12 21:21:09 +0900629 Err(new_binder_exception(
630 ExceptionCode::SECURITY,
631 format!("does not have the {} permission", perm),
632 ))
Andrew Walbran806f1542021-06-10 14:07:12 +0000633 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000634}
635
Jiyong Park753553b2021-07-12 21:21:09 +0900636/// Check whether the caller of the current Binder method is allowed to call debug methods.
637fn check_debug_access() -> binder::Result<()> {
638 check_permission("android.permission.DEBUG_VIRTUAL_MACHINE")
639}
640
641/// Check whether the caller of the current Binder method is allowed to manage VMs
642fn check_manage_access() -> binder::Result<()> {
643 check_permission("android.permission.MANAGE_VIRTUAL_MACHINE")
644}
645
Jiyong Park029977d2021-11-24 21:56:49 +0900646/// Check if a partition has selinux labels that are not allowed
647fn check_label_for_partition(partition: &Partition) -> Result<()> {
648 let ctx = getfilecon(partition.image.as_ref().unwrap().as_ref())?;
649 if ctx == SeContext::new("u:object_r:app_data_file:s0").unwrap() {
650 Err(anyhow!("Partition {} shouldn't be labeled as {}", &partition.label, ctx))
651 } else {
652 Ok(())
653 }
654}
655
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000656/// Implementation of the AIDL `IVirtualMachine` interface. Used as a handle to a VM.
657#[derive(Debug)]
658struct VirtualMachine {
659 instance: Arc<VmInstance>,
Alan Stokes0cc59ee2021-09-24 11:20:34 +0100660 /// Keeps our service process running as long as this VM instance exists.
Chris Wailes641fc4a2021-12-01 15:03:21 -0800661 #[allow(dead_code)]
Alan Stokes0cc59ee2021-09-24 11:20:34 +0100662 lazy_service_guard: LazyServiceGuard,
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000663}
664
665impl VirtualMachine {
666 fn create(instance: Arc<VmInstance>) -> Strong<dyn IVirtualMachine> {
Alan Stokes0cc59ee2021-09-24 11:20:34 +0100667 let binder = VirtualMachine { instance, lazy_service_guard: Default::default() };
Andrew Walbran4de28782021-04-13 14:51:43 +0000668 BnVirtualMachine::new_binder(binder, BinderFeatures::default())
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000669 }
670}
671
672impl Interface for VirtualMachine {}
673
674impl IVirtualMachine for VirtualMachine {
675 fn getCid(&self) -> binder::Result<i32> {
Jiyong Park753553b2021-07-12 21:21:09 +0900676 // Don't check permission. The owner of the VM might have passed this binder object to
677 // others.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000678 Ok(self.instance.cid as i32)
679 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000680
Andrew Walbran6b650662021-09-07 13:13:23 +0000681 fn getState(&self) -> binder::Result<VirtualMachineState> {
Jiyong Park753553b2021-07-12 21:21:09 +0900682 // Don't check permission. The owner of the VM might have passed this binder object to
683 // others.
Andrew Walbran6b650662021-09-07 13:13:23 +0000684 Ok(get_state(&self.instance))
Andrew Walbrandae07162021-03-12 17:05:20 +0000685 }
686
687 fn registerCallback(
688 &self,
689 callback: &Strong<dyn IVirtualMachineCallback>,
690 ) -> binder::Result<()> {
Jiyong Park753553b2021-07-12 21:21:09 +0900691 // Don't check permission. The owner of the VM might have passed this binder object to
692 // others.
693 //
Andrew Walbrandae07162021-03-12 17:05:20 +0000694 // TODO: Should this give an error if the VM is already dead?
695 self.instance.callbacks.add(callback.clone());
696 Ok(())
697 }
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000698
Andrew Walbranf8d94112021-09-07 11:45:36 +0000699 fn start(&self) -> binder::Result<()> {
700 self.instance.start().map_err(|e| {
701 error!("Error starting VM with CID {}: {:?}", self.instance.cid, e);
702 new_binder_exception(ExceptionCode::SERVICE_SPECIFIC, e.to_string())
703 })
704 }
705
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000706 fn connectVsock(&self, port: i32) -> binder::Result<ParcelFileDescriptor> {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000707 if !matches!(&*self.instance.vm_state.lock().unwrap(), VmState::Running { .. }) {
708 return Err(new_binder_exception(ExceptionCode::SERVICE_SPECIFIC, "VM is not running"));
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000709 }
710 let stream =
711 VsockStream::connect_with_cid_port(self.instance.cid, port as u32).map_err(|e| {
712 new_binder_exception(
713 ExceptionCode::SERVICE_SPECIFIC,
714 format!("Failed to connect: {}", e),
715 )
716 })?;
717 Ok(vsock_stream_to_pfd(stream))
718 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000719}
720
721impl Drop for VirtualMachine {
722 fn drop(&mut self) {
723 debug!("Dropping {:?}", self);
724 self.instance.kill();
725 }
726}
727
728/// A set of Binders to be called back in response to various events on the VM, such as when it
729/// dies.
730#[derive(Debug, Default)]
731pub struct VirtualMachineCallbacks(Mutex<Vec<Strong<dyn IVirtualMachineCallback>>>);
732
733impl VirtualMachineCallbacks {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900734 /// Call all registered callbacks to notify that the payload has started.
Inseob Kim7f61fe72021-08-20 20:50:47 +0900735 pub fn notify_payload_started(&self, cid: Cid, stream: Option<VsockStream>) {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900736 let callbacks = &*self.0.lock().unwrap();
Inseob Kim7f61fe72021-08-20 20:50:47 +0900737 let pfd = stream.map(vsock_stream_to_pfd);
Jiyong Park8611a6c2021-07-09 18:17:44 +0900738 for callback in callbacks {
Inseob Kim7f61fe72021-08-20 20:50:47 +0900739 if let Err(e) = callback.onPayloadStarted(cid as i32, pfd.as_ref()) {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900740 error!("Error notifying payload start event from VM CID {}: {}", cid, e);
741 }
742 }
743 }
744
Inseob Kim14cb8692021-08-31 21:50:39 +0900745 /// Call all registered callbacks to notify that the payload is ready to serve.
746 pub fn notify_payload_ready(&self, cid: Cid) {
747 let callbacks = &*self.0.lock().unwrap();
748 for callback in callbacks {
749 if let Err(e) = callback.onPayloadReady(cid as i32) {
750 error!("Error notifying payload ready event from VM CID {}: {}", cid, e);
751 }
752 }
753 }
754
Inseob Kim2444af92021-08-31 01:22:50 +0900755 /// Call all registered callbacks to notify that the payload has finished.
756 pub fn notify_payload_finished(&self, cid: Cid, exit_code: i32) {
757 let callbacks = &*self.0.lock().unwrap();
758 for callback in callbacks {
759 if let Err(e) = callback.onPayloadFinished(cid as i32, exit_code) {
760 error!("Error notifying payload finish event from VM CID {}: {}", cid, e);
761 }
762 }
763 }
764
Jooyung Handd0a1732021-11-23 15:26:20 +0900765 /// Call all registered callbacks to say that the VM encountered an error.
766 pub fn notify_error(&self, cid: Cid, error_code: i32, message: &str) {
767 let callbacks = &*self.0.lock().unwrap();
768 for callback in callbacks {
769 if let Err(e) = callback.onError(cid as i32, error_code, message) {
770 error!("Error notifying error event from VM CID {}: {}", cid, e);
771 }
772 }
773 }
774
Andrew Walbrandae07162021-03-12 17:05:20 +0000775 /// Call all registered callbacks to say that the VM has died.
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000776 pub fn callback_on_died(&self, cid: Cid, reason: DeathReason) {
Andrew Walbrandae07162021-03-12 17:05:20 +0000777 let callbacks = &*self.0.lock().unwrap();
778 for callback in callbacks {
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000779 if let Err(e) = callback.onDied(cid as i32, reason) {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900780 error!("Error notifying exit of VM CID {}: {}", cid, e);
Andrew Walbrandae07162021-03-12 17:05:20 +0000781 }
782 }
783 }
784
785 /// Add a new callback to the set.
786 fn add(&self, callback: Strong<dyn IVirtualMachineCallback>) {
787 self.0.lock().unwrap().push(callback);
788 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000789}
790
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000791/// The mutable state of the VirtualizationService. There should only be one instance of this
792/// struct.
Chris Wailes641fc4a2021-12-01 15:03:21 -0800793#[derive(Debug, Default)]
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000794struct State {
Andrew Walbran320b5602021-03-04 16:11:12 +0000795 /// The VMs which have been started. When VMs are started a weak reference is added to this list
796 /// while a strong reference is returned to the caller over Binder. Once all copies of the
797 /// Binder client are dropped the weak reference here will become invalid, and will be removed
798 /// from the list opportunistically the next time `add_vm` is called.
799 vms: Vec<Weak<VmInstance>>,
David Brazdil3c2ddef2021-03-18 13:09:57 +0000800
801 /// Vector of strong VM references held on behalf of users that cannot hold them themselves.
802 /// This is only used for debugging purposes.
803 debug_held_vms: Vec<Strong<dyn IVirtualMachine>>,
Andrew Walbran320b5602021-03-04 16:11:12 +0000804}
805
806impl State {
Andrew Walbrandae07162021-03-12 17:05:20 +0000807 /// Get a list of VMs which still have Binder references to them.
Andrew Walbran320b5602021-03-04 16:11:12 +0000808 fn vms(&self) -> Vec<Arc<VmInstance>> {
809 // Attempt to upgrade the weak pointers to strong pointers.
810 self.vms.iter().filter_map(Weak::upgrade).collect()
811 }
812
813 /// Add a new VM to the list.
814 fn add_vm(&mut self, vm: Weak<VmInstance>) {
815 // Garbage collect any entries from the stored list which no longer exist.
816 self.vms.retain(|vm| vm.strong_count() > 0);
817
818 // Actually add the new VM.
819 self.vms.push(vm);
820 }
David Brazdil3c2ddef2021-03-18 13:09:57 +0000821
Jiyong Park8611a6c2021-07-09 18:17:44 +0900822 /// Get a VM that corresponds to the given cid
823 fn get_vm(&self, cid: Cid) -> Option<Arc<VmInstance>> {
824 self.vms().into_iter().find(|vm| vm.cid == cid)
825 }
826
David Brazdil3c2ddef2021-03-18 13:09:57 +0000827 /// Store a strong VM reference.
828 fn debug_hold_vm(&mut self, vm: Strong<dyn IVirtualMachine>) {
829 self.debug_held_vms.push(vm);
830 }
831
832 /// Retrieve and remove a strong VM reference.
833 fn debug_drop_vm(&mut self, cid: i32) -> Option<Strong<dyn IVirtualMachine>> {
834 let pos = self.debug_held_vms.iter().position(|vm| vm.getCid() == Ok(cid))?;
Alan Stokes7e54e292021-09-09 11:37:56 +0100835 let vm = self.debug_held_vms.swap_remove(pos);
Alan Stokes7e54e292021-09-09 11:37:56 +0100836 Some(vm)
David Brazdil3c2ddef2021-03-18 13:09:57 +0000837 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000838}
839
Jiyong Parkd50a0242021-09-16 21:00:14 +0900840/// Get the next available CID, or an error if we have run out. The last CID used is stored in
841/// a system property so that restart of virtualizationservice doesn't reuse CID while the host
842/// Android is up.
843fn next_cid() -> Result<Cid> {
Andrew Walbran014efb52022-02-03 17:43:11 +0000844 let next = if let Some(val) = system_properties::read(SYSPROP_LAST_CID)? {
Jiyong Parkd50a0242021-09-16 21:00:14 +0900845 if let Ok(num) = val.parse::<u32>() {
846 num.checked_add(1).ok_or_else(|| anyhow!("run out of CID"))?
847 } else {
848 error!("Invalid last CID {}. Using {}", &val, FIRST_GUEST_CID);
849 FIRST_GUEST_CID
850 }
851 } else {
852 // First VM since the boot
853 FIRST_GUEST_CID
854 };
855 // Persist the last value for next use
856 let str_val = format!("{}", next);
857 system_properties::write(SYSPROP_LAST_CID, &str_val)?;
858 Ok(next)
859}
860
Andrew Walbran6b650662021-09-07 13:13:23 +0000861/// Gets the `VirtualMachineState` of the given `VmInstance`.
862fn get_state(instance: &VmInstance) -> VirtualMachineState {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000863 match &*instance.vm_state.lock().unwrap() {
864 VmState::NotStarted { .. } => VirtualMachineState::NOT_STARTED,
865 VmState::Running { .. } => match instance.payload_state() {
Andrew Walbran6b650662021-09-07 13:13:23 +0000866 PayloadState::Starting => VirtualMachineState::STARTING,
867 PayloadState::Started => VirtualMachineState::STARTED,
868 PayloadState::Ready => VirtualMachineState::READY,
869 PayloadState::Finished => VirtualMachineState::FINISHED,
Andrew Walbranf8d94112021-09-07 11:45:36 +0000870 },
871 VmState::Dead => VirtualMachineState::DEAD,
872 VmState::Failed => VirtualMachineState::DEAD,
Andrew Walbran6b650662021-09-07 13:13:23 +0000873 }
874}
875
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000876/// Converts a `&ParcelFileDescriptor` to a `File` by cloning the file.
Andrew Walbran806f1542021-06-10 14:07:12 +0000877fn clone_file(file: &ParcelFileDescriptor) -> Result<File, Status> {
878 file.as_ref().try_clone().map_err(|e| {
879 new_binder_exception(
880 ExceptionCode::BAD_PARCELABLE,
881 format!("Failed to clone File from ParcelFileDescriptor: {}", e),
882 )
883 })
884}
885
Andrew Walbrand3a84182021-09-07 14:48:52 +0000886/// Converts an `&Option<ParcelFileDescriptor>` to an `Option<File>` by cloning the file.
887fn maybe_clone_file(file: &Option<ParcelFileDescriptor>) -> Result<Option<File>, Status> {
888 file.as_ref().map(clone_file).transpose()
889}
890
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000891/// Converts a `VsockStream` to a `ParcelFileDescriptor`.
892fn vsock_stream_to_pfd(stream: VsockStream) -> ParcelFileDescriptor {
893 // SAFETY: ownership is transferred from stream to f
894 let f = unsafe { File::from_raw_fd(stream.into_raw_fd()) };
895 ParcelFileDescriptor::new(f)
896}
897
Jiyong Parkdcf17412022-02-08 15:07:23 +0900898/// Parses the platform version requirement string.
899fn parse_platform_version_req(s: &str) -> Result<VersionReq, Status> {
900 VersionReq::parse(s).map_err(|e| {
901 new_binder_exception(
902 ExceptionCode::BAD_PARCELABLE,
903 format!("Invalid platform version requirement {}: {}", s, e),
904 )
905 })
906}
907
Jooyung Han35edb8f2021-07-01 16:17:16 +0900908/// Simple utility for referencing Borrowed or Owned. Similar to std::borrow::Cow, but
909/// it doesn't require that T implements Clone.
910enum BorrowedOrOwned<'a, T> {
911 Borrowed(&'a T),
912 Owned(T),
913}
914
915impl<'a, T> AsRef<T> for BorrowedOrOwned<'a, T> {
916 fn as_ref(&self) -> &T {
917 match self {
918 Self::Borrowed(b) => b,
Chris Wailes68c39f82021-07-27 16:03:44 -0700919 Self::Owned(o) => o,
Jooyung Han35edb8f2021-07-01 16:17:16 +0900920 }
921 }
922}
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900923
924/// Implementation of `IVirtualMachineService`, the entry point of the AIDL service.
925#[derive(Debug, Default)]
926struct VirtualMachineService {
927 state: Arc<Mutex<State>>,
Inseob Kimc7d28c72021-10-25 14:28:10 +0000928 cid: Cid,
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900929}
930
931impl Interface for VirtualMachineService {}
932
933impl IVirtualMachineService for VirtualMachineService {
Inseob Kimc7d28c72021-10-25 14:28:10 +0000934 fn notifyPayloadStarted(&self) -> binder::Result<()> {
935 let cid = self.cid;
Inseob Kim7f61fe72021-08-20 20:50:47 +0900936 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
937 info!("VM having CID {} started payload", cid);
Andrew Walbran6b650662021-09-07 13:13:23 +0000938 vm.update_payload_state(PayloadState::Started)
939 .map_err(|e| new_binder_exception(ExceptionCode::ILLEGAL_STATE, e.to_string()))?;
Inseob Kim7f61fe72021-08-20 20:50:47 +0900940 let stream = vm.stream.lock().unwrap().take();
941 vm.callbacks.notify_payload_started(cid, stream);
942 Ok(())
943 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +0900944 error!("notifyPayloadStarted is called from an unknown CID {}", cid);
Inseob Kim7f61fe72021-08-20 20:50:47 +0900945 Err(new_binder_exception(
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900946 ExceptionCode::SERVICE_SPECIFIC,
Jooyung Handd0a1732021-11-23 15:26:20 +0900947 format!("cannot find a VM with CID {}", cid),
Inseob Kim7f61fe72021-08-20 20:50:47 +0900948 ))
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900949 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900950 }
Inseob Kim2444af92021-08-31 01:22:50 +0900951
Inseob Kimc7d28c72021-10-25 14:28:10 +0000952 fn notifyPayloadReady(&self) -> binder::Result<()> {
953 let cid = self.cid;
Inseob Kim14cb8692021-08-31 21:50:39 +0900954 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
955 info!("VM having CID {} payload is ready", cid);
Andrew Walbran6b650662021-09-07 13:13:23 +0000956 vm.update_payload_state(PayloadState::Ready)
957 .map_err(|e| new_binder_exception(ExceptionCode::ILLEGAL_STATE, e.to_string()))?;
Inseob Kim14cb8692021-08-31 21:50:39 +0900958 vm.callbacks.notify_payload_ready(cid);
959 Ok(())
960 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +0900961 error!("notifyPayloadReady is called from an unknown CID {}", cid);
Inseob Kim14cb8692021-08-31 21:50:39 +0900962 Err(new_binder_exception(
963 ExceptionCode::SERVICE_SPECIFIC,
Jooyung Handd0a1732021-11-23 15:26:20 +0900964 format!("cannot find a VM with CID {}", cid),
Inseob Kim14cb8692021-08-31 21:50:39 +0900965 ))
966 }
967 }
968
Inseob Kimc7d28c72021-10-25 14:28:10 +0000969 fn notifyPayloadFinished(&self, exit_code: i32) -> binder::Result<()> {
970 let cid = self.cid;
Inseob Kim2444af92021-08-31 01:22:50 +0900971 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
972 info!("VM having CID {} finished payload", cid);
Andrew Walbran6b650662021-09-07 13:13:23 +0000973 vm.update_payload_state(PayloadState::Finished)
974 .map_err(|e| new_binder_exception(ExceptionCode::ILLEGAL_STATE, e.to_string()))?;
Inseob Kim2444af92021-08-31 01:22:50 +0900975 vm.callbacks.notify_payload_finished(cid, exit_code);
976 Ok(())
977 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +0900978 error!("notifyPayloadFinished is called from an unknown CID {}", cid);
Inseob Kim2444af92021-08-31 01:22:50 +0900979 Err(new_binder_exception(
980 ExceptionCode::SERVICE_SPECIFIC,
Jooyung Handd0a1732021-11-23 15:26:20 +0900981 format!("cannot find a VM with CID {}", cid),
982 ))
983 }
984 }
985
986 fn notifyError(&self, error_code: i32, message: &str) -> binder::Result<()> {
987 let cid = self.cid;
988 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
989 info!("VM having CID {} encountered an error", cid);
990 vm.update_payload_state(PayloadState::Finished)
991 .map_err(|e| new_binder_exception(ExceptionCode::ILLEGAL_STATE, e.to_string()))?;
992 vm.callbacks.notify_error(cid, error_code, message);
993 Ok(())
994 } else {
995 error!("notifyPayloadStarted is called from an unknown CID {}", cid);
996 Err(new_binder_exception(
997 ExceptionCode::SERVICE_SPECIFIC,
998 format!("cannot find a VM with CID {}", cid),
Inseob Kim2444af92021-08-31 01:22:50 +0900999 ))
1000 }
1001 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001002}
1003
1004impl VirtualMachineService {
Inseob Kimc7d28c72021-10-25 14:28:10 +00001005 // SAFETY: Service ownership is held by state, and the binder objects are threadsafe.
1006 pub unsafe extern "C" fn factory(
1007 cid: Cid,
1008 context: *mut raw::c_void,
1009 ) -> *mut binder_rpc_unstable_bindgen::AIBinder {
1010 let state_ptr = context as *mut Arc<Mutex<State>>;
1011 let state = state_ptr.as_ref().unwrap();
1012 if let Some(vm) = state.lock().unwrap().get_vm(cid) {
1013 let mut vm_service = vm.vm_service.lock().unwrap();
1014 let service = vm_service.get_or_insert_with(|| Self::new_binder(state.clone(), cid));
1015 service.as_binder().as_native_mut() as *mut binder_rpc_unstable_bindgen::AIBinder
1016 } else {
1017 error!("connection from cid={} is not from a guest VM", cid);
1018 null_mut()
1019 }
1020 }
1021
1022 fn new_binder(state: Arc<Mutex<State>>, cid: Cid) -> Strong<dyn IVirtualMachineService> {
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001023 BnVirtualMachineService::new_binder(
Inseob Kimc7d28c72021-10-25 14:28:10 +00001024 VirtualMachineService { state, cid },
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001025 BinderFeatures::default(),
1026 )
1027 }
1028}