blob: 22304f174f19e848f23d82e6d085412a8443e4ca [file] [log] [blame]
Alan Stokes17fd36a2021-09-06 17:22:37 +01001/*
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
19use crate::{COMPOS_APEX_ROOT, COMPOS_DATA_ROOT, COMPOS_VSOCK_PORT};
20use android_system_virtualizationservice::aidl::android::system::virtualizationservice::{
21 IVirtualMachine::IVirtualMachine,
22 IVirtualMachineCallback::{BnVirtualMachineCallback, IVirtualMachineCallback},
23 IVirtualizationService::IVirtualizationService,
24 VirtualMachineAppConfig::VirtualMachineAppConfig,
25 VirtualMachineConfig::VirtualMachineConfig,
26};
27use android_system_virtualizationservice::binder::{
28 wait_for_interface, BinderFeatures, DeathRecipient, IBinder, Interface, ParcelFileDescriptor,
29 Result as BinderResult, Strong,
30};
31use anyhow::{anyhow, bail, Context, Result};
32use binder::{
33 unstable_api::{new_spibinder, AIBinder},
34 FromIBinder,
35};
36use compos_aidl_interface::aidl::com::android::compos::ICompOsService::ICompOsService;
37use std::fs::File;
38use std::path::Path;
39use std::sync::{Arc, Condvar, Mutex};
40use std::thread;
41use std::time::Duration;
42
43/// This owns an instance of the CompOS VM.
44pub struct VmInstance {
45 #[allow(dead_code)] // Keeps the vm alive even if we don`t touch it
46 vm: Strong<dyn IVirtualMachine>,
47 cid: i32,
48}
49
50impl VmInstance {
51 /// Start a new CompOS VM instance using the specified instance image file.
52 pub fn start(instance_image: &Path) -> Result<VmInstance> {
53 let instance_image =
54 File::open(instance_image).context("Failed to open instance image file")?;
55 let instance_fd = ParcelFileDescriptor::new(instance_image);
56
57 let apex_dir = Path::new(COMPOS_APEX_ROOT);
58 let data_dir = Path::new(COMPOS_DATA_ROOT);
59
60 let apk_fd = File::open(apex_dir.join("app/CompOSPayloadApp/CompOSPayloadApp.apk"))
61 .context("Failed to open config APK file")?;
62 let apk_fd = ParcelFileDescriptor::new(apk_fd);
63
64 let idsig_fd = File::open(apex_dir.join("etc/CompOSPayloadApp.apk.idsig"))
65 .context("Failed to open config APK idsig file")?;
66 let idsig_fd = ParcelFileDescriptor::new(idsig_fd);
67
68 // TODO: Send this to stdout instead? Or specify None?
69 let log_fd = File::create(data_dir.join("vm.log")).context("Failed to create log file")?;
70 let log_fd = ParcelFileDescriptor::new(log_fd);
71
72 let config = VirtualMachineConfig::AppConfig(VirtualMachineAppConfig {
73 apk: Some(apk_fd),
74 idsig: Some(idsig_fd),
75 instanceImage: Some(instance_fd),
76 configPath: "assets/vm_config.json".to_owned(),
77 ..Default::default()
78 });
79
80 let service = wait_for_interface::<dyn IVirtualizationService>(
81 "android.system.virtualizationservice",
82 )
83 .context("Failed to find VirtualizationService")?;
84
Andrew Walbranf8d94112021-09-07 11:45:36 +000085 let vm = service.createVm(&config, Some(&log_fd)).context("Failed to create VM")?;
Alan Stokes17fd36a2021-09-06 17:22:37 +010086 let vm_state = Arc::new(VmStateMonitor::default());
87
88 let vm_state_clone = Arc::clone(&vm_state);
89 vm.as_binder().link_to_death(&mut DeathRecipient::new(move || {
90 vm_state_clone.set_died();
91 log::error!("VirtualizationService died");
92 }))?;
93
94 let vm_state_clone = Arc::clone(&vm_state);
95 let callback = BnVirtualMachineCallback::new_binder(
96 VmCallback(vm_state_clone),
97 BinderFeatures::default(),
98 );
99 vm.registerCallback(&callback)?;
100
Andrew Walbranf8d94112021-09-07 11:45:36 +0000101 vm.start()?;
102
Alan Stokes17fd36a2021-09-06 17:22:37 +0100103 let cid = vm_state.wait_for_start()?;
104
105 // TODO: Use onPayloadReady to avoid this
106 thread::sleep(Duration::from_secs(3));
107
108 Ok(VmInstance { vm, cid })
109 }
110
111 /// Create and return an RPC Binder connection to the Comp OS service in the VM.
112 pub fn get_service(&self) -> Result<Strong<dyn ICompOsService>> {
113 let cid = self.cid as u32;
114 // SAFETY: AIBinder returned by RpcClient has correct reference count, and the ownership
115 // can be safely taken by new_spibinder.
116 let ibinder = unsafe {
117 new_spibinder(
118 binder_rpc_unstable_bindgen::RpcClient(cid, COMPOS_VSOCK_PORT) as *mut AIBinder
119 )
120 }
121 .ok_or_else(|| anyhow!("Failed to connect to CompOS service"))?;
122
123 FromIBinder::try_from(ibinder).context("Connecting to CompOS service")
124 }
125}
126
127#[derive(Debug)]
128struct VmState {
129 has_died: bool,
130 cid: Option<i32>,
131}
132
133impl Default for VmState {
134 fn default() -> Self {
135 Self { has_died: false, cid: None }
136 }
137}
138
139#[derive(Debug)]
140struct VmStateMonitor {
141 mutex: Mutex<VmState>,
142 state_ready: Condvar,
143}
144
145impl Default for VmStateMonitor {
146 fn default() -> Self {
147 Self { mutex: Mutex::new(Default::default()), state_ready: Condvar::new() }
148 }
149}
150
151impl VmStateMonitor {
152 fn set_died(&self) {
153 let mut state = self.mutex.lock().unwrap();
154 state.has_died = true;
155 state.cid = None;
156 drop(state); // Unlock the mutex prior to notifying
157 self.state_ready.notify_all();
158 }
159
160 fn set_started(&self, cid: i32) {
161 let mut state = self.mutex.lock().unwrap();
162 if state.has_died {
163 return;
164 }
165 state.cid = Some(cid);
166 drop(state); // Unlock the mutex prior to notifying
167 self.state_ready.notify_all();
168 }
169
170 fn wait_for_start(&self) -> Result<i32> {
171 let (state, result) = self
172 .state_ready
173 .wait_timeout_while(self.mutex.lock().unwrap(), Duration::from_secs(10), |state| {
174 state.cid.is_none() && !state.has_died
175 })
176 .unwrap();
177 if result.timed_out() {
178 bail!("Timed out waiting for VM")
179 }
180 state.cid.ok_or_else(|| anyhow!("VM died"))
181 }
182}
183
184#[derive(Debug)]
185struct VmCallback(Arc<VmStateMonitor>);
186
187impl Interface for VmCallback {}
188
189impl IVirtualMachineCallback for VmCallback {
190 fn onDied(&self, cid: i32) -> BinderResult<()> {
191 self.0.set_died();
192 log::warn!("VM died, cid = {}", cid);
193 Ok(())
194 }
195
196 fn onPayloadStarted(
197 &self,
198 cid: i32,
199 _stream: Option<&binder::parcel::ParcelFileDescriptor>,
200 ) -> BinderResult<()> {
201 self.0.set_started(cid);
202 // TODO: Use the stream?
203 log::info!("VM payload started, cid = {}", cid);
204 Ok(())
205 }
206
207 fn onPayloadReady(&self, cid: i32) -> BinderResult<()> {
208 // TODO: Use this to trigger vsock connection
209 log::info!("VM payload ready, cid = {}", cid);
210 Ok(())
211 }
212
213 fn onPayloadFinished(&self, cid: i32, exit_code: i32) -> BinderResult<()> {
214 // This should probably never happen in our case, but if it does we means our VM is no
215 // longer running
216 self.0.set_died();
217 log::warn!("VM payload finished, cid = {}, exit code = {}", cid, exit_code);
218 Ok(())
219 }
220}