Skip to main content

sechost/
sechost.rs

1//! Security probe: resident memory against counted memory for objects the host makes.
2//! `sechost KIND [n]`, KIND one of `ud`, `ud_root`, `root`, `fn`, `fn_root`, `register`,
3//! `ud_tracked`. Each object is kept alive in a global table (and, for `*_root`, a root).
4#![allow(clippy::unwrap_used, clippy::expect_used, missing_docs, clippy::indexing_slicing, clippy::panic)]
5use remedy_lua::{Libs, Limits, Lua, Value};
6
7fn rss() -> usize {
8    std::fs::read_to_string("/proc/self/statm").ok().and_then(|s| s.split_whitespace().nth(1)?.parse::<usize>().ok()).unwrap_or(0) * 4096
9}
10
11fn main() {
12    let a: Vec<String> = std::env::args().collect();
13    let kind = a.get(1).cloned().unwrap_or_else(|| "ud".into());
14    let n: usize = a.get(2).and_then(|s| s.parse().ok()).unwrap_or(200_000);
15    let mut lua = Lua::new(Limits::default().memory(1 << 30).fuel(1 << 40), Libs::ALL);
16    lua.exec("KEEP = {}", "=s").unwrap();
17    let keep = match lua.exec("return KEEP", "=s").unwrap()[0] { Value::Table(t) => t, _ => panic!() };
18    let mut roots = Vec::new();
19    lua.collect_garbage().unwrap();
20    let (r0, m0) = (rss(), lua.memory_used());
21    for i in 0..n {
22        let v = match kind.as_str() {
23            "ud" | "ud_root" => lua.create_userdata(i as u64, None).unwrap(),
24            "ud_tracked" => lua.create_userdata_tracked(i as u64, None, i as u64).unwrap(),
25            "fn" | "fn_root" => lua.create_function("f", move |_, _| Ok(vec![Value::Int(i as i64)])).unwrap(),
26            "root" => Value::Int(i as i64),
27            "register" => {
28                lua.register(&format!("g{i}"), move |_, _| Ok(vec![Value::Int(i as i64)])).unwrap();
29                Value::Nil
30            }
31            _ => panic!("kind"),
32        };
33        if kind.ends_with("root") {
34            let t = if kind == "root" { lua.create_table().map(Value::Table).unwrap() } else { v };
35            roots.push(lua.root(t));
36            if kind == "root" {
37                continue;
38            }
39        }
40        if !v.is_nil() {
41            lua.table_set(keep, Value::Int(i as i64 + 1), v).unwrap();
42        }
43        if i % 4096 == 0 {
44            lua.exec("", "=s").unwrap();
45        }
46    }
47    lua.exec("", "=s").unwrap();
48    lua.collect_garbage().unwrap();
49    let (r1, m1) = (rss(), lua.memory_used());
50    let (dr, dm) = (r1.saturating_sub(r0) as f64 / n as f64, m1.saturating_sub(m0) as f64 / n as f64);
51    println!("{kind}: {dr:.0} B resident, {dm:.0} B counted per object ({:.2}x)", dr / dm.max(1.0));
52    drop(roots);
53}