blob: d99d63a00364055983796f8e893aa9ecf186f187 [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;
18use crate::crosvm::{CrosvmConfig, DiskFile, VmInstance};
Jooyung Han9900f3d2021-07-06 10:27:54 +090019use crate::payload::make_payload_disk;
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000020use crate::{Cid, FIRST_GUEST_CID};
Jooyung Han21e9b922021-06-26 04:14:16 +090021
Andrew Walbranf6bf6862021-05-21 12:41:13 +000022use android_system_virtualizationservice::aidl::android::system::virtualizationservice::IVirtualizationService::IVirtualizationService;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000023use android_system_virtualizationservice::aidl::android::system::virtualizationservice::DiskImage::DiskImage;
Andrew Walbranf6bf6862021-05-21 12:41:13 +000024use android_system_virtualizationservice::aidl::android::system::virtualizationservice::IVirtualMachine::{
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000025 BnVirtualMachine, IVirtualMachine,
26};
Andrew Walbranf6bf6862021-05-21 12:41:13 +000027use android_system_virtualizationservice::aidl::android::system::virtualizationservice::IVirtualMachineCallback::IVirtualMachineCallback;
Jooyung Han21e9b922021-06-26 04:14:16 +090028use android_system_virtualizationservice::aidl::android::system::virtualizationservice::{
29 VirtualMachineAppConfig::VirtualMachineAppConfig,
30 VirtualMachineConfig::VirtualMachineConfig,
31 VirtualMachineRawConfig::VirtualMachineRawConfig,
32};
Andrew Walbranf6bf6862021-05-21 12:41:13 +000033use android_system_virtualizationservice::aidl::android::system::virtualizationservice::VirtualMachineDebugInfo::VirtualMachineDebugInfo;
34use android_system_virtualizationservice::binder::{
Andrew Walbran806f1542021-06-10 14:07:12 +000035 self, BinderFeatures, ExceptionCode, Interface, ParcelFileDescriptor, Status, Strong, ThreadState,
Andrew Walbrana89fc132021-03-17 17:08:36 +000036};
Jooyung Han35edb8f2021-07-01 16:17:16 +090037use anyhow::{bail, Result};
Andrew Walbrandfc953d2021-06-10 13:59:56 +000038use disk::QcowFile;
Jiyong Park8611a6c2021-07-09 18:17:44 +090039use log::{debug, error, warn, info};
Jooyung Hanadfb76c2021-06-28 17:29:30 +090040use microdroid_payload_config::{ApexConfig, VmPayloadConfig};
Andrew Walbrandff3b942021-06-09 15:20:36 +000041use std::convert::TryInto;
Andrew Walbran806f1542021-06-10 14:07:12 +000042use std::ffi::CString;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000043use std::fs::{File, create_dir};
Andrew Walbranb15cd6e2021-07-05 16:38:07 +000044use std::num::NonZeroU32;
Jiyong Park8611a6c2021-07-09 18:17:44 +090045use std::os::unix::io::{AsRawFd, FromRawFd, IntoRawFd};
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000046use std::path::{Path, PathBuf};
Andrew Walbran320b5602021-03-04 16:11:12 +000047use std::sync::{Arc, Mutex, Weak};
Jiyong Park23601142021-07-05 13:15:32 +090048use vmconfig::{VmConfig, Partition};
Jiyong Park8611a6c2021-07-09 18:17:44 +090049use vsock::{VsockListener, SockAddr, VsockStream};
Jooyung Han35edb8f2021-07-01 16:17:16 +090050use zip::ZipArchive;
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000051
Andrew Walbranf6bf6862021-05-21 12:41:13 +000052pub const BINDER_SERVICE_IDENTIFIER: &str = "android.system.virtualizationservice";
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000053
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000054/// Directory in which to write disk image files used while running VMs.
Andrew Walbran488bd072021-07-14 13:29:51 +000055pub const TEMPORARY_DIRECTORY: &str = "/data/misc/virtualizationservice";
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000056
Andrew Walbran320b5602021-03-04 16:11:12 +000057// TODO(qwandor): Use PermissionController once it is available to Rust.
58/// Only processes running with one of these UIDs are allowed to call debug methods.
59const DEBUG_ALLOWED_UIDS: [u32; 2] = [0, 2000];
60
Jooyung Han35edb8f2021-07-01 16:17:16 +090061/// The list of APEXes which microdroid requires.
62/// TODO(b/192200378) move this to microdroid.json?
Jooyung Han1a72c6f2021-07-09 13:47:10 +090063const MICRODROID_REQUIRED_APEXES: [&str; 3] =
64 ["com.android.adbd", "com.android.i18n", "com.android.os.statsd"];
Jooyung Han35edb8f2021-07-01 16:17:16 +090065
Jiyong Park8611a6c2021-07-09 18:17:44 +090066/// The CID representing the host VM
67const VMADDR_CID_HOST: u32 = 2;
68
69/// Port number that virtualizationservice listens on connections from the guest VMs for the
70/// payload output
71const PORT_VIRT_SERVICE: u32 = 3000;
72
Andrew Walbranf6bf6862021-05-21 12:41:13 +000073/// Implementation of `IVirtualizationService`, the entry point of the AIDL service.
Jooyung Han9900f3d2021-07-06 10:27:54 +090074#[derive(Debug, Default)]
Andrew Walbranf6bf6862021-05-21 12:41:13 +000075pub struct VirtualizationService {
Jiyong Park8611a6c2021-07-09 18:17:44 +090076 state: Arc<Mutex<State>>,
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000077}
78
Andrew Walbranf6bf6862021-05-21 12:41:13 +000079impl Interface for VirtualizationService {}
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000080
Andrew Walbranf6bf6862021-05-21 12:41:13 +000081impl IVirtualizationService for VirtualizationService {
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000082 /// Create and start a new VM with the given configuration, assigning it the next available CID.
83 ///
84 /// Returns a binder `IVirtualMachine` object referring to it, as a handle for the client.
Andrew Walbrana89fc132021-03-17 17:08:36 +000085 fn startVm(
86 &self,
Andrew Walbran3a5a9212021-05-04 17:09:08 +000087 config: &VirtualMachineConfig,
Andrew Walbrana89fc132021-03-17 17:08:36 +000088 log_fd: Option<&ParcelFileDescriptor>,
89 ) -> binder::Result<Strong<dyn IVirtualMachine>> {
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000090 let state = &mut *self.state.lock().unwrap();
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000091 let log_fd = log_fd.map(clone_file).transpose()?;
Andrew Walbranf6a1eb92021-04-01 11:16:02 +000092 let requester_uid = ThreadState::get_calling_uid();
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000093 let requester_sid = get_calling_sid()?;
Andrew Walbran02034492021-04-13 15:05:07 +000094 let requester_debug_pid = ThreadState::get_calling_pid();
Andrew Walbrandae07162021-03-12 17:05:20 +000095 let cid = state.allocate_cid()?;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000096
97 // Counter to generate unique IDs for temporary image files.
98 let mut next_temporary_image_id = 0;
99 // Files which are referred to from composite images. These must be mapped to the crosvm
100 // child process, and not closed before it is started.
101 let mut indirect_files = vec![];
102
103 // Make directory for temporary files.
104 let temporary_directory: PathBuf = format!("{}/{}", TEMPORARY_DIRECTORY, cid).into();
105 create_dir(&temporary_directory).map_err(|e| {
106 error!(
Andrew Walbran806f1542021-06-10 14:07:12 +0000107 "Failed to create temporary directory {:?} for VM files: {}",
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000108 temporary_directory, e
109 );
Andrew Walbran806f1542021-06-10 14:07:12 +0000110 new_binder_exception(
111 ExceptionCode::SERVICE_SPECIFIC,
112 format!(
113 "Failed to create temporary directory {:?} for VM files: {}",
114 temporary_directory, e
115 ),
116 )
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000117 })?;
118
Jooyung Han21e9b922021-06-26 04:14:16 +0900119 let config = match config {
Jooyung Han35edb8f2021-07-01 16:17:16 +0900120 VirtualMachineConfig::AppConfig(config) => BorrowedOrOwned::Owned(
Jooyung Han9900f3d2021-07-06 10:27:54 +0900121 load_app_config(config, &temporary_directory).map_err(|e| {
122 error!("Failed to load app config from {}: {}", &config.configPath, e);
123 new_binder_exception(
124 ExceptionCode::SERVICE_SPECIFIC,
125 format!("Failed to load app config from {}: {}", &config.configPath, e),
126 )
127 })?,
Jooyung Han35edb8f2021-07-01 16:17:16 +0900128 ),
129 VirtualMachineConfig::RawConfig(config) => BorrowedOrOwned::Borrowed(config),
Jooyung Han21e9b922021-06-26 04:14:16 +0900130 };
Jooyung Han35edb8f2021-07-01 16:17:16 +0900131 let config = config.as_ref();
Jooyung Han21e9b922021-06-26 04:14:16 +0900132
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000133 // Assemble disk images if needed.
134 let disks = config
135 .disks
136 .iter()
137 .map(|disk| {
138 assemble_disk_image(
139 disk,
140 &temporary_directory,
141 &mut next_temporary_image_id,
142 &mut indirect_files,
143 )
144 })
145 .collect::<Result<Vec<DiskFile>, _>>()?;
146
147 // Actually start the VM.
148 let crosvm_config = CrosvmConfig {
Andrew Walbran02034492021-04-13 15:05:07 +0000149 cid,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000150 bootloader: as_asref(&config.bootloader),
151 kernel: as_asref(&config.kernel),
152 initrd: as_asref(&config.initrd),
153 disks,
154 params: config.params.to_owned(),
Andrew Walbranf8650422021-06-09 15:54:09 +0000155 protected: config.protected_vm,
Andrew Walbranb15cd6e2021-07-05 16:38:07 +0000156 memory_mib: config.memory_mib.try_into().ok().and_then(NonZeroU32::new),
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000157 };
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000158 let composite_disk_fds: Vec<_> =
159 indirect_files.iter().map(|file| file.as_raw_fd()).collect();
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000160 let instance = VmInstance::start(
161 &crosvm_config,
Andrew Walbran02034492021-04-13 15:05:07 +0000162 log_fd,
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000163 &composite_disk_fds,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000164 temporary_directory,
Andrew Walbran02034492021-04-13 15:05:07 +0000165 requester_uid,
166 requester_sid,
167 requester_debug_pid,
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000168 )
169 .map_err(|e| {
Andrew Walbran806f1542021-06-10 14:07:12 +0000170 error!("Failed to start VM with config {:?}: {}", config, e);
171 new_binder_exception(
172 ExceptionCode::SERVICE_SPECIFIC,
173 format!("Failed to start VM: {}", e),
174 )
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000175 })?;
Andrew Walbran320b5602021-03-04 16:11:12 +0000176 state.add_vm(Arc::downgrade(&instance));
177 Ok(VirtualMachine::create(instance))
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000178 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000179
Andrew Walbrandff3b942021-06-09 15:20:36 +0000180 /// Initialise an empty partition image of the given size to be used as a writable partition.
181 fn initializeWritablePartition(
182 &self,
183 image_fd: &ParcelFileDescriptor,
184 size: i64,
185 ) -> binder::Result<()> {
Andrew Walbrandfc953d2021-06-10 13:59:56 +0000186 let size = size.try_into().map_err(|e| {
Andrew Walbran806f1542021-06-10 14:07:12 +0000187 new_binder_exception(
188 ExceptionCode::ILLEGAL_ARGUMENT,
189 format!("Invalid size {}: {}", size, e),
190 )
Andrew Walbrandff3b942021-06-09 15:20:36 +0000191 })?;
Andrew Walbrandfc953d2021-06-10 13:59:56 +0000192 let image = clone_file(image_fd)?;
Andrew Walbrandff3b942021-06-09 15:20:36 +0000193
Andrew Walbrandfc953d2021-06-10 13:59:56 +0000194 QcowFile::new(image, size).map_err(|e| {
Andrew Walbran806f1542021-06-10 14:07:12 +0000195 new_binder_exception(
196 ExceptionCode::SERVICE_SPECIFIC,
197 format!("Failed to create QCOW2 image: {}", e),
198 )
Andrew Walbrandfc953d2021-06-10 13:59:56 +0000199 })?;
Andrew Walbrandff3b942021-06-09 15:20:36 +0000200
201 Ok(())
202 }
203
Andrew Walbran320b5602021-03-04 16:11:12 +0000204 /// Get a list of all currently running VMs. This method is only intended for debug purposes,
205 /// and as such is only permitted from the shell user.
206 fn debugListVms(&self) -> binder::Result<Vec<VirtualMachineDebugInfo>> {
Andrew Walbran806f1542021-06-10 14:07:12 +0000207 check_debug_access()?;
Andrew Walbran320b5602021-03-04 16:11:12 +0000208
209 let state = &mut *self.state.lock().unwrap();
210 let vms = state.vms();
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000211 let cids = vms
212 .into_iter()
213 .map(|vm| VirtualMachineDebugInfo {
214 cid: vm.cid as i32,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000215 temporaryDirectory: vm.temporary_directory.to_string_lossy().to_string(),
Andrew Walbran1ef19ae2021-04-07 11:31:57 +0000216 requesterUid: vm.requester_uid as i32,
217 requesterSid: vm.requester_sid.clone(),
Andrew Walbran02034492021-04-13 15:05:07 +0000218 requesterPid: vm.requester_debug_pid,
Andrew Walbrandae07162021-03-12 17:05:20 +0000219 running: vm.running(),
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000220 })
221 .collect();
Andrew Walbran320b5602021-03-04 16:11:12 +0000222 Ok(cids)
223 }
David Brazdil3c2ddef2021-03-18 13:09:57 +0000224
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000225 /// Hold a strong reference to a VM in VirtualizationService. This method is only intended for
226 /// debug purposes, and as such is only permitted from the shell user.
Andrei Homescu1415c132021-03-24 02:39:55 +0000227 fn debugHoldVmRef(&self, vmref: &Strong<dyn IVirtualMachine>) -> binder::Result<()> {
Andrew Walbran806f1542021-06-10 14:07:12 +0000228 check_debug_access()?;
David Brazdil3c2ddef2021-03-18 13:09:57 +0000229
David Brazdil3c2ddef2021-03-18 13:09:57 +0000230 let state = &mut *self.state.lock().unwrap();
Andrei Homescu1415c132021-03-24 02:39:55 +0000231 state.debug_hold_vm(vmref.clone());
David Brazdil3c2ddef2021-03-18 13:09:57 +0000232 Ok(())
233 }
234
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000235 /// Drop reference to a VM that is being held by VirtualizationService. Returns the reference if
236 /// the VM was found and None otherwise. This method is only intended for debug purposes, and as
237 /// such is only permitted from the shell user.
David Brazdil3c2ddef2021-03-18 13:09:57 +0000238 fn debugDropVmRef(&self, cid: i32) -> binder::Result<Option<Strong<dyn IVirtualMachine>>> {
Andrew Walbran806f1542021-06-10 14:07:12 +0000239 check_debug_access()?;
David Brazdil3c2ddef2021-03-18 13:09:57 +0000240
241 let state = &mut *self.state.lock().unwrap();
242 Ok(state.debug_drop_vm(cid))
243 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000244}
245
Jiyong Park8611a6c2021-07-09 18:17:44 +0900246impl VirtualizationService {
247 pub fn init() -> VirtualizationService {
248 let service = VirtualizationService::default();
249 let state = service.state.clone(); // reference to state (not the state itself) is copied
250 std::thread::spawn(move || {
251 handle_connection_from_vm(state).unwrap();
252 });
253 service
254 }
255}
256
257/// Waits for incoming connections from VM. If a new connection is made, notify the event to the
258/// client via the callback (if registered).
259fn handle_connection_from_vm(state: Arc<Mutex<State>>) -> Result<()> {
260 let listener = VsockListener::bind_with_cid_port(VMADDR_CID_HOST, PORT_VIRT_SERVICE)?;
261 for stream in listener.incoming() {
262 let stream = match stream {
263 Err(e) => {
264 warn!("invalid incoming connection: {}", e);
265 continue;
266 }
267 Ok(s) => s,
268 };
269 if let Ok(SockAddr::Vsock(addr)) = stream.peer_addr() {
270 let cid = addr.cid();
271 let port = addr.port();
272 info!("connected from cid={}, port={}", cid, port);
273 if cid < FIRST_GUEST_CID {
274 warn!("connection is not from a guest VM");
275 continue;
276 }
277 if let Some(vm) = state.lock().unwrap().get_vm(cid) {
278 vm.callbacks.notify_payload_started(cid, stream);
279 }
280 }
281 }
282 Ok(())
283}
284
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000285/// Given the configuration for a disk image, assembles the `DiskFile` to pass to crosvm.
286///
287/// This may involve assembling a composite disk from a set of partition images.
288fn assemble_disk_image(
289 disk: &DiskImage,
290 temporary_directory: &Path,
291 next_temporary_image_id: &mut u64,
292 indirect_files: &mut Vec<File>,
Andrew Walbran806f1542021-06-10 14:07:12 +0000293) -> Result<DiskFile, Status> {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000294 let image = if !disk.partitions.is_empty() {
295 if disk.image.is_some() {
296 warn!("DiskImage {:?} contains both image and partitions.", disk);
Andrew Walbran806f1542021-06-10 14:07:12 +0000297 return Err(new_binder_exception(
298 ExceptionCode::ILLEGAL_ARGUMENT,
299 "DiskImage contains both image and partitions.",
300 ));
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000301 }
302
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000303 let composite_image_filenames =
304 make_composite_image_filenames(temporary_directory, next_temporary_image_id);
305 let (image, partition_files) = make_composite_image(
306 &disk.partitions,
307 &composite_image_filenames.composite,
308 &composite_image_filenames.header,
309 &composite_image_filenames.footer,
310 )
311 .map_err(|e| {
312 error!("Failed to make composite image with config {:?}: {}", disk, e);
313 new_binder_exception(
314 ExceptionCode::SERVICE_SPECIFIC,
315 format!("Failed to make composite image: {}", e),
316 )
317 })?;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000318
319 // Pass the file descriptors for the various partition files to crosvm when it
320 // is run.
321 indirect_files.extend(partition_files);
322
323 image
324 } else if let Some(image) = &disk.image {
325 clone_file(image)?
326 } else {
327 warn!("DiskImage {:?} didn't contain image or partitions.", disk);
Andrew Walbran806f1542021-06-10 14:07:12 +0000328 return Err(new_binder_exception(
329 ExceptionCode::ILLEGAL_ARGUMENT,
330 "DiskImage didn't contain image or partitions.",
331 ));
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000332 };
333
334 Ok(DiskFile { image, writable: disk.writable })
335}
336
Jooyung Han21e9b922021-06-26 04:14:16 +0900337fn load_app_config(
338 config: &VirtualMachineAppConfig,
339 temporary_directory: &Path,
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900340) -> Result<VirtualMachineRawConfig> {
Jooyung Han21e9b922021-06-26 04:14:16 +0900341 let apk_file = config.apk.as_ref().unwrap().as_ref();
342 let idsig_file = config.idsig.as_ref().unwrap().as_ref();
343 let config_path = &config.configPath;
344
Jooyung Han35edb8f2021-07-01 16:17:16 +0900345 let mut apk_zip = ZipArchive::new(apk_file)?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900346 let config_file = apk_zip.by_name(config_path)?;
347 let vm_payload_config: VmPayloadConfig = serde_json::from_reader(config_file)?;
348
349 let os_name = &vm_payload_config.os.name;
Jooyung Han35edb8f2021-07-01 16:17:16 +0900350 // For now, the only supported "os" value is "microdroid"
351 if os_name != "microdroid" {
352 bail!("unknown os: {}", os_name);
353 }
Jooyung Han21e9b922021-06-26 04:14:16 +0900354 let vm_config_path = PathBuf::from(format!("/apex/com.android.virt/etc/{}.json", os_name));
355 let vm_config_file = File::open(vm_config_path)?;
356 let mut vm_config = VmConfig::load(&vm_config_file)?;
357
Jiyong Park23601142021-07-05 13:15:32 +0900358 // Microdroid requires additional payload disk image and the bootconfig partition
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900359 if os_name == "microdroid" {
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900360 let mut apexes = vm_payload_config.apexes.clone();
361 apexes.extend(
Jooyung Han35edb8f2021-07-01 16:17:16 +0900362 MICRODROID_REQUIRED_APEXES.iter().map(|name| ApexConfig { name: name.to_string() }),
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900363 );
364 apexes.dedup_by(|a, b| a.name == b.name);
365
Jooyung Han73bac242021-07-02 10:25:49 +0900366 vm_config.disks.push(make_payload_disk(
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900367 format!("/proc/self/fd/{}", apk_file.as_raw_fd()).into(),
368 format!("/proc/self/fd/{}", idsig_file.as_raw_fd()).into(),
369 config_path,
370 &apexes,
371 temporary_directory,
372 )?);
Jiyong Park23601142021-07-05 13:15:32 +0900373
374 if config.debug {
375 vm_config.disks[1].partitions.push(Partition {
376 label: "bootconfig".to_owned(),
377 paths: vec![PathBuf::from(
378 "/apex/com.android.virt/etc/microdroid_bootconfig.debug",
379 )],
380 writable: false,
381 });
382 }
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900383 }
Jooyung Han21e9b922021-06-26 04:14:16 +0900384
385 vm_config.to_parcelable()
386}
387
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000388/// Generates a unique filename to use for a composite disk image.
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000389fn make_composite_image_filenames(
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000390 temporary_directory: &Path,
391 next_temporary_image_id: &mut u64,
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000392) -> CompositeImageFilenames {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000393 let id = *next_temporary_image_id;
394 *next_temporary_image_id += 1;
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000395 CompositeImageFilenames {
396 composite: temporary_directory.join(format!("composite-{}.img", id)),
397 header: temporary_directory.join(format!("composite-{}-header.img", id)),
398 footer: temporary_directory.join(format!("composite-{}-footer.img", id)),
399 }
400}
401
402/// Filenames for a composite disk image, including header and footer partitions.
403#[derive(Clone, Debug, Eq, PartialEq)]
404struct CompositeImageFilenames {
405 /// The composite disk image itself.
406 composite: PathBuf,
407 /// The header partition image.
408 header: PathBuf,
409 /// The footer partition image.
410 footer: PathBuf,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000411}
412
413/// Gets the calling SID of the current Binder thread.
Andrew Walbran806f1542021-06-10 14:07:12 +0000414fn get_calling_sid() -> Result<String, Status> {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000415 ThreadState::with_calling_sid(|sid| {
416 if let Some(sid) = sid {
417 match sid.to_str() {
418 Ok(sid) => Ok(sid.to_owned()),
419 Err(e) => {
Andrew Walbran806f1542021-06-10 14:07:12 +0000420 error!("SID was not valid UTF-8: {}", e);
421 Err(new_binder_exception(
422 ExceptionCode::ILLEGAL_ARGUMENT,
423 format!("SID was not valid UTF-8: {}", e),
424 ))
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000425 }
426 }
427 } else {
428 error!("Missing SID on startVm");
Andrew Walbran806f1542021-06-10 14:07:12 +0000429 Err(new_binder_exception(ExceptionCode::SECURITY, "Missing SID on startVm"))
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000430 }
431 })
432}
433
Andrew Walbran320b5602021-03-04 16:11:12 +0000434/// Check whether the caller of the current Binder method is allowed to call debug methods.
Andrew Walbran806f1542021-06-10 14:07:12 +0000435fn check_debug_access() -> binder::Result<()> {
Andrew Walbran320b5602021-03-04 16:11:12 +0000436 let uid = ThreadState::get_calling_uid();
437 log::trace!("Debug method call from UID {}.", uid);
Andrew Walbran806f1542021-06-10 14:07:12 +0000438 if DEBUG_ALLOWED_UIDS.contains(&uid) {
439 Ok(())
440 } else {
441 Err(new_binder_exception(ExceptionCode::SECURITY, "Debug access denied"))
442 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000443}
444
445/// Implementation of the AIDL `IVirtualMachine` interface. Used as a handle to a VM.
446#[derive(Debug)]
447struct VirtualMachine {
448 instance: Arc<VmInstance>,
449}
450
451impl VirtualMachine {
452 fn create(instance: Arc<VmInstance>) -> Strong<dyn IVirtualMachine> {
453 let binder = VirtualMachine { instance };
Andrew Walbran4de28782021-04-13 14:51:43 +0000454 BnVirtualMachine::new_binder(binder, BinderFeatures::default())
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000455 }
456}
457
458impl Interface for VirtualMachine {}
459
460impl IVirtualMachine for VirtualMachine {
461 fn getCid(&self) -> binder::Result<i32> {
462 Ok(self.instance.cid as i32)
463 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000464
465 fn isRunning(&self) -> binder::Result<bool> {
466 Ok(self.instance.running())
467 }
468
469 fn registerCallback(
470 &self,
471 callback: &Strong<dyn IVirtualMachineCallback>,
472 ) -> binder::Result<()> {
473 // TODO: Should this give an error if the VM is already dead?
474 self.instance.callbacks.add(callback.clone());
475 Ok(())
476 }
477}
478
479impl Drop for VirtualMachine {
480 fn drop(&mut self) {
481 debug!("Dropping {:?}", self);
482 self.instance.kill();
483 }
484}
485
486/// A set of Binders to be called back in response to various events on the VM, such as when it
487/// dies.
488#[derive(Debug, Default)]
489pub struct VirtualMachineCallbacks(Mutex<Vec<Strong<dyn IVirtualMachineCallback>>>);
490
491impl VirtualMachineCallbacks {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900492 /// Call all registered callbacks to notify that the payload has started.
493 pub fn notify_payload_started(&self, cid: Cid, stream: VsockStream) {
494 let callbacks = &*self.0.lock().unwrap();
495 // SAFETY: ownership is transferred from stream to f
496 let f = unsafe { File::from_raw_fd(stream.into_raw_fd()) };
497 let pfd = ParcelFileDescriptor::new(f);
498 for callback in callbacks {
499 if let Err(e) = callback.onPayloadStarted(cid as i32, &pfd) {
500 error!("Error notifying payload start event from VM CID {}: {}", cid, e);
501 }
502 }
503 }
504
Andrew Walbrandae07162021-03-12 17:05:20 +0000505 /// Call all registered callbacks to say that the VM has died.
506 pub fn callback_on_died(&self, cid: Cid) {
507 let callbacks = &*self.0.lock().unwrap();
508 for callback in callbacks {
509 if let Err(e) = callback.onDied(cid as i32) {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900510 error!("Error notifying exit of VM CID {}: {}", cid, e);
Andrew Walbrandae07162021-03-12 17:05:20 +0000511 }
512 }
513 }
514
515 /// Add a new callback to the set.
516 fn add(&self, callback: Strong<dyn IVirtualMachineCallback>) {
517 self.0.lock().unwrap().push(callback);
518 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000519}
520
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000521/// The mutable state of the VirtualizationService. There should only be one instance of this
522/// struct.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000523#[derive(Debug)]
524struct State {
Andrew Walbran320b5602021-03-04 16:11:12 +0000525 /// The next available unused CID.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000526 next_cid: Cid,
Andrew Walbran320b5602021-03-04 16:11:12 +0000527
528 /// The VMs which have been started. When VMs are started a weak reference is added to this list
529 /// while a strong reference is returned to the caller over Binder. Once all copies of the
530 /// Binder client are dropped the weak reference here will become invalid, and will be removed
531 /// from the list opportunistically the next time `add_vm` is called.
532 vms: Vec<Weak<VmInstance>>,
David Brazdil3c2ddef2021-03-18 13:09:57 +0000533
534 /// Vector of strong VM references held on behalf of users that cannot hold them themselves.
535 /// This is only used for debugging purposes.
536 debug_held_vms: Vec<Strong<dyn IVirtualMachine>>,
Andrew Walbran320b5602021-03-04 16:11:12 +0000537}
538
539impl State {
Andrew Walbrandae07162021-03-12 17:05:20 +0000540 /// Get a list of VMs which still have Binder references to them.
Andrew Walbran320b5602021-03-04 16:11:12 +0000541 fn vms(&self) -> Vec<Arc<VmInstance>> {
542 // Attempt to upgrade the weak pointers to strong pointers.
543 self.vms.iter().filter_map(Weak::upgrade).collect()
544 }
545
546 /// Add a new VM to the list.
547 fn add_vm(&mut self, vm: Weak<VmInstance>) {
548 // Garbage collect any entries from the stored list which no longer exist.
549 self.vms.retain(|vm| vm.strong_count() > 0);
550
551 // Actually add the new VM.
552 self.vms.push(vm);
553 }
David Brazdil3c2ddef2021-03-18 13:09:57 +0000554
Jiyong Park8611a6c2021-07-09 18:17:44 +0900555 /// Get a VM that corresponds to the given cid
556 fn get_vm(&self, cid: Cid) -> Option<Arc<VmInstance>> {
557 self.vms().into_iter().find(|vm| vm.cid == cid)
558 }
559
David Brazdil3c2ddef2021-03-18 13:09:57 +0000560 /// Store a strong VM reference.
561 fn debug_hold_vm(&mut self, vm: Strong<dyn IVirtualMachine>) {
562 self.debug_held_vms.push(vm);
563 }
564
565 /// Retrieve and remove a strong VM reference.
566 fn debug_drop_vm(&mut self, cid: i32) -> Option<Strong<dyn IVirtualMachine>> {
567 let pos = self.debug_held_vms.iter().position(|vm| vm.getCid() == Ok(cid))?;
568 Some(self.debug_held_vms.swap_remove(pos))
569 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000570
571 /// Get the next available CID, or an error if we have run out.
572 fn allocate_cid(&mut self) -> binder::Result<Cid> {
573 // TODO(qwandor): keep track of which CIDs are currently in use so that we can reuse them.
574 let cid = self.next_cid;
Andrew Walbran806f1542021-06-10 14:07:12 +0000575 self.next_cid = self.next_cid.checked_add(1).ok_or(ExceptionCode::ILLEGAL_STATE)?;
Andrew Walbrandae07162021-03-12 17:05:20 +0000576 Ok(cid)
577 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000578}
579
580impl Default for State {
581 fn default() -> Self {
David Brazdil3c2ddef2021-03-18 13:09:57 +0000582 State { next_cid: FIRST_GUEST_CID, vms: vec![], debug_held_vms: vec![] }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000583 }
584}
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000585
586/// Converts an `&Option<T>` to an `Option<U>` where `T` implements `AsRef<U>`.
587fn as_asref<T: AsRef<U>, U>(option: &Option<T>) -> Option<&U> {
588 option.as_ref().map(|t| t.as_ref())
589}
590
591/// Converts a `&ParcelFileDescriptor` to a `File` by cloning the file.
Andrew Walbran806f1542021-06-10 14:07:12 +0000592fn clone_file(file: &ParcelFileDescriptor) -> Result<File, Status> {
593 file.as_ref().try_clone().map_err(|e| {
594 new_binder_exception(
595 ExceptionCode::BAD_PARCELABLE,
596 format!("Failed to clone File from ParcelFileDescriptor: {}", e),
597 )
598 })
599}
600
601/// Constructs a new Binder error `Status` with the given `ExceptionCode` and message.
602fn new_binder_exception<T: AsRef<str>>(exception: ExceptionCode, message: T) -> Status {
603 Status::new_exception(exception, CString::new(message.as_ref()).ok().as_deref())
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000604}
Jooyung Han35edb8f2021-07-01 16:17:16 +0900605
606/// Simple utility for referencing Borrowed or Owned. Similar to std::borrow::Cow, but
607/// it doesn't require that T implements Clone.
608enum BorrowedOrOwned<'a, T> {
609 Borrowed(&'a T),
610 Owned(T),
611}
612
613impl<'a, T> AsRef<T> for BorrowedOrOwned<'a, T> {
614 fn as_ref(&self) -> &T {
615 match self {
616 Self::Borrowed(b) => b,
617 Self::Owned(o) => &o,
618 }
619 }
620}