blob: ad89ba5422ffa375945b48f98237d352b91f6daa [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 Walbran6b650662021-09-07 13:13:23 +000018use crate::crosvm::{CrosvmConfig, DiskFile, PayloadState, 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 Walbranf6bf6862021-05-21 12:41:13 +000023use android_system_virtualizationservice::aidl::android::system::virtualizationservice::IVirtualMachine::{
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000024 BnVirtualMachine, IVirtualMachine,
25};
Jooyung Han21e9b922021-06-26 04:14:16 +090026use android_system_virtualizationservice::aidl::android::system::virtualizationservice::{
Andrew Walbran6b650662021-09-07 13:13:23 +000027 DiskImage::DiskImage,
28 IVirtualMachineCallback::IVirtualMachineCallback,
29 IVirtualizationService::IVirtualizationService,
30 PartitionType::PartitionType,
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::{
Andrew Walbran806f1542021-06-10 14:07:12 +000038 self, BinderFeatures, ExceptionCode, Interface, ParcelFileDescriptor, Status, Strong, ThreadState,
Andrew Walbrana89fc132021-03-17 17:08:36 +000039};
Inseob Kim1b95f2e2021-08-19 13:17:40 +090040use android_system_virtualmachineservice::aidl::android::system::virtualmachineservice::IVirtualMachineService::{
Inseob Kimd0587562021-09-01 21:27:32 +090041 VM_BINDER_SERVICE_PORT, VM_STREAM_SERVICE_PORT, BnVirtualMachineService, IVirtualMachineService,
Inseob Kim1b95f2e2021-08-19 13:17:40 +090042};
Jooyung Han95884632021-07-06 22:27:54 +090043use anyhow::{bail, Context, Result};
Inseob Kim1b95f2e2021-08-19 13:17:40 +090044use ::binder::unstable_api::AsNative;
Andrew Walbrandfc953d2021-06-10 13:59:56 +000045use disk::QcowFile;
Jiyong Park0a248432021-08-20 23:32:39 +090046use idsig::{V4Signature, HashAlgorithm};
Jiyong Park8611a6c2021-07-09 18:17:44 +090047use log::{debug, error, warn, info};
Andrew Walbrancc0db522021-07-12 17:03:42 +000048use microdroid_payload_config::VmPayloadConfig;
Andrew Walbrandff3b942021-06-09 15:20:36 +000049use std::convert::TryInto;
Andrew Walbran806f1542021-06-10 14:07:12 +000050use std::ffi::CString;
Jooyung Han95884632021-07-06 22:27:54 +090051use std::fs::{File, OpenOptions, create_dir};
Jiyong Park9dd389e2021-08-23 20:42:59 +090052use std::io::{Error, ErrorKind, Write};
Andrew Walbranb15cd6e2021-07-05 16:38:07 +000053use std::num::NonZeroU32;
Andrew Walbrand3a84182021-09-07 14:48:52 +000054use std::os::unix::io::{FromRawFd, IntoRawFd};
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000055use std::path::{Path, PathBuf};
Andrew Walbran320b5602021-03-04 16:11:12 +000056use std::sync::{Arc, Mutex, Weak};
Andrew Walbrancc0db522021-07-12 17:03:42 +000057use vmconfig::VmConfig;
Inseob Kim7f61fe72021-08-20 20:50:47 +090058use vsock::{SockAddr, VsockListener, VsockStream};
Jooyung Han35edb8f2021-07-01 16:17:16 +090059use zip::ZipArchive;
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000060
Andrew Walbranf6bf6862021-05-21 12:41:13 +000061pub const BINDER_SERVICE_IDENTIFIER: &str = "android.system.virtualizationservice";
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000062
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000063/// Directory in which to write disk image files used while running VMs.
Andrew Walbran488bd072021-07-14 13:29:51 +000064pub const TEMPORARY_DIRECTORY: &str = "/data/misc/virtualizationservice";
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000065
Jiyong Park8611a6c2021-07-09 18:17:44 +090066/// The CID representing the host VM
67const VMADDR_CID_HOST: u32 = 2;
68
Jooyung Han95884632021-07-06 22:27:54 +090069/// The size of zero.img.
70/// Gaps in composite disk images are filled with a shared zero.img.
71const ZERO_FILLER_SIZE: u64 = 4096;
72
Jiyong Park9dd389e2021-08-23 20:42:59 +090073/// Magic string for the instance image
74const ANDROID_VM_INSTANCE_MAGIC: &str = "Android-VM-instance";
75
76/// Version of the instance image format
77const ANDROID_VM_INSTANCE_VERSION: u16 = 1;
78
Andrew Walbranf6bf6862021-05-21 12:41:13 +000079/// Implementation of `IVirtualizationService`, the entry point of the AIDL service.
Jooyung Han9900f3d2021-07-06 10:27:54 +090080#[derive(Debug, Default)]
Andrew Walbranf6bf6862021-05-21 12:41:13 +000081pub struct VirtualizationService {
Jiyong Park8611a6c2021-07-09 18:17:44 +090082 state: Arc<Mutex<State>>,
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000083}
84
Andrew Walbranf6bf6862021-05-21 12:41:13 +000085impl Interface for VirtualizationService {}
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000086
Andrew Walbranf6bf6862021-05-21 12:41:13 +000087impl IVirtualizationService for VirtualizationService {
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000088 /// Create and start a new VM with the given configuration, assigning it the next available CID.
89 ///
90 /// Returns a binder `IVirtualMachine` object referring to it, as a handle for the client.
Andrew Walbrana89fc132021-03-17 17:08:36 +000091 fn startVm(
92 &self,
Andrew Walbran3a5a9212021-05-04 17:09:08 +000093 config: &VirtualMachineConfig,
Andrew Walbrana89fc132021-03-17 17:08:36 +000094 log_fd: Option<&ParcelFileDescriptor>,
95 ) -> binder::Result<Strong<dyn IVirtualMachine>> {
Jiyong Park753553b2021-07-12 21:21:09 +090096 check_manage_access()?;
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000097 let state = &mut *self.state.lock().unwrap();
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000098 let log_fd = log_fd.map(clone_file).transpose()?;
Andrew Walbranf6a1eb92021-04-01 11:16:02 +000099 let requester_uid = ThreadState::get_calling_uid();
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000100 let requester_sid = get_calling_sid()?;
Andrew Walbran02034492021-04-13 15:05:07 +0000101 let requester_debug_pid = ThreadState::get_calling_pid();
Andrew Walbrandae07162021-03-12 17:05:20 +0000102 let cid = state.allocate_cid()?;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000103
104 // Counter to generate unique IDs for temporary image files.
105 let mut next_temporary_image_id = 0;
106 // Files which are referred to from composite images. These must be mapped to the crosvm
107 // child process, and not closed before it is started.
108 let mut indirect_files = vec![];
109
110 // Make directory for temporary files.
111 let temporary_directory: PathBuf = format!("{}/{}", TEMPORARY_DIRECTORY, cid).into();
112 create_dir(&temporary_directory).map_err(|e| {
113 error!(
Andrew Walbran806f1542021-06-10 14:07:12 +0000114 "Failed to create temporary directory {:?} for VM files: {}",
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000115 temporary_directory, e
116 );
Andrew Walbran806f1542021-06-10 14:07:12 +0000117 new_binder_exception(
118 ExceptionCode::SERVICE_SPECIFIC,
119 format!(
120 "Failed to create temporary directory {:?} for VM files: {}",
121 temporary_directory, e
122 ),
123 )
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000124 })?;
125
Jooyung Han21e9b922021-06-26 04:14:16 +0900126 let config = match config {
Jooyung Han35edb8f2021-07-01 16:17:16 +0900127 VirtualMachineConfig::AppConfig(config) => BorrowedOrOwned::Owned(
Jooyung Han9900f3d2021-07-06 10:27:54 +0900128 load_app_config(config, &temporary_directory).map_err(|e| {
129 error!("Failed to load app config from {}: {}", &config.configPath, e);
130 new_binder_exception(
131 ExceptionCode::SERVICE_SPECIFIC,
132 format!("Failed to load app config from {}: {}", &config.configPath, e),
133 )
134 })?,
Jooyung Han35edb8f2021-07-01 16:17:16 +0900135 ),
136 VirtualMachineConfig::RawConfig(config) => BorrowedOrOwned::Borrowed(config),
Jooyung Han21e9b922021-06-26 04:14:16 +0900137 };
Jooyung Han35edb8f2021-07-01 16:17:16 +0900138 let config = config.as_ref();
Jooyung Han21e9b922021-06-26 04:14:16 +0900139
Jooyung Han95884632021-07-06 22:27:54 +0900140 let zero_filler_path = temporary_directory.join("zero.img");
Andrew Walbranfbb39d22021-07-28 17:01:25 +0000141 write_zero_filler(&zero_filler_path).map_err(|e| {
Jooyung Han95884632021-07-06 22:27:54 +0900142 error!("Failed to make composite image: {}", e);
143 new_binder_exception(
144 ExceptionCode::SERVICE_SPECIFIC,
145 format!("Failed to make composite image: {}", e),
146 )
147 })?;
Jooyung Han95884632021-07-06 22:27:54 +0900148
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000149 // Assemble disk images if needed.
150 let disks = config
151 .disks
152 .iter()
153 .map(|disk| {
154 assemble_disk_image(
155 disk,
Jooyung Han95884632021-07-06 22:27:54 +0900156 &zero_filler_path,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000157 &temporary_directory,
158 &mut next_temporary_image_id,
159 &mut indirect_files,
160 )
161 })
162 .collect::<Result<Vec<DiskFile>, _>>()?;
163
164 // Actually start the VM.
165 let crosvm_config = CrosvmConfig {
Andrew Walbran02034492021-04-13 15:05:07 +0000166 cid,
Andrew Walbrand3a84182021-09-07 14:48:52 +0000167 bootloader: maybe_clone_file(&config.bootloader)?,
168 kernel: maybe_clone_file(&config.kernel)?,
169 initrd: maybe_clone_file(&config.initrd)?,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000170 disks,
171 params: config.params.to_owned(),
Andrew Walbrancc045902021-07-27 16:06:17 +0000172 protected: config.protectedVm,
173 memory_mib: config.memoryMib.try_into().ok().and_then(NonZeroU32::new),
Andrew Walbran02034492021-04-13 15:05:07 +0000174 log_fd,
Andrew Walbrand3a84182021-09-07 14:48:52 +0000175 indirect_files,
176 };
177 let instance = VmInstance::start(
178 crosvm_config,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000179 temporary_directory,
Andrew Walbran02034492021-04-13 15:05:07 +0000180 requester_uid,
181 requester_sid,
182 requester_debug_pid,
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000183 )
184 .map_err(|e| {
Andrew Walbran806f1542021-06-10 14:07:12 +0000185 error!("Failed to start VM with config {:?}: {}", config, e);
186 new_binder_exception(
187 ExceptionCode::SERVICE_SPECIFIC,
188 format!("Failed to start VM: {}", e),
189 )
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000190 })?;
Andrew Walbran320b5602021-03-04 16:11:12 +0000191 state.add_vm(Arc::downgrade(&instance));
192 Ok(VirtualMachine::create(instance))
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000193 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000194
Andrew Walbrandff3b942021-06-09 15:20:36 +0000195 /// Initialise an empty partition image of the given size to be used as a writable partition.
196 fn initializeWritablePartition(
197 &self,
198 image_fd: &ParcelFileDescriptor,
199 size: i64,
Jiyong Park9dd389e2021-08-23 20:42:59 +0900200 partition_type: PartitionType,
Andrew Walbrandff3b942021-06-09 15:20:36 +0000201 ) -> binder::Result<()> {
Jiyong Park753553b2021-07-12 21:21:09 +0900202 check_manage_access()?;
Andrew Walbrandfc953d2021-06-10 13:59:56 +0000203 let size = size.try_into().map_err(|e| {
Andrew Walbran806f1542021-06-10 14:07:12 +0000204 new_binder_exception(
205 ExceptionCode::ILLEGAL_ARGUMENT,
206 format!("Invalid size {}: {}", size, e),
207 )
Andrew Walbrandff3b942021-06-09 15:20:36 +0000208 })?;
Andrew Walbrandfc953d2021-06-10 13:59:56 +0000209 let image = clone_file(image_fd)?;
Andrew Walbrandff3b942021-06-09 15:20:36 +0000210
Jiyong Park9dd389e2021-08-23 20:42:59 +0900211 let mut part = QcowFile::new(image, size).map_err(|e| {
Andrew Walbran806f1542021-06-10 14:07:12 +0000212 new_binder_exception(
213 ExceptionCode::SERVICE_SPECIFIC,
214 format!("Failed to create QCOW2 image: {}", e),
215 )
Andrew Walbrandfc953d2021-06-10 13:59:56 +0000216 })?;
Andrew Walbrandff3b942021-06-09 15:20:36 +0000217
Jiyong Park9dd389e2021-08-23 20:42:59 +0900218 match partition_type {
219 PartitionType::RAW => Ok(()),
220 PartitionType::ANDROID_VM_INSTANCE => format_as_android_vm_instance(&mut part),
221 _ => Err(Error::new(
222 ErrorKind::Unsupported,
223 format!("Unsupported partition type {:?}", partition_type),
224 )),
225 }
226 .map_err(|e| {
227 new_binder_exception(
228 ExceptionCode::SERVICE_SPECIFIC,
229 format!("Failed to initialize partition as {:?}: {}", partition_type, e),
230 )
231 })?;
232
Andrew Walbrandff3b942021-06-09 15:20:36 +0000233 Ok(())
234 }
235
Jiyong Park0a248432021-08-20 23:32:39 +0900236 /// Creates or update the idsig file by digesting the input APK file.
237 fn createOrUpdateIdsigFile(
238 &self,
239 input_fd: &ParcelFileDescriptor,
240 idsig_fd: &ParcelFileDescriptor,
241 ) -> binder::Result<()> {
242 // TODO(b/193504400): do this only when (1) idsig_fd is empty or (2) the APK digest in
243 // idsig_fd is different from APK digest in input_fd
244
245 let mut input = clone_file(input_fd)?;
246 let mut sig = V4Signature::create(&mut input, 4096, &[], HashAlgorithm::SHA256).unwrap();
247
248 let mut output = clone_file(idsig_fd)?;
249 output.set_len(0).unwrap();
250 sig.write_into(&mut output).unwrap();
251 Ok(())
252 }
253
Andrew Walbran320b5602021-03-04 16:11:12 +0000254 /// Get a list of all currently running VMs. This method is only intended for debug purposes,
255 /// and as such is only permitted from the shell user.
256 fn debugListVms(&self) -> binder::Result<Vec<VirtualMachineDebugInfo>> {
Andrew Walbran806f1542021-06-10 14:07:12 +0000257 check_debug_access()?;
Andrew Walbran320b5602021-03-04 16:11:12 +0000258
259 let state = &mut *self.state.lock().unwrap();
260 let vms = state.vms();
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000261 let cids = vms
262 .into_iter()
263 .map(|vm| VirtualMachineDebugInfo {
264 cid: vm.cid as i32,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000265 temporaryDirectory: vm.temporary_directory.to_string_lossy().to_string(),
Andrew Walbran1ef19ae2021-04-07 11:31:57 +0000266 requesterUid: vm.requester_uid as i32,
267 requesterSid: vm.requester_sid.clone(),
Andrew Walbran02034492021-04-13 15:05:07 +0000268 requesterPid: vm.requester_debug_pid,
Andrew Walbran6b650662021-09-07 13:13:23 +0000269 state: get_state(&vm),
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000270 })
271 .collect();
Andrew Walbran320b5602021-03-04 16:11:12 +0000272 Ok(cids)
273 }
David Brazdil3c2ddef2021-03-18 13:09:57 +0000274
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000275 /// Hold a strong reference to a VM in VirtualizationService. This method is only intended for
276 /// debug purposes, and as such is only permitted from the shell user.
Andrei Homescu1415c132021-03-24 02:39:55 +0000277 fn debugHoldVmRef(&self, vmref: &Strong<dyn IVirtualMachine>) -> binder::Result<()> {
Andrew Walbran806f1542021-06-10 14:07:12 +0000278 check_debug_access()?;
David Brazdil3c2ddef2021-03-18 13:09:57 +0000279
David Brazdil3c2ddef2021-03-18 13:09:57 +0000280 let state = &mut *self.state.lock().unwrap();
Andrei Homescu1415c132021-03-24 02:39:55 +0000281 state.debug_hold_vm(vmref.clone());
David Brazdil3c2ddef2021-03-18 13:09:57 +0000282 Ok(())
283 }
284
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000285 /// Drop reference to a VM that is being held by VirtualizationService. Returns the reference if
286 /// the VM was found and None otherwise. This method is only intended for debug purposes, and as
287 /// such is only permitted from the shell user.
David Brazdil3c2ddef2021-03-18 13:09:57 +0000288 fn debugDropVmRef(&self, cid: i32) -> binder::Result<Option<Strong<dyn IVirtualMachine>>> {
Andrew Walbran806f1542021-06-10 14:07:12 +0000289 check_debug_access()?;
David Brazdil3c2ddef2021-03-18 13:09:57 +0000290
291 let state = &mut *self.state.lock().unwrap();
292 Ok(state.debug_drop_vm(cid))
293 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000294}
295
Jiyong Park8611a6c2021-07-09 18:17:44 +0900296impl VirtualizationService {
297 pub fn init() -> VirtualizationService {
298 let service = VirtualizationService::default();
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900299
300 // server for payload output
Jiyong Park8611a6c2021-07-09 18:17:44 +0900301 let state = service.state.clone(); // reference to state (not the state itself) is copied
302 std::thread::spawn(move || {
Inseob Kim7f61fe72021-08-20 20:50:47 +0900303 handle_stream_connection_from_vm(state).unwrap();
Jiyong Park8611a6c2021-07-09 18:17:44 +0900304 });
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900305
306 // binder server for vm
307 let state = service.state.clone(); // reference to state (not the state itself) is copied
308 std::thread::spawn(move || {
309 let mut service = VirtualMachineService::new_binder(state).as_binder();
310 debug!("virtual machine service is starting as an RPC service.");
311 // SAFETY: Service ownership is transferring to the server and won't be valid afterward.
312 // Plus the binder objects are threadsafe.
313 let retval = unsafe {
314 binder_rpc_unstable_bindgen::RunRpcServer(
315 service.as_native_mut() as *mut binder_rpc_unstable_bindgen::AIBinder,
Inseob Kimd0587562021-09-01 21:27:32 +0900316 VM_BINDER_SERVICE_PORT as u32,
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900317 )
318 };
319 if retval {
320 debug!("RPC server has shut down gracefully");
321 } else {
322 bail!("Premature termination of RPC server");
323 }
324
325 Ok(retval)
326 });
Jiyong Park8611a6c2021-07-09 18:17:44 +0900327 service
328 }
329}
330
Andrew Walbran6b650662021-09-07 13:13:23 +0000331/// Waits for incoming connections from VM. If a new connection is made, stores the stream in the
332/// corresponding `VmInstance`.
Inseob Kim7f61fe72021-08-20 20:50:47 +0900333fn handle_stream_connection_from_vm(state: Arc<Mutex<State>>) -> Result<()> {
Inseob Kimd0587562021-09-01 21:27:32 +0900334 let listener =
335 VsockListener::bind_with_cid_port(VMADDR_CID_HOST, VM_STREAM_SERVICE_PORT as u32)?;
Jiyong Park8611a6c2021-07-09 18:17:44 +0900336 for stream in listener.incoming() {
337 let stream = match stream {
338 Err(e) => {
339 warn!("invalid incoming connection: {}", e);
340 continue;
341 }
342 Ok(s) => s,
343 };
344 if let Ok(SockAddr::Vsock(addr)) = stream.peer_addr() {
345 let cid = addr.cid();
346 let port = addr.port();
Inseob Kim7f61fe72021-08-20 20:50:47 +0900347 info!("payload stream connected from cid={}, port={}", cid, port);
Jiyong Park8611a6c2021-07-09 18:17:44 +0900348 if let Some(vm) = state.lock().unwrap().get_vm(cid) {
Inseob Kim7f61fe72021-08-20 20:50:47 +0900349 vm.stream.lock().unwrap().insert(stream);
350 } else {
351 error!("connection from cid={} is not from a guest VM", cid);
Jiyong Park8611a6c2021-07-09 18:17:44 +0900352 }
353 }
354 }
355 Ok(())
356}
357
Andrew Walbranfbb39d22021-07-28 17:01:25 +0000358fn write_zero_filler(zero_filler_path: &Path) -> Result<()> {
Jooyung Han95884632021-07-06 22:27:54 +0900359 let file = OpenOptions::new()
360 .create_new(true)
361 .read(true)
362 .write(true)
363 .open(zero_filler_path)
364 .with_context(|| "Failed to create zero.img")?;
365 file.set_len(ZERO_FILLER_SIZE)?;
Andrew Walbranfbb39d22021-07-28 17:01:25 +0000366 Ok(())
Jooyung Han95884632021-07-06 22:27:54 +0900367}
368
Jiyong Park9dd389e2021-08-23 20:42:59 +0900369fn format_as_android_vm_instance(part: &mut dyn Write) -> std::io::Result<()> {
370 part.write_all(ANDROID_VM_INSTANCE_MAGIC.as_bytes())?;
371 part.write_all(&ANDROID_VM_INSTANCE_VERSION.to_le_bytes())?;
372 part.flush()
373}
374
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000375/// Given the configuration for a disk image, assembles the `DiskFile` to pass to crosvm.
376///
377/// This may involve assembling a composite disk from a set of partition images.
378fn assemble_disk_image(
379 disk: &DiskImage,
Jooyung Han95884632021-07-06 22:27:54 +0900380 zero_filler_path: &Path,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000381 temporary_directory: &Path,
382 next_temporary_image_id: &mut u64,
383 indirect_files: &mut Vec<File>,
Andrew Walbran806f1542021-06-10 14:07:12 +0000384) -> Result<DiskFile, Status> {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000385 let image = if !disk.partitions.is_empty() {
386 if disk.image.is_some() {
387 warn!("DiskImage {:?} contains both image and partitions.", disk);
Andrew Walbran806f1542021-06-10 14:07:12 +0000388 return Err(new_binder_exception(
389 ExceptionCode::ILLEGAL_ARGUMENT,
390 "DiskImage contains both image and partitions.",
391 ));
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000392 }
393
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000394 let composite_image_filenames =
395 make_composite_image_filenames(temporary_directory, next_temporary_image_id);
396 let (image, partition_files) = make_composite_image(
397 &disk.partitions,
Jooyung Han95884632021-07-06 22:27:54 +0900398 zero_filler_path,
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000399 &composite_image_filenames.composite,
400 &composite_image_filenames.header,
401 &composite_image_filenames.footer,
402 )
403 .map_err(|e| {
404 error!("Failed to make composite image with config {:?}: {}", disk, e);
405 new_binder_exception(
406 ExceptionCode::SERVICE_SPECIFIC,
407 format!("Failed to make composite image: {}", e),
408 )
409 })?;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000410
411 // Pass the file descriptors for the various partition files to crosvm when it
412 // is run.
413 indirect_files.extend(partition_files);
414
415 image
416 } else if let Some(image) = &disk.image {
417 clone_file(image)?
418 } else {
419 warn!("DiskImage {:?} didn't contain image or partitions.", disk);
Andrew Walbran806f1542021-06-10 14:07:12 +0000420 return Err(new_binder_exception(
421 ExceptionCode::ILLEGAL_ARGUMENT,
422 "DiskImage didn't contain image or partitions.",
423 ));
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000424 };
425
426 Ok(DiskFile { image, writable: disk.writable })
427}
428
Jooyung Han21e9b922021-06-26 04:14:16 +0900429fn load_app_config(
430 config: &VirtualMachineAppConfig,
431 temporary_directory: &Path,
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900432) -> Result<VirtualMachineRawConfig> {
Andrew Walbrancc0db522021-07-12 17:03:42 +0000433 let apk_file = clone_file(config.apk.as_ref().unwrap())?;
434 let idsig_file = clone_file(config.idsig.as_ref().unwrap())?;
Jiyong Park8d081812021-07-23 17:45:04 +0900435 let instance_file = clone_file(config.instanceImage.as_ref().unwrap())?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900436 let config_path = &config.configPath;
437
Andrew Walbrancc0db522021-07-12 17:03:42 +0000438 let mut apk_zip = ZipArchive::new(&apk_file)?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900439 let config_file = apk_zip.by_name(config_path)?;
440 let vm_payload_config: VmPayloadConfig = serde_json::from_reader(config_file)?;
441
442 let os_name = &vm_payload_config.os.name;
Andrew Walbrancc0db522021-07-12 17:03:42 +0000443
Jooyung Han35edb8f2021-07-01 16:17:16 +0900444 // For now, the only supported "os" value is "microdroid"
445 if os_name != "microdroid" {
Andrew Walbrancc0db522021-07-12 17:03:42 +0000446 bail!("Unknown OS \"{}\"", os_name);
Jooyung Han35edb8f2021-07-01 16:17:16 +0900447 }
Andrew Walbrancc0db522021-07-12 17:03:42 +0000448
449 // It is safe to construct a filename based on the os_name because we've already checked that it
450 // is one of the allowed values.
Jooyung Han21e9b922021-06-26 04:14:16 +0900451 let vm_config_path = PathBuf::from(format!("/apex/com.android.virt/etc/{}.json", os_name));
452 let vm_config_file = File::open(vm_config_path)?;
Andrew Walbrancc0db522021-07-12 17:03:42 +0000453 let mut vm_config = VmConfig::load(&vm_config_file)?.to_parcelable()?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900454
Andrew Walbrancc045902021-07-27 16:06:17 +0000455 if config.memoryMib > 0 {
456 vm_config.memoryMib = config.memoryMib;
Andrew Walbran45bcb0c2021-07-14 15:02:06 +0000457 }
458
Andrew Walbrancc0db522021-07-12 17:03:42 +0000459 // Microdroid requires an additional payload disk image and the bootconfig partition.
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900460 if os_name == "microdroid" {
Andrew Walbrancc0db522021-07-12 17:03:42 +0000461 let apexes = vm_payload_config.apexes.clone();
462 add_microdroid_images(
463 config,
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900464 temporary_directory,
Andrew Walbrancc0db522021-07-12 17:03:42 +0000465 apk_file,
466 idsig_file,
Jiyong Park8d081812021-07-23 17:45:04 +0900467 instance_file,
Andrew Walbrancc0db522021-07-12 17:03:42 +0000468 apexes,
469 &mut vm_config,
470 )?;
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900471 }
Jooyung Han21e9b922021-06-26 04:14:16 +0900472
Andrew Walbrancc0db522021-07-12 17:03:42 +0000473 Ok(vm_config)
Jooyung Han21e9b922021-06-26 04:14:16 +0900474}
475
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000476/// Generates a unique filename to use for a composite disk image.
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000477fn make_composite_image_filenames(
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000478 temporary_directory: &Path,
479 next_temporary_image_id: &mut u64,
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000480) -> CompositeImageFilenames {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000481 let id = *next_temporary_image_id;
482 *next_temporary_image_id += 1;
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000483 CompositeImageFilenames {
484 composite: temporary_directory.join(format!("composite-{}.img", id)),
485 header: temporary_directory.join(format!("composite-{}-header.img", id)),
486 footer: temporary_directory.join(format!("composite-{}-footer.img", id)),
487 }
488}
489
490/// Filenames for a composite disk image, including header and footer partitions.
491#[derive(Clone, Debug, Eq, PartialEq)]
492struct CompositeImageFilenames {
493 /// The composite disk image itself.
494 composite: PathBuf,
495 /// The header partition image.
496 header: PathBuf,
497 /// The footer partition image.
498 footer: PathBuf,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000499}
500
501/// Gets the calling SID of the current Binder thread.
Andrew Walbran806f1542021-06-10 14:07:12 +0000502fn get_calling_sid() -> Result<String, Status> {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000503 ThreadState::with_calling_sid(|sid| {
504 if let Some(sid) = sid {
505 match sid.to_str() {
506 Ok(sid) => Ok(sid.to_owned()),
507 Err(e) => {
Andrew Walbran806f1542021-06-10 14:07:12 +0000508 error!("SID was not valid UTF-8: {}", e);
509 Err(new_binder_exception(
510 ExceptionCode::ILLEGAL_ARGUMENT,
511 format!("SID was not valid UTF-8: {}", e),
512 ))
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000513 }
514 }
515 } else {
516 error!("Missing SID on startVm");
Andrew Walbran806f1542021-06-10 14:07:12 +0000517 Err(new_binder_exception(ExceptionCode::SECURITY, "Missing SID on startVm"))
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000518 }
519 })
520}
521
Jiyong Park753553b2021-07-12 21:21:09 +0900522/// Checks whether the caller has a specific permission
523fn check_permission(perm: &str) -> binder::Result<()> {
524 let calling_pid = ThreadState::get_calling_pid();
525 let calling_uid = ThreadState::get_calling_uid();
526 // Root can do anything
527 if calling_uid == 0 {
528 return Ok(());
529 }
530 let perm_svc: Strong<dyn IPermissionController::IPermissionController> =
531 binder::get_interface("permission")?;
532 if perm_svc.checkPermission(perm, calling_pid, calling_uid as i32)? {
Andrew Walbran806f1542021-06-10 14:07:12 +0000533 Ok(())
534 } else {
Jiyong Park753553b2021-07-12 21:21:09 +0900535 Err(new_binder_exception(
536 ExceptionCode::SECURITY,
537 format!("does not have the {} permission", perm),
538 ))
Andrew Walbran806f1542021-06-10 14:07:12 +0000539 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000540}
541
Jiyong Park753553b2021-07-12 21:21:09 +0900542/// Check whether the caller of the current Binder method is allowed to call debug methods.
543fn check_debug_access() -> binder::Result<()> {
544 check_permission("android.permission.DEBUG_VIRTUAL_MACHINE")
545}
546
547/// Check whether the caller of the current Binder method is allowed to manage VMs
548fn check_manage_access() -> binder::Result<()> {
549 check_permission("android.permission.MANAGE_VIRTUAL_MACHINE")
550}
551
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000552/// Implementation of the AIDL `IVirtualMachine` interface. Used as a handle to a VM.
553#[derive(Debug)]
554struct VirtualMachine {
555 instance: Arc<VmInstance>,
556}
557
558impl VirtualMachine {
559 fn create(instance: Arc<VmInstance>) -> Strong<dyn IVirtualMachine> {
560 let binder = VirtualMachine { instance };
Andrew Walbran4de28782021-04-13 14:51:43 +0000561 BnVirtualMachine::new_binder(binder, BinderFeatures::default())
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000562 }
563}
564
565impl Interface for VirtualMachine {}
566
567impl IVirtualMachine for VirtualMachine {
568 fn getCid(&self) -> binder::Result<i32> {
Jiyong Park753553b2021-07-12 21:21:09 +0900569 // Don't check permission. The owner of the VM might have passed this binder object to
570 // others.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000571 Ok(self.instance.cid as i32)
572 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000573
Andrew Walbran6b650662021-09-07 13:13:23 +0000574 fn getState(&self) -> binder::Result<VirtualMachineState> {
Jiyong Park753553b2021-07-12 21:21:09 +0900575 // Don't check permission. The owner of the VM might have passed this binder object to
576 // others.
Andrew Walbran6b650662021-09-07 13:13:23 +0000577 Ok(get_state(&self.instance))
Andrew Walbrandae07162021-03-12 17:05:20 +0000578 }
579
580 fn registerCallback(
581 &self,
582 callback: &Strong<dyn IVirtualMachineCallback>,
583 ) -> binder::Result<()> {
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.
586 //
Andrew Walbrandae07162021-03-12 17:05:20 +0000587 // TODO: Should this give an error if the VM is already dead?
588 self.instance.callbacks.add(callback.clone());
589 Ok(())
590 }
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000591
592 fn connectVsock(&self, port: i32) -> binder::Result<ParcelFileDescriptor> {
593 if !self.instance.running() {
594 return Err(new_binder_exception(
595 ExceptionCode::SERVICE_SPECIFIC,
596 "VM is no longer running",
597 ));
598 }
599 let stream =
600 VsockStream::connect_with_cid_port(self.instance.cid, port as u32).map_err(|e| {
601 new_binder_exception(
602 ExceptionCode::SERVICE_SPECIFIC,
603 format!("Failed to connect: {}", e),
604 )
605 })?;
606 Ok(vsock_stream_to_pfd(stream))
607 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000608}
609
610impl Drop for VirtualMachine {
611 fn drop(&mut self) {
612 debug!("Dropping {:?}", self);
613 self.instance.kill();
614 }
615}
616
617/// A set of Binders to be called back in response to various events on the VM, such as when it
618/// dies.
619#[derive(Debug, Default)]
620pub struct VirtualMachineCallbacks(Mutex<Vec<Strong<dyn IVirtualMachineCallback>>>);
621
622impl VirtualMachineCallbacks {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900623 /// Call all registered callbacks to notify that the payload has started.
Inseob Kim7f61fe72021-08-20 20:50:47 +0900624 pub fn notify_payload_started(&self, cid: Cid, stream: Option<VsockStream>) {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900625 let callbacks = &*self.0.lock().unwrap();
Inseob Kim7f61fe72021-08-20 20:50:47 +0900626 let pfd = stream.map(vsock_stream_to_pfd);
Jiyong Park8611a6c2021-07-09 18:17:44 +0900627 for callback in callbacks {
Inseob Kim7f61fe72021-08-20 20:50:47 +0900628 if let Err(e) = callback.onPayloadStarted(cid as i32, pfd.as_ref()) {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900629 error!("Error notifying payload start event from VM CID {}: {}", cid, e);
630 }
631 }
632 }
633
Inseob Kim14cb8692021-08-31 21:50:39 +0900634 /// Call all registered callbacks to notify that the payload is ready to serve.
635 pub fn notify_payload_ready(&self, cid: Cid) {
636 let callbacks = &*self.0.lock().unwrap();
637 for callback in callbacks {
638 if let Err(e) = callback.onPayloadReady(cid as i32) {
639 error!("Error notifying payload ready event from VM CID {}: {}", cid, e);
640 }
641 }
642 }
643
Inseob Kim2444af92021-08-31 01:22:50 +0900644 /// Call all registered callbacks to notify that the payload has finished.
645 pub fn notify_payload_finished(&self, cid: Cid, exit_code: i32) {
646 let callbacks = &*self.0.lock().unwrap();
647 for callback in callbacks {
648 if let Err(e) = callback.onPayloadFinished(cid as i32, exit_code) {
649 error!("Error notifying payload finish event from VM CID {}: {}", cid, e);
650 }
651 }
652 }
653
Andrew Walbrandae07162021-03-12 17:05:20 +0000654 /// Call all registered callbacks to say that the VM has died.
655 pub fn callback_on_died(&self, cid: Cid) {
656 let callbacks = &*self.0.lock().unwrap();
657 for callback in callbacks {
658 if let Err(e) = callback.onDied(cid as i32) {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900659 error!("Error notifying exit of VM CID {}: {}", cid, e);
Andrew Walbrandae07162021-03-12 17:05:20 +0000660 }
661 }
662 }
663
664 /// Add a new callback to the set.
665 fn add(&self, callback: Strong<dyn IVirtualMachineCallback>) {
666 self.0.lock().unwrap().push(callback);
667 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000668}
669
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000670/// The mutable state of the VirtualizationService. There should only be one instance of this
671/// struct.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000672#[derive(Debug)]
673struct State {
Andrew Walbran320b5602021-03-04 16:11:12 +0000674 /// The next available unused CID.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000675 next_cid: Cid,
Andrew Walbran320b5602021-03-04 16:11:12 +0000676
677 /// The VMs which have been started. When VMs are started a weak reference is added to this list
678 /// while a strong reference is returned to the caller over Binder. Once all copies of the
679 /// Binder client are dropped the weak reference here will become invalid, and will be removed
680 /// from the list opportunistically the next time `add_vm` is called.
681 vms: Vec<Weak<VmInstance>>,
David Brazdil3c2ddef2021-03-18 13:09:57 +0000682
683 /// Vector of strong VM references held on behalf of users that cannot hold them themselves.
684 /// This is only used for debugging purposes.
685 debug_held_vms: Vec<Strong<dyn IVirtualMachine>>,
Andrew Walbran320b5602021-03-04 16:11:12 +0000686}
687
688impl State {
Andrew Walbrandae07162021-03-12 17:05:20 +0000689 /// Get a list of VMs which still have Binder references to them.
Andrew Walbran320b5602021-03-04 16:11:12 +0000690 fn vms(&self) -> Vec<Arc<VmInstance>> {
691 // Attempt to upgrade the weak pointers to strong pointers.
692 self.vms.iter().filter_map(Weak::upgrade).collect()
693 }
694
695 /// Add a new VM to the list.
696 fn add_vm(&mut self, vm: Weak<VmInstance>) {
697 // Garbage collect any entries from the stored list which no longer exist.
698 self.vms.retain(|vm| vm.strong_count() > 0);
699
700 // Actually add the new VM.
701 self.vms.push(vm);
702 }
David Brazdil3c2ddef2021-03-18 13:09:57 +0000703
Jiyong Park8611a6c2021-07-09 18:17:44 +0900704 /// Get a VM that corresponds to the given cid
705 fn get_vm(&self, cid: Cid) -> Option<Arc<VmInstance>> {
706 self.vms().into_iter().find(|vm| vm.cid == cid)
707 }
708
David Brazdil3c2ddef2021-03-18 13:09:57 +0000709 /// Store a strong VM reference.
710 fn debug_hold_vm(&mut self, vm: Strong<dyn IVirtualMachine>) {
711 self.debug_held_vms.push(vm);
712 }
713
714 /// Retrieve and remove a strong VM reference.
715 fn debug_drop_vm(&mut self, cid: i32) -> Option<Strong<dyn IVirtualMachine>> {
716 let pos = self.debug_held_vms.iter().position(|vm| vm.getCid() == Ok(cid))?;
717 Some(self.debug_held_vms.swap_remove(pos))
718 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000719
720 /// Get the next available CID, or an error if we have run out.
721 fn allocate_cid(&mut self) -> binder::Result<Cid> {
722 // TODO(qwandor): keep track of which CIDs are currently in use so that we can reuse them.
723 let cid = self.next_cid;
Andrew Walbran806f1542021-06-10 14:07:12 +0000724 self.next_cid = self.next_cid.checked_add(1).ok_or(ExceptionCode::ILLEGAL_STATE)?;
Andrew Walbrandae07162021-03-12 17:05:20 +0000725 Ok(cid)
726 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000727}
728
729impl Default for State {
730 fn default() -> Self {
David Brazdil3c2ddef2021-03-18 13:09:57 +0000731 State { next_cid: FIRST_GUEST_CID, vms: vec![], debug_held_vms: vec![] }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000732 }
733}
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000734
Andrew Walbran6b650662021-09-07 13:13:23 +0000735/// Gets the `VirtualMachineState` of the given `VmInstance`.
736fn get_state(instance: &VmInstance) -> VirtualMachineState {
737 if instance.running() {
738 match instance.payload_state() {
739 PayloadState::Starting => VirtualMachineState::STARTING,
740 PayloadState::Started => VirtualMachineState::STARTED,
741 PayloadState::Ready => VirtualMachineState::READY,
742 PayloadState::Finished => VirtualMachineState::FINISHED,
743 }
744 } else {
745 VirtualMachineState::DEAD
746 }
747}
748
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000749/// 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 Walbrand3a84182021-09-07 14:48:52 +0000759/// Converts an `&Option<ParcelFileDescriptor>` to an `Option<File>` by cloning the file.
760fn maybe_clone_file(file: &Option<ParcelFileDescriptor>) -> Result<Option<File>, Status> {
761 file.as_ref().map(clone_file).transpose()
762}
763
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000764/// Converts a `VsockStream` to a `ParcelFileDescriptor`.
765fn vsock_stream_to_pfd(stream: VsockStream) -> ParcelFileDescriptor {
766 // SAFETY: ownership is transferred from stream to f
767 let f = unsafe { File::from_raw_fd(stream.into_raw_fd()) };
768 ParcelFileDescriptor::new(f)
769}
770
Andrew Walbran806f1542021-06-10 14:07:12 +0000771/// Constructs a new Binder error `Status` with the given `ExceptionCode` and message.
772fn new_binder_exception<T: AsRef<str>>(exception: ExceptionCode, message: T) -> Status {
773 Status::new_exception(exception, CString::new(message.as_ref()).ok().as_deref())
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000774}
Jooyung Han35edb8f2021-07-01 16:17:16 +0900775
776/// Simple utility for referencing Borrowed or Owned. Similar to std::borrow::Cow, but
777/// it doesn't require that T implements Clone.
778enum BorrowedOrOwned<'a, T> {
779 Borrowed(&'a T),
780 Owned(T),
781}
782
783impl<'a, T> AsRef<T> for BorrowedOrOwned<'a, T> {
784 fn as_ref(&self) -> &T {
785 match self {
786 Self::Borrowed(b) => b,
Chris Wailes68c39f82021-07-27 16:03:44 -0700787 Self::Owned(o) => o,
Jooyung Han35edb8f2021-07-01 16:17:16 +0900788 }
789 }
790}
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900791
792/// Implementation of `IVirtualMachineService`, the entry point of the AIDL service.
793#[derive(Debug, Default)]
794struct VirtualMachineService {
795 state: Arc<Mutex<State>>,
796}
797
798impl Interface for VirtualMachineService {}
799
800impl IVirtualMachineService for VirtualMachineService {
801 fn notifyPayloadStarted(&self, cid: i32) -> binder::Result<()> {
802 let cid = cid as Cid;
Inseob Kim7f61fe72021-08-20 20:50:47 +0900803 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
804 info!("VM having CID {} started payload", cid);
Andrew Walbran6b650662021-09-07 13:13:23 +0000805 vm.update_payload_state(PayloadState::Started)
806 .map_err(|e| new_binder_exception(ExceptionCode::ILLEGAL_STATE, e.to_string()))?;
Inseob Kim7f61fe72021-08-20 20:50:47 +0900807 let stream = vm.stream.lock().unwrap().take();
808 vm.callbacks.notify_payload_started(cid, stream);
809 Ok(())
810 } else {
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900811 error!("notifyPayloadStarted is called from an unknown cid {}", cid);
Inseob Kim7f61fe72021-08-20 20:50:47 +0900812 Err(new_binder_exception(
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900813 ExceptionCode::SERVICE_SPECIFIC,
814 format!("cannot find a VM with cid {}", cid),
Inseob Kim7f61fe72021-08-20 20:50:47 +0900815 ))
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900816 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900817 }
Inseob Kim2444af92021-08-31 01:22:50 +0900818
Inseob Kim14cb8692021-08-31 21:50:39 +0900819 fn notifyPayloadReady(&self, cid: i32) -> binder::Result<()> {
820 let cid = cid as Cid;
821 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
822 info!("VM having CID {} payload is ready", cid);
Andrew Walbran6b650662021-09-07 13:13:23 +0000823 vm.update_payload_state(PayloadState::Ready)
824 .map_err(|e| new_binder_exception(ExceptionCode::ILLEGAL_STATE, e.to_string()))?;
Inseob Kim14cb8692021-08-31 21:50:39 +0900825 vm.callbacks.notify_payload_ready(cid);
826 Ok(())
827 } else {
828 error!("notifyPayloadReady is called from an unknown cid {}", cid);
829 Err(new_binder_exception(
830 ExceptionCode::SERVICE_SPECIFIC,
831 format!("cannot find a VM with cid {}", cid),
832 ))
833 }
834 }
835
Inseob Kim2444af92021-08-31 01:22:50 +0900836 fn notifyPayloadFinished(&self, cid: i32, exit_code: i32) -> binder::Result<()> {
837 let cid = cid as Cid;
838 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
839 info!("VM having CID {} finished payload", cid);
Andrew Walbran6b650662021-09-07 13:13:23 +0000840 vm.update_payload_state(PayloadState::Finished)
841 .map_err(|e| new_binder_exception(ExceptionCode::ILLEGAL_STATE, e.to_string()))?;
Inseob Kim2444af92021-08-31 01:22:50 +0900842 vm.callbacks.notify_payload_finished(cid, exit_code);
843 Ok(())
844 } else {
845 error!("notifyPayloadFinished is called from an unknown cid {}", cid);
846 Err(new_binder_exception(
847 ExceptionCode::SERVICE_SPECIFIC,
848 format!("cannot find a VM with cid {}", cid),
849 ))
850 }
851 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900852}
853
854impl VirtualMachineService {
855 fn new_binder(state: Arc<Mutex<State>>) -> Strong<dyn IVirtualMachineService> {
856 BnVirtualMachineService::new_binder(
857 VirtualMachineService { state },
858 BinderFeatures::default(),
859 )
860 }
861}