blob: dd8e54f43c4fbcabc4ed694d843fc7208f486ecc [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
85 let vm = service.startVm(&config, Some(&log_fd)).context("Failed to start VM")?;
86 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
101 let cid = vm_state.wait_for_start()?;
102
103 // TODO: Use onPayloadReady to avoid this
104 thread::sleep(Duration::from_secs(3));
105
106 Ok(VmInstance { vm, cid })
107 }
108
109 /// Create and return an RPC Binder connection to the Comp OS service in the VM.
110 pub fn get_service(&self) -> Result<Strong<dyn ICompOsService>> {
111 let cid = self.cid as u32;
112 // SAFETY: AIBinder returned by RpcClient has correct reference count, and the ownership
113 // can be safely taken by new_spibinder.
114 let ibinder = unsafe {
115 new_spibinder(
116 binder_rpc_unstable_bindgen::RpcClient(cid, COMPOS_VSOCK_PORT) as *mut AIBinder
117 )
118 }
119 .ok_or_else(|| anyhow!("Failed to connect to CompOS service"))?;
120
121 FromIBinder::try_from(ibinder).context("Connecting to CompOS service")
122 }
123}
124
125#[derive(Debug)]
126struct VmState {
127 has_died: bool,
128 cid: Option<i32>,
129}
130
131impl Default for VmState {
132 fn default() -> Self {
133 Self { has_died: false, cid: None }
134 }
135}
136
137#[derive(Debug)]
138struct VmStateMonitor {
139 mutex: Mutex<VmState>,
140 state_ready: Condvar,
141}
142
143impl Default for VmStateMonitor {
144 fn default() -> Self {
145 Self { mutex: Mutex::new(Default::default()), state_ready: Condvar::new() }
146 }
147}
148
149impl VmStateMonitor {
150 fn set_died(&self) {
151 let mut state = self.mutex.lock().unwrap();
152 state.has_died = true;
153 state.cid = None;
154 drop(state); // Unlock the mutex prior to notifying
155 self.state_ready.notify_all();
156 }
157
158 fn set_started(&self, cid: i32) {
159 let mut state = self.mutex.lock().unwrap();
160 if state.has_died {
161 return;
162 }
163 state.cid = Some(cid);
164 drop(state); // Unlock the mutex prior to notifying
165 self.state_ready.notify_all();
166 }
167
168 fn wait_for_start(&self) -> Result<i32> {
169 let (state, result) = self
170 .state_ready
171 .wait_timeout_while(self.mutex.lock().unwrap(), Duration::from_secs(10), |state| {
172 state.cid.is_none() && !state.has_died
173 })
174 .unwrap();
175 if result.timed_out() {
176 bail!("Timed out waiting for VM")
177 }
178 state.cid.ok_or_else(|| anyhow!("VM died"))
179 }
180}
181
182#[derive(Debug)]
183struct VmCallback(Arc<VmStateMonitor>);
184
185impl Interface for VmCallback {}
186
187impl IVirtualMachineCallback for VmCallback {
188 fn onDied(&self, cid: i32) -> BinderResult<()> {
189 self.0.set_died();
190 log::warn!("VM died, cid = {}", cid);
191 Ok(())
192 }
193
194 fn onPayloadStarted(
195 &self,
196 cid: i32,
197 _stream: Option<&binder::parcel::ParcelFileDescriptor>,
198 ) -> BinderResult<()> {
199 self.0.set_started(cid);
200 // TODO: Use the stream?
201 log::info!("VM payload started, cid = {}", cid);
202 Ok(())
203 }
204
205 fn onPayloadReady(&self, cid: i32) -> BinderResult<()> {
206 // TODO: Use this to trigger vsock connection
207 log::info!("VM payload ready, cid = {}", cid);
208 Ok(())
209 }
210
211 fn onPayloadFinished(&self, cid: i32, exit_code: i32) -> BinderResult<()> {
212 // This should probably never happen in our case, but if it does we means our VM is no
213 // longer running
214 self.0.set_died();
215 log::warn!("VM payload finished, cid = {}, exit code = {}", cid, exit_code);
216 Ok(())
217 }
218}