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; |
Jooyung Han | 21e9b92 | 2021-06-26 04:14:16 +0900 | [diff] [blame] | 19 | use android_system_virtualizationservice::aidl::android::system::virtualizationservice::{ |
Jiyong Park | c2a49cc | 2021-10-15 00:02:12 +0900 | [diff] [blame^] | 20 | IVirtualMachine::IVirtualMachine, IVirtualMachineCallback::BnVirtualMachineCallback, |
| 21 | IVirtualMachineCallback::IVirtualMachineCallback, |
| 22 | IVirtualizationService::IVirtualizationService, PartitionType::PartitionType, |
| 23 | VirtualMachineAppConfig::DebugLevel::DebugLevel, |
| 24 | VirtualMachineAppConfig::VirtualMachineAppConfig, VirtualMachineConfig::VirtualMachineConfig, |
Andrew Walbran | f8d9411 | 2021-09-07 11:45:36 +0000 | [diff] [blame] | 25 | VirtualMachineState::VirtualMachineState, |
Jooyung Han | 21e9b92 | 2021-06-26 04:14:16 +0900 | [diff] [blame] | 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; |
Jiyong Park | 48b354d | 2021-07-15 15:04:38 +0900 | [diff] [blame] | 36 | use vmconfig::{open_parcel_file, 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. |
Jiyong Park | 48b354d | 2021-07-15 15:04:38 +0900 | [diff] [blame] | 39 | #[allow(clippy::too_many_arguments)] |
Jooyung Han | 21e9b92 | 2021-06-26 04:14:16 +0900 | [diff] [blame] | 40 | pub fn command_run_app( |
| 41 | service: Strong<dyn IVirtualizationService>, |
| 42 | apk: &Path, |
| 43 | idsig: &Path, |
Jiyong Park | 48b354d | 2021-07-15 15:04:38 +0900 | [diff] [blame] | 44 | instance: &Path, |
Jooyung Han | 21e9b92 | 2021-06-26 04:14:16 +0900 | [diff] [blame] | 45 | config_path: &str, |
| 46 | daemonize: bool, |
| 47 | log_path: Option<&Path>, |
Jiyong Park | c2a49cc | 2021-10-15 00:02:12 +0900 | [diff] [blame^] | 48 | debug_level: DebugLevel, |
Jiyong Park | d63cfff | 2021-09-27 20:10:17 +0900 | [diff] [blame] | 49 | mem: Option<u32>, |
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; |
Jiyong Park | 9dd389e | 2021-08-23 20:42:59 +0900 | [diff] [blame] | 63 | command_create_partition( |
| 64 | service.clone(), |
| 65 | instance, |
| 66 | INSTANCE_FILE_SIZE, |
| 67 | PartitionType::ANDROID_VM_INSTANCE, |
| 68 | )?; |
Jiyong Park | 48b354d | 2021-07-15 15:04:38 +0900 | [diff] [blame] | 69 | } |
| 70 | |
Jooyung Han | 21e9b92 | 2021-06-26 04:14:16 +0900 | [diff] [blame] | 71 | let config = VirtualMachineConfig::AppConfig(VirtualMachineAppConfig { |
Jiyong Park | 0a24843 | 2021-08-20 23:32:39 +0900 | [diff] [blame] | 72 | apk: apk_fd.into(), |
| 73 | idsig: idsig_fd.into(), |
Jiyong Park | 48b354d | 2021-07-15 15:04:38 +0900 | [diff] [blame] | 74 | instanceImage: open_parcel_file(instance, true /* writable */)?.into(), |
Jooyung Han | 21e9b92 | 2021-06-26 04:14:16 +0900 | [diff] [blame] | 75 | configPath: config_path.to_owned(), |
Jiyong Park | c2a49cc | 2021-10-15 00:02:12 +0900 | [diff] [blame^] | 76 | debugLevel: debug_level, |
Jiyong Park | d63cfff | 2021-09-27 20:10:17 +0900 | [diff] [blame] | 77 | memoryMib: mem.unwrap_or(0) as i32, // 0 means use the VM default |
Jooyung Han | 21e9b92 | 2021-06-26 04:14:16 +0900 | [diff] [blame] | 78 | }); |
| 79 | run(service, &config, &format!("{:?}!{:?}", apk, config_path), daemonize, log_path) |
| 80 | } |
| 81 | |
Andrew Walbran | f395b82 | 2021-05-05 10:38:59 +0000 | [diff] [blame] | 82 | /// Run a VM from the given configuration file. |
| 83 | pub fn command_run( |
Andrew Walbran | 17de24f | 2021-05-27 13:27:30 +0000 | [diff] [blame] | 84 | service: Strong<dyn IVirtualizationService>, |
Andrew Walbran | f395b82 | 2021-05-05 10:38:59 +0000 | [diff] [blame] | 85 | config_path: &Path, |
| 86 | daemonize: bool, |
Andrew Walbran | be42924 | 2021-06-28 12:22:54 +0000 | [diff] [blame] | 87 | log_path: Option<&Path>, |
Jiyong Park | d63cfff | 2021-09-27 20:10:17 +0900 | [diff] [blame] | 88 | mem: Option<u32>, |
Andrew Walbran | f395b82 | 2021-05-05 10:38:59 +0000 | [diff] [blame] | 89 | ) -> Result<(), Error> { |
Andrew Walbran | 3a5a921 | 2021-05-04 17:09:08 +0000 | [diff] [blame] | 90 | let config_file = File::open(config_path).context("Failed to open config file")?; |
Jiyong Park | d63cfff | 2021-09-27 20:10:17 +0900 | [diff] [blame] | 91 | let mut config = |
Andrew Walbran | 3a5a921 | 2021-05-04 17:09:08 +0000 | [diff] [blame] | 92 | VmConfig::load(&config_file).context("Failed to parse config file")?.to_parcelable()?; |
Jiyong Park | d63cfff | 2021-09-27 20:10:17 +0900 | [diff] [blame] | 93 | if let Some(mem) = mem { |
| 94 | config.memoryMib = mem as i32; |
| 95 | } |
Jooyung Han | 21e9b92 | 2021-06-26 04:14:16 +0900 | [diff] [blame] | 96 | run( |
| 97 | service, |
| 98 | &VirtualMachineConfig::RawConfig(config), |
| 99 | &format!("{:?}", config_path), |
| 100 | daemonize, |
| 101 | log_path, |
| 102 | ) |
| 103 | } |
| 104 | |
Andrew Walbran | f8d9411 | 2021-09-07 11:45:36 +0000 | [diff] [blame] | 105 | fn state_to_str(vm_state: VirtualMachineState) -> &'static str { |
| 106 | match vm_state { |
| 107 | VirtualMachineState::NOT_STARTED => "NOT_STARTED", |
| 108 | VirtualMachineState::STARTING => "STARTING", |
| 109 | VirtualMachineState::STARTED => "STARTED", |
| 110 | VirtualMachineState::READY => "READY", |
| 111 | VirtualMachineState::FINISHED => "FINISHED", |
| 112 | VirtualMachineState::DEAD => "DEAD", |
| 113 | _ => "(invalid state)", |
| 114 | } |
| 115 | } |
| 116 | |
Jooyung Han | 21e9b92 | 2021-06-26 04:14:16 +0900 | [diff] [blame] | 117 | fn run( |
| 118 | service: Strong<dyn IVirtualizationService>, |
| 119 | config: &VirtualMachineConfig, |
| 120 | config_path: &str, |
| 121 | daemonize: bool, |
| 122 | log_path: Option<&Path>, |
| 123 | ) -> Result<(), Error> { |
Andrew Walbran | be42924 | 2021-06-28 12:22:54 +0000 | [diff] [blame] | 124 | let stdout = if let Some(log_path) = log_path { |
| 125 | Some(ParcelFileDescriptor::new( |
| 126 | File::create(log_path) |
| 127 | .with_context(|| format!("Failed to open log file {:?}", log_path))?, |
| 128 | )) |
| 129 | } else if daemonize { |
| 130 | None |
| 131 | } else { |
| 132 | Some(ParcelFileDescriptor::new(duplicate_stdout()?)) |
| 133 | }; |
Andrew Walbran | f8d9411 | 2021-09-07 11:45:36 +0000 | [diff] [blame] | 134 | let vm = service.createVm(config, stdout.as_ref()).context("Failed to create VM")?; |
Andrew Walbran | f395b82 | 2021-05-05 10:38:59 +0000 | [diff] [blame] | 135 | |
| 136 | let cid = vm.getCid().context("Failed to get CID")?; |
Andrew Walbran | f8d9411 | 2021-09-07 11:45:36 +0000 | [diff] [blame] | 137 | println!( |
| 138 | "Created VM from {} with CID {}, state is {}.", |
| 139 | config_path, |
| 140 | cid, |
| 141 | state_to_str(vm.getState()?) |
| 142 | ); |
| 143 | vm.start()?; |
| 144 | println!("Started VM, state now {}.", state_to_str(vm.getState()?)); |
Andrew Walbran | f395b82 | 2021-05-05 10:38:59 +0000 | [diff] [blame] | 145 | |
| 146 | if daemonize { |
Andrew Walbran | f6bf686 | 2021-05-21 12:41:13 +0000 | [diff] [blame] | 147 | // Pass the VM reference back to VirtualizationService and have it hold it in the |
| 148 | // background. |
Andrew Walbran | 17de24f | 2021-05-27 13:27:30 +0000 | [diff] [blame] | 149 | service.debugHoldVmRef(&vm).context("Failed to pass VM to VirtualizationService") |
Andrew Walbran | f395b82 | 2021-05-05 10:38:59 +0000 | [diff] [blame] | 150 | } else { |
Andrew Walbran | f6bf686 | 2021-05-21 12:41:13 +0000 | [diff] [blame] | 151 | // 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] | 152 | // IVirtualMachine Binder object would be dropped and the VM would be killed. |
| 153 | wait_for_vm(vm) |
| 154 | } |
| 155 | } |
| 156 | |
Andrew Walbran | f6bf686 | 2021-05-21 12:41:13 +0000 | [diff] [blame] | 157 | /// Wait until the given VM or the VirtualizationService itself dies. |
Andrew Walbran | f395b82 | 2021-05-05 10:38:59 +0000 | [diff] [blame] | 158 | fn wait_for_vm(vm: Strong<dyn IVirtualMachine>) -> Result<(), Error> { |
| 159 | let dead = AtomicFlag::default(); |
| 160 | let callback = BnVirtualMachineCallback::new_binder( |
| 161 | VirtualMachineCallback { dead: dead.clone() }, |
| 162 | BinderFeatures::default(), |
| 163 | ); |
| 164 | vm.registerCallback(&callback)?; |
| 165 | let death_recipient = wait_for_death(&mut vm.as_binder(), dead.clone())?; |
| 166 | dead.wait(); |
| 167 | // Ensure that death_recipient isn't dropped before we wait on the flag, as it is removed |
| 168 | // from the Binder when it's dropped. |
| 169 | drop(death_recipient); |
| 170 | Ok(()) |
| 171 | } |
| 172 | |
| 173 | /// Raise the given flag when the given Binder object dies. |
| 174 | /// |
| 175 | /// If the returned DeathRecipient is dropped then this will no longer do anything. |
| 176 | fn wait_for_death(binder: &mut impl IBinder, dead: AtomicFlag) -> Result<DeathRecipient, Error> { |
| 177 | let mut death_recipient = DeathRecipient::new(move || { |
Jiyong Park | 8611a6c | 2021-07-09 18:17:44 +0900 | [diff] [blame] | 178 | eprintln!("VirtualizationService unexpectedly died"); |
Andrew Walbran | f395b82 | 2021-05-05 10:38:59 +0000 | [diff] [blame] | 179 | dead.raise(); |
| 180 | }); |
| 181 | binder.link_to_death(&mut death_recipient)?; |
| 182 | Ok(death_recipient) |
| 183 | } |
| 184 | |
| 185 | #[derive(Debug)] |
| 186 | struct VirtualMachineCallback { |
| 187 | dead: AtomicFlag, |
| 188 | } |
| 189 | |
| 190 | impl Interface for VirtualMachineCallback {} |
| 191 | |
| 192 | impl IVirtualMachineCallback for VirtualMachineCallback { |
Inseob Kim | 7f61fe7 | 2021-08-20 20:50:47 +0900 | [diff] [blame] | 193 | fn onPayloadStarted( |
| 194 | &self, |
| 195 | _cid: i32, |
| 196 | stream: Option<&ParcelFileDescriptor>, |
| 197 | ) -> BinderResult<()> { |
| 198 | // Show the output of the payload |
| 199 | if let Some(stream) = stream { |
| 200 | let mut reader = BufReader::new(stream.as_ref()); |
| 201 | loop { |
| 202 | let mut s = String::new(); |
| 203 | match reader.read_line(&mut s) { |
| 204 | Ok(0) => break, |
| 205 | Ok(_) => print!("{}", s), |
| 206 | Err(e) => eprintln!("error reading from virtual machine: {}", e), |
| 207 | }; |
| 208 | } |
Jiyong Park | 8611a6c | 2021-07-09 18:17:44 +0900 | [diff] [blame] | 209 | } |
| 210 | Ok(()) |
| 211 | } |
| 212 | |
Inseob Kim | 14cb869 | 2021-08-31 21:50:39 +0900 | [diff] [blame] | 213 | fn onPayloadReady(&self, _cid: i32) -> BinderResult<()> { |
Inseob Kim | 8dbc322 | 2021-09-01 21:50:23 +0900 | [diff] [blame] | 214 | eprintln!("payload is ready"); |
Inseob Kim | 14cb869 | 2021-08-31 21:50:39 +0900 | [diff] [blame] | 215 | Ok(()) |
| 216 | } |
| 217 | |
Inseob Kim | 8dbc322 | 2021-09-01 21:50:23 +0900 | [diff] [blame] | 218 | fn onPayloadFinished(&self, _cid: i32, exit_code: i32) -> BinderResult<()> { |
| 219 | eprintln!("payload finished with exit code {}", exit_code); |
Inseob Kim | 2444af9 | 2021-08-31 01:22:50 +0900 | [diff] [blame] | 220 | Ok(()) |
| 221 | } |
| 222 | |
Andrew Walbran | f395b82 | 2021-05-05 10:38:59 +0000 | [diff] [blame] | 223 | fn onDied(&self, _cid: i32) -> BinderResult<()> { |
Jiyong Park | 8611a6c | 2021-07-09 18:17:44 +0900 | [diff] [blame] | 224 | // No need to explicitly report the event to the user (e.g. via println!) because this |
| 225 | // callback is registered only when the vm tool is invoked as interactive mode (e.g. not |
| 226 | // --daemonize) in which case the tool will exit to the shell prompt upon VM shutdown. |
| 227 | // Printing something will actually even confuse the user as the output from the app |
| 228 | // payload is printed. |
Andrew Walbran | f395b82 | 2021-05-05 10:38:59 +0000 | [diff] [blame] | 229 | self.dead.raise(); |
| 230 | Ok(()) |
| 231 | } |
| 232 | } |
| 233 | |
| 234 | /// Safely duplicate the standard output file descriptor. |
| 235 | fn duplicate_stdout() -> io::Result<File> { |
| 236 | let stdout_fd = io::stdout().as_raw_fd(); |
| 237 | // Safe because this just duplicates a file descriptor which we know to be valid, and we check |
| 238 | // for an error. |
| 239 | let dup_fd = unsafe { libc::dup(stdout_fd) }; |
| 240 | if dup_fd < 0 { |
| 241 | Err(io::Error::last_os_error()) |
| 242 | } else { |
| 243 | // Safe because we have just duplicated the file descriptor so we own it, and `from_raw_fd` |
| 244 | // takes ownership of it. |
| 245 | Ok(unsafe { File::from_raw_fd(dup_fd) }) |
| 246 | } |
| 247 | } |