1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
use crate::{
    tls::Context,
    unwind::{Captured, Location},
};
use lazy_static::lazy_static;
use std::{
    panic::{self, PanicInfo},
    sync::RwLock,
    thread,
};

#[cfg(feature = "nightly")]
use std::backtrace::Backtrace;

type PanicHook = dyn Fn(&PanicInfo) + Send + Sync + 'static;

lazy_static! {
    static ref PREV_HOOK: RwLock<Option<Box<PanicHook>>> = RwLock::new(None);
}

/// Registers the custom panic hook so that the panic information can be captured.
///
/// This function saves the current panic hook and replaces with a custom hook that
/// captures the panic information caused by closures enclosed in [`maybe_unwind`].
/// After capturing the panic information, the original panic hook is *always* called
/// regardless of where the panic occurred.
///
/// Note that the panic hook is managed globally and replacing the hook reflects
/// all threads in the application.
///
/// [`maybe_unwind`]: ./fn.maybe_unwind.html
///
/// # Panics
///
/// This function panics if it is called from a panicking thread or the global state is poisoned.
///
/// # Data racing
///
/// This function may cause a data race if the panic hook is set from the different thread
/// at the same time. The application **must** ensure that the all dependencies that may
/// use the custom panic hook set their hooks before calling `set_hook`, and the panic hook
/// is not changed afterwards.
///
/// # Example
///
/// ```
/// # #![allow(deprecated)]
/// use maybe_unwind::{maybe_unwind, set_hook};
///
/// set_hook();
///
/// let res = maybe_unwind(|| { panic!("oops"); });
/// assert!(res.is_err());
/// ```
#[deprecated(
    since = "0.2.1",
    note = "this function will be removed in the future version. use `capture_panic_info` in the custom panic hook instead."
)]
#[inline]
pub fn set_hook() {
    if thread::panicking() {
        panic!("cannot modify the panic hook from a panicking thread");
    }

    let mut prev_hook = PREV_HOOK.write().unwrap();
    prev_hook.get_or_insert_with(|| {
        let prev_hook = panic::take_hook();
        panic::set_hook(Box::new(|info| {
            capture_panic_info(info);

            let prev_hook = PREV_HOOK.read().ok();
            let prev_hook = prev_hook.as_ref().and_then(|prev_hook| prev_hook.as_ref());
            if let Some(prev_hook) = prev_hook {
                (prev_hook)(info);
            } else {
                eprintln!("warning: the original panic hook is not available (this is a bug).");
            }
        }));
        prev_hook
    });
}

/// Unregisters the custom panic hook and reset the previous hook.
#[deprecated(
    since = "0.2.1",
    note = "this function will be removed in the future version."
)]
#[inline]
pub fn reset_hook() {
    if thread::panicking() {
        panic!("cannot modify the panic hook from a panicking thread");
    }

    if let Ok(mut prev_hook) = PREV_HOOK.write() {
        if let Some(prev_hook) = prev_hook.take() {
            panic::set_hook(prev_hook);
        }
    }
}

/// Capture the panic information.
///
/// The captured values are stored in the thread local context
/// for passing to the caller of `maybe_unwind`. After capturing
/// the panic information, this function returns `true`.
///
/// If the panic location is outside of the closure passed to
/// `maybe_unwind`, this function does nothing and just return
/// `false`.
///
/// # Example
///
/// ```
/// use maybe_unwind::{maybe_unwind, capture_panic_info};
/// use std::panic::{self, PanicInfo};
///
/// fn my_hook(info: &PanicInfo) {
///     let captured = capture_panic_info(info);
///
///     if !captured {
///         println!("{}", info);
///     }
/// }
/// panic::set_hook(Box::new(my_hook));
///
/// let res = maybe_unwind(|| { panic!("oops"); });
/// assert!(res.is_err());
/// ```
pub fn capture_panic_info(info: &PanicInfo) -> bool {
    if !Context::is_set() {
        return false;
    }

    #[cfg(feature = "nightly")]
    let backtrace = Backtrace::capture();

    let _ = Context::try_with(|ctx| {
        ctx.captured.replace(Captured {
            location: info.location().map(|loc| Location::from_std(loc)),
            #[cfg(feature = "nightly")]
            backtrace,
        });
    });

    true
}