blob: 0d34a9754fe2d4a53eb218d6653f8292ccb87786 [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,
Jooyung Han21e9b922021-06-26 04:14:16 +090052) -> Result<(), Error> {
53 let apk_file = File::open(apk).context("Failed to open APK file")?;
Jiyong Park0a248432021-08-20 23:32:39 +090054 let idsig_file = File::create(idsig).context("Failed to create idsig file")?;
55
56 let apk_fd = ParcelFileDescriptor::new(apk_file);
57 let idsig_fd = ParcelFileDescriptor::new(idsig_file);
58 service.createOrUpdateIdsigFile(&apk_fd, &idsig_fd)?;
59
Jooyung Han21e9b922021-06-26 04:14:16 +090060 let idsig_file = File::open(idsig).context("Failed to open idsig file")?;
Jiyong Park0a248432021-08-20 23:32:39 +090061 let idsig_fd = ParcelFileDescriptor::new(idsig_file);
Jiyong Park48b354d2021-07-15 15:04:38 +090062
63 if !instance.exists() {
64 const INSTANCE_FILE_SIZE: u64 = 10 * 1024 * 1024;
Jiyong Park9dd389e2021-08-23 20:42:59 +090065 command_create_partition(
66 service.clone(),
67 instance,
68 INSTANCE_FILE_SIZE,
69 PartitionType::ANDROID_VM_INSTANCE,
70 )?;
Jiyong Park48b354d2021-07-15 15:04:38 +090071 }
72
Jooyung Han21e9b922021-06-26 04:14:16 +090073 let config = VirtualMachineConfig::AppConfig(VirtualMachineAppConfig {
Jiyong Park0a248432021-08-20 23:32:39 +090074 apk: apk_fd.into(),
75 idsig: idsig_fd.into(),
Jiyong Park48b354d2021-07-15 15:04:38 +090076 instanceImage: open_parcel_file(instance, true /* writable */)?.into(),
Jooyung Han21e9b922021-06-26 04:14:16 +090077 configPath: config_path.to_owned(),
Jiyong Park23601142021-07-05 13:15:32 +090078 debug,
Andrew Walbran45bcb0c2021-07-14 15:02:06 +000079 // Use the default.
Andrew Walbrancc045902021-07-27 16:06:17 +000080 memoryMib: 0,
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>,
Andrew Walbranf395b822021-05-05 10:38:59 +000091) -> Result<(), Error> {
Andrew Walbran3a5a9212021-05-04 17:09:08 +000092 let config_file = File::open(config_path).context("Failed to open config file")?;
93 let config =
94 VmConfig::load(&config_file).context("Failed to parse config file")?.to_parcelable()?;
Jooyung Han21e9b922021-06-26 04:14:16 +090095 run(
96 service,
97 &VirtualMachineConfig::RawConfig(config),
98 &format!("{:?}", config_path),
99 daemonize,
100 log_path,
101 )
102}
103
Andrew Walbranf8d94112021-09-07 11:45:36 +0000104fn state_to_str(vm_state: VirtualMachineState) -> &'static str {
105 match vm_state {
106 VirtualMachineState::NOT_STARTED => "NOT_STARTED",
107 VirtualMachineState::STARTING => "STARTING",
108 VirtualMachineState::STARTED => "STARTED",
109 VirtualMachineState::READY => "READY",
110 VirtualMachineState::FINISHED => "FINISHED",
111 VirtualMachineState::DEAD => "DEAD",
112 _ => "(invalid state)",
113 }
114}
115
Jooyung Han21e9b922021-06-26 04:14:16 +0900116fn run(
117 service: Strong<dyn IVirtualizationService>,
118 config: &VirtualMachineConfig,
119 config_path: &str,
120 daemonize: bool,
121 log_path: Option<&Path>,
122) -> Result<(), Error> {
Andrew Walbranbe429242021-06-28 12:22:54 +0000123 let stdout = if let Some(log_path) = log_path {
124 Some(ParcelFileDescriptor::new(
125 File::create(log_path)
126 .with_context(|| format!("Failed to open log file {:?}", log_path))?,
127 ))
128 } else if daemonize {
129 None
130 } else {
131 Some(ParcelFileDescriptor::new(duplicate_stdout()?))
132 };
Andrew Walbranf8d94112021-09-07 11:45:36 +0000133 let vm = service.createVm(config, stdout.as_ref()).context("Failed to create VM")?;
Andrew Walbranf395b822021-05-05 10:38:59 +0000134
135 let cid = vm.getCid().context("Failed to get CID")?;
Andrew Walbranf8d94112021-09-07 11:45:36 +0000136 println!(
137 "Created VM from {} with CID {}, state is {}.",
138 config_path,
139 cid,
140 state_to_str(vm.getState()?)
141 );
142 vm.start()?;
143 println!("Started VM, state now {}.", state_to_str(vm.getState()?));
Andrew Walbranf395b822021-05-05 10:38:59 +0000144
145 if daemonize {
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000146 // Pass the VM reference back to VirtualizationService and have it hold it in the
147 // background.
Andrew Walbran17de24f2021-05-27 13:27:30 +0000148 service.debugHoldVmRef(&vm).context("Failed to pass VM to VirtualizationService")
Andrew Walbranf395b822021-05-05 10:38:59 +0000149 } else {
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000150 // Wait until the VM or VirtualizationService dies. If we just returned immediately then the
Andrew Walbranf395b822021-05-05 10:38:59 +0000151 // IVirtualMachine Binder object would be dropped and the VM would be killed.
152 wait_for_vm(vm)
153 }
154}
155
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000156/// Wait until the given VM or the VirtualizationService itself dies.
Andrew Walbranf395b822021-05-05 10:38:59 +0000157fn wait_for_vm(vm: Strong<dyn IVirtualMachine>) -> Result<(), Error> {
158 let dead = AtomicFlag::default();
159 let callback = BnVirtualMachineCallback::new_binder(
160 VirtualMachineCallback { dead: dead.clone() },
161 BinderFeatures::default(),
162 );
163 vm.registerCallback(&callback)?;
164 let death_recipient = wait_for_death(&mut vm.as_binder(), dead.clone())?;
165 dead.wait();
166 // Ensure that death_recipient isn't dropped before we wait on the flag, as it is removed
167 // from the Binder when it's dropped.
168 drop(death_recipient);
169 Ok(())
170}
171
172/// Raise the given flag when the given Binder object dies.
173///
174/// If the returned DeathRecipient is dropped then this will no longer do anything.
175fn wait_for_death(binder: &mut impl IBinder, dead: AtomicFlag) -> Result<DeathRecipient, Error> {
176 let mut death_recipient = DeathRecipient::new(move || {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900177 eprintln!("VirtualizationService unexpectedly died");
Andrew Walbranf395b822021-05-05 10:38:59 +0000178 dead.raise();
179 });
180 binder.link_to_death(&mut death_recipient)?;
181 Ok(death_recipient)
182}
183
184#[derive(Debug)]
185struct VirtualMachineCallback {
186 dead: AtomicFlag,
187}
188
189impl Interface for VirtualMachineCallback {}
190
191impl IVirtualMachineCallback for VirtualMachineCallback {
Inseob Kim7f61fe72021-08-20 20:50:47 +0900192 fn onPayloadStarted(
193 &self,
194 _cid: i32,
195 stream: Option<&ParcelFileDescriptor>,
196 ) -> BinderResult<()> {
197 // Show the output of the payload
198 if let Some(stream) = stream {
199 let mut reader = BufReader::new(stream.as_ref());
200 loop {
201 let mut s = String::new();
202 match reader.read_line(&mut s) {
203 Ok(0) => break,
204 Ok(_) => print!("{}", s),
205 Err(e) => eprintln!("error reading from virtual machine: {}", e),
206 };
207 }
Jiyong Park8611a6c2021-07-09 18:17:44 +0900208 }
209 Ok(())
210 }
211
Inseob Kim14cb8692021-08-31 21:50:39 +0900212 fn onPayloadReady(&self, _cid: i32) -> BinderResult<()> {
Inseob Kim8dbc3222021-09-01 21:50:23 +0900213 eprintln!("payload is ready");
Inseob Kim14cb8692021-08-31 21:50:39 +0900214 Ok(())
215 }
216
Inseob Kim8dbc3222021-09-01 21:50:23 +0900217 fn onPayloadFinished(&self, _cid: i32, exit_code: i32) -> BinderResult<()> {
218 eprintln!("payload finished with exit code {}", exit_code);
Inseob Kim2444af92021-08-31 01:22:50 +0900219 Ok(())
220 }
221
Andrew Walbranf395b822021-05-05 10:38:59 +0000222 fn onDied(&self, _cid: i32) -> BinderResult<()> {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900223 // No need to explicitly report the event to the user (e.g. via println!) because this
224 // callback is registered only when the vm tool is invoked as interactive mode (e.g. not
225 // --daemonize) in which case the tool will exit to the shell prompt upon VM shutdown.
226 // Printing something will actually even confuse the user as the output from the app
227 // payload is printed.
Andrew Walbranf395b822021-05-05 10:38:59 +0000228 self.dead.raise();
229 Ok(())
230 }
231}
232
233/// Safely duplicate the standard output file descriptor.
234fn duplicate_stdout() -> io::Result<File> {
235 let stdout_fd = io::stdout().as_raw_fd();
236 // Safe because this just duplicates a file descriptor which we know to be valid, and we check
237 // for an error.
238 let dup_fd = unsafe { libc::dup(stdout_fd) };
239 if dup_fd < 0 {
240 Err(io::Error::last_os_error())
241 } else {
242 // Safe because we have just duplicated the file descriptor so we own it, and `from_raw_fd`
243 // takes ownership of it.
244 Ok(unsafe { File::from_raw_fd(dup_fd) })
245 }
246}