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