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