Description
When allocating large stack frames (that are larger than one page), the LLVM backend (and also the Cranelift backend) makes sure to touch at least one byte in every page to safely trigger a segfault on stack overflow by accessing the guard page. rustc_codegen_gcc
misses this check, so stack overflows are not always caught and can be used to safely produce UB.
For example, this code can be used to write to (almost) any byte in safe code:
#![feature(maybe_uninit_as_bytes)]
use std::mem::MaybeUninit;
use std::ptr::from_ref;
const N: usize = 0x0000_7ff0_0000_0000;
#[inline(never)]
pub fn g(n: &u8) {
let mut xs = MaybeUninit::<[u8; N]>::uninit();
let base = from_ref(&xs.as_bytes()[0]).addr();
let index = from_ref(n).addr() - base;
xs.as_bytes_mut()[index].write(42);
}
pub fn main() {
let n = Box::new(27);
g(&n);
std::process::exit(*n as i32);
}
When compiled with -C opt-level=3
, this program will exit with 42
.
Adding -C llvm-args=-fstack-check
inserts the correct stack probe loop. GCC docs: https://gcc.gnu.org/onlinedocs/gccint/Stack-Checking.html Unfortunately, this also generates code for stack frames that are smaller than the guard page (such as main
).
Godbolt link: https://godbolt.org/z/E5arqfP3M
rustc_codegen_gcc
version (from Compiler Explorer, also reproduces locally):
rustc 1.86.0-nightly (eb54a5083 2025-01-11)
binary: rustc
commit-hash: eb54a50837ad4bcc9842924f27e7287ca66e294c
commit-date: 2025-01-11
host: x86_64-unknown-linux-gnu
release: 1.86.0-nightly