blob: 5a7322bdfc907908c374d1ef08496baba781172e [file] [log] [blame]
Andrew Walbrand6dce6f2021-03-05 16:39:08 +00001// Copyright 2021, The Android Open Source Project
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
Andrew Walbranf6bf6862021-05-21 12:41:13 +000015//! Implementation of the AIDL interface of the VirtualizationService.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000016
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000017use crate::composite::make_composite_image;
Andrew Walbranf8d94112021-09-07 11:45:36 +000018use crate::crosvm::{CrosvmConfig, DiskFile, PayloadState, VmInstance, VmState};
Andrew Walbrancc0db522021-07-12 17:03:42 +000019use crate::payload::add_microdroid_images;
Jiyong Parkd50a0242021-09-16 21:00:14 +090020use crate::{Cid, FIRST_GUEST_CID, SYSPROP_LAST_CID};
Jiyong Park029977d2021-11-24 21:56:49 +090021use crate::selinux::{SeContext, getfilecon};
Alan Stokes0cc59ee2021-09-24 11:20:34 +010022use ::binder::unstable_api::AsNative;
Jiyong Park753553b2021-07-12 21:21:09 +090023use android_os_permissions_aidl::aidl::android::os::IPermissionController;
Jooyung Han21e9b922021-06-26 04:14:16 +090024use android_system_virtualizationservice::aidl::android::system::virtualizationservice::{
Andrew Walbranc92d35f2022-01-12 12:45:19 +000025 DeathReason::DeathReason,
Andrew Walbran6b650662021-09-07 13:13:23 +000026 DiskImage::DiskImage,
Alan Stokes0cc59ee2021-09-24 11:20:34 +010027 IVirtualMachine::{BnVirtualMachine, IVirtualMachine},
Andrew Walbran6b650662021-09-07 13:13:23 +000028 IVirtualMachineCallback::IVirtualMachineCallback,
29 IVirtualizationService::IVirtualizationService,
Jiyong Park029977d2021-11-24 21:56:49 +090030 Partition::Partition,
Andrew Walbran6b650662021-09-07 13:13:23 +000031 PartitionType::PartitionType,
Jiyong Parkc2a49cc2021-10-15 00:02:12 +090032 VirtualMachineAppConfig::DebugLevel::DebugLevel,
Jooyung Han21e9b922021-06-26 04:14:16 +090033 VirtualMachineAppConfig::VirtualMachineAppConfig,
34 VirtualMachineConfig::VirtualMachineConfig,
Andrew Walbran6b650662021-09-07 13:13:23 +000035 VirtualMachineDebugInfo::VirtualMachineDebugInfo,
Jooyung Han21e9b922021-06-26 04:14:16 +090036 VirtualMachineRawConfig::VirtualMachineRawConfig,
Andrew Walbran6b650662021-09-07 13:13:23 +000037 VirtualMachineState::VirtualMachineState,
Jooyung Han21e9b922021-06-26 04:14:16 +090038};
Andrew Walbranf6bf6862021-05-21 12:41:13 +000039use android_system_virtualizationservice::binder::{
Shikha Panward8e35422021-10-11 13:51:27 +000040 self, BinderFeatures, ExceptionCode, Interface, ParcelFileDescriptor, Status, StatusCode, Strong,
Alan Stokes0cc59ee2021-09-24 11:20:34 +010041 ThreadState,
Andrew Walbrana89fc132021-03-17 17:08:36 +000042};
Alan Stokes0cc59ee2021-09-24 11:20:34 +010043use android_system_virtualmachineservice::aidl::android::system::virtualmachineservice::{
44 IVirtualMachineService::{
45 BnVirtualMachineService, IVirtualMachineService, VM_BINDER_SERVICE_PORT,
46 VM_STREAM_SERVICE_PORT,
47 },
Inseob Kim1b95f2e2021-08-19 13:17:40 +090048};
Jiyong Parkd50a0242021-09-16 21:00:14 +090049use anyhow::{anyhow, bail, Context, Result};
Alan Stokes0cc59ee2021-09-24 11:20:34 +010050use binder_common::{lazy_service::LazyServiceGuard, new_binder_exception};
Andrew Walbrandfc953d2021-06-10 13:59:56 +000051use disk::QcowFile;
Alan Stokes0cc59ee2021-09-24 11:20:34 +010052use idsig::{HashAlgorithm, V4Signature};
Jiyong Parkd2dc83f2021-12-20 18:40:52 +090053use kvm::{Kvm, Cap};
Alan Stokes0cc59ee2021-09-24 11:20:34 +010054use log::{debug, error, info, warn};
Andrew Walbrancc0db522021-07-12 17:03:42 +000055use microdroid_payload_config::VmPayloadConfig;
Jiyong Parkd50a0242021-09-16 21:00:14 +090056use rustutils::system_properties;
Andrew Walbrandff3b942021-06-09 15:20:36 +000057use std::convert::TryInto;
Shikha Panward8e35422021-10-11 13:51:27 +000058use std::ffi::CStr;
Alan Stokes0cc59ee2021-09-24 11:20:34 +010059use std::fs::{create_dir, File, OpenOptions};
Jiyong Park9dd389e2021-08-23 20:42:59 +090060use std::io::{Error, ErrorKind, Write};
Andrew Walbranb15cd6e2021-07-05 16:38:07 +000061use std::num::NonZeroU32;
Inseob Kimc7d28c72021-10-25 14:28:10 +000062use std::os::raw;
Andrew Walbrand3a84182021-09-07 14:48:52 +000063use std::os::unix::io::{FromRawFd, IntoRawFd};
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000064use std::path::{Path, PathBuf};
Inseob Kimc7d28c72021-10-25 14:28:10 +000065use std::ptr::null_mut;
Andrew Walbran320b5602021-03-04 16:11:12 +000066use std::sync::{Arc, Mutex, Weak};
Andrew Walbrancc0db522021-07-12 17:03:42 +000067use vmconfig::VmConfig;
Inseob Kim7f61fe72021-08-20 20:50:47 +090068use vsock::{SockAddr, VsockListener, VsockStream};
Jooyung Han35edb8f2021-07-01 16:17:16 +090069use zip::ZipArchive;
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000070
Andrew Walbranf6bf6862021-05-21 12:41:13 +000071pub const BINDER_SERVICE_IDENTIFIER: &str = "android.system.virtualizationservice";
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000072
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000073/// Directory in which to write disk image files used while running VMs.
Andrew Walbran488bd072021-07-14 13:29:51 +000074pub const TEMPORARY_DIRECTORY: &str = "/data/misc/virtualizationservice";
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000075
Jiyong Park8611a6c2021-07-09 18:17:44 +090076/// The CID representing the host VM
77const VMADDR_CID_HOST: u32 = 2;
78
Jooyung Han95884632021-07-06 22:27:54 +090079/// The size of zero.img.
80/// Gaps in composite disk images are filled with a shared zero.img.
81const ZERO_FILLER_SIZE: u64 = 4096;
82
Jiyong Park9dd389e2021-08-23 20:42:59 +090083/// Magic string for the instance image
84const ANDROID_VM_INSTANCE_MAGIC: &str = "Android-VM-instance";
85
86/// Version of the instance image format
87const ANDROID_VM_INSTANCE_VERSION: u16 = 1;
88
Andrew Walbranf6bf6862021-05-21 12:41:13 +000089/// Implementation of `IVirtualizationService`, the entry point of the AIDL service.
Jooyung Han9900f3d2021-07-06 10:27:54 +090090#[derive(Debug, Default)]
Andrew Walbranf6bf6862021-05-21 12:41:13 +000091pub struct VirtualizationService {
Jiyong Park8611a6c2021-07-09 18:17:44 +090092 state: Arc<Mutex<State>>,
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000093}
94
Shikha Panward8e35422021-10-11 13:51:27 +000095impl Interface for VirtualizationService {
96 fn dump(&self, mut file: &File, _args: &[&CStr]) -> Result<(), StatusCode> {
97 check_permission("android.permission.DUMP").or(Err(StatusCode::PERMISSION_DENIED))?;
98 let state = &mut *self.state.lock().unwrap();
99 let vms = state.vms();
100 writeln!(file, "Running {0} VMs:", vms.len()).or(Err(StatusCode::UNKNOWN_ERROR))?;
101 for vm in vms {
102 writeln!(file, "VM CID: {}", vm.cid).or(Err(StatusCode::UNKNOWN_ERROR))?;
103 writeln!(file, "\tState: {:?}", vm.vm_state.lock().unwrap())
104 .or(Err(StatusCode::UNKNOWN_ERROR))?;
105 writeln!(file, "\tPayload state {:?}", vm.payload_state())
106 .or(Err(StatusCode::UNKNOWN_ERROR))?;
107 writeln!(file, "\tProtected: {}", vm.protected).or(Err(StatusCode::UNKNOWN_ERROR))?;
108 writeln!(file, "\ttemporary_directory: {}", vm.temporary_directory.to_string_lossy())
109 .or(Err(StatusCode::UNKNOWN_ERROR))?;
110 writeln!(file, "\trequester_uid: {}", vm.requester_uid)
111 .or(Err(StatusCode::UNKNOWN_ERROR))?;
112 writeln!(file, "\trequester_sid: {}", vm.requester_sid)
113 .or(Err(StatusCode::UNKNOWN_ERROR))?;
114 writeln!(file, "\trequester_debug_pid: {}", vm.requester_debug_pid)
115 .or(Err(StatusCode::UNKNOWN_ERROR))?;
116 }
117 Ok(())
118 }
119}
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000120
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000121impl IVirtualizationService for VirtualizationService {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000122 /// Creates (but does not start) a new VM with the given configuration, assigning it the next
123 /// available CID.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000124 ///
125 /// Returns a binder `IVirtualMachine` object referring to it, as a handle for the client.
Andrew Walbranf8d94112021-09-07 11:45:36 +0000126 fn createVm(
Andrew Walbrana89fc132021-03-17 17:08:36 +0000127 &self,
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000128 config: &VirtualMachineConfig,
Jiyong Parkb8182bb2021-10-26 22:53:08 +0900129 console_fd: Option<&ParcelFileDescriptor>,
Andrew Walbrana89fc132021-03-17 17:08:36 +0000130 log_fd: Option<&ParcelFileDescriptor>,
131 ) -> binder::Result<Strong<dyn IVirtualMachine>> {
Jiyong Park753553b2021-07-12 21:21:09 +0900132 check_manage_access()?;
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000133 let state = &mut *self.state.lock().unwrap();
Jiyong Parkb8182bb2021-10-26 22:53:08 +0900134 let mut console_fd = console_fd.map(clone_file).transpose()?;
Jiyong Parkc2a49cc2021-10-15 00:02:12 +0900135 let mut log_fd = log_fd.map(clone_file).transpose()?;
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000136 let requester_uid = ThreadState::get_calling_uid();
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000137 let requester_sid = get_calling_sid()?;
Andrew Walbran02034492021-04-13 15:05:07 +0000138 let requester_debug_pid = ThreadState::get_calling_pid();
Jiyong Parkd50a0242021-09-16 21:00:14 +0900139 let cid = next_cid().or(Err(ExceptionCode::ILLEGAL_STATE))?;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000140
141 // Counter to generate unique IDs for temporary image files.
142 let mut next_temporary_image_id = 0;
143 // Files which are referred to from composite images. These must be mapped to the crosvm
144 // child process, and not closed before it is started.
145 let mut indirect_files = vec![];
146
147 // Make directory for temporary files.
148 let temporary_directory: PathBuf = format!("{}/{}", TEMPORARY_DIRECTORY, cid).into();
149 create_dir(&temporary_directory).map_err(|e| {
150 error!(
Andrew Walbran806f1542021-06-10 14:07:12 +0000151 "Failed to create temporary directory {:?} for VM files: {}",
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000152 temporary_directory, e
153 );
Andrew Walbran806f1542021-06-10 14:07:12 +0000154 new_binder_exception(
155 ExceptionCode::SERVICE_SPECIFIC,
156 format!(
157 "Failed to create temporary directory {:?} for VM files: {}",
158 temporary_directory, e
159 ),
160 )
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000161 })?;
162
Jiyong Parkc2a49cc2021-10-15 00:02:12 +0900163 // Disable console logging if debug level != full. Note that kernel anyway doesn't use the
164 // console output when debug level != full. So, users won't be able to see the kernel
165 // output even without this overriding. This is to silence output from the bootloader which
166 // doesn't understand the bootconfig parameters.
167 if let VirtualMachineConfig::AppConfig(config) = config {
168 if config.debugLevel != DebugLevel::FULL {
Jiyong Parkb8182bb2021-10-26 22:53:08 +0900169 console_fd = None;
170 }
171 if config.debugLevel == DebugLevel::NONE {
Jiyong Parkc2a49cc2021-10-15 00:02:12 +0900172 log_fd = None;
173 }
174 }
175
Jiyong Park029977d2021-11-24 21:56:49 +0900176 let is_app_config = matches!(config, VirtualMachineConfig::AppConfig(_));
Jiyong Parkd2dc83f2021-12-20 18:40:52 +0900177 let is_debug_level_full = matches!(
178 config,
179 VirtualMachineConfig::AppConfig(VirtualMachineAppConfig {
180 debugLevel: DebugLevel::FULL,
181 ..
182 })
183 );
Jiyong Park029977d2021-11-24 21:56:49 +0900184
Jooyung Han21e9b922021-06-26 04:14:16 +0900185 let config = match config {
Jooyung Han35edb8f2021-07-01 16:17:16 +0900186 VirtualMachineConfig::AppConfig(config) => BorrowedOrOwned::Owned(
Jooyung Han9900f3d2021-07-06 10:27:54 +0900187 load_app_config(config, &temporary_directory).map_err(|e| {
188 error!("Failed to load app config from {}: {}", &config.configPath, e);
189 new_binder_exception(
190 ExceptionCode::SERVICE_SPECIFIC,
191 format!("Failed to load app config from {}: {}", &config.configPath, e),
192 )
193 })?,
Jooyung Han35edb8f2021-07-01 16:17:16 +0900194 ),
195 VirtualMachineConfig::RawConfig(config) => BorrowedOrOwned::Borrowed(config),
Jooyung Han21e9b922021-06-26 04:14:16 +0900196 };
Jooyung Han35edb8f2021-07-01 16:17:16 +0900197 let config = config.as_ref();
Jooyung Han21e9b922021-06-26 04:14:16 +0900198
Jiyong Park029977d2021-11-24 21:56:49 +0900199 // Check if partition images are labeled incorrectly. This is to prevent random images
200 // which are not protected by the Android Verified Boot (e.g. bits downloaded by apps) from
201 // being loaded in a pVM. Specifically, for images in the raw config, nothing is allowed
202 // to be labeled as app_data_file. For images in the app config, nothing but the instance
203 // partition is allowed to be labeled as such.
204 config
205 .disks
206 .iter()
207 .flat_map(|disk| disk.partitions.iter())
208 .filter(|partition| {
209 if is_app_config {
210 partition.label != "vm-instance"
211 } else {
212 true // all partitions are checked
213 }
214 })
215 .try_for_each(check_label_for_partition)
216 .map_err(|e| new_binder_exception(ExceptionCode::SERVICE_SPECIFIC, e.to_string()))?;
217
Jooyung Han95884632021-07-06 22:27:54 +0900218 let zero_filler_path = temporary_directory.join("zero.img");
Andrew Walbranfbb39d22021-07-28 17:01:25 +0000219 write_zero_filler(&zero_filler_path).map_err(|e| {
Jooyung Han95884632021-07-06 22:27:54 +0900220 error!("Failed to make composite image: {}", e);
221 new_binder_exception(
222 ExceptionCode::SERVICE_SPECIFIC,
223 format!("Failed to make composite image: {}", e),
224 )
225 })?;
Jooyung Han95884632021-07-06 22:27:54 +0900226
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000227 // Assemble disk images if needed.
228 let disks = config
229 .disks
230 .iter()
231 .map(|disk| {
232 assemble_disk_image(
233 disk,
Jooyung Han95884632021-07-06 22:27:54 +0900234 &zero_filler_path,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000235 &temporary_directory,
236 &mut next_temporary_image_id,
237 &mut indirect_files,
238 )
239 })
240 .collect::<Result<Vec<DiskFile>, _>>()?;
241
Jiyong Parkd2dc83f2021-12-20 18:40:52 +0900242 let protected_vm_supported = Kvm::new()
243 .map_err(|e| new_binder_exception(ExceptionCode::SERVICE_SPECIFIC, e.to_string()))?
244 .check_extension(Cap::ArmProtectedVm);
245 let protected = config.protectedVm && protected_vm_supported;
246 if config.protectedVm && !protected_vm_supported {
247 warn!("Protected VM was requested, but it isn't supported on this machine. Ignored.");
248 }
249
250 // And force run in non-protected mode when debug level is FULL
251 let protected = if is_debug_level_full {
252 if protected {
253 warn!("VM will run in FULL debug level. Running in non-protected mode");
254 }
255 false
256 } else {
257 protected
258 };
259
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000260 // Actually start the VM.
261 let crosvm_config = CrosvmConfig {
Andrew Walbran02034492021-04-13 15:05:07 +0000262 cid,
Andrew Walbrand3a84182021-09-07 14:48:52 +0000263 bootloader: maybe_clone_file(&config.bootloader)?,
264 kernel: maybe_clone_file(&config.kernel)?,
265 initrd: maybe_clone_file(&config.initrd)?,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000266 disks,
267 params: config.params.to_owned(),
Jiyong Parkd2dc83f2021-12-20 18:40:52 +0900268 protected,
Andrew Walbrancc045902021-07-27 16:06:17 +0000269 memory_mib: config.memoryMib.try_into().ok().and_then(NonZeroU32::new),
Jiyong Park032615f2022-01-10 13:55:34 +0900270 cpus: config.numCpus.try_into().ok().and_then(NonZeroU32::new),
271 cpu_affinity: config.cpuAffinity.clone(),
Jiyong Parkb8182bb2021-10-26 22:53:08 +0900272 console_fd,
Andrew Walbran02034492021-04-13 15:05:07 +0000273 log_fd,
Andrew Walbrand3a84182021-09-07 14:48:52 +0000274 indirect_files,
275 };
Andrew Walbranf8d94112021-09-07 11:45:36 +0000276 let instance = Arc::new(
277 VmInstance::new(
278 crosvm_config,
279 temporary_directory,
280 requester_uid,
281 requester_sid,
282 requester_debug_pid,
Andrew Walbran806f1542021-06-10 14:07:12 +0000283 )
Andrew Walbranf8d94112021-09-07 11:45:36 +0000284 .map_err(|e| {
285 error!("Failed to create VM with config {:?}: {}", config, e);
286 new_binder_exception(
287 ExceptionCode::SERVICE_SPECIFIC,
288 format!("Failed to create VM: {}", e),
289 )
290 })?,
291 );
Andrew Walbran320b5602021-03-04 16:11:12 +0000292 state.add_vm(Arc::downgrade(&instance));
293 Ok(VirtualMachine::create(instance))
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000294 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000295
Andrew Walbrandff3b942021-06-09 15:20:36 +0000296 /// Initialise an empty partition image of the given size to be used as a writable partition.
297 fn initializeWritablePartition(
298 &self,
299 image_fd: &ParcelFileDescriptor,
300 size: i64,
Jiyong Park9dd389e2021-08-23 20:42:59 +0900301 partition_type: PartitionType,
Andrew Walbrandff3b942021-06-09 15:20:36 +0000302 ) -> binder::Result<()> {
Jiyong Park753553b2021-07-12 21:21:09 +0900303 check_manage_access()?;
Andrew Walbrandfc953d2021-06-10 13:59:56 +0000304 let size = size.try_into().map_err(|e| {
Andrew Walbran806f1542021-06-10 14:07:12 +0000305 new_binder_exception(
306 ExceptionCode::ILLEGAL_ARGUMENT,
307 format!("Invalid size {}: {}", size, e),
308 )
Andrew Walbrandff3b942021-06-09 15:20:36 +0000309 })?;
Andrew Walbrandfc953d2021-06-10 13:59:56 +0000310 let image = clone_file(image_fd)?;
Jooyung Han1edd5b92021-10-28 10:58:05 +0900311 // initialize the file. Any data in the file will be erased.
312 image.set_len(0).map_err(|e| {
313 new_binder_exception(
314 ExceptionCode::SERVICE_SPECIFIC,
315 format!("Failed to reset a file: {}", e),
316 )
317 })?;
Jiyong Park9dd389e2021-08-23 20:42:59 +0900318 let mut part = QcowFile::new(image, size).map_err(|e| {
Andrew Walbran806f1542021-06-10 14:07:12 +0000319 new_binder_exception(
320 ExceptionCode::SERVICE_SPECIFIC,
321 format!("Failed to create QCOW2 image: {}", e),
322 )
Andrew Walbrandfc953d2021-06-10 13:59:56 +0000323 })?;
Andrew Walbrandff3b942021-06-09 15:20:36 +0000324
Jiyong Park9dd389e2021-08-23 20:42:59 +0900325 match partition_type {
326 PartitionType::RAW => Ok(()),
327 PartitionType::ANDROID_VM_INSTANCE => format_as_android_vm_instance(&mut part),
328 _ => Err(Error::new(
329 ErrorKind::Unsupported,
330 format!("Unsupported partition type {:?}", partition_type),
331 )),
332 }
333 .map_err(|e| {
334 new_binder_exception(
335 ExceptionCode::SERVICE_SPECIFIC,
336 format!("Failed to initialize partition as {:?}: {}", partition_type, e),
337 )
338 })?;
339
Andrew Walbrandff3b942021-06-09 15:20:36 +0000340 Ok(())
341 }
342
Jiyong Park0a248432021-08-20 23:32:39 +0900343 /// Creates or update the idsig file by digesting the input APK file.
344 fn createOrUpdateIdsigFile(
345 &self,
346 input_fd: &ParcelFileDescriptor,
347 idsig_fd: &ParcelFileDescriptor,
348 ) -> binder::Result<()> {
349 // TODO(b/193504400): do this only when (1) idsig_fd is empty or (2) the APK digest in
350 // idsig_fd is different from APK digest in input_fd
351
352 let mut input = clone_file(input_fd)?;
353 let mut sig = V4Signature::create(&mut input, 4096, &[], HashAlgorithm::SHA256).unwrap();
354
355 let mut output = clone_file(idsig_fd)?;
356 output.set_len(0).unwrap();
357 sig.write_into(&mut output).unwrap();
358 Ok(())
359 }
360
Andrew Walbran320b5602021-03-04 16:11:12 +0000361 /// Get a list of all currently running VMs. This method is only intended for debug purposes,
362 /// and as such is only permitted from the shell user.
363 fn debugListVms(&self) -> binder::Result<Vec<VirtualMachineDebugInfo>> {
Andrew Walbran806f1542021-06-10 14:07:12 +0000364 check_debug_access()?;
Andrew Walbran320b5602021-03-04 16:11:12 +0000365
366 let state = &mut *self.state.lock().unwrap();
367 let vms = state.vms();
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000368 let cids = vms
369 .into_iter()
370 .map(|vm| VirtualMachineDebugInfo {
371 cid: vm.cid as i32,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000372 temporaryDirectory: vm.temporary_directory.to_string_lossy().to_string(),
Andrew Walbran1ef19ae2021-04-07 11:31:57 +0000373 requesterUid: vm.requester_uid as i32,
374 requesterSid: vm.requester_sid.clone(),
Andrew Walbran02034492021-04-13 15:05:07 +0000375 requesterPid: vm.requester_debug_pid,
Andrew Walbran6b650662021-09-07 13:13:23 +0000376 state: get_state(&vm),
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000377 })
378 .collect();
Andrew Walbran320b5602021-03-04 16:11:12 +0000379 Ok(cids)
380 }
David Brazdil3c2ddef2021-03-18 13:09:57 +0000381
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000382 /// Hold a strong reference to a VM in VirtualizationService. This method is only intended for
383 /// debug purposes, and as such is only permitted from the shell user.
Andrei Homescu1415c132021-03-24 02:39:55 +0000384 fn debugHoldVmRef(&self, vmref: &Strong<dyn IVirtualMachine>) -> binder::Result<()> {
Andrew Walbran806f1542021-06-10 14:07:12 +0000385 check_debug_access()?;
David Brazdil3c2ddef2021-03-18 13:09:57 +0000386
David Brazdil3c2ddef2021-03-18 13:09:57 +0000387 let state = &mut *self.state.lock().unwrap();
Andrei Homescu1415c132021-03-24 02:39:55 +0000388 state.debug_hold_vm(vmref.clone());
David Brazdil3c2ddef2021-03-18 13:09:57 +0000389 Ok(())
390 }
391
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000392 /// Drop reference to a VM that is being held by VirtualizationService. Returns the reference if
393 /// the VM was found and None otherwise. This method is only intended for debug purposes, and as
394 /// such is only permitted from the shell user.
David Brazdil3c2ddef2021-03-18 13:09:57 +0000395 fn debugDropVmRef(&self, cid: i32) -> binder::Result<Option<Strong<dyn IVirtualMachine>>> {
Andrew Walbran806f1542021-06-10 14:07:12 +0000396 check_debug_access()?;
David Brazdil3c2ddef2021-03-18 13:09:57 +0000397
398 let state = &mut *self.state.lock().unwrap();
399 Ok(state.debug_drop_vm(cid))
400 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000401}
402
Jiyong Park8611a6c2021-07-09 18:17:44 +0900403impl VirtualizationService {
404 pub fn init() -> VirtualizationService {
405 let service = VirtualizationService::default();
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900406
407 // server for payload output
Jiyong Park8611a6c2021-07-09 18:17:44 +0900408 let state = service.state.clone(); // reference to state (not the state itself) is copied
409 std::thread::spawn(move || {
Inseob Kim7f61fe72021-08-20 20:50:47 +0900410 handle_stream_connection_from_vm(state).unwrap();
Jiyong Park8611a6c2021-07-09 18:17:44 +0900411 });
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900412
413 // binder server for vm
Inseob Kimc7d28c72021-10-25 14:28:10 +0000414 let mut state = service.state.clone(); // reference to state (not the state itself) is copied
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900415 std::thread::spawn(move || {
Inseob Kimc7d28c72021-10-25 14:28:10 +0000416 let state_ptr = &mut state as *mut _ as *mut raw::c_void;
417
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900418 debug!("virtual machine service is starting as an RPC service.");
Inseob Kimc7d28c72021-10-25 14:28:10 +0000419 // SAFETY: factory function is only ever called by RunRpcServerWithFactory, within the
420 // lifetime of the state, with context taking the pointer value above (so a properly
421 // aligned non-null pointer to an initialized instance).
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900422 let retval = unsafe {
Inseob Kimc7d28c72021-10-25 14:28:10 +0000423 binder_rpc_unstable_bindgen::RunRpcServerWithFactory(
424 Some(VirtualMachineService::factory),
425 state_ptr,
Inseob Kimd0587562021-09-01 21:27:32 +0900426 VM_BINDER_SERVICE_PORT as u32,
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900427 )
428 };
429 if retval {
430 debug!("RPC server has shut down gracefully");
431 } else {
432 bail!("Premature termination of RPC server");
433 }
434
435 Ok(retval)
436 });
Jiyong Park8611a6c2021-07-09 18:17:44 +0900437 service
438 }
439}
440
Andrew Walbran6b650662021-09-07 13:13:23 +0000441/// Waits for incoming connections from VM. If a new connection is made, stores the stream in the
442/// corresponding `VmInstance`.
Inseob Kim7f61fe72021-08-20 20:50:47 +0900443fn handle_stream_connection_from_vm(state: Arc<Mutex<State>>) -> Result<()> {
Inseob Kimd0587562021-09-01 21:27:32 +0900444 let listener =
445 VsockListener::bind_with_cid_port(VMADDR_CID_HOST, VM_STREAM_SERVICE_PORT as u32)?;
Jiyong Park8611a6c2021-07-09 18:17:44 +0900446 for stream in listener.incoming() {
447 let stream = match stream {
448 Err(e) => {
449 warn!("invalid incoming connection: {}", e);
450 continue;
451 }
452 Ok(s) => s,
453 };
454 if let Ok(SockAddr::Vsock(addr)) = stream.peer_addr() {
455 let cid = addr.cid();
456 let port = addr.port();
Inseob Kim7f61fe72021-08-20 20:50:47 +0900457 info!("payload stream connected from cid={}, port={}", cid, port);
Jiyong Park8611a6c2021-07-09 18:17:44 +0900458 if let Some(vm) = state.lock().unwrap().get_vm(cid) {
Chris Wailes8bbb8932021-09-10 14:14:19 -0700459 *vm.stream.lock().unwrap() = Some(stream);
Inseob Kim7f61fe72021-08-20 20:50:47 +0900460 } else {
461 error!("connection from cid={} is not from a guest VM", cid);
Jiyong Park8611a6c2021-07-09 18:17:44 +0900462 }
463 }
464 }
465 Ok(())
466}
467
Andrew Walbranfbb39d22021-07-28 17:01:25 +0000468fn write_zero_filler(zero_filler_path: &Path) -> Result<()> {
Jooyung Han95884632021-07-06 22:27:54 +0900469 let file = OpenOptions::new()
470 .create_new(true)
471 .read(true)
472 .write(true)
473 .open(zero_filler_path)
474 .with_context(|| "Failed to create zero.img")?;
475 file.set_len(ZERO_FILLER_SIZE)?;
Andrew Walbranfbb39d22021-07-28 17:01:25 +0000476 Ok(())
Jooyung Han95884632021-07-06 22:27:54 +0900477}
478
Jiyong Park9dd389e2021-08-23 20:42:59 +0900479fn format_as_android_vm_instance(part: &mut dyn Write) -> std::io::Result<()> {
480 part.write_all(ANDROID_VM_INSTANCE_MAGIC.as_bytes())?;
481 part.write_all(&ANDROID_VM_INSTANCE_VERSION.to_le_bytes())?;
482 part.flush()
483}
484
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000485/// Given the configuration for a disk image, assembles the `DiskFile` to pass to crosvm.
486///
487/// This may involve assembling a composite disk from a set of partition images.
488fn assemble_disk_image(
489 disk: &DiskImage,
Jooyung Han95884632021-07-06 22:27:54 +0900490 zero_filler_path: &Path,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000491 temporary_directory: &Path,
492 next_temporary_image_id: &mut u64,
493 indirect_files: &mut Vec<File>,
Andrew Walbran806f1542021-06-10 14:07:12 +0000494) -> Result<DiskFile, Status> {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000495 let image = if !disk.partitions.is_empty() {
496 if disk.image.is_some() {
497 warn!("DiskImage {:?} contains both image and partitions.", disk);
Andrew Walbran806f1542021-06-10 14:07:12 +0000498 return Err(new_binder_exception(
499 ExceptionCode::ILLEGAL_ARGUMENT,
500 "DiskImage contains both image and partitions.",
501 ));
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000502 }
503
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000504 let composite_image_filenames =
505 make_composite_image_filenames(temporary_directory, next_temporary_image_id);
506 let (image, partition_files) = make_composite_image(
507 &disk.partitions,
Jooyung Han95884632021-07-06 22:27:54 +0900508 zero_filler_path,
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000509 &composite_image_filenames.composite,
510 &composite_image_filenames.header,
511 &composite_image_filenames.footer,
512 )
513 .map_err(|e| {
514 error!("Failed to make composite image with config {:?}: {}", disk, e);
515 new_binder_exception(
516 ExceptionCode::SERVICE_SPECIFIC,
517 format!("Failed to make composite image: {}", e),
518 )
519 })?;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000520
521 // Pass the file descriptors for the various partition files to crosvm when it
522 // is run.
523 indirect_files.extend(partition_files);
524
525 image
526 } else if let Some(image) = &disk.image {
527 clone_file(image)?
528 } else {
529 warn!("DiskImage {:?} didn't contain image or partitions.", disk);
Andrew Walbran806f1542021-06-10 14:07:12 +0000530 return Err(new_binder_exception(
531 ExceptionCode::ILLEGAL_ARGUMENT,
532 "DiskImage didn't contain image or partitions.",
533 ));
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000534 };
535
536 Ok(DiskFile { image, writable: disk.writable })
537}
538
Jooyung Han21e9b922021-06-26 04:14:16 +0900539fn load_app_config(
540 config: &VirtualMachineAppConfig,
541 temporary_directory: &Path,
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900542) -> Result<VirtualMachineRawConfig> {
Andrew Walbrancc0db522021-07-12 17:03:42 +0000543 let apk_file = clone_file(config.apk.as_ref().unwrap())?;
544 let idsig_file = clone_file(config.idsig.as_ref().unwrap())?;
Jiyong Park8d081812021-07-23 17:45:04 +0900545 let instance_file = clone_file(config.instanceImage.as_ref().unwrap())?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900546 let config_path = &config.configPath;
547
Andrew Walbrancc0db522021-07-12 17:03:42 +0000548 let mut apk_zip = ZipArchive::new(&apk_file)?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900549 let config_file = apk_zip.by_name(config_path)?;
550 let vm_payload_config: VmPayloadConfig = serde_json::from_reader(config_file)?;
551
552 let os_name = &vm_payload_config.os.name;
Andrew Walbrancc0db522021-07-12 17:03:42 +0000553
Jooyung Han35edb8f2021-07-01 16:17:16 +0900554 // For now, the only supported "os" value is "microdroid"
555 if os_name != "microdroid" {
Andrew Walbrancc0db522021-07-12 17:03:42 +0000556 bail!("Unknown OS \"{}\"", os_name);
Jooyung Han35edb8f2021-07-01 16:17:16 +0900557 }
Andrew Walbrancc0db522021-07-12 17:03:42 +0000558
559 // It is safe to construct a filename based on the os_name because we've already checked that it
560 // is one of the allowed values.
Jooyung Han21e9b922021-06-26 04:14:16 +0900561 let vm_config_path = PathBuf::from(format!("/apex/com.android.virt/etc/{}.json", os_name));
562 let vm_config_file = File::open(vm_config_path)?;
Andrew Walbrancc0db522021-07-12 17:03:42 +0000563 let mut vm_config = VmConfig::load(&vm_config_file)?.to_parcelable()?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900564
Andrew Walbrancc045902021-07-27 16:06:17 +0000565 if config.memoryMib > 0 {
566 vm_config.memoryMib = config.memoryMib;
Andrew Walbran45bcb0c2021-07-14 15:02:06 +0000567 }
568
Jiyong Park032615f2022-01-10 13:55:34 +0900569 vm_config.numCpus = config.numCpus;
570 vm_config.cpuAffinity = config.cpuAffinity.clone();
571
Andrew Walbrancc0db522021-07-12 17:03:42 +0000572 // Microdroid requires an additional payload disk image and the bootconfig partition.
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900573 if os_name == "microdroid" {
Andrew Walbrancc0db522021-07-12 17:03:42 +0000574 add_microdroid_images(
575 config,
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900576 temporary_directory,
Andrew Walbrancc0db522021-07-12 17:03:42 +0000577 apk_file,
578 idsig_file,
Jiyong Park8d081812021-07-23 17:45:04 +0900579 instance_file,
Jooyung Han5dc42172021-10-05 16:43:47 +0900580 &vm_payload_config,
Andrew Walbrancc0db522021-07-12 17:03:42 +0000581 &mut vm_config,
582 )?;
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900583 }
Jooyung Han21e9b922021-06-26 04:14:16 +0900584
Andrew Walbrancc0db522021-07-12 17:03:42 +0000585 Ok(vm_config)
Jooyung Han21e9b922021-06-26 04:14:16 +0900586}
587
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000588/// Generates a unique filename to use for a composite disk image.
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000589fn make_composite_image_filenames(
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000590 temporary_directory: &Path,
591 next_temporary_image_id: &mut u64,
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000592) -> CompositeImageFilenames {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000593 let id = *next_temporary_image_id;
594 *next_temporary_image_id += 1;
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000595 CompositeImageFilenames {
596 composite: temporary_directory.join(format!("composite-{}.img", id)),
597 header: temporary_directory.join(format!("composite-{}-header.img", id)),
598 footer: temporary_directory.join(format!("composite-{}-footer.img", id)),
599 }
600}
601
602/// Filenames for a composite disk image, including header and footer partitions.
603#[derive(Clone, Debug, Eq, PartialEq)]
604struct CompositeImageFilenames {
605 /// The composite disk image itself.
606 composite: PathBuf,
607 /// The header partition image.
608 header: PathBuf,
609 /// The footer partition image.
610 footer: PathBuf,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000611}
612
613/// Gets the calling SID of the current Binder thread.
Andrew Walbran806f1542021-06-10 14:07:12 +0000614fn get_calling_sid() -> Result<String, Status> {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000615 ThreadState::with_calling_sid(|sid| {
616 if let Some(sid) = sid {
617 match sid.to_str() {
618 Ok(sid) => Ok(sid.to_owned()),
619 Err(e) => {
Andrew Walbran806f1542021-06-10 14:07:12 +0000620 error!("SID was not valid UTF-8: {}", e);
621 Err(new_binder_exception(
622 ExceptionCode::ILLEGAL_ARGUMENT,
623 format!("SID was not valid UTF-8: {}", e),
624 ))
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000625 }
626 }
627 } else {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000628 error!("Missing SID on createVm");
629 Err(new_binder_exception(ExceptionCode::SECURITY, "Missing SID on createVm"))
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000630 }
631 })
632}
633
Jiyong Park753553b2021-07-12 21:21:09 +0900634/// Checks whether the caller has a specific permission
635fn check_permission(perm: &str) -> binder::Result<()> {
636 let calling_pid = ThreadState::get_calling_pid();
637 let calling_uid = ThreadState::get_calling_uid();
638 // Root can do anything
639 if calling_uid == 0 {
640 return Ok(());
641 }
642 let perm_svc: Strong<dyn IPermissionController::IPermissionController> =
643 binder::get_interface("permission")?;
644 if perm_svc.checkPermission(perm, calling_pid, calling_uid as i32)? {
Andrew Walbran806f1542021-06-10 14:07:12 +0000645 Ok(())
646 } else {
Jiyong Park753553b2021-07-12 21:21:09 +0900647 Err(new_binder_exception(
648 ExceptionCode::SECURITY,
649 format!("does not have the {} permission", perm),
650 ))
Andrew Walbran806f1542021-06-10 14:07:12 +0000651 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000652}
653
Jiyong Park753553b2021-07-12 21:21:09 +0900654/// Check whether the caller of the current Binder method is allowed to call debug methods.
655fn check_debug_access() -> binder::Result<()> {
656 check_permission("android.permission.DEBUG_VIRTUAL_MACHINE")
657}
658
659/// Check whether the caller of the current Binder method is allowed to manage VMs
660fn check_manage_access() -> binder::Result<()> {
661 check_permission("android.permission.MANAGE_VIRTUAL_MACHINE")
662}
663
Jiyong Park029977d2021-11-24 21:56:49 +0900664/// Check if a partition has selinux labels that are not allowed
665fn check_label_for_partition(partition: &Partition) -> Result<()> {
666 let ctx = getfilecon(partition.image.as_ref().unwrap().as_ref())?;
667 if ctx == SeContext::new("u:object_r:app_data_file:s0").unwrap() {
668 Err(anyhow!("Partition {} shouldn't be labeled as {}", &partition.label, ctx))
669 } else {
670 Ok(())
671 }
672}
673
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000674/// Implementation of the AIDL `IVirtualMachine` interface. Used as a handle to a VM.
675#[derive(Debug)]
676struct VirtualMachine {
677 instance: Arc<VmInstance>,
Alan Stokes0cc59ee2021-09-24 11:20:34 +0100678 /// Keeps our service process running as long as this VM instance exists.
Chris Wailes641fc4a2021-12-01 15:03:21 -0800679 #[allow(dead_code)]
Alan Stokes0cc59ee2021-09-24 11:20:34 +0100680 lazy_service_guard: LazyServiceGuard,
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000681}
682
683impl VirtualMachine {
684 fn create(instance: Arc<VmInstance>) -> Strong<dyn IVirtualMachine> {
Alan Stokes0cc59ee2021-09-24 11:20:34 +0100685 let binder = VirtualMachine { instance, lazy_service_guard: Default::default() };
Andrew Walbran4de28782021-04-13 14:51:43 +0000686 BnVirtualMachine::new_binder(binder, BinderFeatures::default())
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000687 }
688}
689
690impl Interface for VirtualMachine {}
691
692impl IVirtualMachine for VirtualMachine {
693 fn getCid(&self) -> binder::Result<i32> {
Jiyong Park753553b2021-07-12 21:21:09 +0900694 // Don't check permission. The owner of the VM might have passed this binder object to
695 // others.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000696 Ok(self.instance.cid as i32)
697 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000698
Andrew Walbran6b650662021-09-07 13:13:23 +0000699 fn getState(&self) -> binder::Result<VirtualMachineState> {
Jiyong Park753553b2021-07-12 21:21:09 +0900700 // Don't check permission. The owner of the VM might have passed this binder object to
701 // others.
Andrew Walbran6b650662021-09-07 13:13:23 +0000702 Ok(get_state(&self.instance))
Andrew Walbrandae07162021-03-12 17:05:20 +0000703 }
704
705 fn registerCallback(
706 &self,
707 callback: &Strong<dyn IVirtualMachineCallback>,
708 ) -> binder::Result<()> {
Jiyong Park753553b2021-07-12 21:21:09 +0900709 // Don't check permission. The owner of the VM might have passed this binder object to
710 // others.
711 //
Andrew Walbrandae07162021-03-12 17:05:20 +0000712 // TODO: Should this give an error if the VM is already dead?
713 self.instance.callbacks.add(callback.clone());
714 Ok(())
715 }
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000716
Andrew Walbranf8d94112021-09-07 11:45:36 +0000717 fn start(&self) -> binder::Result<()> {
718 self.instance.start().map_err(|e| {
719 error!("Error starting VM with CID {}: {:?}", self.instance.cid, e);
720 new_binder_exception(ExceptionCode::SERVICE_SPECIFIC, e.to_string())
721 })
722 }
723
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000724 fn connectVsock(&self, port: i32) -> binder::Result<ParcelFileDescriptor> {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000725 if !matches!(&*self.instance.vm_state.lock().unwrap(), VmState::Running { .. }) {
726 return Err(new_binder_exception(ExceptionCode::SERVICE_SPECIFIC, "VM is not running"));
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000727 }
728 let stream =
729 VsockStream::connect_with_cid_port(self.instance.cid, port as u32).map_err(|e| {
730 new_binder_exception(
731 ExceptionCode::SERVICE_SPECIFIC,
732 format!("Failed to connect: {}", e),
733 )
734 })?;
735 Ok(vsock_stream_to_pfd(stream))
736 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000737}
738
739impl Drop for VirtualMachine {
740 fn drop(&mut self) {
741 debug!("Dropping {:?}", self);
742 self.instance.kill();
743 }
744}
745
746/// A set of Binders to be called back in response to various events on the VM, such as when it
747/// dies.
748#[derive(Debug, Default)]
749pub struct VirtualMachineCallbacks(Mutex<Vec<Strong<dyn IVirtualMachineCallback>>>);
750
751impl VirtualMachineCallbacks {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900752 /// Call all registered callbacks to notify that the payload has started.
Inseob Kim7f61fe72021-08-20 20:50:47 +0900753 pub fn notify_payload_started(&self, cid: Cid, stream: Option<VsockStream>) {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900754 let callbacks = &*self.0.lock().unwrap();
Inseob Kim7f61fe72021-08-20 20:50:47 +0900755 let pfd = stream.map(vsock_stream_to_pfd);
Jiyong Park8611a6c2021-07-09 18:17:44 +0900756 for callback in callbacks {
Inseob Kim7f61fe72021-08-20 20:50:47 +0900757 if let Err(e) = callback.onPayloadStarted(cid as i32, pfd.as_ref()) {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900758 error!("Error notifying payload start event from VM CID {}: {}", cid, e);
759 }
760 }
761 }
762
Inseob Kim14cb8692021-08-31 21:50:39 +0900763 /// Call all registered callbacks to notify that the payload is ready to serve.
764 pub fn notify_payload_ready(&self, cid: Cid) {
765 let callbacks = &*self.0.lock().unwrap();
766 for callback in callbacks {
767 if let Err(e) = callback.onPayloadReady(cid as i32) {
768 error!("Error notifying payload ready event from VM CID {}: {}", cid, e);
769 }
770 }
771 }
772
Inseob Kim2444af92021-08-31 01:22:50 +0900773 /// Call all registered callbacks to notify that the payload has finished.
774 pub fn notify_payload_finished(&self, cid: Cid, exit_code: i32) {
775 let callbacks = &*self.0.lock().unwrap();
776 for callback in callbacks {
777 if let Err(e) = callback.onPayloadFinished(cid as i32, exit_code) {
778 error!("Error notifying payload finish event from VM CID {}: {}", cid, e);
779 }
780 }
781 }
782
Jooyung Handd0a1732021-11-23 15:26:20 +0900783 /// Call all registered callbacks to say that the VM encountered an error.
784 pub fn notify_error(&self, cid: Cid, error_code: i32, message: &str) {
785 let callbacks = &*self.0.lock().unwrap();
786 for callback in callbacks {
787 if let Err(e) = callback.onError(cid as i32, error_code, message) {
788 error!("Error notifying error event from VM CID {}: {}", cid, e);
789 }
790 }
791 }
792
Andrew Walbrandae07162021-03-12 17:05:20 +0000793 /// Call all registered callbacks to say that the VM has died.
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000794 pub fn callback_on_died(&self, cid: Cid, reason: DeathReason) {
Andrew Walbrandae07162021-03-12 17:05:20 +0000795 let callbacks = &*self.0.lock().unwrap();
796 for callback in callbacks {
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000797 if let Err(e) = callback.onDied(cid as i32, reason) {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900798 error!("Error notifying exit of VM CID {}: {}", cid, e);
Andrew Walbrandae07162021-03-12 17:05:20 +0000799 }
800 }
801 }
802
803 /// Add a new callback to the set.
804 fn add(&self, callback: Strong<dyn IVirtualMachineCallback>) {
805 self.0.lock().unwrap().push(callback);
806 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000807}
808
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000809/// The mutable state of the VirtualizationService. There should only be one instance of this
810/// struct.
Chris Wailes641fc4a2021-12-01 15:03:21 -0800811#[derive(Debug, Default)]
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000812struct State {
Andrew Walbran320b5602021-03-04 16:11:12 +0000813 /// The VMs which have been started. When VMs are started a weak reference is added to this list
814 /// while a strong reference is returned to the caller over Binder. Once all copies of the
815 /// Binder client are dropped the weak reference here will become invalid, and will be removed
816 /// from the list opportunistically the next time `add_vm` is called.
817 vms: Vec<Weak<VmInstance>>,
David Brazdil3c2ddef2021-03-18 13:09:57 +0000818
819 /// Vector of strong VM references held on behalf of users that cannot hold them themselves.
820 /// This is only used for debugging purposes.
821 debug_held_vms: Vec<Strong<dyn IVirtualMachine>>,
Andrew Walbran320b5602021-03-04 16:11:12 +0000822}
823
824impl State {
Andrew Walbrandae07162021-03-12 17:05:20 +0000825 /// Get a list of VMs which still have Binder references to them.
Andrew Walbran320b5602021-03-04 16:11:12 +0000826 fn vms(&self) -> Vec<Arc<VmInstance>> {
827 // Attempt to upgrade the weak pointers to strong pointers.
828 self.vms.iter().filter_map(Weak::upgrade).collect()
829 }
830
831 /// Add a new VM to the list.
832 fn add_vm(&mut self, vm: Weak<VmInstance>) {
833 // Garbage collect any entries from the stored list which no longer exist.
834 self.vms.retain(|vm| vm.strong_count() > 0);
835
836 // Actually add the new VM.
837 self.vms.push(vm);
838 }
David Brazdil3c2ddef2021-03-18 13:09:57 +0000839
Jiyong Park8611a6c2021-07-09 18:17:44 +0900840 /// Get a VM that corresponds to the given cid
841 fn get_vm(&self, cid: Cid) -> Option<Arc<VmInstance>> {
842 self.vms().into_iter().find(|vm| vm.cid == cid)
843 }
844
David Brazdil3c2ddef2021-03-18 13:09:57 +0000845 /// Store a strong VM reference.
846 fn debug_hold_vm(&mut self, vm: Strong<dyn IVirtualMachine>) {
847 self.debug_held_vms.push(vm);
848 }
849
850 /// Retrieve and remove a strong VM reference.
851 fn debug_drop_vm(&mut self, cid: i32) -> Option<Strong<dyn IVirtualMachine>> {
852 let pos = self.debug_held_vms.iter().position(|vm| vm.getCid() == Ok(cid))?;
Alan Stokes7e54e292021-09-09 11:37:56 +0100853 let vm = self.debug_held_vms.swap_remove(pos);
Alan Stokes7e54e292021-09-09 11:37:56 +0100854 Some(vm)
David Brazdil3c2ddef2021-03-18 13:09:57 +0000855 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000856}
857
Jiyong Parkd50a0242021-09-16 21:00:14 +0900858/// Get the next available CID, or an error if we have run out. The last CID used is stored in
859/// a system property so that restart of virtualizationservice doesn't reuse CID while the host
860/// Android is up.
861fn next_cid() -> Result<Cid> {
862 let next = if let Ok(val) = system_properties::read(SYSPROP_LAST_CID) {
863 if let Ok(num) = val.parse::<u32>() {
864 num.checked_add(1).ok_or_else(|| anyhow!("run out of CID"))?
865 } else {
866 error!("Invalid last CID {}. Using {}", &val, FIRST_GUEST_CID);
867 FIRST_GUEST_CID
868 }
869 } else {
870 // First VM since the boot
871 FIRST_GUEST_CID
872 };
873 // Persist the last value for next use
874 let str_val = format!("{}", next);
875 system_properties::write(SYSPROP_LAST_CID, &str_val)?;
876 Ok(next)
877}
878
Andrew Walbran6b650662021-09-07 13:13:23 +0000879/// Gets the `VirtualMachineState` of the given `VmInstance`.
880fn get_state(instance: &VmInstance) -> VirtualMachineState {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000881 match &*instance.vm_state.lock().unwrap() {
882 VmState::NotStarted { .. } => VirtualMachineState::NOT_STARTED,
883 VmState::Running { .. } => match instance.payload_state() {
Andrew Walbran6b650662021-09-07 13:13:23 +0000884 PayloadState::Starting => VirtualMachineState::STARTING,
885 PayloadState::Started => VirtualMachineState::STARTED,
886 PayloadState::Ready => VirtualMachineState::READY,
887 PayloadState::Finished => VirtualMachineState::FINISHED,
Andrew Walbranf8d94112021-09-07 11:45:36 +0000888 },
889 VmState::Dead => VirtualMachineState::DEAD,
890 VmState::Failed => VirtualMachineState::DEAD,
Andrew Walbran6b650662021-09-07 13:13:23 +0000891 }
892}
893
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000894/// Converts a `&ParcelFileDescriptor` to a `File` by cloning the file.
Andrew Walbran806f1542021-06-10 14:07:12 +0000895fn clone_file(file: &ParcelFileDescriptor) -> Result<File, Status> {
896 file.as_ref().try_clone().map_err(|e| {
897 new_binder_exception(
898 ExceptionCode::BAD_PARCELABLE,
899 format!("Failed to clone File from ParcelFileDescriptor: {}", e),
900 )
901 })
902}
903
Andrew Walbrand3a84182021-09-07 14:48:52 +0000904/// Converts an `&Option<ParcelFileDescriptor>` to an `Option<File>` by cloning the file.
905fn maybe_clone_file(file: &Option<ParcelFileDescriptor>) -> Result<Option<File>, Status> {
906 file.as_ref().map(clone_file).transpose()
907}
908
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000909/// Converts a `VsockStream` to a `ParcelFileDescriptor`.
910fn vsock_stream_to_pfd(stream: VsockStream) -> ParcelFileDescriptor {
911 // SAFETY: ownership is transferred from stream to f
912 let f = unsafe { File::from_raw_fd(stream.into_raw_fd()) };
913 ParcelFileDescriptor::new(f)
914}
915
Jooyung Han35edb8f2021-07-01 16:17:16 +0900916/// Simple utility for referencing Borrowed or Owned. Similar to std::borrow::Cow, but
917/// it doesn't require that T implements Clone.
918enum BorrowedOrOwned<'a, T> {
919 Borrowed(&'a T),
920 Owned(T),
921}
922
923impl<'a, T> AsRef<T> for BorrowedOrOwned<'a, T> {
924 fn as_ref(&self) -> &T {
925 match self {
926 Self::Borrowed(b) => b,
Chris Wailes68c39f82021-07-27 16:03:44 -0700927 Self::Owned(o) => o,
Jooyung Han35edb8f2021-07-01 16:17:16 +0900928 }
929 }
930}
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900931
932/// Implementation of `IVirtualMachineService`, the entry point of the AIDL service.
933#[derive(Debug, Default)]
934struct VirtualMachineService {
935 state: Arc<Mutex<State>>,
Inseob Kimc7d28c72021-10-25 14:28:10 +0000936 cid: Cid,
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900937}
938
939impl Interface for VirtualMachineService {}
940
941impl IVirtualMachineService for VirtualMachineService {
Inseob Kimc7d28c72021-10-25 14:28:10 +0000942 fn notifyPayloadStarted(&self) -> binder::Result<()> {
943 let cid = self.cid;
Inseob Kim7f61fe72021-08-20 20:50:47 +0900944 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
945 info!("VM having CID {} started payload", cid);
Andrew Walbran6b650662021-09-07 13:13:23 +0000946 vm.update_payload_state(PayloadState::Started)
947 .map_err(|e| new_binder_exception(ExceptionCode::ILLEGAL_STATE, e.to_string()))?;
Inseob Kim7f61fe72021-08-20 20:50:47 +0900948 let stream = vm.stream.lock().unwrap().take();
949 vm.callbacks.notify_payload_started(cid, stream);
950 Ok(())
951 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +0900952 error!("notifyPayloadStarted is called from an unknown CID {}", cid);
Inseob Kim7f61fe72021-08-20 20:50:47 +0900953 Err(new_binder_exception(
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900954 ExceptionCode::SERVICE_SPECIFIC,
Jooyung Handd0a1732021-11-23 15:26:20 +0900955 format!("cannot find a VM with CID {}", cid),
Inseob Kim7f61fe72021-08-20 20:50:47 +0900956 ))
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900957 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900958 }
Inseob Kim2444af92021-08-31 01:22:50 +0900959
Inseob Kimc7d28c72021-10-25 14:28:10 +0000960 fn notifyPayloadReady(&self) -> binder::Result<()> {
961 let cid = self.cid;
Inseob Kim14cb8692021-08-31 21:50:39 +0900962 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
963 info!("VM having CID {} payload is ready", cid);
Andrew Walbran6b650662021-09-07 13:13:23 +0000964 vm.update_payload_state(PayloadState::Ready)
965 .map_err(|e| new_binder_exception(ExceptionCode::ILLEGAL_STATE, e.to_string()))?;
Inseob Kim14cb8692021-08-31 21:50:39 +0900966 vm.callbacks.notify_payload_ready(cid);
967 Ok(())
968 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +0900969 error!("notifyPayloadReady is called from an unknown CID {}", cid);
Inseob Kim14cb8692021-08-31 21:50:39 +0900970 Err(new_binder_exception(
971 ExceptionCode::SERVICE_SPECIFIC,
Jooyung Handd0a1732021-11-23 15:26:20 +0900972 format!("cannot find a VM with CID {}", cid),
Inseob Kim14cb8692021-08-31 21:50:39 +0900973 ))
974 }
975 }
976
Inseob Kimc7d28c72021-10-25 14:28:10 +0000977 fn notifyPayloadFinished(&self, exit_code: i32) -> binder::Result<()> {
978 let cid = self.cid;
Inseob Kim2444af92021-08-31 01:22:50 +0900979 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
980 info!("VM having CID {} finished payload", cid);
Andrew Walbran6b650662021-09-07 13:13:23 +0000981 vm.update_payload_state(PayloadState::Finished)
982 .map_err(|e| new_binder_exception(ExceptionCode::ILLEGAL_STATE, e.to_string()))?;
Inseob Kim2444af92021-08-31 01:22:50 +0900983 vm.callbacks.notify_payload_finished(cid, exit_code);
984 Ok(())
985 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +0900986 error!("notifyPayloadFinished is called from an unknown CID {}", cid);
Inseob Kim2444af92021-08-31 01:22:50 +0900987 Err(new_binder_exception(
988 ExceptionCode::SERVICE_SPECIFIC,
Jooyung Handd0a1732021-11-23 15:26:20 +0900989 format!("cannot find a VM with CID {}", cid),
990 ))
991 }
992 }
993
994 fn notifyError(&self, error_code: i32, message: &str) -> binder::Result<()> {
995 let cid = self.cid;
996 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
997 info!("VM having CID {} encountered an error", cid);
998 vm.update_payload_state(PayloadState::Finished)
999 .map_err(|e| new_binder_exception(ExceptionCode::ILLEGAL_STATE, e.to_string()))?;
1000 vm.callbacks.notify_error(cid, error_code, message);
1001 Ok(())
1002 } else {
1003 error!("notifyPayloadStarted is called from an unknown CID {}", cid);
1004 Err(new_binder_exception(
1005 ExceptionCode::SERVICE_SPECIFIC,
1006 format!("cannot find a VM with CID {}", cid),
Inseob Kim2444af92021-08-31 01:22:50 +09001007 ))
1008 }
1009 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001010}
1011
1012impl VirtualMachineService {
Inseob Kimc7d28c72021-10-25 14:28:10 +00001013 // SAFETY: Service ownership is held by state, and the binder objects are threadsafe.
1014 pub unsafe extern "C" fn factory(
1015 cid: Cid,
1016 context: *mut raw::c_void,
1017 ) -> *mut binder_rpc_unstable_bindgen::AIBinder {
1018 let state_ptr = context as *mut Arc<Mutex<State>>;
1019 let state = state_ptr.as_ref().unwrap();
1020 if let Some(vm) = state.lock().unwrap().get_vm(cid) {
1021 let mut vm_service = vm.vm_service.lock().unwrap();
1022 let service = vm_service.get_or_insert_with(|| Self::new_binder(state.clone(), cid));
1023 service.as_binder().as_native_mut() as *mut binder_rpc_unstable_bindgen::AIBinder
1024 } else {
1025 error!("connection from cid={} is not from a guest VM", cid);
1026 null_mut()
1027 }
1028 }
1029
1030 fn new_binder(state: Arc<Mutex<State>>, cid: Cid) -> Strong<dyn IVirtualMachineService> {
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001031 BnVirtualMachineService::new_binder(
Inseob Kimc7d28c72021-10-25 14:28:10 +00001032 VirtualMachineService { state, cid },
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001033 BinderFeatures::default(),
1034 )
1035 }
1036}