reth_cli_util/
sigsegv_handler.rs

1//! Signal handler to extract a backtrace from stack overflow.
2//!
3//! Implementation modified from [`rustc`](https://github.com/rust-lang/rust/blob/3dee9775a8c94e701a08f7b2df2c444f353d8699/compiler/rustc_driver_impl/src/signal_handler.rs).
4
5use std::{
6    alloc::{alloc, Layout},
7    fmt, mem, ptr,
8};
9
10extern "C" {
11    fn backtrace_symbols_fd(buffer: *const *mut libc::c_void, size: libc::c_int, fd: libc::c_int);
12}
13
14fn backtrace_stderr(buffer: &[*mut libc::c_void]) {
15    let size = buffer.len().try_into().unwrap_or_default();
16    unsafe { backtrace_symbols_fd(buffer.as_ptr(), size, libc::STDERR_FILENO) };
17}
18
19/// Unbuffered, unsynchronized writer to stderr.
20///
21/// Only acceptable because everything will end soon anyways.
22struct RawStderr(());
23
24impl fmt::Write for RawStderr {
25    fn write_str(&mut self, s: &str) -> Result<(), fmt::Error> {
26        let ret = unsafe { libc::write(libc::STDERR_FILENO, s.as_ptr().cast(), s.len()) };
27        if ret == -1 {
28            Err(fmt::Error)
29        } else {
30            Ok(())
31        }
32    }
33}
34
35/// We don't really care how many bytes we actually get out. SIGSEGV comes for our head.
36/// Splash stderr with letters of our own blood to warn our friends about the monster.
37macro_rules! raw_errln {
38    ($tokens:tt) => {
39        let _ = ::core::fmt::Write::write_fmt(&mut RawStderr(()), format_args!($tokens));
40        let _ = ::core::fmt::Write::write_char(&mut RawStderr(()), '\n');
41    };
42}
43
44/// Signal handler installed for SIGSEGV
45extern "C" fn print_stack_trace(_: libc::c_int) {
46    const MAX_FRAMES: usize = 256;
47    let mut stack_trace: [*mut libc::c_void; MAX_FRAMES] = [ptr::null_mut(); MAX_FRAMES];
48    let stack = unsafe {
49        // Collect return addresses
50        let depth = libc::backtrace(stack_trace.as_mut_ptr(), MAX_FRAMES as i32);
51        if depth == 0 {
52            return
53        }
54        &stack_trace[0..depth as usize]
55    };
56
57    // Just a stack trace is cryptic. Explain what we're doing.
58    raw_errln!("error: reth interrupted by SIGSEGV, printing backtrace\n");
59    let mut written = 1;
60    let mut consumed = 0;
61    // Begin elaborating return addrs into symbols and writing them directly to stderr
62    // Most backtraces are stack overflow, most stack overflows are from recursion
63    // Check for cycles before writing 250 lines of the same ~5 symbols
64    let cycled = |(runner, walker)| runner == walker;
65    let mut cyclic = false;
66    if let Some(period) = stack.iter().skip(1).step_by(2).zip(stack).position(cycled) {
67        let period = period.saturating_add(1); // avoid "what if wrapped?" branches
68        let Some(offset) = stack.iter().skip(period).zip(stack).position(cycled) else {
69            // impossible.
70            return
71        };
72
73        // Count matching trace slices, else we could miscount "biphasic cycles"
74        // with the same period + loop entry but a different inner loop
75        let next_cycle = stack[offset..].chunks_exact(period).skip(1);
76        let cycles = 1 + next_cycle
77            .zip(stack[offset..].chunks_exact(period))
78            .filter(|(next, prev)| next == prev)
79            .count();
80        backtrace_stderr(&stack[..offset]);
81        written += offset;
82        consumed += offset;
83        if cycles > 1 {
84            raw_errln!("\n### cycle encountered after {offset} frames with period {period}");
85            backtrace_stderr(&stack[consumed..consumed + period]);
86            raw_errln!("### recursed {cycles} times\n");
87            written += period + 4;
88            consumed += period * cycles;
89            cyclic = true;
90        };
91    }
92    let rem = &stack[consumed..];
93    backtrace_stderr(rem);
94    raw_errln!("");
95    written += rem.len() + 1;
96
97    let random_depth = || 8 * 16; // chosen by random diceroll (2d20)
98    if cyclic || stack.len() > random_depth() {
99        // technically speculation, but assert it with confidence anyway.
100        // We only arrived in this signal handler because bad things happened
101        // and this message is for explaining it's not the programmer's fault
102        raw_errln!("note: reth unexpectedly overflowed its stack! this is a bug");
103        written += 1;
104    }
105    if stack.len() == MAX_FRAMES {
106        raw_errln!("note: maximum backtrace depth reached, frames may have been lost");
107        written += 1;
108    }
109    raw_errln!("note: we would appreciate a report at https://github.com/paradigmxyz/reth");
110    written += 1;
111    if written > 24 {
112        // We probably just scrolled the earlier "we got SIGSEGV" message off the terminal
113        raw_errln!("note: backtrace dumped due to SIGSEGV! resuming signal");
114    }
115}
116
117/// Installs a SIGSEGV handler.
118///
119/// When SIGSEGV is delivered to the process, print a stack trace and then exit.
120pub fn install() {
121    unsafe {
122        let alt_stack_size: usize = min_sigstack_size() + 64 * 1024;
123        let mut alt_stack: libc::stack_t = mem::zeroed();
124        alt_stack.ss_sp = alloc(Layout::from_size_align(alt_stack_size, 1).unwrap()).cast();
125        alt_stack.ss_size = alt_stack_size;
126        libc::sigaltstack(&alt_stack, ptr::null_mut());
127
128        let mut sa: libc::sigaction = mem::zeroed();
129        sa.sa_sigaction = print_stack_trace as libc::sighandler_t;
130        sa.sa_flags = libc::SA_NODEFER | libc::SA_RESETHAND | libc::SA_ONSTACK;
131        libc::sigemptyset(&mut sa.sa_mask);
132        libc::sigaction(libc::SIGSEGV, &sa, ptr::null_mut());
133    }
134}
135
136/// Modern kernels on modern hardware can have dynamic signal stack sizes.
137#[cfg(any(target_os = "linux", target_os = "android"))]
138fn min_sigstack_size() -> usize {
139    const AT_MINSIGSTKSZ: core::ffi::c_ulong = 51;
140    let dynamic_sigstksz = unsafe { libc::getauxval(AT_MINSIGSTKSZ) };
141    // If getauxval couldn't find the entry, it returns 0,
142    // so take the higher of the "constant" and auxval.
143    // This transparently supports older kernels which don't provide AT_MINSIGSTKSZ
144    libc::MINSIGSTKSZ.max(dynamic_sigstksz as _)
145}
146
147/// Not all OS support hardware where this is needed.
148#[cfg(not(any(target_os = "linux", target_os = "android")))]
149const fn min_sigstack_size() -> usize {
150    libc::MINSIGSTKSZ
151}