blob: 42da6a3a2b9b77e15948c3dbd74509045a9a8e46 [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::IVirtualMachineCallback::{
Andrew Walbranf395b822021-05-05 10:38:59 +000020 BnVirtualMachineCallback, IVirtualMachineCallback,
21};
Jooyung Han21e9b922021-06-26 04:14:16 +090022use android_system_virtualizationservice::aidl::android::system::virtualizationservice::{
Andrew Walbranf8d94112021-09-07 11:45:36 +000023 IVirtualMachine::IVirtualMachine,
24 IVirtualizationService::IVirtualizationService,
Jiyong Park9dd389e2021-08-23 20:42:59 +090025 PartitionType::PartitionType,
Jooyung Han21e9b922021-06-26 04:14:16 +090026 VirtualMachineAppConfig::VirtualMachineAppConfig,
27 VirtualMachineConfig::VirtualMachineConfig,
Andrew Walbranf8d94112021-09-07 11:45:36 +000028 VirtualMachineState::VirtualMachineState,
Jooyung Han21e9b922021-06-26 04:14:16 +090029};
Andrew Walbranf6bf6862021-05-21 12:41:13 +000030use android_system_virtualizationservice::binder::{
Andrew Walbranf395b822021-05-05 10:38:59 +000031 BinderFeatures, DeathRecipient, IBinder, ParcelFileDescriptor, Strong,
32};
Andrew Walbranf6bf6862021-05-21 12:41:13 +000033use android_system_virtualizationservice::binder::{Interface, Result as BinderResult};
Andrew Walbranf395b822021-05-05 10:38:59 +000034use anyhow::{Context, Error};
35use std::fs::File;
Jiyong Park8611a6c2021-07-09 18:17:44 +090036use std::io::{self, BufRead, BufReader};
Andrew Walbranf395b822021-05-05 10:38:59 +000037use std::os::unix::io::{AsRawFd, FromRawFd};
38use std::path::Path;
Jiyong Park48b354d2021-07-15 15:04:38 +090039use vmconfig::{open_parcel_file, VmConfig};
Andrew Walbranf395b822021-05-05 10:38:59 +000040
Jooyung Han21e9b922021-06-26 04:14:16 +090041/// Run a VM from the given APK, idsig, and config.
Jiyong Park48b354d2021-07-15 15:04:38 +090042#[allow(clippy::too_many_arguments)]
Jooyung Han21e9b922021-06-26 04:14:16 +090043pub fn command_run_app(
44 service: Strong<dyn IVirtualizationService>,
45 apk: &Path,
46 idsig: &Path,
Jiyong Park48b354d2021-07-15 15:04:38 +090047 instance: &Path,
Jooyung Han21e9b922021-06-26 04:14:16 +090048 config_path: &str,
49 daemonize: bool,
50 log_path: Option<&Path>,
Jiyong Park23601142021-07-05 13:15:32 +090051 debug: bool,
Jiyong Parkd63cfff2021-09-27 20:10:17 +090052 mem: Option<u32>,
Jooyung Han21e9b922021-06-26 04:14:16 +090053) -> Result<(), Error> {
54 let apk_file = File::open(apk).context("Failed to open APK file")?;
Jiyong Park0a248432021-08-20 23:32:39 +090055 let idsig_file = File::create(idsig).context("Failed to create idsig file")?;
56
57 let apk_fd = ParcelFileDescriptor::new(apk_file);
58 let idsig_fd = ParcelFileDescriptor::new(idsig_file);
59 service.createOrUpdateIdsigFile(&apk_fd, &idsig_fd)?;
60
Jooyung Han21e9b922021-06-26 04:14:16 +090061 let idsig_file = File::open(idsig).context("Failed to open idsig file")?;
Jiyong Park0a248432021-08-20 23:32:39 +090062 let idsig_fd = ParcelFileDescriptor::new(idsig_file);
Jiyong Park48b354d2021-07-15 15:04:38 +090063
64 if !instance.exists() {
65 const INSTANCE_FILE_SIZE: u64 = 10 * 1024 * 1024;
Jiyong Park9dd389e2021-08-23 20:42:59 +090066 command_create_partition(
67 service.clone(),
68 instance,
69 INSTANCE_FILE_SIZE,
70 PartitionType::ANDROID_VM_INSTANCE,
71 )?;
Jiyong Park48b354d2021-07-15 15:04:38 +090072 }
73
Jooyung Han21e9b922021-06-26 04:14:16 +090074 let config = VirtualMachineConfig::AppConfig(VirtualMachineAppConfig {
Jiyong Park0a248432021-08-20 23:32:39 +090075 apk: apk_fd.into(),
76 idsig: idsig_fd.into(),
Jiyong Park48b354d2021-07-15 15:04:38 +090077 instanceImage: open_parcel_file(instance, true /* writable */)?.into(),
Jooyung Han21e9b922021-06-26 04:14:16 +090078 configPath: config_path.to_owned(),
Jiyong Park23601142021-07-05 13:15:32 +090079 debug,
Jiyong Parkd63cfff2021-09-27 20:10:17 +090080 memoryMib: mem.unwrap_or(0) as i32, // 0 means use the VM default
Jooyung Han21e9b922021-06-26 04:14:16 +090081 });
82 run(service, &config, &format!("{:?}!{:?}", apk, config_path), daemonize, log_path)
83}
84
Andrew Walbranf395b822021-05-05 10:38:59 +000085/// Run a VM from the given configuration file.
86pub fn command_run(
Andrew Walbran17de24f2021-05-27 13:27:30 +000087 service: Strong<dyn IVirtualizationService>,
Andrew Walbranf395b822021-05-05 10:38:59 +000088 config_path: &Path,
89 daemonize: bool,
Andrew Walbranbe429242021-06-28 12:22:54 +000090 log_path: Option<&Path>,
Jiyong Parkd63cfff2021-09-27 20:10:17 +090091 mem: Option<u32>,
Andrew Walbranf395b822021-05-05 10:38:59 +000092) -> Result<(), Error> {
Andrew Walbran3a5a9212021-05-04 17:09:08 +000093 let config_file = File::open(config_path).context("Failed to open config file")?;
Jiyong Parkd63cfff2021-09-27 20:10:17 +090094 let mut config =
Andrew Walbran3a5a9212021-05-04 17:09:08 +000095 VmConfig::load(&config_file).context("Failed to parse config file")?.to_parcelable()?;
Jiyong Parkd63cfff2021-09-27 20:10:17 +090096 if let Some(mem) = mem {
97 config.memoryMib = mem as i32;
98 }
Jooyung Han21e9b922021-06-26 04:14:16 +090099 run(
100 service,
101 &VirtualMachineConfig::RawConfig(config),
102 &format!("{:?}", config_path),
103 daemonize,
104 log_path,
105 )
106}
107
Andrew Walbranf8d94112021-09-07 11:45:36 +0000108fn state_to_str(vm_state: VirtualMachineState) -> &'static str {
109 match vm_state {
110 VirtualMachineState::NOT_STARTED => "NOT_STARTED",
111 VirtualMachineState::STARTING => "STARTING",
112 VirtualMachineState::STARTED => "STARTED",
113 VirtualMachineState::READY => "READY",
114 VirtualMachineState::FINISHED => "FINISHED",
115 VirtualMachineState::DEAD => "DEAD",
116 _ => "(invalid state)",
117 }
118}
119
Jooyung Han21e9b922021-06-26 04:14:16 +0900120fn run(
121 service: Strong<dyn IVirtualizationService>,
122 config: &VirtualMachineConfig,
123 config_path: &str,
124 daemonize: bool,
125 log_path: Option<&Path>,
126) -> Result<(), Error> {
Andrew Walbranbe429242021-06-28 12:22:54 +0000127 let stdout = if let Some(log_path) = log_path {
128 Some(ParcelFileDescriptor::new(
129 File::create(log_path)
130 .with_context(|| format!("Failed to open log file {:?}", log_path))?,
131 ))
132 } else if daemonize {
133 None
134 } else {
135 Some(ParcelFileDescriptor::new(duplicate_stdout()?))
136 };
Andrew Walbranf8d94112021-09-07 11:45:36 +0000137 let vm = service.createVm(config, stdout.as_ref()).context("Failed to create VM")?;
Andrew Walbranf395b822021-05-05 10:38:59 +0000138
139 let cid = vm.getCid().context("Failed to get CID")?;
Andrew Walbranf8d94112021-09-07 11:45:36 +0000140 println!(
141 "Created VM from {} with CID {}, state is {}.",
142 config_path,
143 cid,
144 state_to_str(vm.getState()?)
145 );
146 vm.start()?;
147 println!("Started VM, state now {}.", state_to_str(vm.getState()?));
Andrew Walbranf395b822021-05-05 10:38:59 +0000148
149 if daemonize {
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000150 // Pass the VM reference back to VirtualizationService and have it hold it in the
151 // background.
Andrew Walbran17de24f2021-05-27 13:27:30 +0000152 service.debugHoldVmRef(&vm).context("Failed to pass VM to VirtualizationService")
Andrew Walbranf395b822021-05-05 10:38:59 +0000153 } else {
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000154 // Wait until the VM or VirtualizationService dies. If we just returned immediately then the
Andrew Walbranf395b822021-05-05 10:38:59 +0000155 // IVirtualMachine Binder object would be dropped and the VM would be killed.
156 wait_for_vm(vm)
157 }
158}
159
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000160/// Wait until the given VM or the VirtualizationService itself dies.
Andrew Walbranf395b822021-05-05 10:38:59 +0000161fn wait_for_vm(vm: Strong<dyn IVirtualMachine>) -> Result<(), Error> {
162 let dead = AtomicFlag::default();
163 let callback = BnVirtualMachineCallback::new_binder(
164 VirtualMachineCallback { dead: dead.clone() },
165 BinderFeatures::default(),
166 );
167 vm.registerCallback(&callback)?;
168 let death_recipient = wait_for_death(&mut vm.as_binder(), dead.clone())?;
169 dead.wait();
170 // Ensure that death_recipient isn't dropped before we wait on the flag, as it is removed
171 // from the Binder when it's dropped.
172 drop(death_recipient);
173 Ok(())
174}
175
176/// Raise the given flag when the given Binder object dies.
177///
178/// If the returned DeathRecipient is dropped then this will no longer do anything.
179fn wait_for_death(binder: &mut impl IBinder, dead: AtomicFlag) -> Result<DeathRecipient, Error> {
180 let mut death_recipient = DeathRecipient::new(move || {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900181 eprintln!("VirtualizationService unexpectedly died");
Andrew Walbranf395b822021-05-05 10:38:59 +0000182 dead.raise();
183 });
184 binder.link_to_death(&mut death_recipient)?;
185 Ok(death_recipient)
186}
187
188#[derive(Debug)]
189struct VirtualMachineCallback {
190 dead: AtomicFlag,
191}
192
193impl Interface for VirtualMachineCallback {}
194
195impl IVirtualMachineCallback for VirtualMachineCallback {
Inseob Kim7f61fe72021-08-20 20:50:47 +0900196 fn onPayloadStarted(
197 &self,
198 _cid: i32,
199 stream: Option<&ParcelFileDescriptor>,
200 ) -> BinderResult<()> {
201 // Show the output of the payload
202 if let Some(stream) = stream {
203 let mut reader = BufReader::new(stream.as_ref());
204 loop {
205 let mut s = String::new();
206 match reader.read_line(&mut s) {
207 Ok(0) => break,
208 Ok(_) => print!("{}", s),
209 Err(e) => eprintln!("error reading from virtual machine: {}", e),
210 };
211 }
Jiyong Park8611a6c2021-07-09 18:17:44 +0900212 }
213 Ok(())
214 }
215
Inseob Kim14cb8692021-08-31 21:50:39 +0900216 fn onPayloadReady(&self, _cid: i32) -> BinderResult<()> {
Inseob Kim8dbc3222021-09-01 21:50:23 +0900217 eprintln!("payload is ready");
Inseob Kim14cb8692021-08-31 21:50:39 +0900218 Ok(())
219 }
220
Inseob Kim8dbc3222021-09-01 21:50:23 +0900221 fn onPayloadFinished(&self, _cid: i32, exit_code: i32) -> BinderResult<()> {
222 eprintln!("payload finished with exit code {}", exit_code);
Inseob Kim2444af92021-08-31 01:22:50 +0900223 Ok(())
224 }
225
Andrew Walbranf395b822021-05-05 10:38:59 +0000226 fn onDied(&self, _cid: i32) -> BinderResult<()> {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900227 // No need to explicitly report the event to the user (e.g. via println!) because this
228 // callback is registered only when the vm tool is invoked as interactive mode (e.g. not
229 // --daemonize) in which case the tool will exit to the shell prompt upon VM shutdown.
230 // Printing something will actually even confuse the user as the output from the app
231 // payload is printed.
Andrew Walbranf395b822021-05-05 10:38:59 +0000232 self.dead.raise();
233 Ok(())
234 }
235}
236
237/// Safely duplicate the standard output file descriptor.
238fn duplicate_stdout() -> io::Result<File> {
239 let stdout_fd = io::stdout().as_raw_fd();
240 // Safe because this just duplicates a file descriptor which we know to be valid, and we check
241 // for an error.
242 let dup_fd = unsafe { libc::dup(stdout_fd) };
243 if dup_fd < 0 {
244 Err(io::Error::last_os_error())
245 } else {
246 // Safe because we have just duplicated the file descriptor so we own it, and `from_raw_fd`
247 // takes ownership of it.
248 Ok(unsafe { File::from_raw_fd(dup_fd) })
249 }
250}