rustc_driver_impl/
signal_handler.rs

1//! Signal handler for rustc
2//! Primarily used to extract a backtrace from stack overflow
3
4use std::alloc::{Layout, alloc};
5use std::{fmt, mem, ptr, slice};
6
7use rustc_interface::util::{DEFAULT_STACK_SIZE, STACK_SIZE};
8
9unsafe extern "C" {
10    fn backtrace_symbols_fd(buffer: *const *mut libc::c_void, size: libc::c_int, fd: libc::c_int);
11}
12
13fn backtrace_stderr(buffer: &[*mut libc::c_void]) {
14    let size = buffer.len().try_into().unwrap_or_default();
15    unsafe { backtrace_symbols_fd(buffer.as_ptr(), size, libc::STDERR_FILENO) };
16}
17
18/// Unbuffered, unsynchronized writer to stderr.
19///
20/// Only acceptable because everything will end soon anyways.
21struct RawStderr(());
22
23impl fmt::Write for RawStderr {
24    fn write_str(&mut self, s: &str) -> Result<(), fmt::Error> {
25        let ret = unsafe { libc::write(libc::STDERR_FILENO, s.as_ptr().cast(), s.len()) };
26        if ret == -1 { Err(fmt::Error) } else { Ok(()) }
27    }
28}
29
30/// We don't really care how many bytes we actually get out. SIGSEGV comes for our head.
31/// Splash stderr with letters of our own blood to warn our friends about the monster.
32macro raw_errln($tokens:tt) {
33    let _ = ::core::fmt::Write::write_fmt(&mut RawStderr(()), format_args!($tokens));
34    let _ = ::core::fmt::Write::write_char(&mut RawStderr(()), '\n');
35}
36
37/// Signal handler installed for SIGSEGV
38///
39/// # Safety
40///
41/// Caller must ensure that this function is not re-entered.
42unsafe extern "C" fn print_stack_trace(_: libc::c_int) {
43    const MAX_FRAMES: usize = 256;
44    let stack = unsafe {
45        // Reserve data segment so we don't have to malloc in a signal handler, which might fail
46        // in incredibly undesirable and unexpected ways due to e.g. the allocator deadlocking
47        static mut STACK_TRACE: [*mut libc::c_void; MAX_FRAMES] = [ptr::null_mut(); MAX_FRAMES];
48        // Collect return addresses
49        let depth = libc::backtrace(&raw mut STACK_TRACE as _, MAX_FRAMES as i32);
50        if depth == 0 {
51            return;
52        }
53        slice::from_raw_parts(&raw const STACK_TRACE as _, depth as _)
54    };
55
56    // Just a stack trace is cryptic. Explain what we're doing.
57    raw_errln!("error: rustc interrupted by SIGSEGV, printing backtrace\n");
58    let mut written = 1;
59    let mut consumed = 0;
60    // Begin elaborating return addrs into symbols and writing them directly to stderr
61    // Most backtraces are stack overflow, most stack overflows are from recursion
62    // Check for cycles before writing 250 lines of the same ~5 symbols
63    let cycled = |(runner, walker)| runner == walker;
64    let mut cyclic = false;
65    if let Some(period) = stack.iter().skip(1).step_by(2).zip(stack).position(cycled) {
66        let period = period.saturating_add(1); // avoid "what if wrapped?" branches
67        let Some(offset) = stack.iter().skip(period).zip(stack).position(cycled) else {
68            // impossible.
69            return;
70        };
71
72        // Count matching trace slices, else we could miscount "biphasic cycles"
73        // with the same period + loop entry but a different inner loop
74        let next_cycle = stack[offset..].chunks_exact(period).skip(1);
75        let cycles = 1 + next_cycle
76            .zip(stack[offset..].chunks_exact(period))
77            .filter(|(next, prev)| next == prev)
78            .count();
79        backtrace_stderr(&stack[..offset]);
80        written += offset;
81        consumed += offset;
82        if cycles > 1 {
83            raw_errln!("\n### cycle encountered after {offset} frames with period {period}");
84            backtrace_stderr(&stack[consumed..consumed + period]);
85            raw_errln!("### recursed {cycles} times\n");
86            written += period + 4;
87            consumed += period * cycles;
88            cyclic = true;
89        };
90    }
91    let rem = &stack[consumed..];
92    backtrace_stderr(rem);
93    raw_errln!("");
94    written += rem.len() + 1;
95
96    let random_depth = || 8 * 16; // chosen by random diceroll (2d20)
97    if cyclic || stack.len() > random_depth() {
98        // technically speculation, but assert it with confidence anyway.
99        // rustc only arrived in this signal handler because bad things happened
100        // and this message is for explaining it's not the programmer's fault
101        raw_errln!("note: rustc unexpectedly overflowed its stack! this is a bug");
102        written += 1;
103    }
104    if stack.len() == MAX_FRAMES {
105        raw_errln!("note: maximum backtrace depth reached, frames may have been lost");
106        written += 1;
107    }
108    raw_errln!("note: we would appreciate a report at https://github.com/rust-lang/rust");
109    // get the current stack size WITHOUT blocking and double it
110    let new_size = STACK_SIZE.get().copied().unwrap_or(DEFAULT_STACK_SIZE) * 2;
111    raw_errln!("help: you can increase rustc's stack size by setting RUST_MIN_STACK={new_size}");
112    written += 2;
113    if written > 24 {
114        // We probably just scrolled the earlier "we got SIGSEGV" message off the terminal
115        raw_errln!("note: backtrace dumped due to SIGSEGV! resuming signal");
116    };
117}
118
119/// When SIGSEGV is delivered to the process, print a stack trace and then exit.
120pub(super) 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")))]
149fn min_sigstack_size() -> usize {
150    libc::MINSIGSTKSZ
151}