solar_cli/
signal_handler.rs1use std::{
6 alloc::{Layout, alloc},
7 fmt, mem, ptr, slice,
8};
9
10#[rustfmt::skip]
12const KILL_SIGNALS: [(libc::c_int, &str); 3] = [
13 (libc::SIGILL, "SIGILL"),
14 (libc::SIGBUS, "SIGBUS"),
15 (libc::SIGSEGV, "SIGSEGV")
16];
17
18unsafe extern "C" {
19 fn backtrace_symbols_fd(buffer: *const *mut libc::c_void, size: libc::c_int, fd: libc::c_int);
20}
21
22fn backtrace_stderr(buffer: &[*mut libc::c_void]) {
23 let size = buffer.len().try_into().unwrap_or_default();
24 unsafe { backtrace_symbols_fd(buffer.as_ptr(), size, libc::STDERR_FILENO) };
25}
26
27struct RawStderr(());
31
32impl fmt::Write for RawStderr {
33 fn write_str(&mut self, s: &str) -> Result<(), fmt::Error> {
34 let ret = unsafe { libc::write(libc::STDERR_FILENO, s.as_ptr().cast(), s.len()) };
35 if ret == -1 { Err(fmt::Error) } else { Ok(()) }
36 }
37}
38
39macro_rules! raw_errln {
42 ($($tokens:tt)*) => {
43 let _ = ::core::fmt::Write::write_fmt(&mut RawStderr(()), format_args!($($tokens)*));
44 let _ = ::core::fmt::Write::write_char(&mut RawStderr(()), '\n');
45 };
46}
47
48unsafe extern "C" fn print_stack_trace(signum: libc::c_int) {
54 const MAX_FRAMES: usize = 256;
55
56 let signame = KILL_SIGNALS
57 .into_iter()
58 .find(|(num, _)| *num == signum)
59 .map(|(_, name)| name)
60 .unwrap_or("<unknown>");
61
62 let stack = unsafe {
63 static mut STACK_TRACE: [*mut libc::c_void; MAX_FRAMES] = [ptr::null_mut(); MAX_FRAMES];
66 let depth = libc::backtrace(&raw mut STACK_TRACE as _, MAX_FRAMES as i32);
68 if depth == 0 {
69 return;
70 }
71 slice::from_raw_parts(&raw const STACK_TRACE as _, depth as _)
72 };
73
74 raw_errln!("error: solar interrupted by {signame}, printing backtrace\n");
76
77 let mut written = 1;
78 let mut consumed = 0;
79 let cycled = |(runner, walker)| runner == walker;
83 let mut cyclic = false;
84 if let Some(period) = stack.iter().skip(1).step_by(2).zip(stack).position(cycled) {
85 let period = period.saturating_add(1); let Some(offset) = stack.iter().skip(period).zip(stack).position(cycled) else {
87 return;
89 };
90
91 let next_cycle = stack[offset..].chunks_exact(period).skip(1);
94 let cycles = 1 + next_cycle
95 .zip(stack[offset..].chunks_exact(period))
96 .filter(|(next, prev)| next == prev)
97 .count();
98 backtrace_stderr(&stack[..offset]);
99 written += offset;
100 consumed += offset;
101 if cycles > 1 {
102 raw_errln!("\n### cycle encountered after {offset} frames with period {period}");
103 backtrace_stderr(&stack[consumed..consumed + period]);
104 raw_errln!("### recursed {cycles} times\n");
105 written += period + 4;
106 consumed += period * cycles;
107 cyclic = true;
108 };
109 }
110 let rem = &stack[consumed..];
111 backtrace_stderr(rem);
112 raw_errln!("");
113 written += rem.len() + 1;
114
115 let random_depth = || 8 * 16; if (cyclic || stack.len() > random_depth()) && signum == libc::SIGSEGV {
117 raw_errln!("note: solar unexpectedly overflowed its stack! this is a bug");
121 written += 1;
122 }
123 if stack.len() == MAX_FRAMES {
124 raw_errln!("note: maximum backtrace depth reached, frames may have been lost");
125 written += 1;
126 }
127 raw_errln!("note: we would appreciate a report at https://github.com/paradigmxyz/solar");
128 written += 1;
129 if written > 24 {
130 raw_errln!("note: backtrace dumped due to {signame}! resuming signal");
132 }
133}
134
135pub fn install() {
139 unsafe {
140 let alt_stack_size: usize = min_sigstack_size() + 64 * 1024;
141 let mut alt_stack: libc::stack_t = mem::zeroed();
142 alt_stack.ss_sp = alloc(Layout::from_size_align(alt_stack_size, 1).unwrap()).cast();
143 alt_stack.ss_size = alt_stack_size;
144 libc::sigaltstack(&alt_stack, ptr::null_mut());
145
146 let mut sa: libc::sigaction = mem::zeroed();
147 sa.sa_sigaction = print_stack_trace as libc::sighandler_t;
148 sa.sa_flags = libc::SA_NODEFER | libc::SA_RESETHAND | libc::SA_ONSTACK;
149 libc::sigemptyset(&mut sa.sa_mask);
150 for (signum, _signame) in KILL_SIGNALS {
151 libc::sigaction(signum, &sa, ptr::null_mut());
152 }
153 }
154}
155
156#[cfg(any(target_os = "linux", target_os = "android"))]
158fn min_sigstack_size() -> usize {
159 const AT_MINSIGSTKSZ: core::ffi::c_ulong = 51;
160 let dynamic_sigstksz = unsafe { libc::getauxval(AT_MINSIGSTKSZ) };
161 libc::MINSIGSTKSZ.max(dynamic_sigstksz as _)
165}
166
167#[cfg(not(any(target_os = "linux", target_os = "android")))]
169fn min_sigstack_size() -> usize {
170 libc::MINSIGSTKSZ
171}