blob: 1c881746b0e5a0d261e75850b43a06f863efdb27 [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};
Alan Stokes0cc59ee2021-09-24 11:20:34 +010021use ::binder::unstable_api::AsNative;
Jiyong Park753553b2021-07-12 21:21:09 +090022use android_os_permissions_aidl::aidl::android::os::IPermissionController;
Jooyung Han21e9b922021-06-26 04:14:16 +090023use android_system_virtualizationservice::aidl::android::system::virtualizationservice::{
Andrew Walbran6b650662021-09-07 13:13:23 +000024 DiskImage::DiskImage,
Alan Stokes0cc59ee2021-09-24 11:20:34 +010025 IVirtualMachine::{BnVirtualMachine, IVirtualMachine},
Andrew Walbran6b650662021-09-07 13:13:23 +000026 IVirtualMachineCallback::IVirtualMachineCallback,
27 IVirtualizationService::IVirtualizationService,
28 PartitionType::PartitionType,
Jiyong Parkc2a49cc2021-10-15 00:02:12 +090029 VirtualMachineAppConfig::DebugLevel::DebugLevel,
Jooyung Han21e9b922021-06-26 04:14:16 +090030 VirtualMachineAppConfig::VirtualMachineAppConfig,
31 VirtualMachineConfig::VirtualMachineConfig,
Andrew Walbran6b650662021-09-07 13:13:23 +000032 VirtualMachineDebugInfo::VirtualMachineDebugInfo,
Jooyung Han21e9b922021-06-26 04:14:16 +090033 VirtualMachineRawConfig::VirtualMachineRawConfig,
Andrew Walbran6b650662021-09-07 13:13:23 +000034 VirtualMachineState::VirtualMachineState,
Jooyung Han21e9b922021-06-26 04:14:16 +090035};
Andrew Walbranf6bf6862021-05-21 12:41:13 +000036use android_system_virtualizationservice::binder::{
Shikha Panward8e35422021-10-11 13:51:27 +000037 self, BinderFeatures, ExceptionCode, Interface, ParcelFileDescriptor, Status, StatusCode, Strong,
Alan Stokes0cc59ee2021-09-24 11:20:34 +010038 ThreadState,
Andrew Walbrana89fc132021-03-17 17:08:36 +000039};
Alan Stokes0cc59ee2021-09-24 11:20:34 +010040use android_system_virtualmachineservice::aidl::android::system::virtualmachineservice::{
41 IVirtualMachineService::{
42 BnVirtualMachineService, IVirtualMachineService, VM_BINDER_SERVICE_PORT,
43 VM_STREAM_SERVICE_PORT,
44 },
Inseob Kim1b95f2e2021-08-19 13:17:40 +090045};
Jiyong Parkd50a0242021-09-16 21:00:14 +090046use anyhow::{anyhow, bail, Context, Result};
Alan Stokes0cc59ee2021-09-24 11:20:34 +010047use binder_common::{lazy_service::LazyServiceGuard, new_binder_exception};
Andrew Walbrandfc953d2021-06-10 13:59:56 +000048use disk::QcowFile;
Alan Stokes0cc59ee2021-09-24 11:20:34 +010049use idsig::{HashAlgorithm, V4Signature};
50use log::{debug, error, info, warn};
Andrew Walbrancc0db522021-07-12 17:03:42 +000051use microdroid_payload_config::VmPayloadConfig;
Jiyong Parkd50a0242021-09-16 21:00:14 +090052use rustutils::system_properties;
Andrew Walbrandff3b942021-06-09 15:20:36 +000053use std::convert::TryInto;
Shikha Panward8e35422021-10-11 13:51:27 +000054use std::ffi::CStr;
Alan Stokes0cc59ee2021-09-24 11:20:34 +010055use std::fs::{create_dir, File, OpenOptions};
Jiyong Park9dd389e2021-08-23 20:42:59 +090056use std::io::{Error, ErrorKind, Write};
Andrew Walbranb15cd6e2021-07-05 16:38:07 +000057use std::num::NonZeroU32;
Inseob Kimc7d28c72021-10-25 14:28:10 +000058use std::os::raw;
Andrew Walbrand3a84182021-09-07 14:48:52 +000059use std::os::unix::io::{FromRawFd, IntoRawFd};
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000060use std::path::{Path, PathBuf};
Inseob Kimc7d28c72021-10-25 14:28:10 +000061use std::ptr::null_mut;
Andrew Walbran320b5602021-03-04 16:11:12 +000062use std::sync::{Arc, Mutex, Weak};
Andrew Walbrancc0db522021-07-12 17:03:42 +000063use vmconfig::VmConfig;
Inseob Kim7f61fe72021-08-20 20:50:47 +090064use vsock::{SockAddr, VsockListener, VsockStream};
Jooyung Han35edb8f2021-07-01 16:17:16 +090065use zip::ZipArchive;
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000066
Andrew Walbranf6bf6862021-05-21 12:41:13 +000067pub const BINDER_SERVICE_IDENTIFIER: &str = "android.system.virtualizationservice";
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000068
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000069/// Directory in which to write disk image files used while running VMs.
Andrew Walbran488bd072021-07-14 13:29:51 +000070pub const TEMPORARY_DIRECTORY: &str = "/data/misc/virtualizationservice";
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000071
Jiyong Park8611a6c2021-07-09 18:17:44 +090072/// The CID representing the host VM
73const VMADDR_CID_HOST: u32 = 2;
74
Jooyung Han95884632021-07-06 22:27:54 +090075/// The size of zero.img.
76/// Gaps in composite disk images are filled with a shared zero.img.
77const ZERO_FILLER_SIZE: u64 = 4096;
78
Jiyong Park9dd389e2021-08-23 20:42:59 +090079/// Magic string for the instance image
80const ANDROID_VM_INSTANCE_MAGIC: &str = "Android-VM-instance";
81
82/// Version of the instance image format
83const ANDROID_VM_INSTANCE_VERSION: u16 = 1;
84
Andrew Walbranf6bf6862021-05-21 12:41:13 +000085/// Implementation of `IVirtualizationService`, the entry point of the AIDL service.
Jooyung Han9900f3d2021-07-06 10:27:54 +090086#[derive(Debug, Default)]
Andrew Walbranf6bf6862021-05-21 12:41:13 +000087pub struct VirtualizationService {
Jiyong Park8611a6c2021-07-09 18:17:44 +090088 state: Arc<Mutex<State>>,
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000089}
90
Shikha Panward8e35422021-10-11 13:51:27 +000091impl Interface for VirtualizationService {
92 fn dump(&self, mut file: &File, _args: &[&CStr]) -> Result<(), StatusCode> {
93 check_permission("android.permission.DUMP").or(Err(StatusCode::PERMISSION_DENIED))?;
94 let state = &mut *self.state.lock().unwrap();
95 let vms = state.vms();
96 writeln!(file, "Running {0} VMs:", vms.len()).or(Err(StatusCode::UNKNOWN_ERROR))?;
97 for vm in vms {
98 writeln!(file, "VM CID: {}", vm.cid).or(Err(StatusCode::UNKNOWN_ERROR))?;
99 writeln!(file, "\tState: {:?}", vm.vm_state.lock().unwrap())
100 .or(Err(StatusCode::UNKNOWN_ERROR))?;
101 writeln!(file, "\tPayload state {:?}", vm.payload_state())
102 .or(Err(StatusCode::UNKNOWN_ERROR))?;
103 writeln!(file, "\tProtected: {}", vm.protected).or(Err(StatusCode::UNKNOWN_ERROR))?;
104 writeln!(file, "\ttemporary_directory: {}", vm.temporary_directory.to_string_lossy())
105 .or(Err(StatusCode::UNKNOWN_ERROR))?;
106 writeln!(file, "\trequester_uid: {}", vm.requester_uid)
107 .or(Err(StatusCode::UNKNOWN_ERROR))?;
108 writeln!(file, "\trequester_sid: {}", vm.requester_sid)
109 .or(Err(StatusCode::UNKNOWN_ERROR))?;
110 writeln!(file, "\trequester_debug_pid: {}", vm.requester_debug_pid)
111 .or(Err(StatusCode::UNKNOWN_ERROR))?;
112 }
113 Ok(())
114 }
115}
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000116
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000117impl IVirtualizationService for VirtualizationService {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000118 /// Creates (but does not start) a new VM with the given configuration, assigning it the next
119 /// available CID.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000120 ///
121 /// Returns a binder `IVirtualMachine` object referring to it, as a handle for the client.
Andrew Walbranf8d94112021-09-07 11:45:36 +0000122 fn createVm(
Andrew Walbrana89fc132021-03-17 17:08:36 +0000123 &self,
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000124 config: &VirtualMachineConfig,
Jiyong Parkb8182bb2021-10-26 22:53:08 +0900125 console_fd: Option<&ParcelFileDescriptor>,
Andrew Walbrana89fc132021-03-17 17:08:36 +0000126 log_fd: Option<&ParcelFileDescriptor>,
127 ) -> binder::Result<Strong<dyn IVirtualMachine>> {
Jiyong Park753553b2021-07-12 21:21:09 +0900128 check_manage_access()?;
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000129 let state = &mut *self.state.lock().unwrap();
Jiyong Parkb8182bb2021-10-26 22:53:08 +0900130 let mut console_fd = console_fd.map(clone_file).transpose()?;
Jiyong Parkc2a49cc2021-10-15 00:02:12 +0900131 let mut log_fd = log_fd.map(clone_file).transpose()?;
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000132 let requester_uid = ThreadState::get_calling_uid();
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000133 let requester_sid = get_calling_sid()?;
Andrew Walbran02034492021-04-13 15:05:07 +0000134 let requester_debug_pid = ThreadState::get_calling_pid();
Jiyong Parkd50a0242021-09-16 21:00:14 +0900135 let cid = next_cid().or(Err(ExceptionCode::ILLEGAL_STATE))?;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000136
137 // Counter to generate unique IDs for temporary image files.
138 let mut next_temporary_image_id = 0;
139 // Files which are referred to from composite images. These must be mapped to the crosvm
140 // child process, and not closed before it is started.
141 let mut indirect_files = vec![];
142
143 // Make directory for temporary files.
144 let temporary_directory: PathBuf = format!("{}/{}", TEMPORARY_DIRECTORY, cid).into();
145 create_dir(&temporary_directory).map_err(|e| {
146 error!(
Andrew Walbran806f1542021-06-10 14:07:12 +0000147 "Failed to create temporary directory {:?} for VM files: {}",
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000148 temporary_directory, e
149 );
Andrew Walbran806f1542021-06-10 14:07:12 +0000150 new_binder_exception(
151 ExceptionCode::SERVICE_SPECIFIC,
152 format!(
153 "Failed to create temporary directory {:?} for VM files: {}",
154 temporary_directory, e
155 ),
156 )
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000157 })?;
158
Jiyong Parkc2a49cc2021-10-15 00:02:12 +0900159 // Disable console logging if debug level != full. Note that kernel anyway doesn't use the
160 // console output when debug level != full. So, users won't be able to see the kernel
161 // output even without this overriding. This is to silence output from the bootloader which
162 // doesn't understand the bootconfig parameters.
163 if let VirtualMachineConfig::AppConfig(config) = config {
164 if config.debugLevel != DebugLevel::FULL {
Jiyong Parkb8182bb2021-10-26 22:53:08 +0900165 console_fd = None;
166 }
167 if config.debugLevel == DebugLevel::NONE {
Jiyong Parkc2a49cc2021-10-15 00:02:12 +0900168 log_fd = None;
169 }
170 }
171
Jooyung Han21e9b922021-06-26 04:14:16 +0900172 let config = match config {
Jooyung Han35edb8f2021-07-01 16:17:16 +0900173 VirtualMachineConfig::AppConfig(config) => BorrowedOrOwned::Owned(
Jooyung Han9900f3d2021-07-06 10:27:54 +0900174 load_app_config(config, &temporary_directory).map_err(|e| {
175 error!("Failed to load app config from {}: {}", &config.configPath, e);
176 new_binder_exception(
177 ExceptionCode::SERVICE_SPECIFIC,
178 format!("Failed to load app config from {}: {}", &config.configPath, e),
179 )
180 })?,
Jooyung Han35edb8f2021-07-01 16:17:16 +0900181 ),
182 VirtualMachineConfig::RawConfig(config) => BorrowedOrOwned::Borrowed(config),
Jooyung Han21e9b922021-06-26 04:14:16 +0900183 };
Jooyung Han35edb8f2021-07-01 16:17:16 +0900184 let config = config.as_ref();
Jooyung Han21e9b922021-06-26 04:14:16 +0900185
Jooyung Han95884632021-07-06 22:27:54 +0900186 let zero_filler_path = temporary_directory.join("zero.img");
Andrew Walbranfbb39d22021-07-28 17:01:25 +0000187 write_zero_filler(&zero_filler_path).map_err(|e| {
Jooyung Han95884632021-07-06 22:27:54 +0900188 error!("Failed to make composite image: {}", e);
189 new_binder_exception(
190 ExceptionCode::SERVICE_SPECIFIC,
191 format!("Failed to make composite image: {}", e),
192 )
193 })?;
Jooyung Han95884632021-07-06 22:27:54 +0900194
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000195 // Assemble disk images if needed.
196 let disks = config
197 .disks
198 .iter()
199 .map(|disk| {
200 assemble_disk_image(
201 disk,
Jooyung Han95884632021-07-06 22:27:54 +0900202 &zero_filler_path,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000203 &temporary_directory,
204 &mut next_temporary_image_id,
205 &mut indirect_files,
206 )
207 })
208 .collect::<Result<Vec<DiskFile>, _>>()?;
209
210 // Actually start the VM.
211 let crosvm_config = CrosvmConfig {
Andrew Walbran02034492021-04-13 15:05:07 +0000212 cid,
Andrew Walbrand3a84182021-09-07 14:48:52 +0000213 bootloader: maybe_clone_file(&config.bootloader)?,
214 kernel: maybe_clone_file(&config.kernel)?,
215 initrd: maybe_clone_file(&config.initrd)?,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000216 disks,
217 params: config.params.to_owned(),
Andrew Walbrancc045902021-07-27 16:06:17 +0000218 protected: config.protectedVm,
219 memory_mib: config.memoryMib.try_into().ok().and_then(NonZeroU32::new),
Jiyong Parkb8182bb2021-10-26 22:53:08 +0900220 console_fd,
Andrew Walbran02034492021-04-13 15:05:07 +0000221 log_fd,
Andrew Walbrand3a84182021-09-07 14:48:52 +0000222 indirect_files,
223 };
Andrew Walbranf8d94112021-09-07 11:45:36 +0000224 let instance = Arc::new(
225 VmInstance::new(
226 crosvm_config,
227 temporary_directory,
228 requester_uid,
229 requester_sid,
230 requester_debug_pid,
Andrew Walbran806f1542021-06-10 14:07:12 +0000231 )
Andrew Walbranf8d94112021-09-07 11:45:36 +0000232 .map_err(|e| {
233 error!("Failed to create VM with config {:?}: {}", config, e);
234 new_binder_exception(
235 ExceptionCode::SERVICE_SPECIFIC,
236 format!("Failed to create VM: {}", e),
237 )
238 })?,
239 );
Andrew Walbran320b5602021-03-04 16:11:12 +0000240 state.add_vm(Arc::downgrade(&instance));
241 Ok(VirtualMachine::create(instance))
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000242 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000243
Andrew Walbrandff3b942021-06-09 15:20:36 +0000244 /// Initialise an empty partition image of the given size to be used as a writable partition.
245 fn initializeWritablePartition(
246 &self,
247 image_fd: &ParcelFileDescriptor,
248 size: i64,
Jiyong Park9dd389e2021-08-23 20:42:59 +0900249 partition_type: PartitionType,
Andrew Walbrandff3b942021-06-09 15:20:36 +0000250 ) -> binder::Result<()> {
Jiyong Park753553b2021-07-12 21:21:09 +0900251 check_manage_access()?;
Andrew Walbrandfc953d2021-06-10 13:59:56 +0000252 let size = size.try_into().map_err(|e| {
Andrew Walbran806f1542021-06-10 14:07:12 +0000253 new_binder_exception(
254 ExceptionCode::ILLEGAL_ARGUMENT,
255 format!("Invalid size {}: {}", size, e),
256 )
Andrew Walbrandff3b942021-06-09 15:20:36 +0000257 })?;
Andrew Walbrandfc953d2021-06-10 13:59:56 +0000258 let image = clone_file(image_fd)?;
Jooyung Han1edd5b92021-10-28 10:58:05 +0900259 // initialize the file. Any data in the file will be erased.
260 image.set_len(0).map_err(|e| {
261 new_binder_exception(
262 ExceptionCode::SERVICE_SPECIFIC,
263 format!("Failed to reset a file: {}", e),
264 )
265 })?;
Jiyong Park9dd389e2021-08-23 20:42:59 +0900266 let mut part = QcowFile::new(image, size).map_err(|e| {
Andrew Walbran806f1542021-06-10 14:07:12 +0000267 new_binder_exception(
268 ExceptionCode::SERVICE_SPECIFIC,
269 format!("Failed to create QCOW2 image: {}", e),
270 )
Andrew Walbrandfc953d2021-06-10 13:59:56 +0000271 })?;
Andrew Walbrandff3b942021-06-09 15:20:36 +0000272
Jiyong Park9dd389e2021-08-23 20:42:59 +0900273 match partition_type {
274 PartitionType::RAW => Ok(()),
275 PartitionType::ANDROID_VM_INSTANCE => format_as_android_vm_instance(&mut part),
276 _ => Err(Error::new(
277 ErrorKind::Unsupported,
278 format!("Unsupported partition type {:?}", partition_type),
279 )),
280 }
281 .map_err(|e| {
282 new_binder_exception(
283 ExceptionCode::SERVICE_SPECIFIC,
284 format!("Failed to initialize partition as {:?}: {}", partition_type, e),
285 )
286 })?;
287
Andrew Walbrandff3b942021-06-09 15:20:36 +0000288 Ok(())
289 }
290
Jiyong Park0a248432021-08-20 23:32:39 +0900291 /// Creates or update the idsig file by digesting the input APK file.
292 fn createOrUpdateIdsigFile(
293 &self,
294 input_fd: &ParcelFileDescriptor,
295 idsig_fd: &ParcelFileDescriptor,
296 ) -> binder::Result<()> {
297 // TODO(b/193504400): do this only when (1) idsig_fd is empty or (2) the APK digest in
298 // idsig_fd is different from APK digest in input_fd
299
300 let mut input = clone_file(input_fd)?;
301 let mut sig = V4Signature::create(&mut input, 4096, &[], HashAlgorithm::SHA256).unwrap();
302
303 let mut output = clone_file(idsig_fd)?;
304 output.set_len(0).unwrap();
305 sig.write_into(&mut output).unwrap();
306 Ok(())
307 }
308
Andrew Walbran320b5602021-03-04 16:11:12 +0000309 /// Get a list of all currently running VMs. This method is only intended for debug purposes,
310 /// and as such is only permitted from the shell user.
311 fn debugListVms(&self) -> binder::Result<Vec<VirtualMachineDebugInfo>> {
Andrew Walbran806f1542021-06-10 14:07:12 +0000312 check_debug_access()?;
Andrew Walbran320b5602021-03-04 16:11:12 +0000313
314 let state = &mut *self.state.lock().unwrap();
315 let vms = state.vms();
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000316 let cids = vms
317 .into_iter()
318 .map(|vm| VirtualMachineDebugInfo {
319 cid: vm.cid as i32,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000320 temporaryDirectory: vm.temporary_directory.to_string_lossy().to_string(),
Andrew Walbran1ef19ae2021-04-07 11:31:57 +0000321 requesterUid: vm.requester_uid as i32,
322 requesterSid: vm.requester_sid.clone(),
Andrew Walbran02034492021-04-13 15:05:07 +0000323 requesterPid: vm.requester_debug_pid,
Andrew Walbran6b650662021-09-07 13:13:23 +0000324 state: get_state(&vm),
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000325 })
326 .collect();
Andrew Walbran320b5602021-03-04 16:11:12 +0000327 Ok(cids)
328 }
David Brazdil3c2ddef2021-03-18 13:09:57 +0000329
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000330 /// Hold a strong reference to a VM in VirtualizationService. This method is only intended for
331 /// debug purposes, and as such is only permitted from the shell user.
Andrei Homescu1415c132021-03-24 02:39:55 +0000332 fn debugHoldVmRef(&self, vmref: &Strong<dyn IVirtualMachine>) -> binder::Result<()> {
Andrew Walbran806f1542021-06-10 14:07:12 +0000333 check_debug_access()?;
David Brazdil3c2ddef2021-03-18 13:09:57 +0000334
David Brazdil3c2ddef2021-03-18 13:09:57 +0000335 let state = &mut *self.state.lock().unwrap();
Andrei Homescu1415c132021-03-24 02:39:55 +0000336 state.debug_hold_vm(vmref.clone());
David Brazdil3c2ddef2021-03-18 13:09:57 +0000337 Ok(())
338 }
339
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000340 /// Drop reference to a VM that is being held by VirtualizationService. Returns the reference if
341 /// the VM was found and None otherwise. This method is only intended for debug purposes, and as
342 /// such is only permitted from the shell user.
David Brazdil3c2ddef2021-03-18 13:09:57 +0000343 fn debugDropVmRef(&self, cid: i32) -> binder::Result<Option<Strong<dyn IVirtualMachine>>> {
Andrew Walbran806f1542021-06-10 14:07:12 +0000344 check_debug_access()?;
David Brazdil3c2ddef2021-03-18 13:09:57 +0000345
346 let state = &mut *self.state.lock().unwrap();
347 Ok(state.debug_drop_vm(cid))
348 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000349}
350
Jiyong Park8611a6c2021-07-09 18:17:44 +0900351impl VirtualizationService {
352 pub fn init() -> VirtualizationService {
353 let service = VirtualizationService::default();
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900354
355 // server for payload output
Jiyong Park8611a6c2021-07-09 18:17:44 +0900356 let state = service.state.clone(); // reference to state (not the state itself) is copied
357 std::thread::spawn(move || {
Inseob Kim7f61fe72021-08-20 20:50:47 +0900358 handle_stream_connection_from_vm(state).unwrap();
Jiyong Park8611a6c2021-07-09 18:17:44 +0900359 });
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900360
361 // binder server for vm
Inseob Kimc7d28c72021-10-25 14:28:10 +0000362 let mut state = service.state.clone(); // reference to state (not the state itself) is copied
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900363 std::thread::spawn(move || {
Inseob Kimc7d28c72021-10-25 14:28:10 +0000364 let state_ptr = &mut state as *mut _ as *mut raw::c_void;
365
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900366 debug!("virtual machine service is starting as an RPC service.");
Inseob Kimc7d28c72021-10-25 14:28:10 +0000367 // SAFETY: factory function is only ever called by RunRpcServerWithFactory, within the
368 // lifetime of the state, with context taking the pointer value above (so a properly
369 // aligned non-null pointer to an initialized instance).
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900370 let retval = unsafe {
Inseob Kimc7d28c72021-10-25 14:28:10 +0000371 binder_rpc_unstable_bindgen::RunRpcServerWithFactory(
372 Some(VirtualMachineService::factory),
373 state_ptr,
Inseob Kimd0587562021-09-01 21:27:32 +0900374 VM_BINDER_SERVICE_PORT as u32,
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900375 )
376 };
377 if retval {
378 debug!("RPC server has shut down gracefully");
379 } else {
380 bail!("Premature termination of RPC server");
381 }
382
383 Ok(retval)
384 });
Jiyong Park8611a6c2021-07-09 18:17:44 +0900385 service
386 }
387}
388
Andrew Walbran6b650662021-09-07 13:13:23 +0000389/// Waits for incoming connections from VM. If a new connection is made, stores the stream in the
390/// corresponding `VmInstance`.
Inseob Kim7f61fe72021-08-20 20:50:47 +0900391fn handle_stream_connection_from_vm(state: Arc<Mutex<State>>) -> Result<()> {
Inseob Kimd0587562021-09-01 21:27:32 +0900392 let listener =
393 VsockListener::bind_with_cid_port(VMADDR_CID_HOST, VM_STREAM_SERVICE_PORT as u32)?;
Jiyong Park8611a6c2021-07-09 18:17:44 +0900394 for stream in listener.incoming() {
395 let stream = match stream {
396 Err(e) => {
397 warn!("invalid incoming connection: {}", e);
398 continue;
399 }
400 Ok(s) => s,
401 };
402 if let Ok(SockAddr::Vsock(addr)) = stream.peer_addr() {
403 let cid = addr.cid();
404 let port = addr.port();
Inseob Kim7f61fe72021-08-20 20:50:47 +0900405 info!("payload stream connected from cid={}, port={}", cid, port);
Jiyong Park8611a6c2021-07-09 18:17:44 +0900406 if let Some(vm) = state.lock().unwrap().get_vm(cid) {
Chris Wailes8bbb8932021-09-10 14:14:19 -0700407 *vm.stream.lock().unwrap() = Some(stream);
Inseob Kim7f61fe72021-08-20 20:50:47 +0900408 } else {
409 error!("connection from cid={} is not from a guest VM", cid);
Jiyong Park8611a6c2021-07-09 18:17:44 +0900410 }
411 }
412 }
413 Ok(())
414}
415
Andrew Walbranfbb39d22021-07-28 17:01:25 +0000416fn write_zero_filler(zero_filler_path: &Path) -> Result<()> {
Jooyung Han95884632021-07-06 22:27:54 +0900417 let file = OpenOptions::new()
418 .create_new(true)
419 .read(true)
420 .write(true)
421 .open(zero_filler_path)
422 .with_context(|| "Failed to create zero.img")?;
423 file.set_len(ZERO_FILLER_SIZE)?;
Andrew Walbranfbb39d22021-07-28 17:01:25 +0000424 Ok(())
Jooyung Han95884632021-07-06 22:27:54 +0900425}
426
Jiyong Park9dd389e2021-08-23 20:42:59 +0900427fn format_as_android_vm_instance(part: &mut dyn Write) -> std::io::Result<()> {
428 part.write_all(ANDROID_VM_INSTANCE_MAGIC.as_bytes())?;
429 part.write_all(&ANDROID_VM_INSTANCE_VERSION.to_le_bytes())?;
430 part.flush()
431}
432
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000433/// Given the configuration for a disk image, assembles the `DiskFile` to pass to crosvm.
434///
435/// This may involve assembling a composite disk from a set of partition images.
436fn assemble_disk_image(
437 disk: &DiskImage,
Jooyung Han95884632021-07-06 22:27:54 +0900438 zero_filler_path: &Path,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000439 temporary_directory: &Path,
440 next_temporary_image_id: &mut u64,
441 indirect_files: &mut Vec<File>,
Andrew Walbran806f1542021-06-10 14:07:12 +0000442) -> Result<DiskFile, Status> {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000443 let image = if !disk.partitions.is_empty() {
444 if disk.image.is_some() {
445 warn!("DiskImage {:?} contains both image and partitions.", disk);
Andrew Walbran806f1542021-06-10 14:07:12 +0000446 return Err(new_binder_exception(
447 ExceptionCode::ILLEGAL_ARGUMENT,
448 "DiskImage contains both image and partitions.",
449 ));
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000450 }
451
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000452 let composite_image_filenames =
453 make_composite_image_filenames(temporary_directory, next_temporary_image_id);
454 let (image, partition_files) = make_composite_image(
455 &disk.partitions,
Jooyung Han95884632021-07-06 22:27:54 +0900456 zero_filler_path,
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000457 &composite_image_filenames.composite,
458 &composite_image_filenames.header,
459 &composite_image_filenames.footer,
460 )
461 .map_err(|e| {
462 error!("Failed to make composite image with config {:?}: {}", disk, e);
463 new_binder_exception(
464 ExceptionCode::SERVICE_SPECIFIC,
465 format!("Failed to make composite image: {}", e),
466 )
467 })?;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000468
469 // Pass the file descriptors for the various partition files to crosvm when it
470 // is run.
471 indirect_files.extend(partition_files);
472
473 image
474 } else if let Some(image) = &disk.image {
475 clone_file(image)?
476 } else {
477 warn!("DiskImage {:?} didn't contain image or partitions.", disk);
Andrew Walbran806f1542021-06-10 14:07:12 +0000478 return Err(new_binder_exception(
479 ExceptionCode::ILLEGAL_ARGUMENT,
480 "DiskImage didn't contain image or partitions.",
481 ));
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000482 };
483
484 Ok(DiskFile { image, writable: disk.writable })
485}
486
Jooyung Han21e9b922021-06-26 04:14:16 +0900487fn load_app_config(
488 config: &VirtualMachineAppConfig,
489 temporary_directory: &Path,
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900490) -> Result<VirtualMachineRawConfig> {
Andrew Walbrancc0db522021-07-12 17:03:42 +0000491 let apk_file = clone_file(config.apk.as_ref().unwrap())?;
492 let idsig_file = clone_file(config.idsig.as_ref().unwrap())?;
Jiyong Park8d081812021-07-23 17:45:04 +0900493 let instance_file = clone_file(config.instanceImage.as_ref().unwrap())?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900494 let config_path = &config.configPath;
495
Andrew Walbrancc0db522021-07-12 17:03:42 +0000496 let mut apk_zip = ZipArchive::new(&apk_file)?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900497 let config_file = apk_zip.by_name(config_path)?;
498 let vm_payload_config: VmPayloadConfig = serde_json::from_reader(config_file)?;
499
500 let os_name = &vm_payload_config.os.name;
Andrew Walbrancc0db522021-07-12 17:03:42 +0000501
Jooyung Han35edb8f2021-07-01 16:17:16 +0900502 // For now, the only supported "os" value is "microdroid"
503 if os_name != "microdroid" {
Andrew Walbrancc0db522021-07-12 17:03:42 +0000504 bail!("Unknown OS \"{}\"", os_name);
Jooyung Han35edb8f2021-07-01 16:17:16 +0900505 }
Andrew Walbrancc0db522021-07-12 17:03:42 +0000506
507 // It is safe to construct a filename based on the os_name because we've already checked that it
508 // is one of the allowed values.
Jooyung Han21e9b922021-06-26 04:14:16 +0900509 let vm_config_path = PathBuf::from(format!("/apex/com.android.virt/etc/{}.json", os_name));
510 let vm_config_file = File::open(vm_config_path)?;
Andrew Walbrancc0db522021-07-12 17:03:42 +0000511 let mut vm_config = VmConfig::load(&vm_config_file)?.to_parcelable()?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900512
Andrew Walbrancc045902021-07-27 16:06:17 +0000513 if config.memoryMib > 0 {
514 vm_config.memoryMib = config.memoryMib;
Andrew Walbran45bcb0c2021-07-14 15:02:06 +0000515 }
516
Andrew Walbrancc0db522021-07-12 17:03:42 +0000517 // Microdroid requires an additional payload disk image and the bootconfig partition.
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900518 if os_name == "microdroid" {
Andrew Walbrancc0db522021-07-12 17:03:42 +0000519 add_microdroid_images(
520 config,
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900521 temporary_directory,
Andrew Walbrancc0db522021-07-12 17:03:42 +0000522 apk_file,
523 idsig_file,
Jiyong Park8d081812021-07-23 17:45:04 +0900524 instance_file,
Jooyung Han5dc42172021-10-05 16:43:47 +0900525 &vm_payload_config,
Andrew Walbrancc0db522021-07-12 17:03:42 +0000526 &mut vm_config,
527 )?;
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900528 }
Jooyung Han21e9b922021-06-26 04:14:16 +0900529
Andrew Walbrancc0db522021-07-12 17:03:42 +0000530 Ok(vm_config)
Jooyung Han21e9b922021-06-26 04:14:16 +0900531}
532
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000533/// Generates a unique filename to use for a composite disk image.
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000534fn make_composite_image_filenames(
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000535 temporary_directory: &Path,
536 next_temporary_image_id: &mut u64,
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000537) -> CompositeImageFilenames {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000538 let id = *next_temporary_image_id;
539 *next_temporary_image_id += 1;
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000540 CompositeImageFilenames {
541 composite: temporary_directory.join(format!("composite-{}.img", id)),
542 header: temporary_directory.join(format!("composite-{}-header.img", id)),
543 footer: temporary_directory.join(format!("composite-{}-footer.img", id)),
544 }
545}
546
547/// Filenames for a composite disk image, including header and footer partitions.
548#[derive(Clone, Debug, Eq, PartialEq)]
549struct CompositeImageFilenames {
550 /// The composite disk image itself.
551 composite: PathBuf,
552 /// The header partition image.
553 header: PathBuf,
554 /// The footer partition image.
555 footer: PathBuf,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000556}
557
558/// Gets the calling SID of the current Binder thread.
Andrew Walbran806f1542021-06-10 14:07:12 +0000559fn get_calling_sid() -> Result<String, Status> {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000560 ThreadState::with_calling_sid(|sid| {
561 if let Some(sid) = sid {
562 match sid.to_str() {
563 Ok(sid) => Ok(sid.to_owned()),
564 Err(e) => {
Andrew Walbran806f1542021-06-10 14:07:12 +0000565 error!("SID was not valid UTF-8: {}", e);
566 Err(new_binder_exception(
567 ExceptionCode::ILLEGAL_ARGUMENT,
568 format!("SID was not valid UTF-8: {}", e),
569 ))
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000570 }
571 }
572 } else {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000573 error!("Missing SID on createVm");
574 Err(new_binder_exception(ExceptionCode::SECURITY, "Missing SID on createVm"))
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000575 }
576 })
577}
578
Jiyong Park753553b2021-07-12 21:21:09 +0900579/// Checks whether the caller has a specific permission
580fn check_permission(perm: &str) -> binder::Result<()> {
581 let calling_pid = ThreadState::get_calling_pid();
582 let calling_uid = ThreadState::get_calling_uid();
583 // Root can do anything
584 if calling_uid == 0 {
585 return Ok(());
586 }
587 let perm_svc: Strong<dyn IPermissionController::IPermissionController> =
588 binder::get_interface("permission")?;
589 if perm_svc.checkPermission(perm, calling_pid, calling_uid as i32)? {
Andrew Walbran806f1542021-06-10 14:07:12 +0000590 Ok(())
591 } else {
Jiyong Park753553b2021-07-12 21:21:09 +0900592 Err(new_binder_exception(
593 ExceptionCode::SECURITY,
594 format!("does not have the {} permission", perm),
595 ))
Andrew Walbran806f1542021-06-10 14:07:12 +0000596 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000597}
598
Jiyong Park753553b2021-07-12 21:21:09 +0900599/// Check whether the caller of the current Binder method is allowed to call debug methods.
600fn check_debug_access() -> binder::Result<()> {
601 check_permission("android.permission.DEBUG_VIRTUAL_MACHINE")
602}
603
604/// Check whether the caller of the current Binder method is allowed to manage VMs
605fn check_manage_access() -> binder::Result<()> {
606 check_permission("android.permission.MANAGE_VIRTUAL_MACHINE")
607}
608
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000609/// Implementation of the AIDL `IVirtualMachine` interface. Used as a handle to a VM.
610#[derive(Debug)]
611struct VirtualMachine {
612 instance: Arc<VmInstance>,
Alan Stokes0cc59ee2021-09-24 11:20:34 +0100613 /// Keeps our service process running as long as this VM instance exists.
614 lazy_service_guard: LazyServiceGuard,
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000615}
616
617impl VirtualMachine {
618 fn create(instance: Arc<VmInstance>) -> Strong<dyn IVirtualMachine> {
Alan Stokes0cc59ee2021-09-24 11:20:34 +0100619 let binder = VirtualMachine { instance, lazy_service_guard: Default::default() };
Andrew Walbran4de28782021-04-13 14:51:43 +0000620 BnVirtualMachine::new_binder(binder, BinderFeatures::default())
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000621 }
622}
623
624impl Interface for VirtualMachine {}
625
626impl IVirtualMachine for VirtualMachine {
627 fn getCid(&self) -> binder::Result<i32> {
Jiyong Park753553b2021-07-12 21:21:09 +0900628 // Don't check permission. The owner of the VM might have passed this binder object to
629 // others.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000630 Ok(self.instance.cid as i32)
631 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000632
Andrew Walbran6b650662021-09-07 13:13:23 +0000633 fn getState(&self) -> binder::Result<VirtualMachineState> {
Jiyong Park753553b2021-07-12 21:21:09 +0900634 // Don't check permission. The owner of the VM might have passed this binder object to
635 // others.
Andrew Walbran6b650662021-09-07 13:13:23 +0000636 Ok(get_state(&self.instance))
Andrew Walbrandae07162021-03-12 17:05:20 +0000637 }
638
639 fn registerCallback(
640 &self,
641 callback: &Strong<dyn IVirtualMachineCallback>,
642 ) -> binder::Result<()> {
Jiyong Park753553b2021-07-12 21:21:09 +0900643 // Don't check permission. The owner of the VM might have passed this binder object to
644 // others.
645 //
Andrew Walbrandae07162021-03-12 17:05:20 +0000646 // TODO: Should this give an error if the VM is already dead?
647 self.instance.callbacks.add(callback.clone());
648 Ok(())
649 }
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000650
Andrew Walbranf8d94112021-09-07 11:45:36 +0000651 fn start(&self) -> binder::Result<()> {
652 self.instance.start().map_err(|e| {
653 error!("Error starting VM with CID {}: {:?}", self.instance.cid, e);
654 new_binder_exception(ExceptionCode::SERVICE_SPECIFIC, e.to_string())
655 })
656 }
657
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000658 fn connectVsock(&self, port: i32) -> binder::Result<ParcelFileDescriptor> {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000659 if !matches!(&*self.instance.vm_state.lock().unwrap(), VmState::Running { .. }) {
660 return Err(new_binder_exception(ExceptionCode::SERVICE_SPECIFIC, "VM is not running"));
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000661 }
662 let stream =
663 VsockStream::connect_with_cid_port(self.instance.cid, port as u32).map_err(|e| {
664 new_binder_exception(
665 ExceptionCode::SERVICE_SPECIFIC,
666 format!("Failed to connect: {}", e),
667 )
668 })?;
669 Ok(vsock_stream_to_pfd(stream))
670 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000671}
672
673impl Drop for VirtualMachine {
674 fn drop(&mut self) {
675 debug!("Dropping {:?}", self);
676 self.instance.kill();
677 }
678}
679
680/// A set of Binders to be called back in response to various events on the VM, such as when it
681/// dies.
682#[derive(Debug, Default)]
683pub struct VirtualMachineCallbacks(Mutex<Vec<Strong<dyn IVirtualMachineCallback>>>);
684
685impl VirtualMachineCallbacks {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900686 /// Call all registered callbacks to notify that the payload has started.
Inseob Kim7f61fe72021-08-20 20:50:47 +0900687 pub fn notify_payload_started(&self, cid: Cid, stream: Option<VsockStream>) {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900688 let callbacks = &*self.0.lock().unwrap();
Inseob Kim7f61fe72021-08-20 20:50:47 +0900689 let pfd = stream.map(vsock_stream_to_pfd);
Jiyong Park8611a6c2021-07-09 18:17:44 +0900690 for callback in callbacks {
Inseob Kim7f61fe72021-08-20 20:50:47 +0900691 if let Err(e) = callback.onPayloadStarted(cid as i32, pfd.as_ref()) {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900692 error!("Error notifying payload start event from VM CID {}: {}", cid, e);
693 }
694 }
695 }
696
Inseob Kim14cb8692021-08-31 21:50:39 +0900697 /// Call all registered callbacks to notify that the payload is ready to serve.
698 pub fn notify_payload_ready(&self, cid: Cid) {
699 let callbacks = &*self.0.lock().unwrap();
700 for callback in callbacks {
701 if let Err(e) = callback.onPayloadReady(cid as i32) {
702 error!("Error notifying payload ready event from VM CID {}: {}", cid, e);
703 }
704 }
705 }
706
Inseob Kim2444af92021-08-31 01:22:50 +0900707 /// Call all registered callbacks to notify that the payload has finished.
708 pub fn notify_payload_finished(&self, cid: Cid, exit_code: i32) {
709 let callbacks = &*self.0.lock().unwrap();
710 for callback in callbacks {
711 if let Err(e) = callback.onPayloadFinished(cid as i32, exit_code) {
712 error!("Error notifying payload finish event from VM CID {}: {}", cid, e);
713 }
714 }
715 }
716
Jooyung Handd0a1732021-11-23 15:26:20 +0900717 /// Call all registered callbacks to say that the VM encountered an error.
718 pub fn notify_error(&self, cid: Cid, error_code: i32, message: &str) {
719 let callbacks = &*self.0.lock().unwrap();
720 for callback in callbacks {
721 if let Err(e) = callback.onError(cid as i32, error_code, message) {
722 error!("Error notifying error event from VM CID {}: {}", cid, e);
723 }
724 }
725 }
726
Andrew Walbrandae07162021-03-12 17:05:20 +0000727 /// Call all registered callbacks to say that the VM has died.
728 pub fn callback_on_died(&self, cid: Cid) {
729 let callbacks = &*self.0.lock().unwrap();
730 for callback in callbacks {
731 if let Err(e) = callback.onDied(cid as i32) {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900732 error!("Error notifying exit of VM CID {}: {}", cid, e);
Andrew Walbrandae07162021-03-12 17:05:20 +0000733 }
734 }
735 }
736
737 /// Add a new callback to the set.
738 fn add(&self, callback: Strong<dyn IVirtualMachineCallback>) {
739 self.0.lock().unwrap().push(callback);
740 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000741}
742
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000743/// The mutable state of the VirtualizationService. There should only be one instance of this
744/// struct.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000745#[derive(Debug)]
746struct State {
Andrew Walbran320b5602021-03-04 16:11:12 +0000747 /// The VMs which have been started. When VMs are started a weak reference is added to this list
748 /// while a strong reference is returned to the caller over Binder. Once all copies of the
749 /// Binder client are dropped the weak reference here will become invalid, and will be removed
750 /// from the list opportunistically the next time `add_vm` is called.
751 vms: Vec<Weak<VmInstance>>,
David Brazdil3c2ddef2021-03-18 13:09:57 +0000752
753 /// Vector of strong VM references held on behalf of users that cannot hold them themselves.
754 /// This is only used for debugging purposes.
755 debug_held_vms: Vec<Strong<dyn IVirtualMachine>>,
Andrew Walbran320b5602021-03-04 16:11:12 +0000756}
757
758impl State {
Andrew Walbrandae07162021-03-12 17:05:20 +0000759 /// Get a list of VMs which still have Binder references to them.
Andrew Walbran320b5602021-03-04 16:11:12 +0000760 fn vms(&self) -> Vec<Arc<VmInstance>> {
761 // Attempt to upgrade the weak pointers to strong pointers.
762 self.vms.iter().filter_map(Weak::upgrade).collect()
763 }
764
765 /// Add a new VM to the list.
766 fn add_vm(&mut self, vm: Weak<VmInstance>) {
767 // Garbage collect any entries from the stored list which no longer exist.
768 self.vms.retain(|vm| vm.strong_count() > 0);
769
770 // Actually add the new VM.
771 self.vms.push(vm);
772 }
David Brazdil3c2ddef2021-03-18 13:09:57 +0000773
Jiyong Park8611a6c2021-07-09 18:17:44 +0900774 /// Get a VM that corresponds to the given cid
775 fn get_vm(&self, cid: Cid) -> Option<Arc<VmInstance>> {
776 self.vms().into_iter().find(|vm| vm.cid == cid)
777 }
778
David Brazdil3c2ddef2021-03-18 13:09:57 +0000779 /// Store a strong VM reference.
780 fn debug_hold_vm(&mut self, vm: Strong<dyn IVirtualMachine>) {
781 self.debug_held_vms.push(vm);
782 }
783
784 /// Retrieve and remove a strong VM reference.
785 fn debug_drop_vm(&mut self, cid: i32) -> Option<Strong<dyn IVirtualMachine>> {
786 let pos = self.debug_held_vms.iter().position(|vm| vm.getCid() == Ok(cid))?;
Alan Stokes7e54e292021-09-09 11:37:56 +0100787 let vm = self.debug_held_vms.swap_remove(pos);
Alan Stokes7e54e292021-09-09 11:37:56 +0100788 Some(vm)
David Brazdil3c2ddef2021-03-18 13:09:57 +0000789 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000790}
791
792impl Default for State {
793 fn default() -> Self {
Jiyong Parkd50a0242021-09-16 21:00:14 +0900794 State { vms: vec![], debug_held_vms: vec![] }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000795 }
796}
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000797
Jiyong Parkd50a0242021-09-16 21:00:14 +0900798/// Get the next available CID, or an error if we have run out. The last CID used is stored in
799/// a system property so that restart of virtualizationservice doesn't reuse CID while the host
800/// Android is up.
801fn next_cid() -> Result<Cid> {
802 let next = if let Ok(val) = system_properties::read(SYSPROP_LAST_CID) {
803 if let Ok(num) = val.parse::<u32>() {
804 num.checked_add(1).ok_or_else(|| anyhow!("run out of CID"))?
805 } else {
806 error!("Invalid last CID {}. Using {}", &val, FIRST_GUEST_CID);
807 FIRST_GUEST_CID
808 }
809 } else {
810 // First VM since the boot
811 FIRST_GUEST_CID
812 };
813 // Persist the last value for next use
814 let str_val = format!("{}", next);
815 system_properties::write(SYSPROP_LAST_CID, &str_val)?;
816 Ok(next)
817}
818
Andrew Walbran6b650662021-09-07 13:13:23 +0000819/// Gets the `VirtualMachineState` of the given `VmInstance`.
820fn get_state(instance: &VmInstance) -> VirtualMachineState {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000821 match &*instance.vm_state.lock().unwrap() {
822 VmState::NotStarted { .. } => VirtualMachineState::NOT_STARTED,
823 VmState::Running { .. } => match instance.payload_state() {
Andrew Walbran6b650662021-09-07 13:13:23 +0000824 PayloadState::Starting => VirtualMachineState::STARTING,
825 PayloadState::Started => VirtualMachineState::STARTED,
826 PayloadState::Ready => VirtualMachineState::READY,
827 PayloadState::Finished => VirtualMachineState::FINISHED,
Andrew Walbranf8d94112021-09-07 11:45:36 +0000828 },
829 VmState::Dead => VirtualMachineState::DEAD,
830 VmState::Failed => VirtualMachineState::DEAD,
Andrew Walbran6b650662021-09-07 13:13:23 +0000831 }
832}
833
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000834/// Converts a `&ParcelFileDescriptor` to a `File` by cloning the file.
Andrew Walbran806f1542021-06-10 14:07:12 +0000835fn clone_file(file: &ParcelFileDescriptor) -> Result<File, Status> {
836 file.as_ref().try_clone().map_err(|e| {
837 new_binder_exception(
838 ExceptionCode::BAD_PARCELABLE,
839 format!("Failed to clone File from ParcelFileDescriptor: {}", e),
840 )
841 })
842}
843
Andrew Walbrand3a84182021-09-07 14:48:52 +0000844/// Converts an `&Option<ParcelFileDescriptor>` to an `Option<File>` by cloning the file.
845fn maybe_clone_file(file: &Option<ParcelFileDescriptor>) -> Result<Option<File>, Status> {
846 file.as_ref().map(clone_file).transpose()
847}
848
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000849/// Converts a `VsockStream` to a `ParcelFileDescriptor`.
850fn vsock_stream_to_pfd(stream: VsockStream) -> ParcelFileDescriptor {
851 // SAFETY: ownership is transferred from stream to f
852 let f = unsafe { File::from_raw_fd(stream.into_raw_fd()) };
853 ParcelFileDescriptor::new(f)
854}
855
Jooyung Han35edb8f2021-07-01 16:17:16 +0900856/// Simple utility for referencing Borrowed or Owned. Similar to std::borrow::Cow, but
857/// it doesn't require that T implements Clone.
858enum BorrowedOrOwned<'a, T> {
859 Borrowed(&'a T),
860 Owned(T),
861}
862
863impl<'a, T> AsRef<T> for BorrowedOrOwned<'a, T> {
864 fn as_ref(&self) -> &T {
865 match self {
866 Self::Borrowed(b) => b,
Chris Wailes68c39f82021-07-27 16:03:44 -0700867 Self::Owned(o) => o,
Jooyung Han35edb8f2021-07-01 16:17:16 +0900868 }
869 }
870}
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900871
872/// Implementation of `IVirtualMachineService`, the entry point of the AIDL service.
873#[derive(Debug, Default)]
874struct VirtualMachineService {
875 state: Arc<Mutex<State>>,
Inseob Kimc7d28c72021-10-25 14:28:10 +0000876 cid: Cid,
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900877}
878
879impl Interface for VirtualMachineService {}
880
881impl IVirtualMachineService for VirtualMachineService {
Inseob Kimc7d28c72021-10-25 14:28:10 +0000882 fn notifyPayloadStarted(&self) -> binder::Result<()> {
883 let cid = self.cid;
Inseob Kim7f61fe72021-08-20 20:50:47 +0900884 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
885 info!("VM having CID {} started payload", cid);
Andrew Walbran6b650662021-09-07 13:13:23 +0000886 vm.update_payload_state(PayloadState::Started)
887 .map_err(|e| new_binder_exception(ExceptionCode::ILLEGAL_STATE, e.to_string()))?;
Inseob Kim7f61fe72021-08-20 20:50:47 +0900888 let stream = vm.stream.lock().unwrap().take();
889 vm.callbacks.notify_payload_started(cid, stream);
890 Ok(())
891 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +0900892 error!("notifyPayloadStarted is called from an unknown CID {}", cid);
Inseob Kim7f61fe72021-08-20 20:50:47 +0900893 Err(new_binder_exception(
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900894 ExceptionCode::SERVICE_SPECIFIC,
Jooyung Handd0a1732021-11-23 15:26:20 +0900895 format!("cannot find a VM with CID {}", cid),
Inseob Kim7f61fe72021-08-20 20:50:47 +0900896 ))
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900897 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900898 }
Inseob Kim2444af92021-08-31 01:22:50 +0900899
Inseob Kimc7d28c72021-10-25 14:28:10 +0000900 fn notifyPayloadReady(&self) -> binder::Result<()> {
901 let cid = self.cid;
Inseob Kim14cb8692021-08-31 21:50:39 +0900902 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
903 info!("VM having CID {} payload is ready", cid);
Andrew Walbran6b650662021-09-07 13:13:23 +0000904 vm.update_payload_state(PayloadState::Ready)
905 .map_err(|e| new_binder_exception(ExceptionCode::ILLEGAL_STATE, e.to_string()))?;
Inseob Kim14cb8692021-08-31 21:50:39 +0900906 vm.callbacks.notify_payload_ready(cid);
907 Ok(())
908 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +0900909 error!("notifyPayloadReady is called from an unknown CID {}", cid);
Inseob Kim14cb8692021-08-31 21:50:39 +0900910 Err(new_binder_exception(
911 ExceptionCode::SERVICE_SPECIFIC,
Jooyung Handd0a1732021-11-23 15:26:20 +0900912 format!("cannot find a VM with CID {}", cid),
Inseob Kim14cb8692021-08-31 21:50:39 +0900913 ))
914 }
915 }
916
Inseob Kimc7d28c72021-10-25 14:28:10 +0000917 fn notifyPayloadFinished(&self, exit_code: i32) -> binder::Result<()> {
918 let cid = self.cid;
Inseob Kim2444af92021-08-31 01:22:50 +0900919 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
920 info!("VM having CID {} finished payload", cid);
Andrew Walbran6b650662021-09-07 13:13:23 +0000921 vm.update_payload_state(PayloadState::Finished)
922 .map_err(|e| new_binder_exception(ExceptionCode::ILLEGAL_STATE, e.to_string()))?;
Inseob Kim2444af92021-08-31 01:22:50 +0900923 vm.callbacks.notify_payload_finished(cid, exit_code);
924 Ok(())
925 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +0900926 error!("notifyPayloadFinished is called from an unknown CID {}", cid);
Inseob Kim2444af92021-08-31 01:22:50 +0900927 Err(new_binder_exception(
928 ExceptionCode::SERVICE_SPECIFIC,
Jooyung Handd0a1732021-11-23 15:26:20 +0900929 format!("cannot find a VM with CID {}", cid),
930 ))
931 }
932 }
933
934 fn notifyError(&self, error_code: i32, message: &str) -> binder::Result<()> {
935 let cid = self.cid;
936 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
937 info!("VM having CID {} encountered an error", cid);
938 vm.update_payload_state(PayloadState::Finished)
939 .map_err(|e| new_binder_exception(ExceptionCode::ILLEGAL_STATE, e.to_string()))?;
940 vm.callbacks.notify_error(cid, error_code, message);
941 Ok(())
942 } else {
943 error!("notifyPayloadStarted is called from an unknown CID {}", cid);
944 Err(new_binder_exception(
945 ExceptionCode::SERVICE_SPECIFIC,
946 format!("cannot find a VM with CID {}", cid),
Inseob Kim2444af92021-08-31 01:22:50 +0900947 ))
948 }
949 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900950}
951
952impl VirtualMachineService {
Inseob Kimc7d28c72021-10-25 14:28:10 +0000953 // SAFETY: Service ownership is held by state, and the binder objects are threadsafe.
954 pub unsafe extern "C" fn factory(
955 cid: Cid,
956 context: *mut raw::c_void,
957 ) -> *mut binder_rpc_unstable_bindgen::AIBinder {
958 let state_ptr = context as *mut Arc<Mutex<State>>;
959 let state = state_ptr.as_ref().unwrap();
960 if let Some(vm) = state.lock().unwrap().get_vm(cid) {
961 let mut vm_service = vm.vm_service.lock().unwrap();
962 let service = vm_service.get_or_insert_with(|| Self::new_binder(state.clone(), cid));
963 service.as_binder().as_native_mut() as *mut binder_rpc_unstable_bindgen::AIBinder
964 } else {
965 error!("connection from cid={} is not from a guest VM", cid);
966 null_mut()
967 }
968 }
969
970 fn new_binder(state: Arc<Mutex<State>>, cid: Cid) -> Strong<dyn IVirtualMachineService> {
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900971 BnVirtualMachineService::new_binder(
Inseob Kimc7d28c72021-10-25 14:28:10 +0000972 VirtualMachineService { state, cid },
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900973 BinderFeatures::default(),
974 )
975 }
976}