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