stackler 0.1.0

A lightweight, always-on stack telemetry library that requires no instrumentation.
Documentation
//! The initial thread, which is the one stack the kernel grows on demand — and
//! therefore the only one whose reported bounds cannot simply be believed.
//!
//! This test is `harness = false` on purpose: `libtest` runs tests on threads it
//! spawns itself, so nothing under the normal harness ever executes on the
//! initial thread. Everything here runs in `main`.

#[cfg(all(feature = "std", any(target_os = "linux", target_os = "android")))]
mod linux {
    use std::hint::black_box;

    use stackler::Stack;

    /// Uses a known amount of stack in a frame of its own.
    #[inline(never)]
    #[cfg_attr(not(feature = "watermark"), allow(dead_code))]
    pub fn burn(bytes: usize) {
        let mut frame = [0u8; 512 * 1024];
        black_box(&mut frame[..bytes]);
    }

    /// Sets the soft `RLIMIT_STACK`, returning `false` if the system would not
    /// allow it — which is reason to skip a check, not to fail it.
    pub fn set_stack_rlimit(soft: u64) -> bool {
        // SAFETY: reading and then writing a `rlimit` the kernel fills in.
        unsafe {
            let mut limit = std::mem::MaybeUninit::<libc::rlimit>::uninit();
            if libc::getrlimit(libc::RLIMIT_STACK, limit.as_mut_ptr()) != 0 {
                return false;
            }
            let mut limit = limit.assume_init();
            limit.rlim_cur = soft;
            libc::setrlimit(libc::RLIMIT_STACK, &limit) == 0
        }
    }

    pub fn run() {
        assert!(
            Stack::current().is_some(),
            "the initial thread's bounds are discoverable"
        );

        with_a_finite_limit();
        with_an_unlimited_limit();
    }

    /// One page is not a plausible stack and a gigabyte is not a plausible main
    /// thread; anything in between is believable.
    fn assert_plausible(stack: &Stack, what: &str) {
        assert!(
            stack.size() >= 4096 && stack.size() <= 1024 * 1024 * 1024,
            "{what}: {} bytes is not a stack",
            stack.size()
        );
        assert!(stack.contains(stackler::sp()), "{what}: sp is outside it");
    }

    /// The ordinary case: glibc derives the initial thread's low end from
    /// `RLIMIT_STACK`, and the reported size tracks it.
    fn with_a_finite_limit() {
        assert_plausible(&Stack::current().unwrap(), "an ordinary main stack");
        assert!(stackler::attach());

        // The depth of the initial thread is shallow and real.
        let depth = stackler::depth().expect("the main thread is tracked");
        assert!(depth > 0 && depth < 64 * 1024, "{depth}");

        #[cfg(feature = "watermark")]
        {
            // Painting the whole of it writes megabytes below the stack pointer,
            // into pages the kernel has to grow the mapping to cover. If that does
            // not work, this is where it crashes.
            stackler::Stackler::new().paint_depth(usize::MAX).install();

            burn(300 * 1024);
            let peak = stackler::peak().expect("the main thread is painted");
            assert!(peak.bytes() >= 300 * 1024, "{peak:?}");

            let (_, measured) = stackler::measure_peak(|| burn(200 * 1024));
            let measured = measured.expect("the main thread can be repainted");
            assert!(measured.bytes() >= 200 * 1024, "{measured:?}");
            assert!(measured.bytes() < 600 * 1024, "{measured:?}");
        }
    }

    /// The case worth a test: with an unlimited `RLIMIT_STACK` there is no low end
    /// to derive, and glibc reports a span reaching down past the heap and the
    /// executable. Believing it means painting outside the stack — a segmentation
    /// fault — and a headroom guard that never fires.
    fn with_an_unlimited_limit() {
        let finite = Stack::current().unwrap();

        if !set_stack_rlimit(libc::RLIM_INFINITY) {
            eprintln!("skipped: this system will not allow an unlimited stack");
            return;
        }

        let unlimited = Stack::current().expect("bounds are still reported");

        // The base is a real address either way; only the low end was guesswork.
        assert_eq!(unlimited.base(), finite.base());
        assert_plausible(&unlimited, "an unlimited rlimit taken at face value");

        // Which means the guard still answers questions honestly.
        assert!(!stackler::has_headroom(1 << 40));

        // And painting stays inside the stack. Before the cap, this crashed.
        #[cfg(feature = "watermark")]
        {
            stackler::Stackler::new().paint_depth(usize::MAX).install();
            burn(64 * 1024);
            let peak = stackler::peak().expect("still painted");
            assert!(peak.bytes() >= 64 * 1024, "{peak:?}");
        }

        set_stack_rlimit(finite.size() as u64);
    }
}

fn main() {
    #[cfg(all(feature = "std", any(target_os = "linux", target_os = "android")))]
    linux::run();

    println!("main-thread checks passed");
}