blob: 2d771fc1d3f3d369ba01d0855f54181e67a1cfec [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;
Jooyung Han21e9b922021-06-26 04:14:16 +090019use android_system_virtualizationservice::aidl::android::system::virtualizationservice::{
Jiyong Parkc2a49cc2021-10-15 00:02:12 +090020 IVirtualMachine::IVirtualMachine, IVirtualMachineCallback::BnVirtualMachineCallback,
21 IVirtualMachineCallback::IVirtualMachineCallback,
22 IVirtualizationService::IVirtualizationService, PartitionType::PartitionType,
23 VirtualMachineAppConfig::DebugLevel::DebugLevel,
24 VirtualMachineAppConfig::VirtualMachineAppConfig, VirtualMachineConfig::VirtualMachineConfig,
Andrew Walbranf8d94112021-09-07 11:45:36 +000025 VirtualMachineState::VirtualMachineState,
Jooyung Han21e9b922021-06-26 04:14:16 +090026};
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;
Jiyong Park8611a6c2021-07-09 18:17:44 +090033use std::io::{self, BufRead, BufReader};
Andrew Walbranf395b822021-05-05 10:38:59 +000034use std::os::unix::io::{AsRawFd, FromRawFd};
35use std::path::Path;
Jiyong Park48b354d2021-07-15 15:04:38 +090036use vmconfig::{open_parcel_file, 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.
Jiyong Park48b354d2021-07-15 15:04:38 +090039#[allow(clippy::too_many_arguments)]
Jooyung Han21e9b922021-06-26 04:14:16 +090040pub fn command_run_app(
41 service: Strong<dyn IVirtualizationService>,
42 apk: &Path,
43 idsig: &Path,
Jiyong Park48b354d2021-07-15 15:04:38 +090044 instance: &Path,
Jooyung Han21e9b922021-06-26 04:14:16 +090045 config_path: &str,
46 daemonize: bool,
47 log_path: Option<&Path>,
Jiyong Parkc2a49cc2021-10-15 00:02:12 +090048 debug_level: DebugLevel,
Jiyong Parkd63cfff2021-09-27 20:10:17 +090049 mem: Option<u32>,
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;
Jiyong Park9dd389e2021-08-23 20:42:59 +090063 command_create_partition(
64 service.clone(),
65 instance,
66 INSTANCE_FILE_SIZE,
67 PartitionType::ANDROID_VM_INSTANCE,
68 )?;
Jiyong Park48b354d2021-07-15 15:04:38 +090069 }
70
Jooyung Han21e9b922021-06-26 04:14:16 +090071 let config = VirtualMachineConfig::AppConfig(VirtualMachineAppConfig {
Jiyong Park0a248432021-08-20 23:32:39 +090072 apk: apk_fd.into(),
73 idsig: idsig_fd.into(),
Jiyong Park48b354d2021-07-15 15:04:38 +090074 instanceImage: open_parcel_file(instance, true /* writable */)?.into(),
Jooyung Han21e9b922021-06-26 04:14:16 +090075 configPath: config_path.to_owned(),
Jiyong Parkc2a49cc2021-10-15 00:02:12 +090076 debugLevel: debug_level,
Jiyong Parkd63cfff2021-09-27 20:10:17 +090077 memoryMib: mem.unwrap_or(0) as i32, // 0 means use the VM default
Jooyung Han21e9b922021-06-26 04:14:16 +090078 });
79 run(service, &config, &format!("{:?}!{:?}", apk, config_path), daemonize, log_path)
80}
81
Andrew Walbranf395b822021-05-05 10:38:59 +000082/// Run a VM from the given configuration file.
83pub fn command_run(
Andrew Walbran17de24f2021-05-27 13:27:30 +000084 service: Strong<dyn IVirtualizationService>,
Andrew Walbranf395b822021-05-05 10:38:59 +000085 config_path: &Path,
86 daemonize: bool,
Andrew Walbranbe429242021-06-28 12:22:54 +000087 log_path: Option<&Path>,
Jiyong Parkd63cfff2021-09-27 20:10:17 +090088 mem: Option<u32>,
Andrew Walbranf395b822021-05-05 10:38:59 +000089) -> Result<(), Error> {
Andrew Walbran3a5a9212021-05-04 17:09:08 +000090 let config_file = File::open(config_path).context("Failed to open config file")?;
Jiyong Parkd63cfff2021-09-27 20:10:17 +090091 let mut config =
Andrew Walbran3a5a9212021-05-04 17:09:08 +000092 VmConfig::load(&config_file).context("Failed to parse config file")?.to_parcelable()?;
Jiyong Parkd63cfff2021-09-27 20:10:17 +090093 if let Some(mem) = mem {
94 config.memoryMib = mem as i32;
95 }
Jooyung Han21e9b922021-06-26 04:14:16 +090096 run(
97 service,
98 &VirtualMachineConfig::RawConfig(config),
99 &format!("{:?}", config_path),
100 daemonize,
101 log_path,
102 )
103}
104
Andrew Walbranf8d94112021-09-07 11:45:36 +0000105fn state_to_str(vm_state: VirtualMachineState) -> &'static str {
106 match vm_state {
107 VirtualMachineState::NOT_STARTED => "NOT_STARTED",
108 VirtualMachineState::STARTING => "STARTING",
109 VirtualMachineState::STARTED => "STARTED",
110 VirtualMachineState::READY => "READY",
111 VirtualMachineState::FINISHED => "FINISHED",
112 VirtualMachineState::DEAD => "DEAD",
113 _ => "(invalid state)",
114 }
115}
116
Jooyung Han21e9b922021-06-26 04:14:16 +0900117fn run(
118 service: Strong<dyn IVirtualizationService>,
119 config: &VirtualMachineConfig,
120 config_path: &str,
121 daemonize: bool,
122 log_path: Option<&Path>,
123) -> Result<(), Error> {
Andrew Walbranbe429242021-06-28 12:22:54 +0000124 let stdout = if let Some(log_path) = log_path {
125 Some(ParcelFileDescriptor::new(
126 File::create(log_path)
127 .with_context(|| format!("Failed to open log file {:?}", log_path))?,
128 ))
129 } else if daemonize {
130 None
131 } else {
132 Some(ParcelFileDescriptor::new(duplicate_stdout()?))
133 };
Andrew Walbranf8d94112021-09-07 11:45:36 +0000134 let vm = service.createVm(config, stdout.as_ref()).context("Failed to create VM")?;
Andrew Walbranf395b822021-05-05 10:38:59 +0000135
136 let cid = vm.getCid().context("Failed to get CID")?;
Andrew Walbranf8d94112021-09-07 11:45:36 +0000137 println!(
138 "Created VM from {} with CID {}, state is {}.",
139 config_path,
140 cid,
141 state_to_str(vm.getState()?)
142 );
143 vm.start()?;
144 println!("Started VM, state now {}.", state_to_str(vm.getState()?));
Andrew Walbranf395b822021-05-05 10:38:59 +0000145
146 if daemonize {
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000147 // Pass the VM reference back to VirtualizationService and have it hold it in the
148 // background.
Andrew Walbran17de24f2021-05-27 13:27:30 +0000149 service.debugHoldVmRef(&vm).context("Failed to pass VM to VirtualizationService")
Andrew Walbranf395b822021-05-05 10:38:59 +0000150 } else {
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000151 // Wait until the VM or VirtualizationService dies. If we just returned immediately then the
Andrew Walbranf395b822021-05-05 10:38:59 +0000152 // IVirtualMachine Binder object would be dropped and the VM would be killed.
153 wait_for_vm(vm)
154 }
155}
156
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000157/// Wait until the given VM or the VirtualizationService itself dies.
Andrew Walbranf395b822021-05-05 10:38:59 +0000158fn wait_for_vm(vm: Strong<dyn IVirtualMachine>) -> Result<(), Error> {
159 let dead = AtomicFlag::default();
160 let callback = BnVirtualMachineCallback::new_binder(
161 VirtualMachineCallback { dead: dead.clone() },
162 BinderFeatures::default(),
163 );
164 vm.registerCallback(&callback)?;
165 let death_recipient = wait_for_death(&mut vm.as_binder(), dead.clone())?;
166 dead.wait();
167 // Ensure that death_recipient isn't dropped before we wait on the flag, as it is removed
168 // from the Binder when it's dropped.
169 drop(death_recipient);
170 Ok(())
171}
172
173/// Raise the given flag when the given Binder object dies.
174///
175/// If the returned DeathRecipient is dropped then this will no longer do anything.
176fn wait_for_death(binder: &mut impl IBinder, dead: AtomicFlag) -> Result<DeathRecipient, Error> {
177 let mut death_recipient = DeathRecipient::new(move || {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900178 eprintln!("VirtualizationService unexpectedly died");
Andrew Walbranf395b822021-05-05 10:38:59 +0000179 dead.raise();
180 });
181 binder.link_to_death(&mut death_recipient)?;
182 Ok(death_recipient)
183}
184
185#[derive(Debug)]
186struct VirtualMachineCallback {
187 dead: AtomicFlag,
188}
189
190impl Interface for VirtualMachineCallback {}
191
192impl IVirtualMachineCallback for VirtualMachineCallback {
Inseob Kim7f61fe72021-08-20 20:50:47 +0900193 fn onPayloadStarted(
194 &self,
195 _cid: i32,
196 stream: Option<&ParcelFileDescriptor>,
197 ) -> BinderResult<()> {
198 // Show the output of the payload
199 if let Some(stream) = stream {
200 let mut reader = BufReader::new(stream.as_ref());
201 loop {
202 let mut s = String::new();
203 match reader.read_line(&mut s) {
204 Ok(0) => break,
205 Ok(_) => print!("{}", s),
206 Err(e) => eprintln!("error reading from virtual machine: {}", e),
207 };
208 }
Jiyong Park8611a6c2021-07-09 18:17:44 +0900209 }
210 Ok(())
211 }
212
Inseob Kim14cb8692021-08-31 21:50:39 +0900213 fn onPayloadReady(&self, _cid: i32) -> BinderResult<()> {
Inseob Kim8dbc3222021-09-01 21:50:23 +0900214 eprintln!("payload is ready");
Inseob Kim14cb8692021-08-31 21:50:39 +0900215 Ok(())
216 }
217
Inseob Kim8dbc3222021-09-01 21:50:23 +0900218 fn onPayloadFinished(&self, _cid: i32, exit_code: i32) -> BinderResult<()> {
219 eprintln!("payload finished with exit code {}", exit_code);
Inseob Kim2444af92021-08-31 01:22:50 +0900220 Ok(())
221 }
222
Andrew Walbranf395b822021-05-05 10:38:59 +0000223 fn onDied(&self, _cid: i32) -> BinderResult<()> {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900224 // No need to explicitly report the event to the user (e.g. via println!) because this
225 // callback is registered only when the vm tool is invoked as interactive mode (e.g. not
226 // --daemonize) in which case the tool will exit to the shell prompt upon VM shutdown.
227 // Printing something will actually even confuse the user as the output from the app
228 // payload is printed.
Andrew Walbranf395b822021-05-05 10:38:59 +0000229 self.dead.raise();
230 Ok(())
231 }
232}
233
234/// Safely duplicate the standard output file descriptor.
235fn duplicate_stdout() -> io::Result<File> {
236 let stdout_fd = io::stdout().as_raw_fd();
237 // Safe because this just duplicates a file descriptor which we know to be valid, and we check
238 // for an error.
239 let dup_fd = unsafe { libc::dup(stdout_fd) };
240 if dup_fd < 0 {
241 Err(io::Error::last_os_error())
242 } else {
243 // Safe because we have just duplicated the file descriptor so we own it, and `from_raw_fd`
244 // takes ownership of it.
245 Ok(unsafe { File::from_raw_fd(dup_fd) })
246 }
247}