blob: 41fdabb740b396b389b443979c49a3cf8f314b94 [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
Jiyong Park48b354d2021-07-15 15:04:38 +090017use crate::create_partition::command_create_partition;
Andrew Walbranf395b822021-05-05 10:38:59 +000018use crate::sync::AtomicFlag;
Andrew Walbranf6bf6862021-05-21 12:41:13 +000019use android_system_virtualizationservice::aidl::android::system::virtualizationservice::IVirtualizationService::IVirtualizationService;
20use android_system_virtualizationservice::aidl::android::system::virtualizationservice::IVirtualMachine::IVirtualMachine;
21use android_system_virtualizationservice::aidl::android::system::virtualizationservice::IVirtualMachineCallback::{
Andrew Walbranf395b822021-05-05 10:38:59 +000022 BnVirtualMachineCallback, IVirtualMachineCallback,
23};
Jooyung Han21e9b922021-06-26 04:14:16 +090024use android_system_virtualizationservice::aidl::android::system::virtualizationservice::{
25 VirtualMachineAppConfig::VirtualMachineAppConfig,
26 VirtualMachineConfig::VirtualMachineConfig,
27};
Andrew Walbranf6bf6862021-05-21 12:41:13 +000028use android_system_virtualizationservice::binder::{
Andrew Walbranf395b822021-05-05 10:38:59 +000029 BinderFeatures, DeathRecipient, IBinder, ParcelFileDescriptor, Strong,
30};
Andrew Walbranf6bf6862021-05-21 12:41:13 +000031use android_system_virtualizationservice::binder::{Interface, Result as BinderResult};
Andrew Walbranf395b822021-05-05 10:38:59 +000032use anyhow::{Context, Error};
33use std::fs::File;
Jiyong Park8611a6c2021-07-09 18:17:44 +090034use std::io::{self, BufRead, BufReader};
Andrew Walbranf395b822021-05-05 10:38:59 +000035use std::os::unix::io::{AsRawFd, FromRawFd};
36use std::path::Path;
Jiyong Park48b354d2021-07-15 15:04:38 +090037use vmconfig::{open_parcel_file, VmConfig};
Andrew Walbranf395b822021-05-05 10:38:59 +000038
Jooyung Han21e9b922021-06-26 04:14:16 +090039/// Run a VM from the given APK, idsig, and config.
Jiyong Park48b354d2021-07-15 15:04:38 +090040#[allow(clippy::too_many_arguments)]
Jooyung Han21e9b922021-06-26 04:14:16 +090041pub fn command_run_app(
42 service: Strong<dyn IVirtualizationService>,
43 apk: &Path,
44 idsig: &Path,
Jiyong Park48b354d2021-07-15 15:04:38 +090045 instance: &Path,
Jooyung Han21e9b922021-06-26 04:14:16 +090046 config_path: &str,
47 daemonize: bool,
48 log_path: Option<&Path>,
Jiyong Park23601142021-07-05 13:15:32 +090049 debug: bool,
Jooyung Han21e9b922021-06-26 04:14:16 +090050) -> Result<(), Error> {
51 let apk_file = File::open(apk).context("Failed to open APK file")?;
52 let idsig_file = File::open(idsig).context("Failed to open idsig file")?;
Jiyong Park48b354d2021-07-15 15:04:38 +090053
54 if !instance.exists() {
55 const INSTANCE_FILE_SIZE: u64 = 10 * 1024 * 1024;
56 command_create_partition(service.clone(), instance, INSTANCE_FILE_SIZE)?;
57 }
58
Jooyung Han21e9b922021-06-26 04:14:16 +090059 let config = VirtualMachineConfig::AppConfig(VirtualMachineAppConfig {
60 apk: ParcelFileDescriptor::new(apk_file).into(),
61 idsig: ParcelFileDescriptor::new(idsig_file).into(),
Jiyong Park48b354d2021-07-15 15:04:38 +090062 instanceImage: open_parcel_file(instance, true /* writable */)?.into(),
Jooyung Han21e9b922021-06-26 04:14:16 +090063 configPath: config_path.to_owned(),
Jiyong Park23601142021-07-05 13:15:32 +090064 debug,
Jooyung Han21e9b922021-06-26 04:14:16 +090065 });
66 run(service, &config, &format!("{:?}!{:?}", apk, config_path), daemonize, log_path)
67}
68
Andrew Walbranf395b822021-05-05 10:38:59 +000069/// Run a VM from the given configuration file.
70pub fn command_run(
Andrew Walbran17de24f2021-05-27 13:27:30 +000071 service: Strong<dyn IVirtualizationService>,
Andrew Walbranf395b822021-05-05 10:38:59 +000072 config_path: &Path,
73 daemonize: bool,
Andrew Walbranbe429242021-06-28 12:22:54 +000074 log_path: Option<&Path>,
Andrew Walbranf395b822021-05-05 10:38:59 +000075) -> Result<(), Error> {
Andrew Walbran3a5a9212021-05-04 17:09:08 +000076 let config_file = File::open(config_path).context("Failed to open config file")?;
77 let config =
78 VmConfig::load(&config_file).context("Failed to parse config file")?.to_parcelable()?;
Jooyung Han21e9b922021-06-26 04:14:16 +090079 run(
80 service,
81 &VirtualMachineConfig::RawConfig(config),
82 &format!("{:?}", config_path),
83 daemonize,
84 log_path,
85 )
86}
87
88fn run(
89 service: Strong<dyn IVirtualizationService>,
90 config: &VirtualMachineConfig,
91 config_path: &str,
92 daemonize: bool,
93 log_path: Option<&Path>,
94) -> Result<(), Error> {
Andrew Walbranbe429242021-06-28 12:22:54 +000095 let stdout = if let Some(log_path) = log_path {
96 Some(ParcelFileDescriptor::new(
97 File::create(log_path)
98 .with_context(|| format!("Failed to open log file {:?}", log_path))?,
99 ))
100 } else if daemonize {
101 None
102 } else {
103 Some(ParcelFileDescriptor::new(duplicate_stdout()?))
104 };
Jooyung Han21e9b922021-06-26 04:14:16 +0900105 let vm = service.startVm(config, stdout.as_ref()).context("Failed to start VM")?;
Andrew Walbranf395b822021-05-05 10:38:59 +0000106
107 let cid = vm.getCid().context("Failed to get CID")?;
Jooyung Han35edb8f2021-07-01 16:17:16 +0900108 println!("Started VM from {} with CID {}.", config_path, cid);
Andrew Walbranf395b822021-05-05 10:38:59 +0000109
110 if daemonize {
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000111 // Pass the VM reference back to VirtualizationService and have it hold it in the
112 // background.
Andrew Walbran17de24f2021-05-27 13:27:30 +0000113 service.debugHoldVmRef(&vm).context("Failed to pass VM to VirtualizationService")
Andrew Walbranf395b822021-05-05 10:38:59 +0000114 } else {
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000115 // Wait until the VM or VirtualizationService dies. If we just returned immediately then the
Andrew Walbranf395b822021-05-05 10:38:59 +0000116 // IVirtualMachine Binder object would be dropped and the VM would be killed.
117 wait_for_vm(vm)
118 }
119}
120
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000121/// Wait until the given VM or the VirtualizationService itself dies.
Andrew Walbranf395b822021-05-05 10:38:59 +0000122fn wait_for_vm(vm: Strong<dyn IVirtualMachine>) -> Result<(), Error> {
123 let dead = AtomicFlag::default();
124 let callback = BnVirtualMachineCallback::new_binder(
125 VirtualMachineCallback { dead: dead.clone() },
126 BinderFeatures::default(),
127 );
128 vm.registerCallback(&callback)?;
129 let death_recipient = wait_for_death(&mut vm.as_binder(), dead.clone())?;
130 dead.wait();
131 // Ensure that death_recipient isn't dropped before we wait on the flag, as it is removed
132 // from the Binder when it's dropped.
133 drop(death_recipient);
134 Ok(())
135}
136
137/// Raise the given flag when the given Binder object dies.
138///
139/// If the returned DeathRecipient is dropped then this will no longer do anything.
140fn wait_for_death(binder: &mut impl IBinder, dead: AtomicFlag) -> Result<DeathRecipient, Error> {
141 let mut death_recipient = DeathRecipient::new(move || {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900142 eprintln!("VirtualizationService unexpectedly died");
Andrew Walbranf395b822021-05-05 10:38:59 +0000143 dead.raise();
144 });
145 binder.link_to_death(&mut death_recipient)?;
146 Ok(death_recipient)
147}
148
149#[derive(Debug)]
150struct VirtualMachineCallback {
151 dead: AtomicFlag,
152}
153
154impl Interface for VirtualMachineCallback {}
155
156impl IVirtualMachineCallback for VirtualMachineCallback {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900157 fn onPayloadStarted(&self, _cid: i32, stdout: &ParcelFileDescriptor) -> BinderResult<()> {
158 // Show the stdout of the payload
159 let mut reader = BufReader::new(stdout.as_ref());
160 loop {
161 let mut s = String::new();
162 match reader.read_line(&mut s) {
163 Ok(0) => break,
164 Ok(_) => print!("{}", s),
165 Err(e) => eprintln!("error reading from virtual machine: {}", e),
166 };
167 }
168 Ok(())
169 }
170
Andrew Walbranf395b822021-05-05 10:38:59 +0000171 fn onDied(&self, _cid: i32) -> BinderResult<()> {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900172 // No need to explicitly report the event to the user (e.g. via println!) because this
173 // callback is registered only when the vm tool is invoked as interactive mode (e.g. not
174 // --daemonize) in which case the tool will exit to the shell prompt upon VM shutdown.
175 // Printing something will actually even confuse the user as the output from the app
176 // payload is printed.
Andrew Walbranf395b822021-05-05 10:38:59 +0000177 self.dead.raise();
178 Ok(())
179 }
180}
181
182/// Safely duplicate the standard output file descriptor.
183fn duplicate_stdout() -> io::Result<File> {
184 let stdout_fd = io::stdout().as_raw_fd();
185 // Safe because this just duplicates a file descriptor which we know to be valid, and we check
186 // for an error.
187 let dup_fd = unsafe { libc::dup(stdout_fd) };
188 if dup_fd < 0 {
189 Err(io::Error::last_os_error())
190 } else {
191 // Safe because we have just duplicated the file descriptor so we own it, and `from_raw_fd`
192 // takes ownership of it.
193 Ok(unsafe { File::from_raw_fd(dup_fd) })
194 }
195}