blob: cc8d8a323f2602cdf9d465d420639b46801d1caa [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};
Jiyong Park029977d2021-11-24 21:56:49 +090021use crate::selinux::{SeContext, getfilecon};
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 Walbranc92d35f2022-01-12 12:45:19 +000024 DeathReason::DeathReason,
Andrew Walbran6b650662021-09-07 13:13:23 +000025 DiskImage::DiskImage,
Alan Stokes0cc59ee2021-09-24 11:20:34 +010026 IVirtualMachine::{BnVirtualMachine, IVirtualMachine},
Andrew Walbran6b650662021-09-07 13:13:23 +000027 IVirtualMachineCallback::IVirtualMachineCallback,
28 IVirtualizationService::IVirtualizationService,
Jiyong Park029977d2021-11-24 21:56:49 +090029 Partition::Partition,
Andrew Walbran6b650662021-09-07 13:13:23 +000030 PartitionType::PartitionType,
Jooyung Han21e9b922021-06-26 04:14:16 +090031 VirtualMachineAppConfig::VirtualMachineAppConfig,
32 VirtualMachineConfig::VirtualMachineConfig,
Andrew Walbran6b650662021-09-07 13:13:23 +000033 VirtualMachineDebugInfo::VirtualMachineDebugInfo,
Jooyung Han21e9b922021-06-26 04:14:16 +090034 VirtualMachineRawConfig::VirtualMachineRawConfig,
Andrew Walbran6b650662021-09-07 13:13:23 +000035 VirtualMachineState::VirtualMachineState,
Jooyung Han21e9b922021-06-26 04:14:16 +090036};
Andrew Walbranf6bf6862021-05-21 12:41:13 +000037use android_system_virtualizationservice::binder::{
Andrew Walbran0fd0ff02022-07-29 15:59:17 +000038 self, BinderFeatures, ExceptionCode, Interface, ParcelFileDescriptor, SpIBinder, Status,
39 StatusCode, Strong, ThreadState,
Andrew Walbrana89fc132021-03-17 17:08:36 +000040};
Alan Stokes0cc59ee2021-09-24 11:20:34 +010041use android_system_virtualmachineservice::aidl::android::system::virtualmachineservice::{
42 IVirtualMachineService::{
43 BnVirtualMachineService, IVirtualMachineService, VM_BINDER_SERVICE_PORT,
Shikha Panwar7afc1392022-03-24 08:54:43 +000044 VM_STREAM_SERVICE_PORT, VM_TOMBSTONES_SERVICE_PORT,
Alan Stokes0cc59ee2021-09-24 11:20:34 +010045 },
Inseob Kim1b95f2e2021-08-19 13:17:40 +090046};
Jiyong Parkd50a0242021-09-16 21:00:14 +090047use anyhow::{anyhow, bail, Context, Result};
Andrew Walbran0fd0ff02022-07-29 15:59:17 +000048use binder_common::{lazy_service::LazyServiceGuard, new_binder_exception, rpc_server::run_rpc_server_with_factory};
Andrew Walbrandfc953d2021-06-10 13:59:56 +000049use disk::QcowFile;
Alan Stokes0cc59ee2021-09-24 11:20:34 +010050use idsig::{HashAlgorithm, V4Signature};
Andrew Walbranf6d600f2022-02-03 14:42:39 +000051use log::{debug, error, info, warn, trace};
Andrew Walbrancc0db522021-07-12 17:03:42 +000052use microdroid_payload_config::VmPayloadConfig;
Jiyong Parkd50a0242021-09-16 21:00:14 +090053use rustutils::system_properties;
Jiyong Parkdcf17412022-02-08 15:07:23 +090054use semver::VersionReq;
Treehugger Robot3ffa8322021-11-22 12:06:47 +000055use statslog_virtualization_rust::vm_creation_requested::{stats_write, Hypervisor};
Andrew Walbrandff3b942021-06-09 15:20:36 +000056use std::convert::TryInto;
Shikha Panward8e35422021-10-11 13:51:27 +000057use std::ffi::CStr;
Alan Stokes0cc59ee2021-09-24 11:20:34 +010058use std::fs::{create_dir, File, OpenOptions};
Shikha Panwar7afc1392022-03-24 08:54:43 +000059use std::io::{Error, ErrorKind, Write, Read};
Andrew Walbranb15cd6e2021-07-05 16:38:07 +000060use std::num::NonZeroU32;
Andrew Walbrand3a84182021-09-07 14:48:52 +000061use std::os::unix::io::{FromRawFd, IntoRawFd};
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000062use std::path::{Path, PathBuf};
Andrew Walbran320b5602021-03-04 16:11:12 +000063use std::sync::{Arc, Mutex, Weak};
Shikha Panwar7afc1392022-03-24 08:54:43 +000064use tombstoned_client::{TombstonedConnection, DebuggerdDumpType};
Andrew Walbrancc0db522021-07-12 17:03:42 +000065use vmconfig::VmConfig;
Inseob Kim7f61fe72021-08-20 20:50:47 +090066use vsock::{SockAddr, VsockListener, VsockStream};
Jooyung Han35edb8f2021-07-01 16:17:16 +090067use zip::ZipArchive;
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000068
Andrew Walbranf6bf6862021-05-21 12:41:13 +000069pub const BINDER_SERVICE_IDENTIFIER: &str = "android.system.virtualizationservice";
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000070
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000071/// Directory in which to write disk image files used while running VMs.
Andrew Walbran488bd072021-07-14 13:29:51 +000072pub const TEMPORARY_DIRECTORY: &str = "/data/misc/virtualizationservice";
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000073
Jiyong Park8611a6c2021-07-09 18:17:44 +090074/// The CID representing the host VM
75const VMADDR_CID_HOST: u32 = 2;
76
Jooyung Han95884632021-07-06 22:27:54 +090077/// The size of zero.img.
78/// Gaps in composite disk images are filled with a shared zero.img.
79const ZERO_FILLER_SIZE: u64 = 4096;
80
Jiyong Park9dd389e2021-08-23 20:42:59 +090081/// Magic string for the instance image
82const ANDROID_VM_INSTANCE_MAGIC: &str = "Android-VM-instance";
83
84/// Version of the instance image format
85const ANDROID_VM_INSTANCE_VERSION: u16 = 1;
86
Shikha Panwar7afc1392022-03-24 08:54:43 +000087const CHUNK_RECV_MAX_LEN: usize = 1024;
88
Andrew Walbranf6bf6862021-05-21 12:41:13 +000089/// Implementation of `IVirtualizationService`, the entry point of the AIDL service.
Jooyung Han9900f3d2021-07-06 10:27:54 +090090#[derive(Debug, Default)]
Andrew Walbranf6bf6862021-05-21 12:41:13 +000091pub struct VirtualizationService {
Jiyong Park8611a6c2021-07-09 18:17:44 +090092 state: Arc<Mutex<State>>,
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000093}
94
Shikha Panward8e35422021-10-11 13:51:27 +000095impl Interface for VirtualizationService {
96 fn dump(&self, mut file: &File, _args: &[&CStr]) -> Result<(), StatusCode> {
97 check_permission("android.permission.DUMP").or(Err(StatusCode::PERMISSION_DENIED))?;
98 let state = &mut *self.state.lock().unwrap();
99 let vms = state.vms();
100 writeln!(file, "Running {0} VMs:", vms.len()).or(Err(StatusCode::UNKNOWN_ERROR))?;
101 for vm in vms {
102 writeln!(file, "VM CID: {}", vm.cid).or(Err(StatusCode::UNKNOWN_ERROR))?;
103 writeln!(file, "\tState: {:?}", vm.vm_state.lock().unwrap())
104 .or(Err(StatusCode::UNKNOWN_ERROR))?;
105 writeln!(file, "\tPayload state {:?}", vm.payload_state())
106 .or(Err(StatusCode::UNKNOWN_ERROR))?;
107 writeln!(file, "\tProtected: {}", vm.protected).or(Err(StatusCode::UNKNOWN_ERROR))?;
108 writeln!(file, "\ttemporary_directory: {}", vm.temporary_directory.to_string_lossy())
109 .or(Err(StatusCode::UNKNOWN_ERROR))?;
110 writeln!(file, "\trequester_uid: {}", vm.requester_uid)
111 .or(Err(StatusCode::UNKNOWN_ERROR))?;
112 writeln!(file, "\trequester_sid: {}", vm.requester_sid)
113 .or(Err(StatusCode::UNKNOWN_ERROR))?;
114 writeln!(file, "\trequester_debug_pid: {}", vm.requester_debug_pid)
115 .or(Err(StatusCode::UNKNOWN_ERROR))?;
116 }
117 Ok(())
118 }
119}
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000120
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000121impl IVirtualizationService for VirtualizationService {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000122 /// Creates (but does not start) a new VM with the given configuration, assigning it the next
123 /// available CID.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000124 ///
125 /// Returns a binder `IVirtualMachine` object referring to it, as a handle for the client.
Andrew Walbranf8d94112021-09-07 11:45:36 +0000126 fn createVm(
Andrew Walbrana89fc132021-03-17 17:08:36 +0000127 &self,
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000128 config: &VirtualMachineConfig,
Jiyong Parkb8182bb2021-10-26 22:53:08 +0900129 console_fd: Option<&ParcelFileDescriptor>,
Andrew Walbrana89fc132021-03-17 17:08:36 +0000130 log_fd: Option<&ParcelFileDescriptor>,
131 ) -> binder::Result<Strong<dyn IVirtualMachine>> {
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000132 let mut is_protected = false;
133 let ret = self.create_vm_internal(config, console_fd, log_fd, &mut is_protected);
134 match ret {
135 Ok(_) => {
136 let ok_status = Status::ok();
137 write_vm_creation_stats(
138 is_protected,
139 /*creation_succeeded*/ true,
140 ok_status.exception_code() as i32,
141 );
142 }
143 Err(ref e) => {
144 write_vm_creation_stats(
145 is_protected,
146 /*creation_succeeded*/ false,
147 e.exception_code() as i32,
148 );
149 }
150 }
151 ret
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000152 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000153
Andrew Walbrandff3b942021-06-09 15:20:36 +0000154 /// Initialise an empty partition image of the given size to be used as a writable partition.
155 fn initializeWritablePartition(
156 &self,
157 image_fd: &ParcelFileDescriptor,
158 size: i64,
Jiyong Park9dd389e2021-08-23 20:42:59 +0900159 partition_type: PartitionType,
Andrew Walbrandff3b942021-06-09 15:20:36 +0000160 ) -> binder::Result<()> {
Jiyong Park753553b2021-07-12 21:21:09 +0900161 check_manage_access()?;
Andrew Walbrandfc953d2021-06-10 13:59:56 +0000162 let size = size.try_into().map_err(|e| {
Andrew Walbran806f1542021-06-10 14:07:12 +0000163 new_binder_exception(
164 ExceptionCode::ILLEGAL_ARGUMENT,
165 format!("Invalid size {}: {}", size, e),
166 )
Andrew Walbrandff3b942021-06-09 15:20:36 +0000167 })?;
Andrew Walbrandfc953d2021-06-10 13:59:56 +0000168 let image = clone_file(image_fd)?;
Jooyung Han1edd5b92021-10-28 10:58:05 +0900169 // initialize the file. Any data in the file will be erased.
170 image.set_len(0).map_err(|e| {
171 new_binder_exception(
172 ExceptionCode::SERVICE_SPECIFIC,
173 format!("Failed to reset a file: {}", e),
174 )
175 })?;
Jiyong Park9dd389e2021-08-23 20:42:59 +0900176 let mut part = QcowFile::new(image, size).map_err(|e| {
Andrew Walbran806f1542021-06-10 14:07:12 +0000177 new_binder_exception(
178 ExceptionCode::SERVICE_SPECIFIC,
179 format!("Failed to create QCOW2 image: {}", e),
180 )
Andrew Walbrandfc953d2021-06-10 13:59:56 +0000181 })?;
Andrew Walbrandff3b942021-06-09 15:20:36 +0000182
Jiyong Park9dd389e2021-08-23 20:42:59 +0900183 match partition_type {
184 PartitionType::RAW => Ok(()),
185 PartitionType::ANDROID_VM_INSTANCE => format_as_android_vm_instance(&mut part),
186 _ => Err(Error::new(
187 ErrorKind::Unsupported,
188 format!("Unsupported partition type {:?}", partition_type),
189 )),
190 }
191 .map_err(|e| {
192 new_binder_exception(
193 ExceptionCode::SERVICE_SPECIFIC,
194 format!("Failed to initialize partition as {:?}: {}", partition_type, e),
195 )
196 })?;
197
Andrew Walbrandff3b942021-06-09 15:20:36 +0000198 Ok(())
199 }
200
Jiyong Park0a248432021-08-20 23:32:39 +0900201 /// Creates or update the idsig file by digesting the input APK file.
202 fn createOrUpdateIdsigFile(
203 &self,
204 input_fd: &ParcelFileDescriptor,
205 idsig_fd: &ParcelFileDescriptor,
206 ) -> binder::Result<()> {
207 // TODO(b/193504400): do this only when (1) idsig_fd is empty or (2) the APK digest in
208 // idsig_fd is different from APK digest in input_fd
209
Jiyong Parkc3ca24f2022-06-28 10:45:15 +0900210 check_manage_access()?;
211
Jiyong Park0a248432021-08-20 23:32:39 +0900212 let mut input = clone_file(input_fd)?;
213 let mut sig = V4Signature::create(&mut input, 4096, &[], HashAlgorithm::SHA256).unwrap();
214
215 let mut output = clone_file(idsig_fd)?;
216 output.set_len(0).unwrap();
217 sig.write_into(&mut output).unwrap();
218 Ok(())
219 }
220
Andrew Walbran320b5602021-03-04 16:11:12 +0000221 /// Get a list of all currently running VMs. This method is only intended for debug purposes,
222 /// and as such is only permitted from the shell user.
223 fn debugListVms(&self) -> binder::Result<Vec<VirtualMachineDebugInfo>> {
Andrew Walbran806f1542021-06-10 14:07:12 +0000224 check_debug_access()?;
Andrew Walbran320b5602021-03-04 16:11:12 +0000225
226 let state = &mut *self.state.lock().unwrap();
227 let vms = state.vms();
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000228 let cids = vms
229 .into_iter()
230 .map(|vm| VirtualMachineDebugInfo {
231 cid: vm.cid as i32,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000232 temporaryDirectory: vm.temporary_directory.to_string_lossy().to_string(),
Andrew Walbran1ef19ae2021-04-07 11:31:57 +0000233 requesterUid: vm.requester_uid as i32,
234 requesterSid: vm.requester_sid.clone(),
Andrew Walbran02034492021-04-13 15:05:07 +0000235 requesterPid: vm.requester_debug_pid,
Andrew Walbran6b650662021-09-07 13:13:23 +0000236 state: get_state(&vm),
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000237 })
238 .collect();
Andrew Walbran320b5602021-03-04 16:11:12 +0000239 Ok(cids)
240 }
David Brazdil3c2ddef2021-03-18 13:09:57 +0000241
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000242 /// Hold a strong reference to a VM in VirtualizationService. This method is only intended for
243 /// debug purposes, and as such is only permitted from the shell user.
Andrei Homescu1415c132021-03-24 02:39:55 +0000244 fn debugHoldVmRef(&self, vmref: &Strong<dyn IVirtualMachine>) -> binder::Result<()> {
Andrew Walbran806f1542021-06-10 14:07:12 +0000245 check_debug_access()?;
David Brazdil3c2ddef2021-03-18 13:09:57 +0000246
David Brazdil3c2ddef2021-03-18 13:09:57 +0000247 let state = &mut *self.state.lock().unwrap();
Andrei Homescu1415c132021-03-24 02:39:55 +0000248 state.debug_hold_vm(vmref.clone());
David Brazdil3c2ddef2021-03-18 13:09:57 +0000249 Ok(())
250 }
251
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000252 /// Drop reference to a VM that is being held by VirtualizationService. Returns the reference if
253 /// the VM was found and None otherwise. This method is only intended for debug purposes, and as
254 /// such is only permitted from the shell user.
David Brazdil3c2ddef2021-03-18 13:09:57 +0000255 fn debugDropVmRef(&self, cid: i32) -> binder::Result<Option<Strong<dyn IVirtualMachine>>> {
Andrew Walbran806f1542021-06-10 14:07:12 +0000256 check_debug_access()?;
David Brazdil3c2ddef2021-03-18 13:09:57 +0000257
258 let state = &mut *self.state.lock().unwrap();
259 Ok(state.debug_drop_vm(cid))
260 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000261}
262
Shikha Panwar7afc1392022-03-24 08:54:43 +0000263fn handle_stream_connection_tombstoned() -> Result<()> {
264 let listener =
265 VsockListener::bind_with_cid_port(VMADDR_CID_HOST, VM_TOMBSTONES_SERVICE_PORT as u32)?;
266 info!("Listening to tombstones from guests ...");
267 for incoming_stream in listener.incoming() {
268 let mut incoming_stream = match incoming_stream {
269 Err(e) => {
270 warn!("invalid incoming connection: {}", e);
271 continue;
272 }
273 Ok(s) => s,
274 };
275 std::thread::spawn(move || {
276 if let Err(e) = handle_tombstone(&mut incoming_stream) {
277 error!("Failed to write tombstone- {:?}", e);
278 }
279 });
280 }
281 Ok(())
282}
283
284fn handle_tombstone(stream: &mut VsockStream) -> Result<()> {
285 if let Ok(SockAddr::Vsock(addr)) = stream.peer_addr() {
286 info!("Vsock Stream connected to cid={} for tombstones", addr.cid());
287 }
288 let tb_connection =
289 TombstonedConnection::connect(std::process::id() as i32, DebuggerdDumpType::Tombstone)
290 .context("Failed to connect to tombstoned")?;
291 let mut text_output = tb_connection
292 .text_output
293 .as_ref()
294 .ok_or_else(|| anyhow!("Could not get file to write the tombstones on"))?;
295 let mut num_bytes_read = 0;
296 loop {
297 let mut chunk_recv = [0; CHUNK_RECV_MAX_LEN];
298 let n = stream
299 .read(&mut chunk_recv)
300 .context("Failed to read tombstone data from Vsock stream")?;
301 if n == 0 {
302 break;
303 }
304 num_bytes_read += n;
305 text_output.write_all(&chunk_recv[0..n]).context("Failed to write guests tombstones")?;
306 }
307 info!("Received {} bytes from guest & wrote to tombstone file", num_bytes_read);
308 tb_connection.notify_completion()?;
309 Ok(())
310}
311
Jiyong Park8611a6c2021-07-09 18:17:44 +0900312impl VirtualizationService {
313 pub fn init() -> VirtualizationService {
314 let service = VirtualizationService::default();
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900315
316 // server for payload output
Jiyong Park8611a6c2021-07-09 18:17:44 +0900317 let state = service.state.clone(); // reference to state (not the state itself) is copied
318 std::thread::spawn(move || {
Inseob Kim7f61fe72021-08-20 20:50:47 +0900319 handle_stream_connection_from_vm(state).unwrap();
Jiyong Park8611a6c2021-07-09 18:17:44 +0900320 });
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900321
Shikha Panwar7afc1392022-03-24 08:54:43 +0000322 std::thread::spawn(|| {
323 if let Err(e) = handle_stream_connection_tombstoned() {
324 warn!("Error receiving tombstone from guest or writing them. Error: {}", e);
325 }
326 });
327
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900328 // binder server for vm
Shikha Panwar7afc1392022-03-24 08:54:43 +0000329 // reference to state (not the state itself) is copied
Andrew Walbran0fd0ff02022-07-29 15:59:17 +0000330 let state = service.state.clone();
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900331 std::thread::spawn(move || {
Andrew Walbran0fd0ff02022-07-29 15:59:17 +0000332 debug!("VirtualMachineService is starting as an RPC service.");
333 if run_rpc_server_with_factory(VM_BINDER_SERVICE_PORT as u32, |cid| {
334 VirtualMachineService::factory(cid, &state)
335 }) {
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900336 debug!("RPC server has shut down gracefully");
337 } else {
Andrew Walbran0fd0ff02022-07-29 15:59:17 +0000338 panic!("Premature termination of RPC server");
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900339 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900340 });
Jiyong Park8611a6c2021-07-09 18:17:44 +0900341 service
342 }
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000343
344 fn create_vm_internal(
345 &self,
346 config: &VirtualMachineConfig,
347 console_fd: Option<&ParcelFileDescriptor>,
348 log_fd: Option<&ParcelFileDescriptor>,
349 is_protected: &mut bool,
350 ) -> binder::Result<Strong<dyn IVirtualMachine>> {
351 check_manage_access()?;
Inseob Kim1119d702022-05-02 18:01:58 +0900352
353 if let VirtualMachineConfig::RawConfig(config) = config {
354 if config.protectedVm {
355 check_use_custom_virtual_machine()?;
356 }
357 }
358
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000359 let state = &mut *self.state.lock().unwrap();
360 let console_fd = console_fd.map(clone_file).transpose()?;
361 let log_fd = log_fd.map(clone_file).transpose()?;
362 let requester_uid = ThreadState::get_calling_uid();
363 let requester_sid = get_calling_sid()?;
364 let requester_debug_pid = ThreadState::get_calling_pid();
365 let cid = next_cid().or(Err(ExceptionCode::ILLEGAL_STATE))?;
366
367 // Counter to generate unique IDs for temporary image files.
368 let mut next_temporary_image_id = 0;
369 // Files which are referred to from composite images. These must be mapped to the crosvm
370 // child process, and not closed before it is started.
371 let mut indirect_files = vec![];
372
373 // Make directory for temporary files.
374 let temporary_directory: PathBuf = format!("{}/{}", TEMPORARY_DIRECTORY, cid).into();
375 create_dir(&temporary_directory).map_err(|e| {
376 // At this point, we do not know the protected status of Vm
377 // setting it to false, though this may not be correct.
378 error!(
Alan Stokes70ccf162022-07-08 11:05:03 +0100379 "Failed to create temporary directory {:?} for VM files: {:?}",
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000380 temporary_directory, e
381 );
382 new_binder_exception(
383 ExceptionCode::SERVICE_SPECIFIC,
384 format!(
385 "Failed to create temporary directory {:?} for VM files: {}",
386 temporary_directory, e
387 ),
388 )
389 })?;
390
391 let is_app_config = matches!(config, VirtualMachineConfig::AppConfig(_));
392
393 let config = match config {
394 VirtualMachineConfig::AppConfig(config) => BorrowedOrOwned::Owned(
395 load_app_config(config, &temporary_directory).map_err(|e| {
Alan Stokes70ccf162022-07-08 11:05:03 +0100396 error!("Failed to load app config from {}: {:?}", &config.configPath, e);
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000397 *is_protected = config.protectedVm;
398 new_binder_exception(
399 ExceptionCode::SERVICE_SPECIFIC,
400 format!("Failed to load app config from {}: {}", &config.configPath, e),
401 )
402 })?,
403 ),
404 VirtualMachineConfig::RawConfig(config) => BorrowedOrOwned::Borrowed(config),
405 };
406 let config = config.as_ref();
407 *is_protected = config.protectedVm;
408
409 // Check if partition images are labeled incorrectly. This is to prevent random images
410 // which are not protected by the Android Verified Boot (e.g. bits downloaded by apps) from
411 // being loaded in a pVM. Specifically, for images in the raw config, nothing is allowed
412 // to be labeled as app_data_file. For images in the app config, nothing but the instance
413 // partition is allowed to be labeled as such.
414 config
415 .disks
416 .iter()
417 .flat_map(|disk| disk.partitions.iter())
418 .filter(|partition| {
419 if is_app_config {
420 partition.label != "vm-instance"
421 } else {
422 true // all partitions are checked
423 }
424 })
425 .try_for_each(check_label_for_partition)
426 .map_err(|e| new_binder_exception(ExceptionCode::SERVICE_SPECIFIC, e.to_string()))?;
427
428 let zero_filler_path = temporary_directory.join("zero.img");
429 write_zero_filler(&zero_filler_path).map_err(|e| {
Alan Stokes70ccf162022-07-08 11:05:03 +0100430 error!("Failed to make composite image: {:?}", e);
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000431 new_binder_exception(
432 ExceptionCode::SERVICE_SPECIFIC,
433 format!("Failed to make composite image: {}", e),
434 )
435 })?;
436
437 // Assemble disk images if needed.
438 let disks = config
439 .disks
440 .iter()
441 .map(|disk| {
442 assemble_disk_image(
443 disk,
444 &zero_filler_path,
445 &temporary_directory,
446 &mut next_temporary_image_id,
447 &mut indirect_files,
448 )
449 })
450 .collect::<Result<Vec<DiskFile>, _>>()?;
451
Jiyong Parke558ab12022-07-07 20:18:55 +0900452 // Creating this ramdump file unconditionally is not harmful as ramdump will be created
453 // only when the VM is configured as such. `ramdump_write` is sent to crosvm and will
Jiyong Park4afe2012022-07-08 05:38:49 +0900454 // be the backing store for the /dev/hvc1 where VM will emit ramdump to. `ramdump_read`
Jiyong Parke558ab12022-07-07 20:18:55 +0900455 // will be sent back to the client (i.e. the VM owner) for readout.
456 let ramdump_path = temporary_directory.join("ramdump");
457 let ramdump = prepare_ramdump_file(&ramdump_path).map_err(|e| {
458 error!("Failed to prepare ramdump file: {}", e);
459 new_binder_exception(
460 ExceptionCode::SERVICE_SPECIFIC,
461 format!("Failed to prepare ramdump file: {}", e),
462 )
463 })?;
464
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000465 // Actually start the VM.
466 let crosvm_config = CrosvmConfig {
467 cid,
468 bootloader: maybe_clone_file(&config.bootloader)?,
469 kernel: maybe_clone_file(&config.kernel)?,
470 initrd: maybe_clone_file(&config.initrd)?,
471 disks,
472 params: config.params.to_owned(),
473 protected: *is_protected,
474 memory_mib: config.memoryMib.try_into().ok().and_then(NonZeroU32::new),
475 cpus: config.numCpus.try_into().ok().and_then(NonZeroU32::new),
476 cpu_affinity: config.cpuAffinity.clone(),
Jiyong Parkdfe16d62022-04-20 17:32:12 +0900477 task_profiles: config.taskProfiles.clone(),
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000478 console_fd,
479 log_fd,
Jiyong Parke558ab12022-07-07 20:18:55 +0900480 ramdump: Some(ramdump),
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000481 indirect_files,
482 platform_version: parse_platform_version_req(&config.platformVersion)?,
Jiyong Parke6ed0f92022-06-22 00:13:00 +0900483 detect_hangup: is_app_config,
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000484 };
485 let instance = Arc::new(
486 VmInstance::new(
487 crosvm_config,
488 temporary_directory,
489 requester_uid,
490 requester_sid,
491 requester_debug_pid,
492 )
493 .map_err(|e| {
Alan Stokes70ccf162022-07-08 11:05:03 +0100494 error!("Failed to create VM with config {:?}: {:?}", config, e);
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000495 new_binder_exception(
496 ExceptionCode::SERVICE_SPECIFIC,
497 format!("Failed to create VM: {}", e),
498 )
499 })?,
500 );
501 state.add_vm(Arc::downgrade(&instance));
502 Ok(VirtualMachine::create(instance))
503 }
Jiyong Park8611a6c2021-07-09 18:17:44 +0900504}
505
Treehugger Robot3ffa8322021-11-22 12:06:47 +0000506/// Write the stats of VMCreation to statsd
Shikha Panwar061aa2c2022-04-05 12:52:56 +0000507fn write_vm_creation_stats(is_protected: bool, creation_succeeded: bool, exception_code: i32) {
508 match stats_write(Hypervisor::Pkvm, is_protected, creation_succeeded, exception_code) {
Treehugger Robot3ffa8322021-11-22 12:06:47 +0000509 Err(e) => {
Andrew Walbranf6d600f2022-02-03 14:42:39 +0000510 warn!("statslog_rust failed with error: {}", e);
Treehugger Robot3ffa8322021-11-22 12:06:47 +0000511 }
Andrew Walbranf6d600f2022-02-03 14:42:39 +0000512 Ok(_) => trace!("statslog_rust succeeded for virtualization service"),
Treehugger Robot3ffa8322021-11-22 12:06:47 +0000513 }
514}
515
Andrew Walbran6b650662021-09-07 13:13:23 +0000516/// Waits for incoming connections from VM. If a new connection is made, stores the stream in the
517/// corresponding `VmInstance`.
Inseob Kim7f61fe72021-08-20 20:50:47 +0900518fn handle_stream_connection_from_vm(state: Arc<Mutex<State>>) -> Result<()> {
Inseob Kimd0587562021-09-01 21:27:32 +0900519 let listener =
520 VsockListener::bind_with_cid_port(VMADDR_CID_HOST, VM_STREAM_SERVICE_PORT as u32)?;
Jiyong Park8611a6c2021-07-09 18:17:44 +0900521 for stream in listener.incoming() {
522 let stream = match stream {
523 Err(e) => {
524 warn!("invalid incoming connection: {}", e);
525 continue;
526 }
527 Ok(s) => s,
528 };
529 if let Ok(SockAddr::Vsock(addr)) = stream.peer_addr() {
530 let cid = addr.cid();
531 let port = addr.port();
Inseob Kim7f61fe72021-08-20 20:50:47 +0900532 info!("payload stream connected from cid={}, port={}", cid, port);
Jiyong Park8611a6c2021-07-09 18:17:44 +0900533 if let Some(vm) = state.lock().unwrap().get_vm(cid) {
Chris Wailes8bbb8932021-09-10 14:14:19 -0700534 *vm.stream.lock().unwrap() = Some(stream);
Inseob Kim7f61fe72021-08-20 20:50:47 +0900535 } else {
536 error!("connection from cid={} is not from a guest VM", cid);
Jiyong Park8611a6c2021-07-09 18:17:44 +0900537 }
538 }
539 }
540 Ok(())
541}
542
Andrew Walbranfbb39d22021-07-28 17:01:25 +0000543fn write_zero_filler(zero_filler_path: &Path) -> Result<()> {
Jooyung Han95884632021-07-06 22:27:54 +0900544 let file = OpenOptions::new()
545 .create_new(true)
546 .read(true)
547 .write(true)
548 .open(zero_filler_path)
549 .with_context(|| "Failed to create zero.img")?;
550 file.set_len(ZERO_FILLER_SIZE)?;
Andrew Walbranfbb39d22021-07-28 17:01:25 +0000551 Ok(())
Jooyung Han95884632021-07-06 22:27:54 +0900552}
553
Jiyong Park9dd389e2021-08-23 20:42:59 +0900554fn format_as_android_vm_instance(part: &mut dyn Write) -> std::io::Result<()> {
555 part.write_all(ANDROID_VM_INSTANCE_MAGIC.as_bytes())?;
556 part.write_all(&ANDROID_VM_INSTANCE_VERSION.to_le_bytes())?;
557 part.flush()
558}
559
Jiyong Parke558ab12022-07-07 20:18:55 +0900560fn prepare_ramdump_file(ramdump_path: &Path) -> Result<File> {
561 File::create(&ramdump_path)
562 .context(format!("Failed to create ramdump file {:?}", &ramdump_path))
563}
564
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000565/// Given the configuration for a disk image, assembles the `DiskFile` to pass to crosvm.
566///
567/// This may involve assembling a composite disk from a set of partition images.
568fn assemble_disk_image(
569 disk: &DiskImage,
Jooyung Han95884632021-07-06 22:27:54 +0900570 zero_filler_path: &Path,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000571 temporary_directory: &Path,
572 next_temporary_image_id: &mut u64,
573 indirect_files: &mut Vec<File>,
Andrew Walbran806f1542021-06-10 14:07:12 +0000574) -> Result<DiskFile, Status> {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000575 let image = if !disk.partitions.is_empty() {
576 if disk.image.is_some() {
577 warn!("DiskImage {:?} contains both image and partitions.", disk);
Andrew Walbran806f1542021-06-10 14:07:12 +0000578 return Err(new_binder_exception(
579 ExceptionCode::ILLEGAL_ARGUMENT,
580 "DiskImage contains both image and partitions.",
581 ));
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000582 }
583
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000584 let composite_image_filenames =
585 make_composite_image_filenames(temporary_directory, next_temporary_image_id);
586 let (image, partition_files) = make_composite_image(
587 &disk.partitions,
Jooyung Han95884632021-07-06 22:27:54 +0900588 zero_filler_path,
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000589 &composite_image_filenames.composite,
590 &composite_image_filenames.header,
591 &composite_image_filenames.footer,
592 )
593 .map_err(|e| {
Alan Stokes70ccf162022-07-08 11:05:03 +0100594 error!("Failed to make composite image with config {:?}: {:?}", disk, e);
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000595 new_binder_exception(
596 ExceptionCode::SERVICE_SPECIFIC,
597 format!("Failed to make composite image: {}", e),
598 )
599 })?;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000600
601 // Pass the file descriptors for the various partition files to crosvm when it
602 // is run.
603 indirect_files.extend(partition_files);
604
605 image
606 } else if let Some(image) = &disk.image {
607 clone_file(image)?
608 } else {
609 warn!("DiskImage {:?} didn't contain image or partitions.", disk);
Andrew Walbran806f1542021-06-10 14:07:12 +0000610 return Err(new_binder_exception(
611 ExceptionCode::ILLEGAL_ARGUMENT,
612 "DiskImage didn't contain image or partitions.",
613 ));
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000614 };
615
616 Ok(DiskFile { image, writable: disk.writable })
617}
618
Jooyung Han21e9b922021-06-26 04:14:16 +0900619fn load_app_config(
620 config: &VirtualMachineAppConfig,
621 temporary_directory: &Path,
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900622) -> Result<VirtualMachineRawConfig> {
Andrew Walbrancc0db522021-07-12 17:03:42 +0000623 let apk_file = clone_file(config.apk.as_ref().unwrap())?;
624 let idsig_file = clone_file(config.idsig.as_ref().unwrap())?;
Jiyong Park8d081812021-07-23 17:45:04 +0900625 let instance_file = clone_file(config.instanceImage.as_ref().unwrap())?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900626 let config_path = &config.configPath;
627
Andrew Walbrancc0db522021-07-12 17:03:42 +0000628 let mut apk_zip = ZipArchive::new(&apk_file)?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900629 let config_file = apk_zip.by_name(config_path)?;
630 let vm_payload_config: VmPayloadConfig = serde_json::from_reader(config_file)?;
631
632 let os_name = &vm_payload_config.os.name;
Andrew Walbrancc0db522021-07-12 17:03:42 +0000633
Jooyung Han35edb8f2021-07-01 16:17:16 +0900634 // For now, the only supported "os" value is "microdroid"
635 if os_name != "microdroid" {
Andrew Walbrancc0db522021-07-12 17:03:42 +0000636 bail!("Unknown OS \"{}\"", os_name);
Jooyung Han35edb8f2021-07-01 16:17:16 +0900637 }
Andrew Walbrancc0db522021-07-12 17:03:42 +0000638
639 // It is safe to construct a filename based on the os_name because we've already checked that it
640 // is one of the allowed values.
Jooyung Han21e9b922021-06-26 04:14:16 +0900641 let vm_config_path = PathBuf::from(format!("/apex/com.android.virt/etc/{}.json", os_name));
642 let vm_config_file = File::open(vm_config_path)?;
Andrew Walbrancc0db522021-07-12 17:03:42 +0000643 let mut vm_config = VmConfig::load(&vm_config_file)?.to_parcelable()?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900644
Andrew Walbrancc045902021-07-27 16:06:17 +0000645 if config.memoryMib > 0 {
646 vm_config.memoryMib = config.memoryMib;
Andrew Walbran45bcb0c2021-07-14 15:02:06 +0000647 }
648
Andrew Walbran3994f002022-01-27 17:33:45 +0000649 vm_config.protectedVm = config.protectedVm;
Jiyong Park032615f2022-01-10 13:55:34 +0900650 vm_config.numCpus = config.numCpus;
651 vm_config.cpuAffinity = config.cpuAffinity.clone();
Jiyong Parkdfe16d62022-04-20 17:32:12 +0900652 vm_config.taskProfiles = config.taskProfiles.clone();
Jiyong Park032615f2022-01-10 13:55:34 +0900653
Andrew Walbrancc0db522021-07-12 17:03:42 +0000654 // Microdroid requires an additional payload disk image and the bootconfig partition.
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900655 if os_name == "microdroid" {
Andrew Walbrancc0db522021-07-12 17:03:42 +0000656 add_microdroid_images(
657 config,
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900658 temporary_directory,
Andrew Walbrancc0db522021-07-12 17:03:42 +0000659 apk_file,
660 idsig_file,
Jiyong Park8d081812021-07-23 17:45:04 +0900661 instance_file,
Jooyung Han5dc42172021-10-05 16:43:47 +0900662 &vm_payload_config,
Andrew Walbrancc0db522021-07-12 17:03:42 +0000663 &mut vm_config,
664 )?;
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900665 }
Jooyung Han21e9b922021-06-26 04:14:16 +0900666
Andrew Walbrancc0db522021-07-12 17:03:42 +0000667 Ok(vm_config)
Jooyung Han21e9b922021-06-26 04:14:16 +0900668}
669
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000670/// Generates a unique filename to use for a composite disk image.
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000671fn make_composite_image_filenames(
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000672 temporary_directory: &Path,
673 next_temporary_image_id: &mut u64,
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000674) -> CompositeImageFilenames {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000675 let id = *next_temporary_image_id;
676 *next_temporary_image_id += 1;
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000677 CompositeImageFilenames {
678 composite: temporary_directory.join(format!("composite-{}.img", id)),
679 header: temporary_directory.join(format!("composite-{}-header.img", id)),
680 footer: temporary_directory.join(format!("composite-{}-footer.img", id)),
681 }
682}
683
684/// Filenames for a composite disk image, including header and footer partitions.
685#[derive(Clone, Debug, Eq, PartialEq)]
686struct CompositeImageFilenames {
687 /// The composite disk image itself.
688 composite: PathBuf,
689 /// The header partition image.
690 header: PathBuf,
691 /// The footer partition image.
692 footer: PathBuf,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000693}
694
695/// Gets the calling SID of the current Binder thread.
Andrew Walbran806f1542021-06-10 14:07:12 +0000696fn get_calling_sid() -> Result<String, Status> {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000697 ThreadState::with_calling_sid(|sid| {
698 if let Some(sid) = sid {
699 match sid.to_str() {
700 Ok(sid) => Ok(sid.to_owned()),
701 Err(e) => {
Andrew Walbran806f1542021-06-10 14:07:12 +0000702 error!("SID was not valid UTF-8: {}", e);
703 Err(new_binder_exception(
704 ExceptionCode::ILLEGAL_ARGUMENT,
705 format!("SID was not valid UTF-8: {}", e),
706 ))
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000707 }
708 }
709 } else {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000710 error!("Missing SID on createVm");
711 Err(new_binder_exception(ExceptionCode::SECURITY, "Missing SID on createVm"))
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000712 }
713 })
714}
715
Jiyong Park753553b2021-07-12 21:21:09 +0900716/// Checks whether the caller has a specific permission
717fn check_permission(perm: &str) -> binder::Result<()> {
718 let calling_pid = ThreadState::get_calling_pid();
719 let calling_uid = ThreadState::get_calling_uid();
720 // Root can do anything
721 if calling_uid == 0 {
722 return Ok(());
723 }
724 let perm_svc: Strong<dyn IPermissionController::IPermissionController> =
725 binder::get_interface("permission")?;
726 if perm_svc.checkPermission(perm, calling_pid, calling_uid as i32)? {
Andrew Walbran806f1542021-06-10 14:07:12 +0000727 Ok(())
728 } else {
Jiyong Park753553b2021-07-12 21:21:09 +0900729 Err(new_binder_exception(
730 ExceptionCode::SECURITY,
731 format!("does not have the {} permission", perm),
732 ))
Andrew Walbran806f1542021-06-10 14:07:12 +0000733 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000734}
735
Jiyong Park753553b2021-07-12 21:21:09 +0900736/// Check whether the caller of the current Binder method is allowed to call debug methods.
737fn check_debug_access() -> binder::Result<()> {
738 check_permission("android.permission.DEBUG_VIRTUAL_MACHINE")
739}
740
741/// Check whether the caller of the current Binder method is allowed to manage VMs
742fn check_manage_access() -> binder::Result<()> {
743 check_permission("android.permission.MANAGE_VIRTUAL_MACHINE")
744}
745
Inseob Kim1119d702022-05-02 18:01:58 +0900746/// Check whether the caller of the current Binder method is allowed to create custom VMs
747fn check_use_custom_virtual_machine() -> binder::Result<()> {
748 check_permission("android.permission.USE_CUSTOM_VIRTUAL_MACHINE")
749}
750
Jiyong Park029977d2021-11-24 21:56:49 +0900751/// Check if a partition has selinux labels that are not allowed
752fn check_label_for_partition(partition: &Partition) -> Result<()> {
753 let ctx = getfilecon(partition.image.as_ref().unwrap().as_ref())?;
754 if ctx == SeContext::new("u:object_r:app_data_file:s0").unwrap() {
755 Err(anyhow!("Partition {} shouldn't be labeled as {}", &partition.label, ctx))
756 } else {
757 Ok(())
758 }
759}
760
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000761/// Implementation of the AIDL `IVirtualMachine` interface. Used as a handle to a VM.
762#[derive(Debug)]
763struct VirtualMachine {
764 instance: Arc<VmInstance>,
Alan Stokes0cc59ee2021-09-24 11:20:34 +0100765 /// Keeps our service process running as long as this VM instance exists.
Chris Wailes641fc4a2021-12-01 15:03:21 -0800766 #[allow(dead_code)]
Alan Stokes0cc59ee2021-09-24 11:20:34 +0100767 lazy_service_guard: LazyServiceGuard,
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000768}
769
770impl VirtualMachine {
771 fn create(instance: Arc<VmInstance>) -> Strong<dyn IVirtualMachine> {
Alan Stokes0cc59ee2021-09-24 11:20:34 +0100772 let binder = VirtualMachine { instance, lazy_service_guard: Default::default() };
Andrew Walbran4de28782021-04-13 14:51:43 +0000773 BnVirtualMachine::new_binder(binder, BinderFeatures::default())
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000774 }
775}
776
777impl Interface for VirtualMachine {}
778
779impl IVirtualMachine for VirtualMachine {
780 fn getCid(&self) -> binder::Result<i32> {
Jiyong Park753553b2021-07-12 21:21:09 +0900781 // Don't check permission. The owner of the VM might have passed this binder object to
782 // others.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000783 Ok(self.instance.cid as i32)
784 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000785
Andrew Walbran6b650662021-09-07 13:13:23 +0000786 fn getState(&self) -> binder::Result<VirtualMachineState> {
Jiyong Park753553b2021-07-12 21:21:09 +0900787 // Don't check permission. The owner of the VM might have passed this binder object to
788 // others.
Andrew Walbran6b650662021-09-07 13:13:23 +0000789 Ok(get_state(&self.instance))
Andrew Walbrandae07162021-03-12 17:05:20 +0000790 }
791
792 fn registerCallback(
793 &self,
794 callback: &Strong<dyn IVirtualMachineCallback>,
795 ) -> binder::Result<()> {
Jiyong Park753553b2021-07-12 21:21:09 +0900796 // Don't check permission. The owner of the VM might have passed this binder object to
797 // others.
798 //
Andrew Walbrandae07162021-03-12 17:05:20 +0000799 // TODO: Should this give an error if the VM is already dead?
800 self.instance.callbacks.add(callback.clone());
801 Ok(())
802 }
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000803
Andrew Walbranf8d94112021-09-07 11:45:36 +0000804 fn start(&self) -> binder::Result<()> {
805 self.instance.start().map_err(|e| {
806 error!("Error starting VM with CID {}: {:?}", self.instance.cid, e);
807 new_binder_exception(ExceptionCode::SERVICE_SPECIFIC, e.to_string())
808 })
809 }
810
Inseob Kima446f802022-07-11 19:46:37 +0900811 fn stop(&self) -> binder::Result<()> {
812 self.instance.kill().map_err(|e| {
813 error!("Error stopping VM with CID {}: {:?}", self.instance.cid, e);
814 new_binder_exception(ExceptionCode::SERVICE_SPECIFIC, e.to_string())
815 })
816 }
817
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000818 fn connectVsock(&self, port: i32) -> binder::Result<ParcelFileDescriptor> {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000819 if !matches!(&*self.instance.vm_state.lock().unwrap(), VmState::Running { .. }) {
820 return Err(new_binder_exception(ExceptionCode::SERVICE_SPECIFIC, "VM is not running"));
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000821 }
822 let stream =
823 VsockStream::connect_with_cid_port(self.instance.cid, port as u32).map_err(|e| {
824 new_binder_exception(
825 ExceptionCode::SERVICE_SPECIFIC,
826 format!("Failed to connect: {}", e),
827 )
828 })?;
829 Ok(vsock_stream_to_pfd(stream))
830 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000831}
832
833impl Drop for VirtualMachine {
834 fn drop(&mut self) {
835 debug!("Dropping {:?}", self);
Inseob Kima446f802022-07-11 19:46:37 +0900836 if let Err(e) = self.instance.kill() {
837 debug!("Error stopping dropped VM with CID {}: {:?}", self.instance.cid, e);
838 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000839 }
840}
841
842/// A set of Binders to be called back in response to various events on the VM, such as when it
843/// dies.
844#[derive(Debug, Default)]
845pub struct VirtualMachineCallbacks(Mutex<Vec<Strong<dyn IVirtualMachineCallback>>>);
846
847impl VirtualMachineCallbacks {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900848 /// Call all registered callbacks to notify that the payload has started.
Inseob Kim7f61fe72021-08-20 20:50:47 +0900849 pub fn notify_payload_started(&self, cid: Cid, stream: Option<VsockStream>) {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900850 let callbacks = &*self.0.lock().unwrap();
Inseob Kim7f61fe72021-08-20 20:50:47 +0900851 let pfd = stream.map(vsock_stream_to_pfd);
Jiyong Park8611a6c2021-07-09 18:17:44 +0900852 for callback in callbacks {
Inseob Kim7f61fe72021-08-20 20:50:47 +0900853 if let Err(e) = callback.onPayloadStarted(cid as i32, pfd.as_ref()) {
Alan Stokes70ccf162022-07-08 11:05:03 +0100854 error!("Error notifying payload start event from VM CID {}: {:?}", cid, e);
Jiyong Park8611a6c2021-07-09 18:17:44 +0900855 }
856 }
857 }
858
Inseob Kim14cb8692021-08-31 21:50:39 +0900859 /// Call all registered callbacks to notify that the payload is ready to serve.
860 pub fn notify_payload_ready(&self, cid: Cid) {
861 let callbacks = &*self.0.lock().unwrap();
862 for callback in callbacks {
863 if let Err(e) = callback.onPayloadReady(cid as i32) {
Alan Stokes70ccf162022-07-08 11:05:03 +0100864 error!("Error notifying payload ready event from VM CID {}: {:?}", cid, e);
Inseob Kim14cb8692021-08-31 21:50:39 +0900865 }
866 }
867 }
868
Inseob Kim2444af92021-08-31 01:22:50 +0900869 /// Call all registered callbacks to notify that the payload has finished.
870 pub fn notify_payload_finished(&self, cid: Cid, exit_code: i32) {
871 let callbacks = &*self.0.lock().unwrap();
872 for callback in callbacks {
873 if let Err(e) = callback.onPayloadFinished(cid as i32, exit_code) {
Alan Stokes70ccf162022-07-08 11:05:03 +0100874 error!("Error notifying payload finish event from VM CID {}: {:?}", cid, e);
Inseob Kim2444af92021-08-31 01:22:50 +0900875 }
876 }
877 }
878
Jooyung Handd0a1732021-11-23 15:26:20 +0900879 /// Call all registered callbacks to say that the VM encountered an error.
880 pub fn notify_error(&self, cid: Cid, error_code: i32, message: &str) {
881 let callbacks = &*self.0.lock().unwrap();
882 for callback in callbacks {
883 if let Err(e) = callback.onError(cid as i32, error_code, message) {
Alan Stokes70ccf162022-07-08 11:05:03 +0100884 error!("Error notifying error event from VM CID {}: {:?}", cid, e);
Jooyung Handd0a1732021-11-23 15:26:20 +0900885 }
886 }
887 }
888
Andrew Walbrandae07162021-03-12 17:05:20 +0000889 /// Call all registered callbacks to say that the VM has died.
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000890 pub fn callback_on_died(&self, cid: Cid, reason: DeathReason) {
Andrew Walbrandae07162021-03-12 17:05:20 +0000891 let callbacks = &*self.0.lock().unwrap();
892 for callback in callbacks {
Andrew Walbranc92d35f2022-01-12 12:45:19 +0000893 if let Err(e) = callback.onDied(cid as i32, reason) {
Alan Stokes70ccf162022-07-08 11:05:03 +0100894 error!("Error notifying exit of VM CID {}: {:?}", cid, e);
Andrew Walbrandae07162021-03-12 17:05:20 +0000895 }
896 }
897 }
898
Jiyong Parke558ab12022-07-07 20:18:55 +0900899 /// Call all registered callbacks to say that there was a ramdump to download.
900 pub fn callback_on_ramdump(&self, cid: Cid, ramdump: File) {
901 let callbacks = &*self.0.lock().unwrap();
902 let pfd = ParcelFileDescriptor::new(ramdump);
903 for callback in callbacks {
904 if let Err(e) = callback.onRamdump(cid as i32, &pfd) {
905 error!("Error notifying ramdump of VM CID {}: {}", cid, e);
906 }
907 }
908 }
909
Andrew Walbrandae07162021-03-12 17:05:20 +0000910 /// Add a new callback to the set.
911 fn add(&self, callback: Strong<dyn IVirtualMachineCallback>) {
912 self.0.lock().unwrap().push(callback);
913 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000914}
915
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000916/// The mutable state of the VirtualizationService. There should only be one instance of this
917/// struct.
Chris Wailes641fc4a2021-12-01 15:03:21 -0800918#[derive(Debug, Default)]
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000919struct State {
Andrew Walbran320b5602021-03-04 16:11:12 +0000920 /// The VMs which have been started. When VMs are started a weak reference is added to this list
921 /// while a strong reference is returned to the caller over Binder. Once all copies of the
922 /// Binder client are dropped the weak reference here will become invalid, and will be removed
923 /// from the list opportunistically the next time `add_vm` is called.
924 vms: Vec<Weak<VmInstance>>,
David Brazdil3c2ddef2021-03-18 13:09:57 +0000925
926 /// Vector of strong VM references held on behalf of users that cannot hold them themselves.
927 /// This is only used for debugging purposes.
928 debug_held_vms: Vec<Strong<dyn IVirtualMachine>>,
Andrew Walbran320b5602021-03-04 16:11:12 +0000929}
930
931impl State {
Andrew Walbrandae07162021-03-12 17:05:20 +0000932 /// Get a list of VMs which still have Binder references to them.
Andrew Walbran320b5602021-03-04 16:11:12 +0000933 fn vms(&self) -> Vec<Arc<VmInstance>> {
934 // Attempt to upgrade the weak pointers to strong pointers.
935 self.vms.iter().filter_map(Weak::upgrade).collect()
936 }
937
938 /// Add a new VM to the list.
939 fn add_vm(&mut self, vm: Weak<VmInstance>) {
940 // Garbage collect any entries from the stored list which no longer exist.
941 self.vms.retain(|vm| vm.strong_count() > 0);
942
943 // Actually add the new VM.
944 self.vms.push(vm);
945 }
David Brazdil3c2ddef2021-03-18 13:09:57 +0000946
Jiyong Park8611a6c2021-07-09 18:17:44 +0900947 /// Get a VM that corresponds to the given cid
948 fn get_vm(&self, cid: Cid) -> Option<Arc<VmInstance>> {
949 self.vms().into_iter().find(|vm| vm.cid == cid)
950 }
951
David Brazdil3c2ddef2021-03-18 13:09:57 +0000952 /// Store a strong VM reference.
953 fn debug_hold_vm(&mut self, vm: Strong<dyn IVirtualMachine>) {
954 self.debug_held_vms.push(vm);
955 }
956
957 /// Retrieve and remove a strong VM reference.
958 fn debug_drop_vm(&mut self, cid: i32) -> Option<Strong<dyn IVirtualMachine>> {
959 let pos = self.debug_held_vms.iter().position(|vm| vm.getCid() == Ok(cid))?;
Alan Stokes7e54e292021-09-09 11:37:56 +0100960 let vm = self.debug_held_vms.swap_remove(pos);
Alan Stokes7e54e292021-09-09 11:37:56 +0100961 Some(vm)
David Brazdil3c2ddef2021-03-18 13:09:57 +0000962 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000963}
964
Jiyong Parkd50a0242021-09-16 21:00:14 +0900965/// Get the next available CID, or an error if we have run out. The last CID used is stored in
966/// a system property so that restart of virtualizationservice doesn't reuse CID while the host
967/// Android is up.
968fn next_cid() -> Result<Cid> {
Andrew Walbran014efb52022-02-03 17:43:11 +0000969 let next = if let Some(val) = system_properties::read(SYSPROP_LAST_CID)? {
Jiyong Parkd50a0242021-09-16 21:00:14 +0900970 if let Ok(num) = val.parse::<u32>() {
971 num.checked_add(1).ok_or_else(|| anyhow!("run out of CID"))?
972 } else {
973 error!("Invalid last CID {}. Using {}", &val, FIRST_GUEST_CID);
974 FIRST_GUEST_CID
975 }
976 } else {
977 // First VM since the boot
978 FIRST_GUEST_CID
979 };
980 // Persist the last value for next use
981 let str_val = format!("{}", next);
982 system_properties::write(SYSPROP_LAST_CID, &str_val)?;
983 Ok(next)
984}
985
Andrew Walbran6b650662021-09-07 13:13:23 +0000986/// Gets the `VirtualMachineState` of the given `VmInstance`.
987fn get_state(instance: &VmInstance) -> VirtualMachineState {
Andrew Walbranf8d94112021-09-07 11:45:36 +0000988 match &*instance.vm_state.lock().unwrap() {
989 VmState::NotStarted { .. } => VirtualMachineState::NOT_STARTED,
990 VmState::Running { .. } => match instance.payload_state() {
Andrew Walbran6b650662021-09-07 13:13:23 +0000991 PayloadState::Starting => VirtualMachineState::STARTING,
992 PayloadState::Started => VirtualMachineState::STARTED,
993 PayloadState::Ready => VirtualMachineState::READY,
994 PayloadState::Finished => VirtualMachineState::FINISHED,
Jiyong Parka4eebde2022-07-12 18:01:12 +0900995 PayloadState::Hangup => VirtualMachineState::DEAD,
Andrew Walbranf8d94112021-09-07 11:45:36 +0000996 },
997 VmState::Dead => VirtualMachineState::DEAD,
998 VmState::Failed => VirtualMachineState::DEAD,
Andrew Walbran6b650662021-09-07 13:13:23 +0000999 }
1000}
1001
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +00001002/// Converts a `&ParcelFileDescriptor` to a `File` by cloning the file.
Andrew Walbran806f1542021-06-10 14:07:12 +00001003fn clone_file(file: &ParcelFileDescriptor) -> Result<File, Status> {
1004 file.as_ref().try_clone().map_err(|e| {
1005 new_binder_exception(
1006 ExceptionCode::BAD_PARCELABLE,
1007 format!("Failed to clone File from ParcelFileDescriptor: {}", e),
1008 )
1009 })
1010}
1011
Andrew Walbrand3a84182021-09-07 14:48:52 +00001012/// Converts an `&Option<ParcelFileDescriptor>` to an `Option<File>` by cloning the file.
1013fn maybe_clone_file(file: &Option<ParcelFileDescriptor>) -> Result<Option<File>, Status> {
1014 file.as_ref().map(clone_file).transpose()
1015}
1016
Andrew Walbrancbe8b082021-08-06 15:42:11 +00001017/// Converts a `VsockStream` to a `ParcelFileDescriptor`.
1018fn vsock_stream_to_pfd(stream: VsockStream) -> ParcelFileDescriptor {
1019 // SAFETY: ownership is transferred from stream to f
1020 let f = unsafe { File::from_raw_fd(stream.into_raw_fd()) };
1021 ParcelFileDescriptor::new(f)
1022}
1023
Jiyong Parkdcf17412022-02-08 15:07:23 +09001024/// Parses the platform version requirement string.
1025fn parse_platform_version_req(s: &str) -> Result<VersionReq, Status> {
1026 VersionReq::parse(s).map_err(|e| {
1027 new_binder_exception(
1028 ExceptionCode::BAD_PARCELABLE,
1029 format!("Invalid platform version requirement {}: {}", s, e),
1030 )
1031 })
1032}
1033
Jooyung Han35edb8f2021-07-01 16:17:16 +09001034/// Simple utility for referencing Borrowed or Owned. Similar to std::borrow::Cow, but
1035/// it doesn't require that T implements Clone.
1036enum BorrowedOrOwned<'a, T> {
1037 Borrowed(&'a T),
1038 Owned(T),
1039}
1040
1041impl<'a, T> AsRef<T> for BorrowedOrOwned<'a, T> {
1042 fn as_ref(&self) -> &T {
1043 match self {
1044 Self::Borrowed(b) => b,
Chris Wailes68c39f82021-07-27 16:03:44 -07001045 Self::Owned(o) => o,
Jooyung Han35edb8f2021-07-01 16:17:16 +09001046 }
1047 }
1048}
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001049
1050/// Implementation of `IVirtualMachineService`, the entry point of the AIDL service.
1051#[derive(Debug, Default)]
1052struct VirtualMachineService {
1053 state: Arc<Mutex<State>>,
Inseob Kimc7d28c72021-10-25 14:28:10 +00001054 cid: Cid,
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001055}
1056
1057impl Interface for VirtualMachineService {}
1058
1059impl IVirtualMachineService for VirtualMachineService {
Inseob Kimc7d28c72021-10-25 14:28:10 +00001060 fn notifyPayloadStarted(&self) -> binder::Result<()> {
1061 let cid = self.cid;
Inseob Kim7f61fe72021-08-20 20:50:47 +09001062 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
1063 info!("VM having CID {} started payload", cid);
Andrew Walbran6b650662021-09-07 13:13:23 +00001064 vm.update_payload_state(PayloadState::Started)
1065 .map_err(|e| new_binder_exception(ExceptionCode::ILLEGAL_STATE, e.to_string()))?;
Inseob Kim7f61fe72021-08-20 20:50:47 +09001066 let stream = vm.stream.lock().unwrap().take();
1067 vm.callbacks.notify_payload_started(cid, stream);
1068 Ok(())
1069 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09001070 error!("notifyPayloadStarted is called from an unknown CID {}", cid);
Inseob Kim7f61fe72021-08-20 20:50:47 +09001071 Err(new_binder_exception(
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001072 ExceptionCode::SERVICE_SPECIFIC,
Jooyung Handd0a1732021-11-23 15:26:20 +09001073 format!("cannot find a VM with CID {}", cid),
Inseob Kim7f61fe72021-08-20 20:50:47 +09001074 ))
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001075 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001076 }
Inseob Kim2444af92021-08-31 01:22:50 +09001077
Inseob Kimc7d28c72021-10-25 14:28:10 +00001078 fn notifyPayloadReady(&self) -> binder::Result<()> {
1079 let cid = self.cid;
Inseob Kim14cb8692021-08-31 21:50:39 +09001080 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
1081 info!("VM having CID {} payload is ready", cid);
Andrew Walbran6b650662021-09-07 13:13:23 +00001082 vm.update_payload_state(PayloadState::Ready)
1083 .map_err(|e| new_binder_exception(ExceptionCode::ILLEGAL_STATE, e.to_string()))?;
Inseob Kim14cb8692021-08-31 21:50:39 +09001084 vm.callbacks.notify_payload_ready(cid);
1085 Ok(())
1086 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09001087 error!("notifyPayloadReady is called from an unknown CID {}", cid);
Inseob Kim14cb8692021-08-31 21:50:39 +09001088 Err(new_binder_exception(
1089 ExceptionCode::SERVICE_SPECIFIC,
Jooyung Handd0a1732021-11-23 15:26:20 +09001090 format!("cannot find a VM with CID {}", cid),
Inseob Kim14cb8692021-08-31 21:50:39 +09001091 ))
1092 }
1093 }
1094
Inseob Kimc7d28c72021-10-25 14:28:10 +00001095 fn notifyPayloadFinished(&self, exit_code: i32) -> binder::Result<()> {
1096 let cid = self.cid;
Inseob Kim2444af92021-08-31 01:22:50 +09001097 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
1098 info!("VM having CID {} finished payload", cid);
Andrew Walbran6b650662021-09-07 13:13:23 +00001099 vm.update_payload_state(PayloadState::Finished)
1100 .map_err(|e| new_binder_exception(ExceptionCode::ILLEGAL_STATE, e.to_string()))?;
Inseob Kim2444af92021-08-31 01:22:50 +09001101 vm.callbacks.notify_payload_finished(cid, exit_code);
1102 Ok(())
1103 } else {
Jooyung Handd0a1732021-11-23 15:26:20 +09001104 error!("notifyPayloadFinished is called from an unknown CID {}", cid);
Inseob Kim2444af92021-08-31 01:22:50 +09001105 Err(new_binder_exception(
1106 ExceptionCode::SERVICE_SPECIFIC,
Jooyung Handd0a1732021-11-23 15:26:20 +09001107 format!("cannot find a VM with CID {}", cid),
1108 ))
1109 }
1110 }
1111
1112 fn notifyError(&self, error_code: i32, message: &str) -> binder::Result<()> {
1113 let cid = self.cid;
1114 if let Some(vm) = self.state.lock().unwrap().get_vm(cid) {
1115 info!("VM having CID {} encountered an error", cid);
1116 vm.update_payload_state(PayloadState::Finished)
1117 .map_err(|e| new_binder_exception(ExceptionCode::ILLEGAL_STATE, e.to_string()))?;
1118 vm.callbacks.notify_error(cid, error_code, message);
1119 Ok(())
1120 } else {
Seungjae Yooec8c1602022-06-20 05:28:00 +00001121 error!("notifyError is called from an unknown CID {}", cid);
Jooyung Handd0a1732021-11-23 15:26:20 +09001122 Err(new_binder_exception(
1123 ExceptionCode::SERVICE_SPECIFIC,
1124 format!("cannot find a VM with CID {}", cid),
Inseob Kim2444af92021-08-31 01:22:50 +09001125 ))
1126 }
1127 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001128}
1129
1130impl VirtualMachineService {
Andrew Walbran0fd0ff02022-07-29 15:59:17 +00001131 fn factory(cid: Cid, state: &Arc<Mutex<State>>) -> Option<SpIBinder> {
Inseob Kimc7d28c72021-10-25 14:28:10 +00001132 if let Some(vm) = state.lock().unwrap().get_vm(cid) {
1133 let mut vm_service = vm.vm_service.lock().unwrap();
1134 let service = vm_service.get_or_insert_with(|| Self::new_binder(state.clone(), cid));
Andrew Walbran0fd0ff02022-07-29 15:59:17 +00001135 Some(service.as_binder())
Inseob Kimc7d28c72021-10-25 14:28:10 +00001136 } else {
1137 error!("connection from cid={} is not from a guest VM", cid);
Andrew Walbran0fd0ff02022-07-29 15:59:17 +00001138 None
Inseob Kimc7d28c72021-10-25 14:28:10 +00001139 }
1140 }
1141
1142 fn new_binder(state: Arc<Mutex<State>>, cid: Cid) -> Strong<dyn IVirtualMachineService> {
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001143 BnVirtualMachineService::new_binder(
Inseob Kimc7d28c72021-10-25 14:28:10 +00001144 VirtualMachineService { state, cid },
Inseob Kim1b95f2e2021-08-19 13:17:40 +09001145 BinderFeatures::default(),
1146 )
1147 }
1148}