blob: dbcc5ce61949b27eae50ca5a27e7a6b4e1b83f3f [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 Stokes0cc59ee2021-09-24 11:20:34 +010022use ::binder::unstable_api::AsNative;
Jiyong Park753553b2021-07-12 21:21:09 +090023use android_os_permissions_aidl::aidl::android::os::IPermissionController;
Jooyung Han21e9b922021-06-26 04:14:16 +090024use android_system_virtualizationservice::aidl::android::system::virtualizationservice::{
Andrew Walbran6b650662021-09-07 13:13:23 +000025 DiskImage::DiskImage,
Alan Stokes0cc59ee2021-09-24 11:20:34 +010026 IVirtualMachine::{BnVirtualMachine, IVirtualMachine},
Andrew Walbran6b650662021-09-07 13:13:23 +000027 IVirtualMachineCallback::IVirtualMachineCallback,
28 IVirtualizationService::IVirtualizationService,
29 PartitionType::PartitionType,
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::{
Alan Stokes0cc59ee2021-09-24 11:20:34 +010037 self, BinderFeatures, ExceptionCode, Interface, ParcelFileDescriptor, Status, Strong,
38 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;
Alan Stokes0cc59ee2021-09-24 11:20:34 +010054use std::fs::{create_dir, File, OpenOptions};
Jiyong Park9dd389e2021-08-23 20:42:59 +090055use std::io::{Error, ErrorKind, Write};
Andrew Walbranb15cd6e2021-07-05 16:38:07 +000056use std::num::NonZeroU32;
Andrew Walbrand3a84182021-09-07 14:48:52 +000057use std::os::unix::io::{FromRawFd, IntoRawFd};
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000058use std::path::{Path, PathBuf};
Andrew Walbran320b5602021-03-04 16:11:12 +000059use std::sync::{Arc, Mutex, Weak};
Andrew Walbrancc0db522021-07-12 17:03:42 +000060use vmconfig::VmConfig;
Inseob Kim7f61fe72021-08-20 20:50:47 +090061use vsock::{SockAddr, VsockListener, VsockStream};
Jooyung Han35edb8f2021-07-01 16:17:16 +090062use zip::ZipArchive;
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000063
Andrew Walbranf6bf6862021-05-21 12:41:13 +000064pub const BINDER_SERVICE_IDENTIFIER: &str = "android.system.virtualizationservice";
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000065
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000066/// Directory in which to write disk image files used while running VMs.
Andrew Walbran488bd072021-07-14 13:29:51 +000067pub const TEMPORARY_DIRECTORY: &str = "/data/misc/virtualizationservice";
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000068
Jiyong Park8611a6c2021-07-09 18:17:44 +090069/// The CID representing the host VM
70const VMADDR_CID_HOST: u32 = 2;
71
Jooyung Han95884632021-07-06 22:27:54 +090072/// The size of zero.img.
73/// Gaps in composite disk images are filled with a shared zero.img.
74const ZERO_FILLER_SIZE: u64 = 4096;
75
Jiyong Park9dd389e2021-08-23 20:42:59 +090076/// Magic string for the instance image
77const ANDROID_VM_INSTANCE_MAGIC: &str = "Android-VM-instance";
78
79/// Version of the instance image format
80const ANDROID_VM_INSTANCE_VERSION: u16 = 1;
81
Andrew Walbranf6bf6862021-05-21 12:41:13 +000082/// Implementation of `IVirtualizationService`, the entry point of the AIDL service.
Jooyung Han9900f3d2021-07-06 10:27:54 +090083#[derive(Debug, Default)]
Andrew Walbranf6bf6862021-05-21 12:41:13 +000084pub struct VirtualizationService {
Jiyong Park8611a6c2021-07-09 18:17:44 +090085 state: Arc<Mutex<State>>,
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000086}
87
Andrew Walbranf6bf6862021-05-21 12:41:13 +000088impl Interface for VirtualizationService {}
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000089
Andrew Walbranf6bf6862021-05-21 12:41:13 +000090impl IVirtualizationService for VirtualizationService {
Andrew Walbranf8d94112021-09-07 11:45:36 +000091 /// Creates (but does not start) a new VM with the given configuration, assigning it the next
92 /// available CID.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000093 ///
94 /// Returns a binder `IVirtualMachine` object referring to it, as a handle for the client.
Andrew Walbranf8d94112021-09-07 11:45:36 +000095 fn createVm(
Andrew Walbrana89fc132021-03-17 17:08:36 +000096 &self,
Andrew Walbran3a5a9212021-05-04 17:09:08 +000097 config: &VirtualMachineConfig,
Andrew Walbrana89fc132021-03-17 17:08:36 +000098 log_fd: Option<&ParcelFileDescriptor>,
99 ) -> binder::Result<Strong<dyn IVirtualMachine>> {
Jiyong Park753553b2021-07-12 21:21:09 +0900100 check_manage_access()?;
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000101 let state = &mut *self.state.lock().unwrap();
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000102 let log_fd = log_fd.map(clone_file).transpose()?;
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000103 let requester_uid = ThreadState::get_calling_uid();
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000104 let requester_sid = get_calling_sid()?;
Andrew Walbran02034492021-04-13 15:05:07 +0000105 let requester_debug_pid = ThreadState::get_calling_pid();
Jiyong Parkd50a0242021-09-16 21:00:14 +0900106 let cid = next_cid().or(Err(ExceptionCode::ILLEGAL_STATE))?;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000107
108 // Counter to generate unique IDs for temporary image files.
109 let mut next_temporary_image_id = 0;
110 // Files which are referred to from composite images. These must be mapped to the crosvm
111 // child process, and not closed before it is started.
112 let mut indirect_files = vec![];
113
114 // Make directory for temporary files.
115 let temporary_directory: PathBuf = format!("{}/{}", TEMPORARY_DIRECTORY, cid).into();
116 create_dir(&temporary_directory).map_err(|e| {
117 error!(
Andrew Walbran806f1542021-06-10 14:07:12 +0000118 "Failed to create temporary directory {:?} for VM files: {}",
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000119 temporary_directory, e
120 );
Andrew Walbran806f1542021-06-10 14:07:12 +0000121 new_binder_exception(
122 ExceptionCode::SERVICE_SPECIFIC,
123 format!(
124 "Failed to create temporary directory {:?} for VM files: {}",
125 temporary_directory, e
126 ),
127 )
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000128 })?;
129
Jooyung Han21e9b922021-06-26 04:14:16 +0900130 let config = match config {
Jooyung Han35edb8f2021-07-01 16:17:16 +0900131 VirtualMachineConfig::AppConfig(config) => BorrowedOrOwned::Owned(
Jooyung Han9900f3d2021-07-06 10:27:54 +0900132 load_app_config(config, &temporary_directory).map_err(|e| {
133 error!("Failed to load app config from {}: {}", &config.configPath, e);
134 new_binder_exception(
135 ExceptionCode::SERVICE_SPECIFIC,
136 format!("Failed to load app config from {}: {}", &config.configPath, e),
137 )
138 })?,
Jooyung Han35edb8f2021-07-01 16:17:16 +0900139 ),
140 VirtualMachineConfig::RawConfig(config) => BorrowedOrOwned::Borrowed(config),
Jooyung Han21e9b922021-06-26 04:14:16 +0900141 };
Jooyung Han35edb8f2021-07-01 16:17:16 +0900142 let config = config.as_ref();
Jooyung Han21e9b922021-06-26 04:14:16 +0900143
Jooyung Han95884632021-07-06 22:27:54 +0900144 let zero_filler_path = temporary_directory.join("zero.img");
Andrew Walbranfbb39d22021-07-28 17:01:25 +0000145 write_zero_filler(&zero_filler_path).map_err(|e| {
Jooyung Han95884632021-07-06 22:27:54 +0900146 error!("Failed to make composite image: {}", e);
147 new_binder_exception(
148 ExceptionCode::SERVICE_SPECIFIC,
149 format!("Failed to make composite image: {}", e),
150 )
151 })?;
Jooyung Han95884632021-07-06 22:27:54 +0900152
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000153 // Assemble disk images if needed.
154 let disks = config
155 .disks
156 .iter()
157 .map(|disk| {
158 assemble_disk_image(
159 disk,
Jooyung Han95884632021-07-06 22:27:54 +0900160 &zero_filler_path,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000161 &temporary_directory,
162 &mut next_temporary_image_id,
163 &mut indirect_files,
164 )
165 })
166 .collect::<Result<Vec<DiskFile>, _>>()?;
167
168 // Actually start the VM.
169 let crosvm_config = CrosvmConfig {
Andrew Walbran02034492021-04-13 15:05:07 +0000170 cid,
Andrew Walbrand3a84182021-09-07 14:48:52 +0000171 bootloader: maybe_clone_file(&config.bootloader)?,
172 kernel: maybe_clone_file(&config.kernel)?,
173 initrd: maybe_clone_file(&config.initrd)?,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000174 disks,
175 params: config.params.to_owned(),
Andrew Walbrancc045902021-07-27 16:06:17 +0000176 protected: config.protectedVm,
177 memory_mib: config.memoryMib.try_into().ok().and_then(NonZeroU32::new),
Andrew Walbran02034492021-04-13 15:05:07 +0000178 log_fd,
Andrew Walbrand3a84182021-09-07 14:48:52 +0000179 indirect_files,
180 };
Andrew Walbranf8d94112021-09-07 11:45:36 +0000181 let instance = Arc::new(
182 VmInstance::new(
183 crosvm_config,
184 temporary_directory,
185 requester_uid,
186 requester_sid,
187 requester_debug_pid,
Andrew Walbran806f1542021-06-10 14:07:12 +0000188 )
Andrew Walbranf8d94112021-09-07 11:45:36 +0000189 .map_err(|e| {
190 error!("Failed to create VM with config {:?}: {}", config, e);
191 new_binder_exception(
192 ExceptionCode::SERVICE_SPECIFIC,
193 format!("Failed to create VM: {}", e),
194 )
195 })?,
196 );
Andrew Walbran320b5602021-03-04 16:11:12 +0000197 state.add_vm(Arc::downgrade(&instance));
198 Ok(VirtualMachine::create(instance))
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000199 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000200
Andrew Walbrandff3b942021-06-09 15:20:36 +0000201 /// Initialise an empty partition image of the given size to be used as a writable partition.
202 fn initializeWritablePartition(
203 &self,
204 image_fd: &ParcelFileDescriptor,
205 size: i64,
Jiyong Park9dd389e2021-08-23 20:42:59 +0900206 partition_type: PartitionType,
Andrew Walbrandff3b942021-06-09 15:20:36 +0000207 ) -> binder::Result<()> {
Jiyong Park753553b2021-07-12 21:21:09 +0900208 check_manage_access()?;
Andrew Walbrandfc953d2021-06-10 13:59:56 +0000209 let size = size.try_into().map_err(|e| {
Andrew Walbran806f1542021-06-10 14:07:12 +0000210 new_binder_exception(
211 ExceptionCode::ILLEGAL_ARGUMENT,
212 format!("Invalid size {}: {}", size, e),
213 )
Andrew Walbrandff3b942021-06-09 15:20:36 +0000214 })?;
Andrew Walbrandfc953d2021-06-10 13:59:56 +0000215 let image = clone_file(image_fd)?;
Andrew Walbrandff3b942021-06-09 15:20:36 +0000216
Jiyong Park9dd389e2021-08-23 20:42:59 +0900217 let mut part = QcowFile::new(image, size).map_err(|e| {
Andrew Walbran806f1542021-06-10 14:07:12 +0000218 new_binder_exception(
219 ExceptionCode::SERVICE_SPECIFIC,
220 format!("Failed to create QCOW2 image: {}", e),
221 )
Andrew Walbrandfc953d2021-06-10 13:59:56 +0000222 })?;
Andrew Walbrandff3b942021-06-09 15:20:36 +0000223
Jiyong Park9dd389e2021-08-23 20:42:59 +0900224 match partition_type {
225 PartitionType::RAW => Ok(()),
226 PartitionType::ANDROID_VM_INSTANCE => format_as_android_vm_instance(&mut part),
227 _ => Err(Error::new(
228 ErrorKind::Unsupported,
229 format!("Unsupported partition type {:?}", partition_type),
230 )),
231 }
232 .map_err(|e| {
233 new_binder_exception(
234 ExceptionCode::SERVICE_SPECIFIC,
235 format!("Failed to initialize partition as {:?}: {}", partition_type, e),
236 )
237 })?;
238
Andrew Walbrandff3b942021-06-09 15:20:36 +0000239 Ok(())
240 }
241
Jiyong Park0a248432021-08-20 23:32:39 +0900242 /// Creates or update the idsig file by digesting the input APK file.
243 fn createOrUpdateIdsigFile(
244 &self,
245 input_fd: &ParcelFileDescriptor,
246 idsig_fd: &ParcelFileDescriptor,
247 ) -> binder::Result<()> {
248 // TODO(b/193504400): do this only when (1) idsig_fd is empty or (2) the APK digest in
249 // idsig_fd is different from APK digest in input_fd
250
251 let mut input = clone_file(input_fd)?;
252 let mut sig = V4Signature::create(&mut input, 4096, &[], HashAlgorithm::SHA256).unwrap();
253
254 let mut output = clone_file(idsig_fd)?;
255 output.set_len(0).unwrap();
256 sig.write_into(&mut output).unwrap();
257 Ok(())
258 }
259
Andrew Walbran320b5602021-03-04 16:11:12 +0000260 /// Get a list of all currently running VMs. This method is only intended for debug purposes,
261 /// and as such is only permitted from the shell user.
262 fn debugListVms(&self) -> binder::Result<Vec<VirtualMachineDebugInfo>> {
Andrew Walbran806f1542021-06-10 14:07:12 +0000263 check_debug_access()?;
Andrew Walbran320b5602021-03-04 16:11:12 +0000264
265 let state = &mut *self.state.lock().unwrap();
266 let vms = state.vms();
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000267 let cids = vms
268 .into_iter()
269 .map(|vm| VirtualMachineDebugInfo {
270 cid: vm.cid as i32,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000271 temporaryDirectory: vm.temporary_directory.to_string_lossy().to_string(),
Andrew Walbran1ef19ae2021-04-07 11:31:57 +0000272 requesterUid: vm.requester_uid as i32,
273 requesterSid: vm.requester_sid.clone(),
Andrew Walbran02034492021-04-13 15:05:07 +0000274 requesterPid: vm.requester_debug_pid,
Andrew Walbran6b650662021-09-07 13:13:23 +0000275 state: get_state(&vm),
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000276 })
277 .collect();
Andrew Walbran320b5602021-03-04 16:11:12 +0000278 Ok(cids)
279 }
David Brazdil3c2ddef2021-03-18 13:09:57 +0000280
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000281 /// Hold a strong reference to a VM in VirtualizationService. This method is only intended for
282 /// debug purposes, and as such is only permitted from the shell user.
Andrei Homescu1415c132021-03-24 02:39:55 +0000283 fn debugHoldVmRef(&self, vmref: &Strong<dyn IVirtualMachine>) -> binder::Result<()> {
Andrew Walbran806f1542021-06-10 14:07:12 +0000284 check_debug_access()?;
David Brazdil3c2ddef2021-03-18 13:09:57 +0000285
David Brazdil3c2ddef2021-03-18 13:09:57 +0000286 let state = &mut *self.state.lock().unwrap();
Andrei Homescu1415c132021-03-24 02:39:55 +0000287 state.debug_hold_vm(vmref.clone());
David Brazdil3c2ddef2021-03-18 13:09:57 +0000288 Ok(())
289 }
290
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000291 /// Drop reference to a VM that is being held by VirtualizationService. Returns the reference if
292 /// the VM was found and None otherwise. This method is only intended for debug purposes, and as
293 /// such is only permitted from the shell user.
David Brazdil3c2ddef2021-03-18 13:09:57 +0000294 fn debugDropVmRef(&self, cid: i32) -> binder::Result<Option<Strong<dyn IVirtualMachine>>> {
Andrew Walbran806f1542021-06-10 14:07:12 +0000295 check_debug_access()?;
David Brazdil3c2ddef2021-03-18 13:09:57 +0000296
297 let state = &mut *self.state.lock().unwrap();
298 Ok(state.debug_drop_vm(cid))
299 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000300}
301
Jiyong Park8611a6c2021-07-09 18:17:44 +0900302impl VirtualizationService {
303 pub fn init() -> VirtualizationService {
304 let service = VirtualizationService::default();
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900305
306 // server for payload output
Jiyong Park8611a6c2021-07-09 18:17:44 +0900307 let state = service.state.clone(); // reference to state (not the state itself) is copied
308 std::thread::spawn(move || {
Inseob Kim7f61fe72021-08-20 20:50:47 +0900309 handle_stream_connection_from_vm(state).unwrap();
Jiyong Park8611a6c2021-07-09 18:17:44 +0900310 });
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900311
312 // binder server for vm
313 let state = service.state.clone(); // reference to state (not the state itself) is copied
314 std::thread::spawn(move || {
315 let mut service = VirtualMachineService::new_binder(state).as_binder();
316 debug!("virtual machine service is starting as an RPC service.");
317 // SAFETY: Service ownership is transferring to the server and won't be valid afterward.
318 // Plus the binder objects are threadsafe.
319 let retval = unsafe {
320 binder_rpc_unstable_bindgen::RunRpcServer(
321 service.as_native_mut() as *mut binder_rpc_unstable_bindgen::AIBinder,
Inseob Kimd0587562021-09-01 21:27:32 +0900322 VM_BINDER_SERVICE_PORT as u32,
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900323 )
324 };
325 if retval {
326 debug!("RPC server has shut down gracefully");
327 } else {
328 bail!("Premature termination of RPC server");
329 }
330
331 Ok(retval)
332 });
Jiyong Park8611a6c2021-07-09 18:17:44 +0900333 service
334 }
335}
336
Andrew Walbran6b650662021-09-07 13:13:23 +0000337/// Waits for incoming connections from VM. If a new connection is made, stores the stream in the
338/// corresponding `VmInstance`.
Inseob Kim7f61fe72021-08-20 20:50:47 +0900339fn handle_stream_connection_from_vm(state: Arc<Mutex<State>>) -> Result<()> {
Inseob Kimd0587562021-09-01 21:27:32 +0900340 let listener =
341 VsockListener::bind_with_cid_port(VMADDR_CID_HOST, VM_STREAM_SERVICE_PORT as u32)?;
Jiyong Park8611a6c2021-07-09 18:17:44 +0900342 for stream in listener.incoming() {
343 let stream = match stream {
344 Err(e) => {
345 warn!("invalid incoming connection: {}", e);
346 continue;
347 }
348 Ok(s) => s,
349 };
350 if let Ok(SockAddr::Vsock(addr)) = stream.peer_addr() {
351 let cid = addr.cid();
352 let port = addr.port();
Inseob Kim7f61fe72021-08-20 20:50:47 +0900353 info!("payload stream connected from cid={}, port={}", cid, port);
Jiyong Park8611a6c2021-07-09 18:17:44 +0900354 if let Some(vm) = state.lock().unwrap().get_vm(cid) {
Chris Wailes8bbb8932021-09-10 14:14:19 -0700355 *vm.stream.lock().unwrap() = Some(stream);
Inseob Kim7f61fe72021-08-20 20:50:47 +0900356 } else {
357 error!("connection from cid={} is not from a guest VM", cid);
Jiyong Park8611a6c2021-07-09 18:17:44 +0900358 }
359 }
360 }
361 Ok(())
362}
363
Andrew Walbranfbb39d22021-07-28 17:01:25 +0000364fn write_zero_filler(zero_filler_path: &Path) -> Result<()> {
Jooyung Han95884632021-07-06 22:27:54 +0900365 let file = OpenOptions::new()
366 .create_new(true)
367 .read(true)
368 .write(true)
369 .open(zero_filler_path)
370 .with_context(|| "Failed to create zero.img")?;
371 file.set_len(ZERO_FILLER_SIZE)?;
Andrew Walbranfbb39d22021-07-28 17:01:25 +0000372 Ok(())
Jooyung Han95884632021-07-06 22:27:54 +0900373}
374
Jiyong Park9dd389e2021-08-23 20:42:59 +0900375fn format_as_android_vm_instance(part: &mut dyn Write) -> std::io::Result<()> {
376 part.write_all(ANDROID_VM_INSTANCE_MAGIC.as_bytes())?;
377 part.write_all(&ANDROID_VM_INSTANCE_VERSION.to_le_bytes())?;
378 part.flush()
379}
380
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000381/// Given the configuration for a disk image, assembles the `DiskFile` to pass to crosvm.
382///
383/// This may involve assembling a composite disk from a set of partition images.
384fn assemble_disk_image(
385 disk: &DiskImage,
Jooyung Han95884632021-07-06 22:27:54 +0900386 zero_filler_path: &Path,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000387 temporary_directory: &Path,
388 next_temporary_image_id: &mut u64,
389 indirect_files: &mut Vec<File>,
Andrew Walbran806f1542021-06-10 14:07:12 +0000390) -> Result<DiskFile, Status> {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000391 let image = if !disk.partitions.is_empty() {
392 if disk.image.is_some() {
393 warn!("DiskImage {:?} contains both image and partitions.", disk);
Andrew Walbran806f1542021-06-10 14:07:12 +0000394 return Err(new_binder_exception(
395 ExceptionCode::ILLEGAL_ARGUMENT,
396 "DiskImage contains both image and partitions.",
397 ));
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000398 }
399
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000400 let composite_image_filenames =
401 make_composite_image_filenames(temporary_directory, next_temporary_image_id);
402 let (image, partition_files) = make_composite_image(
403 &disk.partitions,
Jooyung Han95884632021-07-06 22:27:54 +0900404 zero_filler_path,
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000405 &composite_image_filenames.composite,
406 &composite_image_filenames.header,
407 &composite_image_filenames.footer,
408 )
409 .map_err(|e| {
410 error!("Failed to make composite image with config {:?}: {}", disk, e);
411 new_binder_exception(
412 ExceptionCode::SERVICE_SPECIFIC,
413 format!("Failed to make composite image: {}", e),
414 )
415 })?;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000416
417 // Pass the file descriptors for the various partition files to crosvm when it
418 // is run.
419 indirect_files.extend(partition_files);
420
421 image
422 } else if let Some(image) = &disk.image {
423 clone_file(image)?
424 } else {
425 warn!("DiskImage {:?} didn't contain image or partitions.", disk);
Andrew Walbran806f1542021-06-10 14:07:12 +0000426 return Err(new_binder_exception(
427 ExceptionCode::ILLEGAL_ARGUMENT,
428 "DiskImage didn't contain image or partitions.",
429 ));
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000430 };
431
432 Ok(DiskFile { image, writable: disk.writable })
433}
434
Jooyung Han21e9b922021-06-26 04:14:16 +0900435fn load_app_config(
436 config: &VirtualMachineAppConfig,
437 temporary_directory: &Path,
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900438) -> Result<VirtualMachineRawConfig> {
Andrew Walbrancc0db522021-07-12 17:03:42 +0000439 let apk_file = clone_file(config.apk.as_ref().unwrap())?;
440 let idsig_file = clone_file(config.idsig.as_ref().unwrap())?;
Jiyong Park8d081812021-07-23 17:45:04 +0900441 let instance_file = clone_file(config.instanceImage.as_ref().unwrap())?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900442 let config_path = &config.configPath;
443
Andrew Walbrancc0db522021-07-12 17:03:42 +0000444 let mut apk_zip = ZipArchive::new(&apk_file)?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900445 let config_file = apk_zip.by_name(config_path)?;
446 let vm_payload_config: VmPayloadConfig = serde_json::from_reader(config_file)?;
447
448 let os_name = &vm_payload_config.os.name;
Andrew Walbrancc0db522021-07-12 17:03:42 +0000449
Jooyung Han35edb8f2021-07-01 16:17:16 +0900450 // For now, the only supported "os" value is "microdroid"
451 if os_name != "microdroid" {
Andrew Walbrancc0db522021-07-12 17:03:42 +0000452 bail!("Unknown OS \"{}\"", os_name);
Jooyung Han35edb8f2021-07-01 16:17:16 +0900453 }
Andrew Walbrancc0db522021-07-12 17:03:42 +0000454
455 // It is safe to construct a filename based on the os_name because we've already checked that it
456 // is one of the allowed values.
Jooyung Han21e9b922021-06-26 04:14:16 +0900457 let vm_config_path = PathBuf::from(format!("/apex/com.android.virt/etc/{}.json", os_name));
458 let vm_config_file = File::open(vm_config_path)?;
Andrew Walbrancc0db522021-07-12 17:03:42 +0000459 let mut vm_config = VmConfig::load(&vm_config_file)?.to_parcelable()?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900460
Andrew Walbrancc045902021-07-27 16:06:17 +0000461 if config.memoryMib > 0 {
462 vm_config.memoryMib = config.memoryMib;
Andrew Walbran45bcb0c2021-07-14 15:02:06 +0000463 }
464
Andrew Walbrancc0db522021-07-12 17:03:42 +0000465 // Microdroid requires an additional payload disk image and the bootconfig partition.
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900466 if os_name == "microdroid" {
Andrew Walbrancc0db522021-07-12 17:03:42 +0000467 add_microdroid_images(
468 config,
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900469 temporary_directory,
Andrew Walbrancc0db522021-07-12 17:03:42 +0000470 apk_file,
471 idsig_file,
Jiyong Park8d081812021-07-23 17:45:04 +0900472 instance_file,
Jooyung Han5dc42172021-10-05 16:43:47 +0900473 &vm_payload_config,
Andrew Walbrancc0db522021-07-12 17:03:42 +0000474 &mut vm_config,
475 )?;
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900476 }
Jooyung Han21e9b922021-06-26 04:14:16 +0900477
Andrew Walbrancc0db522021-07-12 17:03:42 +0000478 Ok(vm_config)
Jooyung Han21e9b922021-06-26 04:14:16 +0900479}
480
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000481/// Generates a unique filename to use for a composite disk image.
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000482fn make_composite_image_filenames(
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000483 temporary_directory: &Path,
484 next_temporary_image_id: &mut u64,
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000485) -> CompositeImageFilenames {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000486 let id = *next_temporary_image_id;
487 *next_temporary_image_id += 1;
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000488 CompositeImageFilenames {
489 composite: temporary_directory.join(format!("composite-{}.img", id)),
490 header: temporary_directory.join(format!("composite-{}-header.img", id)),
491 footer: temporary_directory.join(format!("composite-{}-footer.img", id)),
492 }
493}
494
495/// Filenames for a composite disk image, including header and footer partitions.
496#[derive(Clone, Debug, Eq, PartialEq)]
497struct CompositeImageFilenames {
498 /// The composite disk image itself.
499 composite: PathBuf,
500 /// The header partition image.
501 header: PathBuf,
502 /// The footer partition image.
503 footer: PathBuf,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000504}
505
506/// Gets the calling SID of the current Binder thread.
Andrew Walbran806f1542021-06-10 14:07:12 +0000507fn get_calling_sid() -> Result<String, Status> {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000508 ThreadState::with_calling_sid(|sid| {
509 if let Some(sid) = sid {
510 match sid.to_str() {
511 Ok(sid) => Ok(sid.to_owned()),
512 Err(e) => {
Andrew Walbran806f1542021-06-10 14:07:12 +0000513 error!("SID was not valid UTF-8: {}", e);
514 Err(new_binder_exception(
515 ExceptionCode::ILLEGAL_ARGUMENT,
516 format!("SID was not valid UTF-8: {}", e),
517 ))
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000518 }
519 }
520 } else {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000521 error!("Missing SID on createVm");
522 Err(new_binder_exception(ExceptionCode::SECURITY, "Missing SID on createVm"))
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000523 }
524 })
525}
526
Jiyong Park753553b2021-07-12 21:21:09 +0900527/// Checks whether the caller has a specific permission
528fn check_permission(perm: &str) -> binder::Result<()> {
529 let calling_pid = ThreadState::get_calling_pid();
530 let calling_uid = ThreadState::get_calling_uid();
531 // Root can do anything
532 if calling_uid == 0 {
533 return Ok(());
534 }
535 let perm_svc: Strong<dyn IPermissionController::IPermissionController> =
536 binder::get_interface("permission")?;
537 if perm_svc.checkPermission(perm, calling_pid, calling_uid as i32)? {
Andrew Walbran806f1542021-06-10 14:07:12 +0000538 Ok(())
539 } else {
Jiyong Park753553b2021-07-12 21:21:09 +0900540 Err(new_binder_exception(
541 ExceptionCode::SECURITY,
542 format!("does not have the {} permission", perm),
543 ))
Andrew Walbran806f1542021-06-10 14:07:12 +0000544 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000545}
546
Jiyong Park753553b2021-07-12 21:21:09 +0900547/// Check whether the caller of the current Binder method is allowed to call debug methods.
548fn check_debug_access() -> binder::Result<()> {
549 check_permission("android.permission.DEBUG_VIRTUAL_MACHINE")
550}
551
552/// Check whether the caller of the current Binder method is allowed to manage VMs
553fn check_manage_access() -> binder::Result<()> {
554 check_permission("android.permission.MANAGE_VIRTUAL_MACHINE")
555}
556
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000557/// Implementation of the AIDL `IVirtualMachine` interface. Used as a handle to a VM.
558#[derive(Debug)]
559struct VirtualMachine {
560 instance: Arc<VmInstance>,
Alan Stokes0cc59ee2021-09-24 11:20:34 +0100561 /// Keeps our service process running as long as this VM instance exists.
562 lazy_service_guard: LazyServiceGuard,
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000563}
564
565impl VirtualMachine {
566 fn create(instance: Arc<VmInstance>) -> Strong<dyn IVirtualMachine> {
Alan Stokes0cc59ee2021-09-24 11:20:34 +0100567 let binder = VirtualMachine { instance, lazy_service_guard: Default::default() };
Andrew Walbran4de28782021-04-13 14:51:43 +0000568 BnVirtualMachine::new_binder(binder, BinderFeatures::default())
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000569 }
570}
571
572impl Interface for VirtualMachine {}
573
574impl IVirtualMachine for VirtualMachine {
575 fn getCid(&self) -> binder::Result<i32> {
Jiyong Park753553b2021-07-12 21:21:09 +0900576 // Don't check permission. The owner of the VM might have passed this binder object to
577 // others.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000578 Ok(self.instance.cid as i32)
579 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000580
Andrew Walbran6b650662021-09-07 13:13:23 +0000581 fn getState(&self) -> binder::Result<VirtualMachineState> {
Jiyong Park753553b2021-07-12 21:21:09 +0900582 // Don't check permission. The owner of the VM might have passed this binder object to
583 // others.
Andrew Walbran6b650662021-09-07 13:13:23 +0000584 Ok(get_state(&self.instance))
Andrew Walbrandae07162021-03-12 17:05:20 +0000585 }
586
587 fn registerCallback(
588 &self,
589 callback: &Strong<dyn IVirtualMachineCallback>,
590 ) -> binder::Result<()> {
Jiyong Park753553b2021-07-12 21:21:09 +0900591 // Don't check permission. The owner of the VM might have passed this binder object to
592 // others.
593 //
Andrew Walbrandae07162021-03-12 17:05:20 +0000594 // TODO: Should this give an error if the VM is already dead?
595 self.instance.callbacks.add(callback.clone());
596 Ok(())
597 }
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000598
Andrew Walbranf8d94112021-09-07 11:45:36 +0000599 fn start(&self) -> binder::Result<()> {
600 self.instance.start().map_err(|e| {
601 error!("Error starting VM with CID {}: {:?}", self.instance.cid, e);
602 new_binder_exception(ExceptionCode::SERVICE_SPECIFIC, e.to_string())
603 })
604 }
605
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000606 fn connectVsock(&self, port: i32) -> binder::Result<ParcelFileDescriptor> {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000607 if !matches!(&*self.instance.vm_state.lock().unwrap(), VmState::Running { .. }) {
608 return Err(new_binder_exception(ExceptionCode::SERVICE_SPECIFIC, "VM is not running"));
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000609 }
610 let stream =
611 VsockStream::connect_with_cid_port(self.instance.cid, port as u32).map_err(|e| {
612 new_binder_exception(
613 ExceptionCode::SERVICE_SPECIFIC,
614 format!("Failed to connect: {}", e),
615 )
616 })?;
617 Ok(vsock_stream_to_pfd(stream))
618 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000619}
620
621impl Drop for VirtualMachine {
622 fn drop(&mut self) {
623 debug!("Dropping {:?}", self);
624 self.instance.kill();
625 }
626}
627
628/// A set of Binders to be called back in response to various events on the VM, such as when it
629/// dies.
630#[derive(Debug, Default)]
631pub struct VirtualMachineCallbacks(Mutex<Vec<Strong<dyn IVirtualMachineCallback>>>);
632
633impl VirtualMachineCallbacks {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900634 /// Call all registered callbacks to notify that the payload has started.
Inseob Kim7f61fe72021-08-20 20:50:47 +0900635 pub fn notify_payload_started(&self, cid: Cid, stream: Option<VsockStream>) {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900636 let callbacks = &*self.0.lock().unwrap();
Inseob Kim7f61fe72021-08-20 20:50:47 +0900637 let pfd = stream.map(vsock_stream_to_pfd);
Jiyong Park8611a6c2021-07-09 18:17:44 +0900638 for callback in callbacks {
Inseob Kim7f61fe72021-08-20 20:50:47 +0900639 if let Err(e) = callback.onPayloadStarted(cid as i32, pfd.as_ref()) {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900640 error!("Error notifying payload start event from VM CID {}: {}", cid, e);
641 }
642 }
643 }
644
Inseob Kim14cb8692021-08-31 21:50:39 +0900645 /// Call all registered callbacks to notify that the payload is ready to serve.
646 pub fn notify_payload_ready(&self, cid: Cid) {
647 let callbacks = &*self.0.lock().unwrap();
648 for callback in callbacks {
649 if let Err(e) = callback.onPayloadReady(cid as i32) {
650 error!("Error notifying payload ready event from VM CID {}: {}", cid, e);
651 }
652 }
653 }
654
Inseob Kim2444af92021-08-31 01:22:50 +0900655 /// Call all registered callbacks to notify that the payload has finished.
656 pub fn notify_payload_finished(&self, cid: Cid, exit_code: i32) {
657 let callbacks = &*self.0.lock().unwrap();
658 for callback in callbacks {
659 if let Err(e) = callback.onPayloadFinished(cid as i32, exit_code) {
660 error!("Error notifying payload finish event from VM CID {}: {}", cid, e);
661 }
662 }
663 }
664
Andrew Walbrandae07162021-03-12 17:05:20 +0000665 /// Call all registered callbacks to say that the VM has died.
666 pub fn callback_on_died(&self, cid: Cid) {
667 let callbacks = &*self.0.lock().unwrap();
668 for callback in callbacks {
669 if let Err(e) = callback.onDied(cid as i32) {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900670 error!("Error notifying exit of VM CID {}: {}", cid, e);
Andrew Walbrandae07162021-03-12 17:05:20 +0000671 }
672 }
673 }
674
675 /// Add a new callback to the set.
676 fn add(&self, callback: Strong<dyn IVirtualMachineCallback>) {
677 self.0.lock().unwrap().push(callback);
678 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000679}
680
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000681/// The mutable state of the VirtualizationService. There should only be one instance of this
682/// struct.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000683#[derive(Debug)]
684struct State {
Andrew Walbran320b5602021-03-04 16:11:12 +0000685 /// The VMs which have been started. When VMs are started a weak reference is added to this list
686 /// while a strong reference is returned to the caller over Binder. Once all copies of the
687 /// Binder client are dropped the weak reference here will become invalid, and will be removed
688 /// from the list opportunistically the next time `add_vm` is called.
689 vms: Vec<Weak<VmInstance>>,
David Brazdil3c2ddef2021-03-18 13:09:57 +0000690
691 /// Vector of strong VM references held on behalf of users that cannot hold them themselves.
692 /// This is only used for debugging purposes.
693 debug_held_vms: Vec<Strong<dyn IVirtualMachine>>,
Andrew Walbran320b5602021-03-04 16:11:12 +0000694}
695
696impl State {
Andrew Walbrandae07162021-03-12 17:05:20 +0000697 /// Get a list of VMs which still have Binder references to them.
Andrew Walbran320b5602021-03-04 16:11:12 +0000698 fn vms(&self) -> Vec<Arc<VmInstance>> {
699 // Attempt to upgrade the weak pointers to strong pointers.
700 self.vms.iter().filter_map(Weak::upgrade).collect()
701 }
702
703 /// Add a new VM to the list.
704 fn add_vm(&mut self, vm: Weak<VmInstance>) {
705 // Garbage collect any entries from the stored list which no longer exist.
706 self.vms.retain(|vm| vm.strong_count() > 0);
707
708 // Actually add the new VM.
709 self.vms.push(vm);
710 }
David Brazdil3c2ddef2021-03-18 13:09:57 +0000711
Jiyong Park8611a6c2021-07-09 18:17:44 +0900712 /// Get a VM that corresponds to the given cid
713 fn get_vm(&self, cid: Cid) -> Option<Arc<VmInstance>> {
714 self.vms().into_iter().find(|vm| vm.cid == cid)
715 }
716
David Brazdil3c2ddef2021-03-18 13:09:57 +0000717 /// Store a strong VM reference.
718 fn debug_hold_vm(&mut self, vm: Strong<dyn IVirtualMachine>) {
719 self.debug_held_vms.push(vm);
720 }
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);
Alan Stokes7e54e292021-09-09 11:37:56 +0100726 Some(vm)
David Brazdil3c2ddef2021-03-18 13:09:57 +0000727 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000728}
729
730impl Default for State {
731 fn default() -> Self {
Jiyong Parkd50a0242021-09-16 21:00:14 +0900732 State { vms: vec![], debug_held_vms: vec![] }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000733 }
734}
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000735
Jiyong Parkd50a0242021-09-16 21:00:14 +0900736/// Get the next available CID, or an error if we have run out. The last CID used is stored in
737/// a system property so that restart of virtualizationservice doesn't reuse CID while the host
738/// Android is up.
739fn next_cid() -> Result<Cid> {
740 let next = if let Ok(val) = system_properties::read(SYSPROP_LAST_CID) {
741 if let Ok(num) = val.parse::<u32>() {
742 num.checked_add(1).ok_or_else(|| anyhow!("run out of CID"))?
743 } else {
744 error!("Invalid last CID {}. Using {}", &val, FIRST_GUEST_CID);
745 FIRST_GUEST_CID
746 }
747 } else {
748 // First VM since the boot
749 FIRST_GUEST_CID
750 };
751 // Persist the last value for next use
752 let str_val = format!("{}", next);
753 system_properties::write(SYSPROP_LAST_CID, &str_val)?;
754 Ok(next)
755}
756
Andrew Walbran6b650662021-09-07 13:13:23 +0000757/// Gets the `VirtualMachineState` of the given `VmInstance`.
758fn get_state(instance: &VmInstance) -> VirtualMachineState {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000759 match &*instance.vm_state.lock().unwrap() {
760 VmState::NotStarted { .. } => VirtualMachineState::NOT_STARTED,
761 VmState::Running { .. } => match instance.payload_state() {
Andrew Walbran6b650662021-09-07 13:13:23 +0000762 PayloadState::Starting => VirtualMachineState::STARTING,
763 PayloadState::Started => VirtualMachineState::STARTED,
764 PayloadState::Ready => VirtualMachineState::READY,
765 PayloadState::Finished => VirtualMachineState::FINISHED,
Andrew Walbranf8d94112021-09-07 11:45:36 +0000766 },
767 VmState::Dead => VirtualMachineState::DEAD,
768 VmState::Failed => VirtualMachineState::DEAD,
Andrew Walbran6b650662021-09-07 13:13:23 +0000769 }
770}
771
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000772/// Converts a `&ParcelFileDescriptor` to a `File` by cloning the file.
Andrew Walbran806f1542021-06-10 14:07:12 +0000773fn clone_file(file: &ParcelFileDescriptor) -> Result<File, Status> {
774 file.as_ref().try_clone().map_err(|e| {
775 new_binder_exception(
776 ExceptionCode::BAD_PARCELABLE,
777 format!("Failed to clone File from ParcelFileDescriptor: {}", e),
778 )
779 })
780}
781
Andrew Walbrand3a84182021-09-07 14:48:52 +0000782/// Converts an `&Option<ParcelFileDescriptor>` to an `Option<File>` by cloning the file.
783fn maybe_clone_file(file: &Option<ParcelFileDescriptor>) -> Result<Option<File>, Status> {
784 file.as_ref().map(clone_file).transpose()
785}
786
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000787/// Converts a `VsockStream` to a `ParcelFileDescriptor`.
788fn vsock_stream_to_pfd(stream: VsockStream) -> ParcelFileDescriptor {
789 // SAFETY: ownership is transferred from stream to f
790 let f = unsafe { File::from_raw_fd(stream.into_raw_fd()) };
791 ParcelFileDescriptor::new(f)
792}
793
Jooyung Han35edb8f2021-07-01 16:17:16 +0900794/// Simple utility for referencing Borrowed or Owned. Similar to std::borrow::Cow, but
795/// it doesn't require that T implements Clone.
796enum BorrowedOrOwned<'a, T> {
797 Borrowed(&'a T),
798 Owned(T),
799}
800
801impl<'a, T> AsRef<T> for BorrowedOrOwned<'a, T> {
802 fn as_ref(&self) -> &T {
803 match self {
804 Self::Borrowed(b) => b,
Chris Wailes68c39f82021-07-27 16:03:44 -0700805 Self::Owned(o) => o,
Jooyung Han35edb8f2021-07-01 16:17:16 +0900806 }
807 }
808}
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900809
810/// Implementation of `IVirtualMachineService`, the entry point of the AIDL service.
811#[derive(Debug, Default)]
812struct VirtualMachineService {
813 state: Arc<Mutex<State>>,
814}
815
816impl Interface for VirtualMachineService {}
817
818impl IVirtualMachineService for VirtualMachineService {
819 fn notifyPayloadStarted(&self, cid: i32) -> binder::Result<()> {
820 let cid = cid as Cid;
Inseob Kim7f61fe72021-08-20 20:50:47 +0900821 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
822 info!("VM having CID {} started payload", cid);
Andrew Walbran6b650662021-09-07 13:13:23 +0000823 vm.update_payload_state(PayloadState::Started)
824 .map_err(|e| new_binder_exception(ExceptionCode::ILLEGAL_STATE, e.to_string()))?;
Inseob Kim7f61fe72021-08-20 20:50:47 +0900825 let stream = vm.stream.lock().unwrap().take();
826 vm.callbacks.notify_payload_started(cid, stream);
827 Ok(())
828 } else {
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900829 error!("notifyPayloadStarted is called from an unknown cid {}", cid);
Inseob Kim7f61fe72021-08-20 20:50:47 +0900830 Err(new_binder_exception(
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900831 ExceptionCode::SERVICE_SPECIFIC,
832 format!("cannot find a VM with cid {}", cid),
Inseob Kim7f61fe72021-08-20 20:50:47 +0900833 ))
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900834 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900835 }
Inseob Kim2444af92021-08-31 01:22:50 +0900836
Inseob Kim14cb8692021-08-31 21:50:39 +0900837 fn notifyPayloadReady(&self, cid: i32) -> binder::Result<()> {
838 let cid = cid as Cid;
839 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
840 info!("VM having CID {} payload is ready", cid);
Andrew Walbran6b650662021-09-07 13:13:23 +0000841 vm.update_payload_state(PayloadState::Ready)
842 .map_err(|e| new_binder_exception(ExceptionCode::ILLEGAL_STATE, e.to_string()))?;
Inseob Kim14cb8692021-08-31 21:50:39 +0900843 vm.callbacks.notify_payload_ready(cid);
844 Ok(())
845 } else {
846 error!("notifyPayloadReady is called from an unknown cid {}", cid);
847 Err(new_binder_exception(
848 ExceptionCode::SERVICE_SPECIFIC,
849 format!("cannot find a VM with cid {}", cid),
850 ))
851 }
852 }
853
Inseob Kim2444af92021-08-31 01:22:50 +0900854 fn notifyPayloadFinished(&self, cid: i32, exit_code: i32) -> binder::Result<()> {
855 let cid = cid as Cid;
856 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
857 info!("VM having CID {} finished payload", cid);
Andrew Walbran6b650662021-09-07 13:13:23 +0000858 vm.update_payload_state(PayloadState::Finished)
859 .map_err(|e| new_binder_exception(ExceptionCode::ILLEGAL_STATE, e.to_string()))?;
Inseob Kim2444af92021-08-31 01:22:50 +0900860 vm.callbacks.notify_payload_finished(cid, exit_code);
861 Ok(())
862 } else {
863 error!("notifyPayloadFinished is called from an unknown cid {}", cid);
864 Err(new_binder_exception(
865 ExceptionCode::SERVICE_SPECIFIC,
866 format!("cannot find a VM with cid {}", cid),
867 ))
868 }
869 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900870}
871
872impl VirtualMachineService {
873 fn new_binder(state: Arc<Mutex<State>>) -> Strong<dyn IVirtualMachineService> {
874 BnVirtualMachineService::new_binder(
875 VirtualMachineService { state },
876 BinderFeatures::default(),
877 )
878 }
879}