#[cfg(all(feature = "std", any(target_os = "linux", target_os = "android")))]
mod linux {
use std::hint::black_box;
use stackler::Stack;
#[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]);
}
pub fn set_stack_rlimit(soft: u64) -> bool {
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();
}
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");
}
fn with_a_finite_limit() {
assert_plausible(&Stack::current().unwrap(), "an ordinary main stack");
assert!(stackler::attach());
let depth = stackler::depth().expect("the main thread is tracked");
assert!(depth > 0 && depth < 64 * 1024, "{depth}");
#[cfg(feature = "watermark")]
{
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:?}");
}
}
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");
assert_eq!(unlimited.base(), finite.base());
assert_plausible(&unlimited, "an unlimited rlimit taken at face value");
assert!(!stackler::has_headroom(1 << 40));
#[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");
}