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