panic_write/
lib.rs

1#![no_std]
2
3use core::fmt::Write;
4use core::marker::PhantomPinned;
5use core::mem::{transmute, MaybeUninit};
6use core::ops::DerefMut;
7use core::panic::PanicInfo;
8use core::pin::Pin;
9use core::ptr::null_mut;
10
11static mut PANIC_HANDLER_GETTER: Option<unsafe fn(handler: *mut (), info: &PanicInfo)> = None;
12static mut PANIC_HANDLER: *mut () = null_mut();
13
14/// Use monomorphization to "save" the type parameter of the static pointer
15unsafe fn trampoline<W: Write>(ptr: *mut (), info: &PanicInfo) {
16    let handler: &mut PanicHandler<W> = transmute(ptr);
17
18    let _ = write!(handler.deref_mut(), "{}", info);
19}
20
21pub struct PanicHandler<W: Write> {
22    writer: MaybeUninit<W>,
23    _pin: PhantomPinned,
24}
25
26impl<W: Write> PanicHandler<W> {
27    /// Create a panic handler from a `core::fmt::Write`
28    ///
29    /// Note that the returned handler is detached when it goes out of scope so in most cases it's
30    /// desired to keep the handler in scope for the full duration of the program.
31    ///
32    /// Additionally, the panic handler implements `Deref` for the provided `Write` and can be used
33    /// in place of the original `Write` throughout the app.
34    #[must_use = "the panic handler must be kept in scope"]
35    pub fn new(writer: W) -> Pin<Self> {
36        let handler = unsafe {
37            Pin::new_unchecked(PanicHandler {
38                writer: MaybeUninit::new(writer),
39                _pin: PhantomPinned,
40            })
41        };
42        unsafe {
43            PANIC_HANDLER_GETTER = Some(trampoline::<W>);
44            PANIC_HANDLER = transmute(&handler);
45        }
46        handler
47    }
48
49    /// Detach this panic handler and return the underlying writer
50    pub fn detach(handler: Pin<Self>) -> W {
51        unsafe {
52            PANIC_HANDLER_GETTER = None;
53            PANIC_HANDLER = null_mut();
54
55            // unpin is safe because the pointer to the handler is removed
56            let mut handler = Pin::into_inner_unchecked(handler);
57            let writer = core::mem::replace(&mut handler.writer, MaybeUninit::uninit());
58
59            // safe because self.writer is only uninit during drop
60            writer.assume_init()
61        }
62    }
63}
64
65impl<W: Write> Drop for PanicHandler<W> {
66    fn drop(&mut self) {
67        unsafe {
68            PANIC_HANDLER_GETTER = None;
69            PANIC_HANDLER = null_mut();
70        }
71    }
72}
73
74impl<W: Write> core::ops::Deref for PanicHandler<W> {
75    type Target = W;
76
77    fn deref(&self) -> &Self::Target {
78        // safe because self.writer is only uninit during drop
79        unsafe { &*self.writer.as_ptr() }
80    }
81}
82
83impl<W: Write> core::ops::DerefMut for PanicHandler<W> {
84    fn deref_mut(&mut self) -> &mut Self::Target {
85        // safe because self.writer is only uninit during drop
86        unsafe { &mut *self.writer.as_mut_ptr() }
87    }
88}
89
90#[panic_handler]
91fn panic(info: &PanicInfo) -> ! {
92    unsafe {
93        if let Some(trampoline) = PANIC_HANDLER_GETTER {
94            trampoline(PANIC_HANDLER, info);
95        }
96    }
97    loop {}
98}