fuchsia/
lib.rs

1// Copyright 2020 The Fuchsia Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5//! Macros for creating Fuchsia components and tests.
6//!
7//! These macros work on Fuchsia, and also on host with some limitations (that are called out
8//! where they exist).
9
10// Features from those macros are expected to be implemented by exactly one function in this
11// module. We strive for simple, independent, single purpose functions as building blocks to allow
12// dead code elimination to have the very best chance of removing unused code that might be
13// otherwise pulled in here.
14
15#![deny(missing_docs)]
16
17pub use fuchsia_macro::{main, test};
18use libc as _;
19#[doc(hidden)]
20pub use log::error;
21use std::future::Future;
22
23#[cfg(fuchsia_api_level_less_than = "27")]
24pub use fidl_fuchsia_diagnostics::{Interest, Severity};
25#[cfg(fuchsia_api_level_at_least = "27")]
26pub use fidl_fuchsia_diagnostics_types::{Interest, Severity};
27
28//
29// LOGGING INITIALIZATION
30//
31
32/// Options used when initializing logging.
33#[derive(Default, Clone)]
34pub struct LoggingOptions<'a> {
35    /// Tags with which to initialize the logging system. All logs will carry the tags configured
36    /// here.
37    pub tags: &'a [&'static str],
38
39    /// Allows to configure the minimum severity of the logs being emitted. Logs of lower severity
40    /// won't be emitted.
41    pub interest: Interest,
42
43    /// Whether or not logs will be blocking. By default logs are dropped when they can't be
44    /// written to the socket. However, when this is set, the log statement will block until the
45    /// log can be written to the socket or the socket is closed.
46    ///
47    /// NOTE: this is ignored on `host`.
48    pub blocking: bool,
49
50    /// String to include in logged panic messages.
51    pub panic_prefix: &'static str,
52
53    /// True to always log file/line information, false to only log
54    /// when severity is ERROR or above.
55    pub always_log_file_line: bool,
56}
57
58#[cfg(not(target_os = "fuchsia"))]
59impl<'a> From<LoggingOptions<'a>> for diagnostics_log::PublishOptions<'a> {
60    fn from(logging: LoggingOptions<'a>) -> Self {
61        let mut options = diagnostics_log::PublishOptions::default().tags(logging.tags);
62        if let Some(severity) = logging.interest.min_severity {
63            options = options.minimum_severity(severity);
64        }
65        options = options.panic_prefix(logging.panic_prefix);
66        options
67    }
68}
69
70#[cfg(target_os = "fuchsia")]
71impl<'a> From<LoggingOptions<'a>> for diagnostics_log::PublishOptions<'a> {
72    fn from(logging: LoggingOptions<'a>) -> Self {
73        let mut options = diagnostics_log::PublishOptions::default().tags(logging.tags);
74        options = options.blocking(logging.blocking);
75        if let Some(severity) = logging.interest.min_severity {
76            options = options.minimum_severity(severity);
77        }
78        if logging.always_log_file_line {
79            options = options.always_log_file_line();
80        }
81        options = options.panic_prefix(logging.panic_prefix);
82        options
83    }
84}
85
86/// Initialize logging
87#[doc(hidden)]
88pub fn init_logging_for_component_with_executor<'a, R>(
89    func: impl FnOnce() -> R + 'a,
90    logging: LoggingOptions<'a>,
91) -> impl FnOnce() -> R + 'a {
92    move || {
93        diagnostics_log::initialize(logging.into()).expect("initialize_logging");
94        func()
95    }
96}
97
98/// Initialize logging
99#[doc(hidden)]
100pub fn init_logging_for_component_with_threads<'a, R>(
101    func: impl FnOnce() -> R + 'a,
102    logging: LoggingOptions<'a>,
103) -> impl FnOnce() -> R + 'a {
104    move || {
105        let _guard = init_logging_with_threads(logging);
106        func()
107    }
108}
109
110/// Initialize logging
111#[doc(hidden)]
112#[cfg(target_os = "fuchsia")]
113pub fn init_logging_for_test_with_executor<'a, R>(
114    func: impl Fn(usize) -> R + 'a,
115    logging: LoggingOptions<'a>,
116) -> impl Fn(usize) -> R + 'a {
117    move |n| {
118        diagnostics_log::initialize(logging.clone().into()).expect("initalize logging");
119        func(n)
120    }
121}
122
123/// Initialize logging
124#[doc(hidden)]
125#[cfg(target_os = "fuchsia")]
126pub fn init_logging_for_test_with_threads<'a, R>(
127    func: impl Fn(usize) -> R + 'a,
128    logging: LoggingOptions<'a>,
129) -> impl Fn(usize) -> R + 'a {
130    move |n| {
131        let _guard = init_logging_with_threads(logging.clone());
132        func(n)
133    }
134}
135
136/// Initializes logging on a background thread, returning a guard which cancels interest listening
137/// when dropped.
138#[cfg(target_os = "fuchsia")]
139fn init_logging_with_threads(logging: LoggingOptions<'_>) -> impl Drop {
140    diagnostics_log::initialize_sync(logging.into())
141}
142
143#[cfg(not(target_os = "fuchsia"))]
144fn init_logging_with_threads(logging: LoggingOptions<'_>) {
145    diagnostics_log::initialize(logging.into()).expect("initialize_logging");
146}
147
148/// Initialize logging
149#[doc(hidden)]
150#[cfg(not(target_os = "fuchsia"))]
151pub fn init_logging_for_test_with_executor<'a, R>(
152    func: impl Fn(usize) -> R + 'a,
153    _logging: LoggingOptions<'a>,
154) -> impl Fn(usize) -> R + 'a {
155    move |n| func(n)
156}
157
158/// Initialize logging
159#[doc(hidden)]
160#[cfg(not(target_os = "fuchsia"))]
161pub fn init_logging_for_test_with_threads<'a, R>(
162    func: impl Fn(usize) -> R + 'a,
163    _logging: LoggingOptions<'a>,
164) -> impl Fn(usize) -> R + 'a {
165    move |n| func(n)
166}
167
168#[cfg(target_os = "fuchsia")]
169fn set_thread_role(role_name: &str) {
170    if let Err(e) = fuchsia_scheduler::set_role_for_this_thread(role_name) {
171        log::warn!(e:%, role_name:%; "Couldn't apply thread role.");
172    }
173}
174
175//
176// MAIN FUNCTION WRAPPERS
177//
178
179/// Run a non-async main function.
180#[doc(hidden)]
181pub fn main_not_async<F, R>(f: F) -> R
182where
183    F: FnOnce() -> R,
184{
185    f()
186}
187
188/// Run a non-async main function, applying `role_name` as the thread role.
189#[doc(hidden)]
190pub fn main_not_async_with_role<F, R>(f: F, _role_name: &'static str) -> R
191where
192    F: FnOnce() -> R,
193{
194    #[cfg(target_os = "fuchsia")]
195    set_thread_role(_role_name);
196    f()
197}
198
199/// Run an async main function with a single threaded executor.
200#[doc(hidden)]
201pub fn main_singlethreaded<F, Fut, R>(f: F) -> R
202where
203    F: FnOnce() -> Fut,
204    Fut: Future<Output = R> + 'static,
205{
206    fuchsia_async::LocalExecutor::new().run_singlethreaded(f())
207}
208
209/// Run an async main function with a single threaded executor, applying `role_name`.
210#[doc(hidden)]
211pub fn main_singlethreaded_with_role<F, Fut, R>(f: F, _role_name: &'static str) -> R
212where
213    F: FnOnce() -> Fut,
214    Fut: Future<Output = R> + 'static,
215{
216    #[cfg(target_os = "fuchsia")]
217    set_thread_role(_role_name);
218    fuchsia_async::LocalExecutor::new().run_singlethreaded(f())
219}
220
221/// Run an async main function with a multi threaded executor (containing `num_threads`).
222#[doc(hidden)]
223pub fn main_multithreaded<F, Fut, R>(f: F, num_threads: u8) -> R
224where
225    F: FnOnce() -> Fut,
226    Fut: Future<Output = R> + Send + 'static,
227    R: Send + 'static,
228{
229    fuchsia_async::SendExecutor::new(num_threads).run(f())
230}
231
232/// Run an async main function with a multi threaded executor (containing `num_threads`) and apply
233/// `role_name` to all of the threads.
234#[doc(hidden)]
235pub fn main_multithreaded_with_role<F, Fut, R>(f: F, num_threads: u8, _role_name: &'static str) -> R
236where
237    F: FnOnce() -> Fut,
238    Fut: Future<Output = R> + Send + 'static,
239    R: Send + 'static,
240{
241    let mut exec = fuchsia_async::SendExecutor::new(num_threads);
242    #[cfg(target_os = "fuchsia")]
243    {
244        set_thread_role(_role_name);
245        exec.set_worker_init(move || set_thread_role(_role_name));
246    }
247    exec.run(f())
248}
249
250//
251// TEST FUNCTION WRAPPERS
252//
253
254/// Run a non-async test function.
255#[doc(hidden)]
256pub fn test_not_async<F, R>(f: F) -> R
257where
258    F: FnOnce(usize) -> R,
259    R: fuchsia_async::test_support::TestResult,
260{
261    let result = f(0);
262    if result.is_ok() {
263        install_lsan_hook();
264    }
265    result
266}
267
268/// Run an async test function with a single threaded executor.
269#[doc(hidden)]
270pub fn test_singlethreaded<F, Fut, R>(f: F) -> R
271where
272    F: Fn(usize) -> Fut + Sync + 'static,
273    Fut: Future<Output = R> + 'static,
274    R: fuchsia_async::test_support::TestResult,
275{
276    let result = fuchsia_async::test_support::run_singlethreaded_test(f);
277    if result.is_ok() {
278        install_lsan_hook();
279    }
280    result
281}
282
283/// Run an async test function with a multi threaded executor (containing `num_threads`).
284#[doc(hidden)]
285pub fn test_multithreaded<F, Fut, R>(f: F, num_threads: u8) -> R
286where
287    F: Fn(usize) -> Fut + Sync + 'static,
288    Fut: Future<Output = R> + Send + 'static,
289    R: fuchsia_async::test_support::MultithreadedTestResult,
290{
291    let result = fuchsia_async::test_support::run_test(f, num_threads);
292    if result.is_ok() {
293        install_lsan_hook();
294    }
295    result
296}
297
298/// Run an async test function until it stalls. The executor will also use fake time.
299#[doc(hidden)]
300#[cfg(target_os = "fuchsia")]
301pub fn test_until_stalled<F, Fut, R>(f: F) -> R
302where
303    F: 'static + Sync + Fn(usize) -> Fut,
304    Fut: 'static + Future<Output = R>,
305    R: fuchsia_async::test_support::TestResult,
306{
307    let result = fuchsia_async::test_support::run_until_stalled_test(true, f);
308    if result.is_ok() {
309        install_lsan_hook();
310    }
311    result
312}
313
314//
315// FUNCTION ARGUMENT ADAPTERS
316//
317
318/// Take a main function `f` that takes an argument and return a function that takes none but calls
319/// `f` with the arguments parsed via argh.
320#[doc(hidden)]
321pub fn adapt_to_parse_arguments<A, R>(f: impl FnOnce(A) -> R) -> impl FnOnce() -> R
322where
323    A: argh::TopLevelCommand,
324{
325    move || f(argh::from_env())
326}
327
328/// Take a test function `f` that takes no parameters and return a function that takes the run
329/// number as required by our test runners.
330#[doc(hidden)]
331pub fn adapt_to_take_test_run_number<R>(f: impl Fn() -> R) -> impl Fn(usize) -> R {
332    move |_| f()
333}
334
335//
336// LEAK SANITIZER SUPPORT
337//
338
339// Note that the variant is named variant_asan (for AddressSanitizer), but the specific sanitizer we
340// are targeting is lsan (LeakSanitizer), which is enabled as part of the asan variant.
341
342#[doc(hidden)]
343#[cfg(not(feature = "variant_asan"))]
344pub fn disable_lsan_for_should_panic() {}
345
346#[doc(hidden)]
347#[cfg(feature = "variant_asan")]
348pub fn disable_lsan_for_should_panic() {
349    extern "C" {
350        fn __lsan_disable();
351    }
352    unsafe {
353        __lsan_disable();
354    }
355}
356
357#[cfg(not(feature = "variant_asan"))]
358fn install_lsan_hook() {}
359
360#[cfg(feature = "variant_asan")]
361fn install_lsan_hook() {
362    extern "C" {
363        fn __lsan_do_leak_check();
364    }
365    // Wrap the call because atexit requires a safe function pointer.
366    extern "C" fn lsan_do_leak_check() {
367        unsafe { __lsan_do_leak_check() }
368    }
369    // Wait until atexit hooks are called, in case there is more cleanup left to do.
370    let err = unsafe { libc::atexit(lsan_do_leak_check) };
371    if err != 0 {
372        panic!("Failed to install atexit hook for LeakSanitizer: atexit returned {err}");
373    }
374}