blob: 89c6e8a1e9451012f1299da4e2119b7c1726438d [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;
Treehugger Robot3ffa8322021-11-22 12:06:47 +000055use statslog_virtualization_rust::vm_creation_requested::{stats_write, Hypervisor};
Andrew Walbrandff3b942021-06-09 15:20:36 +000056use std::convert::TryInto;
Shikha Panward8e35422021-10-11 13:51:27 +000057use std::ffi::CStr;
Alan Stokes0cc59ee2021-09-24 11:20:34 +010058use std::fs::{create_dir, File, OpenOptions};
Jiyong Park9dd389e2021-08-23 20:42:59 +090059use std::io::{Error, ErrorKind, Write};
Andrew Walbranb15cd6e2021-07-05 16:38:07 +000060use std::num::NonZeroU32;
Inseob Kimc7d28c72021-10-25 14:28:10 +000061use std::os::raw;
Andrew Walbrand3a84182021-09-07 14:48:52 +000062use std::os::unix::io::{FromRawFd, IntoRawFd};
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000063use std::path::{Path, PathBuf};
Inseob Kimc7d28c72021-10-25 14:28:10 +000064use std::ptr::null_mut;
Andrew Walbran320b5602021-03-04 16:11:12 +000065use std::sync::{Arc, Mutex, Weak};
Andrew Walbrancc0db522021-07-12 17:03:42 +000066use vmconfig::VmConfig;
Inseob Kim7f61fe72021-08-20 20:50:47 +090067use vsock::{SockAddr, VsockListener, VsockStream};
Jooyung Han35edb8f2021-07-01 16:17:16 +090068use zip::ZipArchive;
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000069
Andrew Walbranf6bf6862021-05-21 12:41:13 +000070pub const BINDER_SERVICE_IDENTIFIER: &str = "android.system.virtualizationservice";
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000071
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000072/// Directory in which to write disk image files used while running VMs.
Andrew Walbran488bd072021-07-14 13:29:51 +000073pub const TEMPORARY_DIRECTORY: &str = "/data/misc/virtualizationservice";
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000074
Jiyong Park8611a6c2021-07-09 18:17:44 +090075/// The CID representing the host VM
76const VMADDR_CID_HOST: u32 = 2;
77
Jooyung Han95884632021-07-06 22:27:54 +090078/// The size of zero.img.
79/// Gaps in composite disk images are filled with a shared zero.img.
80const ZERO_FILLER_SIZE: u64 = 4096;
81
Jiyong Park9dd389e2021-08-23 20:42:59 +090082/// Magic string for the instance image
83const ANDROID_VM_INSTANCE_MAGIC: &str = "Android-VM-instance";
84
85/// Version of the instance image format
86const ANDROID_VM_INSTANCE_VERSION: u16 = 1;
87
Andrew Walbranf6bf6862021-05-21 12:41:13 +000088/// Implementation of `IVirtualizationService`, the entry point of the AIDL service.
Jooyung Han9900f3d2021-07-06 10:27:54 +090089#[derive(Debug, Default)]
Andrew Walbranf6bf6862021-05-21 12:41:13 +000090pub struct VirtualizationService {
Jiyong Park8611a6c2021-07-09 18:17:44 +090091 state: Arc<Mutex<State>>,
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000092}
93
Shikha Panward8e35422021-10-11 13:51:27 +000094impl Interface for VirtualizationService {
95 fn dump(&self, mut file: &File, _args: &[&CStr]) -> Result<(), StatusCode> {
96 check_permission("android.permission.DUMP").or(Err(StatusCode::PERMISSION_DENIED))?;
97 let state = &mut *self.state.lock().unwrap();
98 let vms = state.vms();
99 writeln!(file, "Running {0} VMs:", vms.len()).or(Err(StatusCode::UNKNOWN_ERROR))?;
100 for vm in vms {
101 writeln!(file, "VM CID: {}", vm.cid).or(Err(StatusCode::UNKNOWN_ERROR))?;
102 writeln!(file, "\tState: {:?}", vm.vm_state.lock().unwrap())
103 .or(Err(StatusCode::UNKNOWN_ERROR))?;
104 writeln!(file, "\tPayload state {:?}", vm.payload_state())
105 .or(Err(StatusCode::UNKNOWN_ERROR))?;
106 writeln!(file, "\tProtected: {}", vm.protected).or(Err(StatusCode::UNKNOWN_ERROR))?;
107 writeln!(file, "\ttemporary_directory: {}", vm.temporary_directory.to_string_lossy())
108 .or(Err(StatusCode::UNKNOWN_ERROR))?;
109 writeln!(file, "\trequester_uid: {}", vm.requester_uid)
110 .or(Err(StatusCode::UNKNOWN_ERROR))?;
111 writeln!(file, "\trequester_sid: {}", vm.requester_sid)
112 .or(Err(StatusCode::UNKNOWN_ERROR))?;
113 writeln!(file, "\trequester_debug_pid: {}", vm.requester_debug_pid)
114 .or(Err(StatusCode::UNKNOWN_ERROR))?;
115 }
116 Ok(())
117 }
118}
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000119
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000120impl IVirtualizationService for VirtualizationService {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000121 /// Creates (but does not start) a new VM with the given configuration, assigning it the next
122 /// available CID.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000123 ///
124 /// Returns a binder `IVirtualMachine` object referring to it, as a handle for the client.
Andrew Walbranf8d94112021-09-07 11:45:36 +0000125 fn createVm(
Andrew Walbrana89fc132021-03-17 17:08:36 +0000126 &self,
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000127 config: &VirtualMachineConfig,
Jiyong Parkb8182bb2021-10-26 22:53:08 +0900128 console_fd: Option<&ParcelFileDescriptor>,
Andrew Walbrana89fc132021-03-17 17:08:36 +0000129 log_fd: Option<&ParcelFileDescriptor>,
130 ) -> binder::Result<Strong<dyn IVirtualMachine>> {
Jiyong Park753553b2021-07-12 21:21:09 +0900131 check_manage_access()?;
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000132 let state = &mut *self.state.lock().unwrap();
Andrew Scull527e5772022-02-11 15:43:28 +0000133 let console_fd = console_fd.map(clone_file).transpose()?;
134 let log_fd = log_fd.map(clone_file).transpose()?;
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000135 let requester_uid = ThreadState::get_calling_uid();
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000136 let requester_sid = get_calling_sid()?;
Andrew Walbran02034492021-04-13 15:05:07 +0000137 let requester_debug_pid = ThreadState::get_calling_pid();
Jiyong Parkd50a0242021-09-16 21:00:14 +0900138 let cid = next_cid().or(Err(ExceptionCode::ILLEGAL_STATE))?;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000139
140 // Counter to generate unique IDs for temporary image files.
141 let mut next_temporary_image_id = 0;
142 // Files which are referred to from composite images. These must be mapped to the crosvm
143 // child process, and not closed before it is started.
144 let mut indirect_files = vec![];
145
146 // Make directory for temporary files.
147 let temporary_directory: PathBuf = format!("{}/{}", TEMPORARY_DIRECTORY, cid).into();
148 create_dir(&temporary_directory).map_err(|e| {
Treehugger Robot3ffa8322021-11-22 12:06:47 +0000149 // At this point, we do not know the protected status of Vm
150 // setting it to false, though this may not be correct.
151 write_vm_creation_stats(false, false);
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000152 error!(
Andrew Walbran806f1542021-06-10 14:07:12 +0000153 "Failed to create temporary directory {:?} for VM files: {}",
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000154 temporary_directory, e
155 );
Andrew Walbran806f1542021-06-10 14:07:12 +0000156 new_binder_exception(
157 ExceptionCode::SERVICE_SPECIFIC,
158 format!(
159 "Failed to create temporary directory {:?} for VM files: {}",
160 temporary_directory, e
161 ),
162 )
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000163 })?;
164
Jiyong Park029977d2021-11-24 21:56:49 +0900165 let is_app_config = matches!(config, VirtualMachineConfig::AppConfig(_));
166
Jooyung Han21e9b922021-06-26 04:14:16 +0900167 let config = match config {
Jooyung Han35edb8f2021-07-01 16:17:16 +0900168 VirtualMachineConfig::AppConfig(config) => BorrowedOrOwned::Owned(
Jooyung Han9900f3d2021-07-06 10:27:54 +0900169 load_app_config(config, &temporary_directory).map_err(|e| {
170 error!("Failed to load app config from {}: {}", &config.configPath, e);
Andrew Walbran3994f002022-01-27 17:33:45 +0000171 write_vm_creation_stats(config.protectedVm, false);
Jooyung Han9900f3d2021-07-06 10:27:54 +0900172 new_binder_exception(
173 ExceptionCode::SERVICE_SPECIFIC,
174 format!("Failed to load app config from {}: {}", &config.configPath, e),
175 )
176 })?,
Jooyung Han35edb8f2021-07-01 16:17:16 +0900177 ),
178 VirtualMachineConfig::RawConfig(config) => BorrowedOrOwned::Borrowed(config),
Jooyung Han21e9b922021-06-26 04:14:16 +0900179 };
Jooyung Han35edb8f2021-07-01 16:17:16 +0900180 let config = config.as_ref();
Andrew Walbran3994f002022-01-27 17:33:45 +0000181 let protected = config.protectedVm;
182
Jiyong Park029977d2021-11-24 21:56:49 +0900183 // Check if partition images are labeled incorrectly. This is to prevent random images
184 // which are not protected by the Android Verified Boot (e.g. bits downloaded by apps) from
185 // being loaded in a pVM. Specifically, for images in the raw config, nothing is allowed
186 // to be labeled as app_data_file. For images in the app config, nothing but the instance
187 // partition is allowed to be labeled as such.
188 config
189 .disks
190 .iter()
191 .flat_map(|disk| disk.partitions.iter())
192 .filter(|partition| {
193 if is_app_config {
194 partition.label != "vm-instance"
195 } else {
196 true // all partitions are checked
197 }
198 })
199 .try_for_each(check_label_for_partition)
200 .map_err(|e| new_binder_exception(ExceptionCode::SERVICE_SPECIFIC, e.to_string()))?;
201
Jooyung Han95884632021-07-06 22:27:54 +0900202 let zero_filler_path = temporary_directory.join("zero.img");
Andrew Walbranfbb39d22021-07-28 17:01:25 +0000203 write_zero_filler(&zero_filler_path).map_err(|e| {
Jooyung Han95884632021-07-06 22:27:54 +0900204 error!("Failed to make composite image: {}", e);
Andrew Walbran3994f002022-01-27 17:33:45 +0000205 write_vm_creation_stats(protected, false);
Jooyung Han95884632021-07-06 22:27:54 +0900206 new_binder_exception(
207 ExceptionCode::SERVICE_SPECIFIC,
208 format!("Failed to make composite image: {}", e),
209 )
210 })?;
Jooyung Han95884632021-07-06 22:27:54 +0900211
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000212 // Assemble disk images if needed.
213 let disks = config
214 .disks
215 .iter()
216 .map(|disk| {
217 assemble_disk_image(
218 disk,
Jooyung Han95884632021-07-06 22:27:54 +0900219 &zero_filler_path,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000220 &temporary_directory,
221 &mut next_temporary_image_id,
222 &mut indirect_files,
223 )
224 })
225 .collect::<Result<Vec<DiskFile>, _>>()?;
226
227 // Actually start the VM.
228 let crosvm_config = CrosvmConfig {
Andrew Walbran02034492021-04-13 15:05:07 +0000229 cid,
Andrew Walbrand3a84182021-09-07 14:48:52 +0000230 bootloader: maybe_clone_file(&config.bootloader)?,
231 kernel: maybe_clone_file(&config.kernel)?,
232 initrd: maybe_clone_file(&config.initrd)?,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000233 disks,
234 params: config.params.to_owned(),
Jiyong Parkd2dc83f2021-12-20 18:40:52 +0900235 protected,
Andrew Walbrancc045902021-07-27 16:06:17 +0000236 memory_mib: config.memoryMib.try_into().ok().and_then(NonZeroU32::new),
Jiyong Park032615f2022-01-10 13:55:34 +0900237 cpus: config.numCpus.try_into().ok().and_then(NonZeroU32::new),
238 cpu_affinity: config.cpuAffinity.clone(),
Jiyong Parkb8182bb2021-10-26 22:53:08 +0900239 console_fd,
Andrew Walbran02034492021-04-13 15:05:07 +0000240 log_fd,
Andrew Walbrand3a84182021-09-07 14:48:52 +0000241 indirect_files,
242 };
Andrew Walbranf8d94112021-09-07 11:45:36 +0000243 let instance = Arc::new(
244 VmInstance::new(
245 crosvm_config,
246 temporary_directory,
247 requester_uid,
248 requester_sid,
249 requester_debug_pid,
Andrew Walbran806f1542021-06-10 14:07:12 +0000250 )
Andrew Walbranf8d94112021-09-07 11:45:36 +0000251 .map_err(|e| {
252 error!("Failed to create VM with config {:?}: {}", config, e);
Andrew Walbran3994f002022-01-27 17:33:45 +0000253 write_vm_creation_stats(protected, false);
Andrew Walbranf8d94112021-09-07 11:45:36 +0000254 new_binder_exception(
255 ExceptionCode::SERVICE_SPECIFIC,
256 format!("Failed to create VM: {}", e),
257 )
258 })?,
259 );
Andrew Walbran320b5602021-03-04 16:11:12 +0000260 state.add_vm(Arc::downgrade(&instance));
Andrew Walbran3994f002022-01-27 17:33:45 +0000261 write_vm_creation_stats(protected, true);
Andrew Walbran320b5602021-03-04 16:11:12 +0000262 Ok(VirtualMachine::create(instance))
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000263 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000264
Andrew Walbrandff3b942021-06-09 15:20:36 +0000265 /// Initialise an empty partition image of the given size to be used as a writable partition.
266 fn initializeWritablePartition(
267 &self,
268 image_fd: &ParcelFileDescriptor,
269 size: i64,
Jiyong Park9dd389e2021-08-23 20:42:59 +0900270 partition_type: PartitionType,
Andrew Walbrandff3b942021-06-09 15:20:36 +0000271 ) -> binder::Result<()> {
Jiyong Park753553b2021-07-12 21:21:09 +0900272 check_manage_access()?;
Andrew Walbrandfc953d2021-06-10 13:59:56 +0000273 let size = size.try_into().map_err(|e| {
Andrew Walbran806f1542021-06-10 14:07:12 +0000274 new_binder_exception(
275 ExceptionCode::ILLEGAL_ARGUMENT,
276 format!("Invalid size {}: {}", size, e),
277 )
Andrew Walbrandff3b942021-06-09 15:20:36 +0000278 })?;
Andrew Walbrandfc953d2021-06-10 13:59:56 +0000279 let image = clone_file(image_fd)?;
Jooyung Han1edd5b92021-10-28 10:58:05 +0900280 // initialize the file. Any data in the file will be erased.
281 image.set_len(0).map_err(|e| {
282 new_binder_exception(
283 ExceptionCode::SERVICE_SPECIFIC,
284 format!("Failed to reset a file: {}", e),
285 )
286 })?;
Jiyong Park9dd389e2021-08-23 20:42:59 +0900287 let mut part = QcowFile::new(image, size).map_err(|e| {
Andrew Walbran806f1542021-06-10 14:07:12 +0000288 new_binder_exception(
289 ExceptionCode::SERVICE_SPECIFIC,
290 format!("Failed to create QCOW2 image: {}", e),
291 )
Andrew Walbrandfc953d2021-06-10 13:59:56 +0000292 })?;
Andrew Walbrandff3b942021-06-09 15:20:36 +0000293
Jiyong Park9dd389e2021-08-23 20:42:59 +0900294 match partition_type {
295 PartitionType::RAW => Ok(()),
296 PartitionType::ANDROID_VM_INSTANCE => format_as_android_vm_instance(&mut part),
297 _ => Err(Error::new(
298 ErrorKind::Unsupported,
299 format!("Unsupported partition type {:?}", partition_type),
300 )),
301 }
302 .map_err(|e| {
303 new_binder_exception(
304 ExceptionCode::SERVICE_SPECIFIC,
305 format!("Failed to initialize partition as {:?}: {}", partition_type, e),
306 )
307 })?;
308
Andrew Walbrandff3b942021-06-09 15:20:36 +0000309 Ok(())
310 }
311
Jiyong Park0a248432021-08-20 23:32:39 +0900312 /// Creates or update the idsig file by digesting the input APK file.
313 fn createOrUpdateIdsigFile(
314 &self,
315 input_fd: &ParcelFileDescriptor,
316 idsig_fd: &ParcelFileDescriptor,
317 ) -> binder::Result<()> {
318 // TODO(b/193504400): do this only when (1) idsig_fd is empty or (2) the APK digest in
319 // idsig_fd is different from APK digest in input_fd
320
321 let mut input = clone_file(input_fd)?;
322 let mut sig = V4Signature::create(&mut input, 4096, &[], HashAlgorithm::SHA256).unwrap();
323
324 let mut output = clone_file(idsig_fd)?;
325 output.set_len(0).unwrap();
326 sig.write_into(&mut output).unwrap();
327 Ok(())
328 }
329
Andrew Walbran320b5602021-03-04 16:11:12 +0000330 /// Get a list of all currently running VMs. This method is only intended for debug purposes,
331 /// and as such is only permitted from the shell user.
332 fn debugListVms(&self) -> binder::Result<Vec<VirtualMachineDebugInfo>> {
Andrew Walbran806f1542021-06-10 14:07:12 +0000333 check_debug_access()?;
Andrew Walbran320b5602021-03-04 16:11:12 +0000334
335 let state = &mut *self.state.lock().unwrap();
336 let vms = state.vms();
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000337 let cids = vms
338 .into_iter()
339 .map(|vm| VirtualMachineDebugInfo {
340 cid: vm.cid as i32,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000341 temporaryDirectory: vm.temporary_directory.to_string_lossy().to_string(),
Andrew Walbran1ef19ae2021-04-07 11:31:57 +0000342 requesterUid: vm.requester_uid as i32,
343 requesterSid: vm.requester_sid.clone(),
Andrew Walbran02034492021-04-13 15:05:07 +0000344 requesterPid: vm.requester_debug_pid,
Andrew Walbran6b650662021-09-07 13:13:23 +0000345 state: get_state(&vm),
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000346 })
347 .collect();
Andrew Walbran320b5602021-03-04 16:11:12 +0000348 Ok(cids)
349 }
David Brazdil3c2ddef2021-03-18 13:09:57 +0000350
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000351 /// Hold a strong reference to a VM in VirtualizationService. This method is only intended for
352 /// debug purposes, and as such is only permitted from the shell user.
Andrei Homescu1415c132021-03-24 02:39:55 +0000353 fn debugHoldVmRef(&self, vmref: &Strong<dyn IVirtualMachine>) -> binder::Result<()> {
Andrew Walbran806f1542021-06-10 14:07:12 +0000354 check_debug_access()?;
David Brazdil3c2ddef2021-03-18 13:09:57 +0000355
David Brazdil3c2ddef2021-03-18 13:09:57 +0000356 let state = &mut *self.state.lock().unwrap();
Andrei Homescu1415c132021-03-24 02:39:55 +0000357 state.debug_hold_vm(vmref.clone());
David Brazdil3c2ddef2021-03-18 13:09:57 +0000358 Ok(())
359 }
360
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000361 /// Drop reference to a VM that is being held by VirtualizationService. Returns the reference if
362 /// the VM was found and None otherwise. This method is only intended for debug purposes, and as
363 /// such is only permitted from the shell user.
David Brazdil3c2ddef2021-03-18 13:09:57 +0000364 fn debugDropVmRef(&self, cid: i32) -> binder::Result<Option<Strong<dyn IVirtualMachine>>> {
Andrew Walbran806f1542021-06-10 14:07:12 +0000365 check_debug_access()?;
David Brazdil3c2ddef2021-03-18 13:09:57 +0000366
367 let state = &mut *self.state.lock().unwrap();
368 Ok(state.debug_drop_vm(cid))
369 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000370}
371
Jiyong Park8611a6c2021-07-09 18:17:44 +0900372impl VirtualizationService {
373 pub fn init() -> VirtualizationService {
374 let service = VirtualizationService::default();
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900375
376 // server for payload output
Jiyong Park8611a6c2021-07-09 18:17:44 +0900377 let state = service.state.clone(); // reference to state (not the state itself) is copied
378 std::thread::spawn(move || {
Inseob Kim7f61fe72021-08-20 20:50:47 +0900379 handle_stream_connection_from_vm(state).unwrap();
Jiyong Park8611a6c2021-07-09 18:17:44 +0900380 });
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900381
382 // binder server for vm
Inseob Kimc7d28c72021-10-25 14:28:10 +0000383 let mut state = service.state.clone(); // reference to state (not the state itself) is copied
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900384 std::thread::spawn(move || {
Inseob Kimc7d28c72021-10-25 14:28:10 +0000385 let state_ptr = &mut state as *mut _ as *mut raw::c_void;
386
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900387 debug!("virtual machine service is starting as an RPC service.");
Inseob Kimc7d28c72021-10-25 14:28:10 +0000388 // SAFETY: factory function is only ever called by RunRpcServerWithFactory, within the
389 // lifetime of the state, with context taking the pointer value above (so a properly
390 // aligned non-null pointer to an initialized instance).
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900391 let retval = unsafe {
Inseob Kimc7d28c72021-10-25 14:28:10 +0000392 binder_rpc_unstable_bindgen::RunRpcServerWithFactory(
393 Some(VirtualMachineService::factory),
394 state_ptr,
Inseob Kimd0587562021-09-01 21:27:32 +0900395 VM_BINDER_SERVICE_PORT as u32,
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900396 )
397 };
398 if retval {
399 debug!("RPC server has shut down gracefully");
400 } else {
401 bail!("Premature termination of RPC server");
402 }
403
404 Ok(retval)
405 });
Jiyong Park8611a6c2021-07-09 18:17:44 +0900406 service
407 }
408}
409
Treehugger Robot3ffa8322021-11-22 12:06:47 +0000410/// Write the stats of VMCreation to statsd
411fn write_vm_creation_stats(protected: bool, success: bool) {
412 match stats_write(Hypervisor::Pkvm, protected, success) {
413 Err(e) => {
Andrew Walbranf6d600f2022-02-03 14:42:39 +0000414 warn!("statslog_rust failed with error: {}", e);
Treehugger Robot3ffa8322021-11-22 12:06:47 +0000415 }
Andrew Walbranf6d600f2022-02-03 14:42:39 +0000416 Ok(_) => trace!("statslog_rust succeeded for virtualization service"),
Treehugger Robot3ffa8322021-11-22 12:06:47 +0000417 }
418}
419
Andrew Walbran6b650662021-09-07 13:13:23 +0000420/// Waits for incoming connections from VM. If a new connection is made, stores the stream in the
421/// corresponding `VmInstance`.
Inseob Kim7f61fe72021-08-20 20:50:47 +0900422fn handle_stream_connection_from_vm(state: Arc<Mutex<State>>) -> Result<()> {
Inseob Kimd0587562021-09-01 21:27:32 +0900423 let listener =
424 VsockListener::bind_with_cid_port(VMADDR_CID_HOST, VM_STREAM_SERVICE_PORT as u32)?;
Jiyong Park8611a6c2021-07-09 18:17:44 +0900425 for stream in listener.incoming() {
426 let stream = match stream {
427 Err(e) => {
428 warn!("invalid incoming connection: {}", e);
429 continue;
430 }
431 Ok(s) => s,
432 };
433 if let Ok(SockAddr::Vsock(addr)) = stream.peer_addr() {
434 let cid = addr.cid();
435 let port = addr.port();
Inseob Kim7f61fe72021-08-20 20:50:47 +0900436 info!("payload stream connected from cid={}, port={}", cid, port);
Jiyong Park8611a6c2021-07-09 18:17:44 +0900437 if let Some(vm) = state.lock().unwrap().get_vm(cid) {
Chris Wailes8bbb8932021-09-10 14:14:19 -0700438 *vm.stream.lock().unwrap() = Some(stream);
Inseob Kim7f61fe72021-08-20 20:50:47 +0900439 } else {
440 error!("connection from cid={} is not from a guest VM", cid);
Jiyong Park8611a6c2021-07-09 18:17:44 +0900441 }
442 }
443 }
444 Ok(())
445}
446
Andrew Walbranfbb39d22021-07-28 17:01:25 +0000447fn write_zero_filler(zero_filler_path: &Path) -> Result<()> {
Jooyung Han95884632021-07-06 22:27:54 +0900448 let file = OpenOptions::new()
449 .create_new(true)
450 .read(true)
451 .write(true)
452 .open(zero_filler_path)
453 .with_context(|| "Failed to create zero.img")?;
454 file.set_len(ZERO_FILLER_SIZE)?;
Andrew Walbranfbb39d22021-07-28 17:01:25 +0000455 Ok(())
Jooyung Han95884632021-07-06 22:27:54 +0900456}
457
Jiyong Park9dd389e2021-08-23 20:42:59 +0900458fn format_as_android_vm_instance(part: &mut dyn Write) -> std::io::Result<()> {
459 part.write_all(ANDROID_VM_INSTANCE_MAGIC.as_bytes())?;
460 part.write_all(&ANDROID_VM_INSTANCE_VERSION.to_le_bytes())?;
461 part.flush()
462}
463
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000464/// Given the configuration for a disk image, assembles the `DiskFile` to pass to crosvm.
465///
466/// This may involve assembling a composite disk from a set of partition images.
467fn assemble_disk_image(
468 disk: &DiskImage,
Jooyung Han95884632021-07-06 22:27:54 +0900469 zero_filler_path: &Path,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000470 temporary_directory: &Path,
471 next_temporary_image_id: &mut u64,
472 indirect_files: &mut Vec<File>,
Andrew Walbran806f1542021-06-10 14:07:12 +0000473) -> Result<DiskFile, Status> {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000474 let image = if !disk.partitions.is_empty() {
475 if disk.image.is_some() {
476 warn!("DiskImage {:?} contains both image and partitions.", disk);
Andrew Walbran806f1542021-06-10 14:07:12 +0000477 return Err(new_binder_exception(
478 ExceptionCode::ILLEGAL_ARGUMENT,
479 "DiskImage contains both image and partitions.",
480 ));
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000481 }
482
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000483 let composite_image_filenames =
484 make_composite_image_filenames(temporary_directory, next_temporary_image_id);
485 let (image, partition_files) = make_composite_image(
486 &disk.partitions,
Jooyung Han95884632021-07-06 22:27:54 +0900487 zero_filler_path,
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000488 &composite_image_filenames.composite,
489 &composite_image_filenames.header,
490 &composite_image_filenames.footer,
491 )
492 .map_err(|e| {
493 error!("Failed to make composite image with config {:?}: {}", disk, e);
494 new_binder_exception(
495 ExceptionCode::SERVICE_SPECIFIC,
496 format!("Failed to make composite image: {}", e),
497 )
498 })?;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000499
500 // Pass the file descriptors for the various partition files to crosvm when it
501 // is run.
502 indirect_files.extend(partition_files);
503
504 image
505 } else if let Some(image) = &disk.image {
506 clone_file(image)?
507 } else {
508 warn!("DiskImage {:?} didn't contain image or partitions.", disk);
Andrew Walbran806f1542021-06-10 14:07:12 +0000509 return Err(new_binder_exception(
510 ExceptionCode::ILLEGAL_ARGUMENT,
511 "DiskImage didn't contain image or partitions.",
512 ));
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000513 };
514
515 Ok(DiskFile { image, writable: disk.writable })
516}
517
Jooyung Han21e9b922021-06-26 04:14:16 +0900518fn load_app_config(
519 config: &VirtualMachineAppConfig,
520 temporary_directory: &Path,
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900521) -> Result<VirtualMachineRawConfig> {
Andrew Walbrancc0db522021-07-12 17:03:42 +0000522 let apk_file = clone_file(config.apk.as_ref().unwrap())?;
523 let idsig_file = clone_file(config.idsig.as_ref().unwrap())?;
Jiyong Park8d081812021-07-23 17:45:04 +0900524 let instance_file = clone_file(config.instanceImage.as_ref().unwrap())?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900525 let config_path = &config.configPath;
526
Andrew Walbrancc0db522021-07-12 17:03:42 +0000527 let mut apk_zip = ZipArchive::new(&apk_file)?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900528 let config_file = apk_zip.by_name(config_path)?;
529 let vm_payload_config: VmPayloadConfig = serde_json::from_reader(config_file)?;
530
531 let os_name = &vm_payload_config.os.name;
Andrew Walbrancc0db522021-07-12 17:03:42 +0000532
Jooyung Han35edb8f2021-07-01 16:17:16 +0900533 // For now, the only supported "os" value is "microdroid"
534 if os_name != "microdroid" {
Andrew Walbrancc0db522021-07-12 17:03:42 +0000535 bail!("Unknown OS \"{}\"", os_name);
Jooyung Han35edb8f2021-07-01 16:17:16 +0900536 }
Andrew Walbrancc0db522021-07-12 17:03:42 +0000537
538 // It is safe to construct a filename based on the os_name because we've already checked that it
539 // is one of the allowed values.
Jooyung Han21e9b922021-06-26 04:14:16 +0900540 let vm_config_path = PathBuf::from(format!("/apex/com.android.virt/etc/{}.json", os_name));
541 let vm_config_file = File::open(vm_config_path)?;
Andrew Walbrancc0db522021-07-12 17:03:42 +0000542 let mut vm_config = VmConfig::load(&vm_config_file)?.to_parcelable()?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900543
Andrew Walbrancc045902021-07-27 16:06:17 +0000544 if config.memoryMib > 0 {
545 vm_config.memoryMib = config.memoryMib;
Andrew Walbran45bcb0c2021-07-14 15:02:06 +0000546 }
547
Andrew Walbran3994f002022-01-27 17:33:45 +0000548 vm_config.protectedVm = config.protectedVm;
Jiyong Park032615f2022-01-10 13:55:34 +0900549 vm_config.numCpus = config.numCpus;
550 vm_config.cpuAffinity = config.cpuAffinity.clone();
551
Andrew Walbrancc0db522021-07-12 17:03:42 +0000552 // Microdroid requires an additional payload disk image and the bootconfig partition.
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900553 if os_name == "microdroid" {
Andrew Walbrancc0db522021-07-12 17:03:42 +0000554 add_microdroid_images(
555 config,
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900556 temporary_directory,
Andrew Walbrancc0db522021-07-12 17:03:42 +0000557 apk_file,
558 idsig_file,
Jiyong Park8d081812021-07-23 17:45:04 +0900559 instance_file,
Jooyung Han5dc42172021-10-05 16:43:47 +0900560 &vm_payload_config,
Andrew Walbrancc0db522021-07-12 17:03:42 +0000561 &mut vm_config,
562 )?;
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900563 }
Jooyung Han21e9b922021-06-26 04:14:16 +0900564
Andrew Walbrancc0db522021-07-12 17:03:42 +0000565 Ok(vm_config)
Jooyung Han21e9b922021-06-26 04:14:16 +0900566}
567
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000568/// Generates a unique filename to use for a composite disk image.
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000569fn make_composite_image_filenames(
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000570 temporary_directory: &Path,
571 next_temporary_image_id: &mut u64,
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000572) -> CompositeImageFilenames {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000573 let id = *next_temporary_image_id;
574 *next_temporary_image_id += 1;
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000575 CompositeImageFilenames {
576 composite: temporary_directory.join(format!("composite-{}.img", id)),
577 header: temporary_directory.join(format!("composite-{}-header.img", id)),
578 footer: temporary_directory.join(format!("composite-{}-footer.img", id)),
579 }
580}
581
582/// Filenames for a composite disk image, including header and footer partitions.
583#[derive(Clone, Debug, Eq, PartialEq)]
584struct CompositeImageFilenames {
585 /// The composite disk image itself.
586 composite: PathBuf,
587 /// The header partition image.
588 header: PathBuf,
589 /// The footer partition image.
590 footer: PathBuf,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000591}
592
593/// Gets the calling SID of the current Binder thread.
Andrew Walbran806f1542021-06-10 14:07:12 +0000594fn get_calling_sid() -> Result<String, Status> {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000595 ThreadState::with_calling_sid(|sid| {
596 if let Some(sid) = sid {
597 match sid.to_str() {
598 Ok(sid) => Ok(sid.to_owned()),
599 Err(e) => {
Andrew Walbran806f1542021-06-10 14:07:12 +0000600 error!("SID was not valid UTF-8: {}", e);
601 Err(new_binder_exception(
602 ExceptionCode::ILLEGAL_ARGUMENT,
603 format!("SID was not valid UTF-8: {}", e),
604 ))
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000605 }
606 }
607 } else {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000608 error!("Missing SID on createVm");
609 Err(new_binder_exception(ExceptionCode::SECURITY, "Missing SID on createVm"))
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000610 }
611 })
612}
613
Jiyong Park753553b2021-07-12 21:21:09 +0900614/// Checks whether the caller has a specific permission
615fn check_permission(perm: &str) -> binder::Result<()> {
616 let calling_pid = ThreadState::get_calling_pid();
617 let calling_uid = ThreadState::get_calling_uid();
618 // Root can do anything
619 if calling_uid == 0 {
620 return Ok(());
621 }
622 let perm_svc: Strong<dyn IPermissionController::IPermissionController> =
623 binder::get_interface("permission")?;
624 if perm_svc.checkPermission(perm, calling_pid, calling_uid as i32)? {
Andrew Walbran806f1542021-06-10 14:07:12 +0000625 Ok(())
626 } else {
Jiyong Park753553b2021-07-12 21:21:09 +0900627 Err(new_binder_exception(
628 ExceptionCode::SECURITY,
629 format!("does not have the {} permission", perm),
630 ))
Andrew Walbran806f1542021-06-10 14:07:12 +0000631 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000632}
633
Jiyong Park753553b2021-07-12 21:21:09 +0900634/// Check whether the caller of the current Binder method is allowed to call debug methods.
635fn check_debug_access() -> binder::Result<()> {
636 check_permission("android.permission.DEBUG_VIRTUAL_MACHINE")
637}
638
639/// Check whether the caller of the current Binder method is allowed to manage VMs
640fn check_manage_access() -> binder::Result<()> {
641 check_permission("android.permission.MANAGE_VIRTUAL_MACHINE")
642}
643
Jiyong Park029977d2021-11-24 21:56:49 +0900644/// Check if a partition has selinux labels that are not allowed
645fn check_label_for_partition(partition: &Partition) -> Result<()> {
646 let ctx = getfilecon(partition.image.as_ref().unwrap().as_ref())?;
647 if ctx == SeContext::new("u:object_r:app_data_file:s0").unwrap() {
648 Err(anyhow!("Partition {} shouldn't be labeled as {}", &partition.label, ctx))
649 } else {
650 Ok(())
651 }
652}
653
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000654/// Implementation of the AIDL `IVirtualMachine` interface. Used as a handle to a VM.
655#[derive(Debug)]
656struct VirtualMachine {
657 instance: Arc<VmInstance>,
Alan Stokes0cc59ee2021-09-24 11:20:34 +0100658 /// Keeps our service process running as long as this VM instance exists.
Chris Wailes641fc4a2021-12-01 15:03:21 -0800659 #[allow(dead_code)]
Alan Stokes0cc59ee2021-09-24 11:20:34 +0100660 lazy_service_guard: LazyServiceGuard,
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000661}
662
663impl VirtualMachine {
664 fn create(instance: Arc<VmInstance>) -> Strong<dyn IVirtualMachine> {
Alan Stokes0cc59ee2021-09-24 11:20:34 +0100665 let binder = VirtualMachine { instance, lazy_service_guard: Default::default() };
Andrew Walbran4de28782021-04-13 14:51:43 +0000666 BnVirtualMachine::new_binder(binder, BinderFeatures::default())
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000667 }
668}
669
670impl Interface for VirtualMachine {}
671
672impl IVirtualMachine for VirtualMachine {
673 fn getCid(&self) -> binder::Result<i32> {
Jiyong Park753553b2021-07-12 21:21:09 +0900674 // Don't check permission. The owner of the VM might have passed this binder object to
675 // others.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000676 Ok(self.instance.cid as i32)
677 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000678
Andrew Walbran6b650662021-09-07 13:13:23 +0000679 fn getState(&self) -> binder::Result<VirtualMachineState> {
Jiyong Park753553b2021-07-12 21:21:09 +0900680 // Don't check permission. The owner of the VM might have passed this binder object to
681 // others.
Andrew Walbran6b650662021-09-07 13:13:23 +0000682 Ok(get_state(&self.instance))
Andrew Walbrandae07162021-03-12 17:05:20 +0000683 }
684
685 fn registerCallback(
686 &self,
687 callback: &Strong<dyn IVirtualMachineCallback>,
688 ) -> binder::Result<()> {
Jiyong Park753553b2021-07-12 21:21:09 +0900689 // Don't check permission. The owner of the VM might have passed this binder object to
690 // others.
691 //
Andrew Walbrandae07162021-03-12 17:05:20 +0000692 // TODO: Should this give an error if the VM is already dead?
693 self.instance.callbacks.add(callback.clone());
694 Ok(())
695 }
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000696
Andrew Walbranf8d94112021-09-07 11:45:36 +0000697 fn start(&self) -> binder::Result<()> {
698 self.instance.start().map_err(|e| {
699 error!("Error starting VM with CID {}: {:?}", self.instance.cid, e);
700 new_binder_exception(ExceptionCode::SERVICE_SPECIFIC, e.to_string())
701 })
702 }
703
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000704 fn connectVsock(&self, port: i32) -> binder::Result<ParcelFileDescriptor> {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000705 if !matches!(&*self.instance.vm_state.lock().unwrap(), VmState::Running { .. }) {
706 return Err(new_binder_exception(ExceptionCode::SERVICE_SPECIFIC, "VM is not running"));
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000707 }
708 let stream =
709 VsockStream::connect_with_cid_port(self.instance.cid, port as u32).map_err(|e| {
710 new_binder_exception(
711 ExceptionCode::SERVICE_SPECIFIC,
712 format!("Failed to connect: {}", e),
713 )
714 })?;
715 Ok(vsock_stream_to_pfd(stream))
716 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000717}
718
719impl Drop for VirtualMachine {
720 fn drop(&mut self) {
721 debug!("Dropping {:?}", self);
722 self.instance.kill();
723 }
724}
725
726/// A set of Binders to be called back in response to various events on the VM, such as when it
727/// dies.
728#[derive(Debug, Default)]
729pub struct VirtualMachineCallbacks(Mutex<Vec<Strong<dyn IVirtualMachineCallback>>>);
730
731impl VirtualMachineCallbacks {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900732 /// Call all registered callbacks to notify that the payload has started.
Inseob Kim7f61fe72021-08-20 20:50:47 +0900733 pub fn notify_payload_started(&self, cid: Cid, stream: Option<VsockStream>) {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900734 let callbacks = &*self.0.lock().unwrap();
Inseob Kim7f61fe72021-08-20 20:50:47 +0900735 let pfd = stream.map(vsock_stream_to_pfd);
Jiyong Park8611a6c2021-07-09 18:17:44 +0900736 for callback in callbacks {
Inseob Kim7f61fe72021-08-20 20:50:47 +0900737 if let Err(e) = callback.onPayloadStarted(cid as i32, pfd.as_ref()) {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900738 error!("Error notifying payload start event from VM CID {}: {}", cid, e);
739 }
740 }
741 }
742
Inseob Kim14cb8692021-08-31 21:50:39 +0900743 /// Call all registered callbacks to notify that the payload is ready to serve.
744 pub fn notify_payload_ready(&self, cid: Cid) {
745 let callbacks = &*self.0.lock().unwrap();
746 for callback in callbacks {
747 if let Err(e) = callback.onPayloadReady(cid as i32) {
748 error!("Error notifying payload ready event from VM CID {}: {}", cid, e);
749 }
750 }
751 }
752
Inseob Kim2444af92021-08-31 01:22:50 +0900753 /// Call all registered callbacks to notify that the payload has finished.
754 pub fn notify_payload_finished(&self, cid: Cid, exit_code: i32) {
755 let callbacks = &*self.0.lock().unwrap();
756 for callback in callbacks {
757 if let Err(e) = callback.onPayloadFinished(cid as i32, exit_code) {
758 error!("Error notifying payload finish event from VM CID {}: {}", cid, e);
759 }
760 }
761 }
762
Jooyung Handd0a1732021-11-23 15:26:20 +0900763 /// Call all registered callbacks to say that the VM encountered an error.
764 pub fn notify_error(&self, cid: Cid, error_code: i32, message: &str) {
765 let callbacks = &*self.0.lock().unwrap();
766 for callback in callbacks {
767 if let Err(e) = callback.onError(cid as i32, error_code, message) {
768 error!("Error notifying error event from VM CID {}: {}", cid, e);
769 }
770 }
771 }
772
Andrew Walbrandae07162021-03-12 17:05:20 +0000773 /// Call all registered callbacks to say that the VM has died.
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000774 pub fn callback_on_died(&self, cid: Cid, reason: DeathReason) {
Andrew Walbrandae07162021-03-12 17:05:20 +0000775 let callbacks = &*self.0.lock().unwrap();
776 for callback in callbacks {
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000777 if let Err(e) = callback.onDied(cid as i32, reason) {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900778 error!("Error notifying exit of VM CID {}: {}", cid, e);
Andrew Walbrandae07162021-03-12 17:05:20 +0000779 }
780 }
781 }
782
783 /// Add a new callback to the set.
784 fn add(&self, callback: Strong<dyn IVirtualMachineCallback>) {
785 self.0.lock().unwrap().push(callback);
786 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000787}
788
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000789/// The mutable state of the VirtualizationService. There should only be one instance of this
790/// struct.
Chris Wailes641fc4a2021-12-01 15:03:21 -0800791#[derive(Debug, Default)]
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000792struct State {
Andrew Walbran320b5602021-03-04 16:11:12 +0000793 /// The VMs which have been started. When VMs are started a weak reference is added to this list
794 /// while a strong reference is returned to the caller over Binder. Once all copies of the
795 /// Binder client are dropped the weak reference here will become invalid, and will be removed
796 /// from the list opportunistically the next time `add_vm` is called.
797 vms: Vec<Weak<VmInstance>>,
David Brazdil3c2ddef2021-03-18 13:09:57 +0000798
799 /// Vector of strong VM references held on behalf of users that cannot hold them themselves.
800 /// This is only used for debugging purposes.
801 debug_held_vms: Vec<Strong<dyn IVirtualMachine>>,
Andrew Walbran320b5602021-03-04 16:11:12 +0000802}
803
804impl State {
Andrew Walbrandae07162021-03-12 17:05:20 +0000805 /// Get a list of VMs which still have Binder references to them.
Andrew Walbran320b5602021-03-04 16:11:12 +0000806 fn vms(&self) -> Vec<Arc<VmInstance>> {
807 // Attempt to upgrade the weak pointers to strong pointers.
808 self.vms.iter().filter_map(Weak::upgrade).collect()
809 }
810
811 /// Add a new VM to the list.
812 fn add_vm(&mut self, vm: Weak<VmInstance>) {
813 // Garbage collect any entries from the stored list which no longer exist.
814 self.vms.retain(|vm| vm.strong_count() > 0);
815
816 // Actually add the new VM.
817 self.vms.push(vm);
818 }
David Brazdil3c2ddef2021-03-18 13:09:57 +0000819
Jiyong Park8611a6c2021-07-09 18:17:44 +0900820 /// Get a VM that corresponds to the given cid
821 fn get_vm(&self, cid: Cid) -> Option<Arc<VmInstance>> {
822 self.vms().into_iter().find(|vm| vm.cid == cid)
823 }
824
David Brazdil3c2ddef2021-03-18 13:09:57 +0000825 /// Store a strong VM reference.
826 fn debug_hold_vm(&mut self, vm: Strong<dyn IVirtualMachine>) {
827 self.debug_held_vms.push(vm);
828 }
829
830 /// Retrieve and remove a strong VM reference.
831 fn debug_drop_vm(&mut self, cid: i32) -> Option<Strong<dyn IVirtualMachine>> {
832 let pos = self.debug_held_vms.iter().position(|vm| vm.getCid() == Ok(cid))?;
Alan Stokes7e54e292021-09-09 11:37:56 +0100833 let vm = self.debug_held_vms.swap_remove(pos);
Alan Stokes7e54e292021-09-09 11:37:56 +0100834 Some(vm)
David Brazdil3c2ddef2021-03-18 13:09:57 +0000835 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000836}
837
Jiyong Parkd50a0242021-09-16 21:00:14 +0900838/// Get the next available CID, or an error if we have run out. The last CID used is stored in
839/// a system property so that restart of virtualizationservice doesn't reuse CID while the host
840/// Android is up.
841fn next_cid() -> Result<Cid> {
Andrew Walbran014efb52022-02-03 17:43:11 +0000842 let next = if let Some(val) = system_properties::read(SYSPROP_LAST_CID)? {
Jiyong Parkd50a0242021-09-16 21:00:14 +0900843 if let Ok(num) = val.parse::<u32>() {
844 num.checked_add(1).ok_or_else(|| anyhow!("run out of CID"))?
845 } else {
846 error!("Invalid last CID {}. Using {}", &val, FIRST_GUEST_CID);
847 FIRST_GUEST_CID
848 }
849 } else {
850 // First VM since the boot
851 FIRST_GUEST_CID
852 };
853 // Persist the last value for next use
854 let str_val = format!("{}", next);
855 system_properties::write(SYSPROP_LAST_CID, &str_val)?;
856 Ok(next)
857}
858
Andrew Walbran6b650662021-09-07 13:13:23 +0000859/// Gets the `VirtualMachineState` of the given `VmInstance`.
860fn get_state(instance: &VmInstance) -> VirtualMachineState {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000861 match &*instance.vm_state.lock().unwrap() {
862 VmState::NotStarted { .. } => VirtualMachineState::NOT_STARTED,
863 VmState::Running { .. } => match instance.payload_state() {
Andrew Walbran6b650662021-09-07 13:13:23 +0000864 PayloadState::Starting => VirtualMachineState::STARTING,
865 PayloadState::Started => VirtualMachineState::STARTED,
866 PayloadState::Ready => VirtualMachineState::READY,
867 PayloadState::Finished => VirtualMachineState::FINISHED,
Andrew Walbranf8d94112021-09-07 11:45:36 +0000868 },
869 VmState::Dead => VirtualMachineState::DEAD,
870 VmState::Failed => VirtualMachineState::DEAD,
Andrew Walbran6b650662021-09-07 13:13:23 +0000871 }
872}
873
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000874/// Converts a `&ParcelFileDescriptor` to a `File` by cloning the file.
Andrew Walbran806f1542021-06-10 14:07:12 +0000875fn clone_file(file: &ParcelFileDescriptor) -> Result<File, Status> {
876 file.as_ref().try_clone().map_err(|e| {
877 new_binder_exception(
878 ExceptionCode::BAD_PARCELABLE,
879 format!("Failed to clone File from ParcelFileDescriptor: {}", e),
880 )
881 })
882}
883
Andrew Walbrand3a84182021-09-07 14:48:52 +0000884/// Converts an `&Option<ParcelFileDescriptor>` to an `Option<File>` by cloning the file.
885fn maybe_clone_file(file: &Option<ParcelFileDescriptor>) -> Result<Option<File>, Status> {
886 file.as_ref().map(clone_file).transpose()
887}
888
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000889/// Converts a `VsockStream` to a `ParcelFileDescriptor`.
890fn vsock_stream_to_pfd(stream: VsockStream) -> ParcelFileDescriptor {
891 // SAFETY: ownership is transferred from stream to f
892 let f = unsafe { File::from_raw_fd(stream.into_raw_fd()) };
893 ParcelFileDescriptor::new(f)
894}
895
Jooyung Han35edb8f2021-07-01 16:17:16 +0900896/// Simple utility for referencing Borrowed or Owned. Similar to std::borrow::Cow, but
897/// it doesn't require that T implements Clone.
898enum BorrowedOrOwned<'a, T> {
899 Borrowed(&'a T),
900 Owned(T),
901}
902
903impl<'a, T> AsRef<T> for BorrowedOrOwned<'a, T> {
904 fn as_ref(&self) -> &T {
905 match self {
906 Self::Borrowed(b) => b,
Chris Wailes68c39f82021-07-27 16:03:44 -0700907 Self::Owned(o) => o,
Jooyung Han35edb8f2021-07-01 16:17:16 +0900908 }
909 }
910}
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900911
912/// Implementation of `IVirtualMachineService`, the entry point of the AIDL service.
913#[derive(Debug, Default)]
914struct VirtualMachineService {
915 state: Arc<Mutex<State>>,
Inseob Kimc7d28c72021-10-25 14:28:10 +0000916 cid: Cid,
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900917}
918
919impl Interface for VirtualMachineService {}
920
921impl IVirtualMachineService for VirtualMachineService {
Inseob Kimc7d28c72021-10-25 14:28:10 +0000922 fn notifyPayloadStarted(&self) -> binder::Result<()> {
923 let cid = self.cid;
Inseob Kim7f61fe72021-08-20 20:50:47 +0900924 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
925 info!("VM having CID {} started payload", cid);
Andrew Walbran6b650662021-09-07 13:13:23 +0000926 vm.update_payload_state(PayloadState::Started)
927 .map_err(|e| new_binder_exception(ExceptionCode::ILLEGAL_STATE, e.to_string()))?;
Inseob Kim7f61fe72021-08-20 20:50:47 +0900928 let stream = vm.stream.lock().unwrap().take();
929 vm.callbacks.notify_payload_started(cid, stream);
930 Ok(())
931 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +0900932 error!("notifyPayloadStarted is called from an unknown CID {}", cid);
Inseob Kim7f61fe72021-08-20 20:50:47 +0900933 Err(new_binder_exception(
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900934 ExceptionCode::SERVICE_SPECIFIC,
Jooyung Handd0a1732021-11-23 15:26:20 +0900935 format!("cannot find a VM with CID {}", cid),
Inseob Kim7f61fe72021-08-20 20:50:47 +0900936 ))
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900937 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900938 }
Inseob Kim2444af92021-08-31 01:22:50 +0900939
Inseob Kimc7d28c72021-10-25 14:28:10 +0000940 fn notifyPayloadReady(&self) -> binder::Result<()> {
941 let cid = self.cid;
Inseob Kim14cb8692021-08-31 21:50:39 +0900942 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
943 info!("VM having CID {} payload is ready", cid);
Andrew Walbran6b650662021-09-07 13:13:23 +0000944 vm.update_payload_state(PayloadState::Ready)
945 .map_err(|e| new_binder_exception(ExceptionCode::ILLEGAL_STATE, e.to_string()))?;
Inseob Kim14cb8692021-08-31 21:50:39 +0900946 vm.callbacks.notify_payload_ready(cid);
947 Ok(())
948 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +0900949 error!("notifyPayloadReady is called from an unknown CID {}", cid);
Inseob Kim14cb8692021-08-31 21:50:39 +0900950 Err(new_binder_exception(
951 ExceptionCode::SERVICE_SPECIFIC,
Jooyung Handd0a1732021-11-23 15:26:20 +0900952 format!("cannot find a VM with CID {}", cid),
Inseob Kim14cb8692021-08-31 21:50:39 +0900953 ))
954 }
955 }
956
Inseob Kimc7d28c72021-10-25 14:28:10 +0000957 fn notifyPayloadFinished(&self, exit_code: i32) -> binder::Result<()> {
958 let cid = self.cid;
Inseob Kim2444af92021-08-31 01:22:50 +0900959 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
960 info!("VM having CID {} finished payload", cid);
Andrew Walbran6b650662021-09-07 13:13:23 +0000961 vm.update_payload_state(PayloadState::Finished)
962 .map_err(|e| new_binder_exception(ExceptionCode::ILLEGAL_STATE, e.to_string()))?;
Inseob Kim2444af92021-08-31 01:22:50 +0900963 vm.callbacks.notify_payload_finished(cid, exit_code);
964 Ok(())
965 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +0900966 error!("notifyPayloadFinished is called from an unknown CID {}", cid);
Inseob Kim2444af92021-08-31 01:22:50 +0900967 Err(new_binder_exception(
968 ExceptionCode::SERVICE_SPECIFIC,
Jooyung Handd0a1732021-11-23 15:26:20 +0900969 format!("cannot find a VM with CID {}", cid),
970 ))
971 }
972 }
973
974 fn notifyError(&self, error_code: i32, message: &str) -> binder::Result<()> {
975 let cid = self.cid;
976 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
977 info!("VM having CID {} encountered an error", cid);
978 vm.update_payload_state(PayloadState::Finished)
979 .map_err(|e| new_binder_exception(ExceptionCode::ILLEGAL_STATE, e.to_string()))?;
980 vm.callbacks.notify_error(cid, error_code, message);
981 Ok(())
982 } else {
983 error!("notifyPayloadStarted is called from an unknown CID {}", cid);
984 Err(new_binder_exception(
985 ExceptionCode::SERVICE_SPECIFIC,
986 format!("cannot find a VM with CID {}", cid),
Inseob Kim2444af92021-08-31 01:22:50 +0900987 ))
988 }
989 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900990}
991
992impl VirtualMachineService {
Inseob Kimc7d28c72021-10-25 14:28:10 +0000993 // SAFETY: Service ownership is held by state, and the binder objects are threadsafe.
994 pub unsafe extern "C" fn factory(
995 cid: Cid,
996 context: *mut raw::c_void,
997 ) -> *mut binder_rpc_unstable_bindgen::AIBinder {
998 let state_ptr = context as *mut Arc<Mutex<State>>;
999 let state = state_ptr.as_ref().unwrap();
1000 if let Some(vm) = state.lock().unwrap().get_vm(cid) {
1001 let mut vm_service = vm.vm_service.lock().unwrap();
1002 let service = vm_service.get_or_insert_with(|| Self::new_binder(state.clone(), cid));
1003 service.as_binder().as_native_mut() as *mut binder_rpc_unstable_bindgen::AIBinder
1004 } else {
1005 error!("connection from cid={} is not from a guest VM", cid);
1006 null_mut()
1007 }
1008 }
1009
1010 fn new_binder(state: Arc<Mutex<State>>, cid: Cid) -> Strong<dyn IVirtualMachineService> {
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001011 BnVirtualMachineService::new_binder(
Inseob Kimc7d28c72021-10-25 14:28:10 +00001012 VirtualMachineService { state, cid },
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001013 BinderFeatures::default(),
1014 )
1015 }
1016}