blob: 1ae94eaa528a481d4b72724aa4dafd3e46a6b512 [file] [log] [blame]
Andrew Walbranf395b822021-05-05 10:38:59 +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
15//! Command to run a VM.
16
17use crate::sync::AtomicFlag;
Andrew Walbranf6bf6862021-05-21 12:41:13 +000018use android_system_virtualizationservice::aidl::android::system::virtualizationservice::IVirtualizationService::IVirtualizationService;
19use android_system_virtualizationservice::aidl::android::system::virtualizationservice::IVirtualMachine::IVirtualMachine;
20use android_system_virtualizationservice::aidl::android::system::virtualizationservice::IVirtualMachineCallback::{
Andrew Walbranf395b822021-05-05 10:38:59 +000021 BnVirtualMachineCallback, IVirtualMachineCallback,
22};
Jooyung Han21e9b922021-06-26 04:14:16 +090023use android_system_virtualizationservice::aidl::android::system::virtualizationservice::{
24 VirtualMachineAppConfig::VirtualMachineAppConfig,
25 VirtualMachineConfig::VirtualMachineConfig,
26};
Andrew Walbranf6bf6862021-05-21 12:41:13 +000027use android_system_virtualizationservice::binder::{
Andrew Walbranf395b822021-05-05 10:38:59 +000028 BinderFeatures, DeathRecipient, IBinder, ParcelFileDescriptor, Strong,
29};
Andrew Walbranf6bf6862021-05-21 12:41:13 +000030use android_system_virtualizationservice::binder::{Interface, Result as BinderResult};
Andrew Walbranf395b822021-05-05 10:38:59 +000031use anyhow::{Context, Error};
32use std::fs::File;
33use std::io;
34use std::os::unix::io::{AsRawFd, FromRawFd};
35use std::path::Path;
Jooyung Hanfc732f52021-06-26 02:54:20 +090036use vmconfig::VmConfig;
Andrew Walbranf395b822021-05-05 10:38:59 +000037
Jooyung Han21e9b922021-06-26 04:14:16 +090038/// Run a VM from the given APK, idsig, and config.
39pub fn command_run_app(
40 service: Strong<dyn IVirtualizationService>,
41 apk: &Path,
42 idsig: &Path,
43 config_path: &str,
44 daemonize: bool,
45 log_path: Option<&Path>,
46) -> Result<(), Error> {
47 let apk_file = File::open(apk).context("Failed to open APK file")?;
48 let idsig_file = File::open(idsig).context("Failed to open idsig file")?;
49 let config = VirtualMachineConfig::AppConfig(VirtualMachineAppConfig {
50 apk: ParcelFileDescriptor::new(apk_file).into(),
51 idsig: ParcelFileDescriptor::new(idsig_file).into(),
52 configPath: config_path.to_owned(),
53 });
54 run(service, &config, &format!("{:?}!{:?}", apk, config_path), daemonize, log_path)
55}
56
Andrew Walbranf395b822021-05-05 10:38:59 +000057/// Run a VM from the given configuration file.
58pub fn command_run(
Andrew Walbran17de24f2021-05-27 13:27:30 +000059 service: Strong<dyn IVirtualizationService>,
Andrew Walbranf395b822021-05-05 10:38:59 +000060 config_path: &Path,
61 daemonize: bool,
Andrew Walbranbe429242021-06-28 12:22:54 +000062 log_path: Option<&Path>,
Andrew Walbranf395b822021-05-05 10:38:59 +000063) -> Result<(), Error> {
Andrew Walbran3a5a9212021-05-04 17:09:08 +000064 let config_file = File::open(config_path).context("Failed to open config file")?;
65 let config =
66 VmConfig::load(&config_file).context("Failed to parse config file")?.to_parcelable()?;
Jooyung Han21e9b922021-06-26 04:14:16 +090067 run(
68 service,
69 &VirtualMachineConfig::RawConfig(config),
70 &format!("{:?}", config_path),
71 daemonize,
72 log_path,
73 )
74}
75
76fn run(
77 service: Strong<dyn IVirtualizationService>,
78 config: &VirtualMachineConfig,
79 config_path: &str,
80 daemonize: bool,
81 log_path: Option<&Path>,
82) -> Result<(), Error> {
Andrew Walbranbe429242021-06-28 12:22:54 +000083 let stdout = if let Some(log_path) = log_path {
84 Some(ParcelFileDescriptor::new(
85 File::create(log_path)
86 .with_context(|| format!("Failed to open log file {:?}", log_path))?,
87 ))
88 } else if daemonize {
89 None
90 } else {
91 Some(ParcelFileDescriptor::new(duplicate_stdout()?))
92 };
Jooyung Han21e9b922021-06-26 04:14:16 +090093 let vm = service.startVm(config, stdout.as_ref()).context("Failed to start VM")?;
Andrew Walbranf395b822021-05-05 10:38:59 +000094
95 let cid = vm.getCid().context("Failed to get CID")?;
Andrew Walbran3a5a9212021-05-04 17:09:08 +000096 println!("Started VM from {:?} with CID {}.", config_path, cid);
Andrew Walbranf395b822021-05-05 10:38:59 +000097
98 if daemonize {
Andrew Walbranf6bf6862021-05-21 12:41:13 +000099 // Pass the VM reference back to VirtualizationService and have it hold it in the
100 // background.
Andrew Walbran17de24f2021-05-27 13:27:30 +0000101 service.debugHoldVmRef(&vm).context("Failed to pass VM to VirtualizationService")
Andrew Walbranf395b822021-05-05 10:38:59 +0000102 } else {
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000103 // Wait until the VM or VirtualizationService dies. If we just returned immediately then the
Andrew Walbranf395b822021-05-05 10:38:59 +0000104 // IVirtualMachine Binder object would be dropped and the VM would be killed.
105 wait_for_vm(vm)
106 }
107}
108
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000109/// Wait until the given VM or the VirtualizationService itself dies.
Andrew Walbranf395b822021-05-05 10:38:59 +0000110fn wait_for_vm(vm: Strong<dyn IVirtualMachine>) -> Result<(), Error> {
111 let dead = AtomicFlag::default();
112 let callback = BnVirtualMachineCallback::new_binder(
113 VirtualMachineCallback { dead: dead.clone() },
114 BinderFeatures::default(),
115 );
116 vm.registerCallback(&callback)?;
117 let death_recipient = wait_for_death(&mut vm.as_binder(), dead.clone())?;
118 dead.wait();
119 // Ensure that death_recipient isn't dropped before we wait on the flag, as it is removed
120 // from the Binder when it's dropped.
121 drop(death_recipient);
122 Ok(())
123}
124
125/// Raise the given flag when the given Binder object dies.
126///
127/// If the returned DeathRecipient is dropped then this will no longer do anything.
128fn wait_for_death(binder: &mut impl IBinder, dead: AtomicFlag) -> Result<DeathRecipient, Error> {
129 let mut death_recipient = DeathRecipient::new(move || {
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000130 println!("VirtualizationService died");
Andrew Walbranf395b822021-05-05 10:38:59 +0000131 dead.raise();
132 });
133 binder.link_to_death(&mut death_recipient)?;
134 Ok(death_recipient)
135}
136
137#[derive(Debug)]
138struct VirtualMachineCallback {
139 dead: AtomicFlag,
140}
141
142impl Interface for VirtualMachineCallback {}
143
144impl IVirtualMachineCallback for VirtualMachineCallback {
145 fn onDied(&self, _cid: i32) -> BinderResult<()> {
146 println!("VM died");
147 self.dead.raise();
148 Ok(())
149 }
150}
151
152/// Safely duplicate the standard output file descriptor.
153fn duplicate_stdout() -> io::Result<File> {
154 let stdout_fd = io::stdout().as_raw_fd();
155 // Safe because this just duplicates a file descriptor which we know to be valid, and we check
156 // for an error.
157 let dup_fd = unsafe { libc::dup(stdout_fd) };
158 if dup_fd < 0 {
159 Err(io::Error::last_os_error())
160 } else {
161 // Safe because we have just duplicated the file descriptor so we own it, and `from_raw_fd`
162 // takes ownership of it.
163 Ok(unsafe { File::from_raw_fd(dup_fd) })
164 }
165}