blob: fa6ee404f1cc10bcad07194f4359e3ddf78b4d0f [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,
Jiyong Parkc2a49cc2021-10-15 00:02:12 +090029 VirtualMachineAppConfig::DebugLevel::DebugLevel,
Jooyung Han21e9b922021-06-26 04:14:16 +090030 VirtualMachineAppConfig::VirtualMachineAppConfig,
31 VirtualMachineConfig::VirtualMachineConfig,
Andrew Walbran6b650662021-09-07 13:13:23 +000032 VirtualMachineDebugInfo::VirtualMachineDebugInfo,
Jooyung Han21e9b922021-06-26 04:14:16 +090033 VirtualMachineRawConfig::VirtualMachineRawConfig,
Andrew Walbran6b650662021-09-07 13:13:23 +000034 VirtualMachineState::VirtualMachineState,
Jooyung Han21e9b922021-06-26 04:14:16 +090035};
Andrew Walbranf6bf6862021-05-21 12:41:13 +000036use android_system_virtualizationservice::binder::{
Shikha Panward8e35422021-10-11 13:51:27 +000037 self, BinderFeatures, ExceptionCode, Interface, ParcelFileDescriptor, Status, StatusCode, Strong,
Alan Stokes0cc59ee2021-09-24 11:20:34 +010038 ThreadState,
Andrew Walbrana89fc132021-03-17 17:08:36 +000039};
Alan Stokes0cc59ee2021-09-24 11:20:34 +010040use android_system_virtualmachineservice::aidl::android::system::virtualmachineservice::{
41 IVirtualMachineService::{
42 BnVirtualMachineService, IVirtualMachineService, VM_BINDER_SERVICE_PORT,
43 VM_STREAM_SERVICE_PORT,
44 },
Inseob Kim1b95f2e2021-08-19 13:17:40 +090045};
Jiyong Parkd50a0242021-09-16 21:00:14 +090046use anyhow::{anyhow, bail, Context, Result};
Alan Stokes0cc59ee2021-09-24 11:20:34 +010047use binder_common::{lazy_service::LazyServiceGuard, new_binder_exception};
Andrew Walbrandfc953d2021-06-10 13:59:56 +000048use disk::QcowFile;
Alan Stokes0cc59ee2021-09-24 11:20:34 +010049use idsig::{HashAlgorithm, V4Signature};
50use log::{debug, error, info, warn};
Andrew Walbrancc0db522021-07-12 17:03:42 +000051use microdroid_payload_config::VmPayloadConfig;
Jiyong Parkd50a0242021-09-16 21:00:14 +090052use rustutils::system_properties;
Andrew Walbrandff3b942021-06-09 15:20:36 +000053use std::convert::TryInto;
Shikha Panward8e35422021-10-11 13:51:27 +000054use std::ffi::CStr;
Alan Stokes0cc59ee2021-09-24 11:20:34 +010055use std::fs::{create_dir, File, OpenOptions};
Jiyong Park9dd389e2021-08-23 20:42:59 +090056use std::io::{Error, ErrorKind, Write};
Andrew Walbranb15cd6e2021-07-05 16:38:07 +000057use std::num::NonZeroU32;
Andrew Walbrand3a84182021-09-07 14:48:52 +000058use std::os::unix::io::{FromRawFd, IntoRawFd};
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000059use std::path::{Path, PathBuf};
Andrew Walbran320b5602021-03-04 16:11:12 +000060use std::sync::{Arc, Mutex, Weak};
Andrew Walbrancc0db522021-07-12 17:03:42 +000061use vmconfig::VmConfig;
Inseob Kim7f61fe72021-08-20 20:50:47 +090062use vsock::{SockAddr, VsockListener, VsockStream};
Jooyung Han35edb8f2021-07-01 16:17:16 +090063use zip::ZipArchive;
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000064
Andrew Walbranf6bf6862021-05-21 12:41:13 +000065pub const BINDER_SERVICE_IDENTIFIER: &str = "android.system.virtualizationservice";
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000066
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000067/// Directory in which to write disk image files used while running VMs.
Andrew Walbran488bd072021-07-14 13:29:51 +000068pub const TEMPORARY_DIRECTORY: &str = "/data/misc/virtualizationservice";
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000069
Jiyong Park8611a6c2021-07-09 18:17:44 +090070/// The CID representing the host VM
71const VMADDR_CID_HOST: u32 = 2;
72
Jooyung Han95884632021-07-06 22:27:54 +090073/// The size of zero.img.
74/// Gaps in composite disk images are filled with a shared zero.img.
75const ZERO_FILLER_SIZE: u64 = 4096;
76
Jiyong Park9dd389e2021-08-23 20:42:59 +090077/// Magic string for the instance image
78const ANDROID_VM_INSTANCE_MAGIC: &str = "Android-VM-instance";
79
80/// Version of the instance image format
81const ANDROID_VM_INSTANCE_VERSION: u16 = 1;
82
Andrew Walbranf6bf6862021-05-21 12:41:13 +000083/// Implementation of `IVirtualizationService`, the entry point of the AIDL service.
Jooyung Han9900f3d2021-07-06 10:27:54 +090084#[derive(Debug, Default)]
Andrew Walbranf6bf6862021-05-21 12:41:13 +000085pub struct VirtualizationService {
Jiyong Park8611a6c2021-07-09 18:17:44 +090086 state: Arc<Mutex<State>>,
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000087}
88
Shikha Panward8e35422021-10-11 13:51:27 +000089impl Interface for VirtualizationService {
90 fn dump(&self, mut file: &File, _args: &[&CStr]) -> Result<(), StatusCode> {
91 check_permission("android.permission.DUMP").or(Err(StatusCode::PERMISSION_DENIED))?;
92 let state = &mut *self.state.lock().unwrap();
93 let vms = state.vms();
94 writeln!(file, "Running {0} VMs:", vms.len()).or(Err(StatusCode::UNKNOWN_ERROR))?;
95 for vm in vms {
96 writeln!(file, "VM CID: {}", vm.cid).or(Err(StatusCode::UNKNOWN_ERROR))?;
97 writeln!(file, "\tState: {:?}", vm.vm_state.lock().unwrap())
98 .or(Err(StatusCode::UNKNOWN_ERROR))?;
99 writeln!(file, "\tPayload state {:?}", vm.payload_state())
100 .or(Err(StatusCode::UNKNOWN_ERROR))?;
101 writeln!(file, "\tProtected: {}", vm.protected).or(Err(StatusCode::UNKNOWN_ERROR))?;
102 writeln!(file, "\ttemporary_directory: {}", vm.temporary_directory.to_string_lossy())
103 .or(Err(StatusCode::UNKNOWN_ERROR))?;
104 writeln!(file, "\trequester_uid: {}", vm.requester_uid)
105 .or(Err(StatusCode::UNKNOWN_ERROR))?;
106 writeln!(file, "\trequester_sid: {}", vm.requester_sid)
107 .or(Err(StatusCode::UNKNOWN_ERROR))?;
108 writeln!(file, "\trequester_debug_pid: {}", vm.requester_debug_pid)
109 .or(Err(StatusCode::UNKNOWN_ERROR))?;
110 }
111 Ok(())
112 }
113}
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000114
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000115impl IVirtualizationService for VirtualizationService {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000116 /// Creates (but does not start) a new VM with the given configuration, assigning it the next
117 /// available CID.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000118 ///
119 /// Returns a binder `IVirtualMachine` object referring to it, as a handle for the client.
Andrew Walbranf8d94112021-09-07 11:45:36 +0000120 fn createVm(
Andrew Walbrana89fc132021-03-17 17:08:36 +0000121 &self,
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000122 config: &VirtualMachineConfig,
Andrew Walbrana89fc132021-03-17 17:08:36 +0000123 log_fd: Option<&ParcelFileDescriptor>,
124 ) -> binder::Result<Strong<dyn IVirtualMachine>> {
Jiyong Park753553b2021-07-12 21:21:09 +0900125 check_manage_access()?;
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000126 let state = &mut *self.state.lock().unwrap();
Jiyong Parkc2a49cc2021-10-15 00:02:12 +0900127 let mut log_fd = log_fd.map(clone_file).transpose()?;
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000128 let requester_uid = ThreadState::get_calling_uid();
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000129 let requester_sid = get_calling_sid()?;
Andrew Walbran02034492021-04-13 15:05:07 +0000130 let requester_debug_pid = ThreadState::get_calling_pid();
Jiyong Parkd50a0242021-09-16 21:00:14 +0900131 let cid = next_cid().or(Err(ExceptionCode::ILLEGAL_STATE))?;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000132
133 // Counter to generate unique IDs for temporary image files.
134 let mut next_temporary_image_id = 0;
135 // Files which are referred to from composite images. These must be mapped to the crosvm
136 // child process, and not closed before it is started.
137 let mut indirect_files = vec![];
138
139 // Make directory for temporary files.
140 let temporary_directory: PathBuf = format!("{}/{}", TEMPORARY_DIRECTORY, cid).into();
141 create_dir(&temporary_directory).map_err(|e| {
142 error!(
Andrew Walbran806f1542021-06-10 14:07:12 +0000143 "Failed to create temporary directory {:?} for VM files: {}",
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000144 temporary_directory, e
145 );
Andrew Walbran806f1542021-06-10 14:07:12 +0000146 new_binder_exception(
147 ExceptionCode::SERVICE_SPECIFIC,
148 format!(
149 "Failed to create temporary directory {:?} for VM files: {}",
150 temporary_directory, e
151 ),
152 )
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000153 })?;
154
Jiyong Parkc2a49cc2021-10-15 00:02:12 +0900155 // Disable console logging if debug level != full. Note that kernel anyway doesn't use the
156 // console output when debug level != full. So, users won't be able to see the kernel
157 // output even without this overriding. This is to silence output from the bootloader which
158 // doesn't understand the bootconfig parameters.
159 if let VirtualMachineConfig::AppConfig(config) = config {
160 if config.debugLevel != DebugLevel::FULL {
161 log_fd = None;
162 }
163 }
164
Jooyung Han21e9b922021-06-26 04:14:16 +0900165 let config = match config {
Jooyung Han35edb8f2021-07-01 16:17:16 +0900166 VirtualMachineConfig::AppConfig(config) => BorrowedOrOwned::Owned(
Jooyung Han9900f3d2021-07-06 10:27:54 +0900167 load_app_config(config, &temporary_directory).map_err(|e| {
168 error!("Failed to load app config from {}: {}", &config.configPath, e);
169 new_binder_exception(
170 ExceptionCode::SERVICE_SPECIFIC,
171 format!("Failed to load app config from {}: {}", &config.configPath, e),
172 )
173 })?,
Jooyung Han35edb8f2021-07-01 16:17:16 +0900174 ),
175 VirtualMachineConfig::RawConfig(config) => BorrowedOrOwned::Borrowed(config),
Jooyung Han21e9b922021-06-26 04:14:16 +0900176 };
Jooyung Han35edb8f2021-07-01 16:17:16 +0900177 let config = config.as_ref();
Jooyung Han21e9b922021-06-26 04:14:16 +0900178
Jooyung Han95884632021-07-06 22:27:54 +0900179 let zero_filler_path = temporary_directory.join("zero.img");
Andrew Walbranfbb39d22021-07-28 17:01:25 +0000180 write_zero_filler(&zero_filler_path).map_err(|e| {
Jooyung Han95884632021-07-06 22:27:54 +0900181 error!("Failed to make composite image: {}", e);
182 new_binder_exception(
183 ExceptionCode::SERVICE_SPECIFIC,
184 format!("Failed to make composite image: {}", e),
185 )
186 })?;
Jooyung Han95884632021-07-06 22:27:54 +0900187
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000188 // Assemble disk images if needed.
189 let disks = config
190 .disks
191 .iter()
192 .map(|disk| {
193 assemble_disk_image(
194 disk,
Jooyung Han95884632021-07-06 22:27:54 +0900195 &zero_filler_path,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000196 &temporary_directory,
197 &mut next_temporary_image_id,
198 &mut indirect_files,
199 )
200 })
201 .collect::<Result<Vec<DiskFile>, _>>()?;
202
203 // Actually start the VM.
204 let crosvm_config = CrosvmConfig {
Andrew Walbran02034492021-04-13 15:05:07 +0000205 cid,
Andrew Walbrand3a84182021-09-07 14:48:52 +0000206 bootloader: maybe_clone_file(&config.bootloader)?,
207 kernel: maybe_clone_file(&config.kernel)?,
208 initrd: maybe_clone_file(&config.initrd)?,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000209 disks,
210 params: config.params.to_owned(),
Andrew Walbrancc045902021-07-27 16:06:17 +0000211 protected: config.protectedVm,
212 memory_mib: config.memoryMib.try_into().ok().and_then(NonZeroU32::new),
Andrew Walbran02034492021-04-13 15:05:07 +0000213 log_fd,
Andrew Walbrand3a84182021-09-07 14:48:52 +0000214 indirect_files,
215 };
Andrew Walbranf8d94112021-09-07 11:45:36 +0000216 let instance = Arc::new(
217 VmInstance::new(
218 crosvm_config,
219 temporary_directory,
220 requester_uid,
221 requester_sid,
222 requester_debug_pid,
Andrew Walbran806f1542021-06-10 14:07:12 +0000223 )
Andrew Walbranf8d94112021-09-07 11:45:36 +0000224 .map_err(|e| {
225 error!("Failed to create VM with config {:?}: {}", config, e);
226 new_binder_exception(
227 ExceptionCode::SERVICE_SPECIFIC,
228 format!("Failed to create VM: {}", e),
229 )
230 })?,
231 );
Andrew Walbran320b5602021-03-04 16:11:12 +0000232 state.add_vm(Arc::downgrade(&instance));
233 Ok(VirtualMachine::create(instance))
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000234 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000235
Andrew Walbrandff3b942021-06-09 15:20:36 +0000236 /// Initialise an empty partition image of the given size to be used as a writable partition.
237 fn initializeWritablePartition(
238 &self,
239 image_fd: &ParcelFileDescriptor,
240 size: i64,
Jiyong Park9dd389e2021-08-23 20:42:59 +0900241 partition_type: PartitionType,
Andrew Walbrandff3b942021-06-09 15:20:36 +0000242 ) -> binder::Result<()> {
Jiyong Park753553b2021-07-12 21:21:09 +0900243 check_manage_access()?;
Andrew Walbrandfc953d2021-06-10 13:59:56 +0000244 let size = size.try_into().map_err(|e| {
Andrew Walbran806f1542021-06-10 14:07:12 +0000245 new_binder_exception(
246 ExceptionCode::ILLEGAL_ARGUMENT,
247 format!("Invalid size {}: {}", size, e),
248 )
Andrew Walbrandff3b942021-06-09 15:20:36 +0000249 })?;
Andrew Walbrandfc953d2021-06-10 13:59:56 +0000250 let image = clone_file(image_fd)?;
Andrew Walbrandff3b942021-06-09 15:20:36 +0000251
Jiyong Park9dd389e2021-08-23 20:42:59 +0900252 let mut part = QcowFile::new(image, size).map_err(|e| {
Andrew Walbran806f1542021-06-10 14:07:12 +0000253 new_binder_exception(
254 ExceptionCode::SERVICE_SPECIFIC,
255 format!("Failed to create QCOW2 image: {}", e),
256 )
Andrew Walbrandfc953d2021-06-10 13:59:56 +0000257 })?;
Andrew Walbrandff3b942021-06-09 15:20:36 +0000258
Jiyong Park9dd389e2021-08-23 20:42:59 +0900259 match partition_type {
260 PartitionType::RAW => Ok(()),
261 PartitionType::ANDROID_VM_INSTANCE => format_as_android_vm_instance(&mut part),
262 _ => Err(Error::new(
263 ErrorKind::Unsupported,
264 format!("Unsupported partition type {:?}", partition_type),
265 )),
266 }
267 .map_err(|e| {
268 new_binder_exception(
269 ExceptionCode::SERVICE_SPECIFIC,
270 format!("Failed to initialize partition as {:?}: {}", partition_type, e),
271 )
272 })?;
273
Andrew Walbrandff3b942021-06-09 15:20:36 +0000274 Ok(())
275 }
276
Jiyong Park0a248432021-08-20 23:32:39 +0900277 /// Creates or update the idsig file by digesting the input APK file.
278 fn createOrUpdateIdsigFile(
279 &self,
280 input_fd: &ParcelFileDescriptor,
281 idsig_fd: &ParcelFileDescriptor,
282 ) -> binder::Result<()> {
283 // TODO(b/193504400): do this only when (1) idsig_fd is empty or (2) the APK digest in
284 // idsig_fd is different from APK digest in input_fd
285
286 let mut input = clone_file(input_fd)?;
287 let mut sig = V4Signature::create(&mut input, 4096, &[], HashAlgorithm::SHA256).unwrap();
288
289 let mut output = clone_file(idsig_fd)?;
290 output.set_len(0).unwrap();
291 sig.write_into(&mut output).unwrap();
292 Ok(())
293 }
294
Andrew Walbran320b5602021-03-04 16:11:12 +0000295 /// Get a list of all currently running VMs. This method is only intended for debug purposes,
296 /// and as such is only permitted from the shell user.
297 fn debugListVms(&self) -> binder::Result<Vec<VirtualMachineDebugInfo>> {
Andrew Walbran806f1542021-06-10 14:07:12 +0000298 check_debug_access()?;
Andrew Walbran320b5602021-03-04 16:11:12 +0000299
300 let state = &mut *self.state.lock().unwrap();
301 let vms = state.vms();
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000302 let cids = vms
303 .into_iter()
304 .map(|vm| VirtualMachineDebugInfo {
305 cid: vm.cid as i32,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000306 temporaryDirectory: vm.temporary_directory.to_string_lossy().to_string(),
Andrew Walbran1ef19ae2021-04-07 11:31:57 +0000307 requesterUid: vm.requester_uid as i32,
308 requesterSid: vm.requester_sid.clone(),
Andrew Walbran02034492021-04-13 15:05:07 +0000309 requesterPid: vm.requester_debug_pid,
Andrew Walbran6b650662021-09-07 13:13:23 +0000310 state: get_state(&vm),
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000311 })
312 .collect();
Andrew Walbran320b5602021-03-04 16:11:12 +0000313 Ok(cids)
314 }
David Brazdil3c2ddef2021-03-18 13:09:57 +0000315
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000316 /// Hold a strong reference to a VM in VirtualizationService. This method is only intended for
317 /// debug purposes, and as such is only permitted from the shell user.
Andrei Homescu1415c132021-03-24 02:39:55 +0000318 fn debugHoldVmRef(&self, vmref: &Strong<dyn IVirtualMachine>) -> binder::Result<()> {
Andrew Walbran806f1542021-06-10 14:07:12 +0000319 check_debug_access()?;
David Brazdil3c2ddef2021-03-18 13:09:57 +0000320
David Brazdil3c2ddef2021-03-18 13:09:57 +0000321 let state = &mut *self.state.lock().unwrap();
Andrei Homescu1415c132021-03-24 02:39:55 +0000322 state.debug_hold_vm(vmref.clone());
David Brazdil3c2ddef2021-03-18 13:09:57 +0000323 Ok(())
324 }
325
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000326 /// Drop reference to a VM that is being held by VirtualizationService. Returns the reference if
327 /// the VM was found and None otherwise. This method is only intended for debug purposes, and as
328 /// such is only permitted from the shell user.
David Brazdil3c2ddef2021-03-18 13:09:57 +0000329 fn debugDropVmRef(&self, cid: i32) -> binder::Result<Option<Strong<dyn IVirtualMachine>>> {
Andrew Walbran806f1542021-06-10 14:07:12 +0000330 check_debug_access()?;
David Brazdil3c2ddef2021-03-18 13:09:57 +0000331
332 let state = &mut *self.state.lock().unwrap();
333 Ok(state.debug_drop_vm(cid))
334 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000335}
336
Jiyong Park8611a6c2021-07-09 18:17:44 +0900337impl VirtualizationService {
338 pub fn init() -> VirtualizationService {
339 let service = VirtualizationService::default();
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900340
341 // server for payload output
Jiyong Park8611a6c2021-07-09 18:17:44 +0900342 let state = service.state.clone(); // reference to state (not the state itself) is copied
343 std::thread::spawn(move || {
Inseob Kim7f61fe72021-08-20 20:50:47 +0900344 handle_stream_connection_from_vm(state).unwrap();
Jiyong Park8611a6c2021-07-09 18:17:44 +0900345 });
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900346
347 // binder server for vm
348 let state = service.state.clone(); // reference to state (not the state itself) is copied
349 std::thread::spawn(move || {
350 let mut service = VirtualMachineService::new_binder(state).as_binder();
351 debug!("virtual machine service is starting as an RPC service.");
352 // SAFETY: Service ownership is transferring to the server and won't be valid afterward.
353 // Plus the binder objects are threadsafe.
354 let retval = unsafe {
355 binder_rpc_unstable_bindgen::RunRpcServer(
356 service.as_native_mut() as *mut binder_rpc_unstable_bindgen::AIBinder,
Inseob Kimd0587562021-09-01 21:27:32 +0900357 VM_BINDER_SERVICE_PORT as u32,
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900358 )
359 };
360 if retval {
361 debug!("RPC server has shut down gracefully");
362 } else {
363 bail!("Premature termination of RPC server");
364 }
365
366 Ok(retval)
367 });
Jiyong Park8611a6c2021-07-09 18:17:44 +0900368 service
369 }
370}
371
Andrew Walbran6b650662021-09-07 13:13:23 +0000372/// Waits for incoming connections from VM. If a new connection is made, stores the stream in the
373/// corresponding `VmInstance`.
Inseob Kim7f61fe72021-08-20 20:50:47 +0900374fn handle_stream_connection_from_vm(state: Arc<Mutex<State>>) -> Result<()> {
Inseob Kimd0587562021-09-01 21:27:32 +0900375 let listener =
376 VsockListener::bind_with_cid_port(VMADDR_CID_HOST, VM_STREAM_SERVICE_PORT as u32)?;
Jiyong Park8611a6c2021-07-09 18:17:44 +0900377 for stream in listener.incoming() {
378 let stream = match stream {
379 Err(e) => {
380 warn!("invalid incoming connection: {}", e);
381 continue;
382 }
383 Ok(s) => s,
384 };
385 if let Ok(SockAddr::Vsock(addr)) = stream.peer_addr() {
386 let cid = addr.cid();
387 let port = addr.port();
Inseob Kim7f61fe72021-08-20 20:50:47 +0900388 info!("payload stream connected from cid={}, port={}", cid, port);
Jiyong Park8611a6c2021-07-09 18:17:44 +0900389 if let Some(vm) = state.lock().unwrap().get_vm(cid) {
Chris Wailes8bbb8932021-09-10 14:14:19 -0700390 *vm.stream.lock().unwrap() = Some(stream);
Inseob Kim7f61fe72021-08-20 20:50:47 +0900391 } else {
392 error!("connection from cid={} is not from a guest VM", cid);
Jiyong Park8611a6c2021-07-09 18:17:44 +0900393 }
394 }
395 }
396 Ok(())
397}
398
Andrew Walbranfbb39d22021-07-28 17:01:25 +0000399fn write_zero_filler(zero_filler_path: &Path) -> Result<()> {
Jooyung Han95884632021-07-06 22:27:54 +0900400 let file = OpenOptions::new()
401 .create_new(true)
402 .read(true)
403 .write(true)
404 .open(zero_filler_path)
405 .with_context(|| "Failed to create zero.img")?;
406 file.set_len(ZERO_FILLER_SIZE)?;
Andrew Walbranfbb39d22021-07-28 17:01:25 +0000407 Ok(())
Jooyung Han95884632021-07-06 22:27:54 +0900408}
409
Jiyong Park9dd389e2021-08-23 20:42:59 +0900410fn format_as_android_vm_instance(part: &mut dyn Write) -> std::io::Result<()> {
411 part.write_all(ANDROID_VM_INSTANCE_MAGIC.as_bytes())?;
412 part.write_all(&ANDROID_VM_INSTANCE_VERSION.to_le_bytes())?;
413 part.flush()
414}
415
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000416/// Given the configuration for a disk image, assembles the `DiskFile` to pass to crosvm.
417///
418/// This may involve assembling a composite disk from a set of partition images.
419fn assemble_disk_image(
420 disk: &DiskImage,
Jooyung Han95884632021-07-06 22:27:54 +0900421 zero_filler_path: &Path,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000422 temporary_directory: &Path,
423 next_temporary_image_id: &mut u64,
424 indirect_files: &mut Vec<File>,
Andrew Walbran806f1542021-06-10 14:07:12 +0000425) -> Result<DiskFile, Status> {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000426 let image = if !disk.partitions.is_empty() {
427 if disk.image.is_some() {
428 warn!("DiskImage {:?} contains both image and partitions.", disk);
Andrew Walbran806f1542021-06-10 14:07:12 +0000429 return Err(new_binder_exception(
430 ExceptionCode::ILLEGAL_ARGUMENT,
431 "DiskImage contains both image and partitions.",
432 ));
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000433 }
434
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000435 let composite_image_filenames =
436 make_composite_image_filenames(temporary_directory, next_temporary_image_id);
437 let (image, partition_files) = make_composite_image(
438 &disk.partitions,
Jooyung Han95884632021-07-06 22:27:54 +0900439 zero_filler_path,
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000440 &composite_image_filenames.composite,
441 &composite_image_filenames.header,
442 &composite_image_filenames.footer,
443 )
444 .map_err(|e| {
445 error!("Failed to make composite image with config {:?}: {}", disk, e);
446 new_binder_exception(
447 ExceptionCode::SERVICE_SPECIFIC,
448 format!("Failed to make composite image: {}", e),
449 )
450 })?;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000451
452 // Pass the file descriptors for the various partition files to crosvm when it
453 // is run.
454 indirect_files.extend(partition_files);
455
456 image
457 } else if let Some(image) = &disk.image {
458 clone_file(image)?
459 } else {
460 warn!("DiskImage {:?} didn't contain image or partitions.", disk);
Andrew Walbran806f1542021-06-10 14:07:12 +0000461 return Err(new_binder_exception(
462 ExceptionCode::ILLEGAL_ARGUMENT,
463 "DiskImage didn't contain image or partitions.",
464 ));
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000465 };
466
467 Ok(DiskFile { image, writable: disk.writable })
468}
469
Jooyung Han21e9b922021-06-26 04:14:16 +0900470fn load_app_config(
471 config: &VirtualMachineAppConfig,
472 temporary_directory: &Path,
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900473) -> Result<VirtualMachineRawConfig> {
Andrew Walbrancc0db522021-07-12 17:03:42 +0000474 let apk_file = clone_file(config.apk.as_ref().unwrap())?;
475 let idsig_file = clone_file(config.idsig.as_ref().unwrap())?;
Jiyong Park8d081812021-07-23 17:45:04 +0900476 let instance_file = clone_file(config.instanceImage.as_ref().unwrap())?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900477 let config_path = &config.configPath;
478
Andrew Walbrancc0db522021-07-12 17:03:42 +0000479 let mut apk_zip = ZipArchive::new(&apk_file)?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900480 let config_file = apk_zip.by_name(config_path)?;
481 let vm_payload_config: VmPayloadConfig = serde_json::from_reader(config_file)?;
482
483 let os_name = &vm_payload_config.os.name;
Andrew Walbrancc0db522021-07-12 17:03:42 +0000484
Jooyung Han35edb8f2021-07-01 16:17:16 +0900485 // For now, the only supported "os" value is "microdroid"
486 if os_name != "microdroid" {
Andrew Walbrancc0db522021-07-12 17:03:42 +0000487 bail!("Unknown OS \"{}\"", os_name);
Jooyung Han35edb8f2021-07-01 16:17:16 +0900488 }
Andrew Walbrancc0db522021-07-12 17:03:42 +0000489
490 // It is safe to construct a filename based on the os_name because we've already checked that it
491 // is one of the allowed values.
Jooyung Han21e9b922021-06-26 04:14:16 +0900492 let vm_config_path = PathBuf::from(format!("/apex/com.android.virt/etc/{}.json", os_name));
493 let vm_config_file = File::open(vm_config_path)?;
Andrew Walbrancc0db522021-07-12 17:03:42 +0000494 let mut vm_config = VmConfig::load(&vm_config_file)?.to_parcelable()?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900495
Andrew Walbrancc045902021-07-27 16:06:17 +0000496 if config.memoryMib > 0 {
497 vm_config.memoryMib = config.memoryMib;
Andrew Walbran45bcb0c2021-07-14 15:02:06 +0000498 }
499
Andrew Walbrancc0db522021-07-12 17:03:42 +0000500 // Microdroid requires an additional payload disk image and the bootconfig partition.
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900501 if os_name == "microdroid" {
Andrew Walbrancc0db522021-07-12 17:03:42 +0000502 add_microdroid_images(
503 config,
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900504 temporary_directory,
Andrew Walbrancc0db522021-07-12 17:03:42 +0000505 apk_file,
506 idsig_file,
Jiyong Park8d081812021-07-23 17:45:04 +0900507 instance_file,
Jooyung Han5dc42172021-10-05 16:43:47 +0900508 &vm_payload_config,
Andrew Walbrancc0db522021-07-12 17:03:42 +0000509 &mut vm_config,
510 )?;
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900511 }
Jooyung Han21e9b922021-06-26 04:14:16 +0900512
Andrew Walbrancc0db522021-07-12 17:03:42 +0000513 Ok(vm_config)
Jooyung Han21e9b922021-06-26 04:14:16 +0900514}
515
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000516/// Generates a unique filename to use for a composite disk image.
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000517fn make_composite_image_filenames(
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000518 temporary_directory: &Path,
519 next_temporary_image_id: &mut u64,
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000520) -> CompositeImageFilenames {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000521 let id = *next_temporary_image_id;
522 *next_temporary_image_id += 1;
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000523 CompositeImageFilenames {
524 composite: temporary_directory.join(format!("composite-{}.img", id)),
525 header: temporary_directory.join(format!("composite-{}-header.img", id)),
526 footer: temporary_directory.join(format!("composite-{}-footer.img", id)),
527 }
528}
529
530/// Filenames for a composite disk image, including header and footer partitions.
531#[derive(Clone, Debug, Eq, PartialEq)]
532struct CompositeImageFilenames {
533 /// The composite disk image itself.
534 composite: PathBuf,
535 /// The header partition image.
536 header: PathBuf,
537 /// The footer partition image.
538 footer: PathBuf,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000539}
540
541/// Gets the calling SID of the current Binder thread.
Andrew Walbran806f1542021-06-10 14:07:12 +0000542fn get_calling_sid() -> Result<String, Status> {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000543 ThreadState::with_calling_sid(|sid| {
544 if let Some(sid) = sid {
545 match sid.to_str() {
546 Ok(sid) => Ok(sid.to_owned()),
547 Err(e) => {
Andrew Walbran806f1542021-06-10 14:07:12 +0000548 error!("SID was not valid UTF-8: {}", e);
549 Err(new_binder_exception(
550 ExceptionCode::ILLEGAL_ARGUMENT,
551 format!("SID was not valid UTF-8: {}", e),
552 ))
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000553 }
554 }
555 } else {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000556 error!("Missing SID on createVm");
557 Err(new_binder_exception(ExceptionCode::SECURITY, "Missing SID on createVm"))
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000558 }
559 })
560}
561
Jiyong Park753553b2021-07-12 21:21:09 +0900562/// Checks whether the caller has a specific permission
563fn check_permission(perm: &str) -> binder::Result<()> {
564 let calling_pid = ThreadState::get_calling_pid();
565 let calling_uid = ThreadState::get_calling_uid();
566 // Root can do anything
567 if calling_uid == 0 {
568 return Ok(());
569 }
570 let perm_svc: Strong<dyn IPermissionController::IPermissionController> =
571 binder::get_interface("permission")?;
572 if perm_svc.checkPermission(perm, calling_pid, calling_uid as i32)? {
Andrew Walbran806f1542021-06-10 14:07:12 +0000573 Ok(())
574 } else {
Jiyong Park753553b2021-07-12 21:21:09 +0900575 Err(new_binder_exception(
576 ExceptionCode::SECURITY,
577 format!("does not have the {} permission", perm),
578 ))
Andrew Walbran806f1542021-06-10 14:07:12 +0000579 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000580}
581
Jiyong Park753553b2021-07-12 21:21:09 +0900582/// Check whether the caller of the current Binder method is allowed to call debug methods.
583fn check_debug_access() -> binder::Result<()> {
584 check_permission("android.permission.DEBUG_VIRTUAL_MACHINE")
585}
586
587/// Check whether the caller of the current Binder method is allowed to manage VMs
588fn check_manage_access() -> binder::Result<()> {
589 check_permission("android.permission.MANAGE_VIRTUAL_MACHINE")
590}
591
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000592/// Implementation of the AIDL `IVirtualMachine` interface. Used as a handle to a VM.
593#[derive(Debug)]
594struct VirtualMachine {
595 instance: Arc<VmInstance>,
Alan Stokes0cc59ee2021-09-24 11:20:34 +0100596 /// Keeps our service process running as long as this VM instance exists.
597 lazy_service_guard: LazyServiceGuard,
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000598}
599
600impl VirtualMachine {
601 fn create(instance: Arc<VmInstance>) -> Strong<dyn IVirtualMachine> {
Alan Stokes0cc59ee2021-09-24 11:20:34 +0100602 let binder = VirtualMachine { instance, lazy_service_guard: Default::default() };
Andrew Walbran4de28782021-04-13 14:51:43 +0000603 BnVirtualMachine::new_binder(binder, BinderFeatures::default())
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000604 }
605}
606
607impl Interface for VirtualMachine {}
608
609impl IVirtualMachine for VirtualMachine {
610 fn getCid(&self) -> binder::Result<i32> {
Jiyong Park753553b2021-07-12 21:21:09 +0900611 // Don't check permission. The owner of the VM might have passed this binder object to
612 // others.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000613 Ok(self.instance.cid as i32)
614 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000615
Andrew Walbran6b650662021-09-07 13:13:23 +0000616 fn getState(&self) -> binder::Result<VirtualMachineState> {
Jiyong Park753553b2021-07-12 21:21:09 +0900617 // Don't check permission. The owner of the VM might have passed this binder object to
618 // others.
Andrew Walbran6b650662021-09-07 13:13:23 +0000619 Ok(get_state(&self.instance))
Andrew Walbrandae07162021-03-12 17:05:20 +0000620 }
621
622 fn registerCallback(
623 &self,
624 callback: &Strong<dyn IVirtualMachineCallback>,
625 ) -> binder::Result<()> {
Jiyong Park753553b2021-07-12 21:21:09 +0900626 // Don't check permission. The owner of the VM might have passed this binder object to
627 // others.
628 //
Andrew Walbrandae07162021-03-12 17:05:20 +0000629 // TODO: Should this give an error if the VM is already dead?
630 self.instance.callbacks.add(callback.clone());
631 Ok(())
632 }
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000633
Andrew Walbranf8d94112021-09-07 11:45:36 +0000634 fn start(&self) -> binder::Result<()> {
635 self.instance.start().map_err(|e| {
636 error!("Error starting VM with CID {}: {:?}", self.instance.cid, e);
637 new_binder_exception(ExceptionCode::SERVICE_SPECIFIC, e.to_string())
638 })
639 }
640
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000641 fn connectVsock(&self, port: i32) -> binder::Result<ParcelFileDescriptor> {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000642 if !matches!(&*self.instance.vm_state.lock().unwrap(), VmState::Running { .. }) {
643 return Err(new_binder_exception(ExceptionCode::SERVICE_SPECIFIC, "VM is not running"));
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000644 }
645 let stream =
646 VsockStream::connect_with_cid_port(self.instance.cid, port as u32).map_err(|e| {
647 new_binder_exception(
648 ExceptionCode::SERVICE_SPECIFIC,
649 format!("Failed to connect: {}", e),
650 )
651 })?;
652 Ok(vsock_stream_to_pfd(stream))
653 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000654}
655
656impl Drop for VirtualMachine {
657 fn drop(&mut self) {
658 debug!("Dropping {:?}", self);
659 self.instance.kill();
660 }
661}
662
663/// A set of Binders to be called back in response to various events on the VM, such as when it
664/// dies.
665#[derive(Debug, Default)]
666pub struct VirtualMachineCallbacks(Mutex<Vec<Strong<dyn IVirtualMachineCallback>>>);
667
668impl VirtualMachineCallbacks {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900669 /// Call all registered callbacks to notify that the payload has started.
Inseob Kim7f61fe72021-08-20 20:50:47 +0900670 pub fn notify_payload_started(&self, cid: Cid, stream: Option<VsockStream>) {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900671 let callbacks = &*self.0.lock().unwrap();
Inseob Kim7f61fe72021-08-20 20:50:47 +0900672 let pfd = stream.map(vsock_stream_to_pfd);
Jiyong Park8611a6c2021-07-09 18:17:44 +0900673 for callback in callbacks {
Inseob Kim7f61fe72021-08-20 20:50:47 +0900674 if let Err(e) = callback.onPayloadStarted(cid as i32, pfd.as_ref()) {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900675 error!("Error notifying payload start event from VM CID {}: {}", cid, e);
676 }
677 }
678 }
679
Inseob Kim14cb8692021-08-31 21:50:39 +0900680 /// Call all registered callbacks to notify that the payload is ready to serve.
681 pub fn notify_payload_ready(&self, cid: Cid) {
682 let callbacks = &*self.0.lock().unwrap();
683 for callback in callbacks {
684 if let Err(e) = callback.onPayloadReady(cid as i32) {
685 error!("Error notifying payload ready event from VM CID {}: {}", cid, e);
686 }
687 }
688 }
689
Inseob Kim2444af92021-08-31 01:22:50 +0900690 /// Call all registered callbacks to notify that the payload has finished.
691 pub fn notify_payload_finished(&self, cid: Cid, exit_code: i32) {
692 let callbacks = &*self.0.lock().unwrap();
693 for callback in callbacks {
694 if let Err(e) = callback.onPayloadFinished(cid as i32, exit_code) {
695 error!("Error notifying payload finish event from VM CID {}: {}", cid, e);
696 }
697 }
698 }
699
Andrew Walbrandae07162021-03-12 17:05:20 +0000700 /// Call all registered callbacks to say that the VM has died.
701 pub fn callback_on_died(&self, cid: Cid) {
702 let callbacks = &*self.0.lock().unwrap();
703 for callback in callbacks {
704 if let Err(e) = callback.onDied(cid as i32) {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900705 error!("Error notifying exit of VM CID {}: {}", cid, e);
Andrew Walbrandae07162021-03-12 17:05:20 +0000706 }
707 }
708 }
709
710 /// Add a new callback to the set.
711 fn add(&self, callback: Strong<dyn IVirtualMachineCallback>) {
712 self.0.lock().unwrap().push(callback);
713 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000714}
715
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000716/// The mutable state of the VirtualizationService. There should only be one instance of this
717/// struct.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000718#[derive(Debug)]
719struct State {
Andrew Walbran320b5602021-03-04 16:11:12 +0000720 /// The VMs which have been started. When VMs are started a weak reference is added to this list
721 /// while a strong reference is returned to the caller over Binder. Once all copies of the
722 /// Binder client are dropped the weak reference here will become invalid, and will be removed
723 /// from the list opportunistically the next time `add_vm` is called.
724 vms: Vec<Weak<VmInstance>>,
David Brazdil3c2ddef2021-03-18 13:09:57 +0000725
726 /// Vector of strong VM references held on behalf of users that cannot hold them themselves.
727 /// This is only used for debugging purposes.
728 debug_held_vms: Vec<Strong<dyn IVirtualMachine>>,
Andrew Walbran320b5602021-03-04 16:11:12 +0000729}
730
731impl State {
Andrew Walbrandae07162021-03-12 17:05:20 +0000732 /// Get a list of VMs which still have Binder references to them.
Andrew Walbran320b5602021-03-04 16:11:12 +0000733 fn vms(&self) -> Vec<Arc<VmInstance>> {
734 // Attempt to upgrade the weak pointers to strong pointers.
735 self.vms.iter().filter_map(Weak::upgrade).collect()
736 }
737
738 /// Add a new VM to the list.
739 fn add_vm(&mut self, vm: Weak<VmInstance>) {
740 // Garbage collect any entries from the stored list which no longer exist.
741 self.vms.retain(|vm| vm.strong_count() > 0);
742
743 // Actually add the new VM.
744 self.vms.push(vm);
745 }
David Brazdil3c2ddef2021-03-18 13:09:57 +0000746
Jiyong Park8611a6c2021-07-09 18:17:44 +0900747 /// Get a VM that corresponds to the given cid
748 fn get_vm(&self, cid: Cid) -> Option<Arc<VmInstance>> {
749 self.vms().into_iter().find(|vm| vm.cid == cid)
750 }
751
David Brazdil3c2ddef2021-03-18 13:09:57 +0000752 /// Store a strong VM reference.
753 fn debug_hold_vm(&mut self, vm: Strong<dyn IVirtualMachine>) {
754 self.debug_held_vms.push(vm);
755 }
756
757 /// Retrieve and remove a strong VM reference.
758 fn debug_drop_vm(&mut self, cid: i32) -> Option<Strong<dyn IVirtualMachine>> {
759 let pos = self.debug_held_vms.iter().position(|vm| vm.getCid() == Ok(cid))?;
Alan Stokes7e54e292021-09-09 11:37:56 +0100760 let vm = self.debug_held_vms.swap_remove(pos);
Alan Stokes7e54e292021-09-09 11:37:56 +0100761 Some(vm)
David Brazdil3c2ddef2021-03-18 13:09:57 +0000762 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000763}
764
765impl Default for State {
766 fn default() -> Self {
Jiyong Parkd50a0242021-09-16 21:00:14 +0900767 State { vms: vec![], debug_held_vms: vec![] }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000768 }
769}
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000770
Jiyong Parkd50a0242021-09-16 21:00:14 +0900771/// Get the next available CID, or an error if we have run out. The last CID used is stored in
772/// a system property so that restart of virtualizationservice doesn't reuse CID while the host
773/// Android is up.
774fn next_cid() -> Result<Cid> {
775 let next = if let Ok(val) = system_properties::read(SYSPROP_LAST_CID) {
776 if let Ok(num) = val.parse::<u32>() {
777 num.checked_add(1).ok_or_else(|| anyhow!("run out of CID"))?
778 } else {
779 error!("Invalid last CID {}. Using {}", &val, FIRST_GUEST_CID);
780 FIRST_GUEST_CID
781 }
782 } else {
783 // First VM since the boot
784 FIRST_GUEST_CID
785 };
786 // Persist the last value for next use
787 let str_val = format!("{}", next);
788 system_properties::write(SYSPROP_LAST_CID, &str_val)?;
789 Ok(next)
790}
791
Andrew Walbran6b650662021-09-07 13:13:23 +0000792/// Gets the `VirtualMachineState` of the given `VmInstance`.
793fn get_state(instance: &VmInstance) -> VirtualMachineState {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000794 match &*instance.vm_state.lock().unwrap() {
795 VmState::NotStarted { .. } => VirtualMachineState::NOT_STARTED,
796 VmState::Running { .. } => match instance.payload_state() {
Andrew Walbran6b650662021-09-07 13:13:23 +0000797 PayloadState::Starting => VirtualMachineState::STARTING,
798 PayloadState::Started => VirtualMachineState::STARTED,
799 PayloadState::Ready => VirtualMachineState::READY,
800 PayloadState::Finished => VirtualMachineState::FINISHED,
Andrew Walbranf8d94112021-09-07 11:45:36 +0000801 },
802 VmState::Dead => VirtualMachineState::DEAD,
803 VmState::Failed => VirtualMachineState::DEAD,
Andrew Walbran6b650662021-09-07 13:13:23 +0000804 }
805}
806
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000807/// Converts a `&ParcelFileDescriptor` to a `File` by cloning the file.
Andrew Walbran806f1542021-06-10 14:07:12 +0000808fn clone_file(file: &ParcelFileDescriptor) -> Result<File, Status> {
809 file.as_ref().try_clone().map_err(|e| {
810 new_binder_exception(
811 ExceptionCode::BAD_PARCELABLE,
812 format!("Failed to clone File from ParcelFileDescriptor: {}", e),
813 )
814 })
815}
816
Andrew Walbrand3a84182021-09-07 14:48:52 +0000817/// Converts an `&Option<ParcelFileDescriptor>` to an `Option<File>` by cloning the file.
818fn maybe_clone_file(file: &Option<ParcelFileDescriptor>) -> Result<Option<File>, Status> {
819 file.as_ref().map(clone_file).transpose()
820}
821
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000822/// Converts a `VsockStream` to a `ParcelFileDescriptor`.
823fn vsock_stream_to_pfd(stream: VsockStream) -> ParcelFileDescriptor {
824 // SAFETY: ownership is transferred from stream to f
825 let f = unsafe { File::from_raw_fd(stream.into_raw_fd()) };
826 ParcelFileDescriptor::new(f)
827}
828
Jooyung Han35edb8f2021-07-01 16:17:16 +0900829/// Simple utility for referencing Borrowed or Owned. Similar to std::borrow::Cow, but
830/// it doesn't require that T implements Clone.
831enum BorrowedOrOwned<'a, T> {
832 Borrowed(&'a T),
833 Owned(T),
834}
835
836impl<'a, T> AsRef<T> for BorrowedOrOwned<'a, T> {
837 fn as_ref(&self) -> &T {
838 match self {
839 Self::Borrowed(b) => b,
Chris Wailes68c39f82021-07-27 16:03:44 -0700840 Self::Owned(o) => o,
Jooyung Han35edb8f2021-07-01 16:17:16 +0900841 }
842 }
843}
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900844
845/// Implementation of `IVirtualMachineService`, the entry point of the AIDL service.
846#[derive(Debug, Default)]
847struct VirtualMachineService {
848 state: Arc<Mutex<State>>,
849}
850
851impl Interface for VirtualMachineService {}
852
853impl IVirtualMachineService for VirtualMachineService {
854 fn notifyPayloadStarted(&self, cid: i32) -> binder::Result<()> {
855 let cid = cid as Cid;
Inseob Kim7f61fe72021-08-20 20:50:47 +0900856 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
857 info!("VM having CID {} started payload", cid);
Andrew Walbran6b650662021-09-07 13:13:23 +0000858 vm.update_payload_state(PayloadState::Started)
859 .map_err(|e| new_binder_exception(ExceptionCode::ILLEGAL_STATE, e.to_string()))?;
Inseob Kim7f61fe72021-08-20 20:50:47 +0900860 let stream = vm.stream.lock().unwrap().take();
861 vm.callbacks.notify_payload_started(cid, stream);
862 Ok(())
863 } else {
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900864 error!("notifyPayloadStarted is called from an unknown cid {}", cid);
Inseob Kim7f61fe72021-08-20 20:50:47 +0900865 Err(new_binder_exception(
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900866 ExceptionCode::SERVICE_SPECIFIC,
867 format!("cannot find a VM with cid {}", cid),
Inseob Kim7f61fe72021-08-20 20:50:47 +0900868 ))
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900869 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900870 }
Inseob Kim2444af92021-08-31 01:22:50 +0900871
Inseob Kim14cb8692021-08-31 21:50:39 +0900872 fn notifyPayloadReady(&self, cid: i32) -> binder::Result<()> {
873 let cid = cid as Cid;
874 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
875 info!("VM having CID {} payload is ready", cid);
Andrew Walbran6b650662021-09-07 13:13:23 +0000876 vm.update_payload_state(PayloadState::Ready)
877 .map_err(|e| new_binder_exception(ExceptionCode::ILLEGAL_STATE, e.to_string()))?;
Inseob Kim14cb8692021-08-31 21:50:39 +0900878 vm.callbacks.notify_payload_ready(cid);
879 Ok(())
880 } else {
881 error!("notifyPayloadReady is called from an unknown cid {}", cid);
882 Err(new_binder_exception(
883 ExceptionCode::SERVICE_SPECIFIC,
884 format!("cannot find a VM with cid {}", cid),
885 ))
886 }
887 }
888
Inseob Kim2444af92021-08-31 01:22:50 +0900889 fn notifyPayloadFinished(&self, cid: i32, exit_code: i32) -> binder::Result<()> {
890 let cid = cid as Cid;
891 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
892 info!("VM having CID {} finished payload", cid);
Andrew Walbran6b650662021-09-07 13:13:23 +0000893 vm.update_payload_state(PayloadState::Finished)
894 .map_err(|e| new_binder_exception(ExceptionCode::ILLEGAL_STATE, e.to_string()))?;
Inseob Kim2444af92021-08-31 01:22:50 +0900895 vm.callbacks.notify_payload_finished(cid, exit_code);
896 Ok(())
897 } else {
898 error!("notifyPayloadFinished is called from an unknown cid {}", cid);
899 Err(new_binder_exception(
900 ExceptionCode::SERVICE_SPECIFIC,
901 format!("cannot find a VM with cid {}", cid),
902 ))
903 }
904 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900905}
906
907impl VirtualMachineService {
908 fn new_binder(state: Arc<Mutex<State>>) -> Strong<dyn IVirtualMachineService> {
909 BnVirtualMachineService::new_binder(
910 VirtualMachineService { state },
911 BinderFeatures::default(),
912 )
913 }
914}