blob: 74a9365cfee8880188a95d00d95f0b74b4fd54fb [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)?;
Andrew Walbrandff3b942021-06-09 15:20:36 +0000259
Jiyong Park9dd389e2021-08-23 20:42:59 +0900260 let mut part = QcowFile::new(image, size).map_err(|e| {
Andrew Walbran806f1542021-06-10 14:07:12 +0000261 new_binder_exception(
262 ExceptionCode::SERVICE_SPECIFIC,
263 format!("Failed to create QCOW2 image: {}", e),
264 )
Andrew Walbrandfc953d2021-06-10 13:59:56 +0000265 })?;
Andrew Walbrandff3b942021-06-09 15:20:36 +0000266
Jiyong Park9dd389e2021-08-23 20:42:59 +0900267 match partition_type {
268 PartitionType::RAW => Ok(()),
269 PartitionType::ANDROID_VM_INSTANCE => format_as_android_vm_instance(&mut part),
270 _ => Err(Error::new(
271 ErrorKind::Unsupported,
272 format!("Unsupported partition type {:?}", partition_type),
273 )),
274 }
275 .map_err(|e| {
276 new_binder_exception(
277 ExceptionCode::SERVICE_SPECIFIC,
278 format!("Failed to initialize partition as {:?}: {}", partition_type, e),
279 )
280 })?;
281
Andrew Walbrandff3b942021-06-09 15:20:36 +0000282 Ok(())
283 }
284
Jiyong Park0a248432021-08-20 23:32:39 +0900285 /// Creates or update the idsig file by digesting the input APK file.
286 fn createOrUpdateIdsigFile(
287 &self,
288 input_fd: &ParcelFileDescriptor,
289 idsig_fd: &ParcelFileDescriptor,
290 ) -> binder::Result<()> {
291 // TODO(b/193504400): do this only when (1) idsig_fd is empty or (2) the APK digest in
292 // idsig_fd is different from APK digest in input_fd
293
294 let mut input = clone_file(input_fd)?;
295 let mut sig = V4Signature::create(&mut input, 4096, &[], HashAlgorithm::SHA256).unwrap();
296
297 let mut output = clone_file(idsig_fd)?;
298 output.set_len(0).unwrap();
299 sig.write_into(&mut output).unwrap();
300 Ok(())
301 }
302
Andrew Walbran320b5602021-03-04 16:11:12 +0000303 /// Get a list of all currently running VMs. This method is only intended for debug purposes,
304 /// and as such is only permitted from the shell user.
305 fn debugListVms(&self) -> binder::Result<Vec<VirtualMachineDebugInfo>> {
Andrew Walbran806f1542021-06-10 14:07:12 +0000306 check_debug_access()?;
Andrew Walbran320b5602021-03-04 16:11:12 +0000307
308 let state = &mut *self.state.lock().unwrap();
309 let vms = state.vms();
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000310 let cids = vms
311 .into_iter()
312 .map(|vm| VirtualMachineDebugInfo {
313 cid: vm.cid as i32,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000314 temporaryDirectory: vm.temporary_directory.to_string_lossy().to_string(),
Andrew Walbran1ef19ae2021-04-07 11:31:57 +0000315 requesterUid: vm.requester_uid as i32,
316 requesterSid: vm.requester_sid.clone(),
Andrew Walbran02034492021-04-13 15:05:07 +0000317 requesterPid: vm.requester_debug_pid,
Andrew Walbran6b650662021-09-07 13:13:23 +0000318 state: get_state(&vm),
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000319 })
320 .collect();
Andrew Walbran320b5602021-03-04 16:11:12 +0000321 Ok(cids)
322 }
David Brazdil3c2ddef2021-03-18 13:09:57 +0000323
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000324 /// Hold a strong reference to a VM in VirtualizationService. This method is only intended for
325 /// debug purposes, and as such is only permitted from the shell user.
Andrei Homescu1415c132021-03-24 02:39:55 +0000326 fn debugHoldVmRef(&self, vmref: &Strong<dyn IVirtualMachine>) -> binder::Result<()> {
Andrew Walbran806f1542021-06-10 14:07:12 +0000327 check_debug_access()?;
David Brazdil3c2ddef2021-03-18 13:09:57 +0000328
David Brazdil3c2ddef2021-03-18 13:09:57 +0000329 let state = &mut *self.state.lock().unwrap();
Andrei Homescu1415c132021-03-24 02:39:55 +0000330 state.debug_hold_vm(vmref.clone());
David Brazdil3c2ddef2021-03-18 13:09:57 +0000331 Ok(())
332 }
333
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000334 /// Drop reference to a VM that is being held by VirtualizationService. Returns the reference if
335 /// the VM was found and None otherwise. This method is only intended for debug purposes, and as
336 /// such is only permitted from the shell user.
David Brazdil3c2ddef2021-03-18 13:09:57 +0000337 fn debugDropVmRef(&self, cid: i32) -> binder::Result<Option<Strong<dyn IVirtualMachine>>> {
Andrew Walbran806f1542021-06-10 14:07:12 +0000338 check_debug_access()?;
David Brazdil3c2ddef2021-03-18 13:09:57 +0000339
340 let state = &mut *self.state.lock().unwrap();
341 Ok(state.debug_drop_vm(cid))
342 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000343}
344
Jiyong Park8611a6c2021-07-09 18:17:44 +0900345impl VirtualizationService {
346 pub fn init() -> VirtualizationService {
347 let service = VirtualizationService::default();
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900348
349 // server for payload output
Jiyong Park8611a6c2021-07-09 18:17:44 +0900350 let state = service.state.clone(); // reference to state (not the state itself) is copied
351 std::thread::spawn(move || {
Inseob Kim7f61fe72021-08-20 20:50:47 +0900352 handle_stream_connection_from_vm(state).unwrap();
Jiyong Park8611a6c2021-07-09 18:17:44 +0900353 });
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900354
355 // binder server for vm
Inseob Kimc7d28c72021-10-25 14:28:10 +0000356 let mut state = service.state.clone(); // reference to state (not the state itself) is copied
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900357 std::thread::spawn(move || {
Inseob Kimc7d28c72021-10-25 14:28:10 +0000358 let state_ptr = &mut state as *mut _ as *mut raw::c_void;
359
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900360 debug!("virtual machine service is starting as an RPC service.");
Inseob Kimc7d28c72021-10-25 14:28:10 +0000361 // SAFETY: factory function is only ever called by RunRpcServerWithFactory, within the
362 // lifetime of the state, with context taking the pointer value above (so a properly
363 // aligned non-null pointer to an initialized instance).
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900364 let retval = unsafe {
Inseob Kimc7d28c72021-10-25 14:28:10 +0000365 binder_rpc_unstable_bindgen::RunRpcServerWithFactory(
366 Some(VirtualMachineService::factory),
367 state_ptr,
Inseob Kimd0587562021-09-01 21:27:32 +0900368 VM_BINDER_SERVICE_PORT as u32,
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900369 )
370 };
371 if retval {
372 debug!("RPC server has shut down gracefully");
373 } else {
374 bail!("Premature termination of RPC server");
375 }
376
377 Ok(retval)
378 });
Jiyong Park8611a6c2021-07-09 18:17:44 +0900379 service
380 }
381}
382
Andrew Walbran6b650662021-09-07 13:13:23 +0000383/// Waits for incoming connections from VM. If a new connection is made, stores the stream in the
384/// corresponding `VmInstance`.
Inseob Kim7f61fe72021-08-20 20:50:47 +0900385fn handle_stream_connection_from_vm(state: Arc<Mutex<State>>) -> Result<()> {
Inseob Kimd0587562021-09-01 21:27:32 +0900386 let listener =
387 VsockListener::bind_with_cid_port(VMADDR_CID_HOST, VM_STREAM_SERVICE_PORT as u32)?;
Jiyong Park8611a6c2021-07-09 18:17:44 +0900388 for stream in listener.incoming() {
389 let stream = match stream {
390 Err(e) => {
391 warn!("invalid incoming connection: {}", e);
392 continue;
393 }
394 Ok(s) => s,
395 };
396 if let Ok(SockAddr::Vsock(addr)) = stream.peer_addr() {
397 let cid = addr.cid();
398 let port = addr.port();
Inseob Kim7f61fe72021-08-20 20:50:47 +0900399 info!("payload stream connected from cid={}, port={}", cid, port);
Jiyong Park8611a6c2021-07-09 18:17:44 +0900400 if let Some(vm) = state.lock().unwrap().get_vm(cid) {
Chris Wailes8bbb8932021-09-10 14:14:19 -0700401 *vm.stream.lock().unwrap() = Some(stream);
Inseob Kim7f61fe72021-08-20 20:50:47 +0900402 } else {
403 error!("connection from cid={} is not from a guest VM", cid);
Jiyong Park8611a6c2021-07-09 18:17:44 +0900404 }
405 }
406 }
407 Ok(())
408}
409
Andrew Walbranfbb39d22021-07-28 17:01:25 +0000410fn write_zero_filler(zero_filler_path: &Path) -> Result<()> {
Jooyung Han95884632021-07-06 22:27:54 +0900411 let file = OpenOptions::new()
412 .create_new(true)
413 .read(true)
414 .write(true)
415 .open(zero_filler_path)
416 .with_context(|| "Failed to create zero.img")?;
417 file.set_len(ZERO_FILLER_SIZE)?;
Andrew Walbranfbb39d22021-07-28 17:01:25 +0000418 Ok(())
Jooyung Han95884632021-07-06 22:27:54 +0900419}
420
Jiyong Park9dd389e2021-08-23 20:42:59 +0900421fn format_as_android_vm_instance(part: &mut dyn Write) -> std::io::Result<()> {
422 part.write_all(ANDROID_VM_INSTANCE_MAGIC.as_bytes())?;
423 part.write_all(&ANDROID_VM_INSTANCE_VERSION.to_le_bytes())?;
424 part.flush()
425}
426
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000427/// Given the configuration for a disk image, assembles the `DiskFile` to pass to crosvm.
428///
429/// This may involve assembling a composite disk from a set of partition images.
430fn assemble_disk_image(
431 disk: &DiskImage,
Jooyung Han95884632021-07-06 22:27:54 +0900432 zero_filler_path: &Path,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000433 temporary_directory: &Path,
434 next_temporary_image_id: &mut u64,
435 indirect_files: &mut Vec<File>,
Andrew Walbran806f1542021-06-10 14:07:12 +0000436) -> Result<DiskFile, Status> {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000437 let image = if !disk.partitions.is_empty() {
438 if disk.image.is_some() {
439 warn!("DiskImage {:?} contains both image and partitions.", disk);
Andrew Walbran806f1542021-06-10 14:07:12 +0000440 return Err(new_binder_exception(
441 ExceptionCode::ILLEGAL_ARGUMENT,
442 "DiskImage contains both image and partitions.",
443 ));
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000444 }
445
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000446 let composite_image_filenames =
447 make_composite_image_filenames(temporary_directory, next_temporary_image_id);
448 let (image, partition_files) = make_composite_image(
449 &disk.partitions,
Jooyung Han95884632021-07-06 22:27:54 +0900450 zero_filler_path,
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000451 &composite_image_filenames.composite,
452 &composite_image_filenames.header,
453 &composite_image_filenames.footer,
454 )
455 .map_err(|e| {
456 error!("Failed to make composite image with config {:?}: {}", disk, e);
457 new_binder_exception(
458 ExceptionCode::SERVICE_SPECIFIC,
459 format!("Failed to make composite image: {}", e),
460 )
461 })?;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000462
463 // Pass the file descriptors for the various partition files to crosvm when it
464 // is run.
465 indirect_files.extend(partition_files);
466
467 image
468 } else if let Some(image) = &disk.image {
469 clone_file(image)?
470 } else {
471 warn!("DiskImage {:?} didn't contain image or partitions.", disk);
Andrew Walbran806f1542021-06-10 14:07:12 +0000472 return Err(new_binder_exception(
473 ExceptionCode::ILLEGAL_ARGUMENT,
474 "DiskImage didn't contain image or partitions.",
475 ));
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000476 };
477
478 Ok(DiskFile { image, writable: disk.writable })
479}
480
Jooyung Han21e9b922021-06-26 04:14:16 +0900481fn load_app_config(
482 config: &VirtualMachineAppConfig,
483 temporary_directory: &Path,
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900484) -> Result<VirtualMachineRawConfig> {
Andrew Walbrancc0db522021-07-12 17:03:42 +0000485 let apk_file = clone_file(config.apk.as_ref().unwrap())?;
486 let idsig_file = clone_file(config.idsig.as_ref().unwrap())?;
Jiyong Park8d081812021-07-23 17:45:04 +0900487 let instance_file = clone_file(config.instanceImage.as_ref().unwrap())?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900488 let config_path = &config.configPath;
489
Andrew Walbrancc0db522021-07-12 17:03:42 +0000490 let mut apk_zip = ZipArchive::new(&apk_file)?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900491 let config_file = apk_zip.by_name(config_path)?;
492 let vm_payload_config: VmPayloadConfig = serde_json::from_reader(config_file)?;
493
494 let os_name = &vm_payload_config.os.name;
Andrew Walbrancc0db522021-07-12 17:03:42 +0000495
Jooyung Han35edb8f2021-07-01 16:17:16 +0900496 // For now, the only supported "os" value is "microdroid"
497 if os_name != "microdroid" {
Andrew Walbrancc0db522021-07-12 17:03:42 +0000498 bail!("Unknown OS \"{}\"", os_name);
Jooyung Han35edb8f2021-07-01 16:17:16 +0900499 }
Andrew Walbrancc0db522021-07-12 17:03:42 +0000500
501 // It is safe to construct a filename based on the os_name because we've already checked that it
502 // is one of the allowed values.
Jooyung Han21e9b922021-06-26 04:14:16 +0900503 let vm_config_path = PathBuf::from(format!("/apex/com.android.virt/etc/{}.json", os_name));
504 let vm_config_file = File::open(vm_config_path)?;
Andrew Walbrancc0db522021-07-12 17:03:42 +0000505 let mut vm_config = VmConfig::load(&vm_config_file)?.to_parcelable()?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900506
Andrew Walbrancc045902021-07-27 16:06:17 +0000507 if config.memoryMib > 0 {
508 vm_config.memoryMib = config.memoryMib;
Andrew Walbran45bcb0c2021-07-14 15:02:06 +0000509 }
510
Andrew Walbrancc0db522021-07-12 17:03:42 +0000511 // Microdroid requires an additional payload disk image and the bootconfig partition.
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900512 if os_name == "microdroid" {
Andrew Walbrancc0db522021-07-12 17:03:42 +0000513 add_microdroid_images(
514 config,
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900515 temporary_directory,
Andrew Walbrancc0db522021-07-12 17:03:42 +0000516 apk_file,
517 idsig_file,
Jiyong Park8d081812021-07-23 17:45:04 +0900518 instance_file,
Jooyung Han5dc42172021-10-05 16:43:47 +0900519 &vm_payload_config,
Andrew Walbrancc0db522021-07-12 17:03:42 +0000520 &mut vm_config,
521 )?;
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900522 }
Jooyung Han21e9b922021-06-26 04:14:16 +0900523
Andrew Walbrancc0db522021-07-12 17:03:42 +0000524 Ok(vm_config)
Jooyung Han21e9b922021-06-26 04:14:16 +0900525}
526
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000527/// Generates a unique filename to use for a composite disk image.
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000528fn make_composite_image_filenames(
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000529 temporary_directory: &Path,
530 next_temporary_image_id: &mut u64,
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000531) -> CompositeImageFilenames {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000532 let id = *next_temporary_image_id;
533 *next_temporary_image_id += 1;
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000534 CompositeImageFilenames {
535 composite: temporary_directory.join(format!("composite-{}.img", id)),
536 header: temporary_directory.join(format!("composite-{}-header.img", id)),
537 footer: temporary_directory.join(format!("composite-{}-footer.img", id)),
538 }
539}
540
541/// Filenames for a composite disk image, including header and footer partitions.
542#[derive(Clone, Debug, Eq, PartialEq)]
543struct CompositeImageFilenames {
544 /// The composite disk image itself.
545 composite: PathBuf,
546 /// The header partition image.
547 header: PathBuf,
548 /// The footer partition image.
549 footer: PathBuf,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000550}
551
552/// Gets the calling SID of the current Binder thread.
Andrew Walbran806f1542021-06-10 14:07:12 +0000553fn get_calling_sid() -> Result<String, Status> {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000554 ThreadState::with_calling_sid(|sid| {
555 if let Some(sid) = sid {
556 match sid.to_str() {
557 Ok(sid) => Ok(sid.to_owned()),
558 Err(e) => {
Andrew Walbran806f1542021-06-10 14:07:12 +0000559 error!("SID was not valid UTF-8: {}", e);
560 Err(new_binder_exception(
561 ExceptionCode::ILLEGAL_ARGUMENT,
562 format!("SID was not valid UTF-8: {}", e),
563 ))
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000564 }
565 }
566 } else {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000567 error!("Missing SID on createVm");
568 Err(new_binder_exception(ExceptionCode::SECURITY, "Missing SID on createVm"))
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000569 }
570 })
571}
572
Jiyong Park753553b2021-07-12 21:21:09 +0900573/// Checks whether the caller has a specific permission
574fn check_permission(perm: &str) -> binder::Result<()> {
575 let calling_pid = ThreadState::get_calling_pid();
576 let calling_uid = ThreadState::get_calling_uid();
577 // Root can do anything
578 if calling_uid == 0 {
579 return Ok(());
580 }
581 let perm_svc: Strong<dyn IPermissionController::IPermissionController> =
582 binder::get_interface("permission")?;
583 if perm_svc.checkPermission(perm, calling_pid, calling_uid as i32)? {
Andrew Walbran806f1542021-06-10 14:07:12 +0000584 Ok(())
585 } else {
Jiyong Park753553b2021-07-12 21:21:09 +0900586 Err(new_binder_exception(
587 ExceptionCode::SECURITY,
588 format!("does not have the {} permission", perm),
589 ))
Andrew Walbran806f1542021-06-10 14:07:12 +0000590 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000591}
592
Jiyong Park753553b2021-07-12 21:21:09 +0900593/// Check whether the caller of the current Binder method is allowed to call debug methods.
594fn check_debug_access() -> binder::Result<()> {
595 check_permission("android.permission.DEBUG_VIRTUAL_MACHINE")
596}
597
598/// Check whether the caller of the current Binder method is allowed to manage VMs
599fn check_manage_access() -> binder::Result<()> {
600 check_permission("android.permission.MANAGE_VIRTUAL_MACHINE")
601}
602
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000603/// Implementation of the AIDL `IVirtualMachine` interface. Used as a handle to a VM.
604#[derive(Debug)]
605struct VirtualMachine {
606 instance: Arc<VmInstance>,
Alan Stokes0cc59ee2021-09-24 11:20:34 +0100607 /// Keeps our service process running as long as this VM instance exists.
608 lazy_service_guard: LazyServiceGuard,
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000609}
610
611impl VirtualMachine {
612 fn create(instance: Arc<VmInstance>) -> Strong<dyn IVirtualMachine> {
Alan Stokes0cc59ee2021-09-24 11:20:34 +0100613 let binder = VirtualMachine { instance, lazy_service_guard: Default::default() };
Andrew Walbran4de28782021-04-13 14:51:43 +0000614 BnVirtualMachine::new_binder(binder, BinderFeatures::default())
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000615 }
616}
617
618impl Interface for VirtualMachine {}
619
620impl IVirtualMachine for VirtualMachine {
621 fn getCid(&self) -> binder::Result<i32> {
Jiyong Park753553b2021-07-12 21:21:09 +0900622 // Don't check permission. The owner of the VM might have passed this binder object to
623 // others.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000624 Ok(self.instance.cid as i32)
625 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000626
Andrew Walbran6b650662021-09-07 13:13:23 +0000627 fn getState(&self) -> binder::Result<VirtualMachineState> {
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 Walbran6b650662021-09-07 13:13:23 +0000630 Ok(get_state(&self.instance))
Andrew Walbrandae07162021-03-12 17:05:20 +0000631 }
632
633 fn registerCallback(
634 &self,
635 callback: &Strong<dyn IVirtualMachineCallback>,
636 ) -> binder::Result<()> {
Jiyong Park753553b2021-07-12 21:21:09 +0900637 // Don't check permission. The owner of the VM might have passed this binder object to
638 // others.
639 //
Andrew Walbrandae07162021-03-12 17:05:20 +0000640 // TODO: Should this give an error if the VM is already dead?
641 self.instance.callbacks.add(callback.clone());
642 Ok(())
643 }
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000644
Andrew Walbranf8d94112021-09-07 11:45:36 +0000645 fn start(&self) -> binder::Result<()> {
646 self.instance.start().map_err(|e| {
647 error!("Error starting VM with CID {}: {:?}", self.instance.cid, e);
648 new_binder_exception(ExceptionCode::SERVICE_SPECIFIC, e.to_string())
649 })
650 }
651
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000652 fn connectVsock(&self, port: i32) -> binder::Result<ParcelFileDescriptor> {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000653 if !matches!(&*self.instance.vm_state.lock().unwrap(), VmState::Running { .. }) {
654 return Err(new_binder_exception(ExceptionCode::SERVICE_SPECIFIC, "VM is not running"));
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000655 }
656 let stream =
657 VsockStream::connect_with_cid_port(self.instance.cid, port as u32).map_err(|e| {
658 new_binder_exception(
659 ExceptionCode::SERVICE_SPECIFIC,
660 format!("Failed to connect: {}", e),
661 )
662 })?;
663 Ok(vsock_stream_to_pfd(stream))
664 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000665}
666
667impl Drop for VirtualMachine {
668 fn drop(&mut self) {
669 debug!("Dropping {:?}", self);
670 self.instance.kill();
671 }
672}
673
674/// A set of Binders to be called back in response to various events on the VM, such as when it
675/// dies.
676#[derive(Debug, Default)]
677pub struct VirtualMachineCallbacks(Mutex<Vec<Strong<dyn IVirtualMachineCallback>>>);
678
679impl VirtualMachineCallbacks {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900680 /// Call all registered callbacks to notify that the payload has started.
Inseob Kim7f61fe72021-08-20 20:50:47 +0900681 pub fn notify_payload_started(&self, cid: Cid, stream: Option<VsockStream>) {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900682 let callbacks = &*self.0.lock().unwrap();
Inseob Kim7f61fe72021-08-20 20:50:47 +0900683 let pfd = stream.map(vsock_stream_to_pfd);
Jiyong Park8611a6c2021-07-09 18:17:44 +0900684 for callback in callbacks {
Inseob Kim7f61fe72021-08-20 20:50:47 +0900685 if let Err(e) = callback.onPayloadStarted(cid as i32, pfd.as_ref()) {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900686 error!("Error notifying payload start event from VM CID {}: {}", cid, e);
687 }
688 }
689 }
690
Inseob Kim14cb8692021-08-31 21:50:39 +0900691 /// Call all registered callbacks to notify that the payload is ready to serve.
692 pub fn notify_payload_ready(&self, cid: Cid) {
693 let callbacks = &*self.0.lock().unwrap();
694 for callback in callbacks {
695 if let Err(e) = callback.onPayloadReady(cid as i32) {
696 error!("Error notifying payload ready event from VM CID {}: {}", cid, e);
697 }
698 }
699 }
700
Inseob Kim2444af92021-08-31 01:22:50 +0900701 /// Call all registered callbacks to notify that the payload has finished.
702 pub fn notify_payload_finished(&self, cid: Cid, exit_code: i32) {
703 let callbacks = &*self.0.lock().unwrap();
704 for callback in callbacks {
705 if let Err(e) = callback.onPayloadFinished(cid as i32, exit_code) {
706 error!("Error notifying payload finish event from VM CID {}: {}", cid, e);
707 }
708 }
709 }
710
Andrew Walbrandae07162021-03-12 17:05:20 +0000711 /// Call all registered callbacks to say that the VM has died.
712 pub fn callback_on_died(&self, cid: Cid) {
713 let callbacks = &*self.0.lock().unwrap();
714 for callback in callbacks {
715 if let Err(e) = callback.onDied(cid as i32) {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900716 error!("Error notifying exit of VM CID {}: {}", cid, e);
Andrew Walbrandae07162021-03-12 17:05:20 +0000717 }
718 }
719 }
720
721 /// Add a new callback to the set.
722 fn add(&self, callback: Strong<dyn IVirtualMachineCallback>) {
723 self.0.lock().unwrap().push(callback);
724 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000725}
726
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000727/// The mutable state of the VirtualizationService. There should only be one instance of this
728/// struct.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000729#[derive(Debug)]
730struct State {
Andrew Walbran320b5602021-03-04 16:11:12 +0000731 /// The VMs which have been started. When VMs are started a weak reference is added to this list
732 /// while a strong reference is returned to the caller over Binder. Once all copies of the
733 /// Binder client are dropped the weak reference here will become invalid, and will be removed
734 /// from the list opportunistically the next time `add_vm` is called.
735 vms: Vec<Weak<VmInstance>>,
David Brazdil3c2ddef2021-03-18 13:09:57 +0000736
737 /// Vector of strong VM references held on behalf of users that cannot hold them themselves.
738 /// This is only used for debugging purposes.
739 debug_held_vms: Vec<Strong<dyn IVirtualMachine>>,
Andrew Walbran320b5602021-03-04 16:11:12 +0000740}
741
742impl State {
Andrew Walbrandae07162021-03-12 17:05:20 +0000743 /// Get a list of VMs which still have Binder references to them.
Andrew Walbran320b5602021-03-04 16:11:12 +0000744 fn vms(&self) -> Vec<Arc<VmInstance>> {
745 // Attempt to upgrade the weak pointers to strong pointers.
746 self.vms.iter().filter_map(Weak::upgrade).collect()
747 }
748
749 /// Add a new VM to the list.
750 fn add_vm(&mut self, vm: Weak<VmInstance>) {
751 // Garbage collect any entries from the stored list which no longer exist.
752 self.vms.retain(|vm| vm.strong_count() > 0);
753
754 // Actually add the new VM.
755 self.vms.push(vm);
756 }
David Brazdil3c2ddef2021-03-18 13:09:57 +0000757
Jiyong Park8611a6c2021-07-09 18:17:44 +0900758 /// Get a VM that corresponds to the given cid
759 fn get_vm(&self, cid: Cid) -> Option<Arc<VmInstance>> {
760 self.vms().into_iter().find(|vm| vm.cid == cid)
761 }
762
David Brazdil3c2ddef2021-03-18 13:09:57 +0000763 /// Store a strong VM reference.
764 fn debug_hold_vm(&mut self, vm: Strong<dyn IVirtualMachine>) {
765 self.debug_held_vms.push(vm);
766 }
767
768 /// Retrieve and remove a strong VM reference.
769 fn debug_drop_vm(&mut self, cid: i32) -> Option<Strong<dyn IVirtualMachine>> {
770 let pos = self.debug_held_vms.iter().position(|vm| vm.getCid() == Ok(cid))?;
Alan Stokes7e54e292021-09-09 11:37:56 +0100771 let vm = self.debug_held_vms.swap_remove(pos);
Alan Stokes7e54e292021-09-09 11:37:56 +0100772 Some(vm)
David Brazdil3c2ddef2021-03-18 13:09:57 +0000773 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000774}
775
776impl Default for State {
777 fn default() -> Self {
Jiyong Parkd50a0242021-09-16 21:00:14 +0900778 State { vms: vec![], debug_held_vms: vec![] }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000779 }
780}
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000781
Jiyong Parkd50a0242021-09-16 21:00:14 +0900782/// Get the next available CID, or an error if we have run out. The last CID used is stored in
783/// a system property so that restart of virtualizationservice doesn't reuse CID while the host
784/// Android is up.
785fn next_cid() -> Result<Cid> {
786 let next = if let Ok(val) = system_properties::read(SYSPROP_LAST_CID) {
787 if let Ok(num) = val.parse::<u32>() {
788 num.checked_add(1).ok_or_else(|| anyhow!("run out of CID"))?
789 } else {
790 error!("Invalid last CID {}. Using {}", &val, FIRST_GUEST_CID);
791 FIRST_GUEST_CID
792 }
793 } else {
794 // First VM since the boot
795 FIRST_GUEST_CID
796 };
797 // Persist the last value for next use
798 let str_val = format!("{}", next);
799 system_properties::write(SYSPROP_LAST_CID, &str_val)?;
800 Ok(next)
801}
802
Andrew Walbran6b650662021-09-07 13:13:23 +0000803/// Gets the `VirtualMachineState` of the given `VmInstance`.
804fn get_state(instance: &VmInstance) -> VirtualMachineState {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000805 match &*instance.vm_state.lock().unwrap() {
806 VmState::NotStarted { .. } => VirtualMachineState::NOT_STARTED,
807 VmState::Running { .. } => match instance.payload_state() {
Andrew Walbran6b650662021-09-07 13:13:23 +0000808 PayloadState::Starting => VirtualMachineState::STARTING,
809 PayloadState::Started => VirtualMachineState::STARTED,
810 PayloadState::Ready => VirtualMachineState::READY,
811 PayloadState::Finished => VirtualMachineState::FINISHED,
Andrew Walbranf8d94112021-09-07 11:45:36 +0000812 },
813 VmState::Dead => VirtualMachineState::DEAD,
814 VmState::Failed => VirtualMachineState::DEAD,
Andrew Walbran6b650662021-09-07 13:13:23 +0000815 }
816}
817
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000818/// Converts a `&ParcelFileDescriptor` to a `File` by cloning the file.
Andrew Walbran806f1542021-06-10 14:07:12 +0000819fn clone_file(file: &ParcelFileDescriptor) -> Result<File, Status> {
820 file.as_ref().try_clone().map_err(|e| {
821 new_binder_exception(
822 ExceptionCode::BAD_PARCELABLE,
823 format!("Failed to clone File from ParcelFileDescriptor: {}", e),
824 )
825 })
826}
827
Andrew Walbrand3a84182021-09-07 14:48:52 +0000828/// Converts an `&Option<ParcelFileDescriptor>` to an `Option<File>` by cloning the file.
829fn maybe_clone_file(file: &Option<ParcelFileDescriptor>) -> Result<Option<File>, Status> {
830 file.as_ref().map(clone_file).transpose()
831}
832
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000833/// Converts a `VsockStream` to a `ParcelFileDescriptor`.
834fn vsock_stream_to_pfd(stream: VsockStream) -> ParcelFileDescriptor {
835 // SAFETY: ownership is transferred from stream to f
836 let f = unsafe { File::from_raw_fd(stream.into_raw_fd()) };
837 ParcelFileDescriptor::new(f)
838}
839
Jooyung Han35edb8f2021-07-01 16:17:16 +0900840/// Simple utility for referencing Borrowed or Owned. Similar to std::borrow::Cow, but
841/// it doesn't require that T implements Clone.
842enum BorrowedOrOwned<'a, T> {
843 Borrowed(&'a T),
844 Owned(T),
845}
846
847impl<'a, T> AsRef<T> for BorrowedOrOwned<'a, T> {
848 fn as_ref(&self) -> &T {
849 match self {
850 Self::Borrowed(b) => b,
Chris Wailes68c39f82021-07-27 16:03:44 -0700851 Self::Owned(o) => o,
Jooyung Han35edb8f2021-07-01 16:17:16 +0900852 }
853 }
854}
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900855
856/// Implementation of `IVirtualMachineService`, the entry point of the AIDL service.
857#[derive(Debug, Default)]
858struct VirtualMachineService {
859 state: Arc<Mutex<State>>,
Inseob Kimc7d28c72021-10-25 14:28:10 +0000860 cid: Cid,
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900861}
862
863impl Interface for VirtualMachineService {}
864
865impl IVirtualMachineService for VirtualMachineService {
Inseob Kimc7d28c72021-10-25 14:28:10 +0000866 fn notifyPayloadStarted(&self) -> binder::Result<()> {
867 let cid = self.cid;
Inseob Kim7f61fe72021-08-20 20:50:47 +0900868 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
869 info!("VM having CID {} started payload", cid);
Andrew Walbran6b650662021-09-07 13:13:23 +0000870 vm.update_payload_state(PayloadState::Started)
871 .map_err(|e| new_binder_exception(ExceptionCode::ILLEGAL_STATE, e.to_string()))?;
Inseob Kim7f61fe72021-08-20 20:50:47 +0900872 let stream = vm.stream.lock().unwrap().take();
873 vm.callbacks.notify_payload_started(cid, stream);
874 Ok(())
875 } else {
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900876 error!("notifyPayloadStarted is called from an unknown cid {}", cid);
Inseob Kim7f61fe72021-08-20 20:50:47 +0900877 Err(new_binder_exception(
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900878 ExceptionCode::SERVICE_SPECIFIC,
879 format!("cannot find a VM with cid {}", cid),
Inseob Kim7f61fe72021-08-20 20:50:47 +0900880 ))
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900881 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900882 }
Inseob Kim2444af92021-08-31 01:22:50 +0900883
Inseob Kimc7d28c72021-10-25 14:28:10 +0000884 fn notifyPayloadReady(&self) -> binder::Result<()> {
885 let cid = self.cid;
Inseob Kim14cb8692021-08-31 21:50:39 +0900886 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
887 info!("VM having CID {} payload is ready", cid);
Andrew Walbran6b650662021-09-07 13:13:23 +0000888 vm.update_payload_state(PayloadState::Ready)
889 .map_err(|e| new_binder_exception(ExceptionCode::ILLEGAL_STATE, e.to_string()))?;
Inseob Kim14cb8692021-08-31 21:50:39 +0900890 vm.callbacks.notify_payload_ready(cid);
891 Ok(())
892 } else {
893 error!("notifyPayloadReady is called from an unknown cid {}", cid);
894 Err(new_binder_exception(
895 ExceptionCode::SERVICE_SPECIFIC,
896 format!("cannot find a VM with cid {}", cid),
897 ))
898 }
899 }
900
Inseob Kimc7d28c72021-10-25 14:28:10 +0000901 fn notifyPayloadFinished(&self, exit_code: i32) -> binder::Result<()> {
902 let cid = self.cid;
Inseob Kim2444af92021-08-31 01:22:50 +0900903 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
904 info!("VM having CID {} finished payload", cid);
Andrew Walbran6b650662021-09-07 13:13:23 +0000905 vm.update_payload_state(PayloadState::Finished)
906 .map_err(|e| new_binder_exception(ExceptionCode::ILLEGAL_STATE, e.to_string()))?;
Inseob Kim2444af92021-08-31 01:22:50 +0900907 vm.callbacks.notify_payload_finished(cid, exit_code);
908 Ok(())
909 } else {
910 error!("notifyPayloadFinished is called from an unknown cid {}", cid);
911 Err(new_binder_exception(
912 ExceptionCode::SERVICE_SPECIFIC,
913 format!("cannot find a VM with cid {}", cid),
914 ))
915 }
916 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900917}
918
919impl VirtualMachineService {
Inseob Kimc7d28c72021-10-25 14:28:10 +0000920 // SAFETY: Service ownership is held by state, and the binder objects are threadsafe.
921 pub unsafe extern "C" fn factory(
922 cid: Cid,
923 context: *mut raw::c_void,
924 ) -> *mut binder_rpc_unstable_bindgen::AIBinder {
925 let state_ptr = context as *mut Arc<Mutex<State>>;
926 let state = state_ptr.as_ref().unwrap();
927 if let Some(vm) = state.lock().unwrap().get_vm(cid) {
928 let mut vm_service = vm.vm_service.lock().unwrap();
929 let service = vm_service.get_or_insert_with(|| Self::new_binder(state.clone(), cid));
930 service.as_binder().as_native_mut() as *mut binder_rpc_unstable_bindgen::AIBinder
931 } else {
932 error!("connection from cid={} is not from a guest VM", cid);
933 null_mut()
934 }
935 }
936
937 fn new_binder(state: Arc<Mutex<State>>, cid: Cid) -> Strong<dyn IVirtualMachineService> {
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900938 BnVirtualMachineService::new_binder(
Inseob Kimc7d28c72021-10-25 14:28:10 +0000939 VirtualMachineService { state, cid },
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900940 BinderFeatures::default(),
941 )
942 }
943}