Skip to main content

sel4_panicking/
lib.rs

1//
2// Copyright 2023, Colias Group, LLC
3//
4// SPDX-License-Identifier: BSD-2-Clause
5//
6
7#![no_std]
8#![feature(cfg_target_thread_local)]
9#![feature(panic_can_unwind)]
10#![cfg_attr(target_thread_local, feature(thread_local))]
11
12#[cfg(feature = "alloc")]
13extern crate alloc;
14
15use core::panic::{PanicInfo, UnwindSafe};
16
17use sel4_panicking_env::{abort, debug_println};
18
19mod count;
20mod hook;
21mod strategy;
22
23use count::{count_panic, count_panic_caught};
24use hook::get_hook;
25
26pub use hook::{PanicHook, set_hook};
27
28#[cfg_attr(feature = "panic-handler", panic_handler)]
29#[cfg_attr(not(feature = "panic-handler"), allow(dead_code))]
30fn panic(info: &PanicInfo) -> ! {
31    if let Some(must_abort) = count_panic() {
32        debug_println!("{}", info);
33        abort!("{}", must_abort);
34    }
35    (get_hook())(info);
36    if info.can_unwind() {
37        let code = strategy::begin_panic();
38        abort!("failed to initiate panic, error {}", code)
39    } else {
40        abort!("can't unwind this panic")
41    }
42}
43
44/// Like `std::panic::catch_unwind`.
45#[allow(clippy::result_unit_err)]
46pub fn catch_unwind<R, F: FnOnce() -> R + UnwindSafe>(f: F) -> Result<R, ()> {
47    strategy::catch_unwind(f).inspect_err(|_| count_panic_caught())
48}
49
50/// Like the unstable `core::panic::abort_unwind`
51pub fn abort_unwind<F, R>(f: F) -> R
52where
53    F: FnOnce() -> R,
54{
55    extern "C" fn wrap<F, R>(f: F) -> R
56    where
57        F: FnOnce() -> R,
58    {
59        f()
60    }
61
62    wrap(f)
63}