blob: 12c46ee0d5a0f0962b8305a4cfb5c8f8c4f40e23 [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
Jiyong Park753553b2021-07-12 21:21:09 +090022use android_os_permissions_aidl::aidl::android::os::IPermissionController;
Andrew Walbranf6bf6862021-05-21 12:41:13 +000023use android_system_virtualizationservice::aidl::android::system::virtualizationservice::IVirtualizationService::IVirtualizationService;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000024use android_system_virtualizationservice::aidl::android::system::virtualizationservice::DiskImage::DiskImage;
Andrew Walbranf6bf6862021-05-21 12:41:13 +000025use android_system_virtualizationservice::aidl::android::system::virtualizationservice::IVirtualMachine::{
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000026 BnVirtualMachine, IVirtualMachine,
27};
Andrew Walbranf6bf6862021-05-21 12:41:13 +000028use android_system_virtualizationservice::aidl::android::system::virtualizationservice::IVirtualMachineCallback::IVirtualMachineCallback;
Jooyung Han21e9b922021-06-26 04:14:16 +090029use android_system_virtualizationservice::aidl::android::system::virtualizationservice::{
30 VirtualMachineAppConfig::VirtualMachineAppConfig,
31 VirtualMachineConfig::VirtualMachineConfig,
32 VirtualMachineRawConfig::VirtualMachineRawConfig,
33};
Andrew Walbranf6bf6862021-05-21 12:41:13 +000034use android_system_virtualizationservice::aidl::android::system::virtualizationservice::VirtualMachineDebugInfo::VirtualMachineDebugInfo;
35use android_system_virtualizationservice::binder::{
Andrew Walbran806f1542021-06-10 14:07:12 +000036 self, BinderFeatures, ExceptionCode, Interface, ParcelFileDescriptor, Status, Strong, ThreadState,
Andrew Walbrana89fc132021-03-17 17:08:36 +000037};
Jooyung Han95884632021-07-06 22:27:54 +090038use anyhow::{bail, Context, Result};
Andrew Walbrandfc953d2021-06-10 13:59:56 +000039use disk::QcowFile;
Jiyong Park8611a6c2021-07-09 18:17:44 +090040use log::{debug, error, warn, info};
Jooyung Hanadfb76c2021-06-28 17:29:30 +090041use microdroid_payload_config::{ApexConfig, VmPayloadConfig};
Andrew Walbrandff3b942021-06-09 15:20:36 +000042use std::convert::TryInto;
Andrew Walbran806f1542021-06-10 14:07:12 +000043use std::ffi::CString;
Jooyung Han95884632021-07-06 22:27:54 +090044use std::fs::{File, OpenOptions, create_dir};
Andrew Walbranb15cd6e2021-07-05 16:38:07 +000045use std::num::NonZeroU32;
Jiyong Park8611a6c2021-07-09 18:17:44 +090046use std::os::unix::io::{AsRawFd, FromRawFd, IntoRawFd};
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000047use std::path::{Path, PathBuf};
Andrew Walbran320b5602021-03-04 16:11:12 +000048use std::sync::{Arc, Mutex, Weak};
Jiyong Park23601142021-07-05 13:15:32 +090049use vmconfig::{VmConfig, Partition};
Jiyong Park8611a6c2021-07-09 18:17:44 +090050use vsock::{VsockListener, SockAddr, VsockStream};
Jooyung Han35edb8f2021-07-01 16:17:16 +090051use zip::ZipArchive;
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000052
Andrew Walbranf6bf6862021-05-21 12:41:13 +000053pub const BINDER_SERVICE_IDENTIFIER: &str = "android.system.virtualizationservice";
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000054
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000055/// Directory in which to write disk image files used while running VMs.
Andrew Walbran488bd072021-07-14 13:29:51 +000056pub const TEMPORARY_DIRECTORY: &str = "/data/misc/virtualizationservice";
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000057
Jooyung Han35edb8f2021-07-01 16:17:16 +090058/// The list of APEXes which microdroid requires.
59/// TODO(b/192200378) move this to microdroid.json?
Jooyung Han1a72c6f2021-07-09 13:47:10 +090060const MICRODROID_REQUIRED_APEXES: [&str; 3] =
61 ["com.android.adbd", "com.android.i18n", "com.android.os.statsd"];
Jooyung Han35edb8f2021-07-01 16:17:16 +090062
Jiyong Park8611a6c2021-07-09 18:17:44 +090063/// The CID representing the host VM
64const VMADDR_CID_HOST: u32 = 2;
65
66/// Port number that virtualizationservice listens on connections from the guest VMs for the
67/// payload output
68const PORT_VIRT_SERVICE: u32 = 3000;
69
Jooyung Han95884632021-07-06 22:27:54 +090070/// The size of zero.img.
71/// Gaps in composite disk images are filled with a shared zero.img.
72const ZERO_FILLER_SIZE: u64 = 4096;
73
Andrew Walbranf6bf6862021-05-21 12:41:13 +000074/// Implementation of `IVirtualizationService`, the entry point of the AIDL service.
Jooyung Han9900f3d2021-07-06 10:27:54 +090075#[derive(Debug, Default)]
Andrew Walbranf6bf6862021-05-21 12:41:13 +000076pub struct VirtualizationService {
Jiyong Park8611a6c2021-07-09 18:17:44 +090077 state: Arc<Mutex<State>>,
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000078}
79
Andrew Walbranf6bf6862021-05-21 12:41:13 +000080impl Interface for VirtualizationService {}
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000081
Andrew Walbranf6bf6862021-05-21 12:41:13 +000082impl IVirtualizationService for VirtualizationService {
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000083 /// Create and start a new VM with the given configuration, assigning it the next available CID.
84 ///
85 /// Returns a binder `IVirtualMachine` object referring to it, as a handle for the client.
Andrew Walbrana89fc132021-03-17 17:08:36 +000086 fn startVm(
87 &self,
Andrew Walbran3a5a9212021-05-04 17:09:08 +000088 config: &VirtualMachineConfig,
Andrew Walbrana89fc132021-03-17 17:08:36 +000089 log_fd: Option<&ParcelFileDescriptor>,
90 ) -> binder::Result<Strong<dyn IVirtualMachine>> {
Jiyong Park753553b2021-07-12 21:21:09 +090091 check_manage_access()?;
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000092 let state = &mut *self.state.lock().unwrap();
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000093 let log_fd = log_fd.map(clone_file).transpose()?;
Andrew Walbranf6a1eb92021-04-01 11:16:02 +000094 let requester_uid = ThreadState::get_calling_uid();
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000095 let requester_sid = get_calling_sid()?;
Andrew Walbran02034492021-04-13 15:05:07 +000096 let requester_debug_pid = ThreadState::get_calling_pid();
Andrew Walbrandae07162021-03-12 17:05:20 +000097 let cid = state.allocate_cid()?;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000098
99 // Counter to generate unique IDs for temporary image files.
100 let mut next_temporary_image_id = 0;
101 // Files which are referred to from composite images. These must be mapped to the crosvm
102 // child process, and not closed before it is started.
103 let mut indirect_files = vec![];
104
105 // Make directory for temporary files.
106 let temporary_directory: PathBuf = format!("{}/{}", TEMPORARY_DIRECTORY, cid).into();
107 create_dir(&temporary_directory).map_err(|e| {
108 error!(
Andrew Walbran806f1542021-06-10 14:07:12 +0000109 "Failed to create temporary directory {:?} for VM files: {}",
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000110 temporary_directory, e
111 );
Andrew Walbran806f1542021-06-10 14:07:12 +0000112 new_binder_exception(
113 ExceptionCode::SERVICE_SPECIFIC,
114 format!(
115 "Failed to create temporary directory {:?} for VM files: {}",
116 temporary_directory, e
117 ),
118 )
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000119 })?;
120
Jooyung Han21e9b922021-06-26 04:14:16 +0900121 let config = match config {
Jooyung Han35edb8f2021-07-01 16:17:16 +0900122 VirtualMachineConfig::AppConfig(config) => BorrowedOrOwned::Owned(
Jooyung Han9900f3d2021-07-06 10:27:54 +0900123 load_app_config(config, &temporary_directory).map_err(|e| {
124 error!("Failed to load app config from {}: {}", &config.configPath, e);
125 new_binder_exception(
126 ExceptionCode::SERVICE_SPECIFIC,
127 format!("Failed to load app config from {}: {}", &config.configPath, e),
128 )
129 })?,
Jooyung Han35edb8f2021-07-01 16:17:16 +0900130 ),
131 VirtualMachineConfig::RawConfig(config) => BorrowedOrOwned::Borrowed(config),
Jooyung Han21e9b922021-06-26 04:14:16 +0900132 };
Jooyung Han35edb8f2021-07-01 16:17:16 +0900133 let config = config.as_ref();
Jooyung Han21e9b922021-06-26 04:14:16 +0900134
Jooyung Han95884632021-07-06 22:27:54 +0900135 let zero_filler_path = temporary_directory.join("zero.img");
136 let zero_filler_file = write_zero_filler(&zero_filler_path).map_err(|e| {
137 error!("Failed to make composite image: {}", e);
138 new_binder_exception(
139 ExceptionCode::SERVICE_SPECIFIC,
140 format!("Failed to make composite image: {}", e),
141 )
142 })?;
143 indirect_files.push(zero_filler_file);
144
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000145 // Assemble disk images if needed.
146 let disks = config
147 .disks
148 .iter()
149 .map(|disk| {
150 assemble_disk_image(
151 disk,
Jooyung Han95884632021-07-06 22:27:54 +0900152 &zero_filler_path,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000153 &temporary_directory,
154 &mut next_temporary_image_id,
155 &mut indirect_files,
156 )
157 })
158 .collect::<Result<Vec<DiskFile>, _>>()?;
159
160 // Actually start the VM.
161 let crosvm_config = CrosvmConfig {
Andrew Walbran02034492021-04-13 15:05:07 +0000162 cid,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000163 bootloader: as_asref(&config.bootloader),
164 kernel: as_asref(&config.kernel),
165 initrd: as_asref(&config.initrd),
166 disks,
167 params: config.params.to_owned(),
Andrew Walbranf8650422021-06-09 15:54:09 +0000168 protected: config.protected_vm,
Andrew Walbranb15cd6e2021-07-05 16:38:07 +0000169 memory_mib: config.memory_mib.try_into().ok().and_then(NonZeroU32::new),
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000170 };
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000171 let composite_disk_fds: Vec<_> =
172 indirect_files.iter().map(|file| file.as_raw_fd()).collect();
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000173 let instance = VmInstance::start(
174 &crosvm_config,
Andrew Walbran02034492021-04-13 15:05:07 +0000175 log_fd,
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000176 &composite_disk_fds,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000177 temporary_directory,
Andrew Walbran02034492021-04-13 15:05:07 +0000178 requester_uid,
179 requester_sid,
180 requester_debug_pid,
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000181 )
182 .map_err(|e| {
Andrew Walbran806f1542021-06-10 14:07:12 +0000183 error!("Failed to start VM with config {:?}: {}", config, e);
184 new_binder_exception(
185 ExceptionCode::SERVICE_SPECIFIC,
186 format!("Failed to start VM: {}", e),
187 )
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000188 })?;
Andrew Walbran320b5602021-03-04 16:11:12 +0000189 state.add_vm(Arc::downgrade(&instance));
190 Ok(VirtualMachine::create(instance))
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000191 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000192
Andrew Walbrandff3b942021-06-09 15:20:36 +0000193 /// Initialise an empty partition image of the given size to be used as a writable partition.
194 fn initializeWritablePartition(
195 &self,
196 image_fd: &ParcelFileDescriptor,
197 size: i64,
198 ) -> binder::Result<()> {
Jiyong Park753553b2021-07-12 21:21:09 +0900199 check_manage_access()?;
Andrew Walbrandfc953d2021-06-10 13:59:56 +0000200 let size = size.try_into().map_err(|e| {
Andrew Walbran806f1542021-06-10 14:07:12 +0000201 new_binder_exception(
202 ExceptionCode::ILLEGAL_ARGUMENT,
203 format!("Invalid size {}: {}", size, e),
204 )
Andrew Walbrandff3b942021-06-09 15:20:36 +0000205 })?;
Andrew Walbrandfc953d2021-06-10 13:59:56 +0000206 let image = clone_file(image_fd)?;
Andrew Walbrandff3b942021-06-09 15:20:36 +0000207
Andrew Walbrandfc953d2021-06-10 13:59:56 +0000208 QcowFile::new(image, size).map_err(|e| {
Andrew Walbran806f1542021-06-10 14:07:12 +0000209 new_binder_exception(
210 ExceptionCode::SERVICE_SPECIFIC,
211 format!("Failed to create QCOW2 image: {}", e),
212 )
Andrew Walbrandfc953d2021-06-10 13:59:56 +0000213 })?;
Andrew Walbrandff3b942021-06-09 15:20:36 +0000214
215 Ok(())
216 }
217
Andrew Walbran320b5602021-03-04 16:11:12 +0000218 /// Get a list of all currently running VMs. This method is only intended for debug purposes,
219 /// and as such is only permitted from the shell user.
220 fn debugListVms(&self) -> binder::Result<Vec<VirtualMachineDebugInfo>> {
Andrew Walbran806f1542021-06-10 14:07:12 +0000221 check_debug_access()?;
Andrew Walbran320b5602021-03-04 16:11:12 +0000222
223 let state = &mut *self.state.lock().unwrap();
224 let vms = state.vms();
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000225 let cids = vms
226 .into_iter()
227 .map(|vm| VirtualMachineDebugInfo {
228 cid: vm.cid as i32,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000229 temporaryDirectory: vm.temporary_directory.to_string_lossy().to_string(),
Andrew Walbran1ef19ae2021-04-07 11:31:57 +0000230 requesterUid: vm.requester_uid as i32,
231 requesterSid: vm.requester_sid.clone(),
Andrew Walbran02034492021-04-13 15:05:07 +0000232 requesterPid: vm.requester_debug_pid,
Andrew Walbrandae07162021-03-12 17:05:20 +0000233 running: vm.running(),
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000234 })
235 .collect();
Andrew Walbran320b5602021-03-04 16:11:12 +0000236 Ok(cids)
237 }
David Brazdil3c2ddef2021-03-18 13:09:57 +0000238
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000239 /// Hold a strong reference to a VM in VirtualizationService. This method is only intended for
240 /// debug purposes, and as such is only permitted from the shell user.
Andrei Homescu1415c132021-03-24 02:39:55 +0000241 fn debugHoldVmRef(&self, vmref: &Strong<dyn IVirtualMachine>) -> binder::Result<()> {
Andrew Walbran806f1542021-06-10 14:07:12 +0000242 check_debug_access()?;
David Brazdil3c2ddef2021-03-18 13:09:57 +0000243
David Brazdil3c2ddef2021-03-18 13:09:57 +0000244 let state = &mut *self.state.lock().unwrap();
Andrei Homescu1415c132021-03-24 02:39:55 +0000245 state.debug_hold_vm(vmref.clone());
David Brazdil3c2ddef2021-03-18 13:09:57 +0000246 Ok(())
247 }
248
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000249 /// Drop reference to a VM that is being held by VirtualizationService. Returns the reference if
250 /// the VM was found and None otherwise. This method is only intended for debug purposes, and as
251 /// such is only permitted from the shell user.
David Brazdil3c2ddef2021-03-18 13:09:57 +0000252 fn debugDropVmRef(&self, cid: i32) -> binder::Result<Option<Strong<dyn IVirtualMachine>>> {
Andrew Walbran806f1542021-06-10 14:07:12 +0000253 check_debug_access()?;
David Brazdil3c2ddef2021-03-18 13:09:57 +0000254
255 let state = &mut *self.state.lock().unwrap();
256 Ok(state.debug_drop_vm(cid))
257 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000258}
259
Jiyong Park8611a6c2021-07-09 18:17:44 +0900260impl VirtualizationService {
261 pub fn init() -> VirtualizationService {
262 let service = VirtualizationService::default();
263 let state = service.state.clone(); // reference to state (not the state itself) is copied
264 std::thread::spawn(move || {
265 handle_connection_from_vm(state).unwrap();
266 });
267 service
268 }
269}
270
271/// Waits for incoming connections from VM. If a new connection is made, notify the event to the
272/// client via the callback (if registered).
273fn handle_connection_from_vm(state: Arc<Mutex<State>>) -> Result<()> {
274 let listener = VsockListener::bind_with_cid_port(VMADDR_CID_HOST, PORT_VIRT_SERVICE)?;
275 for stream in listener.incoming() {
276 let stream = match stream {
277 Err(e) => {
278 warn!("invalid incoming connection: {}", e);
279 continue;
280 }
281 Ok(s) => s,
282 };
283 if let Ok(SockAddr::Vsock(addr)) = stream.peer_addr() {
284 let cid = addr.cid();
285 let port = addr.port();
286 info!("connected from cid={}, port={}", cid, port);
287 if cid < FIRST_GUEST_CID {
288 warn!("connection is not from a guest VM");
289 continue;
290 }
291 if let Some(vm) = state.lock().unwrap().get_vm(cid) {
292 vm.callbacks.notify_payload_started(cid, stream);
293 }
294 }
295 }
296 Ok(())
297}
298
Jooyung Han95884632021-07-06 22:27:54 +0900299fn write_zero_filler(zero_filler_path: &Path) -> Result<File> {
300 let file = OpenOptions::new()
301 .create_new(true)
302 .read(true)
303 .write(true)
304 .open(zero_filler_path)
305 .with_context(|| "Failed to create zero.img")?;
306 file.set_len(ZERO_FILLER_SIZE)?;
307 Ok(file)
308}
309
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000310/// Given the configuration for a disk image, assembles the `DiskFile` to pass to crosvm.
311///
312/// This may involve assembling a composite disk from a set of partition images.
313fn assemble_disk_image(
314 disk: &DiskImage,
Jooyung Han95884632021-07-06 22:27:54 +0900315 zero_filler_path: &Path,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000316 temporary_directory: &Path,
317 next_temporary_image_id: &mut u64,
318 indirect_files: &mut Vec<File>,
Andrew Walbran806f1542021-06-10 14:07:12 +0000319) -> Result<DiskFile, Status> {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000320 let image = if !disk.partitions.is_empty() {
321 if disk.image.is_some() {
322 warn!("DiskImage {:?} contains both image and partitions.", disk);
Andrew Walbran806f1542021-06-10 14:07:12 +0000323 return Err(new_binder_exception(
324 ExceptionCode::ILLEGAL_ARGUMENT,
325 "DiskImage contains both image and partitions.",
326 ));
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000327 }
328
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000329 let composite_image_filenames =
330 make_composite_image_filenames(temporary_directory, next_temporary_image_id);
331 let (image, partition_files) = make_composite_image(
332 &disk.partitions,
Jooyung Han95884632021-07-06 22:27:54 +0900333 zero_filler_path,
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000334 &composite_image_filenames.composite,
335 &composite_image_filenames.header,
336 &composite_image_filenames.footer,
337 )
338 .map_err(|e| {
339 error!("Failed to make composite image with config {:?}: {}", disk, e);
340 new_binder_exception(
341 ExceptionCode::SERVICE_SPECIFIC,
342 format!("Failed to make composite image: {}", e),
343 )
344 })?;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000345
346 // Pass the file descriptors for the various partition files to crosvm when it
347 // is run.
348 indirect_files.extend(partition_files);
349
350 image
351 } else if let Some(image) = &disk.image {
352 clone_file(image)?
353 } else {
354 warn!("DiskImage {:?} didn't contain image or partitions.", disk);
Andrew Walbran806f1542021-06-10 14:07:12 +0000355 return Err(new_binder_exception(
356 ExceptionCode::ILLEGAL_ARGUMENT,
357 "DiskImage didn't contain image or partitions.",
358 ));
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000359 };
360
361 Ok(DiskFile { image, writable: disk.writable })
362}
363
Jooyung Han21e9b922021-06-26 04:14:16 +0900364fn load_app_config(
365 config: &VirtualMachineAppConfig,
366 temporary_directory: &Path,
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900367) -> Result<VirtualMachineRawConfig> {
Jooyung Han21e9b922021-06-26 04:14:16 +0900368 let apk_file = config.apk.as_ref().unwrap().as_ref();
369 let idsig_file = config.idsig.as_ref().unwrap().as_ref();
Jiyong Park48b354d2021-07-15 15:04:38 +0900370 // TODO(b/193504400) pass this to crosvm
371 let _instance_file = config.instanceImage.as_ref().unwrap().as_ref();
Jooyung Han21e9b922021-06-26 04:14:16 +0900372 let config_path = &config.configPath;
373
Jooyung Han35edb8f2021-07-01 16:17:16 +0900374 let mut apk_zip = ZipArchive::new(apk_file)?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900375 let config_file = apk_zip.by_name(config_path)?;
376 let vm_payload_config: VmPayloadConfig = serde_json::from_reader(config_file)?;
377
378 let os_name = &vm_payload_config.os.name;
Jooyung Han35edb8f2021-07-01 16:17:16 +0900379 // For now, the only supported "os" value is "microdroid"
380 if os_name != "microdroid" {
381 bail!("unknown os: {}", os_name);
382 }
Jooyung Han21e9b922021-06-26 04:14:16 +0900383 let vm_config_path = PathBuf::from(format!("/apex/com.android.virt/etc/{}.json", os_name));
384 let vm_config_file = File::open(vm_config_path)?;
385 let mut vm_config = VmConfig::load(&vm_config_file)?;
386
Jiyong Park23601142021-07-05 13:15:32 +0900387 // Microdroid requires additional payload disk image and the bootconfig partition
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900388 if os_name == "microdroid" {
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900389 let mut apexes = vm_payload_config.apexes.clone();
390 apexes.extend(
Jooyung Han35edb8f2021-07-01 16:17:16 +0900391 MICRODROID_REQUIRED_APEXES.iter().map(|name| ApexConfig { name: name.to_string() }),
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900392 );
393 apexes.dedup_by(|a, b| a.name == b.name);
394
Jooyung Han73bac242021-07-02 10:25:49 +0900395 vm_config.disks.push(make_payload_disk(
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900396 format!("/proc/self/fd/{}", apk_file.as_raw_fd()).into(),
397 format!("/proc/self/fd/{}", idsig_file.as_raw_fd()).into(),
398 config_path,
399 &apexes,
400 temporary_directory,
401 )?);
Jiyong Park23601142021-07-05 13:15:32 +0900402
403 if config.debug {
404 vm_config.disks[1].partitions.push(Partition {
405 label: "bootconfig".to_owned(),
406 paths: vec![PathBuf::from(
407 "/apex/com.android.virt/etc/microdroid_bootconfig.debug",
408 )],
409 writable: false,
410 });
411 }
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900412 }
Jooyung Han21e9b922021-06-26 04:14:16 +0900413
414 vm_config.to_parcelable()
415}
416
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000417/// Generates a unique filename to use for a composite disk image.
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000418fn make_composite_image_filenames(
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000419 temporary_directory: &Path,
420 next_temporary_image_id: &mut u64,
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000421) -> CompositeImageFilenames {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000422 let id = *next_temporary_image_id;
423 *next_temporary_image_id += 1;
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000424 CompositeImageFilenames {
425 composite: temporary_directory.join(format!("composite-{}.img", id)),
426 header: temporary_directory.join(format!("composite-{}-header.img", id)),
427 footer: temporary_directory.join(format!("composite-{}-footer.img", id)),
428 }
429}
430
431/// Filenames for a composite disk image, including header and footer partitions.
432#[derive(Clone, Debug, Eq, PartialEq)]
433struct CompositeImageFilenames {
434 /// The composite disk image itself.
435 composite: PathBuf,
436 /// The header partition image.
437 header: PathBuf,
438 /// The footer partition image.
439 footer: PathBuf,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000440}
441
442/// Gets the calling SID of the current Binder thread.
Andrew Walbran806f1542021-06-10 14:07:12 +0000443fn get_calling_sid() -> Result<String, Status> {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000444 ThreadState::with_calling_sid(|sid| {
445 if let Some(sid) = sid {
446 match sid.to_str() {
447 Ok(sid) => Ok(sid.to_owned()),
448 Err(e) => {
Andrew Walbran806f1542021-06-10 14:07:12 +0000449 error!("SID was not valid UTF-8: {}", e);
450 Err(new_binder_exception(
451 ExceptionCode::ILLEGAL_ARGUMENT,
452 format!("SID was not valid UTF-8: {}", e),
453 ))
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000454 }
455 }
456 } else {
457 error!("Missing SID on startVm");
Andrew Walbran806f1542021-06-10 14:07:12 +0000458 Err(new_binder_exception(ExceptionCode::SECURITY, "Missing SID on startVm"))
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000459 }
460 })
461}
462
Jiyong Park753553b2021-07-12 21:21:09 +0900463/// Checks whether the caller has a specific permission
464fn check_permission(perm: &str) -> binder::Result<()> {
465 let calling_pid = ThreadState::get_calling_pid();
466 let calling_uid = ThreadState::get_calling_uid();
467 // Root can do anything
468 if calling_uid == 0 {
469 return Ok(());
470 }
471 let perm_svc: Strong<dyn IPermissionController::IPermissionController> =
472 binder::get_interface("permission")?;
473 if perm_svc.checkPermission(perm, calling_pid, calling_uid as i32)? {
Andrew Walbran806f1542021-06-10 14:07:12 +0000474 Ok(())
475 } else {
Jiyong Park753553b2021-07-12 21:21:09 +0900476 Err(new_binder_exception(
477 ExceptionCode::SECURITY,
478 format!("does not have the {} permission", perm),
479 ))
Andrew Walbran806f1542021-06-10 14:07:12 +0000480 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000481}
482
Jiyong Park753553b2021-07-12 21:21:09 +0900483/// Check whether the caller of the current Binder method is allowed to call debug methods.
484fn check_debug_access() -> binder::Result<()> {
485 check_permission("android.permission.DEBUG_VIRTUAL_MACHINE")
486}
487
488/// Check whether the caller of the current Binder method is allowed to manage VMs
489fn check_manage_access() -> binder::Result<()> {
490 check_permission("android.permission.MANAGE_VIRTUAL_MACHINE")
491}
492
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000493/// Implementation of the AIDL `IVirtualMachine` interface. Used as a handle to a VM.
494#[derive(Debug)]
495struct VirtualMachine {
496 instance: Arc<VmInstance>,
497}
498
499impl VirtualMachine {
500 fn create(instance: Arc<VmInstance>) -> Strong<dyn IVirtualMachine> {
501 let binder = VirtualMachine { instance };
Andrew Walbran4de28782021-04-13 14:51:43 +0000502 BnVirtualMachine::new_binder(binder, BinderFeatures::default())
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000503 }
504}
505
506impl Interface for VirtualMachine {}
507
508impl IVirtualMachine for VirtualMachine {
509 fn getCid(&self) -> binder::Result<i32> {
Jiyong Park753553b2021-07-12 21:21:09 +0900510 // Don't check permission. The owner of the VM might have passed this binder object to
511 // others.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000512 Ok(self.instance.cid as i32)
513 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000514
515 fn isRunning(&self) -> binder::Result<bool> {
Jiyong Park753553b2021-07-12 21:21:09 +0900516 // Don't check permission. The owner of the VM might have passed this binder object to
517 // others.
Andrew Walbrandae07162021-03-12 17:05:20 +0000518 Ok(self.instance.running())
519 }
520
521 fn registerCallback(
522 &self,
523 callback: &Strong<dyn IVirtualMachineCallback>,
524 ) -> binder::Result<()> {
Jiyong Park753553b2021-07-12 21:21:09 +0900525 // Don't check permission. The owner of the VM might have passed this binder object to
526 // others.
527 //
Andrew Walbrandae07162021-03-12 17:05:20 +0000528 // TODO: Should this give an error if the VM is already dead?
529 self.instance.callbacks.add(callback.clone());
530 Ok(())
531 }
532}
533
534impl Drop for VirtualMachine {
535 fn drop(&mut self) {
536 debug!("Dropping {:?}", self);
537 self.instance.kill();
538 }
539}
540
541/// A set of Binders to be called back in response to various events on the VM, such as when it
542/// dies.
543#[derive(Debug, Default)]
544pub struct VirtualMachineCallbacks(Mutex<Vec<Strong<dyn IVirtualMachineCallback>>>);
545
546impl VirtualMachineCallbacks {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900547 /// Call all registered callbacks to notify that the payload has started.
548 pub fn notify_payload_started(&self, cid: Cid, stream: VsockStream) {
549 let callbacks = &*self.0.lock().unwrap();
550 // SAFETY: ownership is transferred from stream to f
551 let f = unsafe { File::from_raw_fd(stream.into_raw_fd()) };
552 let pfd = ParcelFileDescriptor::new(f);
553 for callback in callbacks {
554 if let Err(e) = callback.onPayloadStarted(cid as i32, &pfd) {
555 error!("Error notifying payload start event from VM CID {}: {}", cid, e);
556 }
557 }
558 }
559
Andrew Walbrandae07162021-03-12 17:05:20 +0000560 /// Call all registered callbacks to say that the VM has died.
561 pub fn callback_on_died(&self, cid: Cid) {
562 let callbacks = &*self.0.lock().unwrap();
563 for callback in callbacks {
564 if let Err(e) = callback.onDied(cid as i32) {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900565 error!("Error notifying exit of VM CID {}: {}", cid, e);
Andrew Walbrandae07162021-03-12 17:05:20 +0000566 }
567 }
568 }
569
570 /// Add a new callback to the set.
571 fn add(&self, callback: Strong<dyn IVirtualMachineCallback>) {
572 self.0.lock().unwrap().push(callback);
573 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000574}
575
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000576/// The mutable state of the VirtualizationService. There should only be one instance of this
577/// struct.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000578#[derive(Debug)]
579struct State {
Andrew Walbran320b5602021-03-04 16:11:12 +0000580 /// The next available unused CID.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000581 next_cid: Cid,
Andrew Walbran320b5602021-03-04 16:11:12 +0000582
583 /// The VMs which have been started. When VMs are started a weak reference is added to this list
584 /// while a strong reference is returned to the caller over Binder. Once all copies of the
585 /// Binder client are dropped the weak reference here will become invalid, and will be removed
586 /// from the list opportunistically the next time `add_vm` is called.
587 vms: Vec<Weak<VmInstance>>,
David Brazdil3c2ddef2021-03-18 13:09:57 +0000588
589 /// Vector of strong VM references held on behalf of users that cannot hold them themselves.
590 /// This is only used for debugging purposes.
591 debug_held_vms: Vec<Strong<dyn IVirtualMachine>>,
Andrew Walbran320b5602021-03-04 16:11:12 +0000592}
593
594impl State {
Andrew Walbrandae07162021-03-12 17:05:20 +0000595 /// Get a list of VMs which still have Binder references to them.
Andrew Walbran320b5602021-03-04 16:11:12 +0000596 fn vms(&self) -> Vec<Arc<VmInstance>> {
597 // Attempt to upgrade the weak pointers to strong pointers.
598 self.vms.iter().filter_map(Weak::upgrade).collect()
599 }
600
601 /// Add a new VM to the list.
602 fn add_vm(&mut self, vm: Weak<VmInstance>) {
603 // Garbage collect any entries from the stored list which no longer exist.
604 self.vms.retain(|vm| vm.strong_count() > 0);
605
606 // Actually add the new VM.
607 self.vms.push(vm);
608 }
David Brazdil3c2ddef2021-03-18 13:09:57 +0000609
Jiyong Park8611a6c2021-07-09 18:17:44 +0900610 /// Get a VM that corresponds to the given cid
611 fn get_vm(&self, cid: Cid) -> Option<Arc<VmInstance>> {
612 self.vms().into_iter().find(|vm| vm.cid == cid)
613 }
614
David Brazdil3c2ddef2021-03-18 13:09:57 +0000615 /// Store a strong VM reference.
616 fn debug_hold_vm(&mut self, vm: Strong<dyn IVirtualMachine>) {
617 self.debug_held_vms.push(vm);
618 }
619
620 /// Retrieve and remove a strong VM reference.
621 fn debug_drop_vm(&mut self, cid: i32) -> Option<Strong<dyn IVirtualMachine>> {
622 let pos = self.debug_held_vms.iter().position(|vm| vm.getCid() == Ok(cid))?;
623 Some(self.debug_held_vms.swap_remove(pos))
624 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000625
626 /// Get the next available CID, or an error if we have run out.
627 fn allocate_cid(&mut self) -> binder::Result<Cid> {
628 // TODO(qwandor): keep track of which CIDs are currently in use so that we can reuse them.
629 let cid = self.next_cid;
Andrew Walbran806f1542021-06-10 14:07:12 +0000630 self.next_cid = self.next_cid.checked_add(1).ok_or(ExceptionCode::ILLEGAL_STATE)?;
Andrew Walbrandae07162021-03-12 17:05:20 +0000631 Ok(cid)
632 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000633}
634
635impl Default for State {
636 fn default() -> Self {
David Brazdil3c2ddef2021-03-18 13:09:57 +0000637 State { next_cid: FIRST_GUEST_CID, vms: vec![], debug_held_vms: vec![] }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000638 }
639}
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000640
641/// Converts an `&Option<T>` to an `Option<U>` where `T` implements `AsRef<U>`.
642fn as_asref<T: AsRef<U>, U>(option: &Option<T>) -> Option<&U> {
643 option.as_ref().map(|t| t.as_ref())
644}
645
646/// Converts a `&ParcelFileDescriptor` to a `File` by cloning the file.
Andrew Walbran806f1542021-06-10 14:07:12 +0000647fn clone_file(file: &ParcelFileDescriptor) -> Result<File, Status> {
648 file.as_ref().try_clone().map_err(|e| {
649 new_binder_exception(
650 ExceptionCode::BAD_PARCELABLE,
651 format!("Failed to clone File from ParcelFileDescriptor: {}", e),
652 )
653 })
654}
655
656/// Constructs a new Binder error `Status` with the given `ExceptionCode` and message.
657fn new_binder_exception<T: AsRef<str>>(exception: ExceptionCode, message: T) -> Status {
658 Status::new_exception(exception, CString::new(message.as_ref()).ok().as_deref())
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000659}
Jooyung Han35edb8f2021-07-01 16:17:16 +0900660
661/// Simple utility for referencing Borrowed or Owned. Similar to std::borrow::Cow, but
662/// it doesn't require that T implements Clone.
663enum BorrowedOrOwned<'a, T> {
664 Borrowed(&'a T),
665 Owned(T),
666}
667
668impl<'a, T> AsRef<T> for BorrowedOrOwned<'a, T> {
669 fn as_ref(&self) -> &T {
670 match self {
671 Self::Borrowed(b) => b,
672 Self::Owned(o) => &o,
673 }
674 }
675}