blob: 6b60da38a290ec4595757f4d3cb9768a9411ba36 [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;
18use crate::crosvm::{CrosvmConfig, DiskFile, VmInstance};
Andrew Walbrancc0db522021-07-12 17:03:42 +000019use crate::payload::add_microdroid_images;
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000020use crate::{Cid, FIRST_GUEST_CID};
Jooyung Han21e9b922021-06-26 04:14:16 +090021
Jiyong Park753553b2021-07-12 21:21:09 +090022use android_os_permissions_aidl::aidl::android::os::IPermissionController;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000023use android_system_virtualizationservice::aidl::android::system::virtualizationservice::DiskImage::DiskImage;
Inseob Kim1b95f2e2021-08-19 13:17:40 +090024use android_system_virtualizationservice::aidl::android::system::virtualizationservice::IVirtualizationService::IVirtualizationService;
Andrew Walbranf6bf6862021-05-21 12:41:13 +000025use android_system_virtualizationservice::aidl::android::system::virtualizationservice::IVirtualMachine::{
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000026 BnVirtualMachine, IVirtualMachine,
27};
Andrew Walbranf6bf6862021-05-21 12:41:13 +000028use android_system_virtualizationservice::aidl::android::system::virtualizationservice::IVirtualMachineCallback::IVirtualMachineCallback;
Jooyung Han21e9b922021-06-26 04:14:16 +090029use android_system_virtualizationservice::aidl::android::system::virtualizationservice::{
30 VirtualMachineAppConfig::VirtualMachineAppConfig,
31 VirtualMachineConfig::VirtualMachineConfig,
32 VirtualMachineRawConfig::VirtualMachineRawConfig,
33};
Andrew Walbranf6bf6862021-05-21 12:41:13 +000034use android_system_virtualizationservice::aidl::android::system::virtualizationservice::VirtualMachineDebugInfo::VirtualMachineDebugInfo;
Jiyong Park9dd389e2021-08-23 20:42:59 +090035use android_system_virtualizationservice::aidl::android::system::virtualizationservice::PartitionType::PartitionType;
Andrew Walbranf6bf6862021-05-21 12:41:13 +000036use android_system_virtualizationservice::binder::{
Andrew Walbran806f1542021-06-10 14:07:12 +000037 self, BinderFeatures, ExceptionCode, Interface, ParcelFileDescriptor, Status, Strong, ThreadState,
Andrew Walbrana89fc132021-03-17 17:08:36 +000038};
Inseob Kim1b95f2e2021-08-19 13:17:40 +090039use android_system_virtualmachineservice::aidl::android::system::virtualmachineservice::IVirtualMachineService::{
40 BnVirtualMachineService, IVirtualMachineService,
41};
Jooyung Han95884632021-07-06 22:27:54 +090042use anyhow::{bail, Context, Result};
Inseob Kim1b95f2e2021-08-19 13:17:40 +090043use ::binder::unstable_api::AsNative;
Andrew Walbrandfc953d2021-06-10 13:59:56 +000044use disk::QcowFile;
Jiyong Park0a248432021-08-20 23:32:39 +090045use idsig::{V4Signature, HashAlgorithm};
Jiyong Park8611a6c2021-07-09 18:17:44 +090046use log::{debug, error, warn, info};
Andrew Walbrancc0db522021-07-12 17:03:42 +000047use microdroid_payload_config::VmPayloadConfig;
Andrew Walbrandff3b942021-06-09 15:20:36 +000048use std::convert::TryInto;
Andrew Walbran806f1542021-06-10 14:07:12 +000049use std::ffi::CString;
Jooyung Han95884632021-07-06 22:27:54 +090050use std::fs::{File, OpenOptions, create_dir};
Jiyong Park9dd389e2021-08-23 20:42:59 +090051use std::io::{Error, ErrorKind, Write};
Andrew Walbranb15cd6e2021-07-05 16:38:07 +000052use std::num::NonZeroU32;
Jiyong Park8611a6c2021-07-09 18:17:44 +090053use std::os::unix::io::{AsRawFd, FromRawFd, IntoRawFd};
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000054use std::path::{Path, PathBuf};
Andrew Walbran320b5602021-03-04 16:11:12 +000055use std::sync::{Arc, Mutex, Weak};
Andrew Walbrancc0db522021-07-12 17:03:42 +000056use vmconfig::VmConfig;
Inseob Kim7f61fe72021-08-20 20:50:47 +090057use vsock::{SockAddr, VsockListener, VsockStream};
Jooyung Han35edb8f2021-07-01 16:17:16 +090058use zip::ZipArchive;
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000059
Andrew Walbranf6bf6862021-05-21 12:41:13 +000060pub const BINDER_SERVICE_IDENTIFIER: &str = "android.system.virtualizationservice";
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000061
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000062/// Directory in which to write disk image files used while running VMs.
Andrew Walbran488bd072021-07-14 13:29:51 +000063pub const TEMPORARY_DIRECTORY: &str = "/data/misc/virtualizationservice";
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000064
Jiyong Park8611a6c2021-07-09 18:17:44 +090065/// The CID representing the host VM
66const VMADDR_CID_HOST: u32 = 2;
67
68/// Port number that virtualizationservice listens on connections from the guest VMs for the
Inseob Kim7f61fe72021-08-20 20:50:47 +090069/// payload input and output
70const PORT_VIRT_STREAM_SERVICE: u32 = 3000;
Jiyong Park8611a6c2021-07-09 18:17:44 +090071
Inseob Kim1b95f2e2021-08-19 13:17:40 +090072/// Port number that virtualizationservice listens on connections from the guest VMs for the
73/// VirtualMachineService binder service
74/// Sync with microdroid_manager/src/main.rs
75const PORT_VM_BINDER_SERVICE: u32 = 5000;
76
Jooyung Han95884632021-07-06 22:27:54 +090077/// The size of zero.img.
78/// Gaps in composite disk images are filled with a shared zero.img.
79const ZERO_FILLER_SIZE: u64 = 4096;
80
Jiyong Park9dd389e2021-08-23 20:42:59 +090081/// Magic string for the instance image
82const ANDROID_VM_INSTANCE_MAGIC: &str = "Android-VM-instance";
83
84/// Version of the instance image format
85const ANDROID_VM_INSTANCE_VERSION: u16 = 1;
86
Andrew Walbranf6bf6862021-05-21 12:41:13 +000087/// Implementation of `IVirtualizationService`, the entry point of the AIDL service.
Jooyung Han9900f3d2021-07-06 10:27:54 +090088#[derive(Debug, Default)]
Andrew Walbranf6bf6862021-05-21 12:41:13 +000089pub struct VirtualizationService {
Jiyong Park8611a6c2021-07-09 18:17:44 +090090 state: Arc<Mutex<State>>,
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000091}
92
Andrew Walbranf6bf6862021-05-21 12:41:13 +000093impl Interface for VirtualizationService {}
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000094
Andrew Walbranf6bf6862021-05-21 12:41:13 +000095impl IVirtualizationService for VirtualizationService {
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000096 /// Create and start a new VM with the given configuration, assigning it the next available CID.
97 ///
98 /// Returns a binder `IVirtualMachine` object referring to it, as a handle for the client.
Andrew Walbrana89fc132021-03-17 17:08:36 +000099 fn startVm(
100 &self,
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000101 config: &VirtualMachineConfig,
Andrew Walbrana89fc132021-03-17 17:08:36 +0000102 log_fd: Option<&ParcelFileDescriptor>,
103 ) -> binder::Result<Strong<dyn IVirtualMachine>> {
Jiyong Park753553b2021-07-12 21:21:09 +0900104 check_manage_access()?;
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000105 let state = &mut *self.state.lock().unwrap();
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000106 let log_fd = log_fd.map(clone_file).transpose()?;
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000107 let requester_uid = ThreadState::get_calling_uid();
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000108 let requester_sid = get_calling_sid()?;
Andrew Walbran02034492021-04-13 15:05:07 +0000109 let requester_debug_pid = ThreadState::get_calling_pid();
Andrew Walbrandae07162021-03-12 17:05:20 +0000110 let cid = state.allocate_cid()?;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000111
112 // Counter to generate unique IDs for temporary image files.
113 let mut next_temporary_image_id = 0;
114 // Files which are referred to from composite images. These must be mapped to the crosvm
115 // child process, and not closed before it is started.
116 let mut indirect_files = vec![];
117
118 // Make directory for temporary files.
119 let temporary_directory: PathBuf = format!("{}/{}", TEMPORARY_DIRECTORY, cid).into();
120 create_dir(&temporary_directory).map_err(|e| {
121 error!(
Andrew Walbran806f1542021-06-10 14:07:12 +0000122 "Failed to create temporary directory {:?} for VM files: {}",
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000123 temporary_directory, e
124 );
Andrew Walbran806f1542021-06-10 14:07:12 +0000125 new_binder_exception(
126 ExceptionCode::SERVICE_SPECIFIC,
127 format!(
128 "Failed to create temporary directory {:?} for VM files: {}",
129 temporary_directory, e
130 ),
131 )
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000132 })?;
133
Jooyung Han21e9b922021-06-26 04:14:16 +0900134 let config = match config {
Jooyung Han35edb8f2021-07-01 16:17:16 +0900135 VirtualMachineConfig::AppConfig(config) => BorrowedOrOwned::Owned(
Jooyung Han9900f3d2021-07-06 10:27:54 +0900136 load_app_config(config, &temporary_directory).map_err(|e| {
137 error!("Failed to load app config from {}: {}", &config.configPath, e);
138 new_binder_exception(
139 ExceptionCode::SERVICE_SPECIFIC,
140 format!("Failed to load app config from {}: {}", &config.configPath, e),
141 )
142 })?,
Jooyung Han35edb8f2021-07-01 16:17:16 +0900143 ),
144 VirtualMachineConfig::RawConfig(config) => BorrowedOrOwned::Borrowed(config),
Jooyung Han21e9b922021-06-26 04:14:16 +0900145 };
Jooyung Han35edb8f2021-07-01 16:17:16 +0900146 let config = config.as_ref();
Jooyung Han21e9b922021-06-26 04:14:16 +0900147
Jooyung Han95884632021-07-06 22:27:54 +0900148 let zero_filler_path = temporary_directory.join("zero.img");
Andrew Walbranfbb39d22021-07-28 17:01:25 +0000149 write_zero_filler(&zero_filler_path).map_err(|e| {
Jooyung Han95884632021-07-06 22:27:54 +0900150 error!("Failed to make composite image: {}", e);
151 new_binder_exception(
152 ExceptionCode::SERVICE_SPECIFIC,
153 format!("Failed to make composite image: {}", e),
154 )
155 })?;
Jooyung Han95884632021-07-06 22:27:54 +0900156
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000157 // Assemble disk images if needed.
158 let disks = config
159 .disks
160 .iter()
161 .map(|disk| {
162 assemble_disk_image(
163 disk,
Jooyung Han95884632021-07-06 22:27:54 +0900164 &zero_filler_path,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000165 &temporary_directory,
166 &mut next_temporary_image_id,
167 &mut indirect_files,
168 )
169 })
170 .collect::<Result<Vec<DiskFile>, _>>()?;
171
172 // Actually start the VM.
173 let crosvm_config = CrosvmConfig {
Andrew Walbran02034492021-04-13 15:05:07 +0000174 cid,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000175 bootloader: as_asref(&config.bootloader),
176 kernel: as_asref(&config.kernel),
177 initrd: as_asref(&config.initrd),
178 disks,
179 params: config.params.to_owned(),
Andrew Walbrancc045902021-07-27 16:06:17 +0000180 protected: config.protectedVm,
181 memory_mib: config.memoryMib.try_into().ok().and_then(NonZeroU32::new),
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000182 };
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000183 let composite_disk_fds: Vec<_> =
184 indirect_files.iter().map(|file| file.as_raw_fd()).collect();
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000185 let instance = VmInstance::start(
186 &crosvm_config,
Andrew Walbran02034492021-04-13 15:05:07 +0000187 log_fd,
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000188 &composite_disk_fds,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000189 temporary_directory,
Andrew Walbran02034492021-04-13 15:05:07 +0000190 requester_uid,
191 requester_sid,
192 requester_debug_pid,
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000193 )
194 .map_err(|e| {
Andrew Walbran806f1542021-06-10 14:07:12 +0000195 error!("Failed to start VM with config {:?}: {}", config, e);
196 new_binder_exception(
197 ExceptionCode::SERVICE_SPECIFIC,
198 format!("Failed to start VM: {}", e),
199 )
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000200 })?;
Andrew Walbran320b5602021-03-04 16:11:12 +0000201 state.add_vm(Arc::downgrade(&instance));
202 Ok(VirtualMachine::create(instance))
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000203 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000204
Andrew Walbrandff3b942021-06-09 15:20:36 +0000205 /// Initialise an empty partition image of the given size to be used as a writable partition.
206 fn initializeWritablePartition(
207 &self,
208 image_fd: &ParcelFileDescriptor,
209 size: i64,
Jiyong Park9dd389e2021-08-23 20:42:59 +0900210 partition_type: PartitionType,
Andrew Walbrandff3b942021-06-09 15:20:36 +0000211 ) -> binder::Result<()> {
Jiyong Park753553b2021-07-12 21:21:09 +0900212 check_manage_access()?;
Andrew Walbrandfc953d2021-06-10 13:59:56 +0000213 let size = size.try_into().map_err(|e| {
Andrew Walbran806f1542021-06-10 14:07:12 +0000214 new_binder_exception(
215 ExceptionCode::ILLEGAL_ARGUMENT,
216 format!("Invalid size {}: {}", size, e),
217 )
Andrew Walbrandff3b942021-06-09 15:20:36 +0000218 })?;
Andrew Walbrandfc953d2021-06-10 13:59:56 +0000219 let image = clone_file(image_fd)?;
Andrew Walbrandff3b942021-06-09 15:20:36 +0000220
Jiyong Park9dd389e2021-08-23 20:42:59 +0900221 let mut part = QcowFile::new(image, size).map_err(|e| {
Andrew Walbran806f1542021-06-10 14:07:12 +0000222 new_binder_exception(
223 ExceptionCode::SERVICE_SPECIFIC,
224 format!("Failed to create QCOW2 image: {}", e),
225 )
Andrew Walbrandfc953d2021-06-10 13:59:56 +0000226 })?;
Andrew Walbrandff3b942021-06-09 15:20:36 +0000227
Jiyong Park9dd389e2021-08-23 20:42:59 +0900228 match partition_type {
229 PartitionType::RAW => Ok(()),
230 PartitionType::ANDROID_VM_INSTANCE => format_as_android_vm_instance(&mut part),
231 _ => Err(Error::new(
232 ErrorKind::Unsupported,
233 format!("Unsupported partition type {:?}", partition_type),
234 )),
235 }
236 .map_err(|e| {
237 new_binder_exception(
238 ExceptionCode::SERVICE_SPECIFIC,
239 format!("Failed to initialize partition as {:?}: {}", partition_type, e),
240 )
241 })?;
242
Andrew Walbrandff3b942021-06-09 15:20:36 +0000243 Ok(())
244 }
245
Jiyong Park0a248432021-08-20 23:32:39 +0900246 /// Creates or update the idsig file by digesting the input APK file.
247 fn createOrUpdateIdsigFile(
248 &self,
249 input_fd: &ParcelFileDescriptor,
250 idsig_fd: &ParcelFileDescriptor,
251 ) -> binder::Result<()> {
252 // TODO(b/193504400): do this only when (1) idsig_fd is empty or (2) the APK digest in
253 // idsig_fd is different from APK digest in input_fd
254
255 let mut input = clone_file(input_fd)?;
256 let mut sig = V4Signature::create(&mut input, 4096, &[], HashAlgorithm::SHA256).unwrap();
257
258 let mut output = clone_file(idsig_fd)?;
259 output.set_len(0).unwrap();
260 sig.write_into(&mut output).unwrap();
261 Ok(())
262 }
263
Andrew Walbran320b5602021-03-04 16:11:12 +0000264 /// Get a list of all currently running VMs. This method is only intended for debug purposes,
265 /// and as such is only permitted from the shell user.
266 fn debugListVms(&self) -> binder::Result<Vec<VirtualMachineDebugInfo>> {
Andrew Walbran806f1542021-06-10 14:07:12 +0000267 check_debug_access()?;
Andrew Walbran320b5602021-03-04 16:11:12 +0000268
269 let state = &mut *self.state.lock().unwrap();
270 let vms = state.vms();
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000271 let cids = vms
272 .into_iter()
273 .map(|vm| VirtualMachineDebugInfo {
274 cid: vm.cid as i32,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000275 temporaryDirectory: vm.temporary_directory.to_string_lossy().to_string(),
Andrew Walbran1ef19ae2021-04-07 11:31:57 +0000276 requesterUid: vm.requester_uid as i32,
277 requesterSid: vm.requester_sid.clone(),
Andrew Walbran02034492021-04-13 15:05:07 +0000278 requesterPid: vm.requester_debug_pid,
Andrew Walbrandae07162021-03-12 17:05:20 +0000279 running: vm.running(),
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000280 })
281 .collect();
Andrew Walbran320b5602021-03-04 16:11:12 +0000282 Ok(cids)
283 }
David Brazdil3c2ddef2021-03-18 13:09:57 +0000284
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000285 /// Hold a strong reference to a VM in VirtualizationService. This method is only intended for
286 /// debug purposes, and as such is only permitted from the shell user.
Andrei Homescu1415c132021-03-24 02:39:55 +0000287 fn debugHoldVmRef(&self, vmref: &Strong<dyn IVirtualMachine>) -> binder::Result<()> {
Andrew Walbran806f1542021-06-10 14:07:12 +0000288 check_debug_access()?;
David Brazdil3c2ddef2021-03-18 13:09:57 +0000289
David Brazdil3c2ddef2021-03-18 13:09:57 +0000290 let state = &mut *self.state.lock().unwrap();
Andrei Homescu1415c132021-03-24 02:39:55 +0000291 state.debug_hold_vm(vmref.clone());
David Brazdil3c2ddef2021-03-18 13:09:57 +0000292 Ok(())
293 }
294
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000295 /// Drop reference to a VM that is being held by VirtualizationService. Returns the reference if
296 /// the VM was found and None otherwise. This method is only intended for debug purposes, and as
297 /// such is only permitted from the shell user.
David Brazdil3c2ddef2021-03-18 13:09:57 +0000298 fn debugDropVmRef(&self, cid: i32) -> binder::Result<Option<Strong<dyn IVirtualMachine>>> {
Andrew Walbran806f1542021-06-10 14:07:12 +0000299 check_debug_access()?;
David Brazdil3c2ddef2021-03-18 13:09:57 +0000300
301 let state = &mut *self.state.lock().unwrap();
302 Ok(state.debug_drop_vm(cid))
303 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000304}
305
Jiyong Park8611a6c2021-07-09 18:17:44 +0900306impl VirtualizationService {
307 pub fn init() -> VirtualizationService {
308 let service = VirtualizationService::default();
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900309
310 // server for payload output
Jiyong Park8611a6c2021-07-09 18:17:44 +0900311 let state = service.state.clone(); // reference to state (not the state itself) is copied
312 std::thread::spawn(move || {
Inseob Kim7f61fe72021-08-20 20:50:47 +0900313 handle_stream_connection_from_vm(state).unwrap();
Jiyong Park8611a6c2021-07-09 18:17:44 +0900314 });
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900315
316 // binder server for vm
317 let state = service.state.clone(); // reference to state (not the state itself) is copied
318 std::thread::spawn(move || {
319 let mut service = VirtualMachineService::new_binder(state).as_binder();
320 debug!("virtual machine service is starting as an RPC service.");
321 // SAFETY: Service ownership is transferring to the server and won't be valid afterward.
322 // Plus the binder objects are threadsafe.
323 let retval = unsafe {
324 binder_rpc_unstable_bindgen::RunRpcServer(
325 service.as_native_mut() as *mut binder_rpc_unstable_bindgen::AIBinder,
326 PORT_VM_BINDER_SERVICE,
327 )
328 };
329 if retval {
330 debug!("RPC server has shut down gracefully");
331 } else {
332 bail!("Premature termination of RPC server");
333 }
334
335 Ok(retval)
336 });
Jiyong Park8611a6c2021-07-09 18:17:44 +0900337 service
338 }
339}
340
341/// Waits for incoming connections from VM. If a new connection is made, notify the event to the
342/// client via the callback (if registered).
Inseob Kim7f61fe72021-08-20 20:50:47 +0900343fn handle_stream_connection_from_vm(state: Arc<Mutex<State>>) -> Result<()> {
344 let listener = VsockListener::bind_with_cid_port(VMADDR_CID_HOST, PORT_VIRT_STREAM_SERVICE)?;
Jiyong Park8611a6c2021-07-09 18:17:44 +0900345 for stream in listener.incoming() {
346 let stream = match stream {
347 Err(e) => {
348 warn!("invalid incoming connection: {}", e);
349 continue;
350 }
351 Ok(s) => s,
352 };
353 if let Ok(SockAddr::Vsock(addr)) = stream.peer_addr() {
354 let cid = addr.cid();
355 let port = addr.port();
Inseob Kim7f61fe72021-08-20 20:50:47 +0900356 info!("payload stream connected from cid={}, port={}", cid, port);
Jiyong Park8611a6c2021-07-09 18:17:44 +0900357 if let Some(vm) = state.lock().unwrap().get_vm(cid) {
Inseob Kim7f61fe72021-08-20 20:50:47 +0900358 vm.stream.lock().unwrap().insert(stream);
359 } else {
360 error!("connection from cid={} is not from a guest VM", cid);
Jiyong Park8611a6c2021-07-09 18:17:44 +0900361 }
362 }
363 }
364 Ok(())
365}
366
Andrew Walbranfbb39d22021-07-28 17:01:25 +0000367fn write_zero_filler(zero_filler_path: &Path) -> Result<()> {
Jooyung Han95884632021-07-06 22:27:54 +0900368 let file = OpenOptions::new()
369 .create_new(true)
370 .read(true)
371 .write(true)
372 .open(zero_filler_path)
373 .with_context(|| "Failed to create zero.img")?;
374 file.set_len(ZERO_FILLER_SIZE)?;
Andrew Walbranfbb39d22021-07-28 17:01:25 +0000375 Ok(())
Jooyung Han95884632021-07-06 22:27:54 +0900376}
377
Jiyong Park9dd389e2021-08-23 20:42:59 +0900378fn format_as_android_vm_instance(part: &mut dyn Write) -> std::io::Result<()> {
379 part.write_all(ANDROID_VM_INSTANCE_MAGIC.as_bytes())?;
380 part.write_all(&ANDROID_VM_INSTANCE_VERSION.to_le_bytes())?;
381 part.flush()
382}
383
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000384/// Given the configuration for a disk image, assembles the `DiskFile` to pass to crosvm.
385///
386/// This may involve assembling a composite disk from a set of partition images.
387fn assemble_disk_image(
388 disk: &DiskImage,
Jooyung Han95884632021-07-06 22:27:54 +0900389 zero_filler_path: &Path,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000390 temporary_directory: &Path,
391 next_temporary_image_id: &mut u64,
392 indirect_files: &mut Vec<File>,
Andrew Walbran806f1542021-06-10 14:07:12 +0000393) -> Result<DiskFile, Status> {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000394 let image = if !disk.partitions.is_empty() {
395 if disk.image.is_some() {
396 warn!("DiskImage {:?} contains both image and partitions.", disk);
Andrew Walbran806f1542021-06-10 14:07:12 +0000397 return Err(new_binder_exception(
398 ExceptionCode::ILLEGAL_ARGUMENT,
399 "DiskImage contains both image and partitions.",
400 ));
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000401 }
402
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000403 let composite_image_filenames =
404 make_composite_image_filenames(temporary_directory, next_temporary_image_id);
405 let (image, partition_files) = make_composite_image(
406 &disk.partitions,
Jooyung Han95884632021-07-06 22:27:54 +0900407 zero_filler_path,
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000408 &composite_image_filenames.composite,
409 &composite_image_filenames.header,
410 &composite_image_filenames.footer,
411 )
412 .map_err(|e| {
413 error!("Failed to make composite image with config {:?}: {}", disk, e);
414 new_binder_exception(
415 ExceptionCode::SERVICE_SPECIFIC,
416 format!("Failed to make composite image: {}", e),
417 )
418 })?;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000419
420 // Pass the file descriptors for the various partition files to crosvm when it
421 // is run.
422 indirect_files.extend(partition_files);
423
424 image
425 } else if let Some(image) = &disk.image {
426 clone_file(image)?
427 } else {
428 warn!("DiskImage {:?} didn't contain image or partitions.", disk);
Andrew Walbran806f1542021-06-10 14:07:12 +0000429 return Err(new_binder_exception(
430 ExceptionCode::ILLEGAL_ARGUMENT,
431 "DiskImage didn't contain image or partitions.",
432 ));
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000433 };
434
435 Ok(DiskFile { image, writable: disk.writable })
436}
437
Jooyung Han21e9b922021-06-26 04:14:16 +0900438fn load_app_config(
439 config: &VirtualMachineAppConfig,
440 temporary_directory: &Path,
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900441) -> Result<VirtualMachineRawConfig> {
Andrew Walbrancc0db522021-07-12 17:03:42 +0000442 let apk_file = clone_file(config.apk.as_ref().unwrap())?;
443 let idsig_file = clone_file(config.idsig.as_ref().unwrap())?;
Jiyong Park8d081812021-07-23 17:45:04 +0900444 let instance_file = clone_file(config.instanceImage.as_ref().unwrap())?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900445 let config_path = &config.configPath;
446
Andrew Walbrancc0db522021-07-12 17:03:42 +0000447 let mut apk_zip = ZipArchive::new(&apk_file)?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900448 let config_file = apk_zip.by_name(config_path)?;
449 let vm_payload_config: VmPayloadConfig = serde_json::from_reader(config_file)?;
450
451 let os_name = &vm_payload_config.os.name;
Andrew Walbrancc0db522021-07-12 17:03:42 +0000452
Jooyung Han35edb8f2021-07-01 16:17:16 +0900453 // For now, the only supported "os" value is "microdroid"
454 if os_name != "microdroid" {
Andrew Walbrancc0db522021-07-12 17:03:42 +0000455 bail!("Unknown OS \"{}\"", os_name);
Jooyung Han35edb8f2021-07-01 16:17:16 +0900456 }
Andrew Walbrancc0db522021-07-12 17:03:42 +0000457
458 // It is safe to construct a filename based on the os_name because we've already checked that it
459 // is one of the allowed values.
Jooyung Han21e9b922021-06-26 04:14:16 +0900460 let vm_config_path = PathBuf::from(format!("/apex/com.android.virt/etc/{}.json", os_name));
461 let vm_config_file = File::open(vm_config_path)?;
Andrew Walbrancc0db522021-07-12 17:03:42 +0000462 let mut vm_config = VmConfig::load(&vm_config_file)?.to_parcelable()?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900463
Andrew Walbrancc045902021-07-27 16:06:17 +0000464 if config.memoryMib > 0 {
465 vm_config.memoryMib = config.memoryMib;
Andrew Walbran45bcb0c2021-07-14 15:02:06 +0000466 }
467
Andrew Walbrancc0db522021-07-12 17:03:42 +0000468 // Microdroid requires an additional payload disk image and the bootconfig partition.
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900469 if os_name == "microdroid" {
Andrew Walbrancc0db522021-07-12 17:03:42 +0000470 let apexes = vm_payload_config.apexes.clone();
471 add_microdroid_images(
472 config,
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900473 temporary_directory,
Andrew Walbrancc0db522021-07-12 17:03:42 +0000474 apk_file,
475 idsig_file,
Jiyong Park8d081812021-07-23 17:45:04 +0900476 instance_file,
Andrew Walbrancc0db522021-07-12 17:03:42 +0000477 apexes,
478 &mut vm_config,
479 )?;
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900480 }
Jooyung Han21e9b922021-06-26 04:14:16 +0900481
Andrew Walbrancc0db522021-07-12 17:03:42 +0000482 Ok(vm_config)
Jooyung Han21e9b922021-06-26 04:14:16 +0900483}
484
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000485/// Generates a unique filename to use for a composite disk image.
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000486fn make_composite_image_filenames(
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000487 temporary_directory: &Path,
488 next_temporary_image_id: &mut u64,
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000489) -> CompositeImageFilenames {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000490 let id = *next_temporary_image_id;
491 *next_temporary_image_id += 1;
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000492 CompositeImageFilenames {
493 composite: temporary_directory.join(format!("composite-{}.img", id)),
494 header: temporary_directory.join(format!("composite-{}-header.img", id)),
495 footer: temporary_directory.join(format!("composite-{}-footer.img", id)),
496 }
497}
498
499/// Filenames for a composite disk image, including header and footer partitions.
500#[derive(Clone, Debug, Eq, PartialEq)]
501struct CompositeImageFilenames {
502 /// The composite disk image itself.
503 composite: PathBuf,
504 /// The header partition image.
505 header: PathBuf,
506 /// The footer partition image.
507 footer: PathBuf,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000508}
509
510/// Gets the calling SID of the current Binder thread.
Andrew Walbran806f1542021-06-10 14:07:12 +0000511fn get_calling_sid() -> Result<String, Status> {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000512 ThreadState::with_calling_sid(|sid| {
513 if let Some(sid) = sid {
514 match sid.to_str() {
515 Ok(sid) => Ok(sid.to_owned()),
516 Err(e) => {
Andrew Walbran806f1542021-06-10 14:07:12 +0000517 error!("SID was not valid UTF-8: {}", e);
518 Err(new_binder_exception(
519 ExceptionCode::ILLEGAL_ARGUMENT,
520 format!("SID was not valid UTF-8: {}", e),
521 ))
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000522 }
523 }
524 } else {
525 error!("Missing SID on startVm");
Andrew Walbran806f1542021-06-10 14:07:12 +0000526 Err(new_binder_exception(ExceptionCode::SECURITY, "Missing SID on startVm"))
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000527 }
528 })
529}
530
Jiyong Park753553b2021-07-12 21:21:09 +0900531/// Checks whether the caller has a specific permission
532fn check_permission(perm: &str) -> binder::Result<()> {
533 let calling_pid = ThreadState::get_calling_pid();
534 let calling_uid = ThreadState::get_calling_uid();
535 // Root can do anything
536 if calling_uid == 0 {
537 return Ok(());
538 }
539 let perm_svc: Strong<dyn IPermissionController::IPermissionController> =
540 binder::get_interface("permission")?;
541 if perm_svc.checkPermission(perm, calling_pid, calling_uid as i32)? {
Andrew Walbran806f1542021-06-10 14:07:12 +0000542 Ok(())
543 } else {
Jiyong Park753553b2021-07-12 21:21:09 +0900544 Err(new_binder_exception(
545 ExceptionCode::SECURITY,
546 format!("does not have the {} permission", perm),
547 ))
Andrew Walbran806f1542021-06-10 14:07:12 +0000548 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000549}
550
Jiyong Park753553b2021-07-12 21:21:09 +0900551/// Check whether the caller of the current Binder method is allowed to call debug methods.
552fn check_debug_access() -> binder::Result<()> {
553 check_permission("android.permission.DEBUG_VIRTUAL_MACHINE")
554}
555
556/// Check whether the caller of the current Binder method is allowed to manage VMs
557fn check_manage_access() -> binder::Result<()> {
558 check_permission("android.permission.MANAGE_VIRTUAL_MACHINE")
559}
560
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000561/// Implementation of the AIDL `IVirtualMachine` interface. Used as a handle to a VM.
562#[derive(Debug)]
563struct VirtualMachine {
564 instance: Arc<VmInstance>,
565}
566
567impl VirtualMachine {
568 fn create(instance: Arc<VmInstance>) -> Strong<dyn IVirtualMachine> {
569 let binder = VirtualMachine { instance };
Andrew Walbran4de28782021-04-13 14:51:43 +0000570 BnVirtualMachine::new_binder(binder, BinderFeatures::default())
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000571 }
572}
573
574impl Interface for VirtualMachine {}
575
576impl IVirtualMachine for VirtualMachine {
577 fn getCid(&self) -> binder::Result<i32> {
Jiyong Park753553b2021-07-12 21:21:09 +0900578 // Don't check permission. The owner of the VM might have passed this binder object to
579 // others.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000580 Ok(self.instance.cid as i32)
581 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000582
583 fn isRunning(&self) -> binder::Result<bool> {
Jiyong Park753553b2021-07-12 21:21:09 +0900584 // Don't check permission. The owner of the VM might have passed this binder object to
585 // others.
Andrew Walbrandae07162021-03-12 17:05:20 +0000586 Ok(self.instance.running())
587 }
588
589 fn registerCallback(
590 &self,
591 callback: &Strong<dyn IVirtualMachineCallback>,
592 ) -> binder::Result<()> {
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.
595 //
Andrew Walbrandae07162021-03-12 17:05:20 +0000596 // TODO: Should this give an error if the VM is already dead?
597 self.instance.callbacks.add(callback.clone());
598 Ok(())
599 }
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000600
601 fn connectVsock(&self, port: i32) -> binder::Result<ParcelFileDescriptor> {
602 if !self.instance.running() {
603 return Err(new_binder_exception(
604 ExceptionCode::SERVICE_SPECIFIC,
605 "VM is no longer running",
606 ));
607 }
608 let stream =
609 VsockStream::connect_with_cid_port(self.instance.cid, port as u32).map_err(|e| {
610 new_binder_exception(
611 ExceptionCode::SERVICE_SPECIFIC,
612 format!("Failed to connect: {}", e),
613 )
614 })?;
615 Ok(vsock_stream_to_pfd(stream))
616 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000617}
618
619impl Drop for VirtualMachine {
620 fn drop(&mut self) {
621 debug!("Dropping {:?}", self);
622 self.instance.kill();
623 }
624}
625
626/// A set of Binders to be called back in response to various events on the VM, such as when it
627/// dies.
628#[derive(Debug, Default)]
629pub struct VirtualMachineCallbacks(Mutex<Vec<Strong<dyn IVirtualMachineCallback>>>);
630
631impl VirtualMachineCallbacks {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900632 /// Call all registered callbacks to notify that the payload has started.
Inseob Kim7f61fe72021-08-20 20:50:47 +0900633 pub fn notify_payload_started(&self, cid: Cid, stream: Option<VsockStream>) {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900634 let callbacks = &*self.0.lock().unwrap();
Inseob Kim7f61fe72021-08-20 20:50:47 +0900635 let pfd = stream.map(vsock_stream_to_pfd);
Jiyong Park8611a6c2021-07-09 18:17:44 +0900636 for callback in callbacks {
Inseob Kim7f61fe72021-08-20 20:50:47 +0900637 if let Err(e) = callback.onPayloadStarted(cid as i32, pfd.as_ref()) {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900638 error!("Error notifying payload start event from VM CID {}: {}", cid, e);
639 }
640 }
641 }
642
Inseob Kim14cb8692021-08-31 21:50:39 +0900643 /// Call all registered callbacks to notify that the payload is ready to serve.
644 pub fn notify_payload_ready(&self, cid: Cid) {
645 let callbacks = &*self.0.lock().unwrap();
646 for callback in callbacks {
647 if let Err(e) = callback.onPayloadReady(cid as i32) {
648 error!("Error notifying payload ready event from VM CID {}: {}", cid, e);
649 }
650 }
651 }
652
Inseob Kim2444af92021-08-31 01:22:50 +0900653 /// Call all registered callbacks to notify that the payload has finished.
654 pub fn notify_payload_finished(&self, cid: Cid, exit_code: i32) {
655 let callbacks = &*self.0.lock().unwrap();
656 for callback in callbacks {
657 if let Err(e) = callback.onPayloadFinished(cid as i32, exit_code) {
658 error!("Error notifying payload finish event from VM CID {}: {}", cid, e);
659 }
660 }
661 }
662
Andrew Walbrandae07162021-03-12 17:05:20 +0000663 /// Call all registered callbacks to say that the VM has died.
664 pub fn callback_on_died(&self, cid: Cid) {
665 let callbacks = &*self.0.lock().unwrap();
666 for callback in callbacks {
667 if let Err(e) = callback.onDied(cid as i32) {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900668 error!("Error notifying exit of VM CID {}: {}", cid, e);
Andrew Walbrandae07162021-03-12 17:05:20 +0000669 }
670 }
671 }
672
673 /// Add a new callback to the set.
674 fn add(&self, callback: Strong<dyn IVirtualMachineCallback>) {
675 self.0.lock().unwrap().push(callback);
676 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000677}
678
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000679/// The mutable state of the VirtualizationService. There should only be one instance of this
680/// struct.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000681#[derive(Debug)]
682struct State {
Andrew Walbran320b5602021-03-04 16:11:12 +0000683 /// The next available unused CID.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000684 next_cid: Cid,
Andrew Walbran320b5602021-03-04 16:11:12 +0000685
686 /// The VMs which have been started. When VMs are started a weak reference is added to this list
687 /// while a strong reference is returned to the caller over Binder. Once all copies of the
688 /// Binder client are dropped the weak reference here will become invalid, and will be removed
689 /// from the list opportunistically the next time `add_vm` is called.
690 vms: Vec<Weak<VmInstance>>,
David Brazdil3c2ddef2021-03-18 13:09:57 +0000691
692 /// Vector of strong VM references held on behalf of users that cannot hold them themselves.
693 /// This is only used for debugging purposes.
694 debug_held_vms: Vec<Strong<dyn IVirtualMachine>>,
Andrew Walbran320b5602021-03-04 16:11:12 +0000695}
696
697impl State {
Andrew Walbrandae07162021-03-12 17:05:20 +0000698 /// Get a list of VMs which still have Binder references to them.
Andrew Walbran320b5602021-03-04 16:11:12 +0000699 fn vms(&self) -> Vec<Arc<VmInstance>> {
700 // Attempt to upgrade the weak pointers to strong pointers.
701 self.vms.iter().filter_map(Weak::upgrade).collect()
702 }
703
704 /// Add a new VM to the list.
705 fn add_vm(&mut self, vm: Weak<VmInstance>) {
706 // Garbage collect any entries from the stored list which no longer exist.
707 self.vms.retain(|vm| vm.strong_count() > 0);
708
709 // Actually add the new VM.
710 self.vms.push(vm);
711 }
David Brazdil3c2ddef2021-03-18 13:09:57 +0000712
Jiyong Park8611a6c2021-07-09 18:17:44 +0900713 /// Get a VM that corresponds to the given cid
714 fn get_vm(&self, cid: Cid) -> Option<Arc<VmInstance>> {
715 self.vms().into_iter().find(|vm| vm.cid == cid)
716 }
717
David Brazdil3c2ddef2021-03-18 13:09:57 +0000718 /// Store a strong VM reference.
719 fn debug_hold_vm(&mut self, vm: Strong<dyn IVirtualMachine>) {
720 self.debug_held_vms.push(vm);
721 }
722
723 /// Retrieve and remove a strong VM reference.
724 fn debug_drop_vm(&mut self, cid: i32) -> Option<Strong<dyn IVirtualMachine>> {
725 let pos = self.debug_held_vms.iter().position(|vm| vm.getCid() == Ok(cid))?;
726 Some(self.debug_held_vms.swap_remove(pos))
727 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000728
729 /// Get the next available CID, or an error if we have run out.
730 fn allocate_cid(&mut self) -> binder::Result<Cid> {
731 // TODO(qwandor): keep track of which CIDs are currently in use so that we can reuse them.
732 let cid = self.next_cid;
Andrew Walbran806f1542021-06-10 14:07:12 +0000733 self.next_cid = self.next_cid.checked_add(1).ok_or(ExceptionCode::ILLEGAL_STATE)?;
Andrew Walbrandae07162021-03-12 17:05:20 +0000734 Ok(cid)
735 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000736}
737
738impl Default for State {
739 fn default() -> Self {
David Brazdil3c2ddef2021-03-18 13:09:57 +0000740 State { next_cid: FIRST_GUEST_CID, vms: vec![], debug_held_vms: vec![] }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000741 }
742}
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000743
744/// Converts an `&Option<T>` to an `Option<U>` where `T` implements `AsRef<U>`.
745fn as_asref<T: AsRef<U>, U>(option: &Option<T>) -> Option<&U> {
746 option.as_ref().map(|t| t.as_ref())
747}
748
749/// Converts a `&ParcelFileDescriptor` to a `File` by cloning the file.
Andrew Walbran806f1542021-06-10 14:07:12 +0000750fn clone_file(file: &ParcelFileDescriptor) -> Result<File, Status> {
751 file.as_ref().try_clone().map_err(|e| {
752 new_binder_exception(
753 ExceptionCode::BAD_PARCELABLE,
754 format!("Failed to clone File from ParcelFileDescriptor: {}", e),
755 )
756 })
757}
758
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000759/// Converts a `VsockStream` to a `ParcelFileDescriptor`.
760fn vsock_stream_to_pfd(stream: VsockStream) -> ParcelFileDescriptor {
761 // SAFETY: ownership is transferred from stream to f
762 let f = unsafe { File::from_raw_fd(stream.into_raw_fd()) };
763 ParcelFileDescriptor::new(f)
764}
765
Andrew Walbran806f1542021-06-10 14:07:12 +0000766/// Constructs a new Binder error `Status` with the given `ExceptionCode` and message.
767fn new_binder_exception<T: AsRef<str>>(exception: ExceptionCode, message: T) -> Status {
768 Status::new_exception(exception, CString::new(message.as_ref()).ok().as_deref())
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000769}
Jooyung Han35edb8f2021-07-01 16:17:16 +0900770
771/// Simple utility for referencing Borrowed or Owned. Similar to std::borrow::Cow, but
772/// it doesn't require that T implements Clone.
773enum BorrowedOrOwned<'a, T> {
774 Borrowed(&'a T),
775 Owned(T),
776}
777
778impl<'a, T> AsRef<T> for BorrowedOrOwned<'a, T> {
779 fn as_ref(&self) -> &T {
780 match self {
781 Self::Borrowed(b) => b,
Chris Wailes68c39f82021-07-27 16:03:44 -0700782 Self::Owned(o) => o,
Jooyung Han35edb8f2021-07-01 16:17:16 +0900783 }
784 }
785}
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900786
787/// Implementation of `IVirtualMachineService`, the entry point of the AIDL service.
788#[derive(Debug, Default)]
789struct VirtualMachineService {
790 state: Arc<Mutex<State>>,
791}
792
793impl Interface for VirtualMachineService {}
794
795impl IVirtualMachineService for VirtualMachineService {
796 fn notifyPayloadStarted(&self, cid: i32) -> binder::Result<()> {
797 let cid = cid as Cid;
Inseob Kim7f61fe72021-08-20 20:50:47 +0900798 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
799 info!("VM having CID {} started payload", cid);
800 let stream = vm.stream.lock().unwrap().take();
801 vm.callbacks.notify_payload_started(cid, stream);
802 Ok(())
803 } else {
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900804 error!("notifyPayloadStarted is called from an unknown cid {}", cid);
Inseob Kim7f61fe72021-08-20 20:50:47 +0900805 Err(new_binder_exception(
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900806 ExceptionCode::SERVICE_SPECIFIC,
807 format!("cannot find a VM with cid {}", cid),
Inseob Kim7f61fe72021-08-20 20:50:47 +0900808 ))
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900809 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900810 }
Inseob Kim2444af92021-08-31 01:22:50 +0900811
Inseob Kim14cb8692021-08-31 21:50:39 +0900812 fn notifyPayloadReady(&self, cid: i32) -> binder::Result<()> {
813 let cid = cid as Cid;
814 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
815 info!("VM having CID {} payload is ready", cid);
816 vm.callbacks.notify_payload_ready(cid);
817 Ok(())
818 } else {
819 error!("notifyPayloadReady is called from an unknown cid {}", cid);
820 Err(new_binder_exception(
821 ExceptionCode::SERVICE_SPECIFIC,
822 format!("cannot find a VM with cid {}", cid),
823 ))
824 }
825 }
826
Inseob Kim2444af92021-08-31 01:22:50 +0900827 fn notifyPayloadFinished(&self, cid: i32, exit_code: i32) -> binder::Result<()> {
828 let cid = cid as Cid;
829 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
830 info!("VM having CID {} finished payload", cid);
831 vm.callbacks.notify_payload_finished(cid, exit_code);
832 Ok(())
833 } else {
834 error!("notifyPayloadFinished is called from an unknown cid {}", cid);
835 Err(new_binder_exception(
836 ExceptionCode::SERVICE_SPECIFIC,
837 format!("cannot find a VM with cid {}", cid),
838 ))
839 }
840 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900841}
842
843impl VirtualMachineService {
844 fn new_binder(state: Arc<Mutex<State>>) -> Strong<dyn IVirtualMachineService> {
845 BnVirtualMachineService::new_binder(
846 VirtualMachineService { state },
847 BinderFeatures::default(),
848 )
849 }
850}