use std::io;
use std::process::{Command, Output};
use crate::stack::{Probe, classify};
pub const SUPPORTED: bool = imp::SUPPORTED;
pub fn mapped() -> io::Result<u64> {
let status = std::fs::read_to_string("/proc/self/status")?;
status
.lines()
.find_map(|l| l.strip_prefix("VmSize:"))
.and_then(|v| v.trim().strip_suffix("kB"))
.and_then(|kb| kb.trim().parse::<u64>().ok())
.map(|kb| kb * 1024)
.ok_or_else(|| io::Error::other("no VmSize in /proc/self/status"))
}
#[track_caller]
pub fn run(probe: &str, var: &str, value: &str) {
let exe = std::env::current_exe().expect("the test binary's path");
let Output {
status,
stdout,
stderr,
} = crate::child::output(
Command::new(exe)
.args(["--exact", probe, "--ignored", "--test-threads=1"])
.env(var, value)
.env("MALLOC_ARENA_MAX", "1"),
)
.unwrap_or_else(|e| panic!("cannot start probe {probe}: {e}"));
match classify(status, &stdout, &stderr) {
Ok(Probe::Fits) => {}
Ok(Probe::Overflows) => panic!("probe {probe} overflowed a stack"),
Err(e) => panic!("probe {probe}: {e}"),
}
}
#[derive(Debug)]
#[must_use = "the cap lasts only while this lives"]
pub struct Capped {
old: u64,
pub cap: u64,
}
impl Drop for Capped {
fn drop(&mut self) {
let _ = imp::set_soft(self.old);
}
}
pub fn cap_above_current(margin: u64) -> io::Result<Capped> {
let (old, hard) = imp::get()?;
let cap = mapped()?.saturating_add(margin);
if cap > hard {
return Err(io::Error::other(format!(
"the hard address-space limit, {hard} bytes, is below the cap, {cap}"
)));
}
imp::set_soft(cap)?;
Ok(Capped { old, cap })
}
#[cfg(all(
target_os = "linux",
any(target_arch = "x86_64", target_arch = "aarch64")
))]
mod imp {
use std::io;
pub const SUPPORTED: bool = true;
const RLIMIT_AS: i32 = 9;
#[repr(C)]
struct Rlimit {
cur: u64,
max: u64,
}
unsafe extern "C" {
fn getrlimit(resource: i32, rlim: *mut Rlimit) -> i32;
fn setrlimit(resource: i32, rlim: *const Rlimit) -> i32;
}
pub fn get() -> io::Result<(u64, u64)> {
let mut r = Rlimit { cur: 0, max: 0 };
if unsafe { getrlimit(RLIMIT_AS, &raw mut r) } != 0 {
return Err(io::Error::last_os_error());
}
Ok((r.cur, r.max))
}
pub fn set_soft(cur: u64) -> io::Result<()> {
let (_, max) = get()?;
let r = Rlimit { cur, max };
if unsafe { setrlimit(RLIMIT_AS, &raw const r) } != 0 {
return Err(io::Error::last_os_error());
}
Ok(())
}
}
#[cfg(not(all(
target_os = "linux",
any(target_arch = "x86_64", target_arch = "aarch64")
)))]
mod imp {
use std::io;
pub const SUPPORTED: bool = false;
fn unsupported() -> io::Error {
io::Error::new(
io::ErrorKind::Unsupported,
"an address-space cap is set on Linux x86-64 and 64-bit Arm only",
)
}
pub fn get() -> io::Result<(u64, u64)> {
Err(unsupported())
}
pub fn set_soft(_: u64) -> io::Result<()> {
Err(unsupported())
}
}
#[cfg(test)]
mod tests {
use super::{SUPPORTED, cap_above_current, mapped, run};
const VAR: &str = "UNITYRS_TESTKIT_ADDRESS_SPACE_PROBE";
#[test]
#[ignore = "run by a_cap_refuses_what_passes_it_and_drops_with_its_guard"]
fn probe() {
let Ok(what) = std::env::var(VAR) else {
return;
};
if let Some(spec) = what.strip_prefix("killed:") {
crate::child::kill_self_while(spec);
}
let big = 8 << 20;
{
let capped = cap_above_current(4 << 20).unwrap();
assert!(capped.cap >= mapped().unwrap());
let mut v: Vec<u8> = Vec::new();
assert!(v.try_reserve_exact(big).is_err(), "8 MiB fit under the cap");
let mut w: Vec<u8> = Vec::new();
assert!(w.try_reserve_exact(64 << 10).is_ok());
}
let mut v: Vec<u8> = Vec::new();
assert!(
v.try_reserve_exact(big).is_ok(),
"the cap outlived its guard"
);
}
#[test]
fn a_cap_refuses_what_passes_it_and_drops_with_its_guard() {
if !SUPPORTED {
eprintln!("skipped: no address-space cap on this target");
return;
}
run("address_space::tests::probe", VAR, "1");
}
#[cfg(unix)]
#[test]
fn a_probe_killed_from_outside_once_is_run_again() {
if !SUPPORTED {
eprintln!("skipped: no address-space cap on this target");
return;
}
let marks = crate::child::Marks::new("address-space-once");
let spec = format!("killed:{}", marks.killed(1));
run("address_space::tests::probe", VAR, &spec);
assert_eq!(marks.runs(), 1, "the probe was not killed first");
}
}