blob: 7f5f9fcd7f8a055c404327d47736298cd39d0875 [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};
Inseob Kima5a262f2021-11-17 19:41:03 +090031use anyhow::{bail, Context, Error};
32use microdroid_payload_config::VmPayloadConfig;
Andrew Walbranf395b822021-05-05 10:38:59 +000033use 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};
Inseob Kima5a262f2021-11-17 19:41:03 +090036use std::path::{Path, PathBuf};
Jiyong Park48b354d2021-07-15 15:04:38 +090037use vmconfig::{open_parcel_file, VmConfig};
Inseob Kima5a262f2021-11-17 19:41:03 +090038use zip::ZipArchive;
Andrew Walbranf395b822021-05-05 10:38:59 +000039
Jooyung Han21e9b922021-06-26 04:14:16 +090040/// Run a VM from the given APK, idsig, and config.
Jiyong Park48b354d2021-07-15 15:04:38 +090041#[allow(clippy::too_many_arguments)]
Jooyung Han21e9b922021-06-26 04:14:16 +090042pub fn command_run_app(
43 service: Strong<dyn IVirtualizationService>,
44 apk: &Path,
45 idsig: &Path,
Jiyong Park48b354d2021-07-15 15:04:38 +090046 instance: &Path,
Jooyung Han21e9b922021-06-26 04:14:16 +090047 config_path: &str,
48 daemonize: bool,
Jiyong Parkb8182bb2021-10-26 22:53:08 +090049 console_path: Option<&Path>,
Jooyung Han21e9b922021-06-26 04:14:16 +090050 log_path: Option<&Path>,
Jiyong Parkc2a49cc2021-10-15 00:02:12 +090051 debug_level: DebugLevel,
Jiyong Parkd63cfff2021-09-27 20:10:17 +090052 mem: Option<u32>,
Inseob Kima5a262f2021-11-17 19:41:03 +090053 extra_idsigs: &[PathBuf],
Jooyung Han21e9b922021-06-26 04:14:16 +090054) -> Result<(), Error> {
Inseob Kima5a262f2021-11-17 19:41:03 +090055 let extra_apks = parse_extra_apk_list(apk, config_path)?;
56 if extra_apks.len() != extra_idsigs.len() {
57 bail!(
58 "Found {} extra apks, but there are {} extra idsigs",
59 extra_apks.len(),
60 extra_idsigs.len()
61 )
62 }
63
64 for i in 0..extra_apks.len() {
65 let extra_apk_fd = ParcelFileDescriptor::new(File::open(&extra_apks[i])?);
66 let extra_idsig_fd = ParcelFileDescriptor::new(File::create(&extra_idsigs[i])?);
67 service.createOrUpdateIdsigFile(&extra_apk_fd, &extra_idsig_fd)?;
68 }
69
Jooyung Han21e9b922021-06-26 04:14:16 +090070 let apk_file = File::open(apk).context("Failed to open APK file")?;
Jiyong Park0a248432021-08-20 23:32:39 +090071 let idsig_file = File::create(idsig).context("Failed to create idsig file")?;
72
73 let apk_fd = ParcelFileDescriptor::new(apk_file);
74 let idsig_fd = ParcelFileDescriptor::new(idsig_file);
75 service.createOrUpdateIdsigFile(&apk_fd, &idsig_fd)?;
76
Jooyung Han21e9b922021-06-26 04:14:16 +090077 let idsig_file = File::open(idsig).context("Failed to open idsig file")?;
Jiyong Park0a248432021-08-20 23:32:39 +090078 let idsig_fd = ParcelFileDescriptor::new(idsig_file);
Jiyong Park48b354d2021-07-15 15:04:38 +090079
80 if !instance.exists() {
81 const INSTANCE_FILE_SIZE: u64 = 10 * 1024 * 1024;
Jiyong Park9dd389e2021-08-23 20:42:59 +090082 command_create_partition(
83 service.clone(),
84 instance,
85 INSTANCE_FILE_SIZE,
86 PartitionType::ANDROID_VM_INSTANCE,
87 )?;
Jiyong Park48b354d2021-07-15 15:04:38 +090088 }
89
Inseob Kima5a262f2021-11-17 19:41:03 +090090 let extra_idsig_files: Result<Vec<File>, _> = extra_idsigs.iter().map(File::open).collect();
91 let extra_idsig_fds = extra_idsig_files?.into_iter().map(ParcelFileDescriptor::new).collect();
92
Jooyung Han21e9b922021-06-26 04:14:16 +090093 let config = VirtualMachineConfig::AppConfig(VirtualMachineAppConfig {
Jiyong Park0a248432021-08-20 23:32:39 +090094 apk: apk_fd.into(),
95 idsig: idsig_fd.into(),
Inseob Kima5a262f2021-11-17 19:41:03 +090096 extraIdsigs: extra_idsig_fds,
Jiyong Park48b354d2021-07-15 15:04:38 +090097 instanceImage: open_parcel_file(instance, true /* writable */)?.into(),
Jooyung Han21e9b922021-06-26 04:14:16 +090098 configPath: config_path.to_owned(),
Jiyong Parkc2a49cc2021-10-15 00:02:12 +090099 debugLevel: debug_level,
Jiyong Parkd63cfff2021-09-27 20:10:17 +0900100 memoryMib: mem.unwrap_or(0) as i32, // 0 means use the VM default
Jooyung Han21e9b922021-06-26 04:14:16 +0900101 });
Jiyong Parkb8182bb2021-10-26 22:53:08 +0900102 run(
103 service,
104 &config,
105 &format!("{:?}!{:?}", apk, config_path),
106 daemonize,
107 console_path,
108 log_path,
109 )
Jooyung Han21e9b922021-06-26 04:14:16 +0900110}
111
Andrew Walbranf395b822021-05-05 10:38:59 +0000112/// Run a VM from the given configuration file.
113pub fn command_run(
Andrew Walbran17de24f2021-05-27 13:27:30 +0000114 service: Strong<dyn IVirtualizationService>,
Andrew Walbranf395b822021-05-05 10:38:59 +0000115 config_path: &Path,
116 daemonize: bool,
Jiyong Parkb8182bb2021-10-26 22:53:08 +0900117 console_path: Option<&Path>,
Jiyong Parkd63cfff2021-09-27 20:10:17 +0900118 mem: Option<u32>,
Andrew Walbranf395b822021-05-05 10:38:59 +0000119) -> Result<(), Error> {
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000120 let config_file = File::open(config_path).context("Failed to open config file")?;
Jiyong Parkd63cfff2021-09-27 20:10:17 +0900121 let mut config =
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000122 VmConfig::load(&config_file).context("Failed to parse config file")?.to_parcelable()?;
Jiyong Parkd63cfff2021-09-27 20:10:17 +0900123 if let Some(mem) = mem {
124 config.memoryMib = mem as i32;
125 }
Jooyung Han21e9b922021-06-26 04:14:16 +0900126 run(
127 service,
128 &VirtualMachineConfig::RawConfig(config),
129 &format!("{:?}", config_path),
130 daemonize,
Jiyong Parkb8182bb2021-10-26 22:53:08 +0900131 console_path,
132 None,
Jooyung Han21e9b922021-06-26 04:14:16 +0900133 )
134}
135
Andrew Walbranf8d94112021-09-07 11:45:36 +0000136fn state_to_str(vm_state: VirtualMachineState) -> &'static str {
137 match vm_state {
138 VirtualMachineState::NOT_STARTED => "NOT_STARTED",
139 VirtualMachineState::STARTING => "STARTING",
140 VirtualMachineState::STARTED => "STARTED",
141 VirtualMachineState::READY => "READY",
142 VirtualMachineState::FINISHED => "FINISHED",
143 VirtualMachineState::DEAD => "DEAD",
144 _ => "(invalid state)",
145 }
146}
147
Jooyung Han21e9b922021-06-26 04:14:16 +0900148fn run(
149 service: Strong<dyn IVirtualizationService>,
150 config: &VirtualMachineConfig,
151 config_path: &str,
152 daemonize: bool,
Jiyong Parkb8182bb2021-10-26 22:53:08 +0900153 console_path: Option<&Path>,
Jooyung Han21e9b922021-06-26 04:14:16 +0900154 log_path: Option<&Path>,
155) -> Result<(), Error> {
Jiyong Parkb8182bb2021-10-26 22:53:08 +0900156 let console = if let Some(console_path) = console_path {
157 Some(ParcelFileDescriptor::new(
158 File::create(console_path)
159 .with_context(|| format!("Failed to open console file {:?}", console_path))?,
160 ))
161 } else if daemonize {
162 None
163 } else {
164 Some(ParcelFileDescriptor::new(duplicate_stdout()?))
165 };
166 let log = if let Some(log_path) = log_path {
Andrew Walbranbe429242021-06-28 12:22:54 +0000167 Some(ParcelFileDescriptor::new(
168 File::create(log_path)
169 .with_context(|| format!("Failed to open log file {:?}", log_path))?,
170 ))
171 } else if daemonize {
172 None
173 } else {
174 Some(ParcelFileDescriptor::new(duplicate_stdout()?))
175 };
Jiyong Parkb8182bb2021-10-26 22:53:08 +0900176
177 let vm =
178 service.createVm(config, console.as_ref(), log.as_ref()).context("Failed to create VM")?;
Andrew Walbranf395b822021-05-05 10:38:59 +0000179
180 let cid = vm.getCid().context("Failed to get CID")?;
Andrew Walbranf8d94112021-09-07 11:45:36 +0000181 println!(
182 "Created VM from {} with CID {}, state is {}.",
183 config_path,
184 cid,
185 state_to_str(vm.getState()?)
186 );
187 vm.start()?;
188 println!("Started VM, state now {}.", state_to_str(vm.getState()?));
Andrew Walbranf395b822021-05-05 10:38:59 +0000189
190 if daemonize {
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000191 // Pass the VM reference back to VirtualizationService and have it hold it in the
192 // background.
Andrew Walbran17de24f2021-05-27 13:27:30 +0000193 service.debugHoldVmRef(&vm).context("Failed to pass VM to VirtualizationService")
Andrew Walbranf395b822021-05-05 10:38:59 +0000194 } else {
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000195 // Wait until the VM or VirtualizationService dies. If we just returned immediately then the
Andrew Walbranf395b822021-05-05 10:38:59 +0000196 // IVirtualMachine Binder object would be dropped and the VM would be killed.
197 wait_for_vm(vm)
198 }
199}
200
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000201/// Wait until the given VM or the VirtualizationService itself dies.
Andrew Walbranf395b822021-05-05 10:38:59 +0000202fn wait_for_vm(vm: Strong<dyn IVirtualMachine>) -> Result<(), Error> {
203 let dead = AtomicFlag::default();
204 let callback = BnVirtualMachineCallback::new_binder(
205 VirtualMachineCallback { dead: dead.clone() },
206 BinderFeatures::default(),
207 );
208 vm.registerCallback(&callback)?;
209 let death_recipient = wait_for_death(&mut vm.as_binder(), dead.clone())?;
210 dead.wait();
211 // Ensure that death_recipient isn't dropped before we wait on the flag, as it is removed
212 // from the Binder when it's dropped.
213 drop(death_recipient);
214 Ok(())
215}
216
217/// Raise the given flag when the given Binder object dies.
218///
219/// If the returned DeathRecipient is dropped then this will no longer do anything.
220fn wait_for_death(binder: &mut impl IBinder, dead: AtomicFlag) -> Result<DeathRecipient, Error> {
221 let mut death_recipient = DeathRecipient::new(move || {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900222 eprintln!("VirtualizationService unexpectedly died");
Andrew Walbranf395b822021-05-05 10:38:59 +0000223 dead.raise();
224 });
225 binder.link_to_death(&mut death_recipient)?;
226 Ok(death_recipient)
227}
228
Inseob Kima5a262f2021-11-17 19:41:03 +0900229fn parse_extra_apk_list(apk: &Path, config_path: &str) -> Result<Vec<String>, Error> {
230 let mut archive = ZipArchive::new(File::open(apk)?)?;
231 let config_file = archive.by_name(config_path)?;
232 let config: VmPayloadConfig = serde_json::from_reader(config_file)?;
233 Ok(config.extra_apks.into_iter().map(|x| x.path).collect())
234}
235
Andrew Walbranf395b822021-05-05 10:38:59 +0000236#[derive(Debug)]
237struct VirtualMachineCallback {
238 dead: AtomicFlag,
239}
240
241impl Interface for VirtualMachineCallback {}
242
243impl IVirtualMachineCallback for VirtualMachineCallback {
Inseob Kim7f61fe72021-08-20 20:50:47 +0900244 fn onPayloadStarted(
245 &self,
246 _cid: i32,
247 stream: Option<&ParcelFileDescriptor>,
248 ) -> BinderResult<()> {
249 // Show the output of the payload
250 if let Some(stream) = stream {
251 let mut reader = BufReader::new(stream.as_ref());
252 loop {
253 let mut s = String::new();
254 match reader.read_line(&mut s) {
255 Ok(0) => break,
256 Ok(_) => print!("{}", s),
257 Err(e) => eprintln!("error reading from virtual machine: {}", e),
258 };
259 }
Jiyong Park8611a6c2021-07-09 18:17:44 +0900260 }
261 Ok(())
262 }
263
Inseob Kim14cb8692021-08-31 21:50:39 +0900264 fn onPayloadReady(&self, _cid: i32) -> BinderResult<()> {
Inseob Kim8dbc3222021-09-01 21:50:23 +0900265 eprintln!("payload is ready");
Inseob Kim14cb8692021-08-31 21:50:39 +0900266 Ok(())
267 }
268
Inseob Kim8dbc3222021-09-01 21:50:23 +0900269 fn onPayloadFinished(&self, _cid: i32, exit_code: i32) -> BinderResult<()> {
270 eprintln!("payload finished with exit code {}", exit_code);
Inseob Kim2444af92021-08-31 01:22:50 +0900271 Ok(())
272 }
273
Jooyung Handd0a1732021-11-23 15:26:20 +0900274 fn onError(&self, _cid: i32, error_code: i32, message: &str) -> BinderResult<()> {
275 eprintln!("VM encountered an error: code={}, message={}", error_code, message);
276 Ok(())
277 }
278
Andrew Walbranf395b822021-05-05 10:38:59 +0000279 fn onDied(&self, _cid: i32) -> BinderResult<()> {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900280 // No need to explicitly report the event to the user (e.g. via println!) because this
281 // callback is registered only when the vm tool is invoked as interactive mode (e.g. not
282 // --daemonize) in which case the tool will exit to the shell prompt upon VM shutdown.
283 // Printing something will actually even confuse the user as the output from the app
284 // payload is printed.
Andrew Walbranf395b822021-05-05 10:38:59 +0000285 self.dead.raise();
286 Ok(())
287 }
288}
289
290/// Safely duplicate the standard output file descriptor.
291fn duplicate_stdout() -> io::Result<File> {
292 let stdout_fd = io::stdout().as_raw_fd();
293 // Safe because this just duplicates a file descriptor which we know to be valid, and we check
294 // for an error.
295 let dup_fd = unsafe { libc::dup(stdout_fd) };
296 if dup_fd < 0 {
297 Err(io::Error::last_os_error())
298 } else {
299 // Safe because we have just duplicated the file descriptor so we own it, and `from_raw_fd`
300 // takes ownership of it.
301 Ok(unsafe { File::from_raw_fd(dup_fd) })
302 }
303}