blob: 2738e2ed5dd7722022b5d5eec6ccdc4a49e5cc4f [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,
Jiyong Parkc2a49cc2021-10-15 00:02:12 +090030 VirtualMachineAppConfig::DebugLevel::DebugLevel,
Jooyung Han21e9b922021-06-26 04:14:16 +090031 VirtualMachineAppConfig::VirtualMachineAppConfig,
32 VirtualMachineConfig::VirtualMachineConfig,
Andrew Walbran6b650662021-09-07 13:13:23 +000033 VirtualMachineDebugInfo::VirtualMachineDebugInfo,
Jooyung Han21e9b922021-06-26 04:14:16 +090034 VirtualMachineRawConfig::VirtualMachineRawConfig,
Andrew Walbran6b650662021-09-07 13:13:23 +000035 VirtualMachineState::VirtualMachineState,
Jooyung Han21e9b922021-06-26 04:14:16 +090036};
Andrew Walbranf6bf6862021-05-21 12:41:13 +000037use android_system_virtualizationservice::binder::{
Alan Stokes0cc59ee2021-09-24 11:20:34 +010038 self, BinderFeatures, ExceptionCode, Interface, ParcelFileDescriptor, Status, Strong,
39 ThreadState,
Andrew Walbrana89fc132021-03-17 17:08:36 +000040};
Alan Stokes0cc59ee2021-09-24 11:20:34 +010041use android_system_virtualmachineservice::aidl::android::system::virtualmachineservice::{
42 IVirtualMachineService::{
43 BnVirtualMachineService, IVirtualMachineService, VM_BINDER_SERVICE_PORT,
44 VM_STREAM_SERVICE_PORT,
45 },
Inseob Kim1b95f2e2021-08-19 13:17:40 +090046};
Jiyong Parkd50a0242021-09-16 21:00:14 +090047use anyhow::{anyhow, bail, Context, Result};
Alan Stokes0cc59ee2021-09-24 11:20:34 +010048use binder_common::{lazy_service::LazyServiceGuard, new_binder_exception};
Andrew Walbrandfc953d2021-06-10 13:59:56 +000049use disk::QcowFile;
Alan Stokes0cc59ee2021-09-24 11:20:34 +010050use idsig::{HashAlgorithm, V4Signature};
51use log::{debug, error, info, warn};
Andrew Walbrancc0db522021-07-12 17:03:42 +000052use microdroid_payload_config::VmPayloadConfig;
Jiyong Parkd50a0242021-09-16 21:00:14 +090053use rustutils::system_properties;
Andrew Walbrandff3b942021-06-09 15:20:36 +000054use std::convert::TryInto;
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;
Andrew Walbrand3a84182021-09-07 14:48:52 +000058use std::os::unix::io::{FromRawFd, IntoRawFd};
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000059use std::path::{Path, PathBuf};
Andrew Walbran320b5602021-03-04 16:11:12 +000060use std::sync::{Arc, Mutex, Weak};
Andrew Walbrancc0db522021-07-12 17:03:42 +000061use vmconfig::VmConfig;
Inseob Kim7f61fe72021-08-20 20:50:47 +090062use vsock::{SockAddr, VsockListener, VsockStream};
Jooyung Han35edb8f2021-07-01 16:17:16 +090063use zip::ZipArchive;
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000064
Andrew Walbranf6bf6862021-05-21 12:41:13 +000065pub const BINDER_SERVICE_IDENTIFIER: &str = "android.system.virtualizationservice";
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000066
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000067/// Directory in which to write disk image files used while running VMs.
Andrew Walbran488bd072021-07-14 13:29:51 +000068pub const TEMPORARY_DIRECTORY: &str = "/data/misc/virtualizationservice";
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000069
Jiyong Park8611a6c2021-07-09 18:17:44 +090070/// The CID representing the host VM
71const VMADDR_CID_HOST: u32 = 2;
72
Jooyung Han95884632021-07-06 22:27:54 +090073/// The size of zero.img.
74/// Gaps in composite disk images are filled with a shared zero.img.
75const ZERO_FILLER_SIZE: u64 = 4096;
76
Jiyong Park9dd389e2021-08-23 20:42:59 +090077/// Magic string for the instance image
78const ANDROID_VM_INSTANCE_MAGIC: &str = "Android-VM-instance";
79
80/// Version of the instance image format
81const ANDROID_VM_INSTANCE_VERSION: u16 = 1;
82
Andrew Walbranf6bf6862021-05-21 12:41:13 +000083/// Implementation of `IVirtualizationService`, the entry point of the AIDL service.
Jooyung Han9900f3d2021-07-06 10:27:54 +090084#[derive(Debug, Default)]
Andrew Walbranf6bf6862021-05-21 12:41:13 +000085pub struct VirtualizationService {
Jiyong Park8611a6c2021-07-09 18:17:44 +090086 state: Arc<Mutex<State>>,
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000087}
88
Andrew Walbranf6bf6862021-05-21 12:41:13 +000089impl Interface for VirtualizationService {}
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000090
Andrew Walbranf6bf6862021-05-21 12:41:13 +000091impl IVirtualizationService for VirtualizationService {
Andrew Walbranf8d94112021-09-07 11:45:36 +000092 /// Creates (but does not start) a new VM with the given configuration, assigning it the next
93 /// available CID.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000094 ///
95 /// Returns a binder `IVirtualMachine` object referring to it, as a handle for the client.
Andrew Walbranf8d94112021-09-07 11:45:36 +000096 fn createVm(
Andrew Walbrana89fc132021-03-17 17:08:36 +000097 &self,
Andrew Walbran3a5a9212021-05-04 17:09:08 +000098 config: &VirtualMachineConfig,
Andrew Walbrana89fc132021-03-17 17:08:36 +000099 log_fd: Option<&ParcelFileDescriptor>,
100 ) -> binder::Result<Strong<dyn IVirtualMachine>> {
Jiyong Park753553b2021-07-12 21:21:09 +0900101 check_manage_access()?;
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000102 let state = &mut *self.state.lock().unwrap();
Jiyong Parkc2a49cc2021-10-15 00:02:12 +0900103 let mut log_fd = log_fd.map(clone_file).transpose()?;
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000104 let requester_uid = ThreadState::get_calling_uid();
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000105 let requester_sid = get_calling_sid()?;
Andrew Walbran02034492021-04-13 15:05:07 +0000106 let requester_debug_pid = ThreadState::get_calling_pid();
Jiyong Parkd50a0242021-09-16 21:00:14 +0900107 let cid = next_cid().or(Err(ExceptionCode::ILLEGAL_STATE))?;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000108
109 // Counter to generate unique IDs for temporary image files.
110 let mut next_temporary_image_id = 0;
111 // Files which are referred to from composite images. These must be mapped to the crosvm
112 // child process, and not closed before it is started.
113 let mut indirect_files = vec![];
114
115 // Make directory for temporary files.
116 let temporary_directory: PathBuf = format!("{}/{}", TEMPORARY_DIRECTORY, cid).into();
117 create_dir(&temporary_directory).map_err(|e| {
118 error!(
Andrew Walbran806f1542021-06-10 14:07:12 +0000119 "Failed to create temporary directory {:?} for VM files: {}",
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000120 temporary_directory, e
121 );
Andrew Walbran806f1542021-06-10 14:07:12 +0000122 new_binder_exception(
123 ExceptionCode::SERVICE_SPECIFIC,
124 format!(
125 "Failed to create temporary directory {:?} for VM files: {}",
126 temporary_directory, e
127 ),
128 )
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000129 })?;
130
Jiyong Parkc2a49cc2021-10-15 00:02:12 +0900131 // Disable console logging if debug level != full. Note that kernel anyway doesn't use the
132 // console output when debug level != full. So, users won't be able to see the kernel
133 // output even without this overriding. This is to silence output from the bootloader which
134 // doesn't understand the bootconfig parameters.
135 if let VirtualMachineConfig::AppConfig(config) = config {
136 if config.debugLevel != DebugLevel::FULL {
137 log_fd = None;
138 }
139 }
140
Jooyung Han21e9b922021-06-26 04:14:16 +0900141 let config = match config {
Jooyung Han35edb8f2021-07-01 16:17:16 +0900142 VirtualMachineConfig::AppConfig(config) => BorrowedOrOwned::Owned(
Jooyung Han9900f3d2021-07-06 10:27:54 +0900143 load_app_config(config, &temporary_directory).map_err(|e| {
144 error!("Failed to load app config from {}: {}", &config.configPath, e);
145 new_binder_exception(
146 ExceptionCode::SERVICE_SPECIFIC,
147 format!("Failed to load app config from {}: {}", &config.configPath, e),
148 )
149 })?,
Jooyung Han35edb8f2021-07-01 16:17:16 +0900150 ),
151 VirtualMachineConfig::RawConfig(config) => BorrowedOrOwned::Borrowed(config),
Jooyung Han21e9b922021-06-26 04:14:16 +0900152 };
Jooyung Han35edb8f2021-07-01 16:17:16 +0900153 let config = config.as_ref();
Jooyung Han21e9b922021-06-26 04:14:16 +0900154
Jooyung Han95884632021-07-06 22:27:54 +0900155 let zero_filler_path = temporary_directory.join("zero.img");
Andrew Walbranfbb39d22021-07-28 17:01:25 +0000156 write_zero_filler(&zero_filler_path).map_err(|e| {
Jooyung Han95884632021-07-06 22:27:54 +0900157 error!("Failed to make composite image: {}", e);
158 new_binder_exception(
159 ExceptionCode::SERVICE_SPECIFIC,
160 format!("Failed to make composite image: {}", e),
161 )
162 })?;
Jooyung Han95884632021-07-06 22:27:54 +0900163
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000164 // Assemble disk images if needed.
165 let disks = config
166 .disks
167 .iter()
168 .map(|disk| {
169 assemble_disk_image(
170 disk,
Jooyung Han95884632021-07-06 22:27:54 +0900171 &zero_filler_path,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000172 &temporary_directory,
173 &mut next_temporary_image_id,
174 &mut indirect_files,
175 )
176 })
177 .collect::<Result<Vec<DiskFile>, _>>()?;
178
179 // Actually start the VM.
180 let crosvm_config = CrosvmConfig {
Andrew Walbran02034492021-04-13 15:05:07 +0000181 cid,
Andrew Walbrand3a84182021-09-07 14:48:52 +0000182 bootloader: maybe_clone_file(&config.bootloader)?,
183 kernel: maybe_clone_file(&config.kernel)?,
184 initrd: maybe_clone_file(&config.initrd)?,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000185 disks,
186 params: config.params.to_owned(),
Andrew Walbrancc045902021-07-27 16:06:17 +0000187 protected: config.protectedVm,
188 memory_mib: config.memoryMib.try_into().ok().and_then(NonZeroU32::new),
Andrew Walbran02034492021-04-13 15:05:07 +0000189 log_fd,
Andrew Walbrand3a84182021-09-07 14:48:52 +0000190 indirect_files,
191 };
Andrew Walbranf8d94112021-09-07 11:45:36 +0000192 let instance = Arc::new(
193 VmInstance::new(
194 crosvm_config,
195 temporary_directory,
196 requester_uid,
197 requester_sid,
198 requester_debug_pid,
Andrew Walbran806f1542021-06-10 14:07:12 +0000199 )
Andrew Walbranf8d94112021-09-07 11:45:36 +0000200 .map_err(|e| {
201 error!("Failed to create VM with config {:?}: {}", config, e);
202 new_binder_exception(
203 ExceptionCode::SERVICE_SPECIFIC,
204 format!("Failed to create VM: {}", e),
205 )
206 })?,
207 );
Andrew Walbran320b5602021-03-04 16:11:12 +0000208 state.add_vm(Arc::downgrade(&instance));
209 Ok(VirtualMachine::create(instance))
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000210 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000211
Andrew Walbrandff3b942021-06-09 15:20:36 +0000212 /// Initialise an empty partition image of the given size to be used as a writable partition.
213 fn initializeWritablePartition(
214 &self,
215 image_fd: &ParcelFileDescriptor,
216 size: i64,
Jiyong Park9dd389e2021-08-23 20:42:59 +0900217 partition_type: PartitionType,
Andrew Walbrandff3b942021-06-09 15:20:36 +0000218 ) -> binder::Result<()> {
Jiyong Park753553b2021-07-12 21:21:09 +0900219 check_manage_access()?;
Andrew Walbrandfc953d2021-06-10 13:59:56 +0000220 let size = size.try_into().map_err(|e| {
Andrew Walbran806f1542021-06-10 14:07:12 +0000221 new_binder_exception(
222 ExceptionCode::ILLEGAL_ARGUMENT,
223 format!("Invalid size {}: {}", size, e),
224 )
Andrew Walbrandff3b942021-06-09 15:20:36 +0000225 })?;
Andrew Walbrandfc953d2021-06-10 13:59:56 +0000226 let image = clone_file(image_fd)?;
Andrew Walbrandff3b942021-06-09 15:20:36 +0000227
Jiyong Park9dd389e2021-08-23 20:42:59 +0900228 let mut part = QcowFile::new(image, size).map_err(|e| {
Andrew Walbran806f1542021-06-10 14:07:12 +0000229 new_binder_exception(
230 ExceptionCode::SERVICE_SPECIFIC,
231 format!("Failed to create QCOW2 image: {}", e),
232 )
Andrew Walbrandfc953d2021-06-10 13:59:56 +0000233 })?;
Andrew Walbrandff3b942021-06-09 15:20:36 +0000234
Jiyong Park9dd389e2021-08-23 20:42:59 +0900235 match partition_type {
236 PartitionType::RAW => Ok(()),
237 PartitionType::ANDROID_VM_INSTANCE => format_as_android_vm_instance(&mut part),
238 _ => Err(Error::new(
239 ErrorKind::Unsupported,
240 format!("Unsupported partition type {:?}", partition_type),
241 )),
242 }
243 .map_err(|e| {
244 new_binder_exception(
245 ExceptionCode::SERVICE_SPECIFIC,
246 format!("Failed to initialize partition as {:?}: {}", partition_type, e),
247 )
248 })?;
249
Andrew Walbrandff3b942021-06-09 15:20:36 +0000250 Ok(())
251 }
252
Jiyong Park0a248432021-08-20 23:32:39 +0900253 /// Creates or update the idsig file by digesting the input APK file.
254 fn createOrUpdateIdsigFile(
255 &self,
256 input_fd: &ParcelFileDescriptor,
257 idsig_fd: &ParcelFileDescriptor,
258 ) -> binder::Result<()> {
259 // TODO(b/193504400): do this only when (1) idsig_fd is empty or (2) the APK digest in
260 // idsig_fd is different from APK digest in input_fd
261
262 let mut input = clone_file(input_fd)?;
263 let mut sig = V4Signature::create(&mut input, 4096, &[], HashAlgorithm::SHA256).unwrap();
264
265 let mut output = clone_file(idsig_fd)?;
266 output.set_len(0).unwrap();
267 sig.write_into(&mut output).unwrap();
268 Ok(())
269 }
270
Andrew Walbran320b5602021-03-04 16:11:12 +0000271 /// Get a list of all currently running VMs. This method is only intended for debug purposes,
272 /// and as such is only permitted from the shell user.
273 fn debugListVms(&self) -> binder::Result<Vec<VirtualMachineDebugInfo>> {
Andrew Walbran806f1542021-06-10 14:07:12 +0000274 check_debug_access()?;
Andrew Walbran320b5602021-03-04 16:11:12 +0000275
276 let state = &mut *self.state.lock().unwrap();
277 let vms = state.vms();
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000278 let cids = vms
279 .into_iter()
280 .map(|vm| VirtualMachineDebugInfo {
281 cid: vm.cid as i32,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000282 temporaryDirectory: vm.temporary_directory.to_string_lossy().to_string(),
Andrew Walbran1ef19ae2021-04-07 11:31:57 +0000283 requesterUid: vm.requester_uid as i32,
284 requesterSid: vm.requester_sid.clone(),
Andrew Walbran02034492021-04-13 15:05:07 +0000285 requesterPid: vm.requester_debug_pid,
Andrew Walbran6b650662021-09-07 13:13:23 +0000286 state: get_state(&vm),
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000287 })
288 .collect();
Andrew Walbran320b5602021-03-04 16:11:12 +0000289 Ok(cids)
290 }
David Brazdil3c2ddef2021-03-18 13:09:57 +0000291
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000292 /// Hold a strong reference to a VM in VirtualizationService. This method is only intended for
293 /// debug purposes, and as such is only permitted from the shell user.
Andrei Homescu1415c132021-03-24 02:39:55 +0000294 fn debugHoldVmRef(&self, vmref: &Strong<dyn IVirtualMachine>) -> binder::Result<()> {
Andrew Walbran806f1542021-06-10 14:07:12 +0000295 check_debug_access()?;
David Brazdil3c2ddef2021-03-18 13:09:57 +0000296
David Brazdil3c2ddef2021-03-18 13:09:57 +0000297 let state = &mut *self.state.lock().unwrap();
Andrei Homescu1415c132021-03-24 02:39:55 +0000298 state.debug_hold_vm(vmref.clone());
David Brazdil3c2ddef2021-03-18 13:09:57 +0000299 Ok(())
300 }
301
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000302 /// Drop reference to a VM that is being held by VirtualizationService. Returns the reference if
303 /// the VM was found and None otherwise. This method is only intended for debug purposes, and as
304 /// such is only permitted from the shell user.
David Brazdil3c2ddef2021-03-18 13:09:57 +0000305 fn debugDropVmRef(&self, cid: i32) -> binder::Result<Option<Strong<dyn IVirtualMachine>>> {
Andrew Walbran806f1542021-06-10 14:07:12 +0000306 check_debug_access()?;
David Brazdil3c2ddef2021-03-18 13:09:57 +0000307
308 let state = &mut *self.state.lock().unwrap();
309 Ok(state.debug_drop_vm(cid))
310 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000311}
312
Jiyong Park8611a6c2021-07-09 18:17:44 +0900313impl VirtualizationService {
314 pub fn init() -> VirtualizationService {
315 let service = VirtualizationService::default();
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900316
317 // server for payload output
Jiyong Park8611a6c2021-07-09 18:17:44 +0900318 let state = service.state.clone(); // reference to state (not the state itself) is copied
319 std::thread::spawn(move || {
Inseob Kim7f61fe72021-08-20 20:50:47 +0900320 handle_stream_connection_from_vm(state).unwrap();
Jiyong Park8611a6c2021-07-09 18:17:44 +0900321 });
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900322
323 // binder server for vm
324 let state = service.state.clone(); // reference to state (not the state itself) is copied
325 std::thread::spawn(move || {
326 let mut service = VirtualMachineService::new_binder(state).as_binder();
327 debug!("virtual machine service is starting as an RPC service.");
328 // SAFETY: Service ownership is transferring to the server and won't be valid afterward.
329 // Plus the binder objects are threadsafe.
330 let retval = unsafe {
331 binder_rpc_unstable_bindgen::RunRpcServer(
332 service.as_native_mut() as *mut binder_rpc_unstable_bindgen::AIBinder,
Inseob Kimd0587562021-09-01 21:27:32 +0900333 VM_BINDER_SERVICE_PORT as u32,
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900334 )
335 };
336 if retval {
337 debug!("RPC server has shut down gracefully");
338 } else {
339 bail!("Premature termination of RPC server");
340 }
341
342 Ok(retval)
343 });
Jiyong Park8611a6c2021-07-09 18:17:44 +0900344 service
345 }
346}
347
Andrew Walbran6b650662021-09-07 13:13:23 +0000348/// Waits for incoming connections from VM. If a new connection is made, stores the stream in the
349/// corresponding `VmInstance`.
Inseob Kim7f61fe72021-08-20 20:50:47 +0900350fn handle_stream_connection_from_vm(state: Arc<Mutex<State>>) -> Result<()> {
Inseob Kimd0587562021-09-01 21:27:32 +0900351 let listener =
352 VsockListener::bind_with_cid_port(VMADDR_CID_HOST, VM_STREAM_SERVICE_PORT as u32)?;
Jiyong Park8611a6c2021-07-09 18:17:44 +0900353 for stream in listener.incoming() {
354 let stream = match stream {
355 Err(e) => {
356 warn!("invalid incoming connection: {}", e);
357 continue;
358 }
359 Ok(s) => s,
360 };
361 if let Ok(SockAddr::Vsock(addr)) = stream.peer_addr() {
362 let cid = addr.cid();
363 let port = addr.port();
Inseob Kim7f61fe72021-08-20 20:50:47 +0900364 info!("payload stream connected from cid={}, port={}", cid, port);
Jiyong Park8611a6c2021-07-09 18:17:44 +0900365 if let Some(vm) = state.lock().unwrap().get_vm(cid) {
Chris Wailes8bbb8932021-09-10 14:14:19 -0700366 *vm.stream.lock().unwrap() = Some(stream);
Inseob Kim7f61fe72021-08-20 20:50:47 +0900367 } else {
368 error!("connection from cid={} is not from a guest VM", cid);
Jiyong Park8611a6c2021-07-09 18:17:44 +0900369 }
370 }
371 }
372 Ok(())
373}
374
Andrew Walbranfbb39d22021-07-28 17:01:25 +0000375fn write_zero_filler(zero_filler_path: &Path) -> Result<()> {
Jooyung Han95884632021-07-06 22:27:54 +0900376 let file = OpenOptions::new()
377 .create_new(true)
378 .read(true)
379 .write(true)
380 .open(zero_filler_path)
381 .with_context(|| "Failed to create zero.img")?;
382 file.set_len(ZERO_FILLER_SIZE)?;
Andrew Walbranfbb39d22021-07-28 17:01:25 +0000383 Ok(())
Jooyung Han95884632021-07-06 22:27:54 +0900384}
385
Jiyong Park9dd389e2021-08-23 20:42:59 +0900386fn format_as_android_vm_instance(part: &mut dyn Write) -> std::io::Result<()> {
387 part.write_all(ANDROID_VM_INSTANCE_MAGIC.as_bytes())?;
388 part.write_all(&ANDROID_VM_INSTANCE_VERSION.to_le_bytes())?;
389 part.flush()
390}
391
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000392/// Given the configuration for a disk image, assembles the `DiskFile` to pass to crosvm.
393///
394/// This may involve assembling a composite disk from a set of partition images.
395fn assemble_disk_image(
396 disk: &DiskImage,
Jooyung Han95884632021-07-06 22:27:54 +0900397 zero_filler_path: &Path,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000398 temporary_directory: &Path,
399 next_temporary_image_id: &mut u64,
400 indirect_files: &mut Vec<File>,
Andrew Walbran806f1542021-06-10 14:07:12 +0000401) -> Result<DiskFile, Status> {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000402 let image = if !disk.partitions.is_empty() {
403 if disk.image.is_some() {
404 warn!("DiskImage {:?} contains both image and partitions.", disk);
Andrew Walbran806f1542021-06-10 14:07:12 +0000405 return Err(new_binder_exception(
406 ExceptionCode::ILLEGAL_ARGUMENT,
407 "DiskImage contains both image and partitions.",
408 ));
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000409 }
410
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000411 let composite_image_filenames =
412 make_composite_image_filenames(temporary_directory, next_temporary_image_id);
413 let (image, partition_files) = make_composite_image(
414 &disk.partitions,
Jooyung Han95884632021-07-06 22:27:54 +0900415 zero_filler_path,
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000416 &composite_image_filenames.composite,
417 &composite_image_filenames.header,
418 &composite_image_filenames.footer,
419 )
420 .map_err(|e| {
421 error!("Failed to make composite image with config {:?}: {}", disk, e);
422 new_binder_exception(
423 ExceptionCode::SERVICE_SPECIFIC,
424 format!("Failed to make composite image: {}", e),
425 )
426 })?;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000427
428 // Pass the file descriptors for the various partition files to crosvm when it
429 // is run.
430 indirect_files.extend(partition_files);
431
432 image
433 } else if let Some(image) = &disk.image {
434 clone_file(image)?
435 } else {
436 warn!("DiskImage {:?} didn't contain image or partitions.", disk);
Andrew Walbran806f1542021-06-10 14:07:12 +0000437 return Err(new_binder_exception(
438 ExceptionCode::ILLEGAL_ARGUMENT,
439 "DiskImage didn't contain image or partitions.",
440 ));
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000441 };
442
443 Ok(DiskFile { image, writable: disk.writable })
444}
445
Jooyung Han21e9b922021-06-26 04:14:16 +0900446fn load_app_config(
447 config: &VirtualMachineAppConfig,
448 temporary_directory: &Path,
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900449) -> Result<VirtualMachineRawConfig> {
Andrew Walbrancc0db522021-07-12 17:03:42 +0000450 let apk_file = clone_file(config.apk.as_ref().unwrap())?;
451 let idsig_file = clone_file(config.idsig.as_ref().unwrap())?;
Jiyong Park8d081812021-07-23 17:45:04 +0900452 let instance_file = clone_file(config.instanceImage.as_ref().unwrap())?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900453 let config_path = &config.configPath;
454
Andrew Walbrancc0db522021-07-12 17:03:42 +0000455 let mut apk_zip = ZipArchive::new(&apk_file)?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900456 let config_file = apk_zip.by_name(config_path)?;
457 let vm_payload_config: VmPayloadConfig = serde_json::from_reader(config_file)?;
458
459 let os_name = &vm_payload_config.os.name;
Andrew Walbrancc0db522021-07-12 17:03:42 +0000460
Jooyung Han35edb8f2021-07-01 16:17:16 +0900461 // For now, the only supported "os" value is "microdroid"
462 if os_name != "microdroid" {
Andrew Walbrancc0db522021-07-12 17:03:42 +0000463 bail!("Unknown OS \"{}\"", os_name);
Jooyung Han35edb8f2021-07-01 16:17:16 +0900464 }
Andrew Walbrancc0db522021-07-12 17:03:42 +0000465
466 // It is safe to construct a filename based on the os_name because we've already checked that it
467 // is one of the allowed values.
Jooyung Han21e9b922021-06-26 04:14:16 +0900468 let vm_config_path = PathBuf::from(format!("/apex/com.android.virt/etc/{}.json", os_name));
469 let vm_config_file = File::open(vm_config_path)?;
Andrew Walbrancc0db522021-07-12 17:03:42 +0000470 let mut vm_config = VmConfig::load(&vm_config_file)?.to_parcelable()?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900471
Andrew Walbrancc045902021-07-27 16:06:17 +0000472 if config.memoryMib > 0 {
473 vm_config.memoryMib = config.memoryMib;
Andrew Walbran45bcb0c2021-07-14 15:02:06 +0000474 }
475
Andrew Walbrancc0db522021-07-12 17:03:42 +0000476 // Microdroid requires an additional payload disk image and the bootconfig partition.
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900477 if os_name == "microdroid" {
Andrew Walbrancc0db522021-07-12 17:03:42 +0000478 add_microdroid_images(
479 config,
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900480 temporary_directory,
Andrew Walbrancc0db522021-07-12 17:03:42 +0000481 apk_file,
482 idsig_file,
Jiyong Park8d081812021-07-23 17:45:04 +0900483 instance_file,
Jooyung Han5dc42172021-10-05 16:43:47 +0900484 &vm_payload_config,
Andrew Walbrancc0db522021-07-12 17:03:42 +0000485 &mut vm_config,
486 )?;
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900487 }
Jooyung Han21e9b922021-06-26 04:14:16 +0900488
Andrew Walbrancc0db522021-07-12 17:03:42 +0000489 Ok(vm_config)
Jooyung Han21e9b922021-06-26 04:14:16 +0900490}
491
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000492/// Generates a unique filename to use for a composite disk image.
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000493fn make_composite_image_filenames(
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000494 temporary_directory: &Path,
495 next_temporary_image_id: &mut u64,
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000496) -> CompositeImageFilenames {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000497 let id = *next_temporary_image_id;
498 *next_temporary_image_id += 1;
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000499 CompositeImageFilenames {
500 composite: temporary_directory.join(format!("composite-{}.img", id)),
501 header: temporary_directory.join(format!("composite-{}-header.img", id)),
502 footer: temporary_directory.join(format!("composite-{}-footer.img", id)),
503 }
504}
505
506/// Filenames for a composite disk image, including header and footer partitions.
507#[derive(Clone, Debug, Eq, PartialEq)]
508struct CompositeImageFilenames {
509 /// The composite disk image itself.
510 composite: PathBuf,
511 /// The header partition image.
512 header: PathBuf,
513 /// The footer partition image.
514 footer: PathBuf,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000515}
516
517/// Gets the calling SID of the current Binder thread.
Andrew Walbran806f1542021-06-10 14:07:12 +0000518fn get_calling_sid() -> Result<String, Status> {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000519 ThreadState::with_calling_sid(|sid| {
520 if let Some(sid) = sid {
521 match sid.to_str() {
522 Ok(sid) => Ok(sid.to_owned()),
523 Err(e) => {
Andrew Walbran806f1542021-06-10 14:07:12 +0000524 error!("SID was not valid UTF-8: {}", e);
525 Err(new_binder_exception(
526 ExceptionCode::ILLEGAL_ARGUMENT,
527 format!("SID was not valid UTF-8: {}", e),
528 ))
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000529 }
530 }
531 } else {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000532 error!("Missing SID on createVm");
533 Err(new_binder_exception(ExceptionCode::SECURITY, "Missing SID on createVm"))
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000534 }
535 })
536}
537
Jiyong Park753553b2021-07-12 21:21:09 +0900538/// Checks whether the caller has a specific permission
539fn check_permission(perm: &str) -> binder::Result<()> {
540 let calling_pid = ThreadState::get_calling_pid();
541 let calling_uid = ThreadState::get_calling_uid();
542 // Root can do anything
543 if calling_uid == 0 {
544 return Ok(());
545 }
546 let perm_svc: Strong<dyn IPermissionController::IPermissionController> =
547 binder::get_interface("permission")?;
548 if perm_svc.checkPermission(perm, calling_pid, calling_uid as i32)? {
Andrew Walbran806f1542021-06-10 14:07:12 +0000549 Ok(())
550 } else {
Jiyong Park753553b2021-07-12 21:21:09 +0900551 Err(new_binder_exception(
552 ExceptionCode::SECURITY,
553 format!("does not have the {} permission", perm),
554 ))
Andrew Walbran806f1542021-06-10 14:07:12 +0000555 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000556}
557
Jiyong Park753553b2021-07-12 21:21:09 +0900558/// Check whether the caller of the current Binder method is allowed to call debug methods.
559fn check_debug_access() -> binder::Result<()> {
560 check_permission("android.permission.DEBUG_VIRTUAL_MACHINE")
561}
562
563/// Check whether the caller of the current Binder method is allowed to manage VMs
564fn check_manage_access() -> binder::Result<()> {
565 check_permission("android.permission.MANAGE_VIRTUAL_MACHINE")
566}
567
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000568/// Implementation of the AIDL `IVirtualMachine` interface. Used as a handle to a VM.
569#[derive(Debug)]
570struct VirtualMachine {
571 instance: Arc<VmInstance>,
Alan Stokes0cc59ee2021-09-24 11:20:34 +0100572 /// Keeps our service process running as long as this VM instance exists.
573 lazy_service_guard: LazyServiceGuard,
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000574}
575
576impl VirtualMachine {
577 fn create(instance: Arc<VmInstance>) -> Strong<dyn IVirtualMachine> {
Alan Stokes0cc59ee2021-09-24 11:20:34 +0100578 let binder = VirtualMachine { instance, lazy_service_guard: Default::default() };
Andrew Walbran4de28782021-04-13 14:51:43 +0000579 BnVirtualMachine::new_binder(binder, BinderFeatures::default())
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000580 }
581}
582
583impl Interface for VirtualMachine {}
584
585impl IVirtualMachine for VirtualMachine {
586 fn getCid(&self) -> binder::Result<i32> {
Jiyong Park753553b2021-07-12 21:21:09 +0900587 // Don't check permission. The owner of the VM might have passed this binder object to
588 // others.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000589 Ok(self.instance.cid as i32)
590 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000591
Andrew Walbran6b650662021-09-07 13:13:23 +0000592 fn getState(&self) -> binder::Result<VirtualMachineState> {
Jiyong Park753553b2021-07-12 21:21:09 +0900593 // Don't check permission. The owner of the VM might have passed this binder object to
594 // others.
Andrew Walbran6b650662021-09-07 13:13:23 +0000595 Ok(get_state(&self.instance))
Andrew Walbrandae07162021-03-12 17:05:20 +0000596 }
597
598 fn registerCallback(
599 &self,
600 callback: &Strong<dyn IVirtualMachineCallback>,
601 ) -> binder::Result<()> {
Jiyong Park753553b2021-07-12 21:21:09 +0900602 // Don't check permission. The owner of the VM might have passed this binder object to
603 // others.
604 //
Andrew Walbrandae07162021-03-12 17:05:20 +0000605 // TODO: Should this give an error if the VM is already dead?
606 self.instance.callbacks.add(callback.clone());
607 Ok(())
608 }
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000609
Andrew Walbranf8d94112021-09-07 11:45:36 +0000610 fn start(&self) -> binder::Result<()> {
611 self.instance.start().map_err(|e| {
612 error!("Error starting VM with CID {}: {:?}", self.instance.cid, e);
613 new_binder_exception(ExceptionCode::SERVICE_SPECIFIC, e.to_string())
614 })
615 }
616
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000617 fn connectVsock(&self, port: i32) -> binder::Result<ParcelFileDescriptor> {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000618 if !matches!(&*self.instance.vm_state.lock().unwrap(), VmState::Running { .. }) {
619 return Err(new_binder_exception(ExceptionCode::SERVICE_SPECIFIC, "VM is not running"));
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000620 }
621 let stream =
622 VsockStream::connect_with_cid_port(self.instance.cid, port as u32).map_err(|e| {
623 new_binder_exception(
624 ExceptionCode::SERVICE_SPECIFIC,
625 format!("Failed to connect: {}", e),
626 )
627 })?;
628 Ok(vsock_stream_to_pfd(stream))
629 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000630}
631
632impl Drop for VirtualMachine {
633 fn drop(&mut self) {
634 debug!("Dropping {:?}", self);
635 self.instance.kill();
636 }
637}
638
639/// A set of Binders to be called back in response to various events on the VM, such as when it
640/// dies.
641#[derive(Debug, Default)]
642pub struct VirtualMachineCallbacks(Mutex<Vec<Strong<dyn IVirtualMachineCallback>>>);
643
644impl VirtualMachineCallbacks {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900645 /// Call all registered callbacks to notify that the payload has started.
Inseob Kim7f61fe72021-08-20 20:50:47 +0900646 pub fn notify_payload_started(&self, cid: Cid, stream: Option<VsockStream>) {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900647 let callbacks = &*self.0.lock().unwrap();
Inseob Kim7f61fe72021-08-20 20:50:47 +0900648 let pfd = stream.map(vsock_stream_to_pfd);
Jiyong Park8611a6c2021-07-09 18:17:44 +0900649 for callback in callbacks {
Inseob Kim7f61fe72021-08-20 20:50:47 +0900650 if let Err(e) = callback.onPayloadStarted(cid as i32, pfd.as_ref()) {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900651 error!("Error notifying payload start event from VM CID {}: {}", cid, e);
652 }
653 }
654 }
655
Inseob Kim14cb8692021-08-31 21:50:39 +0900656 /// Call all registered callbacks to notify that the payload is ready to serve.
657 pub fn notify_payload_ready(&self, cid: Cid) {
658 let callbacks = &*self.0.lock().unwrap();
659 for callback in callbacks {
660 if let Err(e) = callback.onPayloadReady(cid as i32) {
661 error!("Error notifying payload ready event from VM CID {}: {}", cid, e);
662 }
663 }
664 }
665
Inseob Kim2444af92021-08-31 01:22:50 +0900666 /// Call all registered callbacks to notify that the payload has finished.
667 pub fn notify_payload_finished(&self, cid: Cid, exit_code: i32) {
668 let callbacks = &*self.0.lock().unwrap();
669 for callback in callbacks {
670 if let Err(e) = callback.onPayloadFinished(cid as i32, exit_code) {
671 error!("Error notifying payload finish event from VM CID {}: {}", cid, e);
672 }
673 }
674 }
675
Andrew Walbrandae07162021-03-12 17:05:20 +0000676 /// Call all registered callbacks to say that the VM has died.
677 pub fn callback_on_died(&self, cid: Cid) {
678 let callbacks = &*self.0.lock().unwrap();
679 for callback in callbacks {
680 if let Err(e) = callback.onDied(cid as i32) {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900681 error!("Error notifying exit of VM CID {}: {}", cid, e);
Andrew Walbrandae07162021-03-12 17:05:20 +0000682 }
683 }
684 }
685
686 /// Add a new callback to the set.
687 fn add(&self, callback: Strong<dyn IVirtualMachineCallback>) {
688 self.0.lock().unwrap().push(callback);
689 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000690}
691
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000692/// The mutable state of the VirtualizationService. There should only be one instance of this
693/// struct.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000694#[derive(Debug)]
695struct State {
Andrew Walbran320b5602021-03-04 16:11:12 +0000696 /// The VMs which have been started. When VMs are started a weak reference is added to this list
697 /// while a strong reference is returned to the caller over Binder. Once all copies of the
698 /// Binder client are dropped the weak reference here will become invalid, and will be removed
699 /// from the list opportunistically the next time `add_vm` is called.
700 vms: Vec<Weak<VmInstance>>,
David Brazdil3c2ddef2021-03-18 13:09:57 +0000701
702 /// Vector of strong VM references held on behalf of users that cannot hold them themselves.
703 /// This is only used for debugging purposes.
704 debug_held_vms: Vec<Strong<dyn IVirtualMachine>>,
Andrew Walbran320b5602021-03-04 16:11:12 +0000705}
706
707impl State {
Andrew Walbrandae07162021-03-12 17:05:20 +0000708 /// Get a list of VMs which still have Binder references to them.
Andrew Walbran320b5602021-03-04 16:11:12 +0000709 fn vms(&self) -> Vec<Arc<VmInstance>> {
710 // Attempt to upgrade the weak pointers to strong pointers.
711 self.vms.iter().filter_map(Weak::upgrade).collect()
712 }
713
714 /// Add a new VM to the list.
715 fn add_vm(&mut self, vm: Weak<VmInstance>) {
716 // Garbage collect any entries from the stored list which no longer exist.
717 self.vms.retain(|vm| vm.strong_count() > 0);
718
719 // Actually add the new VM.
720 self.vms.push(vm);
721 }
David Brazdil3c2ddef2021-03-18 13:09:57 +0000722
Jiyong Park8611a6c2021-07-09 18:17:44 +0900723 /// Get a VM that corresponds to the given cid
724 fn get_vm(&self, cid: Cid) -> Option<Arc<VmInstance>> {
725 self.vms().into_iter().find(|vm| vm.cid == cid)
726 }
727
David Brazdil3c2ddef2021-03-18 13:09:57 +0000728 /// Store a strong VM reference.
729 fn debug_hold_vm(&mut self, vm: Strong<dyn IVirtualMachine>) {
730 self.debug_held_vms.push(vm);
731 }
732
733 /// Retrieve and remove a strong VM reference.
734 fn debug_drop_vm(&mut self, cid: i32) -> Option<Strong<dyn IVirtualMachine>> {
735 let pos = self.debug_held_vms.iter().position(|vm| vm.getCid() == Ok(cid))?;
Alan Stokes7e54e292021-09-09 11:37:56 +0100736 let vm = self.debug_held_vms.swap_remove(pos);
Alan Stokes7e54e292021-09-09 11:37:56 +0100737 Some(vm)
David Brazdil3c2ddef2021-03-18 13:09:57 +0000738 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000739}
740
741impl Default for State {
742 fn default() -> Self {
Jiyong Parkd50a0242021-09-16 21:00:14 +0900743 State { vms: vec![], debug_held_vms: vec![] }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000744 }
745}
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000746
Jiyong Parkd50a0242021-09-16 21:00:14 +0900747/// Get the next available CID, or an error if we have run out. The last CID used is stored in
748/// a system property so that restart of virtualizationservice doesn't reuse CID while the host
749/// Android is up.
750fn next_cid() -> Result<Cid> {
751 let next = if let Ok(val) = system_properties::read(SYSPROP_LAST_CID) {
752 if let Ok(num) = val.parse::<u32>() {
753 num.checked_add(1).ok_or_else(|| anyhow!("run out of CID"))?
754 } else {
755 error!("Invalid last CID {}. Using {}", &val, FIRST_GUEST_CID);
756 FIRST_GUEST_CID
757 }
758 } else {
759 // First VM since the boot
760 FIRST_GUEST_CID
761 };
762 // Persist the last value for next use
763 let str_val = format!("{}", next);
764 system_properties::write(SYSPROP_LAST_CID, &str_val)?;
765 Ok(next)
766}
767
Andrew Walbran6b650662021-09-07 13:13:23 +0000768/// Gets the `VirtualMachineState` of the given `VmInstance`.
769fn get_state(instance: &VmInstance) -> VirtualMachineState {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000770 match &*instance.vm_state.lock().unwrap() {
771 VmState::NotStarted { .. } => VirtualMachineState::NOT_STARTED,
772 VmState::Running { .. } => match instance.payload_state() {
Andrew Walbran6b650662021-09-07 13:13:23 +0000773 PayloadState::Starting => VirtualMachineState::STARTING,
774 PayloadState::Started => VirtualMachineState::STARTED,
775 PayloadState::Ready => VirtualMachineState::READY,
776 PayloadState::Finished => VirtualMachineState::FINISHED,
Andrew Walbranf8d94112021-09-07 11:45:36 +0000777 },
778 VmState::Dead => VirtualMachineState::DEAD,
779 VmState::Failed => VirtualMachineState::DEAD,
Andrew Walbran6b650662021-09-07 13:13:23 +0000780 }
781}
782
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000783/// Converts a `&ParcelFileDescriptor` to a `File` by cloning the file.
Andrew Walbran806f1542021-06-10 14:07:12 +0000784fn clone_file(file: &ParcelFileDescriptor) -> Result<File, Status> {
785 file.as_ref().try_clone().map_err(|e| {
786 new_binder_exception(
787 ExceptionCode::BAD_PARCELABLE,
788 format!("Failed to clone File from ParcelFileDescriptor: {}", e),
789 )
790 })
791}
792
Andrew Walbrand3a84182021-09-07 14:48:52 +0000793/// Converts an `&Option<ParcelFileDescriptor>` to an `Option<File>` by cloning the file.
794fn maybe_clone_file(file: &Option<ParcelFileDescriptor>) -> Result<Option<File>, Status> {
795 file.as_ref().map(clone_file).transpose()
796}
797
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000798/// Converts a `VsockStream` to a `ParcelFileDescriptor`.
799fn vsock_stream_to_pfd(stream: VsockStream) -> ParcelFileDescriptor {
800 // SAFETY: ownership is transferred from stream to f
801 let f = unsafe { File::from_raw_fd(stream.into_raw_fd()) };
802 ParcelFileDescriptor::new(f)
803}
804
Jooyung Han35edb8f2021-07-01 16:17:16 +0900805/// Simple utility for referencing Borrowed or Owned. Similar to std::borrow::Cow, but
806/// it doesn't require that T implements Clone.
807enum BorrowedOrOwned<'a, T> {
808 Borrowed(&'a T),
809 Owned(T),
810}
811
812impl<'a, T> AsRef<T> for BorrowedOrOwned<'a, T> {
813 fn as_ref(&self) -> &T {
814 match self {
815 Self::Borrowed(b) => b,
Chris Wailes68c39f82021-07-27 16:03:44 -0700816 Self::Owned(o) => o,
Jooyung Han35edb8f2021-07-01 16:17:16 +0900817 }
818 }
819}
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900820
821/// Implementation of `IVirtualMachineService`, the entry point of the AIDL service.
822#[derive(Debug, Default)]
823struct VirtualMachineService {
824 state: Arc<Mutex<State>>,
825}
826
827impl Interface for VirtualMachineService {}
828
829impl IVirtualMachineService for VirtualMachineService {
830 fn notifyPayloadStarted(&self, cid: i32) -> binder::Result<()> {
831 let cid = cid as Cid;
Inseob Kim7f61fe72021-08-20 20:50:47 +0900832 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
833 info!("VM having CID {} started payload", cid);
Andrew Walbran6b650662021-09-07 13:13:23 +0000834 vm.update_payload_state(PayloadState::Started)
835 .map_err(|e| new_binder_exception(ExceptionCode::ILLEGAL_STATE, e.to_string()))?;
Inseob Kim7f61fe72021-08-20 20:50:47 +0900836 let stream = vm.stream.lock().unwrap().take();
837 vm.callbacks.notify_payload_started(cid, stream);
838 Ok(())
839 } else {
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900840 error!("notifyPayloadStarted is called from an unknown cid {}", cid);
Inseob Kim7f61fe72021-08-20 20:50:47 +0900841 Err(new_binder_exception(
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900842 ExceptionCode::SERVICE_SPECIFIC,
843 format!("cannot find a VM with cid {}", cid),
Inseob Kim7f61fe72021-08-20 20:50:47 +0900844 ))
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900845 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900846 }
Inseob Kim2444af92021-08-31 01:22:50 +0900847
Inseob Kim14cb8692021-08-31 21:50:39 +0900848 fn notifyPayloadReady(&self, cid: i32) -> binder::Result<()> {
849 let cid = cid as Cid;
850 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
851 info!("VM having CID {} payload is ready", cid);
Andrew Walbran6b650662021-09-07 13:13:23 +0000852 vm.update_payload_state(PayloadState::Ready)
853 .map_err(|e| new_binder_exception(ExceptionCode::ILLEGAL_STATE, e.to_string()))?;
Inseob Kim14cb8692021-08-31 21:50:39 +0900854 vm.callbacks.notify_payload_ready(cid);
855 Ok(())
856 } else {
857 error!("notifyPayloadReady is called from an unknown cid {}", cid);
858 Err(new_binder_exception(
859 ExceptionCode::SERVICE_SPECIFIC,
860 format!("cannot find a VM with cid {}", cid),
861 ))
862 }
863 }
864
Inseob Kim2444af92021-08-31 01:22:50 +0900865 fn notifyPayloadFinished(&self, cid: i32, exit_code: i32) -> binder::Result<()> {
866 let cid = cid as Cid;
867 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
868 info!("VM having CID {} finished payload", cid);
Andrew Walbran6b650662021-09-07 13:13:23 +0000869 vm.update_payload_state(PayloadState::Finished)
870 .map_err(|e| new_binder_exception(ExceptionCode::ILLEGAL_STATE, e.to_string()))?;
Inseob Kim2444af92021-08-31 01:22:50 +0900871 vm.callbacks.notify_payload_finished(cid, exit_code);
872 Ok(())
873 } else {
874 error!("notifyPayloadFinished is called from an unknown cid {}", cid);
875 Err(new_binder_exception(
876 ExceptionCode::SERVICE_SPECIFIC,
877 format!("cannot find a VM with cid {}", cid),
878 ))
879 }
880 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900881}
882
883impl VirtualMachineService {
884 fn new_binder(state: Arc<Mutex<State>>) -> Strong<dyn IVirtualMachineService> {
885 BnVirtualMachineService::new_binder(
886 VirtualMachineService { state },
887 BinderFeatures::default(),
888 )
889 }
890}