Skip to main content

Limits

Struct Limits 

Source
#[non_exhaustive]
pub struct Limits { pub fuel: u64, pub memory: usize, pub call_depth: usize, pub native_depth: usize, pub stack_slots: usize, pub string_len: usize, pub output: usize, pub error_len: usize, pub stack_bytes: usize, pub hash_seed: Option<u64>, pub strict_5_4: bool, }
Expand description

How much a state may use. Fuel is per call from the host; the rest hold always.

Fields (Non-exhaustive)§

This struct is marked as non-exhaustive
Non-exhaustive structs could have additional fields added in future. Therefore, non-exhaustive structs cannot be constructed in external crates using the traditional Struct { .. } syntax; cannot be matched against without a wildcard ..; and struct update syntax will not work.
§fuel: u64

Steps one call from the host may take: one per instruction, plus what library functions charge for their work, plus collector work.

§memory: usize

Bytes the state’s objects may hold, with the free slots of each kind’s slab (a collected object’s slot stays resident until a new object of its kind reuses it, or until no object of its kind sits past it). The collector paces on the objects alone. Besides these, a state keeps at most 64 KiB (or 1/16 of this limit, if less) of freed table buffers for reuse, uncharged.

§call_depth: usize

Lua call frames one thread may have (deeper recursion is a stack overflow error). Unlimited by default: frames are memory like the value stack, charged to memory, and a call whose frame does not fit is the same catchable stack overflow. Lua-to-Lua calls use no native stack.

§native_depth: usize

How deeply library functions may call back into Lua (sort comparators, __tostring, gsub functions inside each other).

§stack_slots: usize

Stack slots one thread may have. Unlimited by default: the stack is memory like any other, charged to memory before it grows.

§string_len: usize

The longest string a script may make.

§output: usize

Bytes print may write per call from the host (and, with no sink set, the most Lua::take_output’s buffer holds; what does not fit is dropped).

§error_len: usize

The longest error message kept.

§stack_bytes: usize

Bytes of the native stack one call may use for library functions that call back into Lua (and for the parser’s recursion). Lua-to-Lua calls use none.

§hash_seed: Option<u64>

The seed of the state’s hashing and of math.random’s first state; None (the default) is a fresh random seed per state, which keeps a script from aiming keys at one hash slot. A fixed seed is for replays and tests: the same program then gives the same results, pairs order and fuel on every run (see hash_seed).

§strict_5_4: bool

Strict Lua 5.4: leave out what stock C Lua 5.4 builds with LUA_COMPAT_5_3 (its makefile’s default), which RemedyLua offers by default: __le emulated with __lt and math.atan2/cosh/sinh/tanh/pow/frexp/ldexp/log10. Read when the state is made, and fixed for its life (Lua::set_limits keeps it).

Implementations§

Source§

impl Limits

Source

pub fn unmetered() -> Self

No budgets at all (for benchmarks and trusted code): fuel and memory are unlimited and the depth and size limits are as large as the machine allows. The interpreter still counts, so a state can be measured; nothing a script does can hit a limit except the native stack guard, which protects the process.

Examples found in repository?
examples/frontmem.rs (line 35)
16fn main() {
17    let mut args = std::env::args().skip(1);
18    let file = args.next().unwrap();
19    let limit: usize = args.next().and_then(|a| a.parse().ok()).unwrap_or(64 << 20);
20    let mode = args.next().unwrap_or_else(|| "host".into());
21    let src = std::fs::read(&file).unwrap();
22    let name = if file.ends_with(".rlua") { "=t.rlua" } else { "=t" };
23    let before = hwm();
24    let t = std::time::Instant::now();
25    let outcome = match mode.as_str() {
26        "check" => format!("{:?}", remedy_lua::check(&src, name.trim_start_matches('=')).first().map(|d| d.message.clone())),
27        "call" => {
28            let mut lua = Lua::new(Limits::default().memory(limit).fuel(1 << 40), Libs::ALL);
29            let s = lua.create_string(&src).unwrap();
30            lua.set_global("src", s).unwrap();
31            let r = lua.exec(format!("local f, e = load(src, '{name}') return f and 'ok' or e"), "=c");
32            format!("{:?}", r.map(|v| lua.to_string_lossy(v[0])))
33        }
34        _ => {
35            let mut lua = Lua::new(Limits::unmetered().memory(limit), Libs::NONE);
36            format!("{:?}", lua.load(&src, name).map(|_| ()))
37        }
38    };
39    let peak = hwm();
40    println!(
41        "{mode}: {outcome} in {:?}; peak {:.1} MB (before {:.1} MB) under {:.1} MiB: {:.2}x",
42        t.elapsed(),
43        peak as f64 / 1e6,
44        before as f64 / 1e6,
45        limit as f64 / 1048576.0,
46        peak as f64 / limit as f64
47    );
48}
More examples
Hide additional examples
examples/frontbench.rs (line 56)
37fn main() {
38    let mb: usize = std::env::args().nth(1).and_then(|a| a.parse().ok()).unwrap_or(4);
39    let src = match std::env::var("FRONTBENCH_FILE") {
40        Ok(f) => std::fs::read_to_string(f).unwrap(),
41        Err(_) => source(mb << 20),
42    };
43    // `FRONTBENCH_DUMP=path`: writes the source there (for `examples/frontmem.rs`) and stops.
44    if let Ok(path) = std::env::var("FRONTBENCH_DUMP") {
45        std::fs::write(path, &src).unwrap();
46        return;
47    }
48    let runs = 5;
49    let mut parse = f64::MAX;
50    let mut load = f64::MAX;
51    for _ in 0..runs {
52        let t = Instant::now();
53        let d = remedy_lua::check(src.as_bytes(), "bench.lua");
54        assert!(d.is_empty(), "{d:?}");
55        parse = parse.min(t.elapsed().as_secs_f64());
56        let mut lua = Lua::new(Limits::unmetered(), Libs::STANDARD);
57        let t = Instant::now();
58        lua.load(&src, "=bench").unwrap();
59        load = load.min(t.elapsed().as_secs_f64());
60    }
61    let mbs = src.len() as f64 / (1 << 20) as f64;
62    // With the oracle built in, the recursive front end side by side, alternating run by
63    // run so both see the same machine load.
64    #[cfg(feature = "front-oracle")]
65    {
66        let mut best = [[f64::MAX; 3]; 2];
67        for _ in 0..runs * 3 {
68            for (side, old) in best.iter_mut().zip([true, false]) {
69                let t = remedy_lua::__front::time(src.as_bytes(), "bench.lua", old).unwrap();
70                for (b, t) in side.iter_mut().zip(t) {
71                    *b = b.min(t.as_secs_f64() * 1e3);
72                }
73            }
74        }
75        for (label, b) in ["old (recursive)", "new (iterative)"].iter().zip(best) {
76            println!("{label}: parse {:6.1} ms  compile {:6.1} ms  drop {:5.1} ms", b[0], b[1], b[2]);
77        }
78    }
79    println!("source: {:.2} MB, {} lines (best of {runs})", mbs, src.lines().count());
80    println!("parse:           {:8.1} ms  {:6.1} MB/s", parse * 1e3, mbs / parse);
81    println!("parse + compile: {:8.1} ms  {:6.1} MB/s", load * 1e3, mbs / load);
82}
examples/frontstop.rs (line 35)
23fn main() {
24    let mut args = std::env::args().skip(1);
25    let cases: Vec<String> = match args.next() {
26        Some(c) if c != "all" => vec![c],
27        _ => ["do", "dots", "flat", "locals", "keys", "strs"].iter().map(|s| (*s).to_owned()).collect(),
28    };
29    let points: u32 = args.next().and_then(|a| a.parse().ok()).unwrap_or(24);
30    // A third argument: interrupt only there (milliseconds into the load).
31    let only: Option<u64> = args.next().and_then(|a| a.parse().ok());
32    for case in cases {
33        let src = source(&case);
34        let full = {
35            let mut lua = Lua::new(Limits::unmetered().memory(8 << 30), Libs::NONE);
36            let t = Instant::now();
37            let r = lua.load(&src, "=t").map(|_| ());
38            let e = t.elapsed();
39            assert!(r.is_ok(), "{case}: {r:?}");
40            e
41        };
42        let mut worst = (Duration::ZERO, Duration::ZERO);
43        for k in 1..=points {
44            let at = only.map_or(full * k / (points + 1), Duration::from_millis);
45            let mut lua = Lua::new(Limits::unmetered().memory(8 << 30), Libs::NONE);
46            let h = lua.interrupt_handle();
47            let t = std::thread::spawn(move || {
48                std::thread::sleep(at);
49                h.interrupt();
50                Instant::now()
51            });
52            let started = Instant::now();
53            let r = lua.load(&src, "=t").map(|_| ());
54            let end = Instant::now();
55            let fired = t.join().unwrap();
56            if r.is_err() {
57                let late = end.saturating_duration_since(fired);
58                if std::env::var("FRONTSTOP_VERBOSE").is_ok() {
59                    println!("  at {at:?}: {late:?} late, {:?} into the load", fired.saturating_duration_since(started));
60                }
61                if late > worst.0 {
62                    worst = (late, at);
63                }
64            }
65            lua.interrupt_handle().reset();
66            let _ = lua.load("return 1", "=ok");
67        }
68        println!("{case:8} {:.1} MB, load {full:?}: worst {:?} late (interrupted at {:?})", src.len() as f64 / 1e6, worst.0, worst.1);
69    }
70}
examples/interngap.rs (line 63)
32fn main() {
33    let a: Vec<String> = std::env::args().collect();
34    let n: usize = a.get(1).and_then(|s| s.parse().ok()).unwrap_or(2_000_000);
35    let k: usize = a.get(2).and_then(|s| s.parse().ok()).unwrap_or(600_000);
36    let mut lua = Lua::new(Limits::default().memory(4 << 30).fuel(1 << 40).hash_seed(7), Libs::ALL);
37    // The table grows first (its array part's growth is not the interner's).
38    lua.exec(&format!("L = {{}} for i = 1, {n} do L[i] = true end"), "=setup").unwrap();
39    let (clock, st) = gap_clock();
40    lua.set_time_limit(Some((clock, Duration::from_secs(600))));
41    let body = std::env::var("BODY").unwrap_or_else(|_| "L[i] = 's' .. i".into());
42    let f = lua.load(&format!("local L = L for i = 1, {n} do {body} end return #L"), "=vm").unwrap();
43    st.lock().unwrap().0 = Instant::now();
44    let t = Instant::now();
45    lua.call(f.value(), &[]).unwrap();
46    let all = t.elapsed();
47    let g = *st.lock().unwrap();
48    println!("vm: {n} strings in {all:?}, longest between deadline reads {:?}", g.1);
49    println!("reads {}, mean gap {:?}", g.2, all / g.2.max(1) as u32);
50    let stat = std::fs::read_to_string("/proc/self/stat").unwrap_or_default();
51    println!("minflt {}", stat.split_whitespace().nth(9).unwrap_or("?"));
52    println!(
53        "{:?}",
54        lua.internal_sizes().into_iter().filter(|(k, _)| k.starts_with("intern")).collect::<Vec<_>>()
55    );
56    if k == 0 {
57        return;
58    }
59    // A host load: the interrupt is looked at by the compile's steps; a thread notes how late
60    // a load stops after it, at points along the load.
61    let src = format!("return {{{}}}", (0..k).map(|i| format!("\"c{i}\",")).collect::<String>());
62    let full = {
63        let mut l = Lua::new(Limits::unmetered().memory(4 << 30), Libs::NONE);
64        let t = Instant::now();
65        l.load(&src, "=t").unwrap();
66        t.elapsed()
67    };
68    let mut worst = Duration::ZERO;
69    for p in 1..=12u32 {
70        let at = full * p / 13;
71        let mut l = Lua::new(Limits::unmetered().memory(4 << 30), Libs::NONE);
72        let h = l.interrupt_handle();
73        let th = std::thread::spawn(move || {
74            std::thread::sleep(at);
75            h.interrupt();
76            Instant::now()
77        });
78        let r = l.load(&src, "=t").map(|_| ());
79        let end = Instant::now();
80        let fired = th.join().unwrap();
81        if r.is_err() {
82            worst = worst.max(end.saturating_duration_since(fired));
83        }
84    }
85    println!("load: {k} constants in {full:?}, worst stop after the interrupt {worst:?}");
86}
Source

pub fn hash_seed(self, seed: u64) -> Self

A fixed seed for hashing, math.random and math.randomseed() without arguments, so that runs replay exactly: the same program with the same seed gives the same results, pairs order and fuel every time (with the fast loop on or off). For replays and tests; production code should keep the default, a random seed per state, which defends against hash flooding. Read when the state is made.

Examples found in repository?
examples/secprobe.rs (line 21)
19fn state(mem: usize, fast: bool) -> Lua {
20    let libs = Libs::ALL.union(Libs::DEBUG_INFO).union(Libs::REQUIRE);
21    let mut lua = Lua::new(Limits::default().memory(mem).string_len(32 << 20).fuel(1 << 34).hash_seed(7), libs);
22    lua.add_module("hostmod", "local M = {n = 1} for i = 1, 20 do M[i] = function() return i end end return M");
23    lua.set_fast_loop(fast);
24    lua.set_print(|_| {});
25    lua
26}
More examples
Hide additional examples
examples/secmem.rs (line 14)
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}
examples/seclat.rs (line 20)
10fn main() {
11    let a: Vec<String> = std::env::args().collect();
12    let setup = a.get(1).cloned().unwrap_or_default();
13    let body = a.get(2).cloned().unwrap_or_default();
14    let ms: u64 = a.get(3).and_then(|s| s.parse().ok()).unwrap_or(10);
15    let mem: usize = a.get(4).and_then(|s| s.parse().ok()).unwrap_or(512) << 20;
16    let libs = Libs::ALL.union(Libs::DEBUG_INFO).union(Libs::REQUIRE);
17    let mut worst = Duration::ZERO;
18    let mut last = String::new();
19    for _ in 0..5 {
20        let mut lua = Lua::new(Limits::default().memory(mem).string_len(64 << 20).fuel(1 << 40).hash_seed(7), libs);
21        lua.set_print(|_| {});
22        lua.exec(&setup, "=setup").unwrap();
23        let t0 = Instant::now();
24        let clock: remedy_lua::Clock = Arc::new(move || t0.elapsed());
25        lua.set_time_limit(Some((clock, Duration::from_millis(ms))));
26        let f = lua.load(&body, "=body").unwrap();
27        let start = Instant::now();
28        let r = lua.call(f.value(), &[]);
29        let el = start.elapsed();
30        worst = worst.max(el.saturating_sub(Duration::from_millis(ms)));
31        last = format!("{:?}", r.err());
32    }
33    println!("worst overrun {:?} past {ms} ms: {}", worst, &last[..last.len().min(120)]);
34}
examples/fuelcal.rs (line 168)
155fn main() {
156    let fuel: u64 = std::env::var("FUELCAL_FUEL").ok().and_then(|s| s.parse().ok()).unwrap_or(3_000_000);
157    let only = std::env::var("FUELCAL_ONLY").ok();
158    let md = std::env::var_os("FUELCAL_MD").is_some();
159    let mut rows: Vec<(&str, f64, String)> = Vec::new();
160    for &(name, setup, body) in CASES {
161        if only.as_deref().is_some_and(|o| !name.contains(o)) {
162            continue;
163        }
164        let src = format!("{setup}\nwhile true do\n{body}\nend");
165        let mut best = f64::MAX;
166        let mut note = String::new();
167        for _ in 0..3 {
168            let mut lua = Lua::new(Limits::default().fuel(fuel).memory(256 << 20).hash_seed(7), Libs::ALL);
169            let f = match lua.load(&src, "=cal") {
170                Ok(f) => f,
171                Err(e) => {
172                    note = format!("load: {e:?}");
173                    break;
174                }
175            };
176            let t = std::time::Instant::now();
177            let r = lua.call(f.value(), &[]);
178            let el = t.elapsed().as_secs_f64();
179            let used = fuel - lua.fuel_left();
180            match r {
181                Err(Error::Limit(LimitKind::Fuel)) => {}
182                other => note = format!("{other:?}").chars().take(80).collect(),
183            }
184            best = best.min(el * 1e9 / used.max(1) as f64);
185        }
186        if !md {
187            println!("{best:9.1} ns/unit  {name} {note}");
188        }
189        rows.push((name, best, note));
190    }
191    let mut v: Vec<f64> = rows.iter().map(|r| r.1).collect();
192    v.sort_by(f64::total_cmp);
193    let median = v.get(v.len() / 2).copied().unwrap_or(0.0);
194    if md {
195        println!("| case | ns/unit | x median |\n|---|---:|---:|");
196        for (name, ns, note) in &rows {
197            println!("| {name}{} | {ns:.1} | {:.2} |", if note.is_empty() { String::new() } else { format!(" ({note})") }, ns / median);
198        }
199    }
200    println!("median {median:.1} ns/unit, max {:.1} ({:.1}x)", v.last().copied().unwrap_or(0.0), v.last().copied().unwrap_or(0.0) / median);
201    let mut worst: Vec<_> = rows.iter().filter(|r| r.1 > 4.0 * median).collect();
202    worst.sort_by(|a, b| b.1.total_cmp(&a.1));
203    for (name, ns, _) in worst {
204        println!("  over 4x: {name} {ns:.1} ({:.1}x)", ns / median);
205    }
206}
examples/interngap.rs (line 36)
32fn main() {
33    let a: Vec<String> = std::env::args().collect();
34    let n: usize = a.get(1).and_then(|s| s.parse().ok()).unwrap_or(2_000_000);
35    let k: usize = a.get(2).and_then(|s| s.parse().ok()).unwrap_or(600_000);
36    let mut lua = Lua::new(Limits::default().memory(4 << 30).fuel(1 << 40).hash_seed(7), Libs::ALL);
37    // The table grows first (its array part's growth is not the interner's).
38    lua.exec(&format!("L = {{}} for i = 1, {n} do L[i] = true end"), "=setup").unwrap();
39    let (clock, st) = gap_clock();
40    lua.set_time_limit(Some((clock, Duration::from_secs(600))));
41    let body = std::env::var("BODY").unwrap_or_else(|_| "L[i] = 's' .. i".into());
42    let f = lua.load(&format!("local L = L for i = 1, {n} do {body} end return #L"), "=vm").unwrap();
43    st.lock().unwrap().0 = Instant::now();
44    let t = Instant::now();
45    lua.call(f.value(), &[]).unwrap();
46    let all = t.elapsed();
47    let g = *st.lock().unwrap();
48    println!("vm: {n} strings in {all:?}, longest between deadline reads {:?}", g.1);
49    println!("reads {}, mean gap {:?}", g.2, all / g.2.max(1) as u32);
50    let stat = std::fs::read_to_string("/proc/self/stat").unwrap_or_default();
51    println!("minflt {}", stat.split_whitespace().nth(9).unwrap_or("?"));
52    println!(
53        "{:?}",
54        lua.internal_sizes().into_iter().filter(|(k, _)| k.starts_with("intern")).collect::<Vec<_>>()
55    );
56    if k == 0 {
57        return;
58    }
59    // A host load: the interrupt is looked at by the compile's steps; a thread notes how late
60    // a load stops after it, at points along the load.
61    let src = format!("return {{{}}}", (0..k).map(|i| format!("\"c{i}\",")).collect::<String>());
62    let full = {
63        let mut l = Lua::new(Limits::unmetered().memory(4 << 30), Libs::NONE);
64        let t = Instant::now();
65        l.load(&src, "=t").unwrap();
66        t.elapsed()
67    };
68    let mut worst = Duration::ZERO;
69    for p in 1..=12u32 {
70        let at = full * p / 13;
71        let mut l = Lua::new(Limits::unmetered().memory(4 << 30), Libs::NONE);
72        let h = l.interrupt_handle();
73        let th = std::thread::spawn(move || {
74            std::thread::sleep(at);
75            h.interrupt();
76            Instant::now()
77        });
78        let r = l.load(&src, "=t").map(|_| ());
79        let end = Instant::now();
80        let fired = th.join().unwrap();
81        if r.is_err() {
82            worst = worst.max(end.saturating_duration_since(fired));
83        }
84    }
85    println!("load: {k} constants in {full:?}, worst stop after the interrupt {worst:?}");
86}
Source

pub fn strict_5_4(self, on: bool) -> Self

Sets strict_5_4: no Lua 5.3 compatibility (see the field).

Source

pub fn fuel(self, n: u64) -> Self

Sets fuel.

Examples found in repository?
examples/secprobe.rs (line 21)
19fn state(mem: usize, fast: bool) -> Lua {
20    let libs = Libs::ALL.union(Libs::DEBUG_INFO).union(Libs::REQUIRE);
21    let mut lua = Lua::new(Limits::default().memory(mem).string_len(32 << 20).fuel(1 << 34).hash_seed(7), libs);
22    lua.add_module("hostmod", "local M = {n = 1} for i = 1, 20 do M[i] = function() return i end end return M");
23    lua.set_fast_loop(fast);
24    lua.set_print(|_| {});
25    lua
26}
27
28fn run(setup: &str, body: &str, fuel: u64, mem: usize, fast: bool) -> (f64, u64, String, usize, usize) {
29    let r0 = rss();
30    let mut lua = state(mem, fast);
31    lua.exec(format!("I = 0 {setup}"), "=setup").unwrap();
32    lua.set_limits(lua.limits().fuel(fuel));
33    let f = lua.load(format!("while true do I = I + 1 {body} end"), "=probe").unwrap();
34    let t = Instant::now();
35    let r = lua.call(f.value(), &[]);
36    let el = t.elapsed().as_nanos() as f64;
37    let used = fuel - lua.fuel_left();
38    let mu = lua.memory_used();
39    let g = rss().saturating_sub(r0);
40    (el / used.max(1) as f64, used, format!("{:?}", r.err()), mu, g)
41}
More examples
Hide additional examples
examples/secmem.rs (line 14)
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}
examples/seclat.rs (line 20)
10fn main() {
11    let a: Vec<String> = std::env::args().collect();
12    let setup = a.get(1).cloned().unwrap_or_default();
13    let body = a.get(2).cloned().unwrap_or_default();
14    let ms: u64 = a.get(3).and_then(|s| s.parse().ok()).unwrap_or(10);
15    let mem: usize = a.get(4).and_then(|s| s.parse().ok()).unwrap_or(512) << 20;
16    let libs = Libs::ALL.union(Libs::DEBUG_INFO).union(Libs::REQUIRE);
17    let mut worst = Duration::ZERO;
18    let mut last = String::new();
19    for _ in 0..5 {
20        let mut lua = Lua::new(Limits::default().memory(mem).string_len(64 << 20).fuel(1 << 40).hash_seed(7), libs);
21        lua.set_print(|_| {});
22        lua.exec(&setup, "=setup").unwrap();
23        let t0 = Instant::now();
24        let clock: remedy_lua::Clock = Arc::new(move || t0.elapsed());
25        lua.set_time_limit(Some((clock, Duration::from_millis(ms))));
26        let f = lua.load(&body, "=body").unwrap();
27        let start = Instant::now();
28        let r = lua.call(f.value(), &[]);
29        let el = start.elapsed();
30        worst = worst.max(el.saturating_sub(Duration::from_millis(ms)));
31        last = format!("{:?}", r.err());
32    }
33    println!("worst overrun {:?} past {ms} ms: {}", worst, &last[..last.len().min(120)]);
34}
examples/frontmem.rs (line 28)
16fn main() {
17    let mut args = std::env::args().skip(1);
18    let file = args.next().unwrap();
19    let limit: usize = args.next().and_then(|a| a.parse().ok()).unwrap_or(64 << 20);
20    let mode = args.next().unwrap_or_else(|| "host".into());
21    let src = std::fs::read(&file).unwrap();
22    let name = if file.ends_with(".rlua") { "=t.rlua" } else { "=t" };
23    let before = hwm();
24    let t = std::time::Instant::now();
25    let outcome = match mode.as_str() {
26        "check" => format!("{:?}", remedy_lua::check(&src, name.trim_start_matches('=')).first().map(|d| d.message.clone())),
27        "call" => {
28            let mut lua = Lua::new(Limits::default().memory(limit).fuel(1 << 40), Libs::ALL);
29            let s = lua.create_string(&src).unwrap();
30            lua.set_global("src", s).unwrap();
31            let r = lua.exec(format!("local f, e = load(src, '{name}') return f and 'ok' or e"), "=c");
32            format!("{:?}", r.map(|v| lua.to_string_lossy(v[0])))
33        }
34        _ => {
35            let mut lua = Lua::new(Limits::unmetered().memory(limit), Libs::NONE);
36            format!("{:?}", lua.load(&src, name).map(|_| ()))
37        }
38    };
39    let peak = hwm();
40    println!(
41        "{mode}: {outcome} in {:?}; peak {:.1} MB (before {:.1} MB) under {:.1} MiB: {:.2}x",
42        t.elapsed(),
43        peak as f64 / 1e6,
44        before as f64 / 1e6,
45        limit as f64 / 1048576.0,
46        peak as f64 / limit as f64
47    );
48}
examples/sechost.rs (line 15)
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}
examples/fuelcal.rs (line 168)
155fn main() {
156    let fuel: u64 = std::env::var("FUELCAL_FUEL").ok().and_then(|s| s.parse().ok()).unwrap_or(3_000_000);
157    let only = std::env::var("FUELCAL_ONLY").ok();
158    let md = std::env::var_os("FUELCAL_MD").is_some();
159    let mut rows: Vec<(&str, f64, String)> = Vec::new();
160    for &(name, setup, body) in CASES {
161        if only.as_deref().is_some_and(|o| !name.contains(o)) {
162            continue;
163        }
164        let src = format!("{setup}\nwhile true do\n{body}\nend");
165        let mut best = f64::MAX;
166        let mut note = String::new();
167        for _ in 0..3 {
168            let mut lua = Lua::new(Limits::default().fuel(fuel).memory(256 << 20).hash_seed(7), Libs::ALL);
169            let f = match lua.load(&src, "=cal") {
170                Ok(f) => f,
171                Err(e) => {
172                    note = format!("load: {e:?}");
173                    break;
174                }
175            };
176            let t = std::time::Instant::now();
177            let r = lua.call(f.value(), &[]);
178            let el = t.elapsed().as_secs_f64();
179            let used = fuel - lua.fuel_left();
180            match r {
181                Err(Error::Limit(LimitKind::Fuel)) => {}
182                other => note = format!("{other:?}").chars().take(80).collect(),
183            }
184            best = best.min(el * 1e9 / used.max(1) as f64);
185        }
186        if !md {
187            println!("{best:9.1} ns/unit  {name} {note}");
188        }
189        rows.push((name, best, note));
190    }
191    let mut v: Vec<f64> = rows.iter().map(|r| r.1).collect();
192    v.sort_by(f64::total_cmp);
193    let median = v.get(v.len() / 2).copied().unwrap_or(0.0);
194    if md {
195        println!("| case | ns/unit | x median |\n|---|---:|---:|");
196        for (name, ns, note) in &rows {
197            println!("| {name}{} | {ns:.1} | {:.2} |", if note.is_empty() { String::new() } else { format!(" ({note})") }, ns / median);
198        }
199    }
200    println!("median {median:.1} ns/unit, max {:.1} ({:.1}x)", v.last().copied().unwrap_or(0.0), v.last().copied().unwrap_or(0.0) / median);
201    let mut worst: Vec<_> = rows.iter().filter(|r| r.1 > 4.0 * median).collect();
202    worst.sort_by(|a, b| b.1.total_cmp(&a.1));
203    for (name, ns, _) in worst {
204        println!("  over 4x: {name} {ns:.1} ({:.1}x)", ns / median);
205    }
206}
Source

pub fn memory(self, n: usize) -> Self

Sets memory.

Examples found in repository?
examples/secprobe.rs (line 21)
19fn state(mem: usize, fast: bool) -> Lua {
20    let libs = Libs::ALL.union(Libs::DEBUG_INFO).union(Libs::REQUIRE);
21    let mut lua = Lua::new(Limits::default().memory(mem).string_len(32 << 20).fuel(1 << 34).hash_seed(7), libs);
22    lua.add_module("hostmod", "local M = {n = 1} for i = 1, 20 do M[i] = function() return i end end return M");
23    lua.set_fast_loop(fast);
24    lua.set_print(|_| {});
25    lua
26}
More examples
Hide additional examples
examples/secmem.rs (line 14)
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}
examples/seclat.rs (line 20)
10fn main() {
11    let a: Vec<String> = std::env::args().collect();
12    let setup = a.get(1).cloned().unwrap_or_default();
13    let body = a.get(2).cloned().unwrap_or_default();
14    let ms: u64 = a.get(3).and_then(|s| s.parse().ok()).unwrap_or(10);
15    let mem: usize = a.get(4).and_then(|s| s.parse().ok()).unwrap_or(512) << 20;
16    let libs = Libs::ALL.union(Libs::DEBUG_INFO).union(Libs::REQUIRE);
17    let mut worst = Duration::ZERO;
18    let mut last = String::new();
19    for _ in 0..5 {
20        let mut lua = Lua::new(Limits::default().memory(mem).string_len(64 << 20).fuel(1 << 40).hash_seed(7), libs);
21        lua.set_print(|_| {});
22        lua.exec(&setup, "=setup").unwrap();
23        let t0 = Instant::now();
24        let clock: remedy_lua::Clock = Arc::new(move || t0.elapsed());
25        lua.set_time_limit(Some((clock, Duration::from_millis(ms))));
26        let f = lua.load(&body, "=body").unwrap();
27        let start = Instant::now();
28        let r = lua.call(f.value(), &[]);
29        let el = start.elapsed();
30        worst = worst.max(el.saturating_sub(Duration::from_millis(ms)));
31        last = format!("{:?}", r.err());
32    }
33    println!("worst overrun {:?} past {ms} ms: {}", worst, &last[..last.len().min(120)]);
34}
examples/frontmem.rs (line 28)
16fn main() {
17    let mut args = std::env::args().skip(1);
18    let file = args.next().unwrap();
19    let limit: usize = args.next().and_then(|a| a.parse().ok()).unwrap_or(64 << 20);
20    let mode = args.next().unwrap_or_else(|| "host".into());
21    let src = std::fs::read(&file).unwrap();
22    let name = if file.ends_with(".rlua") { "=t.rlua" } else { "=t" };
23    let before = hwm();
24    let t = std::time::Instant::now();
25    let outcome = match mode.as_str() {
26        "check" => format!("{:?}", remedy_lua::check(&src, name.trim_start_matches('=')).first().map(|d| d.message.clone())),
27        "call" => {
28            let mut lua = Lua::new(Limits::default().memory(limit).fuel(1 << 40), Libs::ALL);
29            let s = lua.create_string(&src).unwrap();
30            lua.set_global("src", s).unwrap();
31            let r = lua.exec(format!("local f, e = load(src, '{name}') return f and 'ok' or e"), "=c");
32            format!("{:?}", r.map(|v| lua.to_string_lossy(v[0])))
33        }
34        _ => {
35            let mut lua = Lua::new(Limits::unmetered().memory(limit), Libs::NONE);
36            format!("{:?}", lua.load(&src, name).map(|_| ()))
37        }
38    };
39    let peak = hwm();
40    println!(
41        "{mode}: {outcome} in {:?}; peak {:.1} MB (before {:.1} MB) under {:.1} MiB: {:.2}x",
42        t.elapsed(),
43        peak as f64 / 1e6,
44        before as f64 / 1e6,
45        limit as f64 / 1048576.0,
46        peak as f64 / limit as f64
47    );
48}
examples/sechost.rs (line 15)
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}
examples/frontstop.rs (line 35)
23fn main() {
24    let mut args = std::env::args().skip(1);
25    let cases: Vec<String> = match args.next() {
26        Some(c) if c != "all" => vec![c],
27        _ => ["do", "dots", "flat", "locals", "keys", "strs"].iter().map(|s| (*s).to_owned()).collect(),
28    };
29    let points: u32 = args.next().and_then(|a| a.parse().ok()).unwrap_or(24);
30    // A third argument: interrupt only there (milliseconds into the load).
31    let only: Option<u64> = args.next().and_then(|a| a.parse().ok());
32    for case in cases {
33        let src = source(&case);
34        let full = {
35            let mut lua = Lua::new(Limits::unmetered().memory(8 << 30), Libs::NONE);
36            let t = Instant::now();
37            let r = lua.load(&src, "=t").map(|_| ());
38            let e = t.elapsed();
39            assert!(r.is_ok(), "{case}: {r:?}");
40            e
41        };
42        let mut worst = (Duration::ZERO, Duration::ZERO);
43        for k in 1..=points {
44            let at = only.map_or(full * k / (points + 1), Duration::from_millis);
45            let mut lua = Lua::new(Limits::unmetered().memory(8 << 30), Libs::NONE);
46            let h = lua.interrupt_handle();
47            let t = std::thread::spawn(move || {
48                std::thread::sleep(at);
49                h.interrupt();
50                Instant::now()
51            });
52            let started = Instant::now();
53            let r = lua.load(&src, "=t").map(|_| ());
54            let end = Instant::now();
55            let fired = t.join().unwrap();
56            if r.is_err() {
57                let late = end.saturating_duration_since(fired);
58                if std::env::var("FRONTSTOP_VERBOSE").is_ok() {
59                    println!("  at {at:?}: {late:?} late, {:?} into the load", fired.saturating_duration_since(started));
60                }
61                if late > worst.0 {
62                    worst = (late, at);
63                }
64            }
65            lua.interrupt_handle().reset();
66            let _ = lua.load("return 1", "=ok");
67        }
68        println!("{case:8} {:.1} MB, load {full:?}: worst {:?} late (interrupted at {:?})", src.len() as f64 / 1e6, worst.0, worst.1);
69    }
70}
Source

pub fn call_depth(self, n: usize) -> Self

Sets call_depth.

Source

pub fn native_depth(self, n: usize) -> Self

Sets native_depth.

Source

pub fn string_len(self, n: usize) -> Self

Sets string_len.

Examples found in repository?
examples/secprobe.rs (line 21)
19fn state(mem: usize, fast: bool) -> Lua {
20    let libs = Libs::ALL.union(Libs::DEBUG_INFO).union(Libs::REQUIRE);
21    let mut lua = Lua::new(Limits::default().memory(mem).string_len(32 << 20).fuel(1 << 34).hash_seed(7), libs);
22    lua.add_module("hostmod", "local M = {n = 1} for i = 1, 20 do M[i] = function() return i end end return M");
23    lua.set_fast_loop(fast);
24    lua.set_print(|_| {});
25    lua
26}
More examples
Hide additional examples
examples/seclat.rs (line 20)
10fn main() {
11    let a: Vec<String> = std::env::args().collect();
12    let setup = a.get(1).cloned().unwrap_or_default();
13    let body = a.get(2).cloned().unwrap_or_default();
14    let ms: u64 = a.get(3).and_then(|s| s.parse().ok()).unwrap_or(10);
15    let mem: usize = a.get(4).and_then(|s| s.parse().ok()).unwrap_or(512) << 20;
16    let libs = Libs::ALL.union(Libs::DEBUG_INFO).union(Libs::REQUIRE);
17    let mut worst = Duration::ZERO;
18    let mut last = String::new();
19    for _ in 0..5 {
20        let mut lua = Lua::new(Limits::default().memory(mem).string_len(64 << 20).fuel(1 << 40).hash_seed(7), libs);
21        lua.set_print(|_| {});
22        lua.exec(&setup, "=setup").unwrap();
23        let t0 = Instant::now();
24        let clock: remedy_lua::Clock = Arc::new(move || t0.elapsed());
25        lua.set_time_limit(Some((clock, Duration::from_millis(ms))));
26        let f = lua.load(&body, "=body").unwrap();
27        let start = Instant::now();
28        let r = lua.call(f.value(), &[]);
29        let el = start.elapsed();
30        worst = worst.max(el.saturating_sub(Duration::from_millis(ms)));
31        last = format!("{:?}", r.err());
32    }
33    println!("worst overrun {:?} past {ms} ms: {}", worst, &last[..last.len().min(120)]);
34}
Source

pub fn output(self, n: usize) -> Self

Sets output.

Source

pub fn stack_slots(self, n: usize) -> Self

Sets stack_slots.

Source

pub fn error_len(self, n: usize) -> Self

Sets error_len.

Source

pub fn stack_bytes(self, n: usize) -> Self

Sets stack_bytes.

Trait Implementations§

Source§

impl Clone for Limits

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Copy for Limits

Source§

impl Debug for Limits

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for Limits

Source§

fn default() -> Self

10 million steps, 64 MiB, 200 nested callbacks within 512 KiB of native stack, call frames and a stack bounded only by memory, 16 MiB strings, 1 MiB of output, 4 KiB messages.

Source§

impl Eq for Limits

Source§

impl PartialEq for Limits

Source§

fn eq(&self, other: &Self) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
Source§

impl StructuralPartialEq for Limits

Auto Trait Implementations§

§

impl Forget for Limits

§

impl Freeze for Limits

§

impl Move for Limits

§

impl RefUnwindSafe for Limits

§

impl Send for Limits

§

impl Sync for Limits

§

impl Unpin for Limits

§

impl UnsafeUnpin for Limits

§

impl UnwindSafe for Limits

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.