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