Andrew Walbran | f395b82 | 2021-05-05 10:38:59 +0000 | [diff] [blame] | 1 | // 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 | |
| 17 | use crate::sync::AtomicFlag; |
Andrew Walbran | f6bf686 | 2021-05-21 12:41:13 +0000 | [diff] [blame] | 18 | use android_system_virtualizationservice::aidl::android::system::virtualizationservice::IVirtualizationService::IVirtualizationService; |
| 19 | use android_system_virtualizationservice::aidl::android::system::virtualizationservice::IVirtualMachine::IVirtualMachine; |
| 20 | use android_system_virtualizationservice::aidl::android::system::virtualizationservice::IVirtualMachineCallback::{ |
Andrew Walbran | f395b82 | 2021-05-05 10:38:59 +0000 | [diff] [blame] | 21 | BnVirtualMachineCallback, IVirtualMachineCallback, |
| 22 | }; |
Jooyung Han | 21e9b92 | 2021-06-26 04:14:16 +0900 | [diff] [blame] | 23 | use android_system_virtualizationservice::aidl::android::system::virtualizationservice::{ |
| 24 | VirtualMachineAppConfig::VirtualMachineAppConfig, |
| 25 | VirtualMachineConfig::VirtualMachineConfig, |
| 26 | }; |
Andrew Walbran | f6bf686 | 2021-05-21 12:41:13 +0000 | [diff] [blame] | 27 | use android_system_virtualizationservice::binder::{ |
Andrew Walbran | f395b82 | 2021-05-05 10:38:59 +0000 | [diff] [blame] | 28 | BinderFeatures, DeathRecipient, IBinder, ParcelFileDescriptor, Strong, |
| 29 | }; |
Andrew Walbran | f6bf686 | 2021-05-21 12:41:13 +0000 | [diff] [blame] | 30 | use android_system_virtualizationservice::binder::{Interface, Result as BinderResult}; |
Andrew Walbran | f395b82 | 2021-05-05 10:38:59 +0000 | [diff] [blame] | 31 | use anyhow::{Context, Error}; |
| 32 | use std::fs::File; |
Jiyong Park | 8611a6c | 2021-07-09 18:17:44 +0900 | [diff] [blame^] | 33 | use std::io::{self, BufRead, BufReader}; |
Andrew Walbran | f395b82 | 2021-05-05 10:38:59 +0000 | [diff] [blame] | 34 | use std::os::unix::io::{AsRawFd, FromRawFd}; |
| 35 | use std::path::Path; |
Jooyung Han | fc732f5 | 2021-06-26 02:54:20 +0900 | [diff] [blame] | 36 | use vmconfig::VmConfig; |
Andrew Walbran | f395b82 | 2021-05-05 10:38:59 +0000 | [diff] [blame] | 37 | |
Jooyung Han | 21e9b92 | 2021-06-26 04:14:16 +0900 | [diff] [blame] | 38 | /// Run a VM from the given APK, idsig, and config. |
| 39 | pub fn command_run_app( |
| 40 | service: Strong<dyn IVirtualizationService>, |
| 41 | apk: &Path, |
| 42 | idsig: &Path, |
| 43 | config_path: &str, |
| 44 | daemonize: bool, |
| 45 | log_path: Option<&Path>, |
Jiyong Park | 2360114 | 2021-07-05 13:15:32 +0900 | [diff] [blame] | 46 | debug: bool, |
Jooyung Han | 21e9b92 | 2021-06-26 04:14:16 +0900 | [diff] [blame] | 47 | ) -> Result<(), Error> { |
| 48 | let apk_file = File::open(apk).context("Failed to open APK file")?; |
| 49 | let idsig_file = File::open(idsig).context("Failed to open idsig file")?; |
| 50 | let config = VirtualMachineConfig::AppConfig(VirtualMachineAppConfig { |
| 51 | apk: ParcelFileDescriptor::new(apk_file).into(), |
| 52 | idsig: ParcelFileDescriptor::new(idsig_file).into(), |
| 53 | configPath: config_path.to_owned(), |
Jiyong Park | 2360114 | 2021-07-05 13:15:32 +0900 | [diff] [blame] | 54 | debug, |
Jooyung Han | 21e9b92 | 2021-06-26 04:14:16 +0900 | [diff] [blame] | 55 | }); |
| 56 | run(service, &config, &format!("{:?}!{:?}", apk, config_path), daemonize, log_path) |
| 57 | } |
| 58 | |
Andrew Walbran | f395b82 | 2021-05-05 10:38:59 +0000 | [diff] [blame] | 59 | /// Run a VM from the given configuration file. |
| 60 | pub fn command_run( |
Andrew Walbran | 17de24f | 2021-05-27 13:27:30 +0000 | [diff] [blame] | 61 | service: Strong<dyn IVirtualizationService>, |
Andrew Walbran | f395b82 | 2021-05-05 10:38:59 +0000 | [diff] [blame] | 62 | config_path: &Path, |
| 63 | daemonize: bool, |
Andrew Walbran | be42924 | 2021-06-28 12:22:54 +0000 | [diff] [blame] | 64 | log_path: Option<&Path>, |
Andrew Walbran | f395b82 | 2021-05-05 10:38:59 +0000 | [diff] [blame] | 65 | ) -> Result<(), Error> { |
Andrew Walbran | 3a5a921 | 2021-05-04 17:09:08 +0000 | [diff] [blame] | 66 | let config_file = File::open(config_path).context("Failed to open config file")?; |
| 67 | let config = |
| 68 | VmConfig::load(&config_file).context("Failed to parse config file")?.to_parcelable()?; |
Jooyung Han | 21e9b92 | 2021-06-26 04:14:16 +0900 | [diff] [blame] | 69 | run( |
| 70 | service, |
| 71 | &VirtualMachineConfig::RawConfig(config), |
| 72 | &format!("{:?}", config_path), |
| 73 | daemonize, |
| 74 | log_path, |
| 75 | ) |
| 76 | } |
| 77 | |
| 78 | fn run( |
| 79 | service: Strong<dyn IVirtualizationService>, |
| 80 | config: &VirtualMachineConfig, |
| 81 | config_path: &str, |
| 82 | daemonize: bool, |
| 83 | log_path: Option<&Path>, |
| 84 | ) -> Result<(), Error> { |
Andrew Walbran | be42924 | 2021-06-28 12:22:54 +0000 | [diff] [blame] | 85 | let stdout = if let Some(log_path) = log_path { |
| 86 | Some(ParcelFileDescriptor::new( |
| 87 | File::create(log_path) |
| 88 | .with_context(|| format!("Failed to open log file {:?}", log_path))?, |
| 89 | )) |
| 90 | } else if daemonize { |
| 91 | None |
| 92 | } else { |
| 93 | Some(ParcelFileDescriptor::new(duplicate_stdout()?)) |
| 94 | }; |
Jooyung Han | 21e9b92 | 2021-06-26 04:14:16 +0900 | [diff] [blame] | 95 | let vm = service.startVm(config, stdout.as_ref()).context("Failed to start VM")?; |
Andrew Walbran | f395b82 | 2021-05-05 10:38:59 +0000 | [diff] [blame] | 96 | |
| 97 | let cid = vm.getCid().context("Failed to get CID")?; |
Jooyung Han | 35edb8f | 2021-07-01 16:17:16 +0900 | [diff] [blame] | 98 | println!("Started VM from {} with CID {}.", config_path, cid); |
Andrew Walbran | f395b82 | 2021-05-05 10:38:59 +0000 | [diff] [blame] | 99 | |
| 100 | if daemonize { |
Andrew Walbran | f6bf686 | 2021-05-21 12:41:13 +0000 | [diff] [blame] | 101 | // Pass the VM reference back to VirtualizationService and have it hold it in the |
| 102 | // background. |
Andrew Walbran | 17de24f | 2021-05-27 13:27:30 +0000 | [diff] [blame] | 103 | service.debugHoldVmRef(&vm).context("Failed to pass VM to VirtualizationService") |
Andrew Walbran | f395b82 | 2021-05-05 10:38:59 +0000 | [diff] [blame] | 104 | } else { |
Andrew Walbran | f6bf686 | 2021-05-21 12:41:13 +0000 | [diff] [blame] | 105 | // Wait until the VM or VirtualizationService dies. If we just returned immediately then the |
Andrew Walbran | f395b82 | 2021-05-05 10:38:59 +0000 | [diff] [blame] | 106 | // IVirtualMachine Binder object would be dropped and the VM would be killed. |
| 107 | wait_for_vm(vm) |
| 108 | } |
| 109 | } |
| 110 | |
Andrew Walbran | f6bf686 | 2021-05-21 12:41:13 +0000 | [diff] [blame] | 111 | /// Wait until the given VM or the VirtualizationService itself dies. |
Andrew Walbran | f395b82 | 2021-05-05 10:38:59 +0000 | [diff] [blame] | 112 | fn wait_for_vm(vm: Strong<dyn IVirtualMachine>) -> Result<(), Error> { |
| 113 | let dead = AtomicFlag::default(); |
| 114 | let callback = BnVirtualMachineCallback::new_binder( |
| 115 | VirtualMachineCallback { dead: dead.clone() }, |
| 116 | BinderFeatures::default(), |
| 117 | ); |
| 118 | vm.registerCallback(&callback)?; |
| 119 | let death_recipient = wait_for_death(&mut vm.as_binder(), dead.clone())?; |
| 120 | dead.wait(); |
| 121 | // Ensure that death_recipient isn't dropped before we wait on the flag, as it is removed |
| 122 | // from the Binder when it's dropped. |
| 123 | drop(death_recipient); |
| 124 | Ok(()) |
| 125 | } |
| 126 | |
| 127 | /// Raise the given flag when the given Binder object dies. |
| 128 | /// |
| 129 | /// If the returned DeathRecipient is dropped then this will no longer do anything. |
| 130 | fn wait_for_death(binder: &mut impl IBinder, dead: AtomicFlag) -> Result<DeathRecipient, Error> { |
| 131 | let mut death_recipient = DeathRecipient::new(move || { |
Jiyong Park | 8611a6c | 2021-07-09 18:17:44 +0900 | [diff] [blame^] | 132 | eprintln!("VirtualizationService unexpectedly died"); |
Andrew Walbran | f395b82 | 2021-05-05 10:38:59 +0000 | [diff] [blame] | 133 | dead.raise(); |
| 134 | }); |
| 135 | binder.link_to_death(&mut death_recipient)?; |
| 136 | Ok(death_recipient) |
| 137 | } |
| 138 | |
| 139 | #[derive(Debug)] |
| 140 | struct VirtualMachineCallback { |
| 141 | dead: AtomicFlag, |
| 142 | } |
| 143 | |
| 144 | impl Interface for VirtualMachineCallback {} |
| 145 | |
| 146 | impl IVirtualMachineCallback for VirtualMachineCallback { |
Jiyong Park | 8611a6c | 2021-07-09 18:17:44 +0900 | [diff] [blame^] | 147 | fn onPayloadStarted(&self, _cid: i32, stdout: &ParcelFileDescriptor) -> BinderResult<()> { |
| 148 | // Show the stdout of the payload |
| 149 | let mut reader = BufReader::new(stdout.as_ref()); |
| 150 | loop { |
| 151 | let mut s = String::new(); |
| 152 | match reader.read_line(&mut s) { |
| 153 | Ok(0) => break, |
| 154 | Ok(_) => print!("{}", s), |
| 155 | Err(e) => eprintln!("error reading from virtual machine: {}", e), |
| 156 | }; |
| 157 | } |
| 158 | Ok(()) |
| 159 | } |
| 160 | |
Andrew Walbran | f395b82 | 2021-05-05 10:38:59 +0000 | [diff] [blame] | 161 | fn onDied(&self, _cid: i32) -> BinderResult<()> { |
Jiyong Park | 8611a6c | 2021-07-09 18:17:44 +0900 | [diff] [blame^] | 162 | // No need to explicitly report the event to the user (e.g. via println!) because this |
| 163 | // callback is registered only when the vm tool is invoked as interactive mode (e.g. not |
| 164 | // --daemonize) in which case the tool will exit to the shell prompt upon VM shutdown. |
| 165 | // Printing something will actually even confuse the user as the output from the app |
| 166 | // payload is printed. |
Andrew Walbran | f395b82 | 2021-05-05 10:38:59 +0000 | [diff] [blame] | 167 | self.dead.raise(); |
| 168 | Ok(()) |
| 169 | } |
| 170 | } |
| 171 | |
| 172 | /// Safely duplicate the standard output file descriptor. |
| 173 | fn duplicate_stdout() -> io::Result<File> { |
| 174 | let stdout_fd = io::stdout().as_raw_fd(); |
| 175 | // Safe because this just duplicates a file descriptor which we know to be valid, and we check |
| 176 | // for an error. |
| 177 | let dup_fd = unsafe { libc::dup(stdout_fd) }; |
| 178 | if dup_fd < 0 { |
| 179 | Err(io::Error::last_os_error()) |
| 180 | } else { |
| 181 | // Safe because we have just duplicated the file descriptor so we own it, and `from_raw_fd` |
| 182 | // takes ownership of it. |
| 183 | Ok(unsafe { File::from_raw_fd(dup_fd) }) |
| 184 | } |
| 185 | } |