reth_cli_util/
sigsegv_handler.rs
1use 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
19struct 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
35macro_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
44extern "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 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 raw_errln!("error: reth interrupted by SIGSEGV, printing backtrace\n");
59 let mut written = 1;
60 let mut consumed = 0;
61 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); let Some(offset) = stack.iter().skip(period).zip(stack).position(cycled) else {
69 return
71 };
72
73 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; if cyclic || stack.len() > random_depth() {
99 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 raw_errln!("note: backtrace dumped due to SIGSEGV! resuming signal");
114 }
115}
116
117pub 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#[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 libc::MINSIGSTKSZ.max(dynamic_sigstksz as _)
145}
146
147#[cfg(not(any(target_os = "linux", target_os = "android")))]
149const fn min_sigstack_size() -> usize {
150 libc::MINSIGSTKSZ
151}