blob: 76c3a16c28c332241a1d772d433e70d7d88f89b2 [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};
Jooyung Han21e9b922021-06-26 04:14:16 +090021
Alan Stokes3189af02021-09-30 17:51:19 +010022use binder_common::new_binder_exception;
Jiyong Park753553b2021-07-12 21:21:09 +090023use android_os_permissions_aidl::aidl::android::os::IPermissionController;
Andrew Walbranf6bf6862021-05-21 12:41:13 +000024use android_system_virtualizationservice::aidl::android::system::virtualizationservice::IVirtualMachine::{
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000025 BnVirtualMachine, IVirtualMachine,
26};
Jooyung Han21e9b922021-06-26 04:14:16 +090027use android_system_virtualizationservice::aidl::android::system::virtualizationservice::{
Andrew Walbran6b650662021-09-07 13:13:23 +000028 DiskImage::DiskImage,
29 IVirtualMachineCallback::IVirtualMachineCallback,
30 IVirtualizationService::IVirtualizationService,
31 PartitionType::PartitionType,
Jooyung Han21e9b922021-06-26 04:14:16 +090032 VirtualMachineAppConfig::VirtualMachineAppConfig,
33 VirtualMachineConfig::VirtualMachineConfig,
Andrew Walbran6b650662021-09-07 13:13:23 +000034 VirtualMachineDebugInfo::VirtualMachineDebugInfo,
Jooyung Han21e9b922021-06-26 04:14:16 +090035 VirtualMachineRawConfig::VirtualMachineRawConfig,
Andrew Walbran6b650662021-09-07 13:13:23 +000036 VirtualMachineState::VirtualMachineState,
Jooyung Han21e9b922021-06-26 04:14:16 +090037};
Andrew Walbranf6bf6862021-05-21 12:41:13 +000038use android_system_virtualizationservice::binder::{
Alan Stokes7e54e292021-09-09 11:37:56 +010039 self, force_lazy_services_persist, BinderFeatures, ExceptionCode, Interface, ParcelFileDescriptor, Status, Strong, ThreadState,
Andrew Walbrana89fc132021-03-17 17:08:36 +000040};
Inseob Kim1b95f2e2021-08-19 13:17:40 +090041use android_system_virtualmachineservice::aidl::android::system::virtualmachineservice::IVirtualMachineService::{
Inseob Kimd0587562021-09-01 21:27:32 +090042 VM_BINDER_SERVICE_PORT, VM_STREAM_SERVICE_PORT, BnVirtualMachineService, IVirtualMachineService,
Inseob Kim1b95f2e2021-08-19 13:17:40 +090043};
Jiyong Parkd50a0242021-09-16 21:00:14 +090044use anyhow::{anyhow, bail, Context, Result};
Inseob Kim1b95f2e2021-08-19 13:17:40 +090045use ::binder::unstable_api::AsNative;
Andrew Walbrandfc953d2021-06-10 13:59:56 +000046use disk::QcowFile;
Jiyong Park0a248432021-08-20 23:32:39 +090047use idsig::{V4Signature, HashAlgorithm};
Jiyong Park8611a6c2021-07-09 18:17:44 +090048use log::{debug, error, warn, info};
Andrew Walbrancc0db522021-07-12 17:03:42 +000049use microdroid_payload_config::VmPayloadConfig;
Jiyong Parkd50a0242021-09-16 21:00:14 +090050use rustutils::system_properties;
Andrew Walbrandff3b942021-06-09 15:20:36 +000051use std::convert::TryInto;
Jooyung Han95884632021-07-06 22:27:54 +090052use std::fs::{File, OpenOptions, create_dir};
Jiyong Park9dd389e2021-08-23 20:42:59 +090053use std::io::{Error, ErrorKind, Write};
Andrew Walbranb15cd6e2021-07-05 16:38:07 +000054use std::num::NonZeroU32;
Andrew Walbrand3a84182021-09-07 14:48:52 +000055use std::os::unix::io::{FromRawFd, IntoRawFd};
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000056use std::path::{Path, PathBuf};
Andrew Walbran320b5602021-03-04 16:11:12 +000057use std::sync::{Arc, Mutex, Weak};
Andrew Walbrancc0db522021-07-12 17:03:42 +000058use vmconfig::VmConfig;
Inseob Kim7f61fe72021-08-20 20:50:47 +090059use vsock::{SockAddr, VsockListener, VsockStream};
Jooyung Han35edb8f2021-07-01 16:17:16 +090060use zip::ZipArchive;
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000061
Andrew Walbranf6bf6862021-05-21 12:41:13 +000062pub const BINDER_SERVICE_IDENTIFIER: &str = "android.system.virtualizationservice";
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000063
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000064/// Directory in which to write disk image files used while running VMs.
Andrew Walbran488bd072021-07-14 13:29:51 +000065pub const TEMPORARY_DIRECTORY: &str = "/data/misc/virtualizationservice";
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000066
Jiyong Park8611a6c2021-07-09 18:17:44 +090067/// The CID representing the host VM
68const VMADDR_CID_HOST: u32 = 2;
69
Jooyung Han95884632021-07-06 22:27:54 +090070/// The size of zero.img.
71/// Gaps in composite disk images are filled with a shared zero.img.
72const ZERO_FILLER_SIZE: u64 = 4096;
73
Jiyong Park9dd389e2021-08-23 20:42:59 +090074/// Magic string for the instance image
75const ANDROID_VM_INSTANCE_MAGIC: &str = "Android-VM-instance";
76
77/// Version of the instance image format
78const ANDROID_VM_INSTANCE_VERSION: u16 = 1;
79
Andrew Walbranf6bf6862021-05-21 12:41:13 +000080/// Implementation of `IVirtualizationService`, the entry point of the AIDL service.
Jooyung Han9900f3d2021-07-06 10:27:54 +090081#[derive(Debug, Default)]
Andrew Walbranf6bf6862021-05-21 12:41:13 +000082pub struct VirtualizationService {
Jiyong Park8611a6c2021-07-09 18:17:44 +090083 state: Arc<Mutex<State>>,
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000084}
85
Andrew Walbranf6bf6862021-05-21 12:41:13 +000086impl Interface for VirtualizationService {}
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000087
Andrew Walbranf6bf6862021-05-21 12:41:13 +000088impl IVirtualizationService for VirtualizationService {
Andrew Walbranf8d94112021-09-07 11:45:36 +000089 /// Creates (but does not start) a new VM with the given configuration, assigning it the next
90 /// available CID.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000091 ///
92 /// Returns a binder `IVirtualMachine` object referring to it, as a handle for the client.
Andrew Walbranf8d94112021-09-07 11:45:36 +000093 fn createVm(
Andrew Walbrana89fc132021-03-17 17:08:36 +000094 &self,
Andrew Walbran3a5a9212021-05-04 17:09:08 +000095 config: &VirtualMachineConfig,
Andrew Walbrana89fc132021-03-17 17:08:36 +000096 log_fd: Option<&ParcelFileDescriptor>,
97 ) -> binder::Result<Strong<dyn IVirtualMachine>> {
Jiyong Park753553b2021-07-12 21:21:09 +090098 check_manage_access()?;
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000099 let state = &mut *self.state.lock().unwrap();
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000100 let log_fd = log_fd.map(clone_file).transpose()?;
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000101 let requester_uid = ThreadState::get_calling_uid();
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000102 let requester_sid = get_calling_sid()?;
Andrew Walbran02034492021-04-13 15:05:07 +0000103 let requester_debug_pid = ThreadState::get_calling_pid();
Jiyong Parkd50a0242021-09-16 21:00:14 +0900104 let cid = next_cid().or(Err(ExceptionCode::ILLEGAL_STATE))?;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000105
106 // Counter to generate unique IDs for temporary image files.
107 let mut next_temporary_image_id = 0;
108 // Files which are referred to from composite images. These must be mapped to the crosvm
109 // child process, and not closed before it is started.
110 let mut indirect_files = vec![];
111
112 // Make directory for temporary files.
113 let temporary_directory: PathBuf = format!("{}/{}", TEMPORARY_DIRECTORY, cid).into();
114 create_dir(&temporary_directory).map_err(|e| {
115 error!(
Andrew Walbran806f1542021-06-10 14:07:12 +0000116 "Failed to create temporary directory {:?} for VM files: {}",
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000117 temporary_directory, e
118 );
Andrew Walbran806f1542021-06-10 14:07:12 +0000119 new_binder_exception(
120 ExceptionCode::SERVICE_SPECIFIC,
121 format!(
122 "Failed to create temporary directory {:?} for VM files: {}",
123 temporary_directory, e
124 ),
125 )
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000126 })?;
127
Jooyung Han21e9b922021-06-26 04:14:16 +0900128 let config = match config {
Jooyung Han35edb8f2021-07-01 16:17:16 +0900129 VirtualMachineConfig::AppConfig(config) => BorrowedOrOwned::Owned(
Jooyung Han9900f3d2021-07-06 10:27:54 +0900130 load_app_config(config, &temporary_directory).map_err(|e| {
131 error!("Failed to load app config from {}: {}", &config.configPath, e);
132 new_binder_exception(
133 ExceptionCode::SERVICE_SPECIFIC,
134 format!("Failed to load app config from {}: {}", &config.configPath, e),
135 )
136 })?,
Jooyung Han35edb8f2021-07-01 16:17:16 +0900137 ),
138 VirtualMachineConfig::RawConfig(config) => BorrowedOrOwned::Borrowed(config),
Jooyung Han21e9b922021-06-26 04:14:16 +0900139 };
Jooyung Han35edb8f2021-07-01 16:17:16 +0900140 let config = config.as_ref();
Jooyung Han21e9b922021-06-26 04:14:16 +0900141
Jooyung Han95884632021-07-06 22:27:54 +0900142 let zero_filler_path = temporary_directory.join("zero.img");
Andrew Walbranfbb39d22021-07-28 17:01:25 +0000143 write_zero_filler(&zero_filler_path).map_err(|e| {
Jooyung Han95884632021-07-06 22:27:54 +0900144 error!("Failed to make composite image: {}", e);
145 new_binder_exception(
146 ExceptionCode::SERVICE_SPECIFIC,
147 format!("Failed to make composite image: {}", e),
148 )
149 })?;
Jooyung Han95884632021-07-06 22:27:54 +0900150
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000151 // Assemble disk images if needed.
152 let disks = config
153 .disks
154 .iter()
155 .map(|disk| {
156 assemble_disk_image(
157 disk,
Jooyung Han95884632021-07-06 22:27:54 +0900158 &zero_filler_path,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000159 &temporary_directory,
160 &mut next_temporary_image_id,
161 &mut indirect_files,
162 )
163 })
164 .collect::<Result<Vec<DiskFile>, _>>()?;
165
166 // Actually start the VM.
167 let crosvm_config = CrosvmConfig {
Andrew Walbran02034492021-04-13 15:05:07 +0000168 cid,
Andrew Walbrand3a84182021-09-07 14:48:52 +0000169 bootloader: maybe_clone_file(&config.bootloader)?,
170 kernel: maybe_clone_file(&config.kernel)?,
171 initrd: maybe_clone_file(&config.initrd)?,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000172 disks,
173 params: config.params.to_owned(),
Andrew Walbrancc045902021-07-27 16:06:17 +0000174 protected: config.protectedVm,
175 memory_mib: config.memoryMib.try_into().ok().and_then(NonZeroU32::new),
Andrew Walbran02034492021-04-13 15:05:07 +0000176 log_fd,
Andrew Walbrand3a84182021-09-07 14:48:52 +0000177 indirect_files,
178 };
Andrew Walbranf8d94112021-09-07 11:45:36 +0000179 let instance = Arc::new(
180 VmInstance::new(
181 crosvm_config,
182 temporary_directory,
183 requester_uid,
184 requester_sid,
185 requester_debug_pid,
Andrew Walbran806f1542021-06-10 14:07:12 +0000186 )
Andrew Walbranf8d94112021-09-07 11:45:36 +0000187 .map_err(|e| {
188 error!("Failed to create VM with config {:?}: {}", config, e);
189 new_binder_exception(
190 ExceptionCode::SERVICE_SPECIFIC,
191 format!("Failed to create VM: {}", e),
192 )
193 })?,
194 );
Andrew Walbran320b5602021-03-04 16:11:12 +0000195 state.add_vm(Arc::downgrade(&instance));
196 Ok(VirtualMachine::create(instance))
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000197 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000198
Andrew Walbrandff3b942021-06-09 15:20:36 +0000199 /// Initialise an empty partition image of the given size to be used as a writable partition.
200 fn initializeWritablePartition(
201 &self,
202 image_fd: &ParcelFileDescriptor,
203 size: i64,
Jiyong Park9dd389e2021-08-23 20:42:59 +0900204 partition_type: PartitionType,
Andrew Walbrandff3b942021-06-09 15:20:36 +0000205 ) -> binder::Result<()> {
Jiyong Park753553b2021-07-12 21:21:09 +0900206 check_manage_access()?;
Andrew Walbrandfc953d2021-06-10 13:59:56 +0000207 let size = size.try_into().map_err(|e| {
Andrew Walbran806f1542021-06-10 14:07:12 +0000208 new_binder_exception(
209 ExceptionCode::ILLEGAL_ARGUMENT,
210 format!("Invalid size {}: {}", size, e),
211 )
Andrew Walbrandff3b942021-06-09 15:20:36 +0000212 })?;
Andrew Walbrandfc953d2021-06-10 13:59:56 +0000213 let image = clone_file(image_fd)?;
Andrew Walbrandff3b942021-06-09 15:20:36 +0000214
Jiyong Park9dd389e2021-08-23 20:42:59 +0900215 let mut part = QcowFile::new(image, size).map_err(|e| {
Andrew Walbran806f1542021-06-10 14:07:12 +0000216 new_binder_exception(
217 ExceptionCode::SERVICE_SPECIFIC,
218 format!("Failed to create QCOW2 image: {}", e),
219 )
Andrew Walbrandfc953d2021-06-10 13:59:56 +0000220 })?;
Andrew Walbrandff3b942021-06-09 15:20:36 +0000221
Jiyong Park9dd389e2021-08-23 20:42:59 +0900222 match partition_type {
223 PartitionType::RAW => Ok(()),
224 PartitionType::ANDROID_VM_INSTANCE => format_as_android_vm_instance(&mut part),
225 _ => Err(Error::new(
226 ErrorKind::Unsupported,
227 format!("Unsupported partition type {:?}", partition_type),
228 )),
229 }
230 .map_err(|e| {
231 new_binder_exception(
232 ExceptionCode::SERVICE_SPECIFIC,
233 format!("Failed to initialize partition as {:?}: {}", partition_type, e),
234 )
235 })?;
236
Andrew Walbrandff3b942021-06-09 15:20:36 +0000237 Ok(())
238 }
239
Jiyong Park0a248432021-08-20 23:32:39 +0900240 /// Creates or update the idsig file by digesting the input APK file.
241 fn createOrUpdateIdsigFile(
242 &self,
243 input_fd: &ParcelFileDescriptor,
244 idsig_fd: &ParcelFileDescriptor,
245 ) -> binder::Result<()> {
246 // TODO(b/193504400): do this only when (1) idsig_fd is empty or (2) the APK digest in
247 // idsig_fd is different from APK digest in input_fd
248
249 let mut input = clone_file(input_fd)?;
250 let mut sig = V4Signature::create(&mut input, 4096, &[], HashAlgorithm::SHA256).unwrap();
251
252 let mut output = clone_file(idsig_fd)?;
253 output.set_len(0).unwrap();
254 sig.write_into(&mut output).unwrap();
255 Ok(())
256 }
257
Andrew Walbran320b5602021-03-04 16:11:12 +0000258 /// Get a list of all currently running VMs. This method is only intended for debug purposes,
259 /// and as such is only permitted from the shell user.
260 fn debugListVms(&self) -> binder::Result<Vec<VirtualMachineDebugInfo>> {
Andrew Walbran806f1542021-06-10 14:07:12 +0000261 check_debug_access()?;
Andrew Walbran320b5602021-03-04 16:11:12 +0000262
263 let state = &mut *self.state.lock().unwrap();
264 let vms = state.vms();
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000265 let cids = vms
266 .into_iter()
267 .map(|vm| VirtualMachineDebugInfo {
268 cid: vm.cid as i32,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000269 temporaryDirectory: vm.temporary_directory.to_string_lossy().to_string(),
Andrew Walbran1ef19ae2021-04-07 11:31:57 +0000270 requesterUid: vm.requester_uid as i32,
271 requesterSid: vm.requester_sid.clone(),
Andrew Walbran02034492021-04-13 15:05:07 +0000272 requesterPid: vm.requester_debug_pid,
Andrew Walbran6b650662021-09-07 13:13:23 +0000273 state: get_state(&vm),
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000274 })
275 .collect();
Andrew Walbran320b5602021-03-04 16:11:12 +0000276 Ok(cids)
277 }
David Brazdil3c2ddef2021-03-18 13:09:57 +0000278
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000279 /// Hold a strong reference to a VM in VirtualizationService. This method is only intended for
280 /// debug purposes, and as such is only permitted from the shell user.
Andrei Homescu1415c132021-03-24 02:39:55 +0000281 fn debugHoldVmRef(&self, vmref: &Strong<dyn IVirtualMachine>) -> binder::Result<()> {
Andrew Walbran806f1542021-06-10 14:07:12 +0000282 check_debug_access()?;
David Brazdil3c2ddef2021-03-18 13:09:57 +0000283
David Brazdil3c2ddef2021-03-18 13:09:57 +0000284 let state = &mut *self.state.lock().unwrap();
Andrei Homescu1415c132021-03-24 02:39:55 +0000285 state.debug_hold_vm(vmref.clone());
David Brazdil3c2ddef2021-03-18 13:09:57 +0000286 Ok(())
287 }
288
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000289 /// Drop reference to a VM that is being held by VirtualizationService. Returns the reference if
290 /// the VM was found and None otherwise. This method is only intended for debug purposes, and as
291 /// such is only permitted from the shell user.
David Brazdil3c2ddef2021-03-18 13:09:57 +0000292 fn debugDropVmRef(&self, cid: i32) -> binder::Result<Option<Strong<dyn IVirtualMachine>>> {
Andrew Walbran806f1542021-06-10 14:07:12 +0000293 check_debug_access()?;
David Brazdil3c2ddef2021-03-18 13:09:57 +0000294
295 let state = &mut *self.state.lock().unwrap();
296 Ok(state.debug_drop_vm(cid))
297 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000298}
299
Jiyong Park8611a6c2021-07-09 18:17:44 +0900300impl VirtualizationService {
301 pub fn init() -> VirtualizationService {
302 let service = VirtualizationService::default();
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900303
304 // server for payload output
Jiyong Park8611a6c2021-07-09 18:17:44 +0900305 let state = service.state.clone(); // reference to state (not the state itself) is copied
306 std::thread::spawn(move || {
Inseob Kim7f61fe72021-08-20 20:50:47 +0900307 handle_stream_connection_from_vm(state).unwrap();
Jiyong Park8611a6c2021-07-09 18:17:44 +0900308 });
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900309
310 // binder server for vm
311 let state = service.state.clone(); // reference to state (not the state itself) is copied
312 std::thread::spawn(move || {
313 let mut service = VirtualMachineService::new_binder(state).as_binder();
314 debug!("virtual machine service is starting as an RPC service.");
315 // SAFETY: Service ownership is transferring to the server and won't be valid afterward.
316 // Plus the binder objects are threadsafe.
317 let retval = unsafe {
318 binder_rpc_unstable_bindgen::RunRpcServer(
319 service.as_native_mut() as *mut binder_rpc_unstable_bindgen::AIBinder,
Inseob Kimd0587562021-09-01 21:27:32 +0900320 VM_BINDER_SERVICE_PORT as u32,
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900321 )
322 };
323 if retval {
324 debug!("RPC server has shut down gracefully");
325 } else {
326 bail!("Premature termination of RPC server");
327 }
328
329 Ok(retval)
330 });
Jiyong Park8611a6c2021-07-09 18:17:44 +0900331 service
332 }
333}
334
Andrew Walbran6b650662021-09-07 13:13:23 +0000335/// Waits for incoming connections from VM. If a new connection is made, stores the stream in the
336/// corresponding `VmInstance`.
Inseob Kim7f61fe72021-08-20 20:50:47 +0900337fn handle_stream_connection_from_vm(state: Arc<Mutex<State>>) -> Result<()> {
Inseob Kimd0587562021-09-01 21:27:32 +0900338 let listener =
339 VsockListener::bind_with_cid_port(VMADDR_CID_HOST, VM_STREAM_SERVICE_PORT as u32)?;
Jiyong Park8611a6c2021-07-09 18:17:44 +0900340 for stream in listener.incoming() {
341 let stream = match stream {
342 Err(e) => {
343 warn!("invalid incoming connection: {}", e);
344 continue;
345 }
346 Ok(s) => s,
347 };
348 if let Ok(SockAddr::Vsock(addr)) = stream.peer_addr() {
349 let cid = addr.cid();
350 let port = addr.port();
Inseob Kim7f61fe72021-08-20 20:50:47 +0900351 info!("payload stream connected from cid={}, port={}", cid, port);
Jiyong Park8611a6c2021-07-09 18:17:44 +0900352 if let Some(vm) = state.lock().unwrap().get_vm(cid) {
Chris Wailes8bbb8932021-09-10 14:14:19 -0700353 *vm.stream.lock().unwrap() = Some(stream);
Inseob Kim7f61fe72021-08-20 20:50:47 +0900354 } else {
355 error!("connection from cid={} is not from a guest VM", cid);
Jiyong Park8611a6c2021-07-09 18:17:44 +0900356 }
357 }
358 }
359 Ok(())
360}
361
Andrew Walbranfbb39d22021-07-28 17:01:25 +0000362fn write_zero_filler(zero_filler_path: &Path) -> Result<()> {
Jooyung Han95884632021-07-06 22:27:54 +0900363 let file = OpenOptions::new()
364 .create_new(true)
365 .read(true)
366 .write(true)
367 .open(zero_filler_path)
368 .with_context(|| "Failed to create zero.img")?;
369 file.set_len(ZERO_FILLER_SIZE)?;
Andrew Walbranfbb39d22021-07-28 17:01:25 +0000370 Ok(())
Jooyung Han95884632021-07-06 22:27:54 +0900371}
372
Jiyong Park9dd389e2021-08-23 20:42:59 +0900373fn format_as_android_vm_instance(part: &mut dyn Write) -> std::io::Result<()> {
374 part.write_all(ANDROID_VM_INSTANCE_MAGIC.as_bytes())?;
375 part.write_all(&ANDROID_VM_INSTANCE_VERSION.to_le_bytes())?;
376 part.flush()
377}
378
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000379/// Given the configuration for a disk image, assembles the `DiskFile` to pass to crosvm.
380///
381/// This may involve assembling a composite disk from a set of partition images.
382fn assemble_disk_image(
383 disk: &DiskImage,
Jooyung Han95884632021-07-06 22:27:54 +0900384 zero_filler_path: &Path,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000385 temporary_directory: &Path,
386 next_temporary_image_id: &mut u64,
387 indirect_files: &mut Vec<File>,
Andrew Walbran806f1542021-06-10 14:07:12 +0000388) -> Result<DiskFile, Status> {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000389 let image = if !disk.partitions.is_empty() {
390 if disk.image.is_some() {
391 warn!("DiskImage {:?} contains both image and partitions.", disk);
Andrew Walbran806f1542021-06-10 14:07:12 +0000392 return Err(new_binder_exception(
393 ExceptionCode::ILLEGAL_ARGUMENT,
394 "DiskImage contains both image and partitions.",
395 ));
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000396 }
397
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000398 let composite_image_filenames =
399 make_composite_image_filenames(temporary_directory, next_temporary_image_id);
400 let (image, partition_files) = make_composite_image(
401 &disk.partitions,
Jooyung Han95884632021-07-06 22:27:54 +0900402 zero_filler_path,
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000403 &composite_image_filenames.composite,
404 &composite_image_filenames.header,
405 &composite_image_filenames.footer,
406 )
407 .map_err(|e| {
408 error!("Failed to make composite image with config {:?}: {}", disk, e);
409 new_binder_exception(
410 ExceptionCode::SERVICE_SPECIFIC,
411 format!("Failed to make composite image: {}", e),
412 )
413 })?;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000414
415 // Pass the file descriptors for the various partition files to crosvm when it
416 // is run.
417 indirect_files.extend(partition_files);
418
419 image
420 } else if let Some(image) = &disk.image {
421 clone_file(image)?
422 } else {
423 warn!("DiskImage {:?} didn't contain image or partitions.", disk);
Andrew Walbran806f1542021-06-10 14:07:12 +0000424 return Err(new_binder_exception(
425 ExceptionCode::ILLEGAL_ARGUMENT,
426 "DiskImage didn't contain image or partitions.",
427 ));
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000428 };
429
430 Ok(DiskFile { image, writable: disk.writable })
431}
432
Jooyung Han21e9b922021-06-26 04:14:16 +0900433fn load_app_config(
434 config: &VirtualMachineAppConfig,
435 temporary_directory: &Path,
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900436) -> Result<VirtualMachineRawConfig> {
Andrew Walbrancc0db522021-07-12 17:03:42 +0000437 let apk_file = clone_file(config.apk.as_ref().unwrap())?;
438 let idsig_file = clone_file(config.idsig.as_ref().unwrap())?;
Jiyong Park8d081812021-07-23 17:45:04 +0900439 let instance_file = clone_file(config.instanceImage.as_ref().unwrap())?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900440 let config_path = &config.configPath;
441
Andrew Walbrancc0db522021-07-12 17:03:42 +0000442 let mut apk_zip = ZipArchive::new(&apk_file)?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900443 let config_file = apk_zip.by_name(config_path)?;
444 let vm_payload_config: VmPayloadConfig = serde_json::from_reader(config_file)?;
445
446 let os_name = &vm_payload_config.os.name;
Andrew Walbrancc0db522021-07-12 17:03:42 +0000447
Jooyung Han35edb8f2021-07-01 16:17:16 +0900448 // For now, the only supported "os" value is "microdroid"
449 if os_name != "microdroid" {
Andrew Walbrancc0db522021-07-12 17:03:42 +0000450 bail!("Unknown OS \"{}\"", os_name);
Jooyung Han35edb8f2021-07-01 16:17:16 +0900451 }
Andrew Walbrancc0db522021-07-12 17:03:42 +0000452
453 // It is safe to construct a filename based on the os_name because we've already checked that it
454 // is one of the allowed values.
Jooyung Han21e9b922021-06-26 04:14:16 +0900455 let vm_config_path = PathBuf::from(format!("/apex/com.android.virt/etc/{}.json", os_name));
456 let vm_config_file = File::open(vm_config_path)?;
Andrew Walbrancc0db522021-07-12 17:03:42 +0000457 let mut vm_config = VmConfig::load(&vm_config_file)?.to_parcelable()?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900458
Andrew Walbrancc045902021-07-27 16:06:17 +0000459 if config.memoryMib > 0 {
460 vm_config.memoryMib = config.memoryMib;
Andrew Walbran45bcb0c2021-07-14 15:02:06 +0000461 }
462
Andrew Walbrancc0db522021-07-12 17:03:42 +0000463 // Microdroid requires an additional payload disk image and the bootconfig partition.
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900464 if os_name == "microdroid" {
Andrew Walbrancc0db522021-07-12 17:03:42 +0000465 let apexes = vm_payload_config.apexes.clone();
466 add_microdroid_images(
467 config,
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900468 temporary_directory,
Andrew Walbrancc0db522021-07-12 17:03:42 +0000469 apk_file,
470 idsig_file,
Jiyong Park8d081812021-07-23 17:45:04 +0900471 instance_file,
Andrew Walbrancc0db522021-07-12 17:03:42 +0000472 apexes,
473 &mut vm_config,
474 )?;
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900475 }
Jooyung Han21e9b922021-06-26 04:14:16 +0900476
Andrew Walbrancc0db522021-07-12 17:03:42 +0000477 Ok(vm_config)
Jooyung Han21e9b922021-06-26 04:14:16 +0900478}
479
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000480/// Generates a unique filename to use for a composite disk image.
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000481fn make_composite_image_filenames(
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000482 temporary_directory: &Path,
483 next_temporary_image_id: &mut u64,
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000484) -> CompositeImageFilenames {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000485 let id = *next_temporary_image_id;
486 *next_temporary_image_id += 1;
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000487 CompositeImageFilenames {
488 composite: temporary_directory.join(format!("composite-{}.img", id)),
489 header: temporary_directory.join(format!("composite-{}-header.img", id)),
490 footer: temporary_directory.join(format!("composite-{}-footer.img", id)),
491 }
492}
493
494/// Filenames for a composite disk image, including header and footer partitions.
495#[derive(Clone, Debug, Eq, PartialEq)]
496struct CompositeImageFilenames {
497 /// The composite disk image itself.
498 composite: PathBuf,
499 /// The header partition image.
500 header: PathBuf,
501 /// The footer partition image.
502 footer: PathBuf,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000503}
504
505/// Gets the calling SID of the current Binder thread.
Andrew Walbran806f1542021-06-10 14:07:12 +0000506fn get_calling_sid() -> Result<String, Status> {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000507 ThreadState::with_calling_sid(|sid| {
508 if let Some(sid) = sid {
509 match sid.to_str() {
510 Ok(sid) => Ok(sid.to_owned()),
511 Err(e) => {
Andrew Walbran806f1542021-06-10 14:07:12 +0000512 error!("SID was not valid UTF-8: {}", e);
513 Err(new_binder_exception(
514 ExceptionCode::ILLEGAL_ARGUMENT,
515 format!("SID was not valid UTF-8: {}", e),
516 ))
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000517 }
518 }
519 } else {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000520 error!("Missing SID on createVm");
521 Err(new_binder_exception(ExceptionCode::SECURITY, "Missing SID on createVm"))
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000522 }
523 })
524}
525
Jiyong Park753553b2021-07-12 21:21:09 +0900526/// Checks whether the caller has a specific permission
527fn check_permission(perm: &str) -> binder::Result<()> {
528 let calling_pid = ThreadState::get_calling_pid();
529 let calling_uid = ThreadState::get_calling_uid();
530 // Root can do anything
531 if calling_uid == 0 {
532 return Ok(());
533 }
534 let perm_svc: Strong<dyn IPermissionController::IPermissionController> =
535 binder::get_interface("permission")?;
536 if perm_svc.checkPermission(perm, calling_pid, calling_uid as i32)? {
Andrew Walbran806f1542021-06-10 14:07:12 +0000537 Ok(())
538 } else {
Jiyong Park753553b2021-07-12 21:21:09 +0900539 Err(new_binder_exception(
540 ExceptionCode::SECURITY,
541 format!("does not have the {} permission", perm),
542 ))
Andrew Walbran806f1542021-06-10 14:07:12 +0000543 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000544}
545
Jiyong Park753553b2021-07-12 21:21:09 +0900546/// Check whether the caller of the current Binder method is allowed to call debug methods.
547fn check_debug_access() -> binder::Result<()> {
548 check_permission("android.permission.DEBUG_VIRTUAL_MACHINE")
549}
550
551/// Check whether the caller of the current Binder method is allowed to manage VMs
552fn check_manage_access() -> binder::Result<()> {
553 check_permission("android.permission.MANAGE_VIRTUAL_MACHINE")
554}
555
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000556/// Implementation of the AIDL `IVirtualMachine` interface. Used as a handle to a VM.
557#[derive(Debug)]
558struct VirtualMachine {
559 instance: Arc<VmInstance>,
560}
561
562impl VirtualMachine {
563 fn create(instance: Arc<VmInstance>) -> Strong<dyn IVirtualMachine> {
564 let binder = VirtualMachine { instance };
Andrew Walbran4de28782021-04-13 14:51:43 +0000565 BnVirtualMachine::new_binder(binder, BinderFeatures::default())
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000566 }
567}
568
569impl Interface for VirtualMachine {}
570
571impl IVirtualMachine for VirtualMachine {
572 fn getCid(&self) -> binder::Result<i32> {
Jiyong Park753553b2021-07-12 21:21:09 +0900573 // Don't check permission. The owner of the VM might have passed this binder object to
574 // others.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000575 Ok(self.instance.cid as i32)
576 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000577
Andrew Walbran6b650662021-09-07 13:13:23 +0000578 fn getState(&self) -> binder::Result<VirtualMachineState> {
Jiyong Park753553b2021-07-12 21:21:09 +0900579 // Don't check permission. The owner of the VM might have passed this binder object to
580 // others.
Andrew Walbran6b650662021-09-07 13:13:23 +0000581 Ok(get_state(&self.instance))
Andrew Walbrandae07162021-03-12 17:05:20 +0000582 }
583
584 fn registerCallback(
585 &self,
586 callback: &Strong<dyn IVirtualMachineCallback>,
587 ) -> binder::Result<()> {
Jiyong Park753553b2021-07-12 21:21:09 +0900588 // Don't check permission. The owner of the VM might have passed this binder object to
589 // others.
590 //
Andrew Walbrandae07162021-03-12 17:05:20 +0000591 // TODO: Should this give an error if the VM is already dead?
592 self.instance.callbacks.add(callback.clone());
593 Ok(())
594 }
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000595
Andrew Walbranf8d94112021-09-07 11:45:36 +0000596 fn start(&self) -> binder::Result<()> {
597 self.instance.start().map_err(|e| {
598 error!("Error starting VM with CID {}: {:?}", self.instance.cid, e);
599 new_binder_exception(ExceptionCode::SERVICE_SPECIFIC, e.to_string())
600 })
601 }
602
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000603 fn connectVsock(&self, port: i32) -> binder::Result<ParcelFileDescriptor> {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000604 if !matches!(&*self.instance.vm_state.lock().unwrap(), VmState::Running { .. }) {
605 return Err(new_binder_exception(ExceptionCode::SERVICE_SPECIFIC, "VM is not running"));
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000606 }
607 let stream =
608 VsockStream::connect_with_cid_port(self.instance.cid, port as u32).map_err(|e| {
609 new_binder_exception(
610 ExceptionCode::SERVICE_SPECIFIC,
611 format!("Failed to connect: {}", e),
612 )
613 })?;
614 Ok(vsock_stream_to_pfd(stream))
615 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000616}
617
618impl Drop for VirtualMachine {
619 fn drop(&mut self) {
620 debug!("Dropping {:?}", self);
621 self.instance.kill();
622 }
623}
624
625/// A set of Binders to be called back in response to various events on the VM, such as when it
626/// dies.
627#[derive(Debug, Default)]
628pub struct VirtualMachineCallbacks(Mutex<Vec<Strong<dyn IVirtualMachineCallback>>>);
629
630impl VirtualMachineCallbacks {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900631 /// Call all registered callbacks to notify that the payload has started.
Inseob Kim7f61fe72021-08-20 20:50:47 +0900632 pub fn notify_payload_started(&self, cid: Cid, stream: Option<VsockStream>) {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900633 let callbacks = &*self.0.lock().unwrap();
Inseob Kim7f61fe72021-08-20 20:50:47 +0900634 let pfd = stream.map(vsock_stream_to_pfd);
Jiyong Park8611a6c2021-07-09 18:17:44 +0900635 for callback in callbacks {
Inseob Kim7f61fe72021-08-20 20:50:47 +0900636 if let Err(e) = callback.onPayloadStarted(cid as i32, pfd.as_ref()) {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900637 error!("Error notifying payload start event from VM CID {}: {}", cid, e);
638 }
639 }
640 }
641
Inseob Kim14cb8692021-08-31 21:50:39 +0900642 /// Call all registered callbacks to notify that the payload is ready to serve.
643 pub fn notify_payload_ready(&self, cid: Cid) {
644 let callbacks = &*self.0.lock().unwrap();
645 for callback in callbacks {
646 if let Err(e) = callback.onPayloadReady(cid as i32) {
647 error!("Error notifying payload ready event from VM CID {}: {}", cid, e);
648 }
649 }
650 }
651
Inseob Kim2444af92021-08-31 01:22:50 +0900652 /// Call all registered callbacks to notify that the payload has finished.
653 pub fn notify_payload_finished(&self, cid: Cid, exit_code: i32) {
654 let callbacks = &*self.0.lock().unwrap();
655 for callback in callbacks {
656 if let Err(e) = callback.onPayloadFinished(cid as i32, exit_code) {
657 error!("Error notifying payload finish event from VM CID {}: {}", cid, e);
658 }
659 }
660 }
661
Andrew Walbrandae07162021-03-12 17:05:20 +0000662 /// Call all registered callbacks to say that the VM has died.
663 pub fn callback_on_died(&self, cid: Cid) {
664 let callbacks = &*self.0.lock().unwrap();
665 for callback in callbacks {
666 if let Err(e) = callback.onDied(cid as i32) {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900667 error!("Error notifying exit of VM CID {}: {}", cid, e);
Andrew Walbrandae07162021-03-12 17:05:20 +0000668 }
669 }
670 }
671
672 /// Add a new callback to the set.
673 fn add(&self, callback: Strong<dyn IVirtualMachineCallback>) {
674 self.0.lock().unwrap().push(callback);
675 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000676}
677
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000678/// The mutable state of the VirtualizationService. There should only be one instance of this
679/// struct.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000680#[derive(Debug)]
681struct State {
Andrew Walbran320b5602021-03-04 16:11:12 +0000682 /// The VMs which have been started. When VMs are started a weak reference is added to this list
683 /// while a strong reference is returned to the caller over Binder. Once all copies of the
684 /// Binder client are dropped the weak reference here will become invalid, and will be removed
685 /// from the list opportunistically the next time `add_vm` is called.
686 vms: Vec<Weak<VmInstance>>,
David Brazdil3c2ddef2021-03-18 13:09:57 +0000687
688 /// Vector of strong VM references held on behalf of users that cannot hold them themselves.
689 /// This is only used for debugging purposes.
690 debug_held_vms: Vec<Strong<dyn IVirtualMachine>>,
Andrew Walbran320b5602021-03-04 16:11:12 +0000691}
692
693impl State {
Andrew Walbrandae07162021-03-12 17:05:20 +0000694 /// Get a list of VMs which still have Binder references to them.
Andrew Walbran320b5602021-03-04 16:11:12 +0000695 fn vms(&self) -> Vec<Arc<VmInstance>> {
696 // Attempt to upgrade the weak pointers to strong pointers.
697 self.vms.iter().filter_map(Weak::upgrade).collect()
698 }
699
700 /// Add a new VM to the list.
701 fn add_vm(&mut self, vm: Weak<VmInstance>) {
702 // Garbage collect any entries from the stored list which no longer exist.
703 self.vms.retain(|vm| vm.strong_count() > 0);
704
705 // Actually add the new VM.
706 self.vms.push(vm);
707 }
David Brazdil3c2ddef2021-03-18 13:09:57 +0000708
Jiyong Park8611a6c2021-07-09 18:17:44 +0900709 /// Get a VM that corresponds to the given cid
710 fn get_vm(&self, cid: Cid) -> Option<Arc<VmInstance>> {
711 self.vms().into_iter().find(|vm| vm.cid == cid)
712 }
713
David Brazdil3c2ddef2021-03-18 13:09:57 +0000714 /// Store a strong VM reference.
715 fn debug_hold_vm(&mut self, vm: Strong<dyn IVirtualMachine>) {
716 self.debug_held_vms.push(vm);
Alan Stokes7e54e292021-09-09 11:37:56 +0100717 // Make sure our process is not shut down while we hold the VM reference
718 // on behalf of the caller.
719 force_lazy_services_persist(true);
David Brazdil3c2ddef2021-03-18 13:09:57 +0000720 }
721
722 /// Retrieve and remove a strong VM reference.
723 fn debug_drop_vm(&mut self, cid: i32) -> Option<Strong<dyn IVirtualMachine>> {
724 let pos = self.debug_held_vms.iter().position(|vm| vm.getCid() == Ok(cid))?;
Alan Stokes7e54e292021-09-09 11:37:56 +0100725 let vm = self.debug_held_vms.swap_remove(pos);
726 if self.debug_held_vms.is_empty() {
727 // Once we no longer hold any VM references it is ok for our process to be shut down.
728 force_lazy_services_persist(false);
729 }
730 Some(vm)
David Brazdil3c2ddef2021-03-18 13:09:57 +0000731 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000732}
733
734impl Default for State {
735 fn default() -> Self {
Jiyong Parkd50a0242021-09-16 21:00:14 +0900736 State { vms: vec![], debug_held_vms: vec![] }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000737 }
738}
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000739
Jiyong Parkd50a0242021-09-16 21:00:14 +0900740/// Get the next available CID, or an error if we have run out. The last CID used is stored in
741/// a system property so that restart of virtualizationservice doesn't reuse CID while the host
742/// Android is up.
743fn next_cid() -> Result<Cid> {
744 let next = if let Ok(val) = system_properties::read(SYSPROP_LAST_CID) {
745 if let Ok(num) = val.parse::<u32>() {
746 num.checked_add(1).ok_or_else(|| anyhow!("run out of CID"))?
747 } else {
748 error!("Invalid last CID {}. Using {}", &val, FIRST_GUEST_CID);
749 FIRST_GUEST_CID
750 }
751 } else {
752 // First VM since the boot
753 FIRST_GUEST_CID
754 };
755 // Persist the last value for next use
756 let str_val = format!("{}", next);
757 system_properties::write(SYSPROP_LAST_CID, &str_val)?;
758 Ok(next)
759}
760
Andrew Walbran6b650662021-09-07 13:13:23 +0000761/// Gets the `VirtualMachineState` of the given `VmInstance`.
762fn get_state(instance: &VmInstance) -> VirtualMachineState {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000763 match &*instance.vm_state.lock().unwrap() {
764 VmState::NotStarted { .. } => VirtualMachineState::NOT_STARTED,
765 VmState::Running { .. } => match instance.payload_state() {
Andrew Walbran6b650662021-09-07 13:13:23 +0000766 PayloadState::Starting => VirtualMachineState::STARTING,
767 PayloadState::Started => VirtualMachineState::STARTED,
768 PayloadState::Ready => VirtualMachineState::READY,
769 PayloadState::Finished => VirtualMachineState::FINISHED,
Andrew Walbranf8d94112021-09-07 11:45:36 +0000770 },
771 VmState::Dead => VirtualMachineState::DEAD,
772 VmState::Failed => VirtualMachineState::DEAD,
Andrew Walbran6b650662021-09-07 13:13:23 +0000773 }
774}
775
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000776/// Converts a `&ParcelFileDescriptor` to a `File` by cloning the file.
Andrew Walbran806f1542021-06-10 14:07:12 +0000777fn clone_file(file: &ParcelFileDescriptor) -> Result<File, Status> {
778 file.as_ref().try_clone().map_err(|e| {
779 new_binder_exception(
780 ExceptionCode::BAD_PARCELABLE,
781 format!("Failed to clone File from ParcelFileDescriptor: {}", e),
782 )
783 })
784}
785
Andrew Walbrand3a84182021-09-07 14:48:52 +0000786/// Converts an `&Option<ParcelFileDescriptor>` to an `Option<File>` by cloning the file.
787fn maybe_clone_file(file: &Option<ParcelFileDescriptor>) -> Result<Option<File>, Status> {
788 file.as_ref().map(clone_file).transpose()
789}
790
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000791/// Converts a `VsockStream` to a `ParcelFileDescriptor`.
792fn vsock_stream_to_pfd(stream: VsockStream) -> ParcelFileDescriptor {
793 // SAFETY: ownership is transferred from stream to f
794 let f = unsafe { File::from_raw_fd(stream.into_raw_fd()) };
795 ParcelFileDescriptor::new(f)
796}
797
Jooyung Han35edb8f2021-07-01 16:17:16 +0900798/// Simple utility for referencing Borrowed or Owned. Similar to std::borrow::Cow, but
799/// it doesn't require that T implements Clone.
800enum BorrowedOrOwned<'a, T> {
801 Borrowed(&'a T),
802 Owned(T),
803}
804
805impl<'a, T> AsRef<T> for BorrowedOrOwned<'a, T> {
806 fn as_ref(&self) -> &T {
807 match self {
808 Self::Borrowed(b) => b,
Chris Wailes68c39f82021-07-27 16:03:44 -0700809 Self::Owned(o) => o,
Jooyung Han35edb8f2021-07-01 16:17:16 +0900810 }
811 }
812}
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900813
814/// Implementation of `IVirtualMachineService`, the entry point of the AIDL service.
815#[derive(Debug, Default)]
816struct VirtualMachineService {
817 state: Arc<Mutex<State>>,
818}
819
820impl Interface for VirtualMachineService {}
821
822impl IVirtualMachineService for VirtualMachineService {
823 fn notifyPayloadStarted(&self, cid: i32) -> binder::Result<()> {
824 let cid = cid as Cid;
Inseob Kim7f61fe72021-08-20 20:50:47 +0900825 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
826 info!("VM having CID {} started payload", cid);
Andrew Walbran6b650662021-09-07 13:13:23 +0000827 vm.update_payload_state(PayloadState::Started)
828 .map_err(|e| new_binder_exception(ExceptionCode::ILLEGAL_STATE, e.to_string()))?;
Inseob Kim7f61fe72021-08-20 20:50:47 +0900829 let stream = vm.stream.lock().unwrap().take();
830 vm.callbacks.notify_payload_started(cid, stream);
831 Ok(())
832 } else {
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900833 error!("notifyPayloadStarted is called from an unknown cid {}", cid);
Inseob Kim7f61fe72021-08-20 20:50:47 +0900834 Err(new_binder_exception(
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900835 ExceptionCode::SERVICE_SPECIFIC,
836 format!("cannot find a VM with cid {}", cid),
Inseob Kim7f61fe72021-08-20 20:50:47 +0900837 ))
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900838 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900839 }
Inseob Kim2444af92021-08-31 01:22:50 +0900840
Inseob Kim14cb8692021-08-31 21:50:39 +0900841 fn notifyPayloadReady(&self, cid: i32) -> binder::Result<()> {
842 let cid = cid as Cid;
843 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
844 info!("VM having CID {} payload is ready", cid);
Andrew Walbran6b650662021-09-07 13:13:23 +0000845 vm.update_payload_state(PayloadState::Ready)
846 .map_err(|e| new_binder_exception(ExceptionCode::ILLEGAL_STATE, e.to_string()))?;
Inseob Kim14cb8692021-08-31 21:50:39 +0900847 vm.callbacks.notify_payload_ready(cid);
848 Ok(())
849 } else {
850 error!("notifyPayloadReady is called from an unknown cid {}", cid);
851 Err(new_binder_exception(
852 ExceptionCode::SERVICE_SPECIFIC,
853 format!("cannot find a VM with cid {}", cid),
854 ))
855 }
856 }
857
Inseob Kim2444af92021-08-31 01:22:50 +0900858 fn notifyPayloadFinished(&self, cid: i32, exit_code: i32) -> binder::Result<()> {
859 let cid = cid as Cid;
860 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
861 info!("VM having CID {} finished payload", cid);
Andrew Walbran6b650662021-09-07 13:13:23 +0000862 vm.update_payload_state(PayloadState::Finished)
863 .map_err(|e| new_binder_exception(ExceptionCode::ILLEGAL_STATE, e.to_string()))?;
Inseob Kim2444af92021-08-31 01:22:50 +0900864 vm.callbacks.notify_payload_finished(cid, exit_code);
865 Ok(())
866 } else {
867 error!("notifyPayloadFinished is called from an unknown cid {}", cid);
868 Err(new_binder_exception(
869 ExceptionCode::SERVICE_SPECIFIC,
870 format!("cannot find a VM with cid {}", cid),
871 ))
872 }
873 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900874}
875
876impl VirtualMachineService {
877 fn new_binder(state: Arc<Mutex<State>>) -> Strong<dyn IVirtualMachineService> {
878 BnVirtualMachineService::new_binder(
879 VirtualMachineService { state },
880 BinderFeatures::default(),
881 )
882 }
883}