blob: 8e58e17534398cb74b3f57fc5bcae74956d9c240 [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};
Alan Stokes0cc59ee2021-09-24 11:20:34 +010021use ::binder::unstable_api::AsNative;
Jiyong Park753553b2021-07-12 21:21:09 +090022use android_os_permissions_aidl::aidl::android::os::IPermissionController;
Jooyung Han21e9b922021-06-26 04:14:16 +090023use android_system_virtualizationservice::aidl::android::system::virtualizationservice::{
Andrew Walbran6b650662021-09-07 13:13:23 +000024 DiskImage::DiskImage,
Alan Stokes0cc59ee2021-09-24 11:20:34 +010025 IVirtualMachine::{BnVirtualMachine, IVirtualMachine},
Andrew Walbran6b650662021-09-07 13:13:23 +000026 IVirtualMachineCallback::IVirtualMachineCallback,
27 IVirtualizationService::IVirtualizationService,
28 PartitionType::PartitionType,
Jooyung Han21e9b922021-06-26 04:14:16 +090029 VirtualMachineAppConfig::VirtualMachineAppConfig,
30 VirtualMachineConfig::VirtualMachineConfig,
Andrew Walbran6b650662021-09-07 13:13:23 +000031 VirtualMachineDebugInfo::VirtualMachineDebugInfo,
Jooyung Han21e9b922021-06-26 04:14:16 +090032 VirtualMachineRawConfig::VirtualMachineRawConfig,
Andrew Walbran6b650662021-09-07 13:13:23 +000033 VirtualMachineState::VirtualMachineState,
Jooyung Han21e9b922021-06-26 04:14:16 +090034};
Andrew Walbranf6bf6862021-05-21 12:41:13 +000035use android_system_virtualizationservice::binder::{
Shikha Panward8e35422021-10-11 13:51:27 +000036 self, BinderFeatures, ExceptionCode, Interface, ParcelFileDescriptor, Status, StatusCode, Strong,
Alan Stokes0cc59ee2021-09-24 11:20:34 +010037 ThreadState,
Andrew Walbrana89fc132021-03-17 17:08:36 +000038};
Alan Stokes0cc59ee2021-09-24 11:20:34 +010039use android_system_virtualmachineservice::aidl::android::system::virtualmachineservice::{
40 IVirtualMachineService::{
41 BnVirtualMachineService, IVirtualMachineService, VM_BINDER_SERVICE_PORT,
42 VM_STREAM_SERVICE_PORT,
43 },
Inseob Kim1b95f2e2021-08-19 13:17:40 +090044};
Jiyong Parkd50a0242021-09-16 21:00:14 +090045use anyhow::{anyhow, bail, Context, Result};
Alan Stokes0cc59ee2021-09-24 11:20:34 +010046use binder_common::{lazy_service::LazyServiceGuard, new_binder_exception};
Andrew Walbrandfc953d2021-06-10 13:59:56 +000047use disk::QcowFile;
Alan Stokes0cc59ee2021-09-24 11:20:34 +010048use idsig::{HashAlgorithm, V4Signature};
49use log::{debug, error, info, warn};
Andrew Walbrancc0db522021-07-12 17:03:42 +000050use microdroid_payload_config::VmPayloadConfig;
Jiyong Parkd50a0242021-09-16 21:00:14 +090051use rustutils::system_properties;
Andrew Walbrandff3b942021-06-09 15:20:36 +000052use std::convert::TryInto;
Shikha Panward8e35422021-10-11 13:51:27 +000053use std::ffi::CStr;
Alan Stokes0cc59ee2021-09-24 11:20:34 +010054use std::fs::{create_dir, File, OpenOptions};
Jiyong Park9dd389e2021-08-23 20:42:59 +090055use std::io::{Error, ErrorKind, Write};
Andrew Walbranb15cd6e2021-07-05 16:38:07 +000056use std::num::NonZeroU32;
Andrew Walbrand3a84182021-09-07 14:48:52 +000057use std::os::unix::io::{FromRawFd, IntoRawFd};
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000058use std::path::{Path, PathBuf};
Andrew Walbran320b5602021-03-04 16:11:12 +000059use std::sync::{Arc, Mutex, Weak};
Andrew Walbrancc0db522021-07-12 17:03:42 +000060use vmconfig::VmConfig;
Inseob Kim7f61fe72021-08-20 20:50:47 +090061use vsock::{SockAddr, VsockListener, VsockStream};
Jooyung Han35edb8f2021-07-01 16:17:16 +090062use zip::ZipArchive;
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000063
Andrew Walbranf6bf6862021-05-21 12:41:13 +000064pub const BINDER_SERVICE_IDENTIFIER: &str = "android.system.virtualizationservice";
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000065
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000066/// Directory in which to write disk image files used while running VMs.
Andrew Walbran488bd072021-07-14 13:29:51 +000067pub const TEMPORARY_DIRECTORY: &str = "/data/misc/virtualizationservice";
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000068
Jiyong Park8611a6c2021-07-09 18:17:44 +090069/// The CID representing the host VM
70const VMADDR_CID_HOST: u32 = 2;
71
Jooyung Han95884632021-07-06 22:27:54 +090072/// The size of zero.img.
73/// Gaps in composite disk images are filled with a shared zero.img.
74const ZERO_FILLER_SIZE: u64 = 4096;
75
Jiyong Park9dd389e2021-08-23 20:42:59 +090076/// Magic string for the instance image
77const ANDROID_VM_INSTANCE_MAGIC: &str = "Android-VM-instance";
78
79/// Version of the instance image format
80const ANDROID_VM_INSTANCE_VERSION: u16 = 1;
81
Andrew Walbranf6bf6862021-05-21 12:41:13 +000082/// Implementation of `IVirtualizationService`, the entry point of the AIDL service.
Jooyung Han9900f3d2021-07-06 10:27:54 +090083#[derive(Debug, Default)]
Andrew Walbranf6bf6862021-05-21 12:41:13 +000084pub struct VirtualizationService {
Jiyong Park8611a6c2021-07-09 18:17:44 +090085 state: Arc<Mutex<State>>,
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000086}
87
Shikha Panward8e35422021-10-11 13:51:27 +000088impl Interface for VirtualizationService {
89 fn dump(&self, mut file: &File, _args: &[&CStr]) -> Result<(), StatusCode> {
90 check_permission("android.permission.DUMP").or(Err(StatusCode::PERMISSION_DENIED))?;
91 let state = &mut *self.state.lock().unwrap();
92 let vms = state.vms();
93 writeln!(file, "Running {0} VMs:", vms.len()).or(Err(StatusCode::UNKNOWN_ERROR))?;
94 for vm in vms {
95 writeln!(file, "VM CID: {}", vm.cid).or(Err(StatusCode::UNKNOWN_ERROR))?;
96 writeln!(file, "\tState: {:?}", vm.vm_state.lock().unwrap())
97 .or(Err(StatusCode::UNKNOWN_ERROR))?;
98 writeln!(file, "\tPayload state {:?}", vm.payload_state())
99 .or(Err(StatusCode::UNKNOWN_ERROR))?;
100 writeln!(file, "\tProtected: {}", vm.protected).or(Err(StatusCode::UNKNOWN_ERROR))?;
101 writeln!(file, "\ttemporary_directory: {}", vm.temporary_directory.to_string_lossy())
102 .or(Err(StatusCode::UNKNOWN_ERROR))?;
103 writeln!(file, "\trequester_uid: {}", vm.requester_uid)
104 .or(Err(StatusCode::UNKNOWN_ERROR))?;
105 writeln!(file, "\trequester_sid: {}", vm.requester_sid)
106 .or(Err(StatusCode::UNKNOWN_ERROR))?;
107 writeln!(file, "\trequester_debug_pid: {}", vm.requester_debug_pid)
108 .or(Err(StatusCode::UNKNOWN_ERROR))?;
109 }
110 Ok(())
111 }
112}
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000113
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000114impl IVirtualizationService for VirtualizationService {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000115 /// Creates (but does not start) a new VM with the given configuration, assigning it the next
116 /// available CID.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000117 ///
118 /// Returns a binder `IVirtualMachine` object referring to it, as a handle for the client.
Andrew Walbranf8d94112021-09-07 11:45:36 +0000119 fn createVm(
Andrew Walbrana89fc132021-03-17 17:08:36 +0000120 &self,
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000121 config: &VirtualMachineConfig,
Andrew Walbrana89fc132021-03-17 17:08:36 +0000122 log_fd: Option<&ParcelFileDescriptor>,
123 ) -> binder::Result<Strong<dyn IVirtualMachine>> {
Jiyong Park753553b2021-07-12 21:21:09 +0900124 check_manage_access()?;
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000125 let state = &mut *self.state.lock().unwrap();
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000126 let log_fd = log_fd.map(clone_file).transpose()?;
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000127 let requester_uid = ThreadState::get_calling_uid();
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000128 let requester_sid = get_calling_sid()?;
Andrew Walbran02034492021-04-13 15:05:07 +0000129 let requester_debug_pid = ThreadState::get_calling_pid();
Jiyong Parkd50a0242021-09-16 21:00:14 +0900130 let cid = next_cid().or(Err(ExceptionCode::ILLEGAL_STATE))?;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000131
132 // Counter to generate unique IDs for temporary image files.
133 let mut next_temporary_image_id = 0;
134 // Files which are referred to from composite images. These must be mapped to the crosvm
135 // child process, and not closed before it is started.
136 let mut indirect_files = vec![];
137
138 // Make directory for temporary files.
139 let temporary_directory: PathBuf = format!("{}/{}", TEMPORARY_DIRECTORY, cid).into();
140 create_dir(&temporary_directory).map_err(|e| {
141 error!(
Andrew Walbran806f1542021-06-10 14:07:12 +0000142 "Failed to create temporary directory {:?} for VM files: {}",
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000143 temporary_directory, e
144 );
Andrew Walbran806f1542021-06-10 14:07:12 +0000145 new_binder_exception(
146 ExceptionCode::SERVICE_SPECIFIC,
147 format!(
148 "Failed to create temporary directory {:?} for VM files: {}",
149 temporary_directory, e
150 ),
151 )
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000152 })?;
153
Jooyung Han21e9b922021-06-26 04:14:16 +0900154 let config = match config {
Jooyung Han35edb8f2021-07-01 16:17:16 +0900155 VirtualMachineConfig::AppConfig(config) => BorrowedOrOwned::Owned(
Jooyung Han9900f3d2021-07-06 10:27:54 +0900156 load_app_config(config, &temporary_directory).map_err(|e| {
157 error!("Failed to load app config from {}: {}", &config.configPath, e);
158 new_binder_exception(
159 ExceptionCode::SERVICE_SPECIFIC,
160 format!("Failed to load app config from {}: {}", &config.configPath, e),
161 )
162 })?,
Jooyung Han35edb8f2021-07-01 16:17:16 +0900163 ),
164 VirtualMachineConfig::RawConfig(config) => BorrowedOrOwned::Borrowed(config),
Jooyung Han21e9b922021-06-26 04:14:16 +0900165 };
Jooyung Han35edb8f2021-07-01 16:17:16 +0900166 let config = config.as_ref();
Jooyung Han21e9b922021-06-26 04:14:16 +0900167
Jooyung Han95884632021-07-06 22:27:54 +0900168 let zero_filler_path = temporary_directory.join("zero.img");
Andrew Walbranfbb39d22021-07-28 17:01:25 +0000169 write_zero_filler(&zero_filler_path).map_err(|e| {
Jooyung Han95884632021-07-06 22:27:54 +0900170 error!("Failed to make composite image: {}", e);
171 new_binder_exception(
172 ExceptionCode::SERVICE_SPECIFIC,
173 format!("Failed to make composite image: {}", e),
174 )
175 })?;
Jooyung Han95884632021-07-06 22:27:54 +0900176
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000177 // Assemble disk images if needed.
178 let disks = config
179 .disks
180 .iter()
181 .map(|disk| {
182 assemble_disk_image(
183 disk,
Jooyung Han95884632021-07-06 22:27:54 +0900184 &zero_filler_path,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000185 &temporary_directory,
186 &mut next_temporary_image_id,
187 &mut indirect_files,
188 )
189 })
190 .collect::<Result<Vec<DiskFile>, _>>()?;
191
192 // Actually start the VM.
193 let crosvm_config = CrosvmConfig {
Andrew Walbran02034492021-04-13 15:05:07 +0000194 cid,
Andrew Walbrand3a84182021-09-07 14:48:52 +0000195 bootloader: maybe_clone_file(&config.bootloader)?,
196 kernel: maybe_clone_file(&config.kernel)?,
197 initrd: maybe_clone_file(&config.initrd)?,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000198 disks,
199 params: config.params.to_owned(),
Andrew Walbrancc045902021-07-27 16:06:17 +0000200 protected: config.protectedVm,
201 memory_mib: config.memoryMib.try_into().ok().and_then(NonZeroU32::new),
Andrew Walbran02034492021-04-13 15:05:07 +0000202 log_fd,
Andrew Walbrand3a84182021-09-07 14:48:52 +0000203 indirect_files,
204 };
Andrew Walbranf8d94112021-09-07 11:45:36 +0000205 let instance = Arc::new(
206 VmInstance::new(
207 crosvm_config,
208 temporary_directory,
209 requester_uid,
210 requester_sid,
211 requester_debug_pid,
Andrew Walbran806f1542021-06-10 14:07:12 +0000212 )
Andrew Walbranf8d94112021-09-07 11:45:36 +0000213 .map_err(|e| {
214 error!("Failed to create VM with config {:?}: {}", config, e);
215 new_binder_exception(
216 ExceptionCode::SERVICE_SPECIFIC,
217 format!("Failed to create VM: {}", e),
218 )
219 })?,
220 );
Andrew Walbran320b5602021-03-04 16:11:12 +0000221 state.add_vm(Arc::downgrade(&instance));
222 Ok(VirtualMachine::create(instance))
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000223 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000224
Andrew Walbrandff3b942021-06-09 15:20:36 +0000225 /// Initialise an empty partition image of the given size to be used as a writable partition.
226 fn initializeWritablePartition(
227 &self,
228 image_fd: &ParcelFileDescriptor,
229 size: i64,
Jiyong Park9dd389e2021-08-23 20:42:59 +0900230 partition_type: PartitionType,
Andrew Walbrandff3b942021-06-09 15:20:36 +0000231 ) -> binder::Result<()> {
Jiyong Park753553b2021-07-12 21:21:09 +0900232 check_manage_access()?;
Andrew Walbrandfc953d2021-06-10 13:59:56 +0000233 let size = size.try_into().map_err(|e| {
Andrew Walbran806f1542021-06-10 14:07:12 +0000234 new_binder_exception(
235 ExceptionCode::ILLEGAL_ARGUMENT,
236 format!("Invalid size {}: {}", size, e),
237 )
Andrew Walbrandff3b942021-06-09 15:20:36 +0000238 })?;
Andrew Walbrandfc953d2021-06-10 13:59:56 +0000239 let image = clone_file(image_fd)?;
Andrew Walbrandff3b942021-06-09 15:20:36 +0000240
Jiyong Park9dd389e2021-08-23 20:42:59 +0900241 let mut part = QcowFile::new(image, size).map_err(|e| {
Andrew Walbran806f1542021-06-10 14:07:12 +0000242 new_binder_exception(
243 ExceptionCode::SERVICE_SPECIFIC,
244 format!("Failed to create QCOW2 image: {}", e),
245 )
Andrew Walbrandfc953d2021-06-10 13:59:56 +0000246 })?;
Andrew Walbrandff3b942021-06-09 15:20:36 +0000247
Jiyong Park9dd389e2021-08-23 20:42:59 +0900248 match partition_type {
249 PartitionType::RAW => Ok(()),
250 PartitionType::ANDROID_VM_INSTANCE => format_as_android_vm_instance(&mut part),
251 _ => Err(Error::new(
252 ErrorKind::Unsupported,
253 format!("Unsupported partition type {:?}", partition_type),
254 )),
255 }
256 .map_err(|e| {
257 new_binder_exception(
258 ExceptionCode::SERVICE_SPECIFIC,
259 format!("Failed to initialize partition as {:?}: {}", partition_type, e),
260 )
261 })?;
262
Andrew Walbrandff3b942021-06-09 15:20:36 +0000263 Ok(())
264 }
265
Jiyong Park0a248432021-08-20 23:32:39 +0900266 /// Creates or update the idsig file by digesting the input APK file.
267 fn createOrUpdateIdsigFile(
268 &self,
269 input_fd: &ParcelFileDescriptor,
270 idsig_fd: &ParcelFileDescriptor,
271 ) -> binder::Result<()> {
272 // TODO(b/193504400): do this only when (1) idsig_fd is empty or (2) the APK digest in
273 // idsig_fd is different from APK digest in input_fd
274
275 let mut input = clone_file(input_fd)?;
276 let mut sig = V4Signature::create(&mut input, 4096, &[], HashAlgorithm::SHA256).unwrap();
277
278 let mut output = clone_file(idsig_fd)?;
279 output.set_len(0).unwrap();
280 sig.write_into(&mut output).unwrap();
281 Ok(())
282 }
283
Andrew Walbran320b5602021-03-04 16:11:12 +0000284 /// Get a list of all currently running VMs. This method is only intended for debug purposes,
285 /// and as such is only permitted from the shell user.
286 fn debugListVms(&self) -> binder::Result<Vec<VirtualMachineDebugInfo>> {
Andrew Walbran806f1542021-06-10 14:07:12 +0000287 check_debug_access()?;
Andrew Walbran320b5602021-03-04 16:11:12 +0000288
289 let state = &mut *self.state.lock().unwrap();
290 let vms = state.vms();
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000291 let cids = vms
292 .into_iter()
293 .map(|vm| VirtualMachineDebugInfo {
294 cid: vm.cid as i32,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000295 temporaryDirectory: vm.temporary_directory.to_string_lossy().to_string(),
Andrew Walbran1ef19ae2021-04-07 11:31:57 +0000296 requesterUid: vm.requester_uid as i32,
297 requesterSid: vm.requester_sid.clone(),
Andrew Walbran02034492021-04-13 15:05:07 +0000298 requesterPid: vm.requester_debug_pid,
Andrew Walbran6b650662021-09-07 13:13:23 +0000299 state: get_state(&vm),
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000300 })
301 .collect();
Andrew Walbran320b5602021-03-04 16:11:12 +0000302 Ok(cids)
303 }
David Brazdil3c2ddef2021-03-18 13:09:57 +0000304
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000305 /// Hold a strong reference to a VM in VirtualizationService. This method is only intended for
306 /// debug purposes, and as such is only permitted from the shell user.
Andrei Homescu1415c132021-03-24 02:39:55 +0000307 fn debugHoldVmRef(&self, vmref: &Strong<dyn IVirtualMachine>) -> binder::Result<()> {
Andrew Walbran806f1542021-06-10 14:07:12 +0000308 check_debug_access()?;
David Brazdil3c2ddef2021-03-18 13:09:57 +0000309
David Brazdil3c2ddef2021-03-18 13:09:57 +0000310 let state = &mut *self.state.lock().unwrap();
Andrei Homescu1415c132021-03-24 02:39:55 +0000311 state.debug_hold_vm(vmref.clone());
David Brazdil3c2ddef2021-03-18 13:09:57 +0000312 Ok(())
313 }
314
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000315 /// Drop reference to a VM that is being held by VirtualizationService. Returns the reference if
316 /// the VM was found and None otherwise. This method is only intended for debug purposes, and as
317 /// such is only permitted from the shell user.
David Brazdil3c2ddef2021-03-18 13:09:57 +0000318 fn debugDropVmRef(&self, cid: i32) -> binder::Result<Option<Strong<dyn IVirtualMachine>>> {
Andrew Walbran806f1542021-06-10 14:07:12 +0000319 check_debug_access()?;
David Brazdil3c2ddef2021-03-18 13:09:57 +0000320
321 let state = &mut *self.state.lock().unwrap();
322 Ok(state.debug_drop_vm(cid))
323 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000324}
325
Jiyong Park8611a6c2021-07-09 18:17:44 +0900326impl VirtualizationService {
327 pub fn init() -> VirtualizationService {
328 let service = VirtualizationService::default();
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900329
330 // server for payload output
Jiyong Park8611a6c2021-07-09 18:17:44 +0900331 let state = service.state.clone(); // reference to state (not the state itself) is copied
332 std::thread::spawn(move || {
Inseob Kim7f61fe72021-08-20 20:50:47 +0900333 handle_stream_connection_from_vm(state).unwrap();
Jiyong Park8611a6c2021-07-09 18:17:44 +0900334 });
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900335
336 // binder server for vm
337 let state = service.state.clone(); // reference to state (not the state itself) is copied
338 std::thread::spawn(move || {
339 let mut service = VirtualMachineService::new_binder(state).as_binder();
340 debug!("virtual machine service is starting as an RPC service.");
341 // SAFETY: Service ownership is transferring to the server and won't be valid afterward.
342 // Plus the binder objects are threadsafe.
343 let retval = unsafe {
344 binder_rpc_unstable_bindgen::RunRpcServer(
345 service.as_native_mut() as *mut binder_rpc_unstable_bindgen::AIBinder,
Inseob Kimd0587562021-09-01 21:27:32 +0900346 VM_BINDER_SERVICE_PORT as u32,
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900347 )
348 };
349 if retval {
350 debug!("RPC server has shut down gracefully");
351 } else {
352 bail!("Premature termination of RPC server");
353 }
354
355 Ok(retval)
356 });
Jiyong Park8611a6c2021-07-09 18:17:44 +0900357 service
358 }
359}
360
Andrew Walbran6b650662021-09-07 13:13:23 +0000361/// Waits for incoming connections from VM. If a new connection is made, stores the stream in the
362/// corresponding `VmInstance`.
Inseob Kim7f61fe72021-08-20 20:50:47 +0900363fn handle_stream_connection_from_vm(state: Arc<Mutex<State>>) -> Result<()> {
Inseob Kimd0587562021-09-01 21:27:32 +0900364 let listener =
365 VsockListener::bind_with_cid_port(VMADDR_CID_HOST, VM_STREAM_SERVICE_PORT as u32)?;
Jiyong Park8611a6c2021-07-09 18:17:44 +0900366 for stream in listener.incoming() {
367 let stream = match stream {
368 Err(e) => {
369 warn!("invalid incoming connection: {}", e);
370 continue;
371 }
372 Ok(s) => s,
373 };
374 if let Ok(SockAddr::Vsock(addr)) = stream.peer_addr() {
375 let cid = addr.cid();
376 let port = addr.port();
Inseob Kim7f61fe72021-08-20 20:50:47 +0900377 info!("payload stream connected from cid={}, port={}", cid, port);
Jiyong Park8611a6c2021-07-09 18:17:44 +0900378 if let Some(vm) = state.lock().unwrap().get_vm(cid) {
Chris Wailes8bbb8932021-09-10 14:14:19 -0700379 *vm.stream.lock().unwrap() = Some(stream);
Inseob Kim7f61fe72021-08-20 20:50:47 +0900380 } else {
381 error!("connection from cid={} is not from a guest VM", cid);
Jiyong Park8611a6c2021-07-09 18:17:44 +0900382 }
383 }
384 }
385 Ok(())
386}
387
Andrew Walbranfbb39d22021-07-28 17:01:25 +0000388fn write_zero_filler(zero_filler_path: &Path) -> Result<()> {
Jooyung Han95884632021-07-06 22:27:54 +0900389 let file = OpenOptions::new()
390 .create_new(true)
391 .read(true)
392 .write(true)
393 .open(zero_filler_path)
394 .with_context(|| "Failed to create zero.img")?;
395 file.set_len(ZERO_FILLER_SIZE)?;
Andrew Walbranfbb39d22021-07-28 17:01:25 +0000396 Ok(())
Jooyung Han95884632021-07-06 22:27:54 +0900397}
398
Jiyong Park9dd389e2021-08-23 20:42:59 +0900399fn format_as_android_vm_instance(part: &mut dyn Write) -> std::io::Result<()> {
400 part.write_all(ANDROID_VM_INSTANCE_MAGIC.as_bytes())?;
401 part.write_all(&ANDROID_VM_INSTANCE_VERSION.to_le_bytes())?;
402 part.flush()
403}
404
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000405/// Given the configuration for a disk image, assembles the `DiskFile` to pass to crosvm.
406///
407/// This may involve assembling a composite disk from a set of partition images.
408fn assemble_disk_image(
409 disk: &DiskImage,
Jooyung Han95884632021-07-06 22:27:54 +0900410 zero_filler_path: &Path,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000411 temporary_directory: &Path,
412 next_temporary_image_id: &mut u64,
413 indirect_files: &mut Vec<File>,
Andrew Walbran806f1542021-06-10 14:07:12 +0000414) -> Result<DiskFile, Status> {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000415 let image = if !disk.partitions.is_empty() {
416 if disk.image.is_some() {
417 warn!("DiskImage {:?} contains both image and partitions.", disk);
Andrew Walbran806f1542021-06-10 14:07:12 +0000418 return Err(new_binder_exception(
419 ExceptionCode::ILLEGAL_ARGUMENT,
420 "DiskImage contains both image and partitions.",
421 ));
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000422 }
423
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000424 let composite_image_filenames =
425 make_composite_image_filenames(temporary_directory, next_temporary_image_id);
426 let (image, partition_files) = make_composite_image(
427 &disk.partitions,
Jooyung Han95884632021-07-06 22:27:54 +0900428 zero_filler_path,
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000429 &composite_image_filenames.composite,
430 &composite_image_filenames.header,
431 &composite_image_filenames.footer,
432 )
433 .map_err(|e| {
434 error!("Failed to make composite image with config {:?}: {}", disk, e);
435 new_binder_exception(
436 ExceptionCode::SERVICE_SPECIFIC,
437 format!("Failed to make composite image: {}", e),
438 )
439 })?;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000440
441 // Pass the file descriptors for the various partition files to crosvm when it
442 // is run.
443 indirect_files.extend(partition_files);
444
445 image
446 } else if let Some(image) = &disk.image {
447 clone_file(image)?
448 } else {
449 warn!("DiskImage {:?} didn't contain image or partitions.", disk);
Andrew Walbran806f1542021-06-10 14:07:12 +0000450 return Err(new_binder_exception(
451 ExceptionCode::ILLEGAL_ARGUMENT,
452 "DiskImage didn't contain image or partitions.",
453 ));
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000454 };
455
456 Ok(DiskFile { image, writable: disk.writable })
457}
458
Jooyung Han21e9b922021-06-26 04:14:16 +0900459fn load_app_config(
460 config: &VirtualMachineAppConfig,
461 temporary_directory: &Path,
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900462) -> Result<VirtualMachineRawConfig> {
Andrew Walbrancc0db522021-07-12 17:03:42 +0000463 let apk_file = clone_file(config.apk.as_ref().unwrap())?;
464 let idsig_file = clone_file(config.idsig.as_ref().unwrap())?;
Jiyong Park8d081812021-07-23 17:45:04 +0900465 let instance_file = clone_file(config.instanceImage.as_ref().unwrap())?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900466 let config_path = &config.configPath;
467
Andrew Walbrancc0db522021-07-12 17:03:42 +0000468 let mut apk_zip = ZipArchive::new(&apk_file)?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900469 let config_file = apk_zip.by_name(config_path)?;
470 let vm_payload_config: VmPayloadConfig = serde_json::from_reader(config_file)?;
471
472 let os_name = &vm_payload_config.os.name;
Andrew Walbrancc0db522021-07-12 17:03:42 +0000473
Jooyung Han35edb8f2021-07-01 16:17:16 +0900474 // For now, the only supported "os" value is "microdroid"
475 if os_name != "microdroid" {
Andrew Walbrancc0db522021-07-12 17:03:42 +0000476 bail!("Unknown OS \"{}\"", os_name);
Jooyung Han35edb8f2021-07-01 16:17:16 +0900477 }
Andrew Walbrancc0db522021-07-12 17:03:42 +0000478
479 // It is safe to construct a filename based on the os_name because we've already checked that it
480 // is one of the allowed values.
Jooyung Han21e9b922021-06-26 04:14:16 +0900481 let vm_config_path = PathBuf::from(format!("/apex/com.android.virt/etc/{}.json", os_name));
482 let vm_config_file = File::open(vm_config_path)?;
Andrew Walbrancc0db522021-07-12 17:03:42 +0000483 let mut vm_config = VmConfig::load(&vm_config_file)?.to_parcelable()?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900484
Andrew Walbrancc045902021-07-27 16:06:17 +0000485 if config.memoryMib > 0 {
486 vm_config.memoryMib = config.memoryMib;
Andrew Walbran45bcb0c2021-07-14 15:02:06 +0000487 }
488
Andrew Walbrancc0db522021-07-12 17:03:42 +0000489 // Microdroid requires an additional payload disk image and the bootconfig partition.
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900490 if os_name == "microdroid" {
Andrew Walbrancc0db522021-07-12 17:03:42 +0000491 add_microdroid_images(
492 config,
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900493 temporary_directory,
Andrew Walbrancc0db522021-07-12 17:03:42 +0000494 apk_file,
495 idsig_file,
Jiyong Park8d081812021-07-23 17:45:04 +0900496 instance_file,
Jooyung Han5dc42172021-10-05 16:43:47 +0900497 &vm_payload_config,
Andrew Walbrancc0db522021-07-12 17:03:42 +0000498 &mut vm_config,
499 )?;
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900500 }
Jooyung Han21e9b922021-06-26 04:14:16 +0900501
Andrew Walbrancc0db522021-07-12 17:03:42 +0000502 Ok(vm_config)
Jooyung Han21e9b922021-06-26 04:14:16 +0900503}
504
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000505/// Generates a unique filename to use for a composite disk image.
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000506fn make_composite_image_filenames(
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000507 temporary_directory: &Path,
508 next_temporary_image_id: &mut u64,
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000509) -> CompositeImageFilenames {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000510 let id = *next_temporary_image_id;
511 *next_temporary_image_id += 1;
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000512 CompositeImageFilenames {
513 composite: temporary_directory.join(format!("composite-{}.img", id)),
514 header: temporary_directory.join(format!("composite-{}-header.img", id)),
515 footer: temporary_directory.join(format!("composite-{}-footer.img", id)),
516 }
517}
518
519/// Filenames for a composite disk image, including header and footer partitions.
520#[derive(Clone, Debug, Eq, PartialEq)]
521struct CompositeImageFilenames {
522 /// The composite disk image itself.
523 composite: PathBuf,
524 /// The header partition image.
525 header: PathBuf,
526 /// The footer partition image.
527 footer: PathBuf,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000528}
529
530/// Gets the calling SID of the current Binder thread.
Andrew Walbran806f1542021-06-10 14:07:12 +0000531fn get_calling_sid() -> Result<String, Status> {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000532 ThreadState::with_calling_sid(|sid| {
533 if let Some(sid) = sid {
534 match sid.to_str() {
535 Ok(sid) => Ok(sid.to_owned()),
536 Err(e) => {
Andrew Walbran806f1542021-06-10 14:07:12 +0000537 error!("SID was not valid UTF-8: {}", e);
538 Err(new_binder_exception(
539 ExceptionCode::ILLEGAL_ARGUMENT,
540 format!("SID was not valid UTF-8: {}", e),
541 ))
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000542 }
543 }
544 } else {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000545 error!("Missing SID on createVm");
546 Err(new_binder_exception(ExceptionCode::SECURITY, "Missing SID on createVm"))
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000547 }
548 })
549}
550
Jiyong Park753553b2021-07-12 21:21:09 +0900551/// Checks whether the caller has a specific permission
552fn check_permission(perm: &str) -> binder::Result<()> {
553 let calling_pid = ThreadState::get_calling_pid();
554 let calling_uid = ThreadState::get_calling_uid();
555 // Root can do anything
556 if calling_uid == 0 {
557 return Ok(());
558 }
559 let perm_svc: Strong<dyn IPermissionController::IPermissionController> =
560 binder::get_interface("permission")?;
561 if perm_svc.checkPermission(perm, calling_pid, calling_uid as i32)? {
Andrew Walbran806f1542021-06-10 14:07:12 +0000562 Ok(())
563 } else {
Jiyong Park753553b2021-07-12 21:21:09 +0900564 Err(new_binder_exception(
565 ExceptionCode::SECURITY,
566 format!("does not have the {} permission", perm),
567 ))
Andrew Walbran806f1542021-06-10 14:07:12 +0000568 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000569}
570
Jiyong Park753553b2021-07-12 21:21:09 +0900571/// Check whether the caller of the current Binder method is allowed to call debug methods.
572fn check_debug_access() -> binder::Result<()> {
573 check_permission("android.permission.DEBUG_VIRTUAL_MACHINE")
574}
575
576/// Check whether the caller of the current Binder method is allowed to manage VMs
577fn check_manage_access() -> binder::Result<()> {
578 check_permission("android.permission.MANAGE_VIRTUAL_MACHINE")
579}
580
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000581/// Implementation of the AIDL `IVirtualMachine` interface. Used as a handle to a VM.
582#[derive(Debug)]
583struct VirtualMachine {
584 instance: Arc<VmInstance>,
Alan Stokes0cc59ee2021-09-24 11:20:34 +0100585 /// Keeps our service process running as long as this VM instance exists.
586 lazy_service_guard: LazyServiceGuard,
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000587}
588
589impl VirtualMachine {
590 fn create(instance: Arc<VmInstance>) -> Strong<dyn IVirtualMachine> {
Alan Stokes0cc59ee2021-09-24 11:20:34 +0100591 let binder = VirtualMachine { instance, lazy_service_guard: Default::default() };
Andrew Walbran4de28782021-04-13 14:51:43 +0000592 BnVirtualMachine::new_binder(binder, BinderFeatures::default())
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000593 }
594}
595
596impl Interface for VirtualMachine {}
597
598impl IVirtualMachine for VirtualMachine {
599 fn getCid(&self) -> binder::Result<i32> {
Jiyong Park753553b2021-07-12 21:21:09 +0900600 // Don't check permission. The owner of the VM might have passed this binder object to
601 // others.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000602 Ok(self.instance.cid as i32)
603 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000604
Andrew Walbran6b650662021-09-07 13:13:23 +0000605 fn getState(&self) -> binder::Result<VirtualMachineState> {
Jiyong Park753553b2021-07-12 21:21:09 +0900606 // Don't check permission. The owner of the VM might have passed this binder object to
607 // others.
Andrew Walbran6b650662021-09-07 13:13:23 +0000608 Ok(get_state(&self.instance))
Andrew Walbrandae07162021-03-12 17:05:20 +0000609 }
610
611 fn registerCallback(
612 &self,
613 callback: &Strong<dyn IVirtualMachineCallback>,
614 ) -> binder::Result<()> {
Jiyong Park753553b2021-07-12 21:21:09 +0900615 // Don't check permission. The owner of the VM might have passed this binder object to
616 // others.
617 //
Andrew Walbrandae07162021-03-12 17:05:20 +0000618 // TODO: Should this give an error if the VM is already dead?
619 self.instance.callbacks.add(callback.clone());
620 Ok(())
621 }
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000622
Andrew Walbranf8d94112021-09-07 11:45:36 +0000623 fn start(&self) -> binder::Result<()> {
624 self.instance.start().map_err(|e| {
625 error!("Error starting VM with CID {}: {:?}", self.instance.cid, e);
626 new_binder_exception(ExceptionCode::SERVICE_SPECIFIC, e.to_string())
627 })
628 }
629
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000630 fn connectVsock(&self, port: i32) -> binder::Result<ParcelFileDescriptor> {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000631 if !matches!(&*self.instance.vm_state.lock().unwrap(), VmState::Running { .. }) {
632 return Err(new_binder_exception(ExceptionCode::SERVICE_SPECIFIC, "VM is not running"));
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000633 }
634 let stream =
635 VsockStream::connect_with_cid_port(self.instance.cid, port as u32).map_err(|e| {
636 new_binder_exception(
637 ExceptionCode::SERVICE_SPECIFIC,
638 format!("Failed to connect: {}", e),
639 )
640 })?;
641 Ok(vsock_stream_to_pfd(stream))
642 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000643}
644
645impl Drop for VirtualMachine {
646 fn drop(&mut self) {
647 debug!("Dropping {:?}", self);
648 self.instance.kill();
649 }
650}
651
652/// A set of Binders to be called back in response to various events on the VM, such as when it
653/// dies.
654#[derive(Debug, Default)]
655pub struct VirtualMachineCallbacks(Mutex<Vec<Strong<dyn IVirtualMachineCallback>>>);
656
657impl VirtualMachineCallbacks {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900658 /// Call all registered callbacks to notify that the payload has started.
Inseob Kim7f61fe72021-08-20 20:50:47 +0900659 pub fn notify_payload_started(&self, cid: Cid, stream: Option<VsockStream>) {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900660 let callbacks = &*self.0.lock().unwrap();
Inseob Kim7f61fe72021-08-20 20:50:47 +0900661 let pfd = stream.map(vsock_stream_to_pfd);
Jiyong Park8611a6c2021-07-09 18:17:44 +0900662 for callback in callbacks {
Inseob Kim7f61fe72021-08-20 20:50:47 +0900663 if let Err(e) = callback.onPayloadStarted(cid as i32, pfd.as_ref()) {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900664 error!("Error notifying payload start event from VM CID {}: {}", cid, e);
665 }
666 }
667 }
668
Inseob Kim14cb8692021-08-31 21:50:39 +0900669 /// Call all registered callbacks to notify that the payload is ready to serve.
670 pub fn notify_payload_ready(&self, cid: Cid) {
671 let callbacks = &*self.0.lock().unwrap();
672 for callback in callbacks {
673 if let Err(e) = callback.onPayloadReady(cid as i32) {
674 error!("Error notifying payload ready event from VM CID {}: {}", cid, e);
675 }
676 }
677 }
678
Inseob Kim2444af92021-08-31 01:22:50 +0900679 /// Call all registered callbacks to notify that the payload has finished.
680 pub fn notify_payload_finished(&self, cid: Cid, exit_code: i32) {
681 let callbacks = &*self.0.lock().unwrap();
682 for callback in callbacks {
683 if let Err(e) = callback.onPayloadFinished(cid as i32, exit_code) {
684 error!("Error notifying payload finish event from VM CID {}: {}", cid, e);
685 }
686 }
687 }
688
Andrew Walbrandae07162021-03-12 17:05:20 +0000689 /// Call all registered callbacks to say that the VM has died.
690 pub fn callback_on_died(&self, cid: Cid) {
691 let callbacks = &*self.0.lock().unwrap();
692 for callback in callbacks {
693 if let Err(e) = callback.onDied(cid as i32) {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900694 error!("Error notifying exit of VM CID {}: {}", cid, e);
Andrew Walbrandae07162021-03-12 17:05:20 +0000695 }
696 }
697 }
698
699 /// Add a new callback to the set.
700 fn add(&self, callback: Strong<dyn IVirtualMachineCallback>) {
701 self.0.lock().unwrap().push(callback);
702 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000703}
704
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000705/// The mutable state of the VirtualizationService. There should only be one instance of this
706/// struct.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000707#[derive(Debug)]
708struct State {
Andrew Walbran320b5602021-03-04 16:11:12 +0000709 /// The VMs which have been started. When VMs are started a weak reference is added to this list
710 /// while a strong reference is returned to the caller over Binder. Once all copies of the
711 /// Binder client are dropped the weak reference here will become invalid, and will be removed
712 /// from the list opportunistically the next time `add_vm` is called.
713 vms: Vec<Weak<VmInstance>>,
David Brazdil3c2ddef2021-03-18 13:09:57 +0000714
715 /// Vector of strong VM references held on behalf of users that cannot hold them themselves.
716 /// This is only used for debugging purposes.
717 debug_held_vms: Vec<Strong<dyn IVirtualMachine>>,
Andrew Walbran320b5602021-03-04 16:11:12 +0000718}
719
720impl State {
Andrew Walbrandae07162021-03-12 17:05:20 +0000721 /// Get a list of VMs which still have Binder references to them.
Andrew Walbran320b5602021-03-04 16:11:12 +0000722 fn vms(&self) -> Vec<Arc<VmInstance>> {
723 // Attempt to upgrade the weak pointers to strong pointers.
724 self.vms.iter().filter_map(Weak::upgrade).collect()
725 }
726
727 /// Add a new VM to the list.
728 fn add_vm(&mut self, vm: Weak<VmInstance>) {
729 // Garbage collect any entries from the stored list which no longer exist.
730 self.vms.retain(|vm| vm.strong_count() > 0);
731
732 // Actually add the new VM.
733 self.vms.push(vm);
734 }
David Brazdil3c2ddef2021-03-18 13:09:57 +0000735
Jiyong Park8611a6c2021-07-09 18:17:44 +0900736 /// Get a VM that corresponds to the given cid
737 fn get_vm(&self, cid: Cid) -> Option<Arc<VmInstance>> {
738 self.vms().into_iter().find(|vm| vm.cid == cid)
739 }
740
David Brazdil3c2ddef2021-03-18 13:09:57 +0000741 /// Store a strong VM reference.
742 fn debug_hold_vm(&mut self, vm: Strong<dyn IVirtualMachine>) {
743 self.debug_held_vms.push(vm);
744 }
745
746 /// Retrieve and remove a strong VM reference.
747 fn debug_drop_vm(&mut self, cid: i32) -> Option<Strong<dyn IVirtualMachine>> {
748 let pos = self.debug_held_vms.iter().position(|vm| vm.getCid() == Ok(cid))?;
Alan Stokes7e54e292021-09-09 11:37:56 +0100749 let vm = self.debug_held_vms.swap_remove(pos);
Alan Stokes7e54e292021-09-09 11:37:56 +0100750 Some(vm)
David Brazdil3c2ddef2021-03-18 13:09:57 +0000751 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000752}
753
754impl Default for State {
755 fn default() -> Self {
Jiyong Parkd50a0242021-09-16 21:00:14 +0900756 State { vms: vec![], debug_held_vms: vec![] }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000757 }
758}
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000759
Jiyong Parkd50a0242021-09-16 21:00:14 +0900760/// Get the next available CID, or an error if we have run out. The last CID used is stored in
761/// a system property so that restart of virtualizationservice doesn't reuse CID while the host
762/// Android is up.
763fn next_cid() -> Result<Cid> {
764 let next = if let Ok(val) = system_properties::read(SYSPROP_LAST_CID) {
765 if let Ok(num) = val.parse::<u32>() {
766 num.checked_add(1).ok_or_else(|| anyhow!("run out of CID"))?
767 } else {
768 error!("Invalid last CID {}. Using {}", &val, FIRST_GUEST_CID);
769 FIRST_GUEST_CID
770 }
771 } else {
772 // First VM since the boot
773 FIRST_GUEST_CID
774 };
775 // Persist the last value for next use
776 let str_val = format!("{}", next);
777 system_properties::write(SYSPROP_LAST_CID, &str_val)?;
778 Ok(next)
779}
780
Andrew Walbran6b650662021-09-07 13:13:23 +0000781/// Gets the `VirtualMachineState` of the given `VmInstance`.
782fn get_state(instance: &VmInstance) -> VirtualMachineState {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000783 match &*instance.vm_state.lock().unwrap() {
784 VmState::NotStarted { .. } => VirtualMachineState::NOT_STARTED,
785 VmState::Running { .. } => match instance.payload_state() {
Andrew Walbran6b650662021-09-07 13:13:23 +0000786 PayloadState::Starting => VirtualMachineState::STARTING,
787 PayloadState::Started => VirtualMachineState::STARTED,
788 PayloadState::Ready => VirtualMachineState::READY,
789 PayloadState::Finished => VirtualMachineState::FINISHED,
Andrew Walbranf8d94112021-09-07 11:45:36 +0000790 },
791 VmState::Dead => VirtualMachineState::DEAD,
792 VmState::Failed => VirtualMachineState::DEAD,
Andrew Walbran6b650662021-09-07 13:13:23 +0000793 }
794}
795
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000796/// Converts a `&ParcelFileDescriptor` to a `File` by cloning the file.
Andrew Walbran806f1542021-06-10 14:07:12 +0000797fn clone_file(file: &ParcelFileDescriptor) -> Result<File, Status> {
798 file.as_ref().try_clone().map_err(|e| {
799 new_binder_exception(
800 ExceptionCode::BAD_PARCELABLE,
801 format!("Failed to clone File from ParcelFileDescriptor: {}", e),
802 )
803 })
804}
805
Andrew Walbrand3a84182021-09-07 14:48:52 +0000806/// Converts an `&Option<ParcelFileDescriptor>` to an `Option<File>` by cloning the file.
807fn maybe_clone_file(file: &Option<ParcelFileDescriptor>) -> Result<Option<File>, Status> {
808 file.as_ref().map(clone_file).transpose()
809}
810
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000811/// Converts a `VsockStream` to a `ParcelFileDescriptor`.
812fn vsock_stream_to_pfd(stream: VsockStream) -> ParcelFileDescriptor {
813 // SAFETY: ownership is transferred from stream to f
814 let f = unsafe { File::from_raw_fd(stream.into_raw_fd()) };
815 ParcelFileDescriptor::new(f)
816}
817
Jooyung Han35edb8f2021-07-01 16:17:16 +0900818/// Simple utility for referencing Borrowed or Owned. Similar to std::borrow::Cow, but
819/// it doesn't require that T implements Clone.
820enum BorrowedOrOwned<'a, T> {
821 Borrowed(&'a T),
822 Owned(T),
823}
824
825impl<'a, T> AsRef<T> for BorrowedOrOwned<'a, T> {
826 fn as_ref(&self) -> &T {
827 match self {
828 Self::Borrowed(b) => b,
Chris Wailes68c39f82021-07-27 16:03:44 -0700829 Self::Owned(o) => o,
Jooyung Han35edb8f2021-07-01 16:17:16 +0900830 }
831 }
832}
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900833
834/// Implementation of `IVirtualMachineService`, the entry point of the AIDL service.
835#[derive(Debug, Default)]
836struct VirtualMachineService {
837 state: Arc<Mutex<State>>,
838}
839
840impl Interface for VirtualMachineService {}
841
842impl IVirtualMachineService for VirtualMachineService {
843 fn notifyPayloadStarted(&self, cid: i32) -> binder::Result<()> {
844 let cid = cid as Cid;
Inseob Kim7f61fe72021-08-20 20:50:47 +0900845 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
846 info!("VM having CID {} started payload", cid);
Andrew Walbran6b650662021-09-07 13:13:23 +0000847 vm.update_payload_state(PayloadState::Started)
848 .map_err(|e| new_binder_exception(ExceptionCode::ILLEGAL_STATE, e.to_string()))?;
Inseob Kim7f61fe72021-08-20 20:50:47 +0900849 let stream = vm.stream.lock().unwrap().take();
850 vm.callbacks.notify_payload_started(cid, stream);
851 Ok(())
852 } else {
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900853 error!("notifyPayloadStarted is called from an unknown cid {}", cid);
Inseob Kim7f61fe72021-08-20 20:50:47 +0900854 Err(new_binder_exception(
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900855 ExceptionCode::SERVICE_SPECIFIC,
856 format!("cannot find a VM with cid {}", cid),
Inseob Kim7f61fe72021-08-20 20:50:47 +0900857 ))
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900858 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900859 }
Inseob Kim2444af92021-08-31 01:22:50 +0900860
Inseob Kim14cb8692021-08-31 21:50:39 +0900861 fn notifyPayloadReady(&self, cid: i32) -> binder::Result<()> {
862 let cid = cid as Cid;
863 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
864 info!("VM having CID {} payload is ready", cid);
Andrew Walbran6b650662021-09-07 13:13:23 +0000865 vm.update_payload_state(PayloadState::Ready)
866 .map_err(|e| new_binder_exception(ExceptionCode::ILLEGAL_STATE, e.to_string()))?;
Inseob Kim14cb8692021-08-31 21:50:39 +0900867 vm.callbacks.notify_payload_ready(cid);
868 Ok(())
869 } else {
870 error!("notifyPayloadReady is called from an unknown cid {}", cid);
871 Err(new_binder_exception(
872 ExceptionCode::SERVICE_SPECIFIC,
873 format!("cannot find a VM with cid {}", cid),
874 ))
875 }
876 }
877
Inseob Kim2444af92021-08-31 01:22:50 +0900878 fn notifyPayloadFinished(&self, cid: i32, exit_code: i32) -> binder::Result<()> {
879 let cid = cid as Cid;
880 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
881 info!("VM having CID {} finished payload", cid);
Andrew Walbran6b650662021-09-07 13:13:23 +0000882 vm.update_payload_state(PayloadState::Finished)
883 .map_err(|e| new_binder_exception(ExceptionCode::ILLEGAL_STATE, e.to_string()))?;
Inseob Kim2444af92021-08-31 01:22:50 +0900884 vm.callbacks.notify_payload_finished(cid, exit_code);
885 Ok(())
886 } else {
887 error!("notifyPayloadFinished is called from an unknown cid {}", cid);
888 Err(new_binder_exception(
889 ExceptionCode::SERVICE_SPECIFIC,
890 format!("cannot find a VM with cid {}", cid),
891 ))
892 }
893 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900894}
895
896impl VirtualMachineService {
897 fn new_binder(state: Arc<Mutex<State>>) -> Strong<dyn IVirtualMachineService> {
898 BnVirtualMachineService::new_binder(
899 VirtualMachineService { state },
900 BinderFeatures::default(),
901 )
902 }
903}