blob: e85ac2cde9da8f519a554f02edb1908cd6e02970 [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};
Andrew Walbrancc0db522021-07-12 17:03:42 +000019use crate::payload::add_microdroid_images;
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 Walbranf5fbb7d2021-05-12 17:15:48 +000023use android_system_virtualizationservice::aidl::android::system::virtualizationservice::DiskImage::DiskImage;
Inseob Kim1b95f2e2021-08-19 13:17:40 +090024use android_system_virtualizationservice::aidl::android::system::virtualizationservice::IVirtualizationService::IVirtualizationService;
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};
Inseob Kim1b95f2e2021-08-19 13:17:40 +090038use android_system_virtualmachineservice::aidl::android::system::virtualmachineservice::IVirtualMachineService::{
39 BnVirtualMachineService, IVirtualMachineService,
40};
Jooyung Han95884632021-07-06 22:27:54 +090041use anyhow::{bail, Context, Result};
Inseob Kim1b95f2e2021-08-19 13:17:40 +090042use ::binder::unstable_api::AsNative;
Andrew Walbrandfc953d2021-06-10 13:59:56 +000043use disk::QcowFile;
Jiyong Park0a248432021-08-20 23:32:39 +090044use idsig::{V4Signature, HashAlgorithm};
Jiyong Park8611a6c2021-07-09 18:17:44 +090045use log::{debug, error, warn, info};
Andrew Walbrancc0db522021-07-12 17:03:42 +000046use microdroid_payload_config::VmPayloadConfig;
Andrew Walbrandff3b942021-06-09 15:20:36 +000047use std::convert::TryInto;
Andrew Walbran806f1542021-06-10 14:07:12 +000048use std::ffi::CString;
Jooyung Han95884632021-07-06 22:27:54 +090049use std::fs::{File, OpenOptions, create_dir};
Andrew Walbranb15cd6e2021-07-05 16:38:07 +000050use std::num::NonZeroU32;
Jiyong Park8611a6c2021-07-09 18:17:44 +090051use std::os::unix::io::{AsRawFd, FromRawFd, IntoRawFd};
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000052use std::path::{Path, PathBuf};
Andrew Walbran320b5602021-03-04 16:11:12 +000053use std::sync::{Arc, Mutex, Weak};
Andrew Walbrancc0db522021-07-12 17:03:42 +000054use vmconfig::VmConfig;
Jiyong Park8611a6c2021-07-09 18:17:44 +090055use vsock::{VsockListener, SockAddr, VsockStream};
Jooyung Han35edb8f2021-07-01 16:17:16 +090056use zip::ZipArchive;
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000057
Andrew Walbranf6bf6862021-05-21 12:41:13 +000058pub const BINDER_SERVICE_IDENTIFIER: &str = "android.system.virtualizationservice";
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000059
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000060/// Directory in which to write disk image files used while running VMs.
Andrew Walbran488bd072021-07-14 13:29:51 +000061pub const TEMPORARY_DIRECTORY: &str = "/data/misc/virtualizationservice";
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000062
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
Inseob Kim1b95f2e2021-08-19 13:17:40 +090070/// Port number that virtualizationservice listens on connections from the guest VMs for the
71/// VirtualMachineService binder service
72/// Sync with microdroid_manager/src/main.rs
73const PORT_VM_BINDER_SERVICE: u32 = 5000;
74
Jooyung Han95884632021-07-06 22:27:54 +090075/// The size of zero.img.
76/// Gaps in composite disk images are filled with a shared zero.img.
77const ZERO_FILLER_SIZE: u64 = 4096;
78
Andrew Walbranf6bf6862021-05-21 12:41:13 +000079/// Implementation of `IVirtualizationService`, the entry point of the AIDL service.
Jooyung Han9900f3d2021-07-06 10:27:54 +090080#[derive(Debug, Default)]
Andrew Walbranf6bf6862021-05-21 12:41:13 +000081pub struct VirtualizationService {
Jiyong Park8611a6c2021-07-09 18:17:44 +090082 state: Arc<Mutex<State>>,
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000083}
84
Andrew Walbranf6bf6862021-05-21 12:41:13 +000085impl Interface for VirtualizationService {}
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000086
Andrew Walbranf6bf6862021-05-21 12:41:13 +000087impl IVirtualizationService for VirtualizationService {
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000088 /// Create and start a new VM with the given configuration, assigning it the next available CID.
89 ///
90 /// Returns a binder `IVirtualMachine` object referring to it, as a handle for the client.
Andrew Walbrana89fc132021-03-17 17:08:36 +000091 fn startVm(
92 &self,
Andrew Walbran3a5a9212021-05-04 17:09:08 +000093 config: &VirtualMachineConfig,
Andrew Walbrana89fc132021-03-17 17:08:36 +000094 log_fd: Option<&ParcelFileDescriptor>,
95 ) -> binder::Result<Strong<dyn IVirtualMachine>> {
Jiyong Park753553b2021-07-12 21:21:09 +090096 check_manage_access()?;
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000097 let state = &mut *self.state.lock().unwrap();
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000098 let log_fd = log_fd.map(clone_file).transpose()?;
Andrew Walbranf6a1eb92021-04-01 11:16:02 +000099 let requester_uid = ThreadState::get_calling_uid();
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000100 let requester_sid = get_calling_sid()?;
Andrew Walbran02034492021-04-13 15:05:07 +0000101 let requester_debug_pid = ThreadState::get_calling_pid();
Andrew Walbrandae07162021-03-12 17:05:20 +0000102 let cid = state.allocate_cid()?;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000103
104 // Counter to generate unique IDs for temporary image files.
105 let mut next_temporary_image_id = 0;
106 // Files which are referred to from composite images. These must be mapped to the crosvm
107 // child process, and not closed before it is started.
108 let mut indirect_files = vec![];
109
110 // Make directory for temporary files.
111 let temporary_directory: PathBuf = format!("{}/{}", TEMPORARY_DIRECTORY, cid).into();
112 create_dir(&temporary_directory).map_err(|e| {
113 error!(
Andrew Walbran806f1542021-06-10 14:07:12 +0000114 "Failed to create temporary directory {:?} for VM files: {}",
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000115 temporary_directory, e
116 );
Andrew Walbran806f1542021-06-10 14:07:12 +0000117 new_binder_exception(
118 ExceptionCode::SERVICE_SPECIFIC,
119 format!(
120 "Failed to create temporary directory {:?} for VM files: {}",
121 temporary_directory, e
122 ),
123 )
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000124 })?;
125
Jooyung Han21e9b922021-06-26 04:14:16 +0900126 let config = match config {
Jooyung Han35edb8f2021-07-01 16:17:16 +0900127 VirtualMachineConfig::AppConfig(config) => BorrowedOrOwned::Owned(
Jooyung Han9900f3d2021-07-06 10:27:54 +0900128 load_app_config(config, &temporary_directory).map_err(|e| {
129 error!("Failed to load app config from {}: {}", &config.configPath, e);
130 new_binder_exception(
131 ExceptionCode::SERVICE_SPECIFIC,
132 format!("Failed to load app config from {}: {}", &config.configPath, e),
133 )
134 })?,
Jooyung Han35edb8f2021-07-01 16:17:16 +0900135 ),
136 VirtualMachineConfig::RawConfig(config) => BorrowedOrOwned::Borrowed(config),
Jooyung Han21e9b922021-06-26 04:14:16 +0900137 };
Jooyung Han35edb8f2021-07-01 16:17:16 +0900138 let config = config.as_ref();
Jooyung Han21e9b922021-06-26 04:14:16 +0900139
Jooyung Han95884632021-07-06 22:27:54 +0900140 let zero_filler_path = temporary_directory.join("zero.img");
Andrew Walbranfbb39d22021-07-28 17:01:25 +0000141 write_zero_filler(&zero_filler_path).map_err(|e| {
Jooyung Han95884632021-07-06 22:27:54 +0900142 error!("Failed to make composite image: {}", e);
143 new_binder_exception(
144 ExceptionCode::SERVICE_SPECIFIC,
145 format!("Failed to make composite image: {}", e),
146 )
147 })?;
Jooyung Han95884632021-07-06 22:27:54 +0900148
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000149 // Assemble disk images if needed.
150 let disks = config
151 .disks
152 .iter()
153 .map(|disk| {
154 assemble_disk_image(
155 disk,
Jooyung Han95884632021-07-06 22:27:54 +0900156 &zero_filler_path,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000157 &temporary_directory,
158 &mut next_temporary_image_id,
159 &mut indirect_files,
160 )
161 })
162 .collect::<Result<Vec<DiskFile>, _>>()?;
163
164 // Actually start the VM.
165 let crosvm_config = CrosvmConfig {
Andrew Walbran02034492021-04-13 15:05:07 +0000166 cid,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000167 bootloader: as_asref(&config.bootloader),
168 kernel: as_asref(&config.kernel),
169 initrd: as_asref(&config.initrd),
170 disks,
171 params: config.params.to_owned(),
Andrew Walbrancc045902021-07-27 16:06:17 +0000172 protected: config.protectedVm,
173 memory_mib: config.memoryMib.try_into().ok().and_then(NonZeroU32::new),
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000174 };
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000175 let composite_disk_fds: Vec<_> =
176 indirect_files.iter().map(|file| file.as_raw_fd()).collect();
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000177 let instance = VmInstance::start(
178 &crosvm_config,
Andrew Walbran02034492021-04-13 15:05:07 +0000179 log_fd,
Andrew Walbran02b8ec02021-06-22 13:07:02 +0000180 &composite_disk_fds,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000181 temporary_directory,
Andrew Walbran02034492021-04-13 15:05:07 +0000182 requester_uid,
183 requester_sid,
184 requester_debug_pid,
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000185 )
186 .map_err(|e| {
Andrew Walbran806f1542021-06-10 14:07:12 +0000187 error!("Failed to start VM with config {:?}: {}", config, e);
188 new_binder_exception(
189 ExceptionCode::SERVICE_SPECIFIC,
190 format!("Failed to start VM: {}", e),
191 )
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000192 })?;
Andrew Walbran320b5602021-03-04 16:11:12 +0000193 state.add_vm(Arc::downgrade(&instance));
194 Ok(VirtualMachine::create(instance))
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000195 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000196
Andrew Walbrandff3b942021-06-09 15:20:36 +0000197 /// Initialise an empty partition image of the given size to be used as a writable partition.
198 fn initializeWritablePartition(
199 &self,
200 image_fd: &ParcelFileDescriptor,
201 size: i64,
202 ) -> binder::Result<()> {
Jiyong Park753553b2021-07-12 21:21:09 +0900203 check_manage_access()?;
Andrew Walbrandfc953d2021-06-10 13:59:56 +0000204 let size = size.try_into().map_err(|e| {
Andrew Walbran806f1542021-06-10 14:07:12 +0000205 new_binder_exception(
206 ExceptionCode::ILLEGAL_ARGUMENT,
207 format!("Invalid size {}: {}", size, e),
208 )
Andrew Walbrandff3b942021-06-09 15:20:36 +0000209 })?;
Andrew Walbrandfc953d2021-06-10 13:59:56 +0000210 let image = clone_file(image_fd)?;
Andrew Walbrandff3b942021-06-09 15:20:36 +0000211
Andrew Walbrandfc953d2021-06-10 13:59:56 +0000212 QcowFile::new(image, size).map_err(|e| {
Andrew Walbran806f1542021-06-10 14:07:12 +0000213 new_binder_exception(
214 ExceptionCode::SERVICE_SPECIFIC,
215 format!("Failed to create QCOW2 image: {}", e),
216 )
Andrew Walbrandfc953d2021-06-10 13:59:56 +0000217 })?;
Andrew Walbrandff3b942021-06-09 15:20:36 +0000218
219 Ok(())
220 }
221
Jiyong Park0a248432021-08-20 23:32:39 +0900222 /// Creates or update the idsig file by digesting the input APK file.
223 fn createOrUpdateIdsigFile(
224 &self,
225 input_fd: &ParcelFileDescriptor,
226 idsig_fd: &ParcelFileDescriptor,
227 ) -> binder::Result<()> {
228 // TODO(b/193504400): do this only when (1) idsig_fd is empty or (2) the APK digest in
229 // idsig_fd is different from APK digest in input_fd
230
231 let mut input = clone_file(input_fd)?;
232 let mut sig = V4Signature::create(&mut input, 4096, &[], HashAlgorithm::SHA256).unwrap();
233
234 let mut output = clone_file(idsig_fd)?;
235 output.set_len(0).unwrap();
236 sig.write_into(&mut output).unwrap();
237 Ok(())
238 }
239
Andrew Walbran320b5602021-03-04 16:11:12 +0000240 /// Get a list of all currently running VMs. This method is only intended for debug purposes,
241 /// and as such is only permitted from the shell user.
242 fn debugListVms(&self) -> binder::Result<Vec<VirtualMachineDebugInfo>> {
Andrew Walbran806f1542021-06-10 14:07:12 +0000243 check_debug_access()?;
Andrew Walbran320b5602021-03-04 16:11:12 +0000244
245 let state = &mut *self.state.lock().unwrap();
246 let vms = state.vms();
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000247 let cids = vms
248 .into_iter()
249 .map(|vm| VirtualMachineDebugInfo {
250 cid: vm.cid as i32,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000251 temporaryDirectory: vm.temporary_directory.to_string_lossy().to_string(),
Andrew Walbran1ef19ae2021-04-07 11:31:57 +0000252 requesterUid: vm.requester_uid as i32,
253 requesterSid: vm.requester_sid.clone(),
Andrew Walbran02034492021-04-13 15:05:07 +0000254 requesterPid: vm.requester_debug_pid,
Andrew Walbrandae07162021-03-12 17:05:20 +0000255 running: vm.running(),
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000256 })
257 .collect();
Andrew Walbran320b5602021-03-04 16:11:12 +0000258 Ok(cids)
259 }
David Brazdil3c2ddef2021-03-18 13:09:57 +0000260
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000261 /// Hold a strong reference to a VM in VirtualizationService. This method is only intended for
262 /// debug purposes, and as such is only permitted from the shell user.
Andrei Homescu1415c132021-03-24 02:39:55 +0000263 fn debugHoldVmRef(&self, vmref: &Strong<dyn IVirtualMachine>) -> binder::Result<()> {
Andrew Walbran806f1542021-06-10 14:07:12 +0000264 check_debug_access()?;
David Brazdil3c2ddef2021-03-18 13:09:57 +0000265
David Brazdil3c2ddef2021-03-18 13:09:57 +0000266 let state = &mut *self.state.lock().unwrap();
Andrei Homescu1415c132021-03-24 02:39:55 +0000267 state.debug_hold_vm(vmref.clone());
David Brazdil3c2ddef2021-03-18 13:09:57 +0000268 Ok(())
269 }
270
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000271 /// Drop reference to a VM that is being held by VirtualizationService. Returns the reference if
272 /// the VM was found and None otherwise. This method is only intended for debug purposes, and as
273 /// such is only permitted from the shell user.
David Brazdil3c2ddef2021-03-18 13:09:57 +0000274 fn debugDropVmRef(&self, cid: i32) -> binder::Result<Option<Strong<dyn IVirtualMachine>>> {
Andrew Walbran806f1542021-06-10 14:07:12 +0000275 check_debug_access()?;
David Brazdil3c2ddef2021-03-18 13:09:57 +0000276
277 let state = &mut *self.state.lock().unwrap();
278 Ok(state.debug_drop_vm(cid))
279 }
Andrew Walbran320b5602021-03-04 16:11:12 +0000280}
281
Jiyong Park8611a6c2021-07-09 18:17:44 +0900282impl VirtualizationService {
283 pub fn init() -> VirtualizationService {
284 let service = VirtualizationService::default();
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900285
286 // server for payload output
Jiyong Park8611a6c2021-07-09 18:17:44 +0900287 let state = service.state.clone(); // reference to state (not the state itself) is copied
288 std::thread::spawn(move || {
289 handle_connection_from_vm(state).unwrap();
290 });
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900291
292 // binder server for vm
293 let state = service.state.clone(); // reference to state (not the state itself) is copied
294 std::thread::spawn(move || {
295 let mut service = VirtualMachineService::new_binder(state).as_binder();
296 debug!("virtual machine service is starting as an RPC service.");
297 // SAFETY: Service ownership is transferring to the server and won't be valid afterward.
298 // Plus the binder objects are threadsafe.
299 let retval = unsafe {
300 binder_rpc_unstable_bindgen::RunRpcServer(
301 service.as_native_mut() as *mut binder_rpc_unstable_bindgen::AIBinder,
302 PORT_VM_BINDER_SERVICE,
303 )
304 };
305 if retval {
306 debug!("RPC server has shut down gracefully");
307 } else {
308 bail!("Premature termination of RPC server");
309 }
310
311 Ok(retval)
312 });
Jiyong Park8611a6c2021-07-09 18:17:44 +0900313 service
314 }
315}
316
317/// Waits for incoming connections from VM. If a new connection is made, notify the event to the
318/// client via the callback (if registered).
319fn handle_connection_from_vm(state: Arc<Mutex<State>>) -> Result<()> {
320 let listener = VsockListener::bind_with_cid_port(VMADDR_CID_HOST, PORT_VIRT_SERVICE)?;
321 for stream in listener.incoming() {
322 let stream = match stream {
323 Err(e) => {
324 warn!("invalid incoming connection: {}", e);
325 continue;
326 }
327 Ok(s) => s,
328 };
329 if let Ok(SockAddr::Vsock(addr)) = stream.peer_addr() {
330 let cid = addr.cid();
331 let port = addr.port();
332 info!("connected from cid={}, port={}", cid, port);
333 if cid < FIRST_GUEST_CID {
334 warn!("connection is not from a guest VM");
335 continue;
336 }
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900337 // TODO(b/191845268): handle this with VirtualMachineService
Jiyong Park8611a6c2021-07-09 18:17:44 +0900338 if let Some(vm) = state.lock().unwrap().get_vm(cid) {
339 vm.callbacks.notify_payload_started(cid, stream);
340 }
341 }
342 }
343 Ok(())
344}
345
Andrew Walbranfbb39d22021-07-28 17:01:25 +0000346fn write_zero_filler(zero_filler_path: &Path) -> Result<()> {
Jooyung Han95884632021-07-06 22:27:54 +0900347 let file = OpenOptions::new()
348 .create_new(true)
349 .read(true)
350 .write(true)
351 .open(zero_filler_path)
352 .with_context(|| "Failed to create zero.img")?;
353 file.set_len(ZERO_FILLER_SIZE)?;
Andrew Walbranfbb39d22021-07-28 17:01:25 +0000354 Ok(())
Jooyung Han95884632021-07-06 22:27:54 +0900355}
356
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000357/// Given the configuration for a disk image, assembles the `DiskFile` to pass to crosvm.
358///
359/// This may involve assembling a composite disk from a set of partition images.
360fn assemble_disk_image(
361 disk: &DiskImage,
Jooyung Han95884632021-07-06 22:27:54 +0900362 zero_filler_path: &Path,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000363 temporary_directory: &Path,
364 next_temporary_image_id: &mut u64,
365 indirect_files: &mut Vec<File>,
Andrew Walbran806f1542021-06-10 14:07:12 +0000366) -> Result<DiskFile, Status> {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000367 let image = if !disk.partitions.is_empty() {
368 if disk.image.is_some() {
369 warn!("DiskImage {:?} contains both image and partitions.", disk);
Andrew Walbran806f1542021-06-10 14:07:12 +0000370 return Err(new_binder_exception(
371 ExceptionCode::ILLEGAL_ARGUMENT,
372 "DiskImage contains both image and partitions.",
373 ));
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000374 }
375
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000376 let composite_image_filenames =
377 make_composite_image_filenames(temporary_directory, next_temporary_image_id);
378 let (image, partition_files) = make_composite_image(
379 &disk.partitions,
Jooyung Han95884632021-07-06 22:27:54 +0900380 zero_filler_path,
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000381 &composite_image_filenames.composite,
382 &composite_image_filenames.header,
383 &composite_image_filenames.footer,
384 )
385 .map_err(|e| {
386 error!("Failed to make composite image with config {:?}: {}", disk, e);
387 new_binder_exception(
388 ExceptionCode::SERVICE_SPECIFIC,
389 format!("Failed to make composite image: {}", e),
390 )
391 })?;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000392
393 // Pass the file descriptors for the various partition files to crosvm when it
394 // is run.
395 indirect_files.extend(partition_files);
396
397 image
398 } else if let Some(image) = &disk.image {
399 clone_file(image)?
400 } else {
401 warn!("DiskImage {:?} didn't contain image or partitions.", disk);
Andrew Walbran806f1542021-06-10 14:07:12 +0000402 return Err(new_binder_exception(
403 ExceptionCode::ILLEGAL_ARGUMENT,
404 "DiskImage didn't contain image or partitions.",
405 ));
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000406 };
407
408 Ok(DiskFile { image, writable: disk.writable })
409}
410
Jooyung Han21e9b922021-06-26 04:14:16 +0900411fn load_app_config(
412 config: &VirtualMachineAppConfig,
413 temporary_directory: &Path,
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900414) -> Result<VirtualMachineRawConfig> {
Andrew Walbrancc0db522021-07-12 17:03:42 +0000415 let apk_file = clone_file(config.apk.as_ref().unwrap())?;
416 let idsig_file = clone_file(config.idsig.as_ref().unwrap())?;
Jiyong Park8d081812021-07-23 17:45:04 +0900417 let instance_file = clone_file(config.instanceImage.as_ref().unwrap())?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900418 let config_path = &config.configPath;
419
Andrew Walbrancc0db522021-07-12 17:03:42 +0000420 let mut apk_zip = ZipArchive::new(&apk_file)?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900421 let config_file = apk_zip.by_name(config_path)?;
422 let vm_payload_config: VmPayloadConfig = serde_json::from_reader(config_file)?;
423
424 let os_name = &vm_payload_config.os.name;
Andrew Walbrancc0db522021-07-12 17:03:42 +0000425
Jooyung Han35edb8f2021-07-01 16:17:16 +0900426 // For now, the only supported "os" value is "microdroid"
427 if os_name != "microdroid" {
Andrew Walbrancc0db522021-07-12 17:03:42 +0000428 bail!("Unknown OS \"{}\"", os_name);
Jooyung Han35edb8f2021-07-01 16:17:16 +0900429 }
Andrew Walbrancc0db522021-07-12 17:03:42 +0000430
431 // It is safe to construct a filename based on the os_name because we've already checked that it
432 // is one of the allowed values.
Jooyung Han21e9b922021-06-26 04:14:16 +0900433 let vm_config_path = PathBuf::from(format!("/apex/com.android.virt/etc/{}.json", os_name));
434 let vm_config_file = File::open(vm_config_path)?;
Andrew Walbrancc0db522021-07-12 17:03:42 +0000435 let mut vm_config = VmConfig::load(&vm_config_file)?.to_parcelable()?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900436
Andrew Walbrancc045902021-07-27 16:06:17 +0000437 if config.memoryMib > 0 {
438 vm_config.memoryMib = config.memoryMib;
Andrew Walbran45bcb0c2021-07-14 15:02:06 +0000439 }
440
Andrew Walbrancc0db522021-07-12 17:03:42 +0000441 // Microdroid requires an additional payload disk image and the bootconfig partition.
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900442 if os_name == "microdroid" {
Andrew Walbrancc0db522021-07-12 17:03:42 +0000443 let apexes = vm_payload_config.apexes.clone();
444 add_microdroid_images(
445 config,
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900446 temporary_directory,
Andrew Walbrancc0db522021-07-12 17:03:42 +0000447 apk_file,
448 idsig_file,
Jiyong Park8d081812021-07-23 17:45:04 +0900449 instance_file,
Andrew Walbrancc0db522021-07-12 17:03:42 +0000450 apexes,
451 &mut vm_config,
452 )?;
Jooyung Hanadfb76c2021-06-28 17:29:30 +0900453 }
Jooyung Han21e9b922021-06-26 04:14:16 +0900454
Andrew Walbrancc0db522021-07-12 17:03:42 +0000455 Ok(vm_config)
Jooyung Han21e9b922021-06-26 04:14:16 +0900456}
457
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000458/// Generates a unique filename to use for a composite disk image.
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000459fn make_composite_image_filenames(
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000460 temporary_directory: &Path,
461 next_temporary_image_id: &mut u64,
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000462) -> CompositeImageFilenames {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000463 let id = *next_temporary_image_id;
464 *next_temporary_image_id += 1;
Andrew Walbran3eca16c2021-06-14 11:15:14 +0000465 CompositeImageFilenames {
466 composite: temporary_directory.join(format!("composite-{}.img", id)),
467 header: temporary_directory.join(format!("composite-{}-header.img", id)),
468 footer: temporary_directory.join(format!("composite-{}-footer.img", id)),
469 }
470}
471
472/// Filenames for a composite disk image, including header and footer partitions.
473#[derive(Clone, Debug, Eq, PartialEq)]
474struct CompositeImageFilenames {
475 /// The composite disk image itself.
476 composite: PathBuf,
477 /// The header partition image.
478 header: PathBuf,
479 /// The footer partition image.
480 footer: PathBuf,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000481}
482
483/// Gets the calling SID of the current Binder thread.
Andrew Walbran806f1542021-06-10 14:07:12 +0000484fn get_calling_sid() -> Result<String, Status> {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000485 ThreadState::with_calling_sid(|sid| {
486 if let Some(sid) = sid {
487 match sid.to_str() {
488 Ok(sid) => Ok(sid.to_owned()),
489 Err(e) => {
Andrew Walbran806f1542021-06-10 14:07:12 +0000490 error!("SID was not valid UTF-8: {}", e);
491 Err(new_binder_exception(
492 ExceptionCode::ILLEGAL_ARGUMENT,
493 format!("SID was not valid UTF-8: {}", e),
494 ))
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000495 }
496 }
497 } else {
498 error!("Missing SID on startVm");
Andrew Walbran806f1542021-06-10 14:07:12 +0000499 Err(new_binder_exception(ExceptionCode::SECURITY, "Missing SID on startVm"))
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000500 }
501 })
502}
503
Jiyong Park753553b2021-07-12 21:21:09 +0900504/// Checks whether the caller has a specific permission
505fn check_permission(perm: &str) -> binder::Result<()> {
506 let calling_pid = ThreadState::get_calling_pid();
507 let calling_uid = ThreadState::get_calling_uid();
508 // Root can do anything
509 if calling_uid == 0 {
510 return Ok(());
511 }
512 let perm_svc: Strong<dyn IPermissionController::IPermissionController> =
513 binder::get_interface("permission")?;
514 if perm_svc.checkPermission(perm, calling_pid, calling_uid as i32)? {
Andrew Walbran806f1542021-06-10 14:07:12 +0000515 Ok(())
516 } else {
Jiyong Park753553b2021-07-12 21:21:09 +0900517 Err(new_binder_exception(
518 ExceptionCode::SECURITY,
519 format!("does not have the {} permission", perm),
520 ))
Andrew Walbran806f1542021-06-10 14:07:12 +0000521 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000522}
523
Jiyong Park753553b2021-07-12 21:21:09 +0900524/// Check whether the caller of the current Binder method is allowed to call debug methods.
525fn check_debug_access() -> binder::Result<()> {
526 check_permission("android.permission.DEBUG_VIRTUAL_MACHINE")
527}
528
529/// Check whether the caller of the current Binder method is allowed to manage VMs
530fn check_manage_access() -> binder::Result<()> {
531 check_permission("android.permission.MANAGE_VIRTUAL_MACHINE")
532}
533
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000534/// Implementation of the AIDL `IVirtualMachine` interface. Used as a handle to a VM.
535#[derive(Debug)]
536struct VirtualMachine {
537 instance: Arc<VmInstance>,
538}
539
540impl VirtualMachine {
541 fn create(instance: Arc<VmInstance>) -> Strong<dyn IVirtualMachine> {
542 let binder = VirtualMachine { instance };
Andrew Walbran4de28782021-04-13 14:51:43 +0000543 BnVirtualMachine::new_binder(binder, BinderFeatures::default())
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000544 }
545}
546
547impl Interface for VirtualMachine {}
548
549impl IVirtualMachine for VirtualMachine {
550 fn getCid(&self) -> binder::Result<i32> {
Jiyong Park753553b2021-07-12 21:21:09 +0900551 // Don't check permission. The owner of the VM might have passed this binder object to
552 // others.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000553 Ok(self.instance.cid as i32)
554 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000555
556 fn isRunning(&self) -> binder::Result<bool> {
Jiyong Park753553b2021-07-12 21:21:09 +0900557 // Don't check permission. The owner of the VM might have passed this binder object to
558 // others.
Andrew Walbrandae07162021-03-12 17:05:20 +0000559 Ok(self.instance.running())
560 }
561
562 fn registerCallback(
563 &self,
564 callback: &Strong<dyn IVirtualMachineCallback>,
565 ) -> binder::Result<()> {
Jiyong Park753553b2021-07-12 21:21:09 +0900566 // Don't check permission. The owner of the VM might have passed this binder object to
567 // others.
568 //
Andrew Walbrandae07162021-03-12 17:05:20 +0000569 // TODO: Should this give an error if the VM is already dead?
570 self.instance.callbacks.add(callback.clone());
571 Ok(())
572 }
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000573
574 fn connectVsock(&self, port: i32) -> binder::Result<ParcelFileDescriptor> {
575 if !self.instance.running() {
576 return Err(new_binder_exception(
577 ExceptionCode::SERVICE_SPECIFIC,
578 "VM is no longer running",
579 ));
580 }
581 let stream =
582 VsockStream::connect_with_cid_port(self.instance.cid, port as u32).map_err(|e| {
583 new_binder_exception(
584 ExceptionCode::SERVICE_SPECIFIC,
585 format!("Failed to connect: {}", e),
586 )
587 })?;
588 Ok(vsock_stream_to_pfd(stream))
589 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000590}
591
592impl Drop for VirtualMachine {
593 fn drop(&mut self) {
594 debug!("Dropping {:?}", self);
595 self.instance.kill();
596 }
597}
598
599/// A set of Binders to be called back in response to various events on the VM, such as when it
600/// dies.
601#[derive(Debug, Default)]
602pub struct VirtualMachineCallbacks(Mutex<Vec<Strong<dyn IVirtualMachineCallback>>>);
603
604impl VirtualMachineCallbacks {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900605 /// Call all registered callbacks to notify that the payload has started.
606 pub fn notify_payload_started(&self, cid: Cid, stream: VsockStream) {
607 let callbacks = &*self.0.lock().unwrap();
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000608 let pfd = vsock_stream_to_pfd(stream);
Jiyong Park8611a6c2021-07-09 18:17:44 +0900609 for callback in callbacks {
610 if let Err(e) = callback.onPayloadStarted(cid as i32, &pfd) {
611 error!("Error notifying payload start event from VM CID {}: {}", cid, e);
612 }
613 }
614 }
615
Andrew Walbrandae07162021-03-12 17:05:20 +0000616 /// Call all registered callbacks to say that the VM has died.
617 pub fn callback_on_died(&self, cid: Cid) {
618 let callbacks = &*self.0.lock().unwrap();
619 for callback in callbacks {
620 if let Err(e) = callback.onDied(cid as i32) {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900621 error!("Error notifying exit of VM CID {}: {}", cid, e);
Andrew Walbrandae07162021-03-12 17:05:20 +0000622 }
623 }
624 }
625
626 /// Add a new callback to the set.
627 fn add(&self, callback: Strong<dyn IVirtualMachineCallback>) {
628 self.0.lock().unwrap().push(callback);
629 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000630}
631
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000632/// The mutable state of the VirtualizationService. There should only be one instance of this
633/// struct.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000634#[derive(Debug)]
635struct State {
Andrew Walbran320b5602021-03-04 16:11:12 +0000636 /// The next available unused CID.
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000637 next_cid: Cid,
Andrew Walbran320b5602021-03-04 16:11:12 +0000638
639 /// The VMs which have been started. When VMs are started a weak reference is added to this list
640 /// while a strong reference is returned to the caller over Binder. Once all copies of the
641 /// Binder client are dropped the weak reference here will become invalid, and will be removed
642 /// from the list opportunistically the next time `add_vm` is called.
643 vms: Vec<Weak<VmInstance>>,
David Brazdil3c2ddef2021-03-18 13:09:57 +0000644
645 /// Vector of strong VM references held on behalf of users that cannot hold them themselves.
646 /// This is only used for debugging purposes.
647 debug_held_vms: Vec<Strong<dyn IVirtualMachine>>,
Andrew Walbran320b5602021-03-04 16:11:12 +0000648}
649
650impl State {
Andrew Walbrandae07162021-03-12 17:05:20 +0000651 /// Get a list of VMs which still have Binder references to them.
Andrew Walbran320b5602021-03-04 16:11:12 +0000652 fn vms(&self) -> Vec<Arc<VmInstance>> {
653 // Attempt to upgrade the weak pointers to strong pointers.
654 self.vms.iter().filter_map(Weak::upgrade).collect()
655 }
656
657 /// Add a new VM to the list.
658 fn add_vm(&mut self, vm: Weak<VmInstance>) {
659 // Garbage collect any entries from the stored list which no longer exist.
660 self.vms.retain(|vm| vm.strong_count() > 0);
661
662 // Actually add the new VM.
663 self.vms.push(vm);
664 }
David Brazdil3c2ddef2021-03-18 13:09:57 +0000665
Jiyong Park8611a6c2021-07-09 18:17:44 +0900666 /// Get a VM that corresponds to the given cid
667 fn get_vm(&self, cid: Cid) -> Option<Arc<VmInstance>> {
668 self.vms().into_iter().find(|vm| vm.cid == cid)
669 }
670
David Brazdil3c2ddef2021-03-18 13:09:57 +0000671 /// Store a strong VM reference.
672 fn debug_hold_vm(&mut self, vm: Strong<dyn IVirtualMachine>) {
673 self.debug_held_vms.push(vm);
674 }
675
676 /// Retrieve and remove a strong VM reference.
677 fn debug_drop_vm(&mut self, cid: i32) -> Option<Strong<dyn IVirtualMachine>> {
678 let pos = self.debug_held_vms.iter().position(|vm| vm.getCid() == Ok(cid))?;
679 Some(self.debug_held_vms.swap_remove(pos))
680 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000681
682 /// Get the next available CID, or an error if we have run out.
683 fn allocate_cid(&mut self) -> binder::Result<Cid> {
684 // TODO(qwandor): keep track of which CIDs are currently in use so that we can reuse them.
685 let cid = self.next_cid;
Andrew Walbran806f1542021-06-10 14:07:12 +0000686 self.next_cid = self.next_cid.checked_add(1).ok_or(ExceptionCode::ILLEGAL_STATE)?;
Andrew Walbrandae07162021-03-12 17:05:20 +0000687 Ok(cid)
688 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000689}
690
691impl Default for State {
692 fn default() -> Self {
David Brazdil3c2ddef2021-03-18 13:09:57 +0000693 State { next_cid: FIRST_GUEST_CID, vms: vec![], debug_held_vms: vec![] }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000694 }
695}
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000696
697/// Converts an `&Option<T>` to an `Option<U>` where `T` implements `AsRef<U>`.
698fn as_asref<T: AsRef<U>, U>(option: &Option<T>) -> Option<&U> {
699 option.as_ref().map(|t| t.as_ref())
700}
701
702/// Converts a `&ParcelFileDescriptor` to a `File` by cloning the file.
Andrew Walbran806f1542021-06-10 14:07:12 +0000703fn clone_file(file: &ParcelFileDescriptor) -> Result<File, Status> {
704 file.as_ref().try_clone().map_err(|e| {
705 new_binder_exception(
706 ExceptionCode::BAD_PARCELABLE,
707 format!("Failed to clone File from ParcelFileDescriptor: {}", e),
708 )
709 })
710}
711
Andrew Walbrancbe8b082021-08-06 15:42:11 +0000712/// Converts a `VsockStream` to a `ParcelFileDescriptor`.
713fn vsock_stream_to_pfd(stream: VsockStream) -> ParcelFileDescriptor {
714 // SAFETY: ownership is transferred from stream to f
715 let f = unsafe { File::from_raw_fd(stream.into_raw_fd()) };
716 ParcelFileDescriptor::new(f)
717}
718
Andrew Walbran806f1542021-06-10 14:07:12 +0000719/// Constructs a new Binder error `Status` with the given `ExceptionCode` and message.
720fn new_binder_exception<T: AsRef<str>>(exception: ExceptionCode, message: T) -> Status {
721 Status::new_exception(exception, CString::new(message.as_ref()).ok().as_deref())
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000722}
Jooyung Han35edb8f2021-07-01 16:17:16 +0900723
724/// Simple utility for referencing Borrowed or Owned. Similar to std::borrow::Cow, but
725/// it doesn't require that T implements Clone.
726enum BorrowedOrOwned<'a, T> {
727 Borrowed(&'a T),
728 Owned(T),
729}
730
731impl<'a, T> AsRef<T> for BorrowedOrOwned<'a, T> {
732 fn as_ref(&self) -> &T {
733 match self {
734 Self::Borrowed(b) => b,
Chris Wailes68c39f82021-07-27 16:03:44 -0700735 Self::Owned(o) => o,
Jooyung Han35edb8f2021-07-01 16:17:16 +0900736 }
737 }
738}
Inseob Kim1b95f2e2021-08-19 13:17:40 +0900739
740/// Implementation of `IVirtualMachineService`, the entry point of the AIDL service.
741#[derive(Debug, Default)]
742struct VirtualMachineService {
743 state: Arc<Mutex<State>>,
744}
745
746impl Interface for VirtualMachineService {}
747
748impl IVirtualMachineService for VirtualMachineService {
749 fn notifyPayloadStarted(&self, cid: i32) -> binder::Result<()> {
750 let cid = cid as Cid;
751 if self.state.lock().unwrap().get_vm(cid).is_none() {
752 error!("notifyPayloadStarted is called from an unknown cid {}", cid);
753 return Err(new_binder_exception(
754 ExceptionCode::SERVICE_SPECIFIC,
755 format!("cannot find a VM with cid {}", cid),
756 ));
757 }
758 info!("VM having CID {} started payload", cid);
759 Ok(())
760 }
761}
762
763impl VirtualMachineService {
764 fn new_binder(state: Arc<Mutex<State>>) -> Strong<dyn IVirtualMachineService> {
765 BnVirtualMachineService::new_binder(
766 VirtualMachineService { state },
767 BinderFeatures::default(),
768 )
769 }
770}