d6655d8c10
benilla-lua is a Lua 5.1.5 interpreter in Rust that speaks the 1.12.1 client's grammar. It is opt-in behind the `benilla-vm` feature, with `benilla-mlua`, the slice of mlua that benilla-ui uses, over it. The C build stays the default. Its front end ports 5.1.5's `lparser.c` and `lcode.c`, so registers, limits and messages match the C build's. Our finish on top: - the collector counts growth as C does, off the write path; - frames under a leaky generic `for` start nil, as `luaD_precall`; - the budget hook counts what C dispatches, and costs nothing when unset; - `__index` chains stop at 100; - mlua 0.11's conversions; - `vm_parity` answers recorded per platform. Tests: `vm_parity` on both VMs; the front-end corpus (8,543 chunks) against `string.dump`; 7,613 app and UI tests on benilla-lua. Built on macOS; Linux by CI. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Co-Authored-By: Sam <samuv.eth@gmail.com>
323 lines
11 KiB
Rust
323 lines
11 KiB
Rust
//! The instruction-budget hook: it reaches every loop a script can write, and code it runs does
|
|
//! not run it again.
|
|
|
|
use std::cell::Cell;
|
|
use std::rc::Rc;
|
|
|
|
use benilla_lua::Vm;
|
|
|
|
fn run(vm: &mut Vm, src: &str) -> String {
|
|
match vm.exec(src.as_bytes(), b"=t") {
|
|
Ok(v) => v.first().map_or(String::new(), |&v| vm.display(v)),
|
|
Err(e) => format!("<raised> {}", vm.display(e)),
|
|
}
|
|
}
|
|
|
|
/// A hook that raises once it has run `limit` times.
|
|
fn budget(vm: &mut Vm, limit: u32) -> Rc<Cell<u32>> {
|
|
let fired = Rc::new(Cell::new(0));
|
|
let seen = fired.clone();
|
|
vm.set_hook(
|
|
1000,
|
|
Rc::new(move |vm: &mut Vm| {
|
|
seen.set(seen.get() + 1);
|
|
if seen.get() >= limit {
|
|
let v = vm.str(b"budget");
|
|
return Err(vm.throw(v));
|
|
}
|
|
Ok(())
|
|
}),
|
|
);
|
|
fired
|
|
}
|
|
|
|
/// On a 2 MB thread, as the brief's crash tests run.
|
|
fn small_stack(f: impl FnOnce() + Send + 'static) {
|
|
std::thread::Builder::new()
|
|
.stack_size(2 << 20)
|
|
.spawn(f)
|
|
.unwrap()
|
|
.join()
|
|
.unwrap();
|
|
}
|
|
|
|
#[test]
|
|
fn the_budget_stops_a_tail_recursive_loop() {
|
|
small_stack(|| {
|
|
let mut vm = benilla_lua::new_state();
|
|
budget(&mut vm, 10);
|
|
assert_eq!(
|
|
run(
|
|
&mut vm,
|
|
"n = 0 local function f() n = n + 1 return f() end return f()"
|
|
),
|
|
"<raised> budget"
|
|
);
|
|
// Ten runs of a 1000-instruction step, five instructions a call.
|
|
let n = run(&mut vm, "return n").parse::<u32>().unwrap();
|
|
assert!((1900..=2100).contains(&n), "{n} tail calls ran");
|
|
});
|
|
}
|
|
|
|
#[test]
|
|
fn code_the_hook_runs_does_not_run_the_hook() {
|
|
small_stack(|| {
|
|
let mut vm = benilla_lua::new_state();
|
|
run(
|
|
&mut vm,
|
|
"function Busy() local s = 0 for i = 1, 100000 do s = s + i end return s end",
|
|
);
|
|
let fired = Rc::new(Cell::new(0u32));
|
|
let seen = fired.clone();
|
|
vm.set_hook(
|
|
100,
|
|
Rc::new(move |vm: &mut Vm| {
|
|
seen.set(seen.get() + 1);
|
|
let busy = vm.get_global("Busy");
|
|
vm.call_value(busy, &[], 1)?;
|
|
Ok(())
|
|
}),
|
|
);
|
|
assert_eq!(
|
|
run(
|
|
&mut vm,
|
|
"local s = 0 for i = 1, 10000 do s = s + i end return s"
|
|
),
|
|
"50005000"
|
|
);
|
|
// About one run per 100 instructions of the outer loop, none from `Busy`'s.
|
|
let n = fired.get();
|
|
assert!((10..=1000).contains(&n), "the hook ran {n} times");
|
|
});
|
|
}
|
|
|
|
/// The instructions `src` runs, counted by a hook at every one.
|
|
fn instructions(src: &str) -> u64 {
|
|
let mut vm = benilla_lua::new_state();
|
|
let n = Rc::new(Cell::new(0u64));
|
|
let seen = n.clone();
|
|
vm.set_hook(
|
|
1,
|
|
Rc::new(move |_: &mut Vm| {
|
|
seen.set(seen.get() + 1);
|
|
Ok(())
|
|
}),
|
|
);
|
|
let r = run(&mut vm, src);
|
|
assert!(!r.starts_with("<raised>"), "{r}");
|
|
n.get()
|
|
}
|
|
|
|
/// Each instruction a function runs counts, as 5.1's `LUA_MASKCOUNT` counts it: a call costs its
|
|
/// body, and Lua a library function calls (a `gsub` replacement, a `sort` comparator, `foreach`,
|
|
/// a metamethod, a generic `for`'s iterator) counts as any other.
|
|
#[test]
|
|
fn the_hook_counts_every_instruction_lua_runs() {
|
|
// `F` runs two more instructions a call than `f`, its two moves.
|
|
let fns = "local function f(x) return x end \
|
|
local function F(x) local a = x local b = a return b end ";
|
|
let it = "local function it(s, c) local x = c + 1 if x <= 100 then return x end end \
|
|
local function IT(s, c) local y = c local z = y local x = z + 1 if x <= 100 then return x end end ";
|
|
for (what, light, heavy, calls) in [
|
|
(
|
|
"a call",
|
|
"for i = 1, 100 do f(i) end",
|
|
"for i = 1, 100 do F(i) end",
|
|
100,
|
|
),
|
|
(
|
|
"gsub",
|
|
"string.gsub(string.rep('a', 100), 'a', f)",
|
|
"string.gsub(string.rep('a', 100), 'a', F)",
|
|
100,
|
|
),
|
|
(
|
|
"sort",
|
|
"table.sort({3, 1, 2}, function(a, b) return f(a) < b end)",
|
|
"table.sort({3, 1, 2}, function(a, b) return F(a) < b end)",
|
|
0,
|
|
),
|
|
(
|
|
"foreach",
|
|
"table.foreach({1, 2, 3, 4}, function(k, v) f(v) end)",
|
|
"table.foreach({1, 2, 3, 4}, function(k, v) F(v) end)",
|
|
4,
|
|
),
|
|
(
|
|
"__index",
|
|
"local t = setmetatable({}, {__index = f}) for i = 1, 50 do local _ = t.x end",
|
|
"local t = setmetatable({}, {__index = F}) for i = 1, 50 do local _ = t.x end",
|
|
50,
|
|
),
|
|
(
|
|
"iterator",
|
|
"for i in it, nil, 0 do end",
|
|
"for i in IT, nil, 0 do end",
|
|
101,
|
|
),
|
|
] {
|
|
let (a, b) = (
|
|
instructions(&format!("{fns}{it}{light}")),
|
|
instructions(&format!("{fns}{it}{heavy}")),
|
|
);
|
|
assert!(b > a, "{what}: {a} instructions, then {b}");
|
|
// `sort` calls its comparator as often as its algorithm needs: some number of times.
|
|
if what == "sort" {
|
|
assert_eq!((b - a) % 2, 0, "{what}: {a} instructions, then {b}");
|
|
} else {
|
|
assert_eq!(b - a, 2 * calls, "{what}: {a} instructions, then {b}");
|
|
}
|
|
}
|
|
}
|
|
|
|
/// A hook set by host code while Lua runs counts from the next loop back edge or call, as the
|
|
/// C build's counts from the next instruction: past the few instructions in between, the same.
|
|
#[test]
|
|
fn a_hook_set_while_lua_runs_counts_from_there() {
|
|
// The second runs in the VM's slow loop throughout: its generic `for` reads registers it
|
|
// has not written.
|
|
for src in [
|
|
"local s = 0 arm() for i = 1, 200 do if i > 100 then s = s + i else s = s - 1 end end \
|
|
local function f(x) return x end arm() for i = 1, 100 do f(i) end",
|
|
"for k in next, {1, 2}, nil, 1 do end local function g() local a = 1 end g() \
|
|
local s = 0 arm() for i = 1, 200 do if i > 100 then s = s + i else s = s - 1 end end \
|
|
local function f(x) return x end arm() for i = 1, 100 do f(i) end",
|
|
] {
|
|
counts_from_the_arming(src);
|
|
}
|
|
}
|
|
|
|
/// A loop whose back edge moves it to the VM's slow loop, a hook having been set, runs each
|
|
/// iteration once with its own index, whatever its step: the index is written before the jump.
|
|
#[test]
|
|
fn a_loop_moved_by_a_hook_keeps_its_index() {
|
|
for (src, sum) in [
|
|
(
|
|
"arm() local s = 0 for i = 10, 1, -1 do s = s + i end return s",
|
|
"55",
|
|
),
|
|
(
|
|
"arm() local s = 0 for i = 1, 20, 2 do s = s + i end return s",
|
|
"100",
|
|
),
|
|
(
|
|
"arm() local s = 0 for i = 1, 10 do s = s + i end return s",
|
|
"55",
|
|
),
|
|
] {
|
|
let mut vm = benilla_lua::new_state();
|
|
let arm = vm.new_host(
|
|
"arm",
|
|
Rc::new(|vm: &mut Vm, _| {
|
|
vm.set_hook(1 << 40, Rc::new(|_: &mut Vm| Ok(())));
|
|
Ok(0)
|
|
}),
|
|
);
|
|
vm.set_global("arm", arm);
|
|
assert_eq!(run(&mut vm, src), sum, "{src}");
|
|
}
|
|
}
|
|
|
|
fn counts_from_the_arming(src: &str) {
|
|
let ours = {
|
|
let mut vm = benilla_lua::new_state();
|
|
let n = Rc::new(Cell::new(0u64));
|
|
let seen = n.clone();
|
|
let arm = vm.new_host(
|
|
"arm",
|
|
Rc::new(move |vm: &mut Vm, _| {
|
|
let seen = seen.clone();
|
|
vm.set_hook(
|
|
1,
|
|
Rc::new(move |_: &mut Vm| {
|
|
seen.set(seen.get() + 1);
|
|
Ok(())
|
|
}),
|
|
);
|
|
Ok(0)
|
|
}),
|
|
);
|
|
vm.set_global("arm", arm);
|
|
let r = run(&mut vm, src);
|
|
assert!(!r.starts_with("<raised>"), "{r}");
|
|
n.get()
|
|
};
|
|
let c = {
|
|
let lua = mlua::Lua::new();
|
|
let n = std::sync::Arc::new(std::sync::atomic::AtomicU64::new(0));
|
|
let seen = n.clone();
|
|
let arm = lua
|
|
.create_function(move |lua, ()| {
|
|
let seen = seen.clone();
|
|
lua.set_hook(
|
|
mlua::HookTriggers {
|
|
every_nth_instruction: Some(1),
|
|
..Default::default()
|
|
},
|
|
move |_, _| {
|
|
seen.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
|
Ok(mlua::VmState::Continue)
|
|
},
|
|
)
|
|
})
|
|
.unwrap();
|
|
lua.globals().set("arm", arm).unwrap();
|
|
lua.load(src).exec().unwrap();
|
|
n.load(std::sync::atomic::Ordering::Relaxed)
|
|
};
|
|
assert!(
|
|
ours <= c && c - ours <= 10,
|
|
"{src}: ours {ours}, the C build's {c}"
|
|
);
|
|
}
|
|
|
|
/// What the C build's count hook counts for `src`, run at every instruction.
|
|
fn c_instructions(src: &str) -> u64 {
|
|
let lua = mlua::Lua::new();
|
|
let n = std::sync::Arc::new(std::sync::atomic::AtomicU64::new(0));
|
|
let seen = n.clone();
|
|
lua.set_hook(
|
|
mlua::HookTriggers {
|
|
every_nth_instruction: Some(1),
|
|
..Default::default()
|
|
},
|
|
move |_, _| {
|
|
seen.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
|
Ok(mlua::VmState::Continue)
|
|
},
|
|
)
|
|
.unwrap();
|
|
lua.load(src).exec().unwrap();
|
|
n.load(std::sync::atomic::Ordering::Relaxed)
|
|
}
|
|
|
|
/// The count at every instruction is the C build's: an instruction 5.1 never dispatches is not
|
|
/// counted (the jump a skipping `LOADBOOL` makes, the `LOADNIL` its frame clearing stands for, a
|
|
/// constant loaded into a scratch register), whichever way the code branches.
|
|
#[test]
|
|
fn the_count_is_the_c_builds() {
|
|
for src in [
|
|
"local x, y = 1, 2 local b = x < y",
|
|
"local x, y = 2, 1 local b = x < y",
|
|
"local x, y = 1, 2 for i = 1, 10 do local b = x < y local c = y < x end",
|
|
"table.sort({5, 3, 1, 4, 2, 9, 7}, function(a, b) return a < b end)",
|
|
"local function f() local a, b return a end for i = 1, 10 do f() end",
|
|
"local b = 'a' < 'b'",
|
|
"local x = 'a' .. 'b'",
|
|
"local x = 1 local y = x == 1",
|
|
"local t = {1, 2, 3} for k, v in pairs(t) do end",
|
|
"local t = {1, 2, 3} for k in next, t do end",
|
|
"local function it(s, c) if c < 5 then return c + 1 end end for i in it, nil, 0 do end",
|
|
"local t = {} for i = 1, 5 do t[i] = i end local s = 0 for i = 5, 1, -1 do s = s + t[i] end",
|
|
"local a = nil local b = a and 1 or 2 local c = a or 3 local d = not a",
|
|
"local function f(...) return arg.n end f(1, 2, 3)",
|
|
"local t = {1, 2, 3, x = 1, y = 2}",
|
|
"local x = 0 while x < 5 do x = x + 1 end repeat x = x - 1 until x == 0",
|
|
"local n = 0 for i = 1, 20 do if math.mod(i, 3) == 0 then n = n + 1 elseif i > 10 then n = n - 1 else n = n * 2 end end",
|
|
"string.gsub('abcabc', 'b', function(c) return c == 'b' and 'x' or c end)",
|
|
"local t = setmetatable({}, {__index = function(t, k) return k > 2 end}) for i = 1, 5 do local _ = t[i] end",
|
|
] {
|
|
assert_eq!(instructions(src), c_instructions(src), "{src}");
|
|
}
|
|
}
|