Alan Stokes | 17fd36a | 2021-09-06 17:22:37 +0100 | [diff] [blame] | 1 | /* |
| 2 | * Copyright (C) 2021 The Android Open Source Project |
| 3 | * |
| 4 | * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | * you may not use this file except in compliance with the License. |
| 6 | * You may obtain a copy of the License at |
| 7 | * |
| 8 | * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | * |
| 10 | * Unless required by applicable law or agreed to in writing, software |
| 11 | * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | * See the License for the specific language governing permissions and |
| 14 | * limitations under the License. |
| 15 | */ |
| 16 | |
| 17 | //! Support for starting CompOS in a VM and connecting to the service |
| 18 | |
| 19 | use crate::{COMPOS_APEX_ROOT, COMPOS_DATA_ROOT, COMPOS_VSOCK_PORT}; |
| 20 | use android_system_virtualizationservice::aidl::android::system::virtualizationservice::{ |
| 21 | IVirtualMachine::IVirtualMachine, |
| 22 | IVirtualMachineCallback::{BnVirtualMachineCallback, IVirtualMachineCallback}, |
| 23 | IVirtualizationService::IVirtualizationService, |
| 24 | VirtualMachineAppConfig::VirtualMachineAppConfig, |
| 25 | VirtualMachineConfig::VirtualMachineConfig, |
| 26 | }; |
| 27 | use android_system_virtualizationservice::binder::{ |
| 28 | wait_for_interface, BinderFeatures, DeathRecipient, IBinder, Interface, ParcelFileDescriptor, |
| 29 | Result as BinderResult, Strong, |
| 30 | }; |
| 31 | use anyhow::{anyhow, bail, Context, Result}; |
| 32 | use binder::{ |
| 33 | unstable_api::{new_spibinder, AIBinder}, |
| 34 | FromIBinder, |
| 35 | }; |
| 36 | use compos_aidl_interface::aidl::com::android::compos::ICompOsService::ICompOsService; |
Alan Stokes | f03d81a | 2021-09-20 17:44:03 +0100 | [diff] [blame] | 37 | use log::{info, warn}; |
Alan Stokes | 17fd36a | 2021-09-06 17:22:37 +0100 | [diff] [blame] | 38 | use std::fs::File; |
Alan Stokes | f03d81a | 2021-09-20 17:44:03 +0100 | [diff] [blame] | 39 | use std::io::{BufRead, BufReader}; |
Alan Stokes | 714fcc2 | 2021-09-14 17:43:09 +0100 | [diff] [blame] | 40 | use std::os::raw; |
| 41 | use std::os::unix::io::IntoRawFd; |
Alan Stokes | 17fd36a | 2021-09-06 17:22:37 +0100 | [diff] [blame] | 42 | use std::path::Path; |
| 43 | use std::sync::{Arc, Condvar, Mutex}; |
| 44 | use std::thread; |
| 45 | use std::time::Duration; |
| 46 | |
| 47 | /// This owns an instance of the CompOS VM. |
| 48 | pub struct VmInstance { |
Alan Stokes | f03d81a | 2021-09-20 17:44:03 +0100 | [diff] [blame] | 49 | #[allow(dead_code)] // Prevent service manager from killing the dynamic service |
| 50 | service: Strong<dyn IVirtualizationService>, |
| 51 | #[allow(dead_code)] // Keeps the VM alive even if we don`t touch it |
Alan Stokes | 17fd36a | 2021-09-06 17:22:37 +0100 | [diff] [blame] | 52 | vm: Strong<dyn IVirtualMachine>, |
Alan Stokes | a2869d2 | 2021-09-22 09:06:41 +0100 | [diff] [blame^] | 53 | #[allow(dead_code)] // TODO: Do we need this? |
Alan Stokes | 17fd36a | 2021-09-06 17:22:37 +0100 | [diff] [blame] | 54 | cid: i32, |
| 55 | } |
| 56 | |
| 57 | impl VmInstance { |
| 58 | /// Start a new CompOS VM instance using the specified instance image file. |
| 59 | pub fn start(instance_image: &Path) -> Result<VmInstance> { |
| 60 | let instance_image = |
| 61 | File::open(instance_image).context("Failed to open instance image file")?; |
| 62 | let instance_fd = ParcelFileDescriptor::new(instance_image); |
| 63 | |
| 64 | let apex_dir = Path::new(COMPOS_APEX_ROOT); |
| 65 | let data_dir = Path::new(COMPOS_DATA_ROOT); |
| 66 | |
| 67 | let apk_fd = File::open(apex_dir.join("app/CompOSPayloadApp/CompOSPayloadApp.apk")) |
| 68 | .context("Failed to open config APK file")?; |
| 69 | let apk_fd = ParcelFileDescriptor::new(apk_fd); |
| 70 | |
| 71 | let idsig_fd = File::open(apex_dir.join("etc/CompOSPayloadApp.apk.idsig")) |
| 72 | .context("Failed to open config APK idsig file")?; |
| 73 | let idsig_fd = ParcelFileDescriptor::new(idsig_fd); |
| 74 | |
| 75 | // TODO: Send this to stdout instead? Or specify None? |
| 76 | let log_fd = File::create(data_dir.join("vm.log")).context("Failed to create log file")?; |
| 77 | let log_fd = ParcelFileDescriptor::new(log_fd); |
| 78 | |
| 79 | let config = VirtualMachineConfig::AppConfig(VirtualMachineAppConfig { |
| 80 | apk: Some(apk_fd), |
| 81 | idsig: Some(idsig_fd), |
| 82 | instanceImage: Some(instance_fd), |
| 83 | configPath: "assets/vm_config.json".to_owned(), |
| 84 | ..Default::default() |
| 85 | }); |
| 86 | |
| 87 | let service = wait_for_interface::<dyn IVirtualizationService>( |
| 88 | "android.system.virtualizationservice", |
| 89 | ) |
| 90 | .context("Failed to find VirtualizationService")?; |
| 91 | |
Andrew Walbran | f8d9411 | 2021-09-07 11:45:36 +0000 | [diff] [blame] | 92 | let vm = service.createVm(&config, Some(&log_fd)).context("Failed to create VM")?; |
Alan Stokes | 17fd36a | 2021-09-06 17:22:37 +0100 | [diff] [blame] | 93 | let vm_state = Arc::new(VmStateMonitor::default()); |
| 94 | |
| 95 | let vm_state_clone = Arc::clone(&vm_state); |
| 96 | vm.as_binder().link_to_death(&mut DeathRecipient::new(move || { |
| 97 | vm_state_clone.set_died(); |
| 98 | log::error!("VirtualizationService died"); |
| 99 | }))?; |
| 100 | |
| 101 | let vm_state_clone = Arc::clone(&vm_state); |
| 102 | let callback = BnVirtualMachineCallback::new_binder( |
| 103 | VmCallback(vm_state_clone), |
| 104 | BinderFeatures::default(), |
| 105 | ); |
| 106 | vm.registerCallback(&callback)?; |
| 107 | |
Andrew Walbran | f8d9411 | 2021-09-07 11:45:36 +0000 | [diff] [blame] | 108 | vm.start()?; |
| 109 | |
Alan Stokes | 17fd36a | 2021-09-06 17:22:37 +0100 | [diff] [blame] | 110 | let cid = vm_state.wait_for_start()?; |
| 111 | |
| 112 | // TODO: Use onPayloadReady to avoid this |
| 113 | thread::sleep(Duration::from_secs(3)); |
| 114 | |
Alan Stokes | f03d81a | 2021-09-20 17:44:03 +0100 | [diff] [blame] | 115 | Ok(VmInstance { service, vm, cid }) |
Alan Stokes | 17fd36a | 2021-09-06 17:22:37 +0100 | [diff] [blame] | 116 | } |
| 117 | |
| 118 | /// Create and return an RPC Binder connection to the Comp OS service in the VM. |
| 119 | pub fn get_service(&self) -> Result<Strong<dyn ICompOsService>> { |
Alan Stokes | 714fcc2 | 2021-09-14 17:43:09 +0100 | [diff] [blame] | 120 | let mut vsock_factory = VsockFactory::new(&*self.vm); |
Alan Stokes | 714fcc2 | 2021-09-14 17:43:09 +0100 | [diff] [blame] | 121 | |
Alan Stokes | f03d81a | 2021-09-20 17:44:03 +0100 | [diff] [blame] | 122 | let ibinder = vsock_factory |
| 123 | .connect_rpc_client() |
| 124 | .ok_or_else(|| anyhow!("Failed to connect to CompOS service"))?; |
Alan Stokes | 17fd36a | 2021-09-06 17:22:37 +0100 | [diff] [blame] | 125 | |
| 126 | FromIBinder::try_from(ibinder).context("Connecting to CompOS service") |
| 127 | } |
Alan Stokes | b2cc79e | 2021-09-14 14:08:46 +0100 | [diff] [blame] | 128 | |
| 129 | /// Return the CID of the VM. |
| 130 | pub fn cid(&self) -> i32 { |
| 131 | self.cid |
| 132 | } |
Alan Stokes | 17fd36a | 2021-09-06 17:22:37 +0100 | [diff] [blame] | 133 | } |
| 134 | |
Alan Stokes | 714fcc2 | 2021-09-14 17:43:09 +0100 | [diff] [blame] | 135 | struct VsockFactory<'a> { |
| 136 | vm: &'a dyn IVirtualMachine, |
| 137 | } |
| 138 | |
| 139 | impl<'a> VsockFactory<'a> { |
| 140 | fn new(vm: &'a dyn IVirtualMachine) -> Self { |
| 141 | Self { vm } |
| 142 | } |
| 143 | |
Alan Stokes | f03d81a | 2021-09-20 17:44:03 +0100 | [diff] [blame] | 144 | fn connect_rpc_client(&mut self) -> Option<binder::SpIBinder> { |
| 145 | let param = self.as_void_ptr(); |
| 146 | |
| 147 | unsafe { |
| 148 | // SAFETY: AIBinder returned by RpcPreconnectedClient has correct reference count, and |
| 149 | // the ownership can be safely taken by new_spibinder. |
| 150 | // RpcPreconnectedClient does not take ownership of param, only passing it to |
| 151 | // request_fd. |
| 152 | let binder = |
| 153 | binder_rpc_unstable_bindgen::RpcPreconnectedClient(Some(Self::request_fd), param) |
| 154 | as *mut AIBinder; |
| 155 | new_spibinder(binder) |
| 156 | } |
| 157 | } |
| 158 | |
Alan Stokes | 714fcc2 | 2021-09-14 17:43:09 +0100 | [diff] [blame] | 159 | fn as_void_ptr(&mut self) -> *mut raw::c_void { |
| 160 | self as *mut _ as *mut raw::c_void |
| 161 | } |
| 162 | |
| 163 | fn try_new_vsock_fd(&self) -> Result<i32> { |
| 164 | let vsock = self.vm.connectVsock(COMPOS_VSOCK_PORT as i32)?; |
Alan Stokes | 714fcc2 | 2021-09-14 17:43:09 +0100 | [diff] [blame] | 165 | // Ownership of the fd is transferred to binder |
| 166 | Ok(vsock.into_raw_fd()) |
| 167 | } |
| 168 | |
| 169 | fn new_vsock_fd(&self) -> i32 { |
| 170 | self.try_new_vsock_fd().unwrap_or_else(|e| { |
| 171 | warn!("Connecting vsock failed: {}", e); |
| 172 | -1_i32 |
| 173 | }) |
| 174 | } |
| 175 | |
| 176 | unsafe extern "C" fn request_fd(param: *mut raw::c_void) -> raw::c_int { |
| 177 | // SAFETY: This is only ever called by RpcPreconnectedClient, within the lifetime of the |
| 178 | // VsockFactory, with param taking the value returned by as_void_ptr (so a properly aligned |
| 179 | // non-null pointer to an initialized instance). |
Alan Stokes | f03d81a | 2021-09-20 17:44:03 +0100 | [diff] [blame] | 180 | let vsock_factory = param as *mut Self; |
| 181 | vsock_factory.as_ref().unwrap().new_vsock_fd() |
Alan Stokes | 714fcc2 | 2021-09-14 17:43:09 +0100 | [diff] [blame] | 182 | } |
| 183 | } |
| 184 | |
Alan Stokes | 17fd36a | 2021-09-06 17:22:37 +0100 | [diff] [blame] | 185 | #[derive(Debug)] |
| 186 | struct VmState { |
| 187 | has_died: bool, |
| 188 | cid: Option<i32>, |
| 189 | } |
| 190 | |
| 191 | impl Default for VmState { |
| 192 | fn default() -> Self { |
| 193 | Self { has_died: false, cid: None } |
| 194 | } |
| 195 | } |
| 196 | |
| 197 | #[derive(Debug)] |
| 198 | struct VmStateMonitor { |
| 199 | mutex: Mutex<VmState>, |
| 200 | state_ready: Condvar, |
| 201 | } |
| 202 | |
| 203 | impl Default for VmStateMonitor { |
| 204 | fn default() -> Self { |
| 205 | Self { mutex: Mutex::new(Default::default()), state_ready: Condvar::new() } |
| 206 | } |
| 207 | } |
| 208 | |
| 209 | impl VmStateMonitor { |
| 210 | fn set_died(&self) { |
| 211 | let mut state = self.mutex.lock().unwrap(); |
| 212 | state.has_died = true; |
| 213 | state.cid = None; |
| 214 | drop(state); // Unlock the mutex prior to notifying |
| 215 | self.state_ready.notify_all(); |
| 216 | } |
| 217 | |
| 218 | fn set_started(&self, cid: i32) { |
| 219 | let mut state = self.mutex.lock().unwrap(); |
| 220 | if state.has_died { |
| 221 | return; |
| 222 | } |
| 223 | state.cid = Some(cid); |
| 224 | drop(state); // Unlock the mutex prior to notifying |
| 225 | self.state_ready.notify_all(); |
| 226 | } |
| 227 | |
| 228 | fn wait_for_start(&self) -> Result<i32> { |
| 229 | let (state, result) = self |
| 230 | .state_ready |
| 231 | .wait_timeout_while(self.mutex.lock().unwrap(), Duration::from_secs(10), |state| { |
| 232 | state.cid.is_none() && !state.has_died |
| 233 | }) |
| 234 | .unwrap(); |
| 235 | if result.timed_out() { |
| 236 | bail!("Timed out waiting for VM") |
| 237 | } |
| 238 | state.cid.ok_or_else(|| anyhow!("VM died")) |
| 239 | } |
| 240 | } |
| 241 | |
| 242 | #[derive(Debug)] |
| 243 | struct VmCallback(Arc<VmStateMonitor>); |
| 244 | |
| 245 | impl Interface for VmCallback {} |
| 246 | |
| 247 | impl IVirtualMachineCallback for VmCallback { |
| 248 | fn onDied(&self, cid: i32) -> BinderResult<()> { |
| 249 | self.0.set_died(); |
| 250 | log::warn!("VM died, cid = {}", cid); |
| 251 | Ok(()) |
| 252 | } |
| 253 | |
| 254 | fn onPayloadStarted( |
| 255 | &self, |
| 256 | cid: i32, |
Alan Stokes | f03d81a | 2021-09-20 17:44:03 +0100 | [diff] [blame] | 257 | stream: Option<&ParcelFileDescriptor>, |
Alan Stokes | 17fd36a | 2021-09-06 17:22:37 +0100 | [diff] [blame] | 258 | ) -> BinderResult<()> { |
| 259 | self.0.set_started(cid); |
Alan Stokes | f03d81a | 2021-09-20 17:44:03 +0100 | [diff] [blame] | 260 | if let Some(pfd) = stream { |
| 261 | if let Err(e) = start_logging(pfd) { |
| 262 | warn!("Can't log vm output: {}", e); |
| 263 | }; |
| 264 | } |
Alan Stokes | 17fd36a | 2021-09-06 17:22:37 +0100 | [diff] [blame] | 265 | log::info!("VM payload started, cid = {}", cid); |
| 266 | Ok(()) |
| 267 | } |
| 268 | |
| 269 | fn onPayloadReady(&self, cid: i32) -> BinderResult<()> { |
| 270 | // TODO: Use this to trigger vsock connection |
| 271 | log::info!("VM payload ready, cid = {}", cid); |
| 272 | Ok(()) |
| 273 | } |
| 274 | |
| 275 | fn onPayloadFinished(&self, cid: i32, exit_code: i32) -> BinderResult<()> { |
| 276 | // This should probably never happen in our case, but if it does we means our VM is no |
| 277 | // longer running |
| 278 | self.0.set_died(); |
| 279 | log::warn!("VM payload finished, cid = {}, exit code = {}", cid, exit_code); |
| 280 | Ok(()) |
| 281 | } |
| 282 | } |
Alan Stokes | f03d81a | 2021-09-20 17:44:03 +0100 | [diff] [blame] | 283 | |
| 284 | fn start_logging(pfd: &ParcelFileDescriptor) -> Result<()> { |
| 285 | let reader = BufReader::new(pfd.as_ref().try_clone().context("Cloning fd failed")?); |
| 286 | thread::spawn(move || { |
| 287 | for line in reader.lines() { |
| 288 | match line { |
| 289 | Ok(line) => info!("VM: {}", line), |
| 290 | Err(e) => { |
| 291 | warn!("Reading VM output failed: {}", e); |
| 292 | break; |
| 293 | } |
| 294 | } |
| 295 | } |
| 296 | }); |
| 297 | Ok(()) |
| 298 | } |