Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Stack overflow is unsound (stack probes missing) #634

Open
narpfel opened this issue Feb 19, 2025 · 0 comments
Open

Stack overflow is unsound (stack probes missing) #634

narpfel opened this issue Feb 19, 2025 · 0 comments

Comments

@narpfel
Copy link

narpfel commented Feb 19, 2025

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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant