blob: c2642700ff91c86588ea391806fbfe1f1b5a965a [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 Walbran6b650662021-09-07 13:13:23 +000025 DiskImage::DiskImage,
Alan Stokes0cc59ee2021-09-24 11:20:34 +010026 IVirtualMachine::{BnVirtualMachine, IVirtualMachine},
Andrew Walbran6b650662021-09-07 13:13:23 +000027 IVirtualMachineCallback::IVirtualMachineCallback,
28 IVirtualizationService::IVirtualizationService,
Jiyong Park029977d2021-11-24 21:56:49 +090029 Partition::Partition,
Andrew Walbran6b650662021-09-07 13:13:23 +000030 PartitionType::PartitionType,
Jiyong Parkc2a49cc2021-10-15 00:02:12 +090031 VirtualMachineAppConfig::DebugLevel::DebugLevel,
Jooyung Han21e9b922021-06-26 04:14:16 +090032 VirtualMachineAppConfig::VirtualMachineAppConfig,
33 VirtualMachineConfig::VirtualMachineConfig,
Andrew Walbran6b650662021-09-07 13:13:23 +000034 VirtualMachineDebugInfo::VirtualMachineDebugInfo,
Jooyung Han21e9b922021-06-26 04:14:16 +090035 VirtualMachineRawConfig::VirtualMachineRawConfig,
Andrew Walbran6b650662021-09-07 13:13:23 +000036 VirtualMachineState::VirtualMachineState,
Jooyung Han21e9b922021-06-26 04:14:16 +090037};
Andrew Walbranf6bf6862021-05-21 12:41:13 +000038use android_system_virtualizationservice::binder::{
Shikha Panward8e35422021-10-11 13:51:27 +000039 self, BinderFeatures, ExceptionCode, Interface, ParcelFileDescriptor, Status, StatusCode, Strong,
Alan Stokes0cc59ee2021-09-24 11:20:34 +010040 ThreadState,
Andrew Walbrana89fc132021-03-17 17:08:36 +000041};
Alan Stokes0cc59ee2021-09-24 11:20:34 +010042use android_system_virtualmachineservice::aidl::android::system::virtualmachineservice::{
43 IVirtualMachineService::{
44 BnVirtualMachineService, IVirtualMachineService, VM_BINDER_SERVICE_PORT,
45 VM_STREAM_SERVICE_PORT,
46 },
Inseob Kim1b95f2e2021-08-19 13:17:40 +090047};
Jiyong Parkd50a0242021-09-16 21:00:14 +090048use anyhow::{anyhow, bail, Context, Result};
Alan Stokes0cc59ee2021-09-24 11:20:34 +010049use binder_common::{lazy_service::LazyServiceGuard, new_binder_exception};
Andrew Walbrandfc953d2021-06-10 13:59:56 +000050use disk::QcowFile;
Alan Stokes0cc59ee2021-09-24 11:20:34 +010051use idsig::{HashAlgorithm, V4Signature};
Jiyong Parkd2dc83f2021-12-20 18:40:52 +090052use kvm::{Kvm, Cap};
Alan Stokes0cc59ee2021-09-24 11:20:34 +010053use log::{debug, error, info, warn};
Andrew Walbrancc0db522021-07-12 17:03:42 +000054use microdroid_payload_config::VmPayloadConfig;
Jiyong Parkd50a0242021-09-16 21:00:14 +090055use rustutils::system_properties;
Andrew Walbrandff3b942021-06-09 15:20:36 +000056use std::convert::TryInto;
Shikha Panward8e35422021-10-11 13:51:27 +000057use std::ffi::CStr;
Alan Stokes0cc59ee2021-09-24 11:20:34 +010058use std::fs::{create_dir, File, OpenOptions};
Jiyong Park9dd389e2021-08-23 20:42:59 +090059use std::io::{Error, ErrorKind, Write};
Andrew Walbranb15cd6e2021-07-05 16:38:07 +000060use std::num::NonZeroU32;
Inseob Kimc7d28c72021-10-25 14:28:10 +000061use std::os::raw;
Andrew Walbrand3a84182021-09-07 14:48:52 +000062use std::os::unix::io::{FromRawFd, IntoRawFd};
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000063use std::path::{Path, PathBuf};
Inseob Kimc7d28c72021-10-25 14:28:10 +000064use std::ptr::null_mut;
Andrew Walbran320b5602021-03-04 16:11:12 +000065use std::sync::{Arc, Mutex, Weak};
Andrew Walbrancc0db522021-07-12 17:03:42 +000066use vmconfig::VmConfig;
Inseob Kim7f61fe72021-08-20 20:50:47 +090067use vsock::{SockAddr, VsockListener, VsockStream};
Jooyung Han35edb8f2021-07-01 16:17:16 +090068use zip::ZipArchive;
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000069
Andrew Walbranf6bf6862021-05-21 12:41:13 +000070pub const BINDER_SERVICE_IDENTIFIER: &str = "android.system.virtualizationservice";
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000071
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000072/// Directory in which to write disk image files used while running VMs.
Andrew Walbran488bd072021-07-14 13:29:51 +000073pub const TEMPORARY_DIRECTORY: &str = "/data/misc/virtualizationservice";
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000074
Jiyong Park8611a6c2021-07-09 18:17:44 +090075/// The CID representing the host VM
76const VMADDR_CID_HOST: u32 = 2;
77
Jooyung Han95884632021-07-06 22:27:54 +090078/// The size of zero.img.
79/// Gaps in composite disk images are filled with a shared zero.img.
80const ZERO_FILLER_SIZE: u64 = 4096;
81
Jiyong Park9dd389e2021-08-23 20:42:59 +090082/// Magic string for the instance image
83const ANDROID_VM_INSTANCE_MAGIC: &str = "Android-VM-instance";
84
85/// Version of the instance image format
86const ANDROID_VM_INSTANCE_VERSION: u16 = 1;
87
Andrew Walbranf6bf6862021-05-21 12:41:13 +000088/// Implementation of `IVirtualizationService`, the entry point of the AIDL service.
Jooyung Han9900f3d2021-07-06 10:27:54 +090089#[derive(Debug, Default)]
Andrew Walbranf6bf6862021-05-21 12:41:13 +000090pub struct VirtualizationService {
Jiyong Park8611a6c2021-07-09 18:17:44 +090091 state: Arc<Mutex<State>>,
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000092}
93
Shikha Panward8e35422021-10-11 13:51:27 +000094impl Interface for VirtualizationService {
95 fn dump(&self, mut file: &File, _args: &[&CStr]) -> Result<(), StatusCode> {
96 check_permission("android.permission.DUMP").or(Err(StatusCode::PERMISSION_DENIED))?;
97 let state = &mut *self.state.lock().unwrap();
98 let vms = state.vms();
99 writeln!(file, "Running {0} VMs:", vms.len()).or(Err(StatusCode::UNKNOWN_ERROR))?;
100 for vm in vms {
101 writeln!(file, "VM CID: {}", vm.cid).or(Err(StatusCode::UNKNOWN_ERROR))?;
102 writeln!(file, "\tState: {:?}", vm.vm_state.lock().unwrap())
103 .or(Err(StatusCode::UNKNOWN_ERROR))?;
104 writeln!(file, "\tPayload state {:?}", vm.payload_state())
105 .or(Err(StatusCode::UNKNOWN_ERROR))?;
106 writeln!(file, "\tProtected: {}", vm.protected).or(Err(StatusCode::UNKNOWN_ERROR))?;
107 writeln!(file, "\ttemporary_directory: {}", vm.temporary_directory.to_string_lossy())
108 .or(Err(StatusCode::UNKNOWN_ERROR))?;
109 writeln!(file, "\trequester_uid: {}", vm.requester_uid)
110 .or(Err(StatusCode::UNKNOWN_ERROR))?;
111 writeln!(file, "\trequester_sid: {}", vm.requester_sid)
112 .or(Err(StatusCode::UNKNOWN_ERROR))?;
113 writeln!(file, "\trequester_debug_pid: {}", vm.requester_debug_pid)
114 .or(Err(StatusCode::UNKNOWN_ERROR))?;
115 }
116 Ok(())
117 }
118}
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000119
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000120impl IVirtualizationService for VirtualizationService {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000121 /// Creates (but does not start) a new VM with the given configuration, assigning it the next
122 /// available CID.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000123 ///
124 /// Returns a binder `IVirtualMachine` object referring to it, as a handle for the client.
Andrew Walbranf8d94112021-09-07 11:45:36 +0000125 fn createVm(
Andrew Walbrana89fc132021-03-17 17:08:36 +0000126 &self,
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000127 config: &VirtualMachineConfig,
Jiyong Parkb8182bb2021-10-26 22:53:08 +0900128 console_fd: Option<&ParcelFileDescriptor>,
Andrew Walbrana89fc132021-03-17 17:08:36 +0000129 log_fd: Option<&ParcelFileDescriptor>,
130 ) -> binder::Result<Strong<dyn IVirtualMachine>> {
Jiyong Park753553b2021-07-12 21:21:09 +0900131 check_manage_access()?;
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000132 let state = &mut *self.state.lock().unwrap();
Jiyong Parkb8182bb2021-10-26 22:53:08 +0900133 let mut console_fd = console_fd.map(clone_file).transpose()?;
Jiyong Parkc2a49cc2021-10-15 00:02:12 +0900134 let mut log_fd = log_fd.map(clone_file).transpose()?;
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000135 let requester_uid = ThreadState::get_calling_uid();
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000136 let requester_sid = get_calling_sid()?;
Andrew Walbran02034492021-04-13 15:05:07 +0000137 let requester_debug_pid = ThreadState::get_calling_pid();
Jiyong Parkd50a0242021-09-16 21:00:14 +0900138 let cid = next_cid().or(Err(ExceptionCode::ILLEGAL_STATE))?;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000139
140 // Counter to generate unique IDs for temporary image files.
141 let mut next_temporary_image_id = 0;
142 // Files which are referred to from composite images. These must be mapped to the crosvm
143 // child process, and not closed before it is started.
144 let mut indirect_files = vec![];
145
146 // Make directory for temporary files.
147 let temporary_directory: PathBuf = format!("{}/{}", TEMPORARY_DIRECTORY, cid).into();
148 create_dir(&temporary_directory).map_err(|e| {
149 error!(
Andrew Walbran806f1542021-06-10 14:07:12 +0000150 "Failed to create temporary directory {:?} for VM files: {}",
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000151 temporary_directory, e
152 );
Andrew Walbran806f1542021-06-10 14:07:12 +0000153 new_binder_exception(
154 ExceptionCode::SERVICE_SPECIFIC,
155 format!(
156 "Failed to create temporary directory {:?} for VM files: {}",
157 temporary_directory, e
158 ),
159 )
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000160 })?;
161
Jiyong Parkc2a49cc2021-10-15 00:02:12 +0900162 // Disable console logging if debug level != full. Note that kernel anyway doesn't use the
163 // console output when debug level != full. So, users won't be able to see the kernel
164 // output even without this overriding. This is to silence output from the bootloader which
165 // doesn't understand the bootconfig parameters.
166 if let VirtualMachineConfig::AppConfig(config) = config {
167 if config.debugLevel != DebugLevel::FULL {
Jiyong Parkb8182bb2021-10-26 22:53:08 +0900168 console_fd = None;
169 }
170 if config.debugLevel == DebugLevel::NONE {
Jiyong Parkc2a49cc2021-10-15 00:02:12 +0900171 log_fd = None;
172 }
173 }
174
Jiyong Park029977d2021-11-24 21:56:49 +0900175 let is_app_config = matches!(config, VirtualMachineConfig::AppConfig(_));
Jiyong Parkd2dc83f2021-12-20 18:40:52 +0900176 let is_debug_level_full = matches!(
177 config,
178 VirtualMachineConfig::AppConfig(VirtualMachineAppConfig {
179 debugLevel: DebugLevel::FULL,
180 ..
181 })
182 );
Jiyong Park029977d2021-11-24 21:56:49 +0900183
Jooyung Han21e9b922021-06-26 04:14:16 +0900184 let config = match config {
Jooyung Han35edb8f2021-07-01 16:17:16 +0900185 VirtualMachineConfig::AppConfig(config) => BorrowedOrOwned::Owned(
Jooyung Han9900f3d2021-07-06 10:27:54 +0900186 load_app_config(config, &temporary_directory).map_err(|e| {
187 error!("Failed to load app config from {}: {}", &config.configPath, e);
188 new_binder_exception(
189 ExceptionCode::SERVICE_SPECIFIC,
190 format!("Failed to load app config from {}: {}", &config.configPath, e),
191 )
192 })?,
Jooyung Han35edb8f2021-07-01 16:17:16 +0900193 ),
194 VirtualMachineConfig::RawConfig(config) => BorrowedOrOwned::Borrowed(config),
Jooyung Han21e9b922021-06-26 04:14:16 +0900195 };
Jooyung Han35edb8f2021-07-01 16:17:16 +0900196 let config = config.as_ref();
Jooyung Han21e9b922021-06-26 04:14:16 +0900197
Jiyong Park029977d2021-11-24 21:56:49 +0900198 // Check if partition images are labeled incorrectly. This is to prevent random images
199 // which are not protected by the Android Verified Boot (e.g. bits downloaded by apps) from
200 // being loaded in a pVM. Specifically, for images in the raw config, nothing is allowed
201 // to be labeled as app_data_file. For images in the app config, nothing but the instance
202 // partition is allowed to be labeled as such.
203 config
204 .disks
205 .iter()
206 .flat_map(|disk| disk.partitions.iter())
207 .filter(|partition| {
208 if is_app_config {
209 partition.label != "vm-instance"
210 } else {
211 true // all partitions are checked
212 }
213 })
214 .try_for_each(check_label_for_partition)
215 .map_err(|e| new_binder_exception(ExceptionCode::SERVICE_SPECIFIC, e.to_string()))?;
216
Jooyung Han95884632021-07-06 22:27:54 +0900217 let zero_filler_path = temporary_directory.join("zero.img");
Andrew Walbranfbb39d22021-07-28 17:01:25 +0000218 write_zero_filler(&zero_filler_path).map_err(|e| {
Jooyung Han95884632021-07-06 22:27:54 +0900219 error!("Failed to make composite image: {}", e);
220 new_binder_exception(
221 ExceptionCode::SERVICE_SPECIFIC,
222 format!("Failed to make composite image: {}", e),
223 )
224 })?;
Jooyung Han95884632021-07-06 22:27:54 +0900225
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000226 // Assemble disk images if needed.
227 let disks = config
228 .disks
229 .iter()
230 .map(|disk| {
231 assemble_disk_image(
232 disk,
Jooyung Han95884632021-07-06 22:27:54 +0900233 &zero_filler_path,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000234 &temporary_directory,
235 &mut next_temporary_image_id,
236 &mut indirect_files,
237 )
238 })
239 .collect::<Result<Vec<DiskFile>, _>>()?;
240
Jiyong Parkd2dc83f2021-12-20 18:40:52 +0900241 let protected_vm_supported = Kvm::new()
242 .map_err(|e| new_binder_exception(ExceptionCode::SERVICE_SPECIFIC, e.to_string()))?
243 .check_extension(Cap::ArmProtectedVm);
244 let protected = config.protectedVm && protected_vm_supported;
245 if config.protectedVm && !protected_vm_supported {
246 warn!("Protected VM was requested, but it isn't supported on this machine. Ignored.");
247 }
248
249 // And force run in non-protected mode when debug level is FULL
250 let protected = if is_debug_level_full {
251 if protected {
252 warn!("VM will run in FULL debug level. Running in non-protected mode");
253 }
254 false
255 } else {
256 protected
257 };
258
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000259 // Actually start the VM.
260 let crosvm_config = CrosvmConfig {
Andrew Walbran02034492021-04-13 15:05:07 +0000261 cid,
Andrew Walbrand3a84182021-09-07 14:48:52 +0000262 bootloader: maybe_clone_file(&config.bootloader)?,
263 kernel: maybe_clone_file(&config.kernel)?,
264 initrd: maybe_clone_file(&config.initrd)?,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000265 disks,
266 params: config.params.to_owned(),
Jiyong Parkd2dc83f2021-12-20 18:40:52 +0900267 protected,
Andrew Walbrancc045902021-07-27 16:06:17 +0000268 memory_mib: config.memoryMib.try_into().ok().and_then(NonZeroU32::new),
Jiyong Park032615f2022-01-10 13:55:34 +0900269 cpus: config.numCpus.try_into().ok().and_then(NonZeroU32::new),
270 cpu_affinity: config.cpuAffinity.clone(),
Jiyong Parkb8182bb2021-10-26 22:53:08 +0900271 console_fd,
Andrew Walbran02034492021-04-13 15:05:07 +0000272 log_fd,
Andrew Walbrand3a84182021-09-07 14:48:52 +0000273 indirect_files,
274 };
Andrew Walbranf8d94112021-09-07 11:45:36 +0000275 let instance = Arc::new(
276 VmInstance::new(
277 crosvm_config,
278 temporary_directory,
279 requester_uid,
280 requester_sid,
281 requester_debug_pid,
Andrew Walbran806f1542021-06-10 14:07:12 +0000282 )
Andrew Walbranf8d94112021-09-07 11:45:36 +0000283 .map_err(|e| {
284 error!("Failed to create VM with config {:?}: {}", config, e);
285 new_binder_exception(
286 ExceptionCode::SERVICE_SPECIFIC,
287 format!("Failed to create VM: {}", e),
288 )
289 })?,
290 );
Andrew Walbran320b5602021-03-04 16:11:12 +0000291 state.add_vm(Arc::downgrade(&instance));
292 Ok(VirtualMachine::create(instance))
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000293 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000294
Andrew Walbrandff3b942021-06-09 15:20:36 +0000295 /// Initialise an empty partition image of the given size to be used as a writable partition.
296 fn initializeWritablePartition(
297 &self,
298 image_fd: &ParcelFileDescriptor,
299 size: i64,
Jiyong Park9dd389e2021-08-23 20:42:59 +0900300 partition_type: PartitionType,
Andrew Walbrandff3b942021-06-09 15:20:36 +0000301 ) -> binder::Result<()> {
Jiyong Park753553b2021-07-12 21:21:09 +0900302 check_manage_access()?;
Andrew Walbrandfc953d2021-06-10 13:59:56 +0000303 let size = size.try_into().map_err(|e| {
Andrew Walbran806f1542021-06-10 14:07:12 +0000304 new_binder_exception(
305 ExceptionCode::ILLEGAL_ARGUMENT,
306 format!("Invalid size {}: {}", size, e),
307 )
Andrew Walbrandff3b942021-06-09 15:20:36 +0000308 })?;
Andrew Walbrandfc953d2021-06-10 13:59:56 +0000309 let image = clone_file(image_fd)?;
Jooyung Han1edd5b92021-10-28 10:58:05 +0900310 // initialize the file. Any data in the file will be erased.
311 image.set_len(0).map_err(|e| {
312 new_binder_exception(
313 ExceptionCode::SERVICE_SPECIFIC,
314 format!("Failed to reset a file: {}", e),
315 )
316 })?;
Jiyong Park9dd389e2021-08-23 20:42:59 +0900317 let mut part = QcowFile::new(image, size).map_err(|e| {
Andrew Walbran806f1542021-06-10 14:07:12 +0000318 new_binder_exception(
319 ExceptionCode::SERVICE_SPECIFIC,
320 format!("Failed to create QCOW2 image: {}", e),
321 )
Andrew Walbrandfc953d2021-06-10 13:59:56 +0000322 })?;
Andrew Walbrandff3b942021-06-09 15:20:36 +0000323
Jiyong Park9dd389e2021-08-23 20:42:59 +0900324 match partition_type {
325 PartitionType::RAW => Ok(()),
326 PartitionType::ANDROID_VM_INSTANCE => format_as_android_vm_instance(&mut part),
327 _ => Err(Error::new(
328 ErrorKind::Unsupported,
329 format!("Unsupported partition type {:?}", partition_type),
330 )),
331 }
332 .map_err(|e| {
333 new_binder_exception(
334 ExceptionCode::SERVICE_SPECIFIC,
335 format!("Failed to initialize partition as {:?}: {}", partition_type, e),
336 )
337 })?;
338
Andrew Walbrandff3b942021-06-09 15:20:36 +0000339 Ok(())
340 }
341
Jiyong Park0a248432021-08-20 23:32:39 +0900342 /// Creates or update the idsig file by digesting the input APK file.
343 fn createOrUpdateIdsigFile(
344 &self,
345 input_fd: &ParcelFileDescriptor,
346 idsig_fd: &ParcelFileDescriptor,
347 ) -> binder::Result<()> {
348 // TODO(b/193504400): do this only when (1) idsig_fd is empty or (2) the APK digest in
349 // idsig_fd is different from APK digest in input_fd
350
351 let mut input = clone_file(input_fd)?;
352 let mut sig = V4Signature::create(&mut input, 4096, &[], HashAlgorithm::SHA256).unwrap();
353
354 let mut output = clone_file(idsig_fd)?;
355 output.set_len(0).unwrap();
356 sig.write_into(&mut output).unwrap();
357 Ok(())
358 }
359
Andrew Walbran320b5602021-03-04 16:11:12 +0000360 /// Get a list of all currently running VMs. This method is only intended for debug purposes,
361 /// and as such is only permitted from the shell user.
362 fn debugListVms(&self) -> binder::Result<Vec<VirtualMachineDebugInfo>> {
Andrew Walbran806f1542021-06-10 14:07:12 +0000363 check_debug_access()?;
Andrew Walbran320b5602021-03-04 16:11:12 +0000364
365 let state = &mut *self.state.lock().unwrap();
366 let vms = state.vms();
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000367 let cids = vms
368 .into_iter()
369 .map(|vm| VirtualMachineDebugInfo {
370 cid: vm.cid as i32,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000371 temporaryDirectory: vm.temporary_directory.to_string_lossy().to_string(),
Andrew Walbran1ef19ae2021-04-07 11:31:57 +0000372 requesterUid: vm.requester_uid as i32,
373 requesterSid: vm.requester_sid.clone(),
Andrew Walbran02034492021-04-13 15:05:07 +0000374 requesterPid: vm.requester_debug_pid,
Andrew Walbran6b650662021-09-07 13:13:23 +0000375 state: get_state(&vm),
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000376 })
377 .collect();
Andrew Walbran320b5602021-03-04 16:11:12 +0000378 Ok(cids)
379 }
David Brazdil3c2ddef2021-03-18 13:09:57 +0000380
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000381 /// Hold a strong reference to a VM in VirtualizationService. This method is only intended for
382 /// debug purposes, and as such is only permitted from the shell user.
Andrei Homescu1415c132021-03-24 02:39:55 +0000383 fn debugHoldVmRef(&self, vmref: &Strong<dyn IVirtualMachine>) -> binder::Result<()> {
Andrew Walbran806f1542021-06-10 14:07:12 +0000384 check_debug_access()?;
David Brazdil3c2ddef2021-03-18 13:09:57 +0000385
David Brazdil3c2ddef2021-03-18 13:09:57 +0000386 let state = &mut *self.state.lock().unwrap();
Andrei Homescu1415c132021-03-24 02:39:55 +0000387 state.debug_hold_vm(vmref.clone());
David Brazdil3c2ddef2021-03-18 13:09:57 +0000388 Ok(())
389 }
390
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000391 /// Drop reference to a VM that is being held by VirtualizationService. Returns the reference if
392 /// the VM was found and None otherwise. This method is only intended for debug purposes, and as
393 /// such is only permitted from the shell user.
David Brazdil3c2ddef2021-03-18 13:09:57 +0000394 fn debugDropVmRef(&self, cid: i32) -> binder::Result<Option<Strong<dyn IVirtualMachine>>> {
Andrew Walbran806f1542021-06-10 14:07:12 +0000395 check_debug_access()?;
David Brazdil3c2ddef2021-03-18 13:09:57 +0000396
397 let state = &mut *self.state.lock().unwrap();
398 Ok(state.debug_drop_vm(cid))
399 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000400}
401
Jiyong Park8611a6c2021-07-09 18:17:44 +0900402impl VirtualizationService {
403 pub fn init() -> VirtualizationService {
404 let service = VirtualizationService::default();
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900405
406 // server for payload output
Jiyong Park8611a6c2021-07-09 18:17:44 +0900407 let state = service.state.clone(); // reference to state (not the state itself) is copied
408 std::thread::spawn(move || {
Inseob Kim7f61fe72021-08-20 20:50:47 +0900409 handle_stream_connection_from_vm(state).unwrap();
Jiyong Park8611a6c2021-07-09 18:17:44 +0900410 });
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900411
412 // binder server for vm
Inseob Kimc7d28c72021-10-25 14:28:10 +0000413 let mut state = service.state.clone(); // reference to state (not the state itself) is copied
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900414 std::thread::spawn(move || {
Inseob Kimc7d28c72021-10-25 14:28:10 +0000415 let state_ptr = &mut state as *mut _ as *mut raw::c_void;
416
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900417 debug!("virtual machine service is starting as an RPC service.");
Inseob Kimc7d28c72021-10-25 14:28:10 +0000418 // SAFETY: factory function is only ever called by RunRpcServerWithFactory, within the
419 // lifetime of the state, with context taking the pointer value above (so a properly
420 // aligned non-null pointer to an initialized instance).
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900421 let retval = unsafe {
Inseob Kimc7d28c72021-10-25 14:28:10 +0000422 binder_rpc_unstable_bindgen::RunRpcServerWithFactory(
423 Some(VirtualMachineService::factory),
424 state_ptr,
Inseob Kimd0587562021-09-01 21:27:32 +0900425 VM_BINDER_SERVICE_PORT as u32,
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900426 )
427 };
428 if retval {
429 debug!("RPC server has shut down gracefully");
430 } else {
431 bail!("Premature termination of RPC server");
432 }
433
434 Ok(retval)
435 });
Jiyong Park8611a6c2021-07-09 18:17:44 +0900436 service
437 }
438}
439
Andrew Walbran6b650662021-09-07 13:13:23 +0000440/// Waits for incoming connections from VM. If a new connection is made, stores the stream in the
441/// corresponding `VmInstance`.
Inseob Kim7f61fe72021-08-20 20:50:47 +0900442fn handle_stream_connection_from_vm(state: Arc<Mutex<State>>) -> Result<()> {
Inseob Kimd0587562021-09-01 21:27:32 +0900443 let listener =
444 VsockListener::bind_with_cid_port(VMADDR_CID_HOST, VM_STREAM_SERVICE_PORT as u32)?;
Jiyong Park8611a6c2021-07-09 18:17:44 +0900445 for stream in listener.incoming() {
446 let stream = match stream {
447 Err(e) => {
448 warn!("invalid incoming connection: {}", e);
449 continue;
450 }
451 Ok(s) => s,
452 };
453 if let Ok(SockAddr::Vsock(addr)) = stream.peer_addr() {
454 let cid = addr.cid();
455 let port = addr.port();
Inseob Kim7f61fe72021-08-20 20:50:47 +0900456 info!("payload stream connected from cid={}, port={}", cid, port);
Jiyong Park8611a6c2021-07-09 18:17:44 +0900457 if let Some(vm) = state.lock().unwrap().get_vm(cid) {
Chris Wailes8bbb8932021-09-10 14:14:19 -0700458 *vm.stream.lock().unwrap() = Some(stream);
Inseob Kim7f61fe72021-08-20 20:50:47 +0900459 } else {
460 error!("connection from cid={} is not from a guest VM", cid);
Jiyong Park8611a6c2021-07-09 18:17:44 +0900461 }
462 }
463 }
464 Ok(())
465}
466
Andrew Walbranfbb39d22021-07-28 17:01:25 +0000467fn write_zero_filler(zero_filler_path: &Path) -> Result<()> {
Jooyung Han95884632021-07-06 22:27:54 +0900468 let file = OpenOptions::new()
469 .create_new(true)
470 .read(true)
471 .write(true)
472 .open(zero_filler_path)
473 .with_context(|| "Failed to create zero.img")?;
474 file.set_len(ZERO_FILLER_SIZE)?;
Andrew Walbranfbb39d22021-07-28 17:01:25 +0000475 Ok(())
Jooyung Han95884632021-07-06 22:27:54 +0900476}
477
Jiyong Park9dd389e2021-08-23 20:42:59 +0900478fn format_as_android_vm_instance(part: &mut dyn Write) -> std::io::Result<()> {
479 part.write_all(ANDROID_VM_INSTANCE_MAGIC.as_bytes())?;
480 part.write_all(&ANDROID_VM_INSTANCE_VERSION.to_le_bytes())?;
481 part.flush()
482}
483
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000484/// Given the configuration for a disk image, assembles the `DiskFile` to pass to crosvm.
485///
486/// This may involve assembling a composite disk from a set of partition images.
487fn assemble_disk_image(
488 disk: &DiskImage,
Jooyung Han95884632021-07-06 22:27:54 +0900489 zero_filler_path: &Path,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000490 temporary_directory: &Path,
491 next_temporary_image_id: &mut u64,
492 indirect_files: &mut Vec<File>,
Andrew Walbran806f1542021-06-10 14:07:12 +0000493) -> Result<DiskFile, Status> {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000494 let image = if !disk.partitions.is_empty() {
495 if disk.image.is_some() {
496 warn!("DiskImage {:?} contains both image and partitions.", disk);
Andrew Walbran806f1542021-06-10 14:07:12 +0000497 return Err(new_binder_exception(
498 ExceptionCode::ILLEGAL_ARGUMENT,
499 "DiskImage contains both image and partitions.",
500 ));
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000501 }
502
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000503 let composite_image_filenames =
504 make_composite_image_filenames(temporary_directory, next_temporary_image_id);
505 let (image, partition_files) = make_composite_image(
506 &disk.partitions,
Jooyung Han95884632021-07-06 22:27:54 +0900507 zero_filler_path,
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000508 &composite_image_filenames.composite,
509 &composite_image_filenames.header,
510 &composite_image_filenames.footer,
511 )
512 .map_err(|e| {
513 error!("Failed to make composite image with config {:?}: {}", disk, e);
514 new_binder_exception(
515 ExceptionCode::SERVICE_SPECIFIC,
516 format!("Failed to make composite image: {}", e),
517 )
518 })?;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000519
520 // Pass the file descriptors for the various partition files to crosvm when it
521 // is run.
522 indirect_files.extend(partition_files);
523
524 image
525 } else if let Some(image) = &disk.image {
526 clone_file(image)?
527 } else {
528 warn!("DiskImage {:?} didn't contain image or partitions.", disk);
Andrew Walbran806f1542021-06-10 14:07:12 +0000529 return Err(new_binder_exception(
530 ExceptionCode::ILLEGAL_ARGUMENT,
531 "DiskImage didn't contain image or partitions.",
532 ));
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000533 };
534
535 Ok(DiskFile { image, writable: disk.writable })
536}
537
Jooyung Han21e9b922021-06-26 04:14:16 +0900538fn load_app_config(
539 config: &VirtualMachineAppConfig,
540 temporary_directory: &Path,
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900541) -> Result<VirtualMachineRawConfig> {
Andrew Walbrancc0db522021-07-12 17:03:42 +0000542 let apk_file = clone_file(config.apk.as_ref().unwrap())?;
543 let idsig_file = clone_file(config.idsig.as_ref().unwrap())?;
Jiyong Park8d081812021-07-23 17:45:04 +0900544 let instance_file = clone_file(config.instanceImage.as_ref().unwrap())?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900545 let config_path = &config.configPath;
546
Andrew Walbrancc0db522021-07-12 17:03:42 +0000547 let mut apk_zip = ZipArchive::new(&apk_file)?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900548 let config_file = apk_zip.by_name(config_path)?;
549 let vm_payload_config: VmPayloadConfig = serde_json::from_reader(config_file)?;
550
551 let os_name = &vm_payload_config.os.name;
Andrew Walbrancc0db522021-07-12 17:03:42 +0000552
Jooyung Han35edb8f2021-07-01 16:17:16 +0900553 // For now, the only supported "os" value is "microdroid"
554 if os_name != "microdroid" {
Andrew Walbrancc0db522021-07-12 17:03:42 +0000555 bail!("Unknown OS \"{}\"", os_name);
Jooyung Han35edb8f2021-07-01 16:17:16 +0900556 }
Andrew Walbrancc0db522021-07-12 17:03:42 +0000557
558 // It is safe to construct a filename based on the os_name because we've already checked that it
559 // is one of the allowed values.
Jooyung Han21e9b922021-06-26 04:14:16 +0900560 let vm_config_path = PathBuf::from(format!("/apex/com.android.virt/etc/{}.json", os_name));
561 let vm_config_file = File::open(vm_config_path)?;
Andrew Walbrancc0db522021-07-12 17:03:42 +0000562 let mut vm_config = VmConfig::load(&vm_config_file)?.to_parcelable()?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900563
Andrew Walbrancc045902021-07-27 16:06:17 +0000564 if config.memoryMib > 0 {
565 vm_config.memoryMib = config.memoryMib;
Andrew Walbran45bcb0c2021-07-14 15:02:06 +0000566 }
567
Jiyong Park032615f2022-01-10 13:55:34 +0900568 vm_config.numCpus = config.numCpus;
569 vm_config.cpuAffinity = config.cpuAffinity.clone();
570
Andrew Walbrancc0db522021-07-12 17:03:42 +0000571 // Microdroid requires an additional payload disk image and the bootconfig partition.
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900572 if os_name == "microdroid" {
Andrew Walbrancc0db522021-07-12 17:03:42 +0000573 add_microdroid_images(
574 config,
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900575 temporary_directory,
Andrew Walbrancc0db522021-07-12 17:03:42 +0000576 apk_file,
577 idsig_file,
Jiyong Park8d081812021-07-23 17:45:04 +0900578 instance_file,
Jooyung Han5dc42172021-10-05 16:43:47 +0900579 &vm_payload_config,
Andrew Walbrancc0db522021-07-12 17:03:42 +0000580 &mut vm_config,
581 )?;
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900582 }
Jooyung Han21e9b922021-06-26 04:14:16 +0900583
Andrew Walbrancc0db522021-07-12 17:03:42 +0000584 Ok(vm_config)
Jooyung Han21e9b922021-06-26 04:14:16 +0900585}
586
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000587/// Generates a unique filename to use for a composite disk image.
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000588fn make_composite_image_filenames(
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000589 temporary_directory: &Path,
590 next_temporary_image_id: &mut u64,
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000591) -> CompositeImageFilenames {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000592 let id = *next_temporary_image_id;
593 *next_temporary_image_id += 1;
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000594 CompositeImageFilenames {
595 composite: temporary_directory.join(format!("composite-{}.img", id)),
596 header: temporary_directory.join(format!("composite-{}-header.img", id)),
597 footer: temporary_directory.join(format!("composite-{}-footer.img", id)),
598 }
599}
600
601/// Filenames for a composite disk image, including header and footer partitions.
602#[derive(Clone, Debug, Eq, PartialEq)]
603struct CompositeImageFilenames {
604 /// The composite disk image itself.
605 composite: PathBuf,
606 /// The header partition image.
607 header: PathBuf,
608 /// The footer partition image.
609 footer: PathBuf,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000610}
611
612/// Gets the calling SID of the current Binder thread.
Andrew Walbran806f1542021-06-10 14:07:12 +0000613fn get_calling_sid() -> Result<String, Status> {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000614 ThreadState::with_calling_sid(|sid| {
615 if let Some(sid) = sid {
616 match sid.to_str() {
617 Ok(sid) => Ok(sid.to_owned()),
618 Err(e) => {
Andrew Walbran806f1542021-06-10 14:07:12 +0000619 error!("SID was not valid UTF-8: {}", e);
620 Err(new_binder_exception(
621 ExceptionCode::ILLEGAL_ARGUMENT,
622 format!("SID was not valid UTF-8: {}", e),
623 ))
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000624 }
625 }
626 } else {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000627 error!("Missing SID on createVm");
628 Err(new_binder_exception(ExceptionCode::SECURITY, "Missing SID on createVm"))
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000629 }
630 })
631}
632
Jiyong Park753553b2021-07-12 21:21:09 +0900633/// Checks whether the caller has a specific permission
634fn check_permission(perm: &str) -> binder::Result<()> {
635 let calling_pid = ThreadState::get_calling_pid();
636 let calling_uid = ThreadState::get_calling_uid();
637 // Root can do anything
638 if calling_uid == 0 {
639 return Ok(());
640 }
641 let perm_svc: Strong<dyn IPermissionController::IPermissionController> =
642 binder::get_interface("permission")?;
643 if perm_svc.checkPermission(perm, calling_pid, calling_uid as i32)? {
Andrew Walbran806f1542021-06-10 14:07:12 +0000644 Ok(())
645 } else {
Jiyong Park753553b2021-07-12 21:21:09 +0900646 Err(new_binder_exception(
647 ExceptionCode::SECURITY,
648 format!("does not have the {} permission", perm),
649 ))
Andrew Walbran806f1542021-06-10 14:07:12 +0000650 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000651}
652
Jiyong Park753553b2021-07-12 21:21:09 +0900653/// Check whether the caller of the current Binder method is allowed to call debug methods.
654fn check_debug_access() -> binder::Result<()> {
655 check_permission("android.permission.DEBUG_VIRTUAL_MACHINE")
656}
657
658/// Check whether the caller of the current Binder method is allowed to manage VMs
659fn check_manage_access() -> binder::Result<()> {
660 check_permission("android.permission.MANAGE_VIRTUAL_MACHINE")
661}
662
Jiyong Park029977d2021-11-24 21:56:49 +0900663/// Check if a partition has selinux labels that are not allowed
664fn check_label_for_partition(partition: &Partition) -> Result<()> {
665 let ctx = getfilecon(partition.image.as_ref().unwrap().as_ref())?;
666 if ctx == SeContext::new("u:object_r:app_data_file:s0").unwrap() {
667 Err(anyhow!("Partition {} shouldn't be labeled as {}", &partition.label, ctx))
668 } else {
669 Ok(())
670 }
671}
672
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000673/// Implementation of the AIDL `IVirtualMachine` interface. Used as a handle to a VM.
674#[derive(Debug)]
675struct VirtualMachine {
676 instance: Arc<VmInstance>,
Alan Stokes0cc59ee2021-09-24 11:20:34 +0100677 /// Keeps our service process running as long as this VM instance exists.
Chris Wailes641fc4a2021-12-01 15:03:21 -0800678 #[allow(dead_code)]
Alan Stokes0cc59ee2021-09-24 11:20:34 +0100679 lazy_service_guard: LazyServiceGuard,
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000680}
681
682impl VirtualMachine {
683 fn create(instance: Arc<VmInstance>) -> Strong<dyn IVirtualMachine> {
Alan Stokes0cc59ee2021-09-24 11:20:34 +0100684 let binder = VirtualMachine { instance, lazy_service_guard: Default::default() };
Andrew Walbran4de28782021-04-13 14:51:43 +0000685 BnVirtualMachine::new_binder(binder, BinderFeatures::default())
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000686 }
687}
688
689impl Interface for VirtualMachine {}
690
691impl IVirtualMachine for VirtualMachine {
692 fn getCid(&self) -> binder::Result<i32> {
Jiyong Park753553b2021-07-12 21:21:09 +0900693 // Don't check permission. The owner of the VM might have passed this binder object to
694 // others.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000695 Ok(self.instance.cid as i32)
696 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000697
Andrew Walbran6b650662021-09-07 13:13:23 +0000698 fn getState(&self) -> binder::Result<VirtualMachineState> {
Jiyong Park753553b2021-07-12 21:21:09 +0900699 // Don't check permission. The owner of the VM might have passed this binder object to
700 // others.
Andrew Walbran6b650662021-09-07 13:13:23 +0000701 Ok(get_state(&self.instance))
Andrew Walbrandae07162021-03-12 17:05:20 +0000702 }
703
704 fn registerCallback(
705 &self,
706 callback: &Strong<dyn IVirtualMachineCallback>,
707 ) -> binder::Result<()> {
Jiyong Park753553b2021-07-12 21:21:09 +0900708 // Don't check permission. The owner of the VM might have passed this binder object to
709 // others.
710 //
Andrew Walbrandae07162021-03-12 17:05:20 +0000711 // TODO: Should this give an error if the VM is already dead?
712 self.instance.callbacks.add(callback.clone());
713 Ok(())
714 }
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000715
Andrew Walbranf8d94112021-09-07 11:45:36 +0000716 fn start(&self) -> binder::Result<()> {
717 self.instance.start().map_err(|e| {
718 error!("Error starting VM with CID {}: {:?}", self.instance.cid, e);
719 new_binder_exception(ExceptionCode::SERVICE_SPECIFIC, e.to_string())
720 })
721 }
722
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000723 fn connectVsock(&self, port: i32) -> binder::Result<ParcelFileDescriptor> {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000724 if !matches!(&*self.instance.vm_state.lock().unwrap(), VmState::Running { .. }) {
725 return Err(new_binder_exception(ExceptionCode::SERVICE_SPECIFIC, "VM is not running"));
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000726 }
727 let stream =
728 VsockStream::connect_with_cid_port(self.instance.cid, port as u32).map_err(|e| {
729 new_binder_exception(
730 ExceptionCode::SERVICE_SPECIFIC,
731 format!("Failed to connect: {}", e),
732 )
733 })?;
734 Ok(vsock_stream_to_pfd(stream))
735 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000736}
737
738impl Drop for VirtualMachine {
739 fn drop(&mut self) {
740 debug!("Dropping {:?}", self);
741 self.instance.kill();
742 }
743}
744
745/// A set of Binders to be called back in response to various events on the VM, such as when it
746/// dies.
747#[derive(Debug, Default)]
748pub struct VirtualMachineCallbacks(Mutex<Vec<Strong<dyn IVirtualMachineCallback>>>);
749
750impl VirtualMachineCallbacks {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900751 /// Call all registered callbacks to notify that the payload has started.
Inseob Kim7f61fe72021-08-20 20:50:47 +0900752 pub fn notify_payload_started(&self, cid: Cid, stream: Option<VsockStream>) {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900753 let callbacks = &*self.0.lock().unwrap();
Inseob Kim7f61fe72021-08-20 20:50:47 +0900754 let pfd = stream.map(vsock_stream_to_pfd);
Jiyong Park8611a6c2021-07-09 18:17:44 +0900755 for callback in callbacks {
Inseob Kim7f61fe72021-08-20 20:50:47 +0900756 if let Err(e) = callback.onPayloadStarted(cid as i32, pfd.as_ref()) {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900757 error!("Error notifying payload start event from VM CID {}: {}", cid, e);
758 }
759 }
760 }
761
Inseob Kim14cb8692021-08-31 21:50:39 +0900762 /// Call all registered callbacks to notify that the payload is ready to serve.
763 pub fn notify_payload_ready(&self, cid: Cid) {
764 let callbacks = &*self.0.lock().unwrap();
765 for callback in callbacks {
766 if let Err(e) = callback.onPayloadReady(cid as i32) {
767 error!("Error notifying payload ready event from VM CID {}: {}", cid, e);
768 }
769 }
770 }
771
Inseob Kim2444af92021-08-31 01:22:50 +0900772 /// Call all registered callbacks to notify that the payload has finished.
773 pub fn notify_payload_finished(&self, cid: Cid, exit_code: i32) {
774 let callbacks = &*self.0.lock().unwrap();
775 for callback in callbacks {
776 if let Err(e) = callback.onPayloadFinished(cid as i32, exit_code) {
777 error!("Error notifying payload finish event from VM CID {}: {}", cid, e);
778 }
779 }
780 }
781
Jooyung Handd0a1732021-11-23 15:26:20 +0900782 /// Call all registered callbacks to say that the VM encountered an error.
783 pub fn notify_error(&self, cid: Cid, error_code: i32, message: &str) {
784 let callbacks = &*self.0.lock().unwrap();
785 for callback in callbacks {
786 if let Err(e) = callback.onError(cid as i32, error_code, message) {
787 error!("Error notifying error event from VM CID {}: {}", cid, e);
788 }
789 }
790 }
791
Andrew Walbrandae07162021-03-12 17:05:20 +0000792 /// Call all registered callbacks to say that the VM has died.
793 pub fn callback_on_died(&self, cid: Cid) {
794 let callbacks = &*self.0.lock().unwrap();
795 for callback in callbacks {
796 if let Err(e) = callback.onDied(cid as i32) {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900797 error!("Error notifying exit of VM CID {}: {}", cid, e);
Andrew Walbrandae07162021-03-12 17:05:20 +0000798 }
799 }
800 }
801
802 /// Add a new callback to the set.
803 fn add(&self, callback: Strong<dyn IVirtualMachineCallback>) {
804 self.0.lock().unwrap().push(callback);
805 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000806}
807
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000808/// The mutable state of the VirtualizationService. There should only be one instance of this
809/// struct.
Chris Wailes641fc4a2021-12-01 15:03:21 -0800810#[derive(Debug, Default)]
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000811struct State {
Andrew Walbran320b5602021-03-04 16:11:12 +0000812 /// The VMs which have been started. When VMs are started a weak reference is added to this list
813 /// while a strong reference is returned to the caller over Binder. Once all copies of the
814 /// Binder client are dropped the weak reference here will become invalid, and will be removed
815 /// from the list opportunistically the next time `add_vm` is called.
816 vms: Vec<Weak<VmInstance>>,
David Brazdil3c2ddef2021-03-18 13:09:57 +0000817
818 /// Vector of strong VM references held on behalf of users that cannot hold them themselves.
819 /// This is only used for debugging purposes.
820 debug_held_vms: Vec<Strong<dyn IVirtualMachine>>,
Andrew Walbran320b5602021-03-04 16:11:12 +0000821}
822
823impl State {
Andrew Walbrandae07162021-03-12 17:05:20 +0000824 /// Get a list of VMs which still have Binder references to them.
Andrew Walbran320b5602021-03-04 16:11:12 +0000825 fn vms(&self) -> Vec<Arc<VmInstance>> {
826 // Attempt to upgrade the weak pointers to strong pointers.
827 self.vms.iter().filter_map(Weak::upgrade).collect()
828 }
829
830 /// Add a new VM to the list.
831 fn add_vm(&mut self, vm: Weak<VmInstance>) {
832 // Garbage collect any entries from the stored list which no longer exist.
833 self.vms.retain(|vm| vm.strong_count() > 0);
834
835 // Actually add the new VM.
836 self.vms.push(vm);
837 }
David Brazdil3c2ddef2021-03-18 13:09:57 +0000838
Jiyong Park8611a6c2021-07-09 18:17:44 +0900839 /// Get a VM that corresponds to the given cid
840 fn get_vm(&self, cid: Cid) -> Option<Arc<VmInstance>> {
841 self.vms().into_iter().find(|vm| vm.cid == cid)
842 }
843
David Brazdil3c2ddef2021-03-18 13:09:57 +0000844 /// Store a strong VM reference.
845 fn debug_hold_vm(&mut self, vm: Strong<dyn IVirtualMachine>) {
846 self.debug_held_vms.push(vm);
847 }
848
849 /// Retrieve and remove a strong VM reference.
850 fn debug_drop_vm(&mut self, cid: i32) -> Option<Strong<dyn IVirtualMachine>> {
851 let pos = self.debug_held_vms.iter().position(|vm| vm.getCid() == Ok(cid))?;
Alan Stokes7e54e292021-09-09 11:37:56 +0100852 let vm = self.debug_held_vms.swap_remove(pos);
Alan Stokes7e54e292021-09-09 11:37:56 +0100853 Some(vm)
David Brazdil3c2ddef2021-03-18 13:09:57 +0000854 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000855}
856
Jiyong Parkd50a0242021-09-16 21:00:14 +0900857/// Get the next available CID, or an error if we have run out. The last CID used is stored in
858/// a system property so that restart of virtualizationservice doesn't reuse CID while the host
859/// Android is up.
860fn next_cid() -> Result<Cid> {
861 let next = if let Ok(val) = system_properties::read(SYSPROP_LAST_CID) {
862 if let Ok(num) = val.parse::<u32>() {
863 num.checked_add(1).ok_or_else(|| anyhow!("run out of CID"))?
864 } else {
865 error!("Invalid last CID {}. Using {}", &val, FIRST_GUEST_CID);
866 FIRST_GUEST_CID
867 }
868 } else {
869 // First VM since the boot
870 FIRST_GUEST_CID
871 };
872 // Persist the last value for next use
873 let str_val = format!("{}", next);
874 system_properties::write(SYSPROP_LAST_CID, &str_val)?;
875 Ok(next)
876}
877
Andrew Walbran6b650662021-09-07 13:13:23 +0000878/// Gets the `VirtualMachineState` of the given `VmInstance`.
879fn get_state(instance: &VmInstance) -> VirtualMachineState {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000880 match &*instance.vm_state.lock().unwrap() {
881 VmState::NotStarted { .. } => VirtualMachineState::NOT_STARTED,
882 VmState::Running { .. } => match instance.payload_state() {
Andrew Walbran6b650662021-09-07 13:13:23 +0000883 PayloadState::Starting => VirtualMachineState::STARTING,
884 PayloadState::Started => VirtualMachineState::STARTED,
885 PayloadState::Ready => VirtualMachineState::READY,
886 PayloadState::Finished => VirtualMachineState::FINISHED,
Andrew Walbranf8d94112021-09-07 11:45:36 +0000887 },
888 VmState::Dead => VirtualMachineState::DEAD,
889 VmState::Failed => VirtualMachineState::DEAD,
Andrew Walbran6b650662021-09-07 13:13:23 +0000890 }
891}
892
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000893/// Converts a `&ParcelFileDescriptor` to a `File` by cloning the file.
Andrew Walbran806f1542021-06-10 14:07:12 +0000894fn clone_file(file: &ParcelFileDescriptor) -> Result<File, Status> {
895 file.as_ref().try_clone().map_err(|e| {
896 new_binder_exception(
897 ExceptionCode::BAD_PARCELABLE,
898 format!("Failed to clone File from ParcelFileDescriptor: {}", e),
899 )
900 })
901}
902
Andrew Walbrand3a84182021-09-07 14:48:52 +0000903/// Converts an `&Option<ParcelFileDescriptor>` to an `Option<File>` by cloning the file.
904fn maybe_clone_file(file: &Option<ParcelFileDescriptor>) -> Result<Option<File>, Status> {
905 file.as_ref().map(clone_file).transpose()
906}
907
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000908/// Converts a `VsockStream` to a `ParcelFileDescriptor`.
909fn vsock_stream_to_pfd(stream: VsockStream) -> ParcelFileDescriptor {
910 // SAFETY: ownership is transferred from stream to f
911 let f = unsafe { File::from_raw_fd(stream.into_raw_fd()) };
912 ParcelFileDescriptor::new(f)
913}
914
Jooyung Han35edb8f2021-07-01 16:17:16 +0900915/// Simple utility for referencing Borrowed or Owned. Similar to std::borrow::Cow, but
916/// it doesn't require that T implements Clone.
917enum BorrowedOrOwned<'a, T> {
918 Borrowed(&'a T),
919 Owned(T),
920}
921
922impl<'a, T> AsRef<T> for BorrowedOrOwned<'a, T> {
923 fn as_ref(&self) -> &T {
924 match self {
925 Self::Borrowed(b) => b,
Chris Wailes68c39f82021-07-27 16:03:44 -0700926 Self::Owned(o) => o,
Jooyung Han35edb8f2021-07-01 16:17:16 +0900927 }
928 }
929}
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900930
931/// Implementation of `IVirtualMachineService`, the entry point of the AIDL service.
932#[derive(Debug, Default)]
933struct VirtualMachineService {
934 state: Arc<Mutex<State>>,
Inseob Kimc7d28c72021-10-25 14:28:10 +0000935 cid: Cid,
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900936}
937
938impl Interface for VirtualMachineService {}
939
940impl IVirtualMachineService for VirtualMachineService {
Inseob Kimc7d28c72021-10-25 14:28:10 +0000941 fn notifyPayloadStarted(&self) -> binder::Result<()> {
942 let cid = self.cid;
Inseob Kim7f61fe72021-08-20 20:50:47 +0900943 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
944 info!("VM having CID {} started payload", cid);
Andrew Walbran6b650662021-09-07 13:13:23 +0000945 vm.update_payload_state(PayloadState::Started)
946 .map_err(|e| new_binder_exception(ExceptionCode::ILLEGAL_STATE, e.to_string()))?;
Inseob Kim7f61fe72021-08-20 20:50:47 +0900947 let stream = vm.stream.lock().unwrap().take();
948 vm.callbacks.notify_payload_started(cid, stream);
949 Ok(())
950 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +0900951 error!("notifyPayloadStarted is called from an unknown CID {}", cid);
Inseob Kim7f61fe72021-08-20 20:50:47 +0900952 Err(new_binder_exception(
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900953 ExceptionCode::SERVICE_SPECIFIC,
Jooyung Handd0a1732021-11-23 15:26:20 +0900954 format!("cannot find a VM with CID {}", cid),
Inseob Kim7f61fe72021-08-20 20:50:47 +0900955 ))
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900956 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900957 }
Inseob Kim2444af92021-08-31 01:22:50 +0900958
Inseob Kimc7d28c72021-10-25 14:28:10 +0000959 fn notifyPayloadReady(&self) -> binder::Result<()> {
960 let cid = self.cid;
Inseob Kim14cb8692021-08-31 21:50:39 +0900961 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
962 info!("VM having CID {} payload is ready", cid);
Andrew Walbran6b650662021-09-07 13:13:23 +0000963 vm.update_payload_state(PayloadState::Ready)
964 .map_err(|e| new_binder_exception(ExceptionCode::ILLEGAL_STATE, e.to_string()))?;
Inseob Kim14cb8692021-08-31 21:50:39 +0900965 vm.callbacks.notify_payload_ready(cid);
966 Ok(())
967 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +0900968 error!("notifyPayloadReady is called from an unknown CID {}", cid);
Inseob Kim14cb8692021-08-31 21:50:39 +0900969 Err(new_binder_exception(
970 ExceptionCode::SERVICE_SPECIFIC,
Jooyung Handd0a1732021-11-23 15:26:20 +0900971 format!("cannot find a VM with CID {}", cid),
Inseob Kim14cb8692021-08-31 21:50:39 +0900972 ))
973 }
974 }
975
Inseob Kimc7d28c72021-10-25 14:28:10 +0000976 fn notifyPayloadFinished(&self, exit_code: i32) -> binder::Result<()> {
977 let cid = self.cid;
Inseob Kim2444af92021-08-31 01:22:50 +0900978 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
979 info!("VM having CID {} finished payload", cid);
Andrew Walbran6b650662021-09-07 13:13:23 +0000980 vm.update_payload_state(PayloadState::Finished)
981 .map_err(|e| new_binder_exception(ExceptionCode::ILLEGAL_STATE, e.to_string()))?;
Inseob Kim2444af92021-08-31 01:22:50 +0900982 vm.callbacks.notify_payload_finished(cid, exit_code);
983 Ok(())
984 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +0900985 error!("notifyPayloadFinished is called from an unknown CID {}", cid);
Inseob Kim2444af92021-08-31 01:22:50 +0900986 Err(new_binder_exception(
987 ExceptionCode::SERVICE_SPECIFIC,
Jooyung Handd0a1732021-11-23 15:26:20 +0900988 format!("cannot find a VM with CID {}", cid),
989 ))
990 }
991 }
992
993 fn notifyError(&self, error_code: i32, message: &str) -> binder::Result<()> {
994 let cid = self.cid;
995 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
996 info!("VM having CID {} encountered an error", cid);
997 vm.update_payload_state(PayloadState::Finished)
998 .map_err(|e| new_binder_exception(ExceptionCode::ILLEGAL_STATE, e.to_string()))?;
999 vm.callbacks.notify_error(cid, error_code, message);
1000 Ok(())
1001 } else {
1002 error!("notifyPayloadStarted is called from an unknown CID {}", cid);
1003 Err(new_binder_exception(
1004 ExceptionCode::SERVICE_SPECIFIC,
1005 format!("cannot find a VM with CID {}", cid),
Inseob Kim2444af92021-08-31 01:22:50 +09001006 ))
1007 }
1008 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001009}
1010
1011impl VirtualMachineService {
Inseob Kimc7d28c72021-10-25 14:28:10 +00001012 // SAFETY: Service ownership is held by state, and the binder objects are threadsafe.
1013 pub unsafe extern "C" fn factory(
1014 cid: Cid,
1015 context: *mut raw::c_void,
1016 ) -> *mut binder_rpc_unstable_bindgen::AIBinder {
1017 let state_ptr = context as *mut Arc<Mutex<State>>;
1018 let state = state_ptr.as_ref().unwrap();
1019 if let Some(vm) = state.lock().unwrap().get_vm(cid) {
1020 let mut vm_service = vm.vm_service.lock().unwrap();
1021 let service = vm_service.get_or_insert_with(|| Self::new_binder(state.clone(), cid));
1022 service.as_binder().as_native_mut() as *mut binder_rpc_unstable_bindgen::AIBinder
1023 } else {
1024 error!("connection from cid={} is not from a guest VM", cid);
1025 null_mut()
1026 }
1027 }
1028
1029 fn new_binder(state: Arc<Mutex<State>>, cid: Cid) -> Strong<dyn IVirtualMachineService> {
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001030 BnVirtualMachineService::new_binder(
Inseob Kimc7d28c72021-10-25 14:28:10 +00001031 VirtualMachineService { state, cid },
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001032 BinderFeatures::default(),
1033 )
1034 }
1035}