blob: 8030af1f74005294cd919d888246c81c6c8414df [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)?;
152 // ParcelableFileDescriptor won't release its fd so we have to dup it.
153 let vsock = vsock.as_ref().try_clone()?;
154 // Ownership of the fd is transferred to binder
155 Ok(vsock.into_raw_fd())
156 }
157
158 fn new_vsock_fd(&self) -> i32 {
159 self.try_new_vsock_fd().unwrap_or_else(|e| {
160 warn!("Connecting vsock failed: {}", e);
161 -1_i32
162 })
163 }
164
165 unsafe extern "C" fn request_fd(param: *mut raw::c_void) -> raw::c_int {
166 // SAFETY: This is only ever called by RpcPreconnectedClient, within the lifetime of the
167 // VsockFactory, with param taking the value returned by as_void_ptr (so a properly aligned
168 // non-null pointer to an initialized instance).
169 let holder = param as *mut Self;
170 holder.as_ref().unwrap().new_vsock_fd()
171 }
172}
173
Alan Stokes17fd36a2021-09-06 17:22:37 +0100174#[derive(Debug)]
175struct VmState {
176 has_died: bool,
177 cid: Option<i32>,
178}
179
180impl Default for VmState {
181 fn default() -> Self {
182 Self { has_died: false, cid: None }
183 }
184}
185
186#[derive(Debug)]
187struct VmStateMonitor {
188 mutex: Mutex<VmState>,
189 state_ready: Condvar,
190}
191
192impl Default for VmStateMonitor {
193 fn default() -> Self {
194 Self { mutex: Mutex::new(Default::default()), state_ready: Condvar::new() }
195 }
196}
197
198impl VmStateMonitor {
199 fn set_died(&self) {
200 let mut state = self.mutex.lock().unwrap();
201 state.has_died = true;
202 state.cid = None;
203 drop(state); // Unlock the mutex prior to notifying
204 self.state_ready.notify_all();
205 }
206
207 fn set_started(&self, cid: i32) {
208 let mut state = self.mutex.lock().unwrap();
209 if state.has_died {
210 return;
211 }
212 state.cid = Some(cid);
213 drop(state); // Unlock the mutex prior to notifying
214 self.state_ready.notify_all();
215 }
216
217 fn wait_for_start(&self) -> Result<i32> {
218 let (state, result) = self
219 .state_ready
220 .wait_timeout_while(self.mutex.lock().unwrap(), Duration::from_secs(10), |state| {
221 state.cid.is_none() && !state.has_died
222 })
223 .unwrap();
224 if result.timed_out() {
225 bail!("Timed out waiting for VM")
226 }
227 state.cid.ok_or_else(|| anyhow!("VM died"))
228 }
229}
230
231#[derive(Debug)]
232struct VmCallback(Arc<VmStateMonitor>);
233
234impl Interface for VmCallback {}
235
236impl IVirtualMachineCallback for VmCallback {
237 fn onDied(&self, cid: i32) -> BinderResult<()> {
238 self.0.set_died();
239 log::warn!("VM died, cid = {}", cid);
240 Ok(())
241 }
242
243 fn onPayloadStarted(
244 &self,
245 cid: i32,
246 _stream: Option<&binder::parcel::ParcelFileDescriptor>,
247 ) -> BinderResult<()> {
248 self.0.set_started(cid);
249 // TODO: Use the stream?
250 log::info!("VM payload started, cid = {}", cid);
251 Ok(())
252 }
253
254 fn onPayloadReady(&self, cid: i32) -> BinderResult<()> {
255 // TODO: Use this to trigger vsock connection
256 log::info!("VM payload ready, cid = {}", cid);
257 Ok(())
258 }
259
260 fn onPayloadFinished(&self, cid: i32, exit_code: i32) -> BinderResult<()> {
261 // This should probably never happen in our case, but if it does we means our VM is no
262 // longer running
263 self.0.set_died();
264 log::warn!("VM payload finished, cid = {}, exit code = {}", cid, exit_code);
265 Ok(())
266 }
267}