blob: 6eb88e92962420b2677b08fce20e42cab1a3342b [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")?;
Jiyong Park0a248432021-08-20 23:32:39 +090052 let idsig_file = File::create(idsig).context("Failed to create idsig file")?;
53
54 let apk_fd = ParcelFileDescriptor::new(apk_file);
55 let idsig_fd = ParcelFileDescriptor::new(idsig_file);
56 service.createOrUpdateIdsigFile(&apk_fd, &idsig_fd)?;
57
Jooyung Han21e9b922021-06-26 04:14:16 +090058 let idsig_file = File::open(idsig).context("Failed to open idsig file")?;
Jiyong Park0a248432021-08-20 23:32:39 +090059 let idsig_fd = ParcelFileDescriptor::new(idsig_file);
Jiyong Park48b354d2021-07-15 15:04:38 +090060
61 if !instance.exists() {
62 const INSTANCE_FILE_SIZE: u64 = 10 * 1024 * 1024;
63 command_create_partition(service.clone(), instance, INSTANCE_FILE_SIZE)?;
64 }
65
Jooyung Han21e9b922021-06-26 04:14:16 +090066 let config = VirtualMachineConfig::AppConfig(VirtualMachineAppConfig {
Jiyong Park0a248432021-08-20 23:32:39 +090067 apk: apk_fd.into(),
68 idsig: idsig_fd.into(),
Jiyong Park48b354d2021-07-15 15:04:38 +090069 instanceImage: open_parcel_file(instance, true /* writable */)?.into(),
Jooyung Han21e9b922021-06-26 04:14:16 +090070 configPath: config_path.to_owned(),
Jiyong Park23601142021-07-05 13:15:32 +090071 debug,
Andrew Walbran45bcb0c2021-07-14 15:02:06 +000072 // Use the default.
Andrew Walbrancc045902021-07-27 16:06:17 +000073 memoryMib: 0,
Jooyung Han21e9b922021-06-26 04:14:16 +090074 });
75 run(service, &config, &format!("{:?}!{:?}", apk, config_path), daemonize, log_path)
76}
77
Andrew Walbranf395b822021-05-05 10:38:59 +000078/// Run a VM from the given configuration file.
79pub fn command_run(
Andrew Walbran17de24f2021-05-27 13:27:30 +000080 service: Strong<dyn IVirtualizationService>,
Andrew Walbranf395b822021-05-05 10:38:59 +000081 config_path: &Path,
82 daemonize: bool,
Andrew Walbranbe429242021-06-28 12:22:54 +000083 log_path: Option<&Path>,
Andrew Walbranf395b822021-05-05 10:38:59 +000084) -> Result<(), Error> {
Andrew Walbran3a5a9212021-05-04 17:09:08 +000085 let config_file = File::open(config_path).context("Failed to open config file")?;
86 let config =
87 VmConfig::load(&config_file).context("Failed to parse config file")?.to_parcelable()?;
Jooyung Han21e9b922021-06-26 04:14:16 +090088 run(
89 service,
90 &VirtualMachineConfig::RawConfig(config),
91 &format!("{:?}", config_path),
92 daemonize,
93 log_path,
94 )
95}
96
97fn run(
98 service: Strong<dyn IVirtualizationService>,
99 config: &VirtualMachineConfig,
100 config_path: &str,
101 daemonize: bool,
102 log_path: Option<&Path>,
103) -> Result<(), Error> {
Andrew Walbranbe429242021-06-28 12:22:54 +0000104 let stdout = if let Some(log_path) = log_path {
105 Some(ParcelFileDescriptor::new(
106 File::create(log_path)
107 .with_context(|| format!("Failed to open log file {:?}", log_path))?,
108 ))
109 } else if daemonize {
110 None
111 } else {
112 Some(ParcelFileDescriptor::new(duplicate_stdout()?))
113 };
Jooyung Han21e9b922021-06-26 04:14:16 +0900114 let vm = service.startVm(config, stdout.as_ref()).context("Failed to start VM")?;
Andrew Walbranf395b822021-05-05 10:38:59 +0000115
116 let cid = vm.getCid().context("Failed to get CID")?;
Jooyung Han35edb8f2021-07-01 16:17:16 +0900117 println!("Started VM from {} with CID {}.", config_path, cid);
Andrew Walbranf395b822021-05-05 10:38:59 +0000118
119 if daemonize {
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000120 // Pass the VM reference back to VirtualizationService and have it hold it in the
121 // background.
Andrew Walbran17de24f2021-05-27 13:27:30 +0000122 service.debugHoldVmRef(&vm).context("Failed to pass VM to VirtualizationService")
Andrew Walbranf395b822021-05-05 10:38:59 +0000123 } else {
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000124 // Wait until the VM or VirtualizationService dies. If we just returned immediately then the
Andrew Walbranf395b822021-05-05 10:38:59 +0000125 // IVirtualMachine Binder object would be dropped and the VM would be killed.
126 wait_for_vm(vm)
127 }
128}
129
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000130/// Wait until the given VM or the VirtualizationService itself dies.
Andrew Walbranf395b822021-05-05 10:38:59 +0000131fn wait_for_vm(vm: Strong<dyn IVirtualMachine>) -> Result<(), Error> {
132 let dead = AtomicFlag::default();
133 let callback = BnVirtualMachineCallback::new_binder(
134 VirtualMachineCallback { dead: dead.clone() },
135 BinderFeatures::default(),
136 );
137 vm.registerCallback(&callback)?;
138 let death_recipient = wait_for_death(&mut vm.as_binder(), dead.clone())?;
139 dead.wait();
140 // Ensure that death_recipient isn't dropped before we wait on the flag, as it is removed
141 // from the Binder when it's dropped.
142 drop(death_recipient);
143 Ok(())
144}
145
146/// Raise the given flag when the given Binder object dies.
147///
148/// If the returned DeathRecipient is dropped then this will no longer do anything.
149fn wait_for_death(binder: &mut impl IBinder, dead: AtomicFlag) -> Result<DeathRecipient, Error> {
150 let mut death_recipient = DeathRecipient::new(move || {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900151 eprintln!("VirtualizationService unexpectedly died");
Andrew Walbranf395b822021-05-05 10:38:59 +0000152 dead.raise();
153 });
154 binder.link_to_death(&mut death_recipient)?;
155 Ok(death_recipient)
156}
157
158#[derive(Debug)]
159struct VirtualMachineCallback {
160 dead: AtomicFlag,
161}
162
163impl Interface for VirtualMachineCallback {}
164
165impl IVirtualMachineCallback for VirtualMachineCallback {
Inseob Kim7f61fe72021-08-20 20:50:47 +0900166 fn onPayloadStarted(
167 &self,
168 _cid: i32,
169 stream: Option<&ParcelFileDescriptor>,
170 ) -> BinderResult<()> {
171 // Show the output of the payload
172 if let Some(stream) = stream {
173 let mut reader = BufReader::new(stream.as_ref());
174 loop {
175 let mut s = String::new();
176 match reader.read_line(&mut s) {
177 Ok(0) => break,
178 Ok(_) => print!("{}", s),
179 Err(e) => eprintln!("error reading from virtual machine: {}", e),
180 };
181 }
Jiyong Park8611a6c2021-07-09 18:17:44 +0900182 }
183 Ok(())
184 }
185
Andrew Walbranf395b822021-05-05 10:38:59 +0000186 fn onDied(&self, _cid: i32) -> BinderResult<()> {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900187 // No need to explicitly report the event to the user (e.g. via println!) because this
188 // callback is registered only when the vm tool is invoked as interactive mode (e.g. not
189 // --daemonize) in which case the tool will exit to the shell prompt upon VM shutdown.
190 // Printing something will actually even confuse the user as the output from the app
191 // payload is printed.
Andrew Walbranf395b822021-05-05 10:38:59 +0000192 self.dead.raise();
193 Ok(())
194 }
195}
196
197/// Safely duplicate the standard output file descriptor.
198fn duplicate_stdout() -> io::Result<File> {
199 let stdout_fd = io::stdout().as_raw_fd();
200 // Safe because this just duplicates a file descriptor which we know to be valid, and we check
201 // for an error.
202 let dup_fd = unsafe { libc::dup(stdout_fd) };
203 if dup_fd < 0 {
204 Err(io::Error::last_os_error())
205 } else {
206 // Safe because we have just duplicated the file descriptor so we own it, and `from_raw_fd`
207 // takes ownership of it.
208 Ok(unsafe { File::from_raw_fd(dup_fd) })
209 }
210}