blob: 42eb1e648b913c74b38013da13c2e9b75c861604 [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;
Treehugger Robot3ffa8322021-11-22 12:06:47 +000057use statslog_virtualization_rust::vm_creation_requested::{stats_write, Hypervisor};
Andrew Walbrandff3b942021-06-09 15:20:36 +000058use std::convert::TryInto;
Shikha Panward8e35422021-10-11 13:51:27 +000059use std::ffi::CStr;
Alan Stokes0cc59ee2021-09-24 11:20:34 +010060use std::fs::{create_dir, File, OpenOptions};
Jiyong Park9dd389e2021-08-23 20:42:59 +090061use std::io::{Error, ErrorKind, Write};
Andrew Walbranb15cd6e2021-07-05 16:38:07 +000062use std::num::NonZeroU32;
Inseob Kimc7d28c72021-10-25 14:28:10 +000063use std::os::raw;
Andrew Walbrand3a84182021-09-07 14:48:52 +000064use std::os::unix::io::{FromRawFd, IntoRawFd};
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000065use std::path::{Path, PathBuf};
Inseob Kimc7d28c72021-10-25 14:28:10 +000066use std::ptr::null_mut;
Andrew Walbran320b5602021-03-04 16:11:12 +000067use std::sync::{Arc, Mutex, Weak};
Andrew Walbrancc0db522021-07-12 17:03:42 +000068use vmconfig::VmConfig;
Inseob Kim7f61fe72021-08-20 20:50:47 +090069use vsock::{SockAddr, VsockListener, VsockStream};
Jooyung Han35edb8f2021-07-01 16:17:16 +090070use zip::ZipArchive;
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000071
Andrew Walbranf6bf6862021-05-21 12:41:13 +000072pub const BINDER_SERVICE_IDENTIFIER: &str = "android.system.virtualizationservice";
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000073
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000074/// Directory in which to write disk image files used while running VMs.
Andrew Walbran488bd072021-07-14 13:29:51 +000075pub const TEMPORARY_DIRECTORY: &str = "/data/misc/virtualizationservice";
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000076
Jiyong Park8611a6c2021-07-09 18:17:44 +090077/// The CID representing the host VM
78const VMADDR_CID_HOST: u32 = 2;
79
Jooyung Han95884632021-07-06 22:27:54 +090080/// The size of zero.img.
81/// Gaps in composite disk images are filled with a shared zero.img.
82const ZERO_FILLER_SIZE: u64 = 4096;
83
Jiyong Park9dd389e2021-08-23 20:42:59 +090084/// Magic string for the instance image
85const ANDROID_VM_INSTANCE_MAGIC: &str = "Android-VM-instance";
86
87/// Version of the instance image format
88const ANDROID_VM_INSTANCE_VERSION: u16 = 1;
89
Andrew Walbranf6bf6862021-05-21 12:41:13 +000090/// Implementation of `IVirtualizationService`, the entry point of the AIDL service.
Jooyung Han9900f3d2021-07-06 10:27:54 +090091#[derive(Debug, Default)]
Andrew Walbranf6bf6862021-05-21 12:41:13 +000092pub struct VirtualizationService {
Jiyong Park8611a6c2021-07-09 18:17:44 +090093 state: Arc<Mutex<State>>,
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000094}
95
Shikha Panward8e35422021-10-11 13:51:27 +000096impl Interface for VirtualizationService {
97 fn dump(&self, mut file: &File, _args: &[&CStr]) -> Result<(), StatusCode> {
98 check_permission("android.permission.DUMP").or(Err(StatusCode::PERMISSION_DENIED))?;
99 let state = &mut *self.state.lock().unwrap();
100 let vms = state.vms();
101 writeln!(file, "Running {0} VMs:", vms.len()).or(Err(StatusCode::UNKNOWN_ERROR))?;
102 for vm in vms {
103 writeln!(file, "VM CID: {}", vm.cid).or(Err(StatusCode::UNKNOWN_ERROR))?;
104 writeln!(file, "\tState: {:?}", vm.vm_state.lock().unwrap())
105 .or(Err(StatusCode::UNKNOWN_ERROR))?;
106 writeln!(file, "\tPayload state {:?}", vm.payload_state())
107 .or(Err(StatusCode::UNKNOWN_ERROR))?;
108 writeln!(file, "\tProtected: {}", vm.protected).or(Err(StatusCode::UNKNOWN_ERROR))?;
109 writeln!(file, "\ttemporary_directory: {}", vm.temporary_directory.to_string_lossy())
110 .or(Err(StatusCode::UNKNOWN_ERROR))?;
111 writeln!(file, "\trequester_uid: {}", vm.requester_uid)
112 .or(Err(StatusCode::UNKNOWN_ERROR))?;
113 writeln!(file, "\trequester_sid: {}", vm.requester_sid)
114 .or(Err(StatusCode::UNKNOWN_ERROR))?;
115 writeln!(file, "\trequester_debug_pid: {}", vm.requester_debug_pid)
116 .or(Err(StatusCode::UNKNOWN_ERROR))?;
117 }
118 Ok(())
119 }
120}
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000121
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000122impl IVirtualizationService for VirtualizationService {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000123 /// Creates (but does not start) a new VM with the given configuration, assigning it the next
124 /// available CID.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000125 ///
126 /// Returns a binder `IVirtualMachine` object referring to it, as a handle for the client.
Andrew Walbranf8d94112021-09-07 11:45:36 +0000127 fn createVm(
Andrew Walbrana89fc132021-03-17 17:08:36 +0000128 &self,
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000129 config: &VirtualMachineConfig,
Jiyong Parkb8182bb2021-10-26 22:53:08 +0900130 console_fd: Option<&ParcelFileDescriptor>,
Andrew Walbrana89fc132021-03-17 17:08:36 +0000131 log_fd: Option<&ParcelFileDescriptor>,
132 ) -> binder::Result<Strong<dyn IVirtualMachine>> {
Jiyong Park753553b2021-07-12 21:21:09 +0900133 check_manage_access()?;
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000134 let state = &mut *self.state.lock().unwrap();
Jiyong Parkb8182bb2021-10-26 22:53:08 +0900135 let mut console_fd = console_fd.map(clone_file).transpose()?;
Jiyong Parkc2a49cc2021-10-15 00:02:12 +0900136 let mut log_fd = log_fd.map(clone_file).transpose()?;
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000137 let requester_uid = ThreadState::get_calling_uid();
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000138 let requester_sid = get_calling_sid()?;
Andrew Walbran02034492021-04-13 15:05:07 +0000139 let requester_debug_pid = ThreadState::get_calling_pid();
Jiyong Parkd50a0242021-09-16 21:00:14 +0900140 let cid = next_cid().or(Err(ExceptionCode::ILLEGAL_STATE))?;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000141
142 // Counter to generate unique IDs for temporary image files.
143 let mut next_temporary_image_id = 0;
144 // Files which are referred to from composite images. These must be mapped to the crosvm
145 // child process, and not closed before it is started.
146 let mut indirect_files = vec![];
147
148 // Make directory for temporary files.
149 let temporary_directory: PathBuf = format!("{}/{}", TEMPORARY_DIRECTORY, cid).into();
150 create_dir(&temporary_directory).map_err(|e| {
Treehugger Robot3ffa8322021-11-22 12:06:47 +0000151 // At this point, we do not know the protected status of Vm
152 // setting it to false, though this may not be correct.
153 write_vm_creation_stats(false, false);
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000154 error!(
Andrew Walbran806f1542021-06-10 14:07:12 +0000155 "Failed to create temporary directory {:?} for VM files: {}",
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000156 temporary_directory, e
157 );
Andrew Walbran806f1542021-06-10 14:07:12 +0000158 new_binder_exception(
159 ExceptionCode::SERVICE_SPECIFIC,
160 format!(
161 "Failed to create temporary directory {:?} for VM files: {}",
162 temporary_directory, e
163 ),
164 )
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000165 })?;
166
Jiyong Parkc2a49cc2021-10-15 00:02:12 +0900167 // Disable console logging if debug level != full. Note that kernel anyway doesn't use the
168 // console output when debug level != full. So, users won't be able to see the kernel
169 // output even without this overriding. This is to silence output from the bootloader which
170 // doesn't understand the bootconfig parameters.
171 if let VirtualMachineConfig::AppConfig(config) = config {
172 if config.debugLevel != DebugLevel::FULL {
Jiyong Parkb8182bb2021-10-26 22:53:08 +0900173 console_fd = None;
174 }
175 if config.debugLevel == DebugLevel::NONE {
Jiyong Parkc2a49cc2021-10-15 00:02:12 +0900176 log_fd = None;
177 }
178 }
179
Jiyong Park029977d2021-11-24 21:56:49 +0900180 let is_app_config = matches!(config, VirtualMachineConfig::AppConfig(_));
Jiyong Parkd2dc83f2021-12-20 18:40:52 +0900181 let is_debug_level_full = matches!(
182 config,
183 VirtualMachineConfig::AppConfig(VirtualMachineAppConfig {
184 debugLevel: DebugLevel::FULL,
185 ..
186 })
187 );
Jiyong Park029977d2021-11-24 21:56:49 +0900188
Jooyung Han21e9b922021-06-26 04:14:16 +0900189 let config = match config {
Jooyung Han35edb8f2021-07-01 16:17:16 +0900190 VirtualMachineConfig::AppConfig(config) => BorrowedOrOwned::Owned(
Jooyung Han9900f3d2021-07-06 10:27:54 +0900191 load_app_config(config, &temporary_directory).map_err(|e| {
192 error!("Failed to load app config from {}: {}", &config.configPath, e);
Treehugger Robot3ffa8322021-11-22 12:06:47 +0000193 // At this point, we do not know the protected status of Vm
194 // setting it to false, though this may not be correct.
195 write_vm_creation_stats(false, false);
Jooyung Han9900f3d2021-07-06 10:27:54 +0900196 new_binder_exception(
197 ExceptionCode::SERVICE_SPECIFIC,
198 format!("Failed to load app config from {}: {}", &config.configPath, e),
199 )
200 })?,
Jooyung Han35edb8f2021-07-01 16:17:16 +0900201 ),
202 VirtualMachineConfig::RawConfig(config) => BorrowedOrOwned::Borrowed(config),
Jooyung Han21e9b922021-06-26 04:14:16 +0900203 };
Jooyung Han35edb8f2021-07-01 16:17:16 +0900204 let config = config.as_ref();
Treehugger Robot3ffa8322021-11-22 12:06:47 +0000205 let protected_vm = config.protectedVm;
Jooyung Han21e9b922021-06-26 04:14:16 +0900206
Jiyong Park029977d2021-11-24 21:56:49 +0900207 // Check if partition images are labeled incorrectly. This is to prevent random images
208 // which are not protected by the Android Verified Boot (e.g. bits downloaded by apps) from
209 // being loaded in a pVM. Specifically, for images in the raw config, nothing is allowed
210 // to be labeled as app_data_file. For images in the app config, nothing but the instance
211 // partition is allowed to be labeled as such.
212 config
213 .disks
214 .iter()
215 .flat_map(|disk| disk.partitions.iter())
216 .filter(|partition| {
217 if is_app_config {
218 partition.label != "vm-instance"
219 } else {
220 true // all partitions are checked
221 }
222 })
223 .try_for_each(check_label_for_partition)
224 .map_err(|e| new_binder_exception(ExceptionCode::SERVICE_SPECIFIC, e.to_string()))?;
225
Jooyung Han95884632021-07-06 22:27:54 +0900226 let zero_filler_path = temporary_directory.join("zero.img");
Andrew Walbranfbb39d22021-07-28 17:01:25 +0000227 write_zero_filler(&zero_filler_path).map_err(|e| {
Jooyung Han95884632021-07-06 22:27:54 +0900228 error!("Failed to make composite image: {}", e);
Treehugger Robot3ffa8322021-11-22 12:06:47 +0000229 write_vm_creation_stats(protected_vm, false);
Jooyung Han95884632021-07-06 22:27:54 +0900230 new_binder_exception(
231 ExceptionCode::SERVICE_SPECIFIC,
232 format!("Failed to make composite image: {}", e),
233 )
234 })?;
Jooyung Han95884632021-07-06 22:27:54 +0900235
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000236 // Assemble disk images if needed.
237 let disks = config
238 .disks
239 .iter()
240 .map(|disk| {
241 assemble_disk_image(
242 disk,
Jooyung Han95884632021-07-06 22:27:54 +0900243 &zero_filler_path,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000244 &temporary_directory,
245 &mut next_temporary_image_id,
246 &mut indirect_files,
247 )
248 })
249 .collect::<Result<Vec<DiskFile>, _>>()?;
250
Jiyong Parkd2dc83f2021-12-20 18:40:52 +0900251 let protected_vm_supported = Kvm::new()
252 .map_err(|e| new_binder_exception(ExceptionCode::SERVICE_SPECIFIC, e.to_string()))?
253 .check_extension(Cap::ArmProtectedVm);
254 let protected = config.protectedVm && protected_vm_supported;
255 if config.protectedVm && !protected_vm_supported {
256 warn!("Protected VM was requested, but it isn't supported on this machine. Ignored.");
257 }
258
259 // And force run in non-protected mode when debug level is FULL
260 let protected = if is_debug_level_full {
261 if protected {
262 warn!("VM will run in FULL debug level. Running in non-protected mode");
263 }
264 false
265 } else {
266 protected
267 };
268
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000269 // Actually start the VM.
270 let crosvm_config = CrosvmConfig {
Andrew Walbran02034492021-04-13 15:05:07 +0000271 cid,
Andrew Walbrand3a84182021-09-07 14:48:52 +0000272 bootloader: maybe_clone_file(&config.bootloader)?,
273 kernel: maybe_clone_file(&config.kernel)?,
274 initrd: maybe_clone_file(&config.initrd)?,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000275 disks,
276 params: config.params.to_owned(),
Jiyong Parkd2dc83f2021-12-20 18:40:52 +0900277 protected,
Andrew Walbrancc045902021-07-27 16:06:17 +0000278 memory_mib: config.memoryMib.try_into().ok().and_then(NonZeroU32::new),
Jiyong Park032615f2022-01-10 13:55:34 +0900279 cpus: config.numCpus.try_into().ok().and_then(NonZeroU32::new),
280 cpu_affinity: config.cpuAffinity.clone(),
Jiyong Parkb8182bb2021-10-26 22:53:08 +0900281 console_fd,
Andrew Walbran02034492021-04-13 15:05:07 +0000282 log_fd,
Andrew Walbrand3a84182021-09-07 14:48:52 +0000283 indirect_files,
284 };
Andrew Walbranf8d94112021-09-07 11:45:36 +0000285 let instance = Arc::new(
286 VmInstance::new(
287 crosvm_config,
288 temporary_directory,
289 requester_uid,
290 requester_sid,
291 requester_debug_pid,
Andrew Walbran806f1542021-06-10 14:07:12 +0000292 )
Andrew Walbranf8d94112021-09-07 11:45:36 +0000293 .map_err(|e| {
294 error!("Failed to create VM with config {:?}: {}", config, e);
Treehugger Robot3ffa8322021-11-22 12:06:47 +0000295 write_vm_creation_stats(protected_vm, false);
Andrew Walbranf8d94112021-09-07 11:45:36 +0000296 new_binder_exception(
297 ExceptionCode::SERVICE_SPECIFIC,
298 format!("Failed to create VM: {}", e),
299 )
300 })?,
301 );
Andrew Walbran320b5602021-03-04 16:11:12 +0000302 state.add_vm(Arc::downgrade(&instance));
Treehugger Robot3ffa8322021-11-22 12:06:47 +0000303 write_vm_creation_stats(protected_vm, true);
Andrew Walbran320b5602021-03-04 16:11:12 +0000304 Ok(VirtualMachine::create(instance))
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000305 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000306
Andrew Walbrandff3b942021-06-09 15:20:36 +0000307 /// Initialise an empty partition image of the given size to be used as a writable partition.
308 fn initializeWritablePartition(
309 &self,
310 image_fd: &ParcelFileDescriptor,
311 size: i64,
Jiyong Park9dd389e2021-08-23 20:42:59 +0900312 partition_type: PartitionType,
Andrew Walbrandff3b942021-06-09 15:20:36 +0000313 ) -> binder::Result<()> {
Jiyong Park753553b2021-07-12 21:21:09 +0900314 check_manage_access()?;
Andrew Walbrandfc953d2021-06-10 13:59:56 +0000315 let size = size.try_into().map_err(|e| {
Andrew Walbran806f1542021-06-10 14:07:12 +0000316 new_binder_exception(
317 ExceptionCode::ILLEGAL_ARGUMENT,
318 format!("Invalid size {}: {}", size, e),
319 )
Andrew Walbrandff3b942021-06-09 15:20:36 +0000320 })?;
Andrew Walbrandfc953d2021-06-10 13:59:56 +0000321 let image = clone_file(image_fd)?;
Jooyung Han1edd5b92021-10-28 10:58:05 +0900322 // initialize the file. Any data in the file will be erased.
323 image.set_len(0).map_err(|e| {
324 new_binder_exception(
325 ExceptionCode::SERVICE_SPECIFIC,
326 format!("Failed to reset a file: {}", e),
327 )
328 })?;
Jiyong Park9dd389e2021-08-23 20:42:59 +0900329 let mut part = QcowFile::new(image, size).map_err(|e| {
Andrew Walbran806f1542021-06-10 14:07:12 +0000330 new_binder_exception(
331 ExceptionCode::SERVICE_SPECIFIC,
332 format!("Failed to create QCOW2 image: {}", e),
333 )
Andrew Walbrandfc953d2021-06-10 13:59:56 +0000334 })?;
Andrew Walbrandff3b942021-06-09 15:20:36 +0000335
Jiyong Park9dd389e2021-08-23 20:42:59 +0900336 match partition_type {
337 PartitionType::RAW => Ok(()),
338 PartitionType::ANDROID_VM_INSTANCE => format_as_android_vm_instance(&mut part),
339 _ => Err(Error::new(
340 ErrorKind::Unsupported,
341 format!("Unsupported partition type {:?}", partition_type),
342 )),
343 }
344 .map_err(|e| {
345 new_binder_exception(
346 ExceptionCode::SERVICE_SPECIFIC,
347 format!("Failed to initialize partition as {:?}: {}", partition_type, e),
348 )
349 })?;
350
Andrew Walbrandff3b942021-06-09 15:20:36 +0000351 Ok(())
352 }
353
Jiyong Park0a248432021-08-20 23:32:39 +0900354 /// Creates or update the idsig file by digesting the input APK file.
355 fn createOrUpdateIdsigFile(
356 &self,
357 input_fd: &ParcelFileDescriptor,
358 idsig_fd: &ParcelFileDescriptor,
359 ) -> binder::Result<()> {
360 // TODO(b/193504400): do this only when (1) idsig_fd is empty or (2) the APK digest in
361 // idsig_fd is different from APK digest in input_fd
362
363 let mut input = clone_file(input_fd)?;
364 let mut sig = V4Signature::create(&mut input, 4096, &[], HashAlgorithm::SHA256).unwrap();
365
366 let mut output = clone_file(idsig_fd)?;
367 output.set_len(0).unwrap();
368 sig.write_into(&mut output).unwrap();
369 Ok(())
370 }
371
Andrew Walbran320b5602021-03-04 16:11:12 +0000372 /// Get a list of all currently running VMs. This method is only intended for debug purposes,
373 /// and as such is only permitted from the shell user.
374 fn debugListVms(&self) -> binder::Result<Vec<VirtualMachineDebugInfo>> {
Andrew Walbran806f1542021-06-10 14:07:12 +0000375 check_debug_access()?;
Andrew Walbran320b5602021-03-04 16:11:12 +0000376
377 let state = &mut *self.state.lock().unwrap();
378 let vms = state.vms();
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000379 let cids = vms
380 .into_iter()
381 .map(|vm| VirtualMachineDebugInfo {
382 cid: vm.cid as i32,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000383 temporaryDirectory: vm.temporary_directory.to_string_lossy().to_string(),
Andrew Walbran1ef19ae2021-04-07 11:31:57 +0000384 requesterUid: vm.requester_uid as i32,
385 requesterSid: vm.requester_sid.clone(),
Andrew Walbran02034492021-04-13 15:05:07 +0000386 requesterPid: vm.requester_debug_pid,
Andrew Walbran6b650662021-09-07 13:13:23 +0000387 state: get_state(&vm),
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000388 })
389 .collect();
Andrew Walbran320b5602021-03-04 16:11:12 +0000390 Ok(cids)
391 }
David Brazdil3c2ddef2021-03-18 13:09:57 +0000392
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000393 /// Hold a strong reference to a VM in VirtualizationService. This method is only intended for
394 /// debug purposes, and as such is only permitted from the shell user.
Andrei Homescu1415c132021-03-24 02:39:55 +0000395 fn debugHoldVmRef(&self, vmref: &Strong<dyn IVirtualMachine>) -> binder::Result<()> {
Andrew Walbran806f1542021-06-10 14:07:12 +0000396 check_debug_access()?;
David Brazdil3c2ddef2021-03-18 13:09:57 +0000397
David Brazdil3c2ddef2021-03-18 13:09:57 +0000398 let state = &mut *self.state.lock().unwrap();
Andrei Homescu1415c132021-03-24 02:39:55 +0000399 state.debug_hold_vm(vmref.clone());
David Brazdil3c2ddef2021-03-18 13:09:57 +0000400 Ok(())
401 }
402
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000403 /// Drop reference to a VM that is being held by VirtualizationService. Returns the reference if
404 /// the VM was found and None otherwise. This method is only intended for debug purposes, and as
405 /// such is only permitted from the shell user.
David Brazdil3c2ddef2021-03-18 13:09:57 +0000406 fn debugDropVmRef(&self, cid: i32) -> binder::Result<Option<Strong<dyn IVirtualMachine>>> {
Andrew Walbran806f1542021-06-10 14:07:12 +0000407 check_debug_access()?;
David Brazdil3c2ddef2021-03-18 13:09:57 +0000408
409 let state = &mut *self.state.lock().unwrap();
410 Ok(state.debug_drop_vm(cid))
411 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000412}
413
Jiyong Park8611a6c2021-07-09 18:17:44 +0900414impl VirtualizationService {
415 pub fn init() -> VirtualizationService {
416 let service = VirtualizationService::default();
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900417
418 // server for payload output
Jiyong Park8611a6c2021-07-09 18:17:44 +0900419 let state = service.state.clone(); // reference to state (not the state itself) is copied
420 std::thread::spawn(move || {
Inseob Kim7f61fe72021-08-20 20:50:47 +0900421 handle_stream_connection_from_vm(state).unwrap();
Jiyong Park8611a6c2021-07-09 18:17:44 +0900422 });
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900423
424 // binder server for vm
Inseob Kimc7d28c72021-10-25 14:28:10 +0000425 let mut state = service.state.clone(); // reference to state (not the state itself) is copied
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900426 std::thread::spawn(move || {
Inseob Kimc7d28c72021-10-25 14:28:10 +0000427 let state_ptr = &mut state as *mut _ as *mut raw::c_void;
428
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900429 debug!("virtual machine service is starting as an RPC service.");
Inseob Kimc7d28c72021-10-25 14:28:10 +0000430 // SAFETY: factory function is only ever called by RunRpcServerWithFactory, within the
431 // lifetime of the state, with context taking the pointer value above (so a properly
432 // aligned non-null pointer to an initialized instance).
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900433 let retval = unsafe {
Inseob Kimc7d28c72021-10-25 14:28:10 +0000434 binder_rpc_unstable_bindgen::RunRpcServerWithFactory(
435 Some(VirtualMachineService::factory),
436 state_ptr,
Inseob Kimd0587562021-09-01 21:27:32 +0900437 VM_BINDER_SERVICE_PORT as u32,
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900438 )
439 };
440 if retval {
441 debug!("RPC server has shut down gracefully");
442 } else {
443 bail!("Premature termination of RPC server");
444 }
445
446 Ok(retval)
447 });
Jiyong Park8611a6c2021-07-09 18:17:44 +0900448 service
449 }
450}
451
Treehugger Robot3ffa8322021-11-22 12:06:47 +0000452/// Write the stats of VMCreation to statsd
453fn write_vm_creation_stats(protected: bool, success: bool) {
454 match stats_write(Hypervisor::Pkvm, protected, success) {
455 Err(e) => {
456 info!("stastlog_rust fails with error: {}", e);
457 }
458 Ok(_) => info!("stastlog_rust succeeded for virtualization service"),
459 }
460}
461
Andrew Walbran6b650662021-09-07 13:13:23 +0000462/// Waits for incoming connections from VM. If a new connection is made, stores the stream in the
463/// corresponding `VmInstance`.
Inseob Kim7f61fe72021-08-20 20:50:47 +0900464fn handle_stream_connection_from_vm(state: Arc<Mutex<State>>) -> Result<()> {
Inseob Kimd0587562021-09-01 21:27:32 +0900465 let listener =
466 VsockListener::bind_with_cid_port(VMADDR_CID_HOST, VM_STREAM_SERVICE_PORT as u32)?;
Jiyong Park8611a6c2021-07-09 18:17:44 +0900467 for stream in listener.incoming() {
468 let stream = match stream {
469 Err(e) => {
470 warn!("invalid incoming connection: {}", e);
471 continue;
472 }
473 Ok(s) => s,
474 };
475 if let Ok(SockAddr::Vsock(addr)) = stream.peer_addr() {
476 let cid = addr.cid();
477 let port = addr.port();
Inseob Kim7f61fe72021-08-20 20:50:47 +0900478 info!("payload stream connected from cid={}, port={}", cid, port);
Jiyong Park8611a6c2021-07-09 18:17:44 +0900479 if let Some(vm) = state.lock().unwrap().get_vm(cid) {
Chris Wailes8bbb8932021-09-10 14:14:19 -0700480 *vm.stream.lock().unwrap() = Some(stream);
Inseob Kim7f61fe72021-08-20 20:50:47 +0900481 } else {
482 error!("connection from cid={} is not from a guest VM", cid);
Jiyong Park8611a6c2021-07-09 18:17:44 +0900483 }
484 }
485 }
486 Ok(())
487}
488
Andrew Walbranfbb39d22021-07-28 17:01:25 +0000489fn write_zero_filler(zero_filler_path: &Path) -> Result<()> {
Jooyung Han95884632021-07-06 22:27:54 +0900490 let file = OpenOptions::new()
491 .create_new(true)
492 .read(true)
493 .write(true)
494 .open(zero_filler_path)
495 .with_context(|| "Failed to create zero.img")?;
496 file.set_len(ZERO_FILLER_SIZE)?;
Andrew Walbranfbb39d22021-07-28 17:01:25 +0000497 Ok(())
Jooyung Han95884632021-07-06 22:27:54 +0900498}
499
Jiyong Park9dd389e2021-08-23 20:42:59 +0900500fn format_as_android_vm_instance(part: &mut dyn Write) -> std::io::Result<()> {
501 part.write_all(ANDROID_VM_INSTANCE_MAGIC.as_bytes())?;
502 part.write_all(&ANDROID_VM_INSTANCE_VERSION.to_le_bytes())?;
503 part.flush()
504}
505
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000506/// Given the configuration for a disk image, assembles the `DiskFile` to pass to crosvm.
507///
508/// This may involve assembling a composite disk from a set of partition images.
509fn assemble_disk_image(
510 disk: &DiskImage,
Jooyung Han95884632021-07-06 22:27:54 +0900511 zero_filler_path: &Path,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000512 temporary_directory: &Path,
513 next_temporary_image_id: &mut u64,
514 indirect_files: &mut Vec<File>,
Andrew Walbran806f1542021-06-10 14:07:12 +0000515) -> Result<DiskFile, Status> {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000516 let image = if !disk.partitions.is_empty() {
517 if disk.image.is_some() {
518 warn!("DiskImage {:?} contains both image and partitions.", disk);
Andrew Walbran806f1542021-06-10 14:07:12 +0000519 return Err(new_binder_exception(
520 ExceptionCode::ILLEGAL_ARGUMENT,
521 "DiskImage contains both image and partitions.",
522 ));
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000523 }
524
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000525 let composite_image_filenames =
526 make_composite_image_filenames(temporary_directory, next_temporary_image_id);
527 let (image, partition_files) = make_composite_image(
528 &disk.partitions,
Jooyung Han95884632021-07-06 22:27:54 +0900529 zero_filler_path,
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000530 &composite_image_filenames.composite,
531 &composite_image_filenames.header,
532 &composite_image_filenames.footer,
533 )
534 .map_err(|e| {
535 error!("Failed to make composite image with config {:?}: {}", disk, e);
536 new_binder_exception(
537 ExceptionCode::SERVICE_SPECIFIC,
538 format!("Failed to make composite image: {}", e),
539 )
540 })?;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000541
542 // Pass the file descriptors for the various partition files to crosvm when it
543 // is run.
544 indirect_files.extend(partition_files);
545
546 image
547 } else if let Some(image) = &disk.image {
548 clone_file(image)?
549 } else {
550 warn!("DiskImage {:?} didn't contain image or partitions.", disk);
Andrew Walbran806f1542021-06-10 14:07:12 +0000551 return Err(new_binder_exception(
552 ExceptionCode::ILLEGAL_ARGUMENT,
553 "DiskImage didn't contain image or partitions.",
554 ));
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000555 };
556
557 Ok(DiskFile { image, writable: disk.writable })
558}
559
Jooyung Han21e9b922021-06-26 04:14:16 +0900560fn load_app_config(
561 config: &VirtualMachineAppConfig,
562 temporary_directory: &Path,
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900563) -> Result<VirtualMachineRawConfig> {
Andrew Walbrancc0db522021-07-12 17:03:42 +0000564 let apk_file = clone_file(config.apk.as_ref().unwrap())?;
565 let idsig_file = clone_file(config.idsig.as_ref().unwrap())?;
Jiyong Park8d081812021-07-23 17:45:04 +0900566 let instance_file = clone_file(config.instanceImage.as_ref().unwrap())?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900567 let config_path = &config.configPath;
568
Andrew Walbrancc0db522021-07-12 17:03:42 +0000569 let mut apk_zip = ZipArchive::new(&apk_file)?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900570 let config_file = apk_zip.by_name(config_path)?;
571 let vm_payload_config: VmPayloadConfig = serde_json::from_reader(config_file)?;
572
573 let os_name = &vm_payload_config.os.name;
Andrew Walbrancc0db522021-07-12 17:03:42 +0000574
Jooyung Han35edb8f2021-07-01 16:17:16 +0900575 // For now, the only supported "os" value is "microdroid"
576 if os_name != "microdroid" {
Andrew Walbrancc0db522021-07-12 17:03:42 +0000577 bail!("Unknown OS \"{}\"", os_name);
Jooyung Han35edb8f2021-07-01 16:17:16 +0900578 }
Andrew Walbrancc0db522021-07-12 17:03:42 +0000579
580 // It is safe to construct a filename based on the os_name because we've already checked that it
581 // is one of the allowed values.
Jooyung Han21e9b922021-06-26 04:14:16 +0900582 let vm_config_path = PathBuf::from(format!("/apex/com.android.virt/etc/{}.json", os_name));
583 let vm_config_file = File::open(vm_config_path)?;
Andrew Walbrancc0db522021-07-12 17:03:42 +0000584 let mut vm_config = VmConfig::load(&vm_config_file)?.to_parcelable()?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900585
Andrew Walbrancc045902021-07-27 16:06:17 +0000586 if config.memoryMib > 0 {
587 vm_config.memoryMib = config.memoryMib;
Andrew Walbran45bcb0c2021-07-14 15:02:06 +0000588 }
589
Jiyong Park032615f2022-01-10 13:55:34 +0900590 vm_config.numCpus = config.numCpus;
591 vm_config.cpuAffinity = config.cpuAffinity.clone();
592
Andrew Walbrancc0db522021-07-12 17:03:42 +0000593 // Microdroid requires an additional payload disk image and the bootconfig partition.
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900594 if os_name == "microdroid" {
Andrew Walbrancc0db522021-07-12 17:03:42 +0000595 add_microdroid_images(
596 config,
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900597 temporary_directory,
Andrew Walbrancc0db522021-07-12 17:03:42 +0000598 apk_file,
599 idsig_file,
Jiyong Park8d081812021-07-23 17:45:04 +0900600 instance_file,
Jooyung Han5dc42172021-10-05 16:43:47 +0900601 &vm_payload_config,
Andrew Walbrancc0db522021-07-12 17:03:42 +0000602 &mut vm_config,
603 )?;
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900604 }
Jooyung Han21e9b922021-06-26 04:14:16 +0900605
Andrew Walbrancc0db522021-07-12 17:03:42 +0000606 Ok(vm_config)
Jooyung Han21e9b922021-06-26 04:14:16 +0900607}
608
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000609/// Generates a unique filename to use for a composite disk image.
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000610fn make_composite_image_filenames(
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000611 temporary_directory: &Path,
612 next_temporary_image_id: &mut u64,
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000613) -> CompositeImageFilenames {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000614 let id = *next_temporary_image_id;
615 *next_temporary_image_id += 1;
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000616 CompositeImageFilenames {
617 composite: temporary_directory.join(format!("composite-{}.img", id)),
618 header: temporary_directory.join(format!("composite-{}-header.img", id)),
619 footer: temporary_directory.join(format!("composite-{}-footer.img", id)),
620 }
621}
622
623/// Filenames for a composite disk image, including header and footer partitions.
624#[derive(Clone, Debug, Eq, PartialEq)]
625struct CompositeImageFilenames {
626 /// The composite disk image itself.
627 composite: PathBuf,
628 /// The header partition image.
629 header: PathBuf,
630 /// The footer partition image.
631 footer: PathBuf,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000632}
633
634/// Gets the calling SID of the current Binder thread.
Andrew Walbran806f1542021-06-10 14:07:12 +0000635fn get_calling_sid() -> Result<String, Status> {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000636 ThreadState::with_calling_sid(|sid| {
637 if let Some(sid) = sid {
638 match sid.to_str() {
639 Ok(sid) => Ok(sid.to_owned()),
640 Err(e) => {
Andrew Walbran806f1542021-06-10 14:07:12 +0000641 error!("SID was not valid UTF-8: {}", e);
642 Err(new_binder_exception(
643 ExceptionCode::ILLEGAL_ARGUMENT,
644 format!("SID was not valid UTF-8: {}", e),
645 ))
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000646 }
647 }
648 } else {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000649 error!("Missing SID on createVm");
650 Err(new_binder_exception(ExceptionCode::SECURITY, "Missing SID on createVm"))
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000651 }
652 })
653}
654
Jiyong Park753553b2021-07-12 21:21:09 +0900655/// Checks whether the caller has a specific permission
656fn check_permission(perm: &str) -> binder::Result<()> {
657 let calling_pid = ThreadState::get_calling_pid();
658 let calling_uid = ThreadState::get_calling_uid();
659 // Root can do anything
660 if calling_uid == 0 {
661 return Ok(());
662 }
663 let perm_svc: Strong<dyn IPermissionController::IPermissionController> =
664 binder::get_interface("permission")?;
665 if perm_svc.checkPermission(perm, calling_pid, calling_uid as i32)? {
Andrew Walbran806f1542021-06-10 14:07:12 +0000666 Ok(())
667 } else {
Jiyong Park753553b2021-07-12 21:21:09 +0900668 Err(new_binder_exception(
669 ExceptionCode::SECURITY,
670 format!("does not have the {} permission", perm),
671 ))
Andrew Walbran806f1542021-06-10 14:07:12 +0000672 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000673}
674
Jiyong Park753553b2021-07-12 21:21:09 +0900675/// Check whether the caller of the current Binder method is allowed to call debug methods.
676fn check_debug_access() -> binder::Result<()> {
677 check_permission("android.permission.DEBUG_VIRTUAL_MACHINE")
678}
679
680/// Check whether the caller of the current Binder method is allowed to manage VMs
681fn check_manage_access() -> binder::Result<()> {
682 check_permission("android.permission.MANAGE_VIRTUAL_MACHINE")
683}
684
Jiyong Park029977d2021-11-24 21:56:49 +0900685/// Check if a partition has selinux labels that are not allowed
686fn check_label_for_partition(partition: &Partition) -> Result<()> {
687 let ctx = getfilecon(partition.image.as_ref().unwrap().as_ref())?;
688 if ctx == SeContext::new("u:object_r:app_data_file:s0").unwrap() {
689 Err(anyhow!("Partition {} shouldn't be labeled as {}", &partition.label, ctx))
690 } else {
691 Ok(())
692 }
693}
694
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000695/// Implementation of the AIDL `IVirtualMachine` interface. Used as a handle to a VM.
696#[derive(Debug)]
697struct VirtualMachine {
698 instance: Arc<VmInstance>,
Alan Stokes0cc59ee2021-09-24 11:20:34 +0100699 /// Keeps our service process running as long as this VM instance exists.
Chris Wailes641fc4a2021-12-01 15:03:21 -0800700 #[allow(dead_code)]
Alan Stokes0cc59ee2021-09-24 11:20:34 +0100701 lazy_service_guard: LazyServiceGuard,
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000702}
703
704impl VirtualMachine {
705 fn create(instance: Arc<VmInstance>) -> Strong<dyn IVirtualMachine> {
Alan Stokes0cc59ee2021-09-24 11:20:34 +0100706 let binder = VirtualMachine { instance, lazy_service_guard: Default::default() };
Andrew Walbran4de28782021-04-13 14:51:43 +0000707 BnVirtualMachine::new_binder(binder, BinderFeatures::default())
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000708 }
709}
710
711impl Interface for VirtualMachine {}
712
713impl IVirtualMachine for VirtualMachine {
714 fn getCid(&self) -> binder::Result<i32> {
Jiyong Park753553b2021-07-12 21:21:09 +0900715 // Don't check permission. The owner of the VM might have passed this binder object to
716 // others.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000717 Ok(self.instance.cid as i32)
718 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000719
Andrew Walbran6b650662021-09-07 13:13:23 +0000720 fn getState(&self) -> binder::Result<VirtualMachineState> {
Jiyong Park753553b2021-07-12 21:21:09 +0900721 // Don't check permission. The owner of the VM might have passed this binder object to
722 // others.
Andrew Walbran6b650662021-09-07 13:13:23 +0000723 Ok(get_state(&self.instance))
Andrew Walbrandae07162021-03-12 17:05:20 +0000724 }
725
726 fn registerCallback(
727 &self,
728 callback: &Strong<dyn IVirtualMachineCallback>,
729 ) -> binder::Result<()> {
Jiyong Park753553b2021-07-12 21:21:09 +0900730 // Don't check permission. The owner of the VM might have passed this binder object to
731 // others.
732 //
Andrew Walbrandae07162021-03-12 17:05:20 +0000733 // TODO: Should this give an error if the VM is already dead?
734 self.instance.callbacks.add(callback.clone());
735 Ok(())
736 }
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000737
Andrew Walbranf8d94112021-09-07 11:45:36 +0000738 fn start(&self) -> binder::Result<()> {
739 self.instance.start().map_err(|e| {
740 error!("Error starting VM with CID {}: {:?}", self.instance.cid, e);
741 new_binder_exception(ExceptionCode::SERVICE_SPECIFIC, e.to_string())
742 })
743 }
744
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000745 fn connectVsock(&self, port: i32) -> binder::Result<ParcelFileDescriptor> {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000746 if !matches!(&*self.instance.vm_state.lock().unwrap(), VmState::Running { .. }) {
747 return Err(new_binder_exception(ExceptionCode::SERVICE_SPECIFIC, "VM is not running"));
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000748 }
749 let stream =
750 VsockStream::connect_with_cid_port(self.instance.cid, port as u32).map_err(|e| {
751 new_binder_exception(
752 ExceptionCode::SERVICE_SPECIFIC,
753 format!("Failed to connect: {}", e),
754 )
755 })?;
756 Ok(vsock_stream_to_pfd(stream))
757 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000758}
759
760impl Drop for VirtualMachine {
761 fn drop(&mut self) {
762 debug!("Dropping {:?}", self);
763 self.instance.kill();
764 }
765}
766
767/// A set of Binders to be called back in response to various events on the VM, such as when it
768/// dies.
769#[derive(Debug, Default)]
770pub struct VirtualMachineCallbacks(Mutex<Vec<Strong<dyn IVirtualMachineCallback>>>);
771
772impl VirtualMachineCallbacks {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900773 /// Call all registered callbacks to notify that the payload has started.
Inseob Kim7f61fe72021-08-20 20:50:47 +0900774 pub fn notify_payload_started(&self, cid: Cid, stream: Option<VsockStream>) {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900775 let callbacks = &*self.0.lock().unwrap();
Inseob Kim7f61fe72021-08-20 20:50:47 +0900776 let pfd = stream.map(vsock_stream_to_pfd);
Jiyong Park8611a6c2021-07-09 18:17:44 +0900777 for callback in callbacks {
Inseob Kim7f61fe72021-08-20 20:50:47 +0900778 if let Err(e) = callback.onPayloadStarted(cid as i32, pfd.as_ref()) {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900779 error!("Error notifying payload start event from VM CID {}: {}", cid, e);
780 }
781 }
782 }
783
Inseob Kim14cb8692021-08-31 21:50:39 +0900784 /// Call all registered callbacks to notify that the payload is ready to serve.
785 pub fn notify_payload_ready(&self, cid: Cid) {
786 let callbacks = &*self.0.lock().unwrap();
787 for callback in callbacks {
788 if let Err(e) = callback.onPayloadReady(cid as i32) {
789 error!("Error notifying payload ready event from VM CID {}: {}", cid, e);
790 }
791 }
792 }
793
Inseob Kim2444af92021-08-31 01:22:50 +0900794 /// Call all registered callbacks to notify that the payload has finished.
795 pub fn notify_payload_finished(&self, cid: Cid, exit_code: i32) {
796 let callbacks = &*self.0.lock().unwrap();
797 for callback in callbacks {
798 if let Err(e) = callback.onPayloadFinished(cid as i32, exit_code) {
799 error!("Error notifying payload finish event from VM CID {}: {}", cid, e);
800 }
801 }
802 }
803
Jooyung Handd0a1732021-11-23 15:26:20 +0900804 /// Call all registered callbacks to say that the VM encountered an error.
805 pub fn notify_error(&self, cid: Cid, error_code: i32, message: &str) {
806 let callbacks = &*self.0.lock().unwrap();
807 for callback in callbacks {
808 if let Err(e) = callback.onError(cid as i32, error_code, message) {
809 error!("Error notifying error event from VM CID {}: {}", cid, e);
810 }
811 }
812 }
813
Andrew Walbrandae07162021-03-12 17:05:20 +0000814 /// Call all registered callbacks to say that the VM has died.
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000815 pub fn callback_on_died(&self, cid: Cid, reason: DeathReason) {
Andrew Walbrandae07162021-03-12 17:05:20 +0000816 let callbacks = &*self.0.lock().unwrap();
817 for callback in callbacks {
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000818 if let Err(e) = callback.onDied(cid as i32, reason) {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900819 error!("Error notifying exit of VM CID {}: {}", cid, e);
Andrew Walbrandae07162021-03-12 17:05:20 +0000820 }
821 }
822 }
823
824 /// Add a new callback to the set.
825 fn add(&self, callback: Strong<dyn IVirtualMachineCallback>) {
826 self.0.lock().unwrap().push(callback);
827 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000828}
829
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000830/// The mutable state of the VirtualizationService. There should only be one instance of this
831/// struct.
Chris Wailes641fc4a2021-12-01 15:03:21 -0800832#[derive(Debug, Default)]
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000833struct State {
Andrew Walbran320b5602021-03-04 16:11:12 +0000834 /// The VMs which have been started. When VMs are started a weak reference is added to this list
835 /// while a strong reference is returned to the caller over Binder. Once all copies of the
836 /// Binder client are dropped the weak reference here will become invalid, and will be removed
837 /// from the list opportunistically the next time `add_vm` is called.
838 vms: Vec<Weak<VmInstance>>,
David Brazdil3c2ddef2021-03-18 13:09:57 +0000839
840 /// Vector of strong VM references held on behalf of users that cannot hold them themselves.
841 /// This is only used for debugging purposes.
842 debug_held_vms: Vec<Strong<dyn IVirtualMachine>>,
Andrew Walbran320b5602021-03-04 16:11:12 +0000843}
844
845impl State {
Andrew Walbrandae07162021-03-12 17:05:20 +0000846 /// Get a list of VMs which still have Binder references to them.
Andrew Walbran320b5602021-03-04 16:11:12 +0000847 fn vms(&self) -> Vec<Arc<VmInstance>> {
848 // Attempt to upgrade the weak pointers to strong pointers.
849 self.vms.iter().filter_map(Weak::upgrade).collect()
850 }
851
852 /// Add a new VM to the list.
853 fn add_vm(&mut self, vm: Weak<VmInstance>) {
854 // Garbage collect any entries from the stored list which no longer exist.
855 self.vms.retain(|vm| vm.strong_count() > 0);
856
857 // Actually add the new VM.
858 self.vms.push(vm);
859 }
David Brazdil3c2ddef2021-03-18 13:09:57 +0000860
Jiyong Park8611a6c2021-07-09 18:17:44 +0900861 /// Get a VM that corresponds to the given cid
862 fn get_vm(&self, cid: Cid) -> Option<Arc<VmInstance>> {
863 self.vms().into_iter().find(|vm| vm.cid == cid)
864 }
865
David Brazdil3c2ddef2021-03-18 13:09:57 +0000866 /// Store a strong VM reference.
867 fn debug_hold_vm(&mut self, vm: Strong<dyn IVirtualMachine>) {
868 self.debug_held_vms.push(vm);
869 }
870
871 /// Retrieve and remove a strong VM reference.
872 fn debug_drop_vm(&mut self, cid: i32) -> Option<Strong<dyn IVirtualMachine>> {
873 let pos = self.debug_held_vms.iter().position(|vm| vm.getCid() == Ok(cid))?;
Alan Stokes7e54e292021-09-09 11:37:56 +0100874 let vm = self.debug_held_vms.swap_remove(pos);
Alan Stokes7e54e292021-09-09 11:37:56 +0100875 Some(vm)
David Brazdil3c2ddef2021-03-18 13:09:57 +0000876 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000877}
878
Jiyong Parkd50a0242021-09-16 21:00:14 +0900879/// Get the next available CID, or an error if we have run out. The last CID used is stored in
880/// a system property so that restart of virtualizationservice doesn't reuse CID while the host
881/// Android is up.
882fn next_cid() -> Result<Cid> {
883 let next = if let Ok(val) = system_properties::read(SYSPROP_LAST_CID) {
884 if let Ok(num) = val.parse::<u32>() {
885 num.checked_add(1).ok_or_else(|| anyhow!("run out of CID"))?
886 } else {
887 error!("Invalid last CID {}. Using {}", &val, FIRST_GUEST_CID);
888 FIRST_GUEST_CID
889 }
890 } else {
891 // First VM since the boot
892 FIRST_GUEST_CID
893 };
894 // Persist the last value for next use
895 let str_val = format!("{}", next);
896 system_properties::write(SYSPROP_LAST_CID, &str_val)?;
897 Ok(next)
898}
899
Andrew Walbran6b650662021-09-07 13:13:23 +0000900/// Gets the `VirtualMachineState` of the given `VmInstance`.
901fn get_state(instance: &VmInstance) -> VirtualMachineState {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000902 match &*instance.vm_state.lock().unwrap() {
903 VmState::NotStarted { .. } => VirtualMachineState::NOT_STARTED,
904 VmState::Running { .. } => match instance.payload_state() {
Andrew Walbran6b650662021-09-07 13:13:23 +0000905 PayloadState::Starting => VirtualMachineState::STARTING,
906 PayloadState::Started => VirtualMachineState::STARTED,
907 PayloadState::Ready => VirtualMachineState::READY,
908 PayloadState::Finished => VirtualMachineState::FINISHED,
Andrew Walbranf8d94112021-09-07 11:45:36 +0000909 },
910 VmState::Dead => VirtualMachineState::DEAD,
911 VmState::Failed => VirtualMachineState::DEAD,
Andrew Walbran6b650662021-09-07 13:13:23 +0000912 }
913}
914
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000915/// Converts a `&ParcelFileDescriptor` to a `File` by cloning the file.
Andrew Walbran806f1542021-06-10 14:07:12 +0000916fn clone_file(file: &ParcelFileDescriptor) -> Result<File, Status> {
917 file.as_ref().try_clone().map_err(|e| {
918 new_binder_exception(
919 ExceptionCode::BAD_PARCELABLE,
920 format!("Failed to clone File from ParcelFileDescriptor: {}", e),
921 )
922 })
923}
924
Andrew Walbrand3a84182021-09-07 14:48:52 +0000925/// Converts an `&Option<ParcelFileDescriptor>` to an `Option<File>` by cloning the file.
926fn maybe_clone_file(file: &Option<ParcelFileDescriptor>) -> Result<Option<File>, Status> {
927 file.as_ref().map(clone_file).transpose()
928}
929
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000930/// Converts a `VsockStream` to a `ParcelFileDescriptor`.
931fn vsock_stream_to_pfd(stream: VsockStream) -> ParcelFileDescriptor {
932 // SAFETY: ownership is transferred from stream to f
933 let f = unsafe { File::from_raw_fd(stream.into_raw_fd()) };
934 ParcelFileDescriptor::new(f)
935}
936
Jooyung Han35edb8f2021-07-01 16:17:16 +0900937/// Simple utility for referencing Borrowed or Owned. Similar to std::borrow::Cow, but
938/// it doesn't require that T implements Clone.
939enum BorrowedOrOwned<'a, T> {
940 Borrowed(&'a T),
941 Owned(T),
942}
943
944impl<'a, T> AsRef<T> for BorrowedOrOwned<'a, T> {
945 fn as_ref(&self) -> &T {
946 match self {
947 Self::Borrowed(b) => b,
Chris Wailes68c39f82021-07-27 16:03:44 -0700948 Self::Owned(o) => o,
Jooyung Han35edb8f2021-07-01 16:17:16 +0900949 }
950 }
951}
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900952
953/// Implementation of `IVirtualMachineService`, the entry point of the AIDL service.
954#[derive(Debug, Default)]
955struct VirtualMachineService {
956 state: Arc<Mutex<State>>,
Inseob Kimc7d28c72021-10-25 14:28:10 +0000957 cid: Cid,
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900958}
959
960impl Interface for VirtualMachineService {}
961
962impl IVirtualMachineService for VirtualMachineService {
Inseob Kimc7d28c72021-10-25 14:28:10 +0000963 fn notifyPayloadStarted(&self) -> binder::Result<()> {
964 let cid = self.cid;
Inseob Kim7f61fe72021-08-20 20:50:47 +0900965 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
966 info!("VM having CID {} started payload", cid);
Andrew Walbran6b650662021-09-07 13:13:23 +0000967 vm.update_payload_state(PayloadState::Started)
968 .map_err(|e| new_binder_exception(ExceptionCode::ILLEGAL_STATE, e.to_string()))?;
Inseob Kim7f61fe72021-08-20 20:50:47 +0900969 let stream = vm.stream.lock().unwrap().take();
970 vm.callbacks.notify_payload_started(cid, stream);
971 Ok(())
972 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +0900973 error!("notifyPayloadStarted is called from an unknown CID {}", cid);
Inseob Kim7f61fe72021-08-20 20:50:47 +0900974 Err(new_binder_exception(
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900975 ExceptionCode::SERVICE_SPECIFIC,
Jooyung Handd0a1732021-11-23 15:26:20 +0900976 format!("cannot find a VM with CID {}", cid),
Inseob Kim7f61fe72021-08-20 20:50:47 +0900977 ))
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900978 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900979 }
Inseob Kim2444af92021-08-31 01:22:50 +0900980
Inseob Kimc7d28c72021-10-25 14:28:10 +0000981 fn notifyPayloadReady(&self) -> binder::Result<()> {
982 let cid = self.cid;
Inseob Kim14cb8692021-08-31 21:50:39 +0900983 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
984 info!("VM having CID {} payload is ready", cid);
Andrew Walbran6b650662021-09-07 13:13:23 +0000985 vm.update_payload_state(PayloadState::Ready)
986 .map_err(|e| new_binder_exception(ExceptionCode::ILLEGAL_STATE, e.to_string()))?;
Inseob Kim14cb8692021-08-31 21:50:39 +0900987 vm.callbacks.notify_payload_ready(cid);
988 Ok(())
989 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +0900990 error!("notifyPayloadReady is called from an unknown CID {}", cid);
Inseob Kim14cb8692021-08-31 21:50:39 +0900991 Err(new_binder_exception(
992 ExceptionCode::SERVICE_SPECIFIC,
Jooyung Handd0a1732021-11-23 15:26:20 +0900993 format!("cannot find a VM with CID {}", cid),
Inseob Kim14cb8692021-08-31 21:50:39 +0900994 ))
995 }
996 }
997
Inseob Kimc7d28c72021-10-25 14:28:10 +0000998 fn notifyPayloadFinished(&self, exit_code: i32) -> binder::Result<()> {
999 let cid = self.cid;
Inseob Kim2444af92021-08-31 01:22:50 +09001000 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
1001 info!("VM having CID {} finished payload", cid);
Andrew Walbran6b650662021-09-07 13:13:23 +00001002 vm.update_payload_state(PayloadState::Finished)
1003 .map_err(|e| new_binder_exception(ExceptionCode::ILLEGAL_STATE, e.to_string()))?;
Inseob Kim2444af92021-08-31 01:22:50 +09001004 vm.callbacks.notify_payload_finished(cid, exit_code);
1005 Ok(())
1006 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09001007 error!("notifyPayloadFinished is called from an unknown CID {}", cid);
Inseob Kim2444af92021-08-31 01:22:50 +09001008 Err(new_binder_exception(
1009 ExceptionCode::SERVICE_SPECIFIC,
Jooyung Handd0a1732021-11-23 15:26:20 +09001010 format!("cannot find a VM with CID {}", cid),
1011 ))
1012 }
1013 }
1014
1015 fn notifyError(&self, error_code: i32, message: &str) -> binder::Result<()> {
1016 let cid = self.cid;
1017 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
1018 info!("VM having CID {} encountered an error", cid);
1019 vm.update_payload_state(PayloadState::Finished)
1020 .map_err(|e| new_binder_exception(ExceptionCode::ILLEGAL_STATE, e.to_string()))?;
1021 vm.callbacks.notify_error(cid, error_code, message);
1022 Ok(())
1023 } else {
1024 error!("notifyPayloadStarted is called from an unknown CID {}", cid);
1025 Err(new_binder_exception(
1026 ExceptionCode::SERVICE_SPECIFIC,
1027 format!("cannot find a VM with CID {}", cid),
Inseob Kim2444af92021-08-31 01:22:50 +09001028 ))
1029 }
1030 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001031}
1032
1033impl VirtualMachineService {
Inseob Kimc7d28c72021-10-25 14:28:10 +00001034 // SAFETY: Service ownership is held by state, and the binder objects are threadsafe.
1035 pub unsafe extern "C" fn factory(
1036 cid: Cid,
1037 context: *mut raw::c_void,
1038 ) -> *mut binder_rpc_unstable_bindgen::AIBinder {
1039 let state_ptr = context as *mut Arc<Mutex<State>>;
1040 let state = state_ptr.as_ref().unwrap();
1041 if let Some(vm) = state.lock().unwrap().get_vm(cid) {
1042 let mut vm_service = vm.vm_service.lock().unwrap();
1043 let service = vm_service.get_or_insert_with(|| Self::new_binder(state.clone(), cid));
1044 service.as_binder().as_native_mut() as *mut binder_rpc_unstable_bindgen::AIBinder
1045 } else {
1046 error!("connection from cid={} is not from a guest VM", cid);
1047 null_mut()
1048 }
1049 }
1050
1051 fn new_binder(state: Arc<Mutex<State>>, cid: Cid) -> Strong<dyn IVirtualMachineService> {
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001052 BnVirtualMachineService::new_binder(
Inseob Kimc7d28c72021-10-25 14:28:10 +00001053 VirtualMachineService { state, cid },
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001054 BinderFeatures::default(),
1055 )
1056 }
1057}