panic_rtt_target/
lib.rs

1//! Logs panic messages over RTT. A companion crate for rtt-target.
2//!
3//! RTT must have been initialized by using one of the `rtt_init` macros. Otherwise you will get a
4//! linker error at compile time.
5//!
6//! Panics are always logged to the print and defmt channels, if they are configured. Upon panicking
7//! the channel mode is also automatically set to `BlockIfFull`, so that the full message will
8//! always be logged.
9//! If the code somehow manages to panic at runtime before RTT is initialized (quite unlikely),
10//! or if the print channel doesn't exist, nothing is logged.
11//!
12//! The panic handler runs in a non-returning [critical_section](https://docs.rs/critical-section)
13//! which implementation should be provided by the user.
14//!
15//! # Usage
16//!
17//! Cargo.toml:
18//!
19//! ```toml
20//! [dependencies]
21//! rtt-target = "x.y.z"
22//! panic-rtt-target = "x.y.z"
23//! ```
24//!
25//! main.rs:
26//!
27//! ```no_run
28//! #![no_std]
29//!
30//! use panic_rtt_target as _;
31//! use rtt_target::rtt_init_default;
32//!
33//! fn main() -> ! {
34//!     // you can use `rtt_init_print`, `rtt_init_defmt` or you can call `set_print_channel` after initialization.
35//!     rtt_init_default!();
36//!
37//!     panic!("Something has gone terribly wrong");
38//! }
39//! ```
40
41#![no_std]
42
43use core::{fmt::Write, panic::PanicInfo};
44use portable_atomic::{compiler_fence, Ordering};
45
46use rtt_target::{with_terminal_channel, ChannelMode};
47
48#[inline(never)]
49#[panic_handler]
50fn panic(info: &PanicInfo) -> ! {
51    critical_section::with(|_| {
52        #[cfg(feature = "defmt")]
53        defmt::error!("{}", defmt::Display2Format(info));
54
55        with_terminal_channel(|term| {
56            term.set_mode(ChannelMode::BlockIfFull);
57            let mut channel = term.write(0);
58
59            writeln!(channel, "{}", info).ok();
60        });
61
62        // we should never leave critical section
63        loop {
64            compiler_fence(Ordering::SeqCst);
65        }
66    })
67}