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