blob: 15775cb57e57777907c4f5610a1a87e67b118f31 [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,
Jiyong Parkb8182bb2021-10-26 22:53:08 +090047 console_path: Option<&Path>,
Jooyung Han21e9b922021-06-26 04:14:16 +090048 log_path: Option<&Path>,
Jiyong Parkc2a49cc2021-10-15 00:02:12 +090049 debug_level: DebugLevel,
Jiyong Parkd63cfff2021-09-27 20:10:17 +090050 mem: Option<u32>,
Jooyung Han21e9b922021-06-26 04:14:16 +090051) -> Result<(), Error> {
52 let apk_file = File::open(apk).context("Failed to open APK file")?;
Jiyong Park0a248432021-08-20 23:32:39 +090053 let idsig_file = File::create(idsig).context("Failed to create idsig file")?;
54
55 let apk_fd = ParcelFileDescriptor::new(apk_file);
56 let idsig_fd = ParcelFileDescriptor::new(idsig_file);
57 service.createOrUpdateIdsigFile(&apk_fd, &idsig_fd)?;
58
Jooyung Han21e9b922021-06-26 04:14:16 +090059 let idsig_file = File::open(idsig).context("Failed to open idsig file")?;
Jiyong Park0a248432021-08-20 23:32:39 +090060 let idsig_fd = ParcelFileDescriptor::new(idsig_file);
Jiyong Park48b354d2021-07-15 15:04:38 +090061
62 if !instance.exists() {
63 const INSTANCE_FILE_SIZE: u64 = 10 * 1024 * 1024;
Jiyong Park9dd389e2021-08-23 20:42:59 +090064 command_create_partition(
65 service.clone(),
66 instance,
67 INSTANCE_FILE_SIZE,
68 PartitionType::ANDROID_VM_INSTANCE,
69 )?;
Jiyong Park48b354d2021-07-15 15:04:38 +090070 }
71
Jooyung Han21e9b922021-06-26 04:14:16 +090072 let config = VirtualMachineConfig::AppConfig(VirtualMachineAppConfig {
Jiyong Park0a248432021-08-20 23:32:39 +090073 apk: apk_fd.into(),
74 idsig: idsig_fd.into(),
Jiyong Park48b354d2021-07-15 15:04:38 +090075 instanceImage: open_parcel_file(instance, true /* writable */)?.into(),
Jooyung Han21e9b922021-06-26 04:14:16 +090076 configPath: config_path.to_owned(),
Jiyong Parkc2a49cc2021-10-15 00:02:12 +090077 debugLevel: debug_level,
Jiyong Parkd63cfff2021-09-27 20:10:17 +090078 memoryMib: mem.unwrap_or(0) as i32, // 0 means use the VM default
Jooyung Han21e9b922021-06-26 04:14:16 +090079 });
Jiyong Parkb8182bb2021-10-26 22:53:08 +090080 run(
81 service,
82 &config,
83 &format!("{:?}!{:?}", apk, config_path),
84 daemonize,
85 console_path,
86 log_path,
87 )
Jooyung Han21e9b922021-06-26 04:14:16 +090088}
89
Andrew Walbranf395b822021-05-05 10:38:59 +000090/// Run a VM from the given configuration file.
91pub fn command_run(
Andrew Walbran17de24f2021-05-27 13:27:30 +000092 service: Strong<dyn IVirtualizationService>,
Andrew Walbranf395b822021-05-05 10:38:59 +000093 config_path: &Path,
94 daemonize: bool,
Jiyong Parkb8182bb2021-10-26 22:53:08 +090095 console_path: Option<&Path>,
Jiyong Parkd63cfff2021-09-27 20:10:17 +090096 mem: Option<u32>,
Andrew Walbranf395b822021-05-05 10:38:59 +000097) -> Result<(), Error> {
Andrew Walbran3a5a9212021-05-04 17:09:08 +000098 let config_file = File::open(config_path).context("Failed to open config file")?;
Jiyong Parkd63cfff2021-09-27 20:10:17 +090099 let mut config =
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000100 VmConfig::load(&config_file).context("Failed to parse config file")?.to_parcelable()?;
Jiyong Parkd63cfff2021-09-27 20:10:17 +0900101 if let Some(mem) = mem {
102 config.memoryMib = mem as i32;
103 }
Jooyung Han21e9b922021-06-26 04:14:16 +0900104 run(
105 service,
106 &VirtualMachineConfig::RawConfig(config),
107 &format!("{:?}", config_path),
108 daemonize,
Jiyong Parkb8182bb2021-10-26 22:53:08 +0900109 console_path,
110 None,
Jooyung Han21e9b922021-06-26 04:14:16 +0900111 )
112}
113
Andrew Walbranf8d94112021-09-07 11:45:36 +0000114fn state_to_str(vm_state: VirtualMachineState) -> &'static str {
115 match vm_state {
116 VirtualMachineState::NOT_STARTED => "NOT_STARTED",
117 VirtualMachineState::STARTING => "STARTING",
118 VirtualMachineState::STARTED => "STARTED",
119 VirtualMachineState::READY => "READY",
120 VirtualMachineState::FINISHED => "FINISHED",
121 VirtualMachineState::DEAD => "DEAD",
122 _ => "(invalid state)",
123 }
124}
125
Jooyung Han21e9b922021-06-26 04:14:16 +0900126fn run(
127 service: Strong<dyn IVirtualizationService>,
128 config: &VirtualMachineConfig,
129 config_path: &str,
130 daemonize: bool,
Jiyong Parkb8182bb2021-10-26 22:53:08 +0900131 console_path: Option<&Path>,
Jooyung Han21e9b922021-06-26 04:14:16 +0900132 log_path: Option<&Path>,
133) -> Result<(), Error> {
Jiyong Parkb8182bb2021-10-26 22:53:08 +0900134 let console = if let Some(console_path) = console_path {
135 Some(ParcelFileDescriptor::new(
136 File::create(console_path)
137 .with_context(|| format!("Failed to open console file {:?}", console_path))?,
138 ))
139 } else if daemonize {
140 None
141 } else {
142 Some(ParcelFileDescriptor::new(duplicate_stdout()?))
143 };
144 let log = if let Some(log_path) = log_path {
Andrew Walbranbe429242021-06-28 12:22:54 +0000145 Some(ParcelFileDescriptor::new(
146 File::create(log_path)
147 .with_context(|| format!("Failed to open log file {:?}", log_path))?,
148 ))
149 } else if daemonize {
150 None
151 } else {
152 Some(ParcelFileDescriptor::new(duplicate_stdout()?))
153 };
Jiyong Parkb8182bb2021-10-26 22:53:08 +0900154
155 let vm =
156 service.createVm(config, console.as_ref(), log.as_ref()).context("Failed to create VM")?;
Andrew Walbranf395b822021-05-05 10:38:59 +0000157
158 let cid = vm.getCid().context("Failed to get CID")?;
Andrew Walbranf8d94112021-09-07 11:45:36 +0000159 println!(
160 "Created VM from {} with CID {}, state is {}.",
161 config_path,
162 cid,
163 state_to_str(vm.getState()?)
164 );
165 vm.start()?;
166 println!("Started VM, state now {}.", state_to_str(vm.getState()?));
Andrew Walbranf395b822021-05-05 10:38:59 +0000167
168 if daemonize {
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000169 // Pass the VM reference back to VirtualizationService and have it hold it in the
170 // background.
Andrew Walbran17de24f2021-05-27 13:27:30 +0000171 service.debugHoldVmRef(&vm).context("Failed to pass VM to VirtualizationService")
Andrew Walbranf395b822021-05-05 10:38:59 +0000172 } else {
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000173 // Wait until the VM or VirtualizationService dies. If we just returned immediately then the
Andrew Walbranf395b822021-05-05 10:38:59 +0000174 // IVirtualMachine Binder object would be dropped and the VM would be killed.
175 wait_for_vm(vm)
176 }
177}
178
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000179/// Wait until the given VM or the VirtualizationService itself dies.
Andrew Walbranf395b822021-05-05 10:38:59 +0000180fn wait_for_vm(vm: Strong<dyn IVirtualMachine>) -> Result<(), Error> {
181 let dead = AtomicFlag::default();
182 let callback = BnVirtualMachineCallback::new_binder(
183 VirtualMachineCallback { dead: dead.clone() },
184 BinderFeatures::default(),
185 );
186 vm.registerCallback(&callback)?;
187 let death_recipient = wait_for_death(&mut vm.as_binder(), dead.clone())?;
188 dead.wait();
189 // Ensure that death_recipient isn't dropped before we wait on the flag, as it is removed
190 // from the Binder when it's dropped.
191 drop(death_recipient);
192 Ok(())
193}
194
195/// Raise the given flag when the given Binder object dies.
196///
197/// If the returned DeathRecipient is dropped then this will no longer do anything.
198fn wait_for_death(binder: &mut impl IBinder, dead: AtomicFlag) -> Result<DeathRecipient, Error> {
199 let mut death_recipient = DeathRecipient::new(move || {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900200 eprintln!("VirtualizationService unexpectedly died");
Andrew Walbranf395b822021-05-05 10:38:59 +0000201 dead.raise();
202 });
203 binder.link_to_death(&mut death_recipient)?;
204 Ok(death_recipient)
205}
206
207#[derive(Debug)]
208struct VirtualMachineCallback {
209 dead: AtomicFlag,
210}
211
212impl Interface for VirtualMachineCallback {}
213
214impl IVirtualMachineCallback for VirtualMachineCallback {
Inseob Kim7f61fe72021-08-20 20:50:47 +0900215 fn onPayloadStarted(
216 &self,
217 _cid: i32,
218 stream: Option<&ParcelFileDescriptor>,
219 ) -> BinderResult<()> {
220 // Show the output of the payload
221 if let Some(stream) = stream {
222 let mut reader = BufReader::new(stream.as_ref());
223 loop {
224 let mut s = String::new();
225 match reader.read_line(&mut s) {
226 Ok(0) => break,
227 Ok(_) => print!("{}", s),
228 Err(e) => eprintln!("error reading from virtual machine: {}", e),
229 };
230 }
Jiyong Park8611a6c2021-07-09 18:17:44 +0900231 }
232 Ok(())
233 }
234
Inseob Kim14cb8692021-08-31 21:50:39 +0900235 fn onPayloadReady(&self, _cid: i32) -> BinderResult<()> {
Inseob Kim8dbc3222021-09-01 21:50:23 +0900236 eprintln!("payload is ready");
Inseob Kim14cb8692021-08-31 21:50:39 +0900237 Ok(())
238 }
239
Inseob Kim8dbc3222021-09-01 21:50:23 +0900240 fn onPayloadFinished(&self, _cid: i32, exit_code: i32) -> BinderResult<()> {
241 eprintln!("payload finished with exit code {}", exit_code);
Inseob Kim2444af92021-08-31 01:22:50 +0900242 Ok(())
243 }
244
Andrew Walbranf395b822021-05-05 10:38:59 +0000245 fn onDied(&self, _cid: i32) -> BinderResult<()> {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900246 // No need to explicitly report the event to the user (e.g. via println!) because this
247 // callback is registered only when the vm tool is invoked as interactive mode (e.g. not
248 // --daemonize) in which case the tool will exit to the shell prompt upon VM shutdown.
249 // Printing something will actually even confuse the user as the output from the app
250 // payload is printed.
Andrew Walbranf395b822021-05-05 10:38:59 +0000251 self.dead.raise();
252 Ok(())
253 }
254}
255
256/// Safely duplicate the standard output file descriptor.
257fn duplicate_stdout() -> io::Result<File> {
258 let stdout_fd = io::stdout().as_raw_fd();
259 // Safe because this just duplicates a file descriptor which we know to be valid, and we check
260 // for an error.
261 let dup_fd = unsafe { libc::dup(stdout_fd) };
262 if dup_fd < 0 {
263 Err(io::Error::last_os_error())
264 } else {
265 // Safe because we have just duplicated the file descriptor so we own it, and `from_raw_fd`
266 // takes ownership of it.
267 Ok(unsafe { File::from_raw_fd(dup_fd) })
268 }
269}