blob: 2f901b49ff3d5c890241ee7acd9129b625f38112 [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;
Inseob Kimc7d28c72021-10-25 14:28:10 +000058use std::os::raw;
Andrew Walbrand3a84182021-09-07 14:48:52 +000059use std::os::unix::io::{FromRawFd, IntoRawFd};
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000060use std::path::{Path, PathBuf};
Inseob Kimc7d28c72021-10-25 14:28:10 +000061use std::ptr::null_mut;
Andrew Walbran320b5602021-03-04 16:11:12 +000062use std::sync::{Arc, Mutex, Weak};
Andrew Walbrancc0db522021-07-12 17:03:42 +000063use vmconfig::VmConfig;
Inseob Kim7f61fe72021-08-20 20:50:47 +090064use vsock::{SockAddr, VsockListener, VsockStream};
Jooyung Han35edb8f2021-07-01 16:17:16 +090065use zip::ZipArchive;
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000066
Andrew Walbranf6bf6862021-05-21 12:41:13 +000067pub const BINDER_SERVICE_IDENTIFIER: &str = "android.system.virtualizationservice";
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000068
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000069/// Directory in which to write disk image files used while running VMs.
Andrew Walbran488bd072021-07-14 13:29:51 +000070pub const TEMPORARY_DIRECTORY: &str = "/data/misc/virtualizationservice";
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000071
Jiyong Park8611a6c2021-07-09 18:17:44 +090072/// The CID representing the host VM
73const VMADDR_CID_HOST: u32 = 2;
74
Jooyung Han95884632021-07-06 22:27:54 +090075/// The size of zero.img.
76/// Gaps in composite disk images are filled with a shared zero.img.
77const ZERO_FILLER_SIZE: u64 = 4096;
78
Jiyong Park9dd389e2021-08-23 20:42:59 +090079/// Magic string for the instance image
80const ANDROID_VM_INSTANCE_MAGIC: &str = "Android-VM-instance";
81
82/// Version of the instance image format
83const ANDROID_VM_INSTANCE_VERSION: u16 = 1;
84
Andrew Walbranf6bf6862021-05-21 12:41:13 +000085/// Implementation of `IVirtualizationService`, the entry point of the AIDL service.
Jooyung Han9900f3d2021-07-06 10:27:54 +090086#[derive(Debug, Default)]
Andrew Walbranf6bf6862021-05-21 12:41:13 +000087pub struct VirtualizationService {
Jiyong Park8611a6c2021-07-09 18:17:44 +090088 state: Arc<Mutex<State>>,
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000089}
90
Shikha Panward8e35422021-10-11 13:51:27 +000091impl Interface for VirtualizationService {
92 fn dump(&self, mut file: &File, _args: &[&CStr]) -> Result<(), StatusCode> {
93 check_permission("android.permission.DUMP").or(Err(StatusCode::PERMISSION_DENIED))?;
94 let state = &mut *self.state.lock().unwrap();
95 let vms = state.vms();
96 writeln!(file, "Running {0} VMs:", vms.len()).or(Err(StatusCode::UNKNOWN_ERROR))?;
97 for vm in vms {
98 writeln!(file, "VM CID: {}", vm.cid).or(Err(StatusCode::UNKNOWN_ERROR))?;
99 writeln!(file, "\tState: {:?}", vm.vm_state.lock().unwrap())
100 .or(Err(StatusCode::UNKNOWN_ERROR))?;
101 writeln!(file, "\tPayload state {:?}", vm.payload_state())
102 .or(Err(StatusCode::UNKNOWN_ERROR))?;
103 writeln!(file, "\tProtected: {}", vm.protected).or(Err(StatusCode::UNKNOWN_ERROR))?;
104 writeln!(file, "\ttemporary_directory: {}", vm.temporary_directory.to_string_lossy())
105 .or(Err(StatusCode::UNKNOWN_ERROR))?;
106 writeln!(file, "\trequester_uid: {}", vm.requester_uid)
107 .or(Err(StatusCode::UNKNOWN_ERROR))?;
108 writeln!(file, "\trequester_sid: {}", vm.requester_sid)
109 .or(Err(StatusCode::UNKNOWN_ERROR))?;
110 writeln!(file, "\trequester_debug_pid: {}", vm.requester_debug_pid)
111 .or(Err(StatusCode::UNKNOWN_ERROR))?;
112 }
113 Ok(())
114 }
115}
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000116
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000117impl IVirtualizationService for VirtualizationService {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000118 /// Creates (but does not start) a new VM with the given configuration, assigning it the next
119 /// available CID.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000120 ///
121 /// Returns a binder `IVirtualMachine` object referring to it, as a handle for the client.
Andrew Walbranf8d94112021-09-07 11:45:36 +0000122 fn createVm(
Andrew Walbrana89fc132021-03-17 17:08:36 +0000123 &self,
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000124 config: &VirtualMachineConfig,
Andrew Walbrana89fc132021-03-17 17:08:36 +0000125 log_fd: Option<&ParcelFileDescriptor>,
126 ) -> binder::Result<Strong<dyn IVirtualMachine>> {
Jiyong Park753553b2021-07-12 21:21:09 +0900127 check_manage_access()?;
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000128 let state = &mut *self.state.lock().unwrap();
Jiyong Parkc2a49cc2021-10-15 00:02:12 +0900129 let mut log_fd = log_fd.map(clone_file).transpose()?;
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000130 let requester_uid = ThreadState::get_calling_uid();
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000131 let requester_sid = get_calling_sid()?;
Andrew Walbran02034492021-04-13 15:05:07 +0000132 let requester_debug_pid = ThreadState::get_calling_pid();
Jiyong Parkd50a0242021-09-16 21:00:14 +0900133 let cid = next_cid().or(Err(ExceptionCode::ILLEGAL_STATE))?;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000134
135 // Counter to generate unique IDs for temporary image files.
136 let mut next_temporary_image_id = 0;
137 // Files which are referred to from composite images. These must be mapped to the crosvm
138 // child process, and not closed before it is started.
139 let mut indirect_files = vec![];
140
141 // Make directory for temporary files.
142 let temporary_directory: PathBuf = format!("{}/{}", TEMPORARY_DIRECTORY, cid).into();
143 create_dir(&temporary_directory).map_err(|e| {
144 error!(
Andrew Walbran806f1542021-06-10 14:07:12 +0000145 "Failed to create temporary directory {:?} for VM files: {}",
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000146 temporary_directory, e
147 );
Andrew Walbran806f1542021-06-10 14:07:12 +0000148 new_binder_exception(
149 ExceptionCode::SERVICE_SPECIFIC,
150 format!(
151 "Failed to create temporary directory {:?} for VM files: {}",
152 temporary_directory, e
153 ),
154 )
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000155 })?;
156
Jiyong Parkc2a49cc2021-10-15 00:02:12 +0900157 // Disable console logging if debug level != full. Note that kernel anyway doesn't use the
158 // console output when debug level != full. So, users won't be able to see the kernel
159 // output even without this overriding. This is to silence output from the bootloader which
160 // doesn't understand the bootconfig parameters.
161 if let VirtualMachineConfig::AppConfig(config) = config {
162 if config.debugLevel != DebugLevel::FULL {
163 log_fd = None;
164 }
165 }
166
Jooyung Han21e9b922021-06-26 04:14:16 +0900167 let config = match config {
Jooyung Han35edb8f2021-07-01 16:17:16 +0900168 VirtualMachineConfig::AppConfig(config) => BorrowedOrOwned::Owned(
Jooyung Han9900f3d2021-07-06 10:27:54 +0900169 load_app_config(config, &temporary_directory).map_err(|e| {
170 error!("Failed to load app config from {}: {}", &config.configPath, e);
171 new_binder_exception(
172 ExceptionCode::SERVICE_SPECIFIC,
173 format!("Failed to load app config from {}: {}", &config.configPath, e),
174 )
175 })?,
Jooyung Han35edb8f2021-07-01 16:17:16 +0900176 ),
177 VirtualMachineConfig::RawConfig(config) => BorrowedOrOwned::Borrowed(config),
Jooyung Han21e9b922021-06-26 04:14:16 +0900178 };
Jooyung Han35edb8f2021-07-01 16:17:16 +0900179 let config = config.as_ref();
Jooyung Han21e9b922021-06-26 04:14:16 +0900180
Jooyung Han95884632021-07-06 22:27:54 +0900181 let zero_filler_path = temporary_directory.join("zero.img");
Andrew Walbranfbb39d22021-07-28 17:01:25 +0000182 write_zero_filler(&zero_filler_path).map_err(|e| {
Jooyung Han95884632021-07-06 22:27:54 +0900183 error!("Failed to make composite image: {}", e);
184 new_binder_exception(
185 ExceptionCode::SERVICE_SPECIFIC,
186 format!("Failed to make composite image: {}", e),
187 )
188 })?;
Jooyung Han95884632021-07-06 22:27:54 +0900189
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000190 // Assemble disk images if needed.
191 let disks = config
192 .disks
193 .iter()
194 .map(|disk| {
195 assemble_disk_image(
196 disk,
Jooyung Han95884632021-07-06 22:27:54 +0900197 &zero_filler_path,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000198 &temporary_directory,
199 &mut next_temporary_image_id,
200 &mut indirect_files,
201 )
202 })
203 .collect::<Result<Vec<DiskFile>, _>>()?;
204
205 // Actually start the VM.
206 let crosvm_config = CrosvmConfig {
Andrew Walbran02034492021-04-13 15:05:07 +0000207 cid,
Andrew Walbrand3a84182021-09-07 14:48:52 +0000208 bootloader: maybe_clone_file(&config.bootloader)?,
209 kernel: maybe_clone_file(&config.kernel)?,
210 initrd: maybe_clone_file(&config.initrd)?,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000211 disks,
212 params: config.params.to_owned(),
Andrew Walbrancc045902021-07-27 16:06:17 +0000213 protected: config.protectedVm,
214 memory_mib: config.memoryMib.try_into().ok().and_then(NonZeroU32::new),
Andrew Walbran02034492021-04-13 15:05:07 +0000215 log_fd,
Andrew Walbrand3a84182021-09-07 14:48:52 +0000216 indirect_files,
217 };
Andrew Walbranf8d94112021-09-07 11:45:36 +0000218 let instance = Arc::new(
219 VmInstance::new(
220 crosvm_config,
221 temporary_directory,
222 requester_uid,
223 requester_sid,
224 requester_debug_pid,
Andrew Walbran806f1542021-06-10 14:07:12 +0000225 )
Andrew Walbranf8d94112021-09-07 11:45:36 +0000226 .map_err(|e| {
227 error!("Failed to create VM with config {:?}: {}", config, e);
228 new_binder_exception(
229 ExceptionCode::SERVICE_SPECIFIC,
230 format!("Failed to create VM: {}", e),
231 )
232 })?,
233 );
Andrew Walbran320b5602021-03-04 16:11:12 +0000234 state.add_vm(Arc::downgrade(&instance));
235 Ok(VirtualMachine::create(instance))
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000236 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000237
Andrew Walbrandff3b942021-06-09 15:20:36 +0000238 /// Initialise an empty partition image of the given size to be used as a writable partition.
239 fn initializeWritablePartition(
240 &self,
241 image_fd: &ParcelFileDescriptor,
242 size: i64,
Jiyong Park9dd389e2021-08-23 20:42:59 +0900243 partition_type: PartitionType,
Andrew Walbrandff3b942021-06-09 15:20:36 +0000244 ) -> binder::Result<()> {
Jiyong Park753553b2021-07-12 21:21:09 +0900245 check_manage_access()?;
Andrew Walbrandfc953d2021-06-10 13:59:56 +0000246 let size = size.try_into().map_err(|e| {
Andrew Walbran806f1542021-06-10 14:07:12 +0000247 new_binder_exception(
248 ExceptionCode::ILLEGAL_ARGUMENT,
249 format!("Invalid size {}: {}", size, e),
250 )
Andrew Walbrandff3b942021-06-09 15:20:36 +0000251 })?;
Andrew Walbrandfc953d2021-06-10 13:59:56 +0000252 let image = clone_file(image_fd)?;
Andrew Walbrandff3b942021-06-09 15:20:36 +0000253
Jiyong Park9dd389e2021-08-23 20:42:59 +0900254 let mut part = QcowFile::new(image, size).map_err(|e| {
Andrew Walbran806f1542021-06-10 14:07:12 +0000255 new_binder_exception(
256 ExceptionCode::SERVICE_SPECIFIC,
257 format!("Failed to create QCOW2 image: {}", e),
258 )
Andrew Walbrandfc953d2021-06-10 13:59:56 +0000259 })?;
Andrew Walbrandff3b942021-06-09 15:20:36 +0000260
Jiyong Park9dd389e2021-08-23 20:42:59 +0900261 match partition_type {
262 PartitionType::RAW => Ok(()),
263 PartitionType::ANDROID_VM_INSTANCE => format_as_android_vm_instance(&mut part),
264 _ => Err(Error::new(
265 ErrorKind::Unsupported,
266 format!("Unsupported partition type {:?}", partition_type),
267 )),
268 }
269 .map_err(|e| {
270 new_binder_exception(
271 ExceptionCode::SERVICE_SPECIFIC,
272 format!("Failed to initialize partition as {:?}: {}", partition_type, e),
273 )
274 })?;
275
Andrew Walbrandff3b942021-06-09 15:20:36 +0000276 Ok(())
277 }
278
Jiyong Park0a248432021-08-20 23:32:39 +0900279 /// Creates or update the idsig file by digesting the input APK file.
280 fn createOrUpdateIdsigFile(
281 &self,
282 input_fd: &ParcelFileDescriptor,
283 idsig_fd: &ParcelFileDescriptor,
284 ) -> binder::Result<()> {
285 // TODO(b/193504400): do this only when (1) idsig_fd is empty or (2) the APK digest in
286 // idsig_fd is different from APK digest in input_fd
287
288 let mut input = clone_file(input_fd)?;
289 let mut sig = V4Signature::create(&mut input, 4096, &[], HashAlgorithm::SHA256).unwrap();
290
291 let mut output = clone_file(idsig_fd)?;
292 output.set_len(0).unwrap();
293 sig.write_into(&mut output).unwrap();
294 Ok(())
295 }
296
Andrew Walbran320b5602021-03-04 16:11:12 +0000297 /// Get a list of all currently running VMs. This method is only intended for debug purposes,
298 /// and as such is only permitted from the shell user.
299 fn debugListVms(&self) -> binder::Result<Vec<VirtualMachineDebugInfo>> {
Andrew Walbran806f1542021-06-10 14:07:12 +0000300 check_debug_access()?;
Andrew Walbran320b5602021-03-04 16:11:12 +0000301
302 let state = &mut *self.state.lock().unwrap();
303 let vms = state.vms();
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000304 let cids = vms
305 .into_iter()
306 .map(|vm| VirtualMachineDebugInfo {
307 cid: vm.cid as i32,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000308 temporaryDirectory: vm.temporary_directory.to_string_lossy().to_string(),
Andrew Walbran1ef19ae2021-04-07 11:31:57 +0000309 requesterUid: vm.requester_uid as i32,
310 requesterSid: vm.requester_sid.clone(),
Andrew Walbran02034492021-04-13 15:05:07 +0000311 requesterPid: vm.requester_debug_pid,
Andrew Walbran6b650662021-09-07 13:13:23 +0000312 state: get_state(&vm),
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000313 })
314 .collect();
Andrew Walbran320b5602021-03-04 16:11:12 +0000315 Ok(cids)
316 }
David Brazdil3c2ddef2021-03-18 13:09:57 +0000317
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000318 /// Hold a strong reference to a VM in VirtualizationService. This method is only intended for
319 /// debug purposes, and as such is only permitted from the shell user.
Andrei Homescu1415c132021-03-24 02:39:55 +0000320 fn debugHoldVmRef(&self, vmref: &Strong<dyn IVirtualMachine>) -> binder::Result<()> {
Andrew Walbran806f1542021-06-10 14:07:12 +0000321 check_debug_access()?;
David Brazdil3c2ddef2021-03-18 13:09:57 +0000322
David Brazdil3c2ddef2021-03-18 13:09:57 +0000323 let state = &mut *self.state.lock().unwrap();
Andrei Homescu1415c132021-03-24 02:39:55 +0000324 state.debug_hold_vm(vmref.clone());
David Brazdil3c2ddef2021-03-18 13:09:57 +0000325 Ok(())
326 }
327
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000328 /// Drop reference to a VM that is being held by VirtualizationService. Returns the reference if
329 /// the VM was found and None otherwise. This method is only intended for debug purposes, and as
330 /// such is only permitted from the shell user.
David Brazdil3c2ddef2021-03-18 13:09:57 +0000331 fn debugDropVmRef(&self, cid: i32) -> binder::Result<Option<Strong<dyn IVirtualMachine>>> {
Andrew Walbran806f1542021-06-10 14:07:12 +0000332 check_debug_access()?;
David Brazdil3c2ddef2021-03-18 13:09:57 +0000333
334 let state = &mut *self.state.lock().unwrap();
335 Ok(state.debug_drop_vm(cid))
336 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000337}
338
Jiyong Park8611a6c2021-07-09 18:17:44 +0900339impl VirtualizationService {
340 pub fn init() -> VirtualizationService {
341 let service = VirtualizationService::default();
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900342
343 // server for payload output
Jiyong Park8611a6c2021-07-09 18:17:44 +0900344 let state = service.state.clone(); // reference to state (not the state itself) is copied
345 std::thread::spawn(move || {
Inseob Kim7f61fe72021-08-20 20:50:47 +0900346 handle_stream_connection_from_vm(state).unwrap();
Jiyong Park8611a6c2021-07-09 18:17:44 +0900347 });
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900348
349 // binder server for vm
Inseob Kimc7d28c72021-10-25 14:28:10 +0000350 let mut state = service.state.clone(); // reference to state (not the state itself) is copied
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900351 std::thread::spawn(move || {
Inseob Kimc7d28c72021-10-25 14:28:10 +0000352 let state_ptr = &mut state as *mut _ as *mut raw::c_void;
353
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900354 debug!("virtual machine service is starting as an RPC service.");
Inseob Kimc7d28c72021-10-25 14:28:10 +0000355 // SAFETY: factory function is only ever called by RunRpcServerWithFactory, within the
356 // lifetime of the state, with context taking the pointer value above (so a properly
357 // aligned non-null pointer to an initialized instance).
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900358 let retval = unsafe {
Inseob Kimc7d28c72021-10-25 14:28:10 +0000359 binder_rpc_unstable_bindgen::RunRpcServerWithFactory(
360 Some(VirtualMachineService::factory),
361 state_ptr,
Inseob Kimd0587562021-09-01 21:27:32 +0900362 VM_BINDER_SERVICE_PORT as u32,
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900363 )
364 };
365 if retval {
366 debug!("RPC server has shut down gracefully");
367 } else {
368 bail!("Premature termination of RPC server");
369 }
370
371 Ok(retval)
372 });
Jiyong Park8611a6c2021-07-09 18:17:44 +0900373 service
374 }
375}
376
Andrew Walbran6b650662021-09-07 13:13:23 +0000377/// Waits for incoming connections from VM. If a new connection is made, stores the stream in the
378/// corresponding `VmInstance`.
Inseob Kim7f61fe72021-08-20 20:50:47 +0900379fn handle_stream_connection_from_vm(state: Arc<Mutex<State>>) -> Result<()> {
Inseob Kimd0587562021-09-01 21:27:32 +0900380 let listener =
381 VsockListener::bind_with_cid_port(VMADDR_CID_HOST, VM_STREAM_SERVICE_PORT as u32)?;
Jiyong Park8611a6c2021-07-09 18:17:44 +0900382 for stream in listener.incoming() {
383 let stream = match stream {
384 Err(e) => {
385 warn!("invalid incoming connection: {}", e);
386 continue;
387 }
388 Ok(s) => s,
389 };
390 if let Ok(SockAddr::Vsock(addr)) = stream.peer_addr() {
391 let cid = addr.cid();
392 let port = addr.port();
Inseob Kim7f61fe72021-08-20 20:50:47 +0900393 info!("payload stream connected from cid={}, port={}", cid, port);
Jiyong Park8611a6c2021-07-09 18:17:44 +0900394 if let Some(vm) = state.lock().unwrap().get_vm(cid) {
Chris Wailes8bbb8932021-09-10 14:14:19 -0700395 *vm.stream.lock().unwrap() = Some(stream);
Inseob Kim7f61fe72021-08-20 20:50:47 +0900396 } else {
397 error!("connection from cid={} is not from a guest VM", cid);
Jiyong Park8611a6c2021-07-09 18:17:44 +0900398 }
399 }
400 }
401 Ok(())
402}
403
Andrew Walbranfbb39d22021-07-28 17:01:25 +0000404fn write_zero_filler(zero_filler_path: &Path) -> Result<()> {
Jooyung Han95884632021-07-06 22:27:54 +0900405 let file = OpenOptions::new()
406 .create_new(true)
407 .read(true)
408 .write(true)
409 .open(zero_filler_path)
410 .with_context(|| "Failed to create zero.img")?;
411 file.set_len(ZERO_FILLER_SIZE)?;
Andrew Walbranfbb39d22021-07-28 17:01:25 +0000412 Ok(())
Jooyung Han95884632021-07-06 22:27:54 +0900413}
414
Jiyong Park9dd389e2021-08-23 20:42:59 +0900415fn format_as_android_vm_instance(part: &mut dyn Write) -> std::io::Result<()> {
416 part.write_all(ANDROID_VM_INSTANCE_MAGIC.as_bytes())?;
417 part.write_all(&ANDROID_VM_INSTANCE_VERSION.to_le_bytes())?;
418 part.flush()
419}
420
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000421/// Given the configuration for a disk image, assembles the `DiskFile` to pass to crosvm.
422///
423/// This may involve assembling a composite disk from a set of partition images.
424fn assemble_disk_image(
425 disk: &DiskImage,
Jooyung Han95884632021-07-06 22:27:54 +0900426 zero_filler_path: &Path,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000427 temporary_directory: &Path,
428 next_temporary_image_id: &mut u64,
429 indirect_files: &mut Vec<File>,
Andrew Walbran806f1542021-06-10 14:07:12 +0000430) -> Result<DiskFile, Status> {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000431 let image = if !disk.partitions.is_empty() {
432 if disk.image.is_some() {
433 warn!("DiskImage {:?} contains both image and partitions.", disk);
Andrew Walbran806f1542021-06-10 14:07:12 +0000434 return Err(new_binder_exception(
435 ExceptionCode::ILLEGAL_ARGUMENT,
436 "DiskImage contains both image and partitions.",
437 ));
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000438 }
439
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000440 let composite_image_filenames =
441 make_composite_image_filenames(temporary_directory, next_temporary_image_id);
442 let (image, partition_files) = make_composite_image(
443 &disk.partitions,
Jooyung Han95884632021-07-06 22:27:54 +0900444 zero_filler_path,
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000445 &composite_image_filenames.composite,
446 &composite_image_filenames.header,
447 &composite_image_filenames.footer,
448 )
449 .map_err(|e| {
450 error!("Failed to make composite image with config {:?}: {}", disk, e);
451 new_binder_exception(
452 ExceptionCode::SERVICE_SPECIFIC,
453 format!("Failed to make composite image: {}", e),
454 )
455 })?;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000456
457 // Pass the file descriptors for the various partition files to crosvm when it
458 // is run.
459 indirect_files.extend(partition_files);
460
461 image
462 } else if let Some(image) = &disk.image {
463 clone_file(image)?
464 } else {
465 warn!("DiskImage {:?} didn't contain image or partitions.", disk);
Andrew Walbran806f1542021-06-10 14:07:12 +0000466 return Err(new_binder_exception(
467 ExceptionCode::ILLEGAL_ARGUMENT,
468 "DiskImage didn't contain image or partitions.",
469 ));
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000470 };
471
472 Ok(DiskFile { image, writable: disk.writable })
473}
474
Jooyung Han21e9b922021-06-26 04:14:16 +0900475fn load_app_config(
476 config: &VirtualMachineAppConfig,
477 temporary_directory: &Path,
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900478) -> Result<VirtualMachineRawConfig> {
Andrew Walbrancc0db522021-07-12 17:03:42 +0000479 let apk_file = clone_file(config.apk.as_ref().unwrap())?;
480 let idsig_file = clone_file(config.idsig.as_ref().unwrap())?;
Jiyong Park8d081812021-07-23 17:45:04 +0900481 let instance_file = clone_file(config.instanceImage.as_ref().unwrap())?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900482 let config_path = &config.configPath;
483
Andrew Walbrancc0db522021-07-12 17:03:42 +0000484 let mut apk_zip = ZipArchive::new(&apk_file)?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900485 let config_file = apk_zip.by_name(config_path)?;
486 let vm_payload_config: VmPayloadConfig = serde_json::from_reader(config_file)?;
487
488 let os_name = &vm_payload_config.os.name;
Andrew Walbrancc0db522021-07-12 17:03:42 +0000489
Jooyung Han35edb8f2021-07-01 16:17:16 +0900490 // For now, the only supported "os" value is "microdroid"
491 if os_name != "microdroid" {
Andrew Walbrancc0db522021-07-12 17:03:42 +0000492 bail!("Unknown OS \"{}\"", os_name);
Jooyung Han35edb8f2021-07-01 16:17:16 +0900493 }
Andrew Walbrancc0db522021-07-12 17:03:42 +0000494
495 // It is safe to construct a filename based on the os_name because we've already checked that it
496 // is one of the allowed values.
Jooyung Han21e9b922021-06-26 04:14:16 +0900497 let vm_config_path = PathBuf::from(format!("/apex/com.android.virt/etc/{}.json", os_name));
498 let vm_config_file = File::open(vm_config_path)?;
Andrew Walbrancc0db522021-07-12 17:03:42 +0000499 let mut vm_config = VmConfig::load(&vm_config_file)?.to_parcelable()?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900500
Andrew Walbrancc045902021-07-27 16:06:17 +0000501 if config.memoryMib > 0 {
502 vm_config.memoryMib = config.memoryMib;
Andrew Walbran45bcb0c2021-07-14 15:02:06 +0000503 }
504
Andrew Walbrancc0db522021-07-12 17:03:42 +0000505 // Microdroid requires an additional payload disk image and the bootconfig partition.
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900506 if os_name == "microdroid" {
Andrew Walbrancc0db522021-07-12 17:03:42 +0000507 add_microdroid_images(
508 config,
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900509 temporary_directory,
Andrew Walbrancc0db522021-07-12 17:03:42 +0000510 apk_file,
511 idsig_file,
Jiyong Park8d081812021-07-23 17:45:04 +0900512 instance_file,
Jooyung Han5dc42172021-10-05 16:43:47 +0900513 &vm_payload_config,
Andrew Walbrancc0db522021-07-12 17:03:42 +0000514 &mut vm_config,
515 )?;
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900516 }
Jooyung Han21e9b922021-06-26 04:14:16 +0900517
Andrew Walbrancc0db522021-07-12 17:03:42 +0000518 Ok(vm_config)
Jooyung Han21e9b922021-06-26 04:14:16 +0900519}
520
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000521/// Generates a unique filename to use for a composite disk image.
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000522fn make_composite_image_filenames(
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000523 temporary_directory: &Path,
524 next_temporary_image_id: &mut u64,
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000525) -> CompositeImageFilenames {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000526 let id = *next_temporary_image_id;
527 *next_temporary_image_id += 1;
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000528 CompositeImageFilenames {
529 composite: temporary_directory.join(format!("composite-{}.img", id)),
530 header: temporary_directory.join(format!("composite-{}-header.img", id)),
531 footer: temporary_directory.join(format!("composite-{}-footer.img", id)),
532 }
533}
534
535/// Filenames for a composite disk image, including header and footer partitions.
536#[derive(Clone, Debug, Eq, PartialEq)]
537struct CompositeImageFilenames {
538 /// The composite disk image itself.
539 composite: PathBuf,
540 /// The header partition image.
541 header: PathBuf,
542 /// The footer partition image.
543 footer: PathBuf,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000544}
545
546/// Gets the calling SID of the current Binder thread.
Andrew Walbran806f1542021-06-10 14:07:12 +0000547fn get_calling_sid() -> Result<String, Status> {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000548 ThreadState::with_calling_sid(|sid| {
549 if let Some(sid) = sid {
550 match sid.to_str() {
551 Ok(sid) => Ok(sid.to_owned()),
552 Err(e) => {
Andrew Walbran806f1542021-06-10 14:07:12 +0000553 error!("SID was not valid UTF-8: {}", e);
554 Err(new_binder_exception(
555 ExceptionCode::ILLEGAL_ARGUMENT,
556 format!("SID was not valid UTF-8: {}", e),
557 ))
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000558 }
559 }
560 } else {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000561 error!("Missing SID on createVm");
562 Err(new_binder_exception(ExceptionCode::SECURITY, "Missing SID on createVm"))
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000563 }
564 })
565}
566
Jiyong Park753553b2021-07-12 21:21:09 +0900567/// Checks whether the caller has a specific permission
568fn check_permission(perm: &str) -> binder::Result<()> {
569 let calling_pid = ThreadState::get_calling_pid();
570 let calling_uid = ThreadState::get_calling_uid();
571 // Root can do anything
572 if calling_uid == 0 {
573 return Ok(());
574 }
575 let perm_svc: Strong<dyn IPermissionController::IPermissionController> =
576 binder::get_interface("permission")?;
577 if perm_svc.checkPermission(perm, calling_pid, calling_uid as i32)? {
Andrew Walbran806f1542021-06-10 14:07:12 +0000578 Ok(())
579 } else {
Jiyong Park753553b2021-07-12 21:21:09 +0900580 Err(new_binder_exception(
581 ExceptionCode::SECURITY,
582 format!("does not have the {} permission", perm),
583 ))
Andrew Walbran806f1542021-06-10 14:07:12 +0000584 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000585}
586
Jiyong Park753553b2021-07-12 21:21:09 +0900587/// Check whether the caller of the current Binder method is allowed to call debug methods.
588fn check_debug_access() -> binder::Result<()> {
589 check_permission("android.permission.DEBUG_VIRTUAL_MACHINE")
590}
591
592/// Check whether the caller of the current Binder method is allowed to manage VMs
593fn check_manage_access() -> binder::Result<()> {
594 check_permission("android.permission.MANAGE_VIRTUAL_MACHINE")
595}
596
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000597/// Implementation of the AIDL `IVirtualMachine` interface. Used as a handle to a VM.
598#[derive(Debug)]
599struct VirtualMachine {
600 instance: Arc<VmInstance>,
Alan Stokes0cc59ee2021-09-24 11:20:34 +0100601 /// Keeps our service process running as long as this VM instance exists.
602 lazy_service_guard: LazyServiceGuard,
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000603}
604
605impl VirtualMachine {
606 fn create(instance: Arc<VmInstance>) -> Strong<dyn IVirtualMachine> {
Alan Stokes0cc59ee2021-09-24 11:20:34 +0100607 let binder = VirtualMachine { instance, lazy_service_guard: Default::default() };
Andrew Walbran4de28782021-04-13 14:51:43 +0000608 BnVirtualMachine::new_binder(binder, BinderFeatures::default())
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000609 }
610}
611
612impl Interface for VirtualMachine {}
613
614impl IVirtualMachine for VirtualMachine {
615 fn getCid(&self) -> binder::Result<i32> {
Jiyong Park753553b2021-07-12 21:21:09 +0900616 // Don't check permission. The owner of the VM might have passed this binder object to
617 // others.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000618 Ok(self.instance.cid as i32)
619 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000620
Andrew Walbran6b650662021-09-07 13:13:23 +0000621 fn getState(&self) -> binder::Result<VirtualMachineState> {
Jiyong Park753553b2021-07-12 21:21:09 +0900622 // Don't check permission. The owner of the VM might have passed this binder object to
623 // others.
Andrew Walbran6b650662021-09-07 13:13:23 +0000624 Ok(get_state(&self.instance))
Andrew Walbrandae07162021-03-12 17:05:20 +0000625 }
626
627 fn registerCallback(
628 &self,
629 callback: &Strong<dyn IVirtualMachineCallback>,
630 ) -> binder::Result<()> {
Jiyong Park753553b2021-07-12 21:21:09 +0900631 // Don't check permission. The owner of the VM might have passed this binder object to
632 // others.
633 //
Andrew Walbrandae07162021-03-12 17:05:20 +0000634 // TODO: Should this give an error if the VM is already dead?
635 self.instance.callbacks.add(callback.clone());
636 Ok(())
637 }
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000638
Andrew Walbranf8d94112021-09-07 11:45:36 +0000639 fn start(&self) -> binder::Result<()> {
640 self.instance.start().map_err(|e| {
641 error!("Error starting VM with CID {}: {:?}", self.instance.cid, e);
642 new_binder_exception(ExceptionCode::SERVICE_SPECIFIC, e.to_string())
643 })
644 }
645
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000646 fn connectVsock(&self, port: i32) -> binder::Result<ParcelFileDescriptor> {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000647 if !matches!(&*self.instance.vm_state.lock().unwrap(), VmState::Running { .. }) {
648 return Err(new_binder_exception(ExceptionCode::SERVICE_SPECIFIC, "VM is not running"));
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000649 }
650 let stream =
651 VsockStream::connect_with_cid_port(self.instance.cid, port as u32).map_err(|e| {
652 new_binder_exception(
653 ExceptionCode::SERVICE_SPECIFIC,
654 format!("Failed to connect: {}", e),
655 )
656 })?;
657 Ok(vsock_stream_to_pfd(stream))
658 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000659}
660
661impl Drop for VirtualMachine {
662 fn drop(&mut self) {
663 debug!("Dropping {:?}", self);
664 self.instance.kill();
665 }
666}
667
668/// A set of Binders to be called back in response to various events on the VM, such as when it
669/// dies.
670#[derive(Debug, Default)]
671pub struct VirtualMachineCallbacks(Mutex<Vec<Strong<dyn IVirtualMachineCallback>>>);
672
673impl VirtualMachineCallbacks {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900674 /// Call all registered callbacks to notify that the payload has started.
Inseob Kim7f61fe72021-08-20 20:50:47 +0900675 pub fn notify_payload_started(&self, cid: Cid, stream: Option<VsockStream>) {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900676 let callbacks = &*self.0.lock().unwrap();
Inseob Kim7f61fe72021-08-20 20:50:47 +0900677 let pfd = stream.map(vsock_stream_to_pfd);
Jiyong Park8611a6c2021-07-09 18:17:44 +0900678 for callback in callbacks {
Inseob Kim7f61fe72021-08-20 20:50:47 +0900679 if let Err(e) = callback.onPayloadStarted(cid as i32, pfd.as_ref()) {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900680 error!("Error notifying payload start event from VM CID {}: {}", cid, e);
681 }
682 }
683 }
684
Inseob Kim14cb8692021-08-31 21:50:39 +0900685 /// Call all registered callbacks to notify that the payload is ready to serve.
686 pub fn notify_payload_ready(&self, cid: Cid) {
687 let callbacks = &*self.0.lock().unwrap();
688 for callback in callbacks {
689 if let Err(e) = callback.onPayloadReady(cid as i32) {
690 error!("Error notifying payload ready event from VM CID {}: {}", cid, e);
691 }
692 }
693 }
694
Inseob Kim2444af92021-08-31 01:22:50 +0900695 /// Call all registered callbacks to notify that the payload has finished.
696 pub fn notify_payload_finished(&self, cid: Cid, exit_code: i32) {
697 let callbacks = &*self.0.lock().unwrap();
698 for callback in callbacks {
699 if let Err(e) = callback.onPayloadFinished(cid as i32, exit_code) {
700 error!("Error notifying payload finish event from VM CID {}: {}", cid, e);
701 }
702 }
703 }
704
Andrew Walbrandae07162021-03-12 17:05:20 +0000705 /// Call all registered callbacks to say that the VM has died.
706 pub fn callback_on_died(&self, cid: Cid) {
707 let callbacks = &*self.0.lock().unwrap();
708 for callback in callbacks {
709 if let Err(e) = callback.onDied(cid as i32) {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900710 error!("Error notifying exit of VM CID {}: {}", cid, e);
Andrew Walbrandae07162021-03-12 17:05:20 +0000711 }
712 }
713 }
714
715 /// Add a new callback to the set.
716 fn add(&self, callback: Strong<dyn IVirtualMachineCallback>) {
717 self.0.lock().unwrap().push(callback);
718 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000719}
720
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000721/// The mutable state of the VirtualizationService. There should only be one instance of this
722/// struct.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000723#[derive(Debug)]
724struct State {
Andrew Walbran320b5602021-03-04 16:11:12 +0000725 /// The VMs which have been started. When VMs are started a weak reference is added to this list
726 /// while a strong reference is returned to the caller over Binder. Once all copies of the
727 /// Binder client are dropped the weak reference here will become invalid, and will be removed
728 /// from the list opportunistically the next time `add_vm` is called.
729 vms: Vec<Weak<VmInstance>>,
David Brazdil3c2ddef2021-03-18 13:09:57 +0000730
731 /// Vector of strong VM references held on behalf of users that cannot hold them themselves.
732 /// This is only used for debugging purposes.
733 debug_held_vms: Vec<Strong<dyn IVirtualMachine>>,
Andrew Walbran320b5602021-03-04 16:11:12 +0000734}
735
736impl State {
Andrew Walbrandae07162021-03-12 17:05:20 +0000737 /// Get a list of VMs which still have Binder references to them.
Andrew Walbran320b5602021-03-04 16:11:12 +0000738 fn vms(&self) -> Vec<Arc<VmInstance>> {
739 // Attempt to upgrade the weak pointers to strong pointers.
740 self.vms.iter().filter_map(Weak::upgrade).collect()
741 }
742
743 /// Add a new VM to the list.
744 fn add_vm(&mut self, vm: Weak<VmInstance>) {
745 // Garbage collect any entries from the stored list which no longer exist.
746 self.vms.retain(|vm| vm.strong_count() > 0);
747
748 // Actually add the new VM.
749 self.vms.push(vm);
750 }
David Brazdil3c2ddef2021-03-18 13:09:57 +0000751
Jiyong Park8611a6c2021-07-09 18:17:44 +0900752 /// Get a VM that corresponds to the given cid
753 fn get_vm(&self, cid: Cid) -> Option<Arc<VmInstance>> {
754 self.vms().into_iter().find(|vm| vm.cid == cid)
755 }
756
David Brazdil3c2ddef2021-03-18 13:09:57 +0000757 /// Store a strong VM reference.
758 fn debug_hold_vm(&mut self, vm: Strong<dyn IVirtualMachine>) {
759 self.debug_held_vms.push(vm);
760 }
761
762 /// Retrieve and remove a strong VM reference.
763 fn debug_drop_vm(&mut self, cid: i32) -> Option<Strong<dyn IVirtualMachine>> {
764 let pos = self.debug_held_vms.iter().position(|vm| vm.getCid() == Ok(cid))?;
Alan Stokes7e54e292021-09-09 11:37:56 +0100765 let vm = self.debug_held_vms.swap_remove(pos);
Alan Stokes7e54e292021-09-09 11:37:56 +0100766 Some(vm)
David Brazdil3c2ddef2021-03-18 13:09:57 +0000767 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000768}
769
770impl Default for State {
771 fn default() -> Self {
Jiyong Parkd50a0242021-09-16 21:00:14 +0900772 State { vms: vec![], debug_held_vms: vec![] }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000773 }
774}
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000775
Jiyong Parkd50a0242021-09-16 21:00:14 +0900776/// Get the next available CID, or an error if we have run out. The last CID used is stored in
777/// a system property so that restart of virtualizationservice doesn't reuse CID while the host
778/// Android is up.
779fn next_cid() -> Result<Cid> {
780 let next = if let Ok(val) = system_properties::read(SYSPROP_LAST_CID) {
781 if let Ok(num) = val.parse::<u32>() {
782 num.checked_add(1).ok_or_else(|| anyhow!("run out of CID"))?
783 } else {
784 error!("Invalid last CID {}. Using {}", &val, FIRST_GUEST_CID);
785 FIRST_GUEST_CID
786 }
787 } else {
788 // First VM since the boot
789 FIRST_GUEST_CID
790 };
791 // Persist the last value for next use
792 let str_val = format!("{}", next);
793 system_properties::write(SYSPROP_LAST_CID, &str_val)?;
794 Ok(next)
795}
796
Andrew Walbran6b650662021-09-07 13:13:23 +0000797/// Gets the `VirtualMachineState` of the given `VmInstance`.
798fn get_state(instance: &VmInstance) -> VirtualMachineState {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000799 match &*instance.vm_state.lock().unwrap() {
800 VmState::NotStarted { .. } => VirtualMachineState::NOT_STARTED,
801 VmState::Running { .. } => match instance.payload_state() {
Andrew Walbran6b650662021-09-07 13:13:23 +0000802 PayloadState::Starting => VirtualMachineState::STARTING,
803 PayloadState::Started => VirtualMachineState::STARTED,
804 PayloadState::Ready => VirtualMachineState::READY,
805 PayloadState::Finished => VirtualMachineState::FINISHED,
Andrew Walbranf8d94112021-09-07 11:45:36 +0000806 },
807 VmState::Dead => VirtualMachineState::DEAD,
808 VmState::Failed => VirtualMachineState::DEAD,
Andrew Walbran6b650662021-09-07 13:13:23 +0000809 }
810}
811
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000812/// Converts a `&ParcelFileDescriptor` to a `File` by cloning the file.
Andrew Walbran806f1542021-06-10 14:07:12 +0000813fn clone_file(file: &ParcelFileDescriptor) -> Result<File, Status> {
814 file.as_ref().try_clone().map_err(|e| {
815 new_binder_exception(
816 ExceptionCode::BAD_PARCELABLE,
817 format!("Failed to clone File from ParcelFileDescriptor: {}", e),
818 )
819 })
820}
821
Andrew Walbrand3a84182021-09-07 14:48:52 +0000822/// Converts an `&Option<ParcelFileDescriptor>` to an `Option<File>` by cloning the file.
823fn maybe_clone_file(file: &Option<ParcelFileDescriptor>) -> Result<Option<File>, Status> {
824 file.as_ref().map(clone_file).transpose()
825}
826
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000827/// Converts a `VsockStream` to a `ParcelFileDescriptor`.
828fn vsock_stream_to_pfd(stream: VsockStream) -> ParcelFileDescriptor {
829 // SAFETY: ownership is transferred from stream to f
830 let f = unsafe { File::from_raw_fd(stream.into_raw_fd()) };
831 ParcelFileDescriptor::new(f)
832}
833
Jooyung Han35edb8f2021-07-01 16:17:16 +0900834/// Simple utility for referencing Borrowed or Owned. Similar to std::borrow::Cow, but
835/// it doesn't require that T implements Clone.
836enum BorrowedOrOwned<'a, T> {
837 Borrowed(&'a T),
838 Owned(T),
839}
840
841impl<'a, T> AsRef<T> for BorrowedOrOwned<'a, T> {
842 fn as_ref(&self) -> &T {
843 match self {
844 Self::Borrowed(b) => b,
Chris Wailes68c39f82021-07-27 16:03:44 -0700845 Self::Owned(o) => o,
Jooyung Han35edb8f2021-07-01 16:17:16 +0900846 }
847 }
848}
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900849
850/// Implementation of `IVirtualMachineService`, the entry point of the AIDL service.
851#[derive(Debug, Default)]
852struct VirtualMachineService {
853 state: Arc<Mutex<State>>,
Inseob Kimc7d28c72021-10-25 14:28:10 +0000854 cid: Cid,
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900855}
856
857impl Interface for VirtualMachineService {}
858
859impl IVirtualMachineService for VirtualMachineService {
Inseob Kimc7d28c72021-10-25 14:28:10 +0000860 fn notifyPayloadStarted(&self) -> binder::Result<()> {
861 let cid = self.cid;
Inseob Kim7f61fe72021-08-20 20:50:47 +0900862 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
863 info!("VM having CID {} started payload", cid);
Andrew Walbran6b650662021-09-07 13:13:23 +0000864 vm.update_payload_state(PayloadState::Started)
865 .map_err(|e| new_binder_exception(ExceptionCode::ILLEGAL_STATE, e.to_string()))?;
Inseob Kim7f61fe72021-08-20 20:50:47 +0900866 let stream = vm.stream.lock().unwrap().take();
867 vm.callbacks.notify_payload_started(cid, stream);
868 Ok(())
869 } else {
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900870 error!("notifyPayloadStarted is called from an unknown cid {}", cid);
Inseob Kim7f61fe72021-08-20 20:50:47 +0900871 Err(new_binder_exception(
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900872 ExceptionCode::SERVICE_SPECIFIC,
873 format!("cannot find a VM with cid {}", cid),
Inseob Kim7f61fe72021-08-20 20:50:47 +0900874 ))
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900875 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900876 }
Inseob Kim2444af92021-08-31 01:22:50 +0900877
Inseob Kimc7d28c72021-10-25 14:28:10 +0000878 fn notifyPayloadReady(&self) -> binder::Result<()> {
879 let cid = self.cid;
Inseob Kim14cb8692021-08-31 21:50:39 +0900880 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
881 info!("VM having CID {} payload is ready", cid);
Andrew Walbran6b650662021-09-07 13:13:23 +0000882 vm.update_payload_state(PayloadState::Ready)
883 .map_err(|e| new_binder_exception(ExceptionCode::ILLEGAL_STATE, e.to_string()))?;
Inseob Kim14cb8692021-08-31 21:50:39 +0900884 vm.callbacks.notify_payload_ready(cid);
885 Ok(())
886 } else {
887 error!("notifyPayloadReady 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 }
894
Inseob Kimc7d28c72021-10-25 14:28:10 +0000895 fn notifyPayloadFinished(&self, exit_code: i32) -> binder::Result<()> {
896 let cid = self.cid;
Inseob Kim2444af92021-08-31 01:22:50 +0900897 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
898 info!("VM having CID {} finished payload", cid);
Andrew Walbran6b650662021-09-07 13:13:23 +0000899 vm.update_payload_state(PayloadState::Finished)
900 .map_err(|e| new_binder_exception(ExceptionCode::ILLEGAL_STATE, e.to_string()))?;
Inseob Kim2444af92021-08-31 01:22:50 +0900901 vm.callbacks.notify_payload_finished(cid, exit_code);
902 Ok(())
903 } else {
904 error!("notifyPayloadFinished is called from an unknown cid {}", cid);
905 Err(new_binder_exception(
906 ExceptionCode::SERVICE_SPECIFIC,
907 format!("cannot find a VM with cid {}", cid),
908 ))
909 }
910 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900911}
912
913impl VirtualMachineService {
Inseob Kimc7d28c72021-10-25 14:28:10 +0000914 // SAFETY: Service ownership is held by state, and the binder objects are threadsafe.
915 pub unsafe extern "C" fn factory(
916 cid: Cid,
917 context: *mut raw::c_void,
918 ) -> *mut binder_rpc_unstable_bindgen::AIBinder {
919 let state_ptr = context as *mut Arc<Mutex<State>>;
920 let state = state_ptr.as_ref().unwrap();
921 if let Some(vm) = state.lock().unwrap().get_vm(cid) {
922 let mut vm_service = vm.vm_service.lock().unwrap();
923 let service = vm_service.get_or_insert_with(|| Self::new_binder(state.clone(), cid));
924 service.as_binder().as_native_mut() as *mut binder_rpc_unstable_bindgen::AIBinder
925 } else {
926 error!("connection from cid={} is not from a guest VM", cid);
927 null_mut()
928 }
929 }
930
931 fn new_binder(state: Arc<Mutex<State>>, cid: Cid) -> Strong<dyn IVirtualMachineService> {
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900932 BnVirtualMachineService::new_binder(
Inseob Kimc7d28c72021-10-25 14:28:10 +0000933 VirtualMachineService { state, cid },
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900934 BinderFeatures::default(),
935 )
936 }
937}