1//! Signal handler for rustc
2//! Primarily used to extract a backtrace from stack overflow
34use std::alloc::{Layout, alloc};
5use std::{fmt, mem, ptr, slice};
67use rustc_interface::util::{DEFAULT_STACK_SIZE, STACK_SIZE};
89/// Signals that represent that we have a bug, and our prompt termination has
10/// been ordered.
11#[rustfmt::skip]
12const KILL_SIGNALS: [(libc::c_int, &str); 3] = [
13 (libc::SIGILL, "SIGILL"),
14 (libc::SIGBUS, "SIGBUS"),
15 (libc::SIGSEGV, "SIGSEGV")
16];
1718unsafe extern "C" {
19fn backtrace_symbols_fd(buffer: *const *mut libc::c_void, size: libc::c_int, fd: libc::c_int);
20}
2122fn backtrace_stderr(buffer: &[*mut libc::c_void]) {
23let size = buffer.len().try_into().unwrap_or_default();
24unsafe { backtrace_symbols_fd(buffer.as_ptr(), size, libc::STDERR_FILENO) };
25}
2627/// Unbuffered, unsynchronized writer to stderr.
28///
29/// Only acceptable because everything will end soon anyways.
30struct RawStderr(());
3132impl fmt::Writefor RawStderr {
33fn write_str(&mut self, s: &str) -> Result<(), fmt::Error> {
34let ret = unsafe { libc::write(libc::STDERR_FILENO, s.as_ptr().cast(), s.len()) };
35if ret == -1 { Err(fmt::Error) } else { Ok(()) }
36 }
37}
3839/// We don't really care how many bytes we actually get out. SIGSEGV comes for our head.
40/// Splash stderr with letters of our own blood to warn our friends about the monster.
41macro raw_errln($tokens:tt) {
42let _ = ::core::fmt::Write::write_fmt(&mut RawStderr(()), format_args!($tokens));
43let _ = ::core::fmt::Write::write_char(&mut RawStderr(()), '\n');
44}
4546/// Signal handler installed for SIGSEGV
47///
48/// # Safety
49///
50/// Caller must ensure that this function is not re-entered.
51unsafe extern "C" fn print_stack_trace(signum: libc::c_int) {
52const MAX_FRAMES: usize = 256;
5354let signame = {
55let mut signame = "<unknown>";
56for sig in KILL_SIGNALS {
57if sig.0 == signum {
58 signame = sig.1;
59 }
60 }
61signame62 };
6364let stack = unsafe {
65// Reserve data segment so we don't have to malloc in a signal handler, which might fail
66 // in incredibly undesirable and unexpected ways due to e.g. the allocator deadlocking
67static mut STACK_TRACE: [*mut libc::c_void; MAX_FRAMES] = [ptr::null_mut(); MAX_FRAMES];
68// Collect return addresses
69let depth = libc::backtrace(&raw mut STACK_TRACEas _, MAX_FRAMESas i32);
70if depth == 0 {
71return;
72 }
73 slice::from_raw_parts(&raw const STACK_TRACEas _, depthas _)
74 };
7576// Just a stack trace is cryptic. Explain what we're doing.
77let _ =
::core::fmt::Write::write_fmt(&mut RawStderr(()),
format_args!("error: rustc interrupted by {0}, printing backtrace\n",
signame));
let _ = ::core::fmt::Write::write_char(&mut RawStderr(()), '\n');raw_errln!("error: rustc interrupted by {signame}, printing backtrace\n");
7879let mut written = 1;
80let mut consumed = 0;
81// Begin elaborating return addrs into symbols and writing them directly to stderr
82 // Most backtraces are stack overflow, most stack overflows are from recursion
83 // Check for cycles before writing 250 lines of the same ~5 symbols
84let cycled = |(runner, walker)| runner == walker;
85let mut cyclic = false;
86if let Some(period) = stack.iter().skip(1).step_by(2).zip(stack).position(cycled) {
87let period = period.saturating_add(1); // avoid "what if wrapped?" branches
88let Some(offset) = stack.iter().skip(period).zip(stack).position(cycled) else {
89// impossible.
90return;
91 };
9293// Count matching trace slices, else we could miscount "biphasic cycles"
94 // with the same period + loop entry but a different inner loop
95let next_cycle = stack[offset..].chunks_exact(period).skip(1);
96let cycles = 1 + next_cycle97 .zip(stack[offset..].chunks_exact(period))
98 .filter(|(next, prev)| next == prev)
99 .count();
100backtrace_stderr(&stack[..offset]);
101written += offset;
102consumed += offset;
103if cycles > 1 {
104let _ =
::core::fmt::Write::write_fmt(&mut RawStderr(()),
format_args!("\n### cycle encountered after {0} frames with period {1}",
offset, period));
let _ = ::core::fmt::Write::write_char(&mut RawStderr(()), '\n');raw_errln!("\n### cycle encountered after {offset} frames with period {period}");
105backtrace_stderr(&stack[consumed..consumed + period]);
106let _ =
::core::fmt::Write::write_fmt(&mut RawStderr(()),
format_args!("### recursed {0} times\n", cycles));
let _ = ::core::fmt::Write::write_char(&mut RawStderr(()), '\n');raw_errln!("### recursed {cycles} times\n");
107written += period + 4;
108consumed += period * cycles;
109cyclic = true;
110 };
111 }
112let rem = &stack[consumed..];
113backtrace_stderr(rem);
114let _ = ::core::fmt::Write::write_fmt(&mut RawStderr(()), format_args!(""));
let _ = ::core::fmt::Write::write_char(&mut RawStderr(()), '\n');raw_errln!("");
115written += rem.len() + 1;
116117let random_depth = || 8 * 16; // chosen by random diceroll (2d20)
118if (cyclic || stack.len() > random_depth()) && signum == libc::SIGSEGV {
119// technically speculation, but assert it with confidence anyway.
120 // rustc only arrived in this signal handler because bad things happened
121 // and this message is for explaining it's not the programmer's fault
122let _ =
::core::fmt::Write::write_fmt(&mut RawStderr(()),
format_args!("note: rustc unexpectedly overflowed its stack! this is a bug"));
let _ = ::core::fmt::Write::write_char(&mut RawStderr(()), '\n');raw_errln!("note: rustc unexpectedly overflowed its stack! this is a bug");
123written += 1;
124 }
125if stack.len() == MAX_FRAMES {
126let _ =
::core::fmt::Write::write_fmt(&mut RawStderr(()),
format_args!("note: maximum backtrace depth reached, frames may have been lost"));
let _ = ::core::fmt::Write::write_char(&mut RawStderr(()), '\n');raw_errln!("note: maximum backtrace depth reached, frames may have been lost");
127written += 1;
128 }
129let _ =
::core::fmt::Write::write_fmt(&mut RawStderr(()),
format_args!("note: we would appreciate a report at https://github.com/rust-lang/rust"));
let _ = ::core::fmt::Write::write_char(&mut RawStderr(()), '\n');raw_errln!("note: we would appreciate a report at https://github.com/rust-lang/rust");
130written += 1;
131if signum == libc::SIGSEGV {
132// get the current stack size WITHOUT blocking and double it
133let new_size = STACK_SIZE.get().copied().unwrap_or(DEFAULT_STACK_SIZE) * 2;
134let _ =
::core::fmt::Write::write_fmt(&mut RawStderr(()),
format_args!("help: you can increase rustc\'s stack size by setting RUST_MIN_STACK={0}",
new_size));
let _ = ::core::fmt::Write::write_char(&mut RawStderr(()), '\n');raw_errln!(
135"help: you can increase rustc's stack size by setting RUST_MIN_STACK={new_size}"
136);
137written += 1;
138 }
139if written > 24 {
140// We probably just scrolled the earlier "interrupted by {signame}" message off the terminal
141let _ =
::core::fmt::Write::write_fmt(&mut RawStderr(()),
format_args!("note: backtrace dumped due to {0}! resuming signal",
signame));
let _ = ::core::fmt::Write::write_char(&mut RawStderr(()), '\n');raw_errln!("note: backtrace dumped due to {signame}! resuming signal");
142 };
143}
144145/// When one of the KILL signals is delivered to the process, print a stack trace and then exit.
146pub(super) fn install() {
147unsafe {
148let alt_stack_size: usize = min_sigstack_size() + 64 * 1024;
149let mut alt_stack: libc::stack_t = mem::zeroed();
150alt_stack.ss_sp = alloc(Layout::from_size_align(alt_stack_size, 1).unwrap()).cast();
151alt_stack.ss_size = alt_stack_size;
152 libc::sigaltstack(&alt_stack, ptr::null_mut());
153154let mut sa: libc::sigaction = mem::zeroed();
155sa.sa_sigaction =
156print_stack_traceas unsafe extern "C" fn(libc::c_int) as libc::sighandler_t;
157sa.sa_flags = libc::SA_NODEFER | libc::SA_RESETHAND | libc::SA_ONSTACK;
158 libc::sigemptyset(&mut sa.sa_mask);
159for (signum, _signame) in KILL_SIGNALS {
160 libc::sigaction(signum, &sa, ptr::null_mut());
161 }
162 }
163}
164165/// Modern kernels on modern hardware can have dynamic signal stack sizes.
166#[cfg(any(target_os = "linux", target_os = "android"))]
167fn min_sigstack_size() -> usize {
168const AT_MINSIGSTKSZ: core::ffi::c_ulong = 51;
169let dynamic_sigstksz = unsafe { libc::getauxval(AT_MINSIGSTKSZ) };
170// If getauxval couldn't find the entry, it returns 0,
171 // so take the higher of the "constant" and auxval.
172 // This transparently supports older kernels which don't provide AT_MINSIGSTKSZ
173libc::MINSIGSTKSZ.max(dynamic_sigstkszas _)
174}
175176/// Not all OS support hardware where this is needed.
177#[cfg(not(any(target_os = "linux", target_os = "android")))]
178fn min_sigstack_size() -> usize {
179 libc::MINSIGSTKSZ
180}