1 /*
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 //! Simple command-line tool to drive composd for testing and debugging.
18 
19 use android_system_composd::{
20     aidl::android::system::composd::{
21         ICompilationTask::ICompilationTask,
22         ICompilationTaskCallback::{
23             BnCompilationTaskCallback, FailureReason::FailureReason, ICompilationTaskCallback,
24         },
25         IIsolatedCompilationService::ApexSource::ApexSource,
26         IIsolatedCompilationService::IIsolatedCompilationService,
27     },
28     binder::{
29         wait_for_interface, BinderFeatures, DeathRecipient, IBinder, Interface, ProcessState,
30         Result as BinderResult, Strong,
31     },
32 };
33 use anyhow::{bail, Context, Result};
34 use clap::Parser;
35 use compos_common::timeouts::TIMEOUTS;
36 use std::sync::{Arc, Condvar, Mutex};
37 use std::time::Duration;
38 
39 #[derive(Parser)]
40 enum Actions {
41     /// Compile classpath for real. Output can be used after a reboot.
42     StagedApexCompile {},
43 
44     /// Compile classpath in a debugging VM. Output is ignored.
45     TestCompile {
46         /// If any APEX is staged, prefer the staged version.
47         #[clap(long)]
48         prefer_staged: bool,
49 
50         /// OS for the VM.
51         #[clap(long, default_value = "microdroid")]
52         os: String,
53     },
54 }
55 
main() -> Result<()>56 fn main() -> Result<()> {
57     let action = Actions::parse();
58 
59     ProcessState::start_thread_pool();
60 
61     match action {
62         Actions::StagedApexCompile {} => run_staged_apex_compile()?,
63         Actions::TestCompile { prefer_staged, os } => run_test_compile(prefer_staged, &os)?,
64     }
65 
66     println!("All Ok!");
67 
68     Ok(())
69 }
70 
71 struct Callback(Arc<State>);
72 
73 #[derive(Default)]
74 struct State {
75     mutex: Mutex<Option<Outcome>>,
76     completed: Condvar,
77 }
78 
79 enum Outcome {
80     Succeeded,
81     Failed(FailureReason, String),
82     TaskDied,
83 }
84 
85 impl Interface for Callback {}
86 
87 impl ICompilationTaskCallback for Callback {
onSuccess(&self) -> BinderResult<()>88     fn onSuccess(&self) -> BinderResult<()> {
89         self.0.set_outcome(Outcome::Succeeded);
90         Ok(())
91     }
92 
onFailure(&self, reason: FailureReason, message: &str) -> BinderResult<()>93     fn onFailure(&self, reason: FailureReason, message: &str) -> BinderResult<()> {
94         self.0.set_outcome(Outcome::Failed(reason, message.to_owned()));
95         Ok(())
96     }
97 }
98 
99 impl State {
set_outcome(&self, outcome: Outcome)100     fn set_outcome(&self, outcome: Outcome) {
101         let mut guard = self.mutex.lock().unwrap();
102         *guard = Some(outcome);
103         drop(guard);
104         self.completed.notify_all();
105     }
106 
wait(&self, duration: Duration) -> Result<Outcome>107     fn wait(&self, duration: Duration) -> Result<Outcome> {
108         let (mut outcome, result) = self
109             .completed
110             .wait_timeout_while(self.mutex.lock().unwrap(), duration, |outcome| outcome.is_none())
111             .unwrap();
112         if result.timed_out() {
113             bail!("Timed out waiting for compilation")
114         }
115         Ok(outcome.take().unwrap())
116     }
117 }
118 
run_staged_apex_compile() -> Result<()>119 fn run_staged_apex_compile() -> Result<()> {
120     run_async_compilation(|service, callback| service.startStagedApexCompile(callback))
121 }
122 
run_test_compile(prefer_staged: bool, os: &str) -> Result<()>123 fn run_test_compile(prefer_staged: bool, os: &str) -> Result<()> {
124     let apex_source = if prefer_staged { ApexSource::PreferStaged } else { ApexSource::NoStaged };
125     run_async_compilation(|service, callback| service.startTestCompile(apex_source, callback, os))
126 }
127 
run_async_compilation<F>(start_compile_fn: F) -> Result<()> where F: FnOnce( &dyn IIsolatedCompilationService, &Strong<dyn ICompilationTaskCallback>, ) -> BinderResult<Strong<dyn ICompilationTask>>,128 fn run_async_compilation<F>(start_compile_fn: F) -> Result<()>
129 where
130     F: FnOnce(
131         &dyn IIsolatedCompilationService,
132         &Strong<dyn ICompilationTaskCallback>,
133     ) -> BinderResult<Strong<dyn ICompilationTask>>,
134 {
135     if !hypervisor_props::is_any_vm_supported()? {
136         // Give up now, before trying to start composd, or we may end up waiting forever
137         // as it repeatedly starts and then aborts (b/254599807).
138         bail!("Device doesn't support protected or non-protected VMs")
139     }
140 
141     let service = wait_for_interface::<dyn IIsolatedCompilationService>("android.system.composd")
142         .context("Failed to connect to composd service")?;
143 
144     let state = Arc::new(State::default());
145     let callback = Callback(state.clone());
146     let callback = BnCompilationTaskCallback::new_binder(callback, BinderFeatures::default());
147     let task = start_compile_fn(&*service, &callback).context("Compilation failed")?;
148 
149     // Make sure composd keeps going even if we don't hold a reference to its service.
150     drop(service);
151 
152     let state_clone = state.clone();
153     let mut death_recipient = DeathRecipient::new(move || {
154         eprintln!("CompilationTask died");
155         state_clone.set_outcome(Outcome::TaskDied);
156     });
157     // Note that dropping death_recipient cancels this, so we can't use a temporary here.
158     task.as_binder().link_to_death(&mut death_recipient)?;
159 
160     println!("Waiting");
161 
162     match state.wait(TIMEOUTS.odrefresh_max_execution_time) {
163         Ok(Outcome::Succeeded) => Ok(()),
164         Ok(Outcome::TaskDied) => bail!("Compilation task died"),
165         Ok(Outcome::Failed(reason, message)) => {
166             bail!("Compilation failed: {:?}: {}", reason, message)
167         }
168         Err(e) => {
169             if let Err(e) = task.cancel() {
170                 eprintln!("Failed to cancel compilation: {:?}", e);
171             }
172             Err(e)
173         }
174     }
175 }
176 
177 #[cfg(test)]
178 mod tests {
179     use super::*;
180     use clap::CommandFactory;
181 
182     #[test]
verify_actions()183     fn verify_actions() {
184         // Check that the command parsing has been configured in a valid way.
185         Actions::command().debug_assert();
186     }
187 }
188