|
| 1 | +// |
| 2 | +// traps.rs |
| 3 | +// |
| 4 | +// Copyright (C) 2023 Posit Software, PBC. All rights reserved. |
| 5 | +// |
| 6 | +// |
| 7 | + |
| 8 | +// Call this after initialising the `log` package. Instruments SIGBUS, |
| 9 | +// SIGSEGV, and SIGILL to generate a backtrace with `info` verbosity |
| 10 | +// (lowest level so it's always reported). |
| 11 | +// |
| 12 | +// This uses `signal()` instead of `sigaction()` for Windows support |
| 13 | +// (SIGSEGV is one of the rare supported signals) |
| 14 | +// |
| 15 | +// Note that Rust also has a SIGSEGV handler to catch stack overflows. In |
| 16 | +// this case it displays an informative message and aborts the program (no |
| 17 | +// segfaults in Rust!). Ideally we'd save the Rust handler and notify |
| 18 | +// it. However the only safe way to notify an old handler on Unixes is to |
| 19 | +// use `sigaction()` so that we get the information needed to determine the |
| 20 | +// type of handler (old or new school). So we'd need to make a different |
| 21 | +// implementation for Windows (which only supports old style) and for Unix, |
| 22 | +// and this doesn't seem worth it. |
| 23 | +pub fn register_trap_handlers() { |
| 24 | + unsafe { |
| 25 | + libc::signal(libc::SIGBUS, backtrace_handler as libc::sighandler_t); |
| 26 | + libc::signal(libc::SIGSEGV, backtrace_handler as libc::sighandler_t); |
| 27 | + libc::signal(libc::SIGILL, backtrace_handler as libc::sighandler_t); |
| 28 | + } |
| 29 | +} |
| 30 | + |
| 31 | +extern "C" fn backtrace_handler(signum: libc::c_int) { |
| 32 | + // Prevent infloop into the handler |
| 33 | + unsafe { |
| 34 | + libc::signal(signum, libc::SIG_DFL); |
| 35 | + } |
| 36 | + |
| 37 | + let mut header = format!("\n>>> Backtrace for signal {}", signum); |
| 38 | + |
| 39 | + if let Some(name) = std::thread::current().name() { |
| 40 | + header = format!("{}\n>>> In thread {}", header, name); |
| 41 | + } |
| 42 | + |
| 43 | + // Unlike asynchronous signals, SIGSEGV and SIGBUS are synchronous and |
| 44 | + // always delivered to the thread that caused it, so we can just |
| 45 | + // capture the current thread's backtrace |
| 46 | + let bt = backtrace::Backtrace::new(); |
| 47 | + log::info!("{}\n{:?}", header, bt); |
| 48 | +} |
0 commit comments