stackler 0.1.0

A lightweight, always-on stack telemetry library that requires no instrumentation.
Documentation
//! Platform-specific stack introspection.
//!
//! Everything the crate knows about the machine lives here, and it is only two
//! things: how to read the stack pointer (architecture-specific, a single
//! instruction) and how to ask the OS for the calling thread's stack bounds
//! (OS-specific, and only possible on hosted platforms).

/// Returns the current stack pointer of the calling thread.
///
/// On architectures with a well-known stack pointer register this reads the
/// register directly and is exact. Elsewhere it takes the address of a local in a
/// frame of its own, which sits just below the caller's: the answer is then a few
/// dozen bytes low, meaning depth is very slightly over-reported and headroom very
/// slightly under-reported. That is the safe direction for a guard.
///
/// The function is `#[inline(always)]`, so the value describes the *caller's*
/// frame rather than a frame belonging to `stackler`.
#[inline(always)]
pub fn sp() -> usize {
    sp_impl()
}

#[cfg(target_arch = "x86_64")]
#[inline(always)]
fn sp_impl() -> usize {
    let sp: usize;
    // SAFETY: copying a register into another register touches no memory and
    // has no side effects.
    unsafe {
        core::arch::asm!("mov {}, rsp", out(reg) sp, options(nomem, nostack, preserves_flags));
    }
    sp
}

#[cfg(target_arch = "x86")]
#[inline(always)]
fn sp_impl() -> usize {
    let sp: usize;
    // SAFETY: copying a register into another register touches no memory and
    // has no side effects.
    unsafe {
        core::arch::asm!("mov {}, esp", out(reg) sp, options(nomem, nostack, preserves_flags));
    }
    sp
}

#[cfg(any(target_arch = "aarch64", target_arch = "arm"))]
#[inline(always)]
fn sp_impl() -> usize {
    let sp: usize;
    // SAFETY: copying a register into another register touches no memory and
    // has no side effects.
    unsafe {
        core::arch::asm!("mov {}, sp", out(reg) sp, options(nomem, nostack, preserves_flags));
    }
    sp
}

#[cfg(any(target_arch = "riscv32", target_arch = "riscv64"))]
#[inline(always)]
fn sp_impl() -> usize {
    let sp: usize;
    // SAFETY: copying a register into another register touches no memory and
    // has no side effects.
    unsafe {
        core::arch::asm!("mv {}, sp", out(reg) sp, options(nomem, nostack, preserves_flags));
    }
    sp
}

#[cfg(not(any(
    target_arch = "x86",
    target_arch = "x86_64",
    target_arch = "aarch64",
    target_arch = "arm",
    target_arch = "riscv32",
    target_arch = "riscv64",
)))]
// Deliberately *not* inlined: a local in this function's own frame is guaranteed
// to sit below the caller's stack pointer, which bounds the error by this frame
// rather than by the caller's — and puts it on the conservative side. Inlining
// would place the probe anywhere in the caller's frame instead.
#[inline(never)]
fn sp_impl() -> usize {
    // Taking the address of a local forces it onto the stack.
    let probe = 0usize;
    core::hint::black_box(&probe) as *const usize as usize
}

/// Returns the `(base, limit)` addresses of the calling thread's stack, where
/// `base` is one past its highest byte and `limit` its lowest usable byte, or
/// `None` if the platform cannot report them.
#[cfg(feature = "std")]
pub fn current_bounds() -> Option<(usize, usize)> {
    bounds_impl()
}

#[cfg(all(
    feature = "std",
    any(target_os = "linux", target_os = "android", target_os = "fuchsia")
))]
fn bounds_impl() -> Option<(usize, usize)> {
    let mut attr = core::mem::MaybeUninit::<libc::pthread_attr_t>::uninit();

    // SAFETY: `pthread_getattr_np` initializes `attr` when it succeeds, and the
    // attribute object is destroyed on every path that observes it initialized.
    unsafe {
        if libc::pthread_getattr_np(libc::pthread_self(), attr.as_mut_ptr()) != 0 {
            return None;
        }

        let mut addr: *mut libc::c_void = core::ptr::null_mut();
        let mut size: libc::size_t = 0;
        let rc = libc::pthread_attr_getstack(attr.as_ptr(), &mut addr, &mut size);
        libc::pthread_attr_destroy(attr.as_mut_ptr());

        if rc != 0 || addr.is_null() || size == 0 {
            return None;
        }

        let limit = addr as usize;
        let base = limit.checked_add(size)?;

        Some((base, trustworthy_limit(base, limit)))
    }
}

/// The largest stack this crate takes at face value.
///
/// Bigger than any stack a program asks for on purpose, and small enough that the
/// one case which reports something absurd — see [`trustworthy_limit`] — is always
/// caught.
#[cfg(all(feature = "std", any(target_os = "linux", target_os = "android")))]
const TRUSTED_STACK_MAX: usize = 1024 * 1024 * 1024;

/// What to assume the initial thread's stack size is when the system will not say.
///
/// The conventional default, and what "unlimited" means to almost every program
/// that has never thought about it.
#[cfg(all(feature = "std", any(target_os = "linux", target_os = "android")))]
const ASSUMED_MAIN_STACK: usize = 8 * 1024 * 1024;

/// Returns a low end for the stack that is safe to paint into and to measure
/// headroom against.
///
/// Every stack but one is a fixed mapping, and the bounds of those are exact. The
/// exception is the initial thread, whose stack grows on demand: there is no
/// mapping to report, so glibc derives the low end from `RLIMIT_STACK`. When that
/// limit is unlimited, what comes back describes a span of the address space that
/// reaches down past the heap and the executable — painting into it would write
/// outside the stack, and a headroom guard built on it would never fire.
///
/// So the answer is capped at what the process is actually allowed to grow into,
/// and where even that is unbounded, at [`ASSUMED_MAIN_STACK`]. Capping the low end
/// upwards is the conservative direction: depth and peaks are measured from the
/// base and are unaffected, while headroom can only be understated.
#[cfg(all(feature = "std", any(target_os = "linux", target_os = "android")))]
fn trustworthy_limit(base: usize, limit: usize) -> usize {
    // The threshold spares every ordinary thread the two syscalls below; it cannot
    // hide the pathological case, which is orders of magnitude larger.
    if base - limit <= TRUSTED_STACK_MAX || !is_initial_thread() {
        return limit;
    }

    cap_limit(base, limit, stack_rlimit().unwrap_or(ASSUMED_MAIN_STACK))
}

/// Fuchsia reports every stack, including the initial thread's, as the fixed
/// mapping it is, so there is nothing to distrust.
#[cfg(all(feature = "std", target_os = "fuchsia"))]
fn trustworthy_limit(_base: usize, limit: usize) -> usize {
    limit
}

/// Raises `limit` so that `[limit, base)` spans at most `cap` bytes.
#[cfg(all(feature = "std", any(target_os = "linux", target_os = "android")))]
const fn cap_limit(base: usize, limit: usize, cap: usize) -> usize {
    // `base - limit > cap` implies `cap < base`, so the subtraction cannot wrap.
    if base - limit > cap {
        base - cap
    } else {
        limit
    }
}

/// Returns `true` if the caller is the process' initial thread — the only one
/// whose stack the kernel grows on demand.
#[cfg(all(feature = "std", any(target_os = "linux", target_os = "android")))]
fn is_initial_thread() -> bool {
    // SAFETY: neither call takes an argument, and neither can fail.
    unsafe { libc::syscall(libc::SYS_gettid) as libc::pid_t == libc::getpid() }
}

/// Returns the soft `RLIMIT_STACK`, or `None` if it is unlimited or unreadable.
#[cfg(all(feature = "std", any(target_os = "linux", target_os = "android")))]
fn stack_rlimit() -> Option<usize> {
    let mut limit = core::mem::MaybeUninit::<libc::rlimit>::uninit();

    // SAFETY: `getrlimit` initializes the struct when it succeeds.
    let limit = unsafe {
        if libc::getrlimit(libc::RLIMIT_STACK, limit.as_mut_ptr()) != 0 {
            return None;
        }
        limit.assume_init()
    };

    if limit.rlim_cur == libc::RLIM_INFINITY {
        return None;
    }

    usize::try_from(limit.rlim_cur).ok()
}

#[cfg(all(feature = "std", target_vendor = "apple"))]
fn bounds_impl() -> Option<(usize, usize)> {
    // SAFETY: both calls are infallible reads of the current thread's own
    // descriptor.
    let (base, size) = unsafe {
        let this = libc::pthread_self();
        (
            libc::pthread_get_stackaddr_np(this) as usize,
            libc::pthread_get_stacksize_np(this),
        )
    };

    if base == 0 || size == 0 {
        return None;
    }

    // Unlike the pthread attribute API, Apple's accessor returns the *top* of
    // the stack.
    Some((base, base.checked_sub(size)?))
}

#[cfg(all(feature = "std", windows))]
fn bounds_impl() -> Option<(usize, usize)> {
    #[link(name = "kernel32")]
    unsafe extern "system" {
        fn GetCurrentThreadStackLimits(low: *mut usize, high: *mut usize);
    }

    let mut low = 0usize;
    let mut high = 0usize;
    // SAFETY: both out-pointers are valid for writes of `usize`.
    unsafe { GetCurrentThreadStackLimits(&mut low, &mut high) };

    if low == 0 || high <= low {
        return None;
    }

    Some((high, low))
}

#[cfg(all(
    feature = "std",
    not(any(
        target_os = "linux",
        target_os = "android",
        target_os = "fuchsia",
        target_vendor = "apple",
        windows,
    ))
))]
fn bounds_impl() -> Option<(usize, usize)> {
    None
}

/// Returns an opaque identifier of the calling thread, or `0` if the platform
/// has no cheap way of providing one.
///
/// On Linux this is the kernel thread id, which is what `top -H`, `perf` and
/// `/proc/<pid>/task` show; on other unices it is the `pthread_t` handle, and on
/// Windows the thread id.
#[cfg(feature = "std")]
pub fn thread_id() -> u64 {
    thread_id_impl()
}

#[cfg(all(feature = "std", any(target_os = "linux", target_os = "android")))]
fn thread_id_impl() -> u64 {
    // SAFETY: `gettid` takes no arguments and cannot fail.
    let tid = unsafe { libc::syscall(libc::SYS_gettid) };
    if tid < 0 { 0 } else { tid as u64 }
}

#[cfg(all(
    feature = "std",
    unix,
    not(any(target_os = "linux", target_os = "android"))
))]
fn thread_id_impl() -> u64 {
    // SAFETY: `pthread_self` cannot fail.
    (unsafe { libc::pthread_self() }) as usize as u64
}

#[cfg(all(feature = "std", windows))]
fn thread_id_impl() -> u64 {
    #[link(name = "kernel32")]
    unsafe extern "system" {
        fn GetCurrentThreadId() -> u32;
    }

    // SAFETY: the call takes no arguments and cannot fail.
    u64::from(unsafe { GetCurrentThreadId() })
}

#[cfg(all(feature = "std", not(any(unix, windows))))]
fn thread_id_impl() -> u64 {
    0
}

#[cfg(all(test, feature = "std", any(target_os = "linux", target_os = "android")))]
mod tests {
    use super::*;

    #[test]
    fn capping_a_limit() {
        let base = 0x7fff_0000_0000;

        // A stack no larger than the cap is left alone.
        assert_eq!(cap_limit(base, base - 4096, 8192), base - 4096);
        assert_eq!(cap_limit(base, base - 8192, 8192), base - 8192);

        // A larger one is cut down to it, from the bottom.
        assert_eq!(cap_limit(base, base - 16384, 8192), base - 8192);

        // The absurd case: a "stack" that reaches down past everything else.
        assert_eq!(
            cap_limit(base, 0x5555_0000_0000, ASSUMED_MAIN_STACK),
            base - ASSUMED_MAIN_STACK
        );

        // A cap wider than the address space below the base cannot wrap, because
        // it can only apply when it is narrower than the span being capped.
        assert_eq!(cap_limit(4096, 0, usize::MAX), 0);
    }

    #[test]
    fn the_test_harness_does_not_run_on_the_initial_thread() {
        // Which is why `tests/main_thread.rs` exists and is harness-free.
        assert!(!is_initial_thread());
    }

    #[test]
    fn a_stack_rlimit_is_readable_or_unlimited() {
        // Either answer is valid; the point is that the call works and stays
        // within `usize`.
        if let Some(limit) = stack_rlimit() {
            assert!(limit > 0);
        }
    }
}