Skip to main content

secmem/
secmem.rs

1//! Security probe: peak RSS of a script against its memory limit.
2//! `secmem SCRIPT [mem_mib] [fuel]`
3#![allow(clippy::unwrap_used, clippy::expect_used, missing_docs, clippy::indexing_slicing, clippy::panic)]
4use remedy_lua::{Libs, Limits, Lua};
5fn hwm() -> usize {
6    std::fs::read_to_string("/proc/self/status").ok().and_then(|s| s.lines().find(|l| l.starts_with("VmHWM")).and_then(|l| l.split_whitespace().nth(1)?.parse().ok())).unwrap_or(0)
7}
8fn main() {
9    let a: Vec<String> = std::env::args().collect();
10    let src = a.get(1).cloned().unwrap_or_default();
11    let mem: usize = a.get(2).and_then(|s| s.parse().ok()).unwrap_or(64) << 20;
12    let fuel: u64 = a.get(3).and_then(|s| s.parse().ok()).unwrap_or(1 << 32);
13    let libs = Libs::ALL.union(Libs::DEBUG_INFO).union(Libs::REQUIRE);
14    let mut lua = Lua::new(Limits::default().memory(mem).fuel(fuel).hash_seed(7), libs);
15    lua.set_print(|_| {});
16    let h0 = hwm();
17    let t = std::time::Instant::now();
18    let r = lua.exec(src, "=s");
19    let r = match r { Ok(v) => format!("ok {:?}", v.first().and_then(|x| lua.to_string_lossy(*x))), Err(e) => format!("err {e}") };
20    let now = std::fs::read_to_string("/proc/self/statm").ok().and_then(|s| s.split_whitespace().nth(1)?.parse::<usize>().ok()).unwrap_or(0) * 4096;
21    println!(
22        "peak rss {} MiB (from {} MiB) under a {} MiB limit, rss now {} MiB with {} MiB counted, {:?}, fuel {}, {}",
23        hwm() >> 10,
24        h0 >> 10,
25        mem >> 20,
26        now >> 20,
27        lua.memory_used() >> 20,
28        t.elapsed(),
29        fuel - lua.fuel_left(),
30        &r[..r.len().min(200)]
31    );
32}