blob: 5b3f193b4e27fa7e9f4c7155c777e960932e4b7d [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,
Andrew Walbran45bcb0c2021-07-14 15:02:06 +000065 // Use the default.
Andrew Walbrancc045902021-07-27 16:06:17 +000066 memoryMib: 0,
Jooyung Han21e9b922021-06-26 04:14:16 +090067 });
68 run(service, &config, &format!("{:?}!{:?}", apk, config_path), daemonize, log_path)
69}
70
Andrew Walbranf395b822021-05-05 10:38:59 +000071/// Run a VM from the given configuration file.
72pub fn command_run(
Andrew Walbran17de24f2021-05-27 13:27:30 +000073 service: Strong<dyn IVirtualizationService>,
Andrew Walbranf395b822021-05-05 10:38:59 +000074 config_path: &Path,
75 daemonize: bool,
Andrew Walbranbe429242021-06-28 12:22:54 +000076 log_path: Option<&Path>,
Andrew Walbranf395b822021-05-05 10:38:59 +000077) -> Result<(), Error> {
Andrew Walbran3a5a9212021-05-04 17:09:08 +000078 let config_file = File::open(config_path).context("Failed to open config file")?;
79 let config =
80 VmConfig::load(&config_file).context("Failed to parse config file")?.to_parcelable()?;
Jooyung Han21e9b922021-06-26 04:14:16 +090081 run(
82 service,
83 &VirtualMachineConfig::RawConfig(config),
84 &format!("{:?}", config_path),
85 daemonize,
86 log_path,
87 )
88}
89
90fn run(
91 service: Strong<dyn IVirtualizationService>,
92 config: &VirtualMachineConfig,
93 config_path: &str,
94 daemonize: bool,
95 log_path: Option<&Path>,
96) -> Result<(), Error> {
Andrew Walbranbe429242021-06-28 12:22:54 +000097 let stdout = if let Some(log_path) = log_path {
98 Some(ParcelFileDescriptor::new(
99 File::create(log_path)
100 .with_context(|| format!("Failed to open log file {:?}", log_path))?,
101 ))
102 } else if daemonize {
103 None
104 } else {
105 Some(ParcelFileDescriptor::new(duplicate_stdout()?))
106 };
Jooyung Han21e9b922021-06-26 04:14:16 +0900107 let vm = service.startVm(config, stdout.as_ref()).context("Failed to start VM")?;
Andrew Walbranf395b822021-05-05 10:38:59 +0000108
109 let cid = vm.getCid().context("Failed to get CID")?;
Jooyung Han35edb8f2021-07-01 16:17:16 +0900110 println!("Started VM from {} with CID {}.", config_path, cid);
Andrew Walbranf395b822021-05-05 10:38:59 +0000111
112 if daemonize {
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000113 // Pass the VM reference back to VirtualizationService and have it hold it in the
114 // background.
Andrew Walbran17de24f2021-05-27 13:27:30 +0000115 service.debugHoldVmRef(&vm).context("Failed to pass VM to VirtualizationService")
Andrew Walbranf395b822021-05-05 10:38:59 +0000116 } else {
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000117 // Wait until the VM or VirtualizationService dies. If we just returned immediately then the
Andrew Walbranf395b822021-05-05 10:38:59 +0000118 // IVirtualMachine Binder object would be dropped and the VM would be killed.
119 wait_for_vm(vm)
120 }
121}
122
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000123/// Wait until the given VM or the VirtualizationService itself dies.
Andrew Walbranf395b822021-05-05 10:38:59 +0000124fn wait_for_vm(vm: Strong<dyn IVirtualMachine>) -> Result<(), Error> {
125 let dead = AtomicFlag::default();
126 let callback = BnVirtualMachineCallback::new_binder(
127 VirtualMachineCallback { dead: dead.clone() },
128 BinderFeatures::default(),
129 );
130 vm.registerCallback(&callback)?;
131 let death_recipient = wait_for_death(&mut vm.as_binder(), dead.clone())?;
132 dead.wait();
133 // Ensure that death_recipient isn't dropped before we wait on the flag, as it is removed
134 // from the Binder when it's dropped.
135 drop(death_recipient);
136 Ok(())
137}
138
139/// Raise the given flag when the given Binder object dies.
140///
141/// If the returned DeathRecipient is dropped then this will no longer do anything.
142fn wait_for_death(binder: &mut impl IBinder, dead: AtomicFlag) -> Result<DeathRecipient, Error> {
143 let mut death_recipient = DeathRecipient::new(move || {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900144 eprintln!("VirtualizationService unexpectedly died");
Andrew Walbranf395b822021-05-05 10:38:59 +0000145 dead.raise();
146 });
147 binder.link_to_death(&mut death_recipient)?;
148 Ok(death_recipient)
149}
150
151#[derive(Debug)]
152struct VirtualMachineCallback {
153 dead: AtomicFlag,
154}
155
156impl Interface for VirtualMachineCallback {}
157
158impl IVirtualMachineCallback for VirtualMachineCallback {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900159 fn onPayloadStarted(&self, _cid: i32, stdout: &ParcelFileDescriptor) -> BinderResult<()> {
160 // Show the stdout of the payload
161 let mut reader = BufReader::new(stdout.as_ref());
162 loop {
163 let mut s = String::new();
164 match reader.read_line(&mut s) {
165 Ok(0) => break,
166 Ok(_) => print!("{}", s),
167 Err(e) => eprintln!("error reading from virtual machine: {}", e),
168 };
169 }
170 Ok(())
171 }
172
Andrew Walbranf395b822021-05-05 10:38:59 +0000173 fn onDied(&self, _cid: i32) -> BinderResult<()> {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900174 // No need to explicitly report the event to the user (e.g. via println!) because this
175 // callback is registered only when the vm tool is invoked as interactive mode (e.g. not
176 // --daemonize) in which case the tool will exit to the shell prompt upon VM shutdown.
177 // Printing something will actually even confuse the user as the output from the app
178 // payload is printed.
Andrew Walbranf395b822021-05-05 10:38:59 +0000179 self.dead.raise();
180 Ok(())
181 }
182}
183
184/// Safely duplicate the standard output file descriptor.
185fn duplicate_stdout() -> io::Result<File> {
186 let stdout_fd = io::stdout().as_raw_fd();
187 // Safe because this just duplicates a file descriptor which we know to be valid, and we check
188 // for an error.
189 let dup_fd = unsafe { libc::dup(stdout_fd) };
190 if dup_fd < 0 {
191 Err(io::Error::last_os_error())
192 } else {
193 // Safe because we have just duplicated the file descriptor so we own it, and `from_raw_fd`
194 // takes ownership of it.
195 Ok(unsafe { File::from_raw_fd(dup_fd) })
196 }
197}