diff --git a/CHANGELOG.md b/CHANGELOG.md index c26f0ca..aa30d65 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -55,6 +55,13 @@ is in the [`1.0.0-rc.0`](#100-rc0---2026-05-26) entry below. past the ceiling in a single allocation. Each raises the same catchable `"resulting string too large"` error as `string.rep` and `..`, before the result is built (#425). +- `:max_instructions` now bounds `goto` loops, and keeps the work done in + metamethods and before an error trapped by `pcall` (#411). +- `:max_call_depth` and `:max_instructions` count each re-entry into Lua from + native code (`pcall`, `table.sort` comparators, `gsub` callbacks, + metamethods, `__call`, `Lua.call_function/3`), so recursion through them + raises `"stack overflow"` instead of exhausting the host. +- A `__call` chain through callable tables is hop-limited like `__index`. ## [1.0.2] - 2026-07-28 diff --git a/lib/lua.ex b/lib/lua.ex index 242d83c..cc91d0e 100644 --- a/lib/lua.ex +++ b/lib/lua.ex @@ -90,7 +90,8 @@ defmodule Lua do * `:max_call_depth` - (default `:infinity`) caps the depth of nested function calls. When a script recurses deeper than this, a catchable `"stack overflow"` runtime error is raised instead of letting the recursion exhaust the host process. Accepts a positive integer or - `:infinity` for no limit. + `:infinity` for no limit. Functions called from library code (`pcall`, `table.sort`, + `string.gsub`, metamethods, `__call`) count like direct calls. Note: this VM does not implement proper tail-call optimization, so a call in tail position (`return f(x)`) consumes a frame like any other call. A finite `:max_call_depth` therefore @@ -849,14 +850,33 @@ defmodule Lua do end end - defp do_call_function({:native_func, fun}, args, state) do - {results, new_state} = fun.(args, state) - {:ok, List.wrap(results), new_state} + defp do_call_function({:native_func, _} = native, args, state), do: charge_and_call(native, args, state) + defp do_call_function({:lua_closure, _, _} = closure, args, state), do: charge_and_call(closure, args, state) + defp do_call_function({:compiled_closure, _, _} = closure, args, state), do: charge_and_call(closure, args, state) + + # A resolved tuple that isn't one of the callable shapes above — e.g. a + # table or userdata reference. No name is available at this layer, so the + # error is reported by type without a name hint. + # + # This is one place the programmatic boundary does *not* mirror the in-Lua + # `:call` opcode: a table carrying a `__call` metamethod is reported as + # "attempt to call a table value" here rather than invoking the metamethod. + # `call_function/3` is a by-name function-call entry point, not a general + # value-application path, so callable tables are out of scope (and the prior + # implementation errored on them too). + defp do_call_function(other, _args, state) do + {:error, Executor.call_type_error(other, nil, state), state} + end + + # Host callbacks re-enter Lua through here, so the callee is charged like a library callback. + defp charge_and_call(function, args, %State{call_depth: call_depth} = state) do + {results, new_state} = call_uncharged(function, args, State.charge_call!(state)) + {:ok, results, %{new_state | call_depth: call_depth}} rescue e -> {:error, e, recover_state(e, state)} end - defp do_call_function({:lua_closure, proto, upvalues}, args, state) do + defp call_uncharged({:lua_closure, proto, upvalues}, args, state) do callee_regs = Tuple.duplicate(nil, max(proto.max_registers, proto.param_count) + 64) callee_regs = @@ -869,33 +889,10 @@ defmodule Lua do {results, _regs, new_state} = Executor.execute(proto.instructions, callee_regs, upvalues, proto, state) - {:ok, results, new_state} - rescue - e -> {:error, e, recover_state(e, state)} - end - - defp do_call_function({:compiled_closure, _, _} = closure, args, state) do - # Compiled callees route through the dispatcher; same observable - # contract as the interpreter branch above. - {results, new_state} = Executor.call_function(closure, args, state) - {:ok, results, new_state} - rescue - e -> {:error, e, recover_state(e, state)} + {results, new_state} end - # A resolved tuple that isn't one of the callable shapes above — e.g. a - # table or userdata reference. No name is available at this layer, so the - # error is reported by type without a name hint. - # - # This is one place the programmatic boundary does *not* mirror the in-Lua - # `:call` opcode: a table carrying a `__call` metamethod is reported as - # "attempt to call a table value" here rather than invoking the metamethod. - # `call_function/3` is a by-name function-call entry point, not a general - # value-application path, so callable tables are out of scope (and the prior - # implementation errored on them too). - defp do_call_function(other, _args, state) do - {:error, Executor.call_type_error(other, nil, state), state} - end + defp call_uncharged(function, args, state), do: Executor.call_function_uncharged(function, args, state) # This is a protected-call boundary like pcall: trapping the error # unwinds control state, but heap effects the callee made before raising diff --git a/lib/lua/compiler/bytecode.ex b/lib/lua/compiler/bytecode.ex index e12fd66..5e2a6ad 100644 --- a/lib/lua/compiler/bytecode.ex +++ b/lib/lua/compiler/bytecode.ex @@ -145,6 +145,9 @@ defmodule Lua.Compiler.Bytecode do # `Lua.Compiler.Peephole` emits the instruction; codegen never does. @op_call_self 76 + # A `goto` to a preceding label: `@op_goto` that also ticks `:max_instructions`. + @op_goto_back 77 + # The call opcodes whose tuple is `{tag, base, name_hint}` before # `annotate_line/2` bakes the source line in. @static_arity_calls [ @@ -591,8 +594,8 @@ defmodule Lua.Compiler.Bytecode do # Illegal gotos (undefined / out-of-scope target) are rejected up front by # `Lua.Compiler.GotoValidation` as a compile error, so resolution always # succeeds here. - {:ok, depth, target_pc, level} = resolve_goto_target(name, block_path, labels, pc, ancestors) - {@op_goto, depth, target_pc, level} + {:ok, op, depth, target_pc, level} = resolve_goto_target(name, block_path, labels, pc, ancestors) + {op, depth, target_pc, level} end defp resolve_entry({@op_test, reg, then_bc, else_bc}, pc, labels, ancestors) do @@ -620,7 +623,7 @@ defmodule Lua.Compiler.Bytecode do defp resolve_goto_target(name, goto_path, labels, from_pc, ancestors) do case find_label(labels, name, goto_path, from_pc) do - {:ok, target_pc, level} -> {:ok, 0, target_pc, level} + {:ok, target_pc, level} -> {:ok, goto_op(target_pc, from_pc), 0, target_pc, level} :error -> resolve_in_ancestors(name, goto_path, ancestors, 0) end end @@ -631,11 +634,15 @@ defmodule Lua.Compiler.Bytecode do depth = depth + weight case find_label(labels, name, goto_path, from_pc) do - {:ok, target_pc, level} -> {:ok, depth, target_pc, level} + {:ok, target_pc, level} -> {:ok, goto_op(target_pc, from_pc), depth, target_pc, level} :error -> resolve_in_ancestors(name, goto_path, rest, depth) end end + # `from_pc` is the goto's own pc, or the enclosing construct's in an ancestor. + defp goto_op(target_pc, from_pc) when target_pc < from_pc, do: @op_goto_back + defp goto_op(_target_pc, _from_pc), do: @op_goto + # Nearest visible label after `from_pc`, else nearest before — matching the # interpreter's `GotoResolution`. A label is visible when its block path is # a prefix of the goto's, excluding nested and sibling `do` blocks flattened @@ -730,6 +737,7 @@ defmodule Lua.Compiler.Bytecode do def op_set_list_multi, do: @op_set_list_multi def op_label, do: @op_label def op_goto, do: @op_goto + def op_goto_back, do: @op_goto_back def op_add_k, do: @op_add_k def op_subtract_k, do: @op_subtract_k def op_multiply_k, do: @op_multiply_k diff --git a/lib/lua/compiler/goto_resolution.ex b/lib/lua/compiler/goto_resolution.ex index 8f0a83e..af702df 100644 --- a/lib/lua/compiler/goto_resolution.ex +++ b/lib/lua/compiler/goto_resolution.ex @@ -7,7 +7,7 @@ defmodule Lua.Compiler.GotoResolution do neither scan backward nor reach an enclosing block at run time. This pass resolves every goto up front, rewriting `{:goto, name}` to `{:goto, id}` and recording in `proto.goto_targets` an entry - `id => {depth, level, target_tail}`: + `id => {depth, level, target_tail, direction}`: * `depth` — the number of `cont` entries the interpreter drops to leave the blocks between the goto and its target. A `:test` branch pushes one @@ -24,6 +24,9 @@ defmodule Lua.Compiler.GotoResolution do * `target_tail` — the instruction sublist immediately after the matching `{:label, name, level}` in its owning block. + * `direction` — `:backward` when the label precedes the goto, a loop + back-edge that ticks `:max_instructions`; otherwise `:forward`. + Label scope (Lua 5.3 §3.3.4): a goto targets a label in its own block or an enclosing one, never inside a nested block or a sibling block. `do` blocks are flattened by codegen into the parent's instruction list, so several @@ -123,8 +126,8 @@ defmodule Lua.Compiler.GotoResolution do {name, block_path} = Map.fetch!(names, id) case resolve_target(name, block_path, block, idx, ancestors) do - {:ok, depth, level, tail} -> - Map.put(targets, id, {depth, level, tail}) + {:ok, depth, level, tail, direction} -> + Map.put(targets, id, {depth, level, tail, direction}) # Unresolved gotos are rejected up front by `Lua.Compiler.GotoValidation` # as a compile error, so this branch is unreachable in practice; leaving @@ -161,13 +164,13 @@ defmodule Lua.Compiler.GotoResolution do defp resolve_instr(_other, _idx, _block, _ancestors, targets, _names), do: targets # Search the current block, then each enclosing block, summing `cont` - # weights along the way. Returns `{:ok, depth, level, target_tail}` where - # `level` is the target label's scope register level (the goto's close - # threshold). `goto_path` is the goto's lexical block path; only labels in - # the goto's own block or an enclosing one are visible. + # weights along the way. Returns `{:ok, depth, level, target_tail, + # direction}` where `level` is the target label's scope register level (the + # goto's close threshold). `goto_path` is the goto's lexical block path; only + # labels in the goto's own block or an enclosing one are visible. defp resolve_target(name, goto_path, block, idx, ancestors) do case find_label_pos(block, name, goto_path, idx) do - {:ok, pos, level} -> {:ok, 0, level, Enum.drop(block, pos + 1)} + {:ok, pos, level} -> {:ok, 0, level, Enum.drop(block, pos + 1), direction(pos, idx)} :error -> resolve_in_ancestors(name, goto_path, ancestors, 0) end end @@ -178,11 +181,14 @@ defmodule Lua.Compiler.GotoResolution do depth = depth + weight case find_label_pos(parent_block, name, goto_path, child_idx) do - {:ok, pos, level} -> {:ok, depth, level, Enum.drop(parent_block, pos + 1)} + {:ok, pos, level} -> {:ok, depth, level, Enum.drop(parent_block, pos + 1), direction(pos, child_idx)} :error -> resolve_in_ancestors(name, goto_path, rest, depth) end end + defp direction(label_pos, from) when label_pos < from, do: :backward + defp direction(_label_pos, _from), do: :forward + # The visible label nearest after `from`, else the nearest before it. A # label is visible when its block path is a prefix of the goto's path (the # label is in the goto's block or one enclosing it) — this excludes nested diff --git a/lib/lua/compiler/prototype.ex b/lib/lua/compiler/prototype.ex index a6d0933..2ade6d6 100644 --- a/lib/lua/compiler/prototype.ex +++ b/lib/lua/compiler/prototype.ex @@ -24,7 +24,7 @@ defmodule Lua.Compiler.Prototype do lines: {non_neg_integer(), non_neg_integer()}, bytecode: tuple() | nil, goto_targets: %{ - non_neg_integer() => {non_neg_integer(), non_neg_integer(), [instruction()]} + non_neg_integer() => {non_neg_integer(), non_neg_integer(), [instruction()], :forward | :backward} } } diff --git a/lib/lua/vm/dispatcher.ex b/lib/lua/vm/dispatcher.ex index e04d96b..b8afd89 100644 --- a/lib/lua/vm/dispatcher.ex +++ b/lib/lua/vm/dispatcher.ex @@ -153,6 +153,9 @@ defmodule Lua.VM.Dispatcher do # the loop already holds everything the call needs. @op_call_self 76 + # A `goto` to a preceding label: `@op_goto` that also ticks `:max_instructions`. + @op_goto_back 77 + @doc """ Execute a compiled prototype against `args` and `state`. """ @@ -251,8 +254,8 @@ defmodule Lua.VM.Dispatcher do # # `frames` holds dispatcher-side call frames for in-mode calls. Out-of- # mode calls (compiled → interpreted) bridge through - # `Executor.call_function/3` instead, paying one Erlang stack frame - # at the boundary. + # `Executor.call_function_uncharged/3` instead, paying one Erlang stack + # frame at the boundary. defp dispatch(code, pc, regs, upvalues, proto, state, cont, frames, instruction_count, cs, cd, ou) when pc > tuple_size(code) do @@ -329,7 +332,13 @@ defmodule Lua.VM.Dispatcher do _ -> {value, state} = - Executor.dispatcher_get_field(table_val, name, sync(state, cs, cd), proto, name_hint) + Executor.dispatcher_get_field( + table_val, + name, + sync(state, cs, cd, instruction_count), + proto, + name_hint + ) regs = :erlang.setelement(dest + 1, regs, value) dispatch(code, pc + 1, regs, upvalues, proto, state, cont, frames, instruction_count, cs, cd, ou) @@ -338,7 +347,7 @@ defmodule Lua.VM.Dispatcher do _ -> {value, state} = - Executor.dispatcher_get_field(table_val, name, sync(state, cs, cd), proto, name_hint) + Executor.dispatcher_get_field(table_val, name, sync(state, cs, cd, instruction_count), proto, name_hint) regs = :erlang.setelement(dest + 1, regs, value) dispatch(code, pc + 1, regs, upvalues, proto, state, cont, frames, instruction_count, cs, cd, ou) @@ -369,7 +378,13 @@ defmodule Lua.VM.Dispatcher do _ -> {value, state} = - Executor.dispatcher_get_field(table_val, name, sync(state, cs, cd), proto, name_hint) + Executor.dispatcher_get_field( + table_val, + name, + sync(state, cs, cd, instruction_count), + proto, + name_hint + ) regs = :erlang.setelement(dest + 1, regs, value) dispatch(code, pc + 1, regs, upvalues, proto, state, cont, frames, instruction_count, cs, cd, ou) @@ -378,7 +393,7 @@ defmodule Lua.VM.Dispatcher do _ -> {value, state} = - Executor.dispatcher_get_field(table_val, name, sync(state, cs, cd), proto, name_hint) + Executor.dispatcher_get_field(table_val, name, sync(state, cs, cd, instruction_count), proto, name_hint) regs = :erlang.setelement(dest + 1, regs, value) dispatch(code, pc + 1, regs, upvalues, proto, state, cont, frames, instruction_count, cs, cd, ou) @@ -401,13 +416,27 @@ defmodule Lua.VM.Dispatcher do %{state | tables: :maps.put(id, Table.put(table, name, value), state.tables)} _ -> - Executor.dispatcher_set_field(table_val, name, value, sync(state, cs, cd), proto, name_hint) + Executor.dispatcher_set_field( + table_val, + name, + value, + sync(state, cs, cd, instruction_count), + proto, + name_hint + ) end dispatch(code, pc + 1, regs, upvalues, proto, state, cont, frames, instruction_count, cs, cd, ou) _ -> - Executor.dispatcher_set_field(table_val, name, value, sync(state, cs, cd), proto, name_hint) + Executor.dispatcher_set_field( + table_val, + name, + value, + sync(state, cs, cd, instruction_count), + proto, + name_hint + ) end # ── Arithmetic ────────────────────────────────────────────────── @@ -433,7 +462,9 @@ defmodule Lua.VM.Dispatcher do dispatch(code, pc + 1, regs, upvalues, proto, state, cont, frames, instruction_count, cs, cd, ou) true -> - {value, state} = Executor.dispatcher_binop(:add, va, vb, sync(state, cs, cd), proto, hint_a, hint_b) + {value, state} = + Executor.dispatcher_binop(:add, va, vb, sync(state, cs, cd, instruction_count), proto, hint_a, hint_b) + regs = :erlang.setelement(dest + 1, regs, value) dispatch(code, pc + 1, regs, upvalues, proto, state, cont, frames, instruction_count, cs, cd, ou) end @@ -454,7 +485,9 @@ defmodule Lua.VM.Dispatcher do dispatch(code, pc + 1, regs, upvalues, proto, state, cont, frames, instruction_count, cs, cd, ou) true -> - {value, state} = Executor.dispatcher_binop(:subtract, va, vb, sync(state, cs, cd), proto, hint_a, hint_b) + {value, state} = + Executor.dispatcher_binop(:subtract, va, vb, sync(state, cs, cd, instruction_count), proto, hint_a, hint_b) + regs = :erlang.setelement(dest + 1, regs, value) dispatch(code, pc + 1, regs, upvalues, proto, state, cont, frames, instruction_count, cs, cd, ou) end @@ -475,7 +508,9 @@ defmodule Lua.VM.Dispatcher do dispatch(code, pc + 1, regs, upvalues, proto, state, cont, frames, instruction_count, cs, cd, ou) true -> - {value, state} = Executor.dispatcher_binop(:multiply, va, vb, sync(state, cs, cd), proto, hint_a, hint_b) + {value, state} = + Executor.dispatcher_binop(:multiply, va, vb, sync(state, cs, cd, instruction_count), proto, hint_a, hint_b) + regs = :erlang.setelement(dest + 1, regs, value) dispatch(code, pc + 1, regs, upvalues, proto, state, cont, frames, instruction_count, cs, cd, ou) end @@ -502,7 +537,9 @@ defmodule Lua.VM.Dispatcher do dispatch(code, pc + 1, regs, upvalues, proto, state, cont, frames, instruction_count, cs, cd, ou) true -> - {value, state} = Executor.dispatcher_binop(:add, va, k, sync(state, cs, cd), proto, hint_a, nil) + {value, state} = + Executor.dispatcher_binop(:add, va, k, sync(state, cs, cd, instruction_count), proto, hint_a, nil) + regs = :erlang.setelement(dest + 1, regs, value) dispatch(code, pc + 1, regs, upvalues, proto, state, cont, frames, instruction_count, cs, cd, ou) end @@ -522,7 +559,9 @@ defmodule Lua.VM.Dispatcher do dispatch(code, pc + 1, regs, upvalues, proto, state, cont, frames, instruction_count, cs, cd, ou) true -> - {value, state} = Executor.dispatcher_binop(:subtract, va, k, sync(state, cs, cd), proto, hint_a, nil) + {value, state} = + Executor.dispatcher_binop(:subtract, va, k, sync(state, cs, cd, instruction_count), proto, hint_a, nil) + regs = :erlang.setelement(dest + 1, regs, value) dispatch(code, pc + 1, regs, upvalues, proto, state, cont, frames, instruction_count, cs, cd, ou) end @@ -542,7 +581,9 @@ defmodule Lua.VM.Dispatcher do dispatch(code, pc + 1, regs, upvalues, proto, state, cont, frames, instruction_count, cs, cd, ou) true -> - {value, state} = Executor.dispatcher_binop(:multiply, va, k, sync(state, cs, cd), proto, hint_a, nil) + {value, state} = + Executor.dispatcher_binop(:multiply, va, k, sync(state, cs, cd, instruction_count), proto, hint_a, nil) + regs = :erlang.setelement(dest + 1, regs, value) dispatch(code, pc + 1, regs, upvalues, proto, state, cont, frames, instruction_count, cs, cd, ou) end @@ -553,7 +594,7 @@ defmodule Lua.VM.Dispatcher do :divide, :erlang.element(a + 1, regs), :erlang.element(b + 1, regs), - sync(state, cs, cd), + sync(state, cs, cd, instruction_count), proto, hint_a, hint_b @@ -568,7 +609,7 @@ defmodule Lua.VM.Dispatcher do :floor_divide, :erlang.element(a + 1, regs), :erlang.element(b + 1, regs), - sync(state, cs, cd), + sync(state, cs, cd, instruction_count), proto, hint_a, hint_b @@ -583,7 +624,7 @@ defmodule Lua.VM.Dispatcher do :modulo, :erlang.element(a + 1, regs), :erlang.element(b + 1, regs), - sync(state, cs, cd), + sync(state, cs, cd, instruction_count), proto, hint_a, hint_b @@ -598,7 +639,7 @@ defmodule Lua.VM.Dispatcher do :power, :erlang.element(a + 1, regs), :erlang.element(b + 1, regs), - sync(state, cs, cd), + sync(state, cs, cd, instruction_count), proto, hint_a, hint_b @@ -609,7 +650,13 @@ defmodule Lua.VM.Dispatcher do {@op_negate, dest, src, hint} -> {value, state} = - Executor.dispatcher_unop(:negate, :erlang.element(src + 1, regs), sync(state, cs, cd), proto, hint) + Executor.dispatcher_unop( + :negate, + :erlang.element(src + 1, regs), + sync(state, cs, cd, instruction_count), + proto, + hint + ) regs = :erlang.setelement(dest + 1, regs, value) dispatch(code, pc + 1, regs, upvalues, proto, state, cont, frames, instruction_count, cs, cd, ou) @@ -638,7 +685,9 @@ defmodule Lua.VM.Dispatcher do regs = :erlang.setelement(dest + 1, regs, Numeric.to_signed_int64(Bitwise.band(va, vb))) dispatch(code, pc + 1, regs, upvalues, proto, state, cont, frames, instruction_count, cs, cd, ou) else - {value, state} = Executor.dispatcher_bitwise(:band, va, vb, sync(state, cs, cd), proto, hint_a, hint_b) + {value, state} = + Executor.dispatcher_bitwise(:band, va, vb, sync(state, cs, cd, instruction_count), proto, hint_a, hint_b) + regs = :erlang.setelement(dest + 1, regs, value) dispatch(code, pc + 1, regs, upvalues, proto, state, cont, frames, instruction_count, cs, cd, ou) end @@ -651,7 +700,9 @@ defmodule Lua.VM.Dispatcher do regs = :erlang.setelement(dest + 1, regs, Numeric.to_signed_int64(Bitwise.bor(va, vb))) dispatch(code, pc + 1, regs, upvalues, proto, state, cont, frames, instruction_count, cs, cd, ou) else - {value, state} = Executor.dispatcher_bitwise(:bor, va, vb, sync(state, cs, cd), proto, hint_a, hint_b) + {value, state} = + Executor.dispatcher_bitwise(:bor, va, vb, sync(state, cs, cd, instruction_count), proto, hint_a, hint_b) + regs = :erlang.setelement(dest + 1, regs, value) dispatch(code, pc + 1, regs, upvalues, proto, state, cont, frames, instruction_count, cs, cd, ou) end @@ -664,7 +715,9 @@ defmodule Lua.VM.Dispatcher do regs = :erlang.setelement(dest + 1, regs, Numeric.to_signed_int64(Bitwise.bxor(va, vb))) dispatch(code, pc + 1, regs, upvalues, proto, state, cont, frames, instruction_count, cs, cd, ou) else - {value, state} = Executor.dispatcher_bitwise(:bxor, va, vb, sync(state, cs, cd), proto, hint_a, hint_b) + {value, state} = + Executor.dispatcher_bitwise(:bxor, va, vb, sync(state, cs, cd, instruction_count), proto, hint_a, hint_b) + regs = :erlang.setelement(dest + 1, regs, value) dispatch(code, pc + 1, regs, upvalues, proto, state, cont, frames, instruction_count, cs, cd, ou) end @@ -672,20 +725,26 @@ defmodule Lua.VM.Dispatcher do {@op_shift_left, dest, a, b, hint_a, hint_b} -> va = :erlang.element(a + 1, regs) vb = :erlang.element(b + 1, regs) - {value, state} = Executor.dispatcher_bitwise(:shl, va, vb, sync(state, cs, cd), proto, hint_a, hint_b) + + {value, state} = + Executor.dispatcher_bitwise(:shl, va, vb, sync(state, cs, cd, instruction_count), proto, hint_a, hint_b) + regs = :erlang.setelement(dest + 1, regs, value) dispatch(code, pc + 1, regs, upvalues, proto, state, cont, frames, instruction_count, cs, cd, ou) {@op_shift_right, dest, a, b, hint_a, hint_b} -> va = :erlang.element(a + 1, regs) vb = :erlang.element(b + 1, regs) - {value, state} = Executor.dispatcher_bitwise(:shr, va, vb, sync(state, cs, cd), proto, hint_a, hint_b) + + {value, state} = + Executor.dispatcher_bitwise(:shr, va, vb, sync(state, cs, cd, instruction_count), proto, hint_a, hint_b) + regs = :erlang.setelement(dest + 1, regs, value) dispatch(code, pc + 1, regs, upvalues, proto, state, cont, frames, instruction_count, cs, cd, ou) {@op_bitwise_not, dest, src, hint} -> val = :erlang.element(src + 1, regs) - {value, state} = Executor.dispatcher_bnot(val, sync(state, cs, cd), proto, hint) + {value, state} = Executor.dispatcher_bnot(val, sync(state, cs, cd, instruction_count), proto, hint) regs = :erlang.setelement(dest + 1, regs, value) dispatch(code, pc + 1, regs, upvalues, proto, state, cont, frames, instruction_count, cs, cd, ou) @@ -705,7 +764,7 @@ defmodule Lua.VM.Dispatcher do dispatch(code, pc + 1, regs, upvalues, proto, state, cont, frames, instruction_count, cs, cd, ou) true -> - {value, state} = Executor.dispatcher_cmp(:less_than, va, vb, sync(state, cs, cd), proto) + {value, state} = Executor.dispatcher_cmp(:less_than, va, vb, sync(state, cs, cd, instruction_count), proto) regs = :erlang.setelement(dest + 1, regs, value) dispatch(code, pc + 1, regs, upvalues, proto, state, cont, frames, instruction_count, cs, cd, ou) end @@ -724,7 +783,7 @@ defmodule Lua.VM.Dispatcher do dispatch(code, pc + 1, regs, upvalues, proto, state, cont, frames, instruction_count, cs, cd, ou) true -> - {value, state} = Executor.dispatcher_cmp(:less_equal, va, vb, sync(state, cs, cd), proto) + {value, state} = Executor.dispatcher_cmp(:less_equal, va, vb, sync(state, cs, cd, instruction_count), proto) regs = :erlang.setelement(dest + 1, regs, value) dispatch(code, pc + 1, regs, upvalues, proto, state, cont, frames, instruction_count, cs, cd, ou) end @@ -743,7 +802,7 @@ defmodule Lua.VM.Dispatcher do dispatch(code, pc + 1, regs, upvalues, proto, state, cont, frames, instruction_count, cs, cd, ou) true -> - {value, state} = Executor.dispatcher_cmp(:greater_than, va, vb, sync(state, cs, cd), proto) + {value, state} = Executor.dispatcher_cmp(:greater_than, va, vb, sync(state, cs, cd, instruction_count), proto) regs = :erlang.setelement(dest + 1, regs, value) dispatch(code, pc + 1, regs, upvalues, proto, state, cont, frames, instruction_count, cs, cd, ou) end @@ -762,7 +821,9 @@ defmodule Lua.VM.Dispatcher do dispatch(code, pc + 1, regs, upvalues, proto, state, cont, frames, instruction_count, cs, cd, ou) true -> - {value, state} = Executor.dispatcher_cmp(:greater_equal, va, vb, sync(state, cs, cd), proto) + {value, state} = + Executor.dispatcher_cmp(:greater_equal, va, vb, sync(state, cs, cd, instruction_count), proto) + regs = :erlang.setelement(dest + 1, regs, value) dispatch(code, pc + 1, regs, upvalues, proto, state, cont, frames, instruction_count, cs, cd, ou) end @@ -781,7 +842,7 @@ defmodule Lua.VM.Dispatcher do dispatch(code, pc + 1, regs, upvalues, proto, state, cont, frames, instruction_count, cs, cd, ou) true -> - {value, state} = Executor.dispatcher_cmp(:equal, va, vb, sync(state, cs, cd), proto) + {value, state} = Executor.dispatcher_cmp(:equal, va, vb, sync(state, cs, cd, instruction_count), proto) regs = :erlang.setelement(dest + 1, regs, value) dispatch(code, pc + 1, regs, upvalues, proto, state, cont, frames, instruction_count, cs, cd, ou) end @@ -800,7 +861,7 @@ defmodule Lua.VM.Dispatcher do dispatch(code, pc + 1, regs, upvalues, proto, state, cont, frames, instruction_count, cs, cd, ou) true -> - {value, state} = Executor.dispatcher_cmp(:not_equal, va, vb, sync(state, cs, cd), proto) + {value, state} = Executor.dispatcher_cmp(:not_equal, va, vb, sync(state, cs, cd, instruction_count), proto) regs = :erlang.setelement(dest + 1, regs, value) dispatch(code, pc + 1, regs, upvalues, proto, state, cont, frames, instruction_count, cs, cd, ou) end @@ -825,7 +886,7 @@ defmodule Lua.VM.Dispatcher do dispatch(code, pc + 1, regs, upvalues, proto, state, cont, frames, instruction_count, cs, cd, ou) true -> - {value, state} = Executor.dispatcher_cmp(:less_than, va, k, sync(state, cs, cd), proto) + {value, state} = Executor.dispatcher_cmp(:less_than, va, k, sync(state, cs, cd, instruction_count), proto) regs = :erlang.setelement(dest + 1, regs, value) dispatch(code, pc + 1, regs, upvalues, proto, state, cont, frames, instruction_count, cs, cd, ou) end @@ -843,7 +904,7 @@ defmodule Lua.VM.Dispatcher do dispatch(code, pc + 1, regs, upvalues, proto, state, cont, frames, instruction_count, cs, cd, ou) true -> - {value, state} = Executor.dispatcher_cmp(:less_equal, va, k, sync(state, cs, cd), proto) + {value, state} = Executor.dispatcher_cmp(:less_equal, va, k, sync(state, cs, cd, instruction_count), proto) regs = :erlang.setelement(dest + 1, regs, value) dispatch(code, pc + 1, regs, upvalues, proto, state, cont, frames, instruction_count, cs, cd, ou) end @@ -861,7 +922,7 @@ defmodule Lua.VM.Dispatcher do dispatch(code, pc + 1, regs, upvalues, proto, state, cont, frames, instruction_count, cs, cd, ou) true -> - {value, state} = Executor.dispatcher_cmp(:equal, va, k, sync(state, cs, cd), proto) + {value, state} = Executor.dispatcher_cmp(:equal, va, k, sync(state, cs, cd, instruction_count), proto) regs = :erlang.setelement(dest + 1, regs, value) dispatch(code, pc + 1, regs, upvalues, proto, state, cont, frames, instruction_count, cs, cd, ou) end @@ -900,8 +961,9 @@ defmodule Lua.VM.Dispatcher do # `print(x)`): results are discarded. `:compiled_closure` callees # stay in the dispatcher via the frame stack — no Erlang stack # growth. Everything else bridges to the interpreter through - # `Executor.call_function/3`, which grows the Erlang stack by one - # frame at the mode boundary. + # `Executor.call_function_uncharged/3` (interpreted closures) or + # `Executor.dispatcher_call_function/6`, which grow the Erlang stack + # by one frame at the mode boundary. # # The `:discard` sentinel in the frame's `base` slot signals # "throw the return value away"; `return_one/3` skips its @@ -921,7 +983,7 @@ defmodule Lua.VM.Dispatcher do frame = {code, pc + 1, regs, upvalues, proto, cont, :discard, ou} call_info = {proto.source, 0, name_hint} instruction_count = tick(state, instruction_count, cs, cd) - ckdepth(state, cs, cd) + ckdepth(state, cs, cd, instruction_count) dispatch( callee_proto.bytecode, @@ -975,7 +1037,7 @@ defmodule Lua.VM.Dispatcher do frame = {code, pc + 1, regs, upvalues, proto, cont, base, ou} call_info = {proto.source, 0, name_hint} instruction_count = tick(state, instruction_count, cs, cd) - ckdepth(state, cs, cd) + ckdepth(state, cs, cd, instruction_count) dispatch( callee_proto.bytecode, @@ -1037,7 +1099,7 @@ defmodule Lua.VM.Dispatcher do frame = {code, pc + 1, regs, upvalues, proto, cont, base, ou} call_info = {proto.source, 0, name_hint} instruction_count = tick(state, instruction_count, cs, cd) - ckdepth(state, cs, cd) + ckdepth(state, cs, cd, instruction_count) dispatch( callee_proto.bytecode, @@ -1090,7 +1152,7 @@ defmodule Lua.VM.Dispatcher do frame = {code, pc + 1, regs, upvalues, proto, cont, base, ou} call_info = {proto.source, 0, name_hint} instruction_count = tick(state, instruction_count, cs, cd) - ckdepth(state, cs, cd) + ckdepth(state, cs, cd, instruction_count) dispatch( callee_proto.bytecode, @@ -1144,7 +1206,7 @@ defmodule Lua.VM.Dispatcher do frame = {code, pc + 1, regs, upvalues, proto, cont, base, ou} call_info = {proto.source, 0, name_hint} instruction_count = tick(state, instruction_count, cs, cd) - ckdepth(state, cs, cd) + ckdepth(state, cs, cd, instruction_count) dispatch( callee_proto.bytecode, @@ -1196,7 +1258,7 @@ defmodule Lua.VM.Dispatcher do frame = {code, pc + 1, regs, upvalues, proto, cont, :discard, ou} call_info = {proto.source, 0, name_hint} instruction_count = tick(state, instruction_count, cs, cd) - ckdepth(state, cs, cd) + ckdepth(state, cs, cd, instruction_count) dispatch( callee_proto.bytecode, @@ -1248,7 +1310,7 @@ defmodule Lua.VM.Dispatcher do frame = {code, pc + 1, regs, upvalues, proto, cont, :discard, ou} call_info = {proto.source, 0, name_hint} instruction_count = tick(state, instruction_count, cs, cd) - ckdepth(state, cs, cd) + ckdepth(state, cs, cd, instruction_count) dispatch( callee_proto.bytecode, @@ -1301,7 +1363,7 @@ defmodule Lua.VM.Dispatcher do frame = {code, pc + 1, regs, upvalues, proto, cont, :discard, ou} call_info = {proto.source, 0, name_hint} instruction_count = tick(state, instruction_count, cs, cd) - ckdepth(state, cs, cd) + ckdepth(state, cs, cd, instruction_count) dispatch( callee_proto.bytecode, @@ -1377,7 +1439,7 @@ defmodule Lua.VM.Dispatcher do frame = {code, pc + 1, regs, upvalues, proto, cont, dest, ou} call_info = {proto.source, 0, name_hint} instruction_count = tick(state, instruction_count, cs, cd) - ckdepth(state, cs, cd) + ckdepth(state, cs, cd, instruction_count) dispatch( callee_proto.bytecode, @@ -1438,7 +1500,13 @@ defmodule Lua.VM.Dispatcher do _ -> {value, state} = - Executor.dispatcher_get_table(table_val, key, sync(state, cs, cd), proto, name_hint) + Executor.dispatcher_get_table( + table_val, + key, + sync(state, cs, cd, instruction_count), + proto, + name_hint + ) regs = :erlang.setelement(dest + 1, regs, value) dispatch(code, pc + 1, regs, upvalues, proto, state, cont, frames, instruction_count, cs, cd, ou) @@ -1466,7 +1534,13 @@ defmodule Lua.VM.Dispatcher do _ -> {value, state} = - Executor.dispatcher_get_table(table_val, key, sync(state, cs, cd), proto, name_hint) + Executor.dispatcher_get_table( + table_val, + key, + sync(state, cs, cd, instruction_count), + proto, + name_hint + ) regs = :erlang.setelement(dest + 1, regs, value) dispatch(code, pc + 1, regs, upvalues, proto, state, cont, frames, instruction_count, cs, cd, ou) @@ -1475,7 +1549,7 @@ defmodule Lua.VM.Dispatcher do _ -> {value, state} = - Executor.dispatcher_get_table(table_val, key, sync(state, cs, cd), proto, name_hint) + Executor.dispatcher_get_table(table_val, key, sync(state, cs, cd, instruction_count), proto, name_hint) regs = :erlang.setelement(dest + 1, regs, value) dispatch(code, pc + 1, regs, upvalues, proto, state, cont, frames, instruction_count, cs, cd, ou) @@ -1485,7 +1559,10 @@ defmodule Lua.VM.Dispatcher do table_val = :erlang.element(table_reg + 1, regs) key = :erlang.element(key_reg + 1, regs) value = :erlang.element(value_reg + 1, regs) - state = Executor.dispatcher_set_table(table_val, key, value, sync(state, cs, cd), proto, name_hint) + + state = + Executor.dispatcher_set_table(table_val, key, value, sync(state, cs, cd, instruction_count), proto, name_hint) + dispatch(code, pc + 1, regs, upvalues, proto, state, cont, frames, instruction_count, cs, cd, ou) # Mirrors `@op_get_field`'s shape: a tref whose table has no metatable @@ -1507,14 +1584,28 @@ defmodule Lua.VM.Dispatcher do %{state | tables: :maps.put(id, Table.put(table, name, value), state.tables)} _ -> - Executor.dispatcher_set_field(table_val, name, value, sync(state, cs, cd), proto, name_hint) + Executor.dispatcher_set_field( + table_val, + name, + value, + sync(state, cs, cd, instruction_count), + proto, + name_hint + ) end dispatch(code, pc + 1, regs, upvalues, proto, state, cont, frames, instruction_count, cs, cd, ou) # Indexing a non-table always raises; the bridge owns the wording. _ -> - Executor.dispatcher_set_field(table_val, name, value, sync(state, cs, cd), proto, name_hint) + Executor.dispatcher_set_field( + table_val, + name, + value, + sync(state, cs, cd, instruction_count), + proto, + name_hint + ) end # `:set_list` with a positive integer count is the table-constructor @@ -1561,7 +1652,7 @@ defmodule Lua.VM.Dispatcher do dispatch(code, pc + 1, regs, upvalues, proto, state, cont, frames, instruction_count, cs, cd, ou) _ -> - {len, state} = Executor.dispatcher_length(value, sync(state, cs, cd), proto) + {len, state} = Executor.dispatcher_length(value, sync(state, cs, cd, instruction_count), proto) regs = :erlang.setelement(dest + 1, regs, len) dispatch(code, pc + 1, regs, upvalues, proto, state, cont, frames, instruction_count, cs, cd, ou) end @@ -1571,7 +1662,7 @@ defmodule Lua.VM.Dispatcher do dispatch(code, pc + 1, regs, upvalues, proto, state, cont, frames, instruction_count, cs, cd, ou) _ -> - {len, state} = Executor.dispatcher_length(value, sync(state, cs, cd), proto) + {len, state} = Executor.dispatcher_length(value, sync(state, cs, cd, instruction_count), proto) regs = :erlang.setelement(dest + 1, regs, len) dispatch(code, pc + 1, regs, upvalues, proto, state, cont, frames, instruction_count, cs, cd, ou) end @@ -1590,7 +1681,7 @@ defmodule Lua.VM.Dispatcher do :erlang.element(base + 1, regs), :erlang.element(base + 2, regs), :erlang.element(base + 3, regs), - sync(state, cs, cd) + sync(state, cs, cd, instruction_count) ) regs = :erlang.setelement(base + 1, regs, counter) @@ -1652,7 +1743,7 @@ defmodule Lua.VM.Dispatcher do invariant_state = :erlang.element(base + 2, regs) control = :erlang.element(base + 3, regs) - state = %{state | call_stack: cs, call_depth: cd, instruction_count: instruction_count} + state = sync(state, cs, cd, instruction_count) {results, state} = Executor.dispatcher_call_value(iter_func, [invariant_state, control], proto, state, line) @@ -1706,8 +1797,8 @@ defmodule Lua.VM.Dispatcher do # target's scope `level`, drops `depth` `cont` entries (a `:test` # branch pushed one, a loop body two), and resumes the destination # tuple at `target_pc`. `depth == 0` is a jump within the current - # tuple (forward or backward); otherwise the destination tuple is the - # enclosing `code` recorded on the unwound markers. + # tuple; otherwise the destination tuple is the enclosing `code` + # recorded on the unwound markers. `@op_goto_back` also ticks the budget. {@op_label, _name, _level} -> dispatch(code, pc + 1, regs, upvalues, proto, state, cont, frames, instruction_count, cs, cd, ou) @@ -1721,6 +1812,17 @@ defmodule Lua.VM.Dispatcher do {dest_code, rest_cont} = unwind_goto(cont, depth) dispatch(dest_code, target_pc, regs, upvalues, proto, state, rest_cont, frames, instruction_count, cs, cd, ou) + {@op_goto_back, 0, target_pc, level} -> + instruction_count = tick(state, instruction_count, cs, cd) + ou = close_upv(ou, level) + dispatch(code, target_pc, regs, upvalues, proto, state, cont, frames, instruction_count, cs, cd, ou) + + {@op_goto_back, depth, target_pc, level} -> + instruction_count = tick(state, instruction_count, cs, cd) + ou = close_upv(ou, level) + {dest_code, rest_cont} = unwind_goto(cont, depth) + dispatch(dest_code, target_pc, regs, upvalues, proto, state, rest_cont, frames, instruction_count, cs, cd, ou) + # ── Closure construction ────────────────────────────────────── # # Walks `nested_proto.upvalue_descriptors`, allocating a new cell @@ -1868,7 +1970,7 @@ defmodule Lua.VM.Dispatcher do frame = {code, pc + 1, regs, upvalues, proto, cont, dest, ou} call_info = {proto.source, 0, name_hint} instruction_count = tick(state, instruction_count, cs, cd) - ckdepth(state, cs, cd) + ckdepth(state, cs, cd, instruction_count) dispatch( callee_proto.bytecode, @@ -1889,7 +1991,7 @@ defmodule Lua.VM.Dispatcher do args = collect_args(regs, base + 1, total_args) call_info = {proto.source, 0, name_hint} instruction_count = tick(state, instruction_count, cs, cd) - ckdepth(state, cs, cd) + ckdepth(state, cs, cd, instruction_count) state = %{ state @@ -1898,7 +2000,7 @@ defmodule Lua.VM.Dispatcher do instruction_count: instruction_count } - {results, state} = Executor.call_function(closure, args, state) + {results, state} = Executor.call_function_uncharged(closure, args, state) instruction_count = state.instruction_count apply_multi_call_result( @@ -1922,7 +2024,7 @@ defmodule Lua.VM.Dispatcher do _ -> args = collect_args(regs, base + 1, total_args) - state = %{state | call_stack: cs, call_depth: cd, instruction_count: instruction_count} + state = sync(state, cs, cd, instruction_count) {results, state} = Executor.dispatcher_call_function(func_value, args, state, proto, name_hint, line) @@ -1958,7 +2060,16 @@ defmodule Lua.VM.Dispatcher do {@op_self, base, obj_reg, method_name, name_hint} -> obj = :erlang.element(obj_reg + 1, regs) - {func, state} = Executor.dispatcher_index_method_target(obj, method_name, sync(state, cs, cd), proto, name_hint) + + {func, state} = + Executor.dispatcher_index_method_target( + obj, + method_name, + sync(state, cs, cd, instruction_count), + proto, + name_hint + ) + regs = :erlang.setelement(base + 2, regs, obj) regs = :erlang.setelement(base + 1, regs, func) dispatch(code, pc + 1, regs, upvalues, proto, state, cont, frames, instruction_count, cs, cd, ou) @@ -1975,13 +2086,13 @@ defmodule Lua.VM.Dispatcher do if is_binary(left) and is_binary(right) do if byte_size(left) + byte_size(right) > state.max_string_bytes do - raise RuntimeError, value: "resulting string too large", state: state + raise RuntimeError, value: "resulting string too large", state: sync(state, cs, cd, instruction_count) end regs = :erlang.setelement(dest + 1, regs, left <> right) dispatch(code, pc + 1, regs, upvalues, proto, state, cont, frames, instruction_count, cs, cd, ou) else - {result, state} = Executor.dispatcher_concat(left, right, sync(state, cs, cd), proto) + {result, state} = Executor.dispatcher_concat(left, right, sync(state, cs, cd, instruction_count), proto) regs = :erlang.setelement(dest + 1, regs, result) dispatch(code, pc + 1, regs, upvalues, proto, state, cont, frames, instruction_count, cs, cd, ou) end @@ -2228,7 +2339,7 @@ defmodule Lua.VM.Dispatcher do invariant_state = :erlang.element(base + 2, regs) control = :erlang.element(base + 3, regs) - state = %{state | call_stack: cs, call_depth: cd, instruction_count: instruction_count} + state = sync(state, cs, cd, instruction_count) {results, state} = Executor.dispatcher_call_value(iter_func, [invariant_state, control], proto, state, line) @@ -2305,7 +2416,7 @@ defmodule Lua.VM.Dispatcher do # resumes the same budget and the same call stack. A bridge out of the # loop may have left a deeper stack stamped in the struct; `cs`/`cd` # have unwound back to their entry values, so this restores them. - {[value], %{state | instruction_count: instruction_count, call_stack: cs, call_depth: cd}} + {[value], sync(state, cs, cd, instruction_count)} end defp return_one(value, state, [frame | rest_frames], instruction_count, cs, cd, _ou) do @@ -2350,7 +2461,7 @@ defmodule Lua.VM.Dispatcher do # `:call_multi`. Mirrors `return_one/7`'s frame-variant handling. defp return_multi(results, state, [], instruction_count, cs, cd, _ou) do - {results, %{state | instruction_count: instruction_count, call_stack: cs, call_depth: cd}} + {results, sync(state, cs, cd, instruction_count)} end defp return_multi(results, state, [frame | rest_frames], instruction_count, cs, cd, _ou) do @@ -2388,16 +2499,29 @@ defmodule Lua.VM.Dispatcher do # ── Helpers ───────────────────────────────────────────────────────────── - # Writes the loop-carried control fields back into the struct. Called - # wherever execution leaves the dispatch loop — bridges into `Executor`, - # native callbacks, the loop's own raise sites — so anything that reads - # `state.call_stack` / `state.call_depth` out there sees the live values. + # Writes the loop-carried control fields and instruction tally back into + # the struct. Called wherever execution leaves the dispatch loop — bridges + # into `Executor`, native callbacks, the loop's own raise sites — so code + # out there sees the live values. # # The first clause makes a repeat crossing free: a loop body that bridges # every iteration without calling anything (a `t[k] = v` write, an # `__index` read) leaves the struct already carrying this frame's stack, # so only the first crossing rebuilds it. - @compile {:inline, sync: 3} + @compile {:inline, sync: 3, sync: 4} + defp sync( + %{call_stack: call_stack, call_depth: call_depth, instruction_count: recorded} = state, + call_stack, + call_depth, + instruction_count + ) + when recorded >= instruction_count, do: state + + defp sync(%{instruction_count: recorded} = state, call_stack, call_depth, instruction_count) do + %{state | call_stack: call_stack, call_depth: call_depth, instruction_count: max(recorded, instruction_count)} + end + + # Control fields only, for `tick/4`: `State.tick!/2` stamps the tally itself. defp sync(%{call_stack: call_stack, call_depth: call_depth} = state, call_stack, call_depth), do: state defp sync(state, call_stack, call_depth) do @@ -2409,9 +2533,9 @@ defmodule Lua.VM.Dispatcher do # Inlining the guard here keeps the no-op case to a single function-head # match instead of a cross-module call into `Executor`/`State`; the # non-trivial case still routes to the canonical implementation (paying - # one `sync/3` on the way) so the behaviour and its error shapes live in + # one `sync` on the way) so the behaviour and its error shapes live in # one place. - @compile {:inline, close_upv: 2, tick: 4, ckdepth: 3} + @compile {:inline, close_upv: 2, tick: 4, ckdepth: 4} defp close_upv(open_upvalues, _threshold) when map_size(open_upvalues) == 0, do: open_upvalues @@ -2425,11 +2549,11 @@ defmodule Lua.VM.Dispatcher do State.tick!(sync(state, call_stack, call_depth), instruction_count) end - defp ckdepth(%{max_call_depth: :infinity}, _call_stack, _call_depth), do: :ok - defp ckdepth(%{max_call_depth: max}, _call_stack, call_depth) when call_depth < max, do: :ok + defp ckdepth(%{max_call_depth: :infinity}, _call_stack, _call_depth, _instruction_count), do: :ok + defp ckdepth(%{max_call_depth: max}, _call_stack, call_depth, _instruction_count) when call_depth < max, do: :ok - defp ckdepth(state, call_stack, call_depth) do - State.check_call_depth!(sync(state, call_stack, call_depth)) + defp ckdepth(state, call_stack, call_depth, instruction_count) do + State.check_call_depth!(sync(state, call_stack, call_depth, instruction_count)) end defp clear_nils(regs, _dest, 0), do: regs @@ -2441,12 +2565,13 @@ defmodule Lua.VM.Dispatcher do # ── Non-dispatcher callees ────────────────────────────────────────────── # # Everything that is not a `:compiled_closure` leaves the dispatch loop: - # interpreted Lua closures through `Executor.call_function/3`, natives and - # callables through `Executor.dispatcher_call_function/6`. Both grow the - # Erlang stack by one frame at the mode boundary. Factored out of the call - # handlers so the generic and static-arity opcodes share one copy — - # `line` reaches the native bridge for error attribution exactly as it did - # when these branches were inline. + # interpreted Lua closures through `Executor.call_function_uncharged/3` + # (charged here first), natives and callables through + # `Executor.dispatcher_call_function/6`. Both grow the Erlang stack by one + # frame at the mode boundary. Factored out of the call handlers so the + # generic and static-arity opcodes share one copy — `line` reaches the + # native bridge for error attribution exactly as it did when these branches + # were inline. defp call_zero_bridge( {:lua_closure, _, _} = closure, @@ -2468,7 +2593,7 @@ defmodule Lua.VM.Dispatcher do ) do call_info = {proto.source, 0, name_hint} instruction_count = tick(state, instruction_count, cs, cd) - ckdepth(state, cs, cd) + ckdepth(state, cs, cd, instruction_count) state = %{ state @@ -2477,7 +2602,7 @@ defmodule Lua.VM.Dispatcher do instruction_count: instruction_count } - {_results, state} = Executor.call_function(closure, args, state) + {_results, state} = Executor.call_function_uncharged(closure, args, state) instruction_count = state.instruction_count dispatch(code, pc + 1, regs, upvalues, proto, state, cont, frames, instruction_count, cs, cd, ou) end @@ -2500,7 +2625,7 @@ defmodule Lua.VM.Dispatcher do cd, ou ) do - state = %{state | call_stack: cs, call_depth: cd, instruction_count: instruction_count} + state = sync(state, cs, cd, instruction_count) {_results, state} = Executor.dispatcher_call_function(func_value, args, state, proto, name_hint, line) @@ -2529,7 +2654,7 @@ defmodule Lua.VM.Dispatcher do ) do call_info = {proto.source, 0, name_hint} instruction_count = tick(state, instruction_count, cs, cd) - ckdepth(state, cs, cd) + ckdepth(state, cs, cd, instruction_count) state = %{ state @@ -2538,7 +2663,7 @@ defmodule Lua.VM.Dispatcher do instruction_count: instruction_count } - {results, state} = Executor.call_function(closure, args, state) + {results, state} = Executor.call_function_uncharged(closure, args, state) instruction_count = state.instruction_count regs = :erlang.setelement(base + 1, regs, first_result(results)) dispatch(code, pc + 1, regs, upvalues, proto, state, cont, frames, instruction_count, cs, cd, ou) @@ -2563,7 +2688,7 @@ defmodule Lua.VM.Dispatcher do cd, ou ) do - state = %{state | call_stack: cs, call_depth: cd, instruction_count: instruction_count} + state = sync(state, cs, cd, instruction_count) {results, state} = Executor.dispatcher_call_function(func_value, args, state, proto, name_hint, line) diff --git a/lib/lua/vm/executor.ex b/lib/lua/vm/executor.ex index ccad361..0d6940c 100644 --- a/lib/lua/vm/executor.ex +++ b/lib/lua/vm/executor.ex @@ -26,6 +26,8 @@ defmodule Lua.VM.Executor do alias Lua.VM.TypeError alias Lua.VM.Value + @metamethod_chain_limit 200 + # ── Source position bridge for native callbacks ─────────────────────────── # # In-executor raise sites get `line` / `proto.source` threaded as args @@ -129,13 +131,18 @@ defmodule Lua.VM.Executor do def annotate_frame_state(e, _state), do: e @doc """ - Calls a Lua function value with the given arguments. + Calls a function value, or a value with a `__call` metamethod, from host + code (`pcall`, metamethods, stdlib callbacks). - Used by pcall/xpcall to invoke functions in protected mode. - Returns {results, final_state}. + The callee is charged as one call against `:max_instructions` and + `:max_call_depth`, native functions included. Returns `{results, final_state}`. """ @spec call_function(term(), list(), State.t()) :: {list(), State.t()} - def call_function({:lua_closure, callee_proto, callee_upvalues}, args, state) do + def call_function(callee, args, state), do: call_resolving_call_metamethod(callee, args, state, 0) + + @doc false + @spec call_function_uncharged(term(), list(), State.t()) :: {list(), State.t()} + def call_function_uncharged({:lua_closure, callee_proto, callee_upvalues}, args, state) do callee_regs = Tuple.duplicate(nil, max(callee_proto.max_registers, callee_proto.param_count)) @@ -185,12 +192,12 @@ defmodule Lua.VM.Executor do end end - def call_function({:compiled_closure, callee_proto, callee_upvalues}, args, state) do + def call_function_uncharged({:compiled_closure, callee_proto, callee_upvalues}, args, state) do # Compiled callees route through the dispatcher. The dispatcher manages # its own register file setup and vararg routing, and isolates open # upvalues by threading them as a dispatch-loop parameter seeded empty # at this boundary — `Dispatcher.execute/4` mirrors the semantics of - # this function for the bytecode-encoded path. + # the clause above for the bytecode-encoded path. Dispatcher.execute(callee_proto, args, callee_upvalues, state) end @@ -199,7 +206,7 @@ defmodule Lua.VM.Executor do # protected calls can keep heap effects made before the error without # every bad-argument check threading state into its raise. Innermost # annotation wins — see `annotate_frame_state/2`. - def call_function({:native_func, fun}, args, state) do + def call_function_uncharged({:native_func, fun}, args, state) do case fun.(args, state) do {results, %State{} = new_state} when is_list(results) -> {results, new_state} @@ -211,7 +218,39 @@ defmodule Lua.VM.Executor do e -> reraise annotate_frame_state(e, state), __STACKTRACE__ end - def call_function(nil, _args, state) do + # No release on raise: the trapping pcall restores `call_depth` from its entry state. + defp charge_and_call(function, args, %State{max_instructions: :infinity, max_call_depth: :infinity} = state), + do: call_function_uncharged(function, args, state) + + defp charge_and_call(function, args, %State{call_depth: depth} = state) do + {results, new_state} = call_function_uncharged(function, args, State.charge_call!(state)) + {results, %{new_state | call_depth: depth}} + end + + defp call_resolving_call_metamethod({:lua_closure, _, _} = closure, args, state, _hops), + do: charge_and_call(closure, args, state) + + defp call_resolving_call_metamethod({:compiled_closure, _, _} = closure, args, state, _hops), + do: charge_and_call(closure, args, state) + + defp call_resolving_call_metamethod({:native_func, _} = native, args, state, _hops), + do: charge_and_call(native, args, state) + + defp call_resolving_call_metamethod(_callee, _args, state, hops) when hops >= @metamethod_chain_limit, + do: raise_call_chain_too_long(state) + + defp call_resolving_call_metamethod(callee, args, state, hops) do + case lookup_metamethod(callee, "__call", state) do + nil -> raise_call_error(callee, state) + call_metamethod -> call_resolving_call_metamethod(call_metamethod, [callee | args], state, hops + 1) + end + end + + defp raise_call_chain_too_long(state) do + raise RuntimeError, value: "'__call' chain too long; possible loop", state: state + end + + defp raise_call_error(nil, state) do raise TypeError, value: "attempt to call a nil value", error_kind: :call_nil, @@ -219,31 +258,12 @@ defmodule Lua.VM.Executor do state: state end - def call_function(other, args, state) do - # Check for __call metamethod - case get_metatable(other, state) do - nil -> - raise TypeError, - value: "attempt to call a #{Value.type_name(other)} value", - error_kind: :call_non_function, - value_type: value_type(other), - state: state - - {:tref, mt_id} -> - mt = Map.fetch!(state.tables, mt_id) - - case Map.get(mt.data, "__call") do - nil -> - raise TypeError, - value: "attempt to call a #{Value.type_name(other)} value", - error_kind: :call_non_function, - value_type: value_type(other), - state: state - - call_mm -> - call_function(call_mm, [other | args], state) - end - end + defp raise_call_error(value, state) do + raise TypeError, + value: "attempt to call a #{Value.type_name(value)} value", + error_kind: :call_non_function, + value_type: value_type(value), + state: state end # ── Bridges for Lua.VM.Dispatcher ────────────────────────────────────────── @@ -585,8 +605,9 @@ defmodule Lua.VM.Executor do prev_pos = :erlang.get(@position_key) :erlang.put(@position_key, {line, proto.source}) + # Matches the interpreter: a direct native call from Lua is not charged. try do - call_function(nf, args, state) + call_function_uncharged(nf, args, state) after case prev_pos do :undefined -> :erlang.erase(@position_key) @@ -596,7 +617,7 @@ defmodule Lua.VM.Executor do end def dispatcher_call_function(other, args, state, proto, name_hint, line) do - case get_metatable(other, state) do + case lookup_metamethod(other, "__call", state) do nil -> raise TypeError, value: "attempt to call a #{Value.type_name(other)} value" <> format_target_hint(name_hint), @@ -607,23 +628,8 @@ defmodule Lua.VM.Executor do value_type: value_type(other), state: state - {:tref, mt_id} -> - mt = Map.fetch!(state.tables, mt_id) - - case Map.get(mt.data, "__call") do - nil -> - raise TypeError, - value: "attempt to call a #{Value.type_name(other)} value" <> format_target_hint(name_hint), - source: proto.source, - call_stack: state.call_stack, - line: line, - error_kind: :call_non_function, - value_type: value_type(other), - state: state - - call_mm -> - call_function(call_mm, [other | args], state) - end + call_mm -> + call_resolving_call_metamethod(call_mm, [other | args], state, 1) end end @@ -672,13 +678,15 @@ defmodule Lua.VM.Executor do # ── Goto ─────────────────────────────────────────────────────────────────── # # `Lua.Compiler.GotoResolution` rewrote each `goto` to `{:goto, id}` and - # recorded `proto.goto_targets[id] = {depth, target_tail}`. Dropping `depth` - # `cont` entries leaves the blocks between here and the target; `target_tail` - # is the destination block's instruction suffix after the `::label::`. + # recorded `proto.goto_targets[id] = {depth, level, target_tail, direction}`. + # Dropping `depth` `cont` entries leaves the blocks between here and the + # target; `target_tail` is the destination block's instruction suffix after + # the `::label::`. defp do_execute([{:goto, id} | _rest], regs, upvalues, proto, state, cont, frames, line, instruction_count) do case proto.goto_targets do - %{^id => {depth, level, target_tail}} -> + %{^id => {depth, level, target_tail, direction}} -> + {state, instruction_count} = charge_goto(direction, state, instruction_count) # Close upvalue cells for locals allocated beyond the target's scope: # the blocks the goto leaves (or re-enters, on a backward jump) take # their captured locals with them, so the next pass through gets fresh @@ -743,7 +751,7 @@ defmodule Lua.VM.Executor do # After while loop body — restart condition [{:cps_while_body, test_reg, loop_body, cond_body, rest, outer_cont} | _] -> - instruction_count = State.tick!(state, instruction_count) + {state, instruction_count} = tick(state, instruction_count) loop_exit_cont = [{:loop_exit, rest} | outer_cont] cond_check = {:cps_while_test, test_reg, loop_body, cond_body, rest, outer_cont} @@ -783,7 +791,7 @@ defmodule Lua.VM.Executor do do_execute(rest, regs, upvalues, proto, state, outer_cont, frames, line, instruction_count) else # Condition false = repeat body - instruction_count = State.tick!(state, instruction_count) + {state, instruction_count} = tick(state, instruction_count) loop_exit_cont = [{:loop_exit, rest} | outer_cont] body_done = {:cps_repeat_body, loop_body, cond_body, test_reg, rest, outer_cont} @@ -810,7 +818,7 @@ defmodule Lua.VM.Executor do should_continue = if step > 0, do: new_counter <= limit, else: new_counter >= limit if should_continue do - instruction_count = State.tick!(state, instruction_count) + {state, instruction_count} = tick(state, instruction_count) regs = put_elem(regs, loop_var, new_counter) state = close_open_upvalues_at_or_above(state, loop_var) @@ -828,7 +836,7 @@ defmodule Lua.VM.Executor do invariant_state = elem(regs, base + 1) control = elem(regs, base + 2) - state = %{state | instruction_count: instruction_count} + state = stamp_tally(state, instruction_count) {results, state} = call_value(iter_func, [invariant_state, control], proto, state, line) instruction_count = state.instruction_count first_result = List.first(results) @@ -836,7 +844,7 @@ defmodule Lua.VM.Executor do if first_result == nil do do_execute(rest, regs, upvalues, proto, state, outer_cont, frames, line, instruction_count) else - instruction_count = State.tick!(state, instruction_count) + {state, instruction_count} = tick(state, instruction_count) regs = put_elem(regs, base + 2, first_result) regs = @@ -1242,7 +1250,7 @@ defmodule Lua.VM.Executor do invariant_state = elem(regs, base + 1) control = elem(regs, base + 2) - state = %{state | instruction_count: instruction_count} + state = stamp_tally(state, instruction_count) {results, state} = call_value(iter_func, [invariant_state, control], proto, state, line) instruction_count = state.instruction_count first_result = List.first(results) @@ -1400,7 +1408,7 @@ defmodule Lua.VM.Executor do # without going through this branch. args = collect_args(regs, base + 1, total_args) call_info = {proto.source, line, name_hint} - instruction_count = State.tick!(state, instruction_count) + {state, instruction_count} = tick(state, instruction_count) State.check_call_depth!(state) # Carry the tally into the dispatcher so the budget spans the # boundary; `Dispatcher.execute/4` seeds from `state.instruction_count` and @@ -1468,7 +1476,7 @@ defmodule Lua.VM.Executor do call_info = {proto.source, line, name_hint} - instruction_count = State.tick!(state, instruction_count) + {state, instruction_count} = tick(state, instruction_count) State.check_call_depth!(state) state = %{ @@ -1507,7 +1515,7 @@ defmodule Lua.VM.Executor do # Carry the tally into the native callback so a callback that # re-enters Lua (pcall, a sort comparator, a gsub function) keeps # accumulating against the same budget instead of restarting it. - state = %{state | instruction_count: instruction_count} + state = stamp_tally(state, instruction_count) {results, state} = try do @@ -1556,7 +1564,7 @@ defmodule Lua.VM.Executor do state: state other -> - case get_metatable(other, state) do + case lookup_metamethod(other, "__call", state) do nil -> raise TypeError, value: "attempt to call a #{Value.type_name(other)} value" <> format_target_hint(name_hint), @@ -1567,41 +1575,26 @@ defmodule Lua.VM.Executor do value_type: value_type(other), state: state - {:tref, mt_id} -> - mt = Map.fetch!(state.tables, mt_id) - - case Map.get(mt.data, "__call") do - nil -> - raise TypeError, - value: "attempt to call a #{Value.type_name(other)} value" <> format_target_hint(name_hint), - source: proto.source, - call_stack: state.call_stack, - line: line, - error_kind: :call_non_function, - value_type: value_type(other), - state: state - - call_mm -> - args = collect_args(regs, base + 1, total_args) - state = %{state | instruction_count: instruction_count} - {results, state} = call_function(call_mm, [other | args], state) - instruction_count = state.instruction_count - - continue_after_call( - results, - regs, - rest, - upvalues, - proto, - state, - cont, - frames, - line, - instruction_count, - base, - result_count - ) - end + call_mm -> + args = collect_args(regs, base + 1, total_args) + state = stamp_tally(state, instruction_count) + {results, state} = call_resolving_call_metamethod(call_mm, [other | args], state, 1) + instruction_count = state.instruction_count + + continue_after_call( + results, + regs, + rest, + upvalues, + proto, + state, + cont, + frames, + line, + instruction_count, + base, + result_count + ) end end end @@ -2966,13 +2959,28 @@ defmodule Lua.VM.Executor do # ── do_frame_return — restore caller context after a Lua function returns ── # Stamp the running tally into the state at a top-of-evaluation terminal - # so the entry wrapper (`call_function/3`, `call_value/5`, `execute/5`) + # so the entry wrapper (`call_function_uncharged/3`, `execute/5`) # can carry it back across an engine boundary. Only ever fired when the # frame stack is empty — i.e. the interpreter sub-evaluation as a whole # is unwinding — never per intra-evaluation return, so the default # `:infinity` path pays only at boundaries, exactly like the call-frame # bookkeeping it sits beside. - defp finish_instructions(state, instruction_count), do: %{state | instruction_count: instruction_count} + defp finish_instructions(state, instruction_count), do: stamp_tally(state, instruction_count) + + # Under a finite budget the tick also stamps the tally into the struct, so + # work charged behind a bridge is folded back in (see `State.tick!/2`). + @compile {:inline, tick: 2, stamp_tally: 2} + defp tick(%State{max_instructions: :infinity} = state, instruction_count), do: {state, instruction_count} + + defp tick(state, instruction_count) do + instruction_count = State.tick!(state, instruction_count) + {%{state | instruction_count: instruction_count}, instruction_count} + end + + defp stamp_tally(%State{instruction_count: recorded} = state, instruction_count) when recorded >= instruction_count, + do: state + + defp stamp_tally(state, instruction_count), do: State.stamp_tally(state, instruction_count) defp do_frame_return(results, _callee_regs, state, frame, rest_frames, line, instruction_count) do %{ @@ -3174,60 +3182,30 @@ defmodule Lua.VM.Executor do defp find_loop_exit([_ | rest_cont]), do: find_loop_exit(rest_cont) defp find_loop_exit([]), do: raise(InternalError, value: "break outside loop") - # ── call_value — invoke a function for generic_for iterator ─────────────── - - defp call_value({:lua_closure, callee_proto, callee_upvalues}, args, _proto, state, _line) do - callee_regs = - Tuple.duplicate(nil, max(callee_proto.max_registers, callee_proto.param_count)) + # ── charge_goto — a backward goto is a loop back-edge ───────────────────── - callee_regs = - args - |> Enum.with_index() - |> Enum.reduce(callee_regs, fn {arg, i}, regs -> - if i < callee_proto.param_count, do: put_elem(regs, i, arg), else: regs - end) - - callee_proto = - if callee_proto.is_vararg do - %{callee_proto | varargs: Enum.drop(args, callee_proto.param_count)} - else - callee_proto - end + defp charge_goto(:backward, state, instruction_count), do: tick(state, instruction_count) + defp charge_goto(:forward, state, instruction_count), do: {state, instruction_count} - saved_open_upvalues = state.open_upvalues + # ── call_value — invoke a function for generic_for iterator ─────────────── + # + # Charged like `call_resolving_call_metamethod/4`, except that a native + # iterator is charged only when reached through `__call`. - try do - state = %{state | open_upvalues: %{}} + defp call_value(callable, args, proto, state, line), do: call_value(callable, args, proto, state, line, 0) - # Seed/recover the cross-boundary budget tally (see `call_function/3`). - {results, _callee_regs, state} = - do_execute( - callee_proto.instructions, - callee_regs, - callee_upvalues, - callee_proto, - state, - [], - [], - 0, - state.instruction_count - ) + defp call_value({:lua_closure, _, _} = closure, args, _proto, state, _line, _hops), + do: charge_and_call(closure, args, state) - state = %{state | open_upvalues: saved_open_upvalues} - {results, state} - rescue - # Backstop net — same rationale as the `call_function/3` closure path. - e -> reraise annotate_frame_state(e, state), __STACKTRACE__ - end - end + defp call_value({:compiled_closure, _, _} = closure, args, _proto, state, _line, _hops), + do: charge_and_call(closure, args, state) - defp call_value({:compiled_closure, _, _} = closure, args, _proto, state, _line) do - # Compiled-closure callees for generic_for iterators reuse the same - # dispatcher bridge as `call_function/3`. - call_function(closure, args, state) + defp call_value({:native_func, _} = native, args, proto, %State{call_depth: depth} = state, line, hops) when hops > 0 do + {results, new_state} = call_value(native, args, proto, State.charge_call!(state), line, 0) + {results, %{new_state | call_depth: depth}} end - defp call_value({:native_func, fun}, args, proto, state, line) do + defp call_value({:native_func, fun}, args, proto, state, line, _hops) do # Same source-position bridge as the `:call` opcode's native dispatch. # Used by `for` loop iteration when the iterator is native. prev_pos = Process.get(@position_key, @unset) @@ -3253,7 +3231,7 @@ defmodule Lua.VM.Executor do end end - defp call_value(nil, _args, proto, state, line) do + defp call_value(nil, _args, proto, state, line, _hops) do raise TypeError, value: "attempt to call a nil value", source: proto.source, @@ -3264,8 +3242,11 @@ defmodule Lua.VM.Executor do state: state end - defp call_value(other, args, proto, state, line) do - case get_metatable(other, state) do + defp call_value(_other, _args, _proto, state, _line, hops) when hops >= @metamethod_chain_limit, + do: raise_call_chain_too_long(state) + + defp call_value(other, args, proto, state, line, hops) do + case lookup_metamethod(other, "__call", state) do nil -> raise TypeError, value: "attempt to call a #{Value.type_name(other)} value", @@ -3276,23 +3257,8 @@ defmodule Lua.VM.Executor do value_type: value_type(other), state: state - {:tref, mt_id} -> - mt = Map.fetch!(state.tables, mt_id) - - case Map.get(mt.data, "__call") do - nil -> - raise TypeError, - value: "attempt to call a #{Value.type_name(other)} value", - source: proto.source, - call_stack: state.call_stack, - line: line, - error_kind: :call_non_function, - value_type: value_type(other), - state: state - - call_mm -> - call_value(call_mm, [other | args], proto, state, line) - end + call_mm -> + call_value(call_mm, [other | args], proto, state, line, hops + 1) end end @@ -3332,8 +3298,6 @@ defmodule Lua.VM.Executor do # ── Metamethod support ───────────────────────────────────────────────────── - @metamethod_chain_limit 200 - defp get_metatable({:tref, id}, state) do table = Map.fetch!(state.tables, id) table.metatable diff --git a/lib/lua/vm/state.ex b/lib/lua/vm/state.ex index 054bfc5..0ba8f08 100644 --- a/lib/lua/vm/state.ex +++ b/lib/lua/vm/state.ex @@ -19,8 +19,9 @@ defmodule Lua.VM.State do defstruct call_stack: [], # Call depth tracked as an O(1) counter that moves in lockstep # with `call_stack` — `length(call_stack)` would be O(depth) per - # call. `max_call_depth` bounds it; `:infinity` (the default) - # means no limit. See `check_call_depth!/1`. + # call — plus host calls into Lua, which push no frame (see + # `charge_call!/1`). `max_call_depth` bounds it; `:infinity` (the + # default) means no limit. See `check_call_depth!/1`. call_depth: 0, max_call_depth: :infinity, # Ceiling for any single string the VM will build (`..` and the @@ -39,11 +40,9 @@ defmodule Lua.VM.State do max_instructions: :infinity, # `instruction_count` carries the running tally ACROSS engine boundaries # only. The interpreter and dispatcher each thread their tally as - # a loop parameter; at an `Executor`↔`Dispatcher` hand-off (where - # the struct is already rebuilt to push a call frame) the crossing - # engine writes its tally here and the entered engine seeds from - # it, so the budget spans a chain that alternates engines instead - # of resetting at each boundary. Never written per opcode. + # a loop parameter and stamp it here before leaving the loop; the + # higher of the two is live (see `stamp_tally/2`). Never written + # per opcode. instruction_count: 0, metatables: %{}, upvalue_cells: %{}, @@ -132,8 +131,8 @@ defmodule Lua.VM.State do this one call. When a finite budget is set it increments the tally and, once the new tally reaches `max_instructions`, raises a catchable Lua `"instruction budget exceeded"` runtime error. The clauses are ordered so - both the `:infinity` and under-budget cases resolve in a single - function-head match. + both the `:infinity` and under-budget cases resolve in function-head + matches. The raise reuses the same `Lua.VM.RuntimeError` used by `"stack overflow"`, carrying the raise-time `state:` so `pcall`/`xpcall` recover @@ -141,10 +140,16 @@ defmodule Lua.VM.State do threaded `instruction_count` is not otherwise in `%State{}`), so `unwind_to/2` can carry it forward and a caught budget error stays spent — a protected call cannot refund the work it burned. + + When `state.instruction_count` is ahead of the threaded tally, the tick + starts from it. """ @spec tick!(t(), non_neg_integer()) :: non_neg_integer() def tick!(%__MODULE__{max_instructions: :infinity}, instruction_count), do: instruction_count + def tick!(%__MODULE__{instruction_count: recorded} = state, instruction_count) when recorded > instruction_count, + do: tick!(state, recorded) + def tick!(%__MODULE__{max_instructions: max}, instruction_count) when instruction_count + 1 < max, do: instruction_count + 1 @@ -157,6 +162,26 @@ defmodule Lua.VM.State do state: %{state | instruction_count: instruction_count} end + @doc """ + Stamps a loop-carried tally into the struct unless the struct's count is higher. + """ + @spec stamp_tally(t(), non_neg_integer()) :: t() + def stamp_tally(%__MODULE__{instruction_count: recorded} = state, instruction_count) when recorded >= instruction_count, + do: state + + def stamp_tally(%__MODULE__{} = state, instruction_count), do: %{state | instruction_count: instruction_count} + + @doc """ + Charges a host call into a function value as one tick and one `call_depth` + level, without a `call_stack` frame. The caller restores `call_depth`. + """ + @spec charge_call!(t()) :: t() + def charge_call!(%__MODULE__{call_depth: call_depth, instruction_count: instruction_count} = state) do + ticked_state = %{state | instruction_count: tick!(state, instruction_count)} + check_call_depth!(ticked_state) + %{ticked_state | call_depth: call_depth + 1} + end + @doc """ Recovers the state a protected call should continue with after trapping an error. diff --git a/test/lua/vm/dispatcher_test.exs b/test/lua/vm/dispatcher_test.exs index 038b2c1..00241dd 100644 --- a/test/lua/vm/dispatcher_test.exs +++ b/test/lua/vm/dispatcher_test.exs @@ -1374,6 +1374,7 @@ defmodule Lua.VM.DispatcherTest do """) assert encodes_op?(proto, Bytecode.op_goto()) + refute encodes_op?(proto, Bytecode.op_goto_back()) assert results == [1] end @@ -1390,7 +1391,8 @@ defmodule Lua.VM.DispatcherTest do return f() """) - assert encodes_op?(proto, Bytecode.op_goto()) + assert encodes_op?(proto, Bytecode.op_goto_back()) + refute encodes_op?(proto, Bytecode.op_goto()) assert results == [5] end @@ -1410,9 +1412,30 @@ defmodule Lua.VM.DispatcherTest do """) assert encodes_op?(proto, Bytecode.op_goto()) + refute encodes_op?(proto, Bytecode.op_goto_back()) assert results == [42] end + test "goto out of a loop to a label before it is a back-edge", %{} do + {proto, results} = + run!(""" + function f() + local n = 0 + ::again:: + for i = 1, 3 do + n = n + 1 + if n < 7 then goto again end + end + return n + end + return f() + """) + + assert encodes_op?(proto, Bytecode.op_goto_back()) + refute encodes_op?(proto, Bytecode.op_goto()) + assert results == [9] + end + test "goto exiting a loop closes captured upvalues", %{} do {proto, results} = run!(""" diff --git a/test/lua/vm/limit_bypass_test.exs b/test/lua/vm/limit_bypass_test.exs new file mode 100644 index 0000000..ffc5216 --- /dev/null +++ b/test/lua/vm/limit_bypass_test.exs @@ -0,0 +1,341 @@ +defmodule Lua.VM.LimitBypassTest do + @moduledoc """ + Each script runs heap-capped with a timeout, on both the dispatcher and + the interpreter. + """ + use ExUnit.Case, async: true + + alias Lua.Compiler + alias Lua.Compiler.Prototype + alias Lua.Parser + alias Lua.VM + + @timeout 15_000 + @heap_words div(256 * 1024 * 1024, :erlang.system_info(:wordsize)) + + @budget [max_instructions: 10_000] + @depth [max_call_depth: 100] + @budget_and_depth [max_instructions: 10_000, max_call_depth: 100] + + @engines [:dispatcher, :interpreter] + + defp run_isolated(code, engine, opts) do + parent = self() + + {pid, ref} = + spawn_monitor(fn -> + Process.flag(:max_heap_size, %{size: @heap_words, kill: true, error_logger: false}) + send(parent, {:result, self(), compile_and_run(code, engine, opts)}) + end) + + receive do + {:result, ^pid, result} -> + Process.demonitor(ref, [:flush]) + result + + {:DOWN, ^ref, :process, ^pid, reason} -> + flunk("#{engine}: script died (#{inspect(reason)}) instead of raising a Lua error:\n#{code}") + after + @timeout -> + Process.exit(pid, :kill) + flunk("#{engine}: script did not terminate within #{@timeout}ms:\n#{code}") + end + end + + defp compile_and_run(code, engine, opts) do + {:ok, ast} = Parser.parse(code) + {:ok, proto} = Compiler.compile(ast, source: "limits.lua") + proto = if engine == :interpreter, do: strip_bytecode(proto), else: proto + {:ok, results, _state} = VM.execute(proto, lua_with_host_callback(opts).state) + {:ok, results} + rescue + e -> {:error, Map.get(e, :value) || Exception.message(e)} + end + + defp lua_with_host_callback(opts) do + Lua.set!(Lua.new(opts), [:call_with_self], fn [function | args], lua -> + Lua.call_function!(lua, function, [function | args]) + end) + end + + defp strip_bytecode(%Prototype{} = proto) do + %{proto | bytecode: nil, prototypes: Enum.map(proto.prototypes, &strip_bytecode/1)} + end + + defp assert_raises_lua(code, opts, message) do + for engine <- @engines do + assert {:error, value} = run_isolated(code, engine, opts), "#{engine}: expected #{inspect(message)} for:\n#{code}" + assert is_binary(value) and value =~ message, "#{engine}: expected #{inspect(message)}, got #{inspect(value)}" + end + end + + defp assert_recursion_bounded(code) do + assert_raises_lua(code, @budget_and_depth, "stack overflow") + assert_raises_lua(code, @depth, "stack overflow") + assert_raises_lua(code, @budget, "instruction budget exceeded") + end + + defp assert_results(code, opts, expected) do + for engine <- @engines do + assert expected == results!(code, engine, opts) + end + end + + defp results!(code, engine, opts) do + assert {:ok, results} = run_isolated(code, engine, opts), "#{engine}: unexpected error for:\n#{code}" + results + end + + describe "backward goto" do + test "in the main chunk exhausts the budget" do + code = "local n = 0 ::top:: n = n + 1 if n < 1e9 then goto top end return n" + assert_raises_lua(code, @budget, "instruction budget exceeded") + end + + test "in a function exhausts the budget" do + code = """ + local function spin() + local n = 0 + ::top:: + n = n + 1 + if n < 1e9 then goto top end + return n + end + return spin() + """ + + assert_raises_lua(code, @budget, "instruction budget exceeded") + end + + test "out of a loop exhausts the budget" do + code = """ + local function spin() + local n = 0 + ::again:: + for i = 1, 2 do + n = n + 1 + if n < 1e9 then goto again end + end + return n + end + return spin() + """ + + assert_raises_lua(code, @budget, "instruction budget exceeded") + end + + test "loop that ends under the budget returns" do + assert_results("local n = 0 ::top:: n = n + 1 if n < 100 then goto top end return n", @budget, [100]) + end + + test "forward gotos are free" do + jumps = Enum.map_join(1..40, " ", fn i -> "do goto l#{i} end ::l#{i}::" end) + assert_results("local function f() #{jumps} return 1 end #{jumps} return f()", [max_instructions: 5], [1]) + end + end + + describe "host re-entry" do + test "pcall recursion stops at :max_call_depth" do + code = "local function f() return pcall(f) end return f()" + + for engine <- @engines, opts <- [@depth, @budget_and_depth] do + results = results!(code, engine, opts) + assert List.last(results) =~ "stack overflow" + assert length(results) <= 102 + end + end + + test "pcall recursion stops at :max_instructions" do + code = "local function f() return pcall(f) end return f()" + + for engine <- @engines do + assert List.last(results!(code, engine, @budget)) =~ "instruction budget exceeded" + end + end + + test "counting pcall recursion stops at either limit" do + code = "local n = 0 local function f() n = n + 1 local ok = pcall(f) return ok end f() return n" + + for engine <- @engines do + assert [call_count] = results!(code, engine, @depth) + assert call_count in 1..100 + + assert [call_count] = results!(code, engine, @budget) + assert call_count in 1..10_000 + end + end + + test "recursive xpcall handler terminates" do + code = "local function f() return xpcall(error, f) end return f()" + + for engine <- @engines, opts <- [@depth, @budget, @budget_and_depth] do + assert [false | _] = results!(code, engine, opts) + end + end + + # `for _ in it, nil, nil`: a bare `for _ in it` hits an unrelated + # register-allocation bug. + for {name, code} <- [ + {"string.gsub replacement", ~S|local function f() return (("x"):gsub("x", f)) end return f()|}, + {"table.sort comparator", "local function f() table.sort({2, 1}, f) return true end return f()"}, + {"__tostring via tostring", + "local t t = setmetatable({}, {__tostring = function(a) return tostring(a) end}) return tostring(t)"}, + {"generic-for iterator", "local function it() for _ in it, nil, nil do end end for _ in it, nil, nil do end"}, + {"__index", "local t t = setmetatable({}, {__index = function(_, k) return t[k] end}) return t.x"}, + {"__newindex", "local t t = setmetatable({}, {__newindex = function(_, k, v) t[k] = v end}) t.x = 1"}, + {"__add", "local t t = setmetatable({}, {__add = function(a, b) return a + b end}) return t + 1"}, + {"__unm", "local t t = setmetatable({}, {__unm = function(a) return -a end}) return -t"}, + {"__concat", ~S|local t t = setmetatable({}, {__concat = function(a, b) return a .. b end}) return t .. "x"|}, + {"__len", "local t t = setmetatable({}, {__len = function(a) return #a end}) return #t"}, + {"__lt", "local mt = {} mt.__lt = function(a, b) return a < b end local t = setmetatable({}, mt) return t < t"}, + {"__eq", + "local mt = {} mt.__eq = function(a, b) return a == b end return setmetatable({}, mt) == setmetatable({}, mt)"}, + {"__call calling its table", + "local t = setmetatable({}, {__call = function(self) return self() end}) return t()"}, + {"native __tostring", + "local t = setmetatable({}, {}) getmetatable(t).__tostring = tostring return tostring(t)"}, + {"host callback through Lua.call_function!/3", "local function f() return call_with_self(f) end return f()"}, + {"host callback calling itself through Lua.call_function!/3", "return call_with_self(call_with_self)"} + ] do + test name, do: assert_recursion_bounded(unquote(code)) + end + + for {name, comparator} <- [{"Lua", "function(a, b) return a < b end"}, {"native", "rawequal"}] do + test "table.sort charges each #{name} comparator call" do + code = """ + local t = {} + for i = 1, 3000 do t[i] = i end + return pcall(table.sort, t, #{unquote(comparator)}) + """ + + for engine <- @engines do + assert [false, err] = results!(code, engine, @budget) + assert err =~ "instruction budget exceeded" + end + end + end + + test "native __call calling its table" do + code = "local t = setmetatable({}, {__call = pcall}) return t()" + + for engine <- @engines do + assert List.last(results!(code, engine, @depth)) =~ "stack overflow" + assert List.last(results!(code, engine, @budget)) =~ "instruction budget exceeded" + end + end + end + + # Each of the 400 iterations runs ~100 instructions behind a bridge: + # counted in full, the total is four times the budget. + describe "work behind a metamethod bridge" do + @spin_loop "local s = 0 for j = 1, 100 do s = s + j end" + + test "stays counted when a native call follows" do + code = """ + local t = setmetatable({}, {__index = function() #{@spin_loop} return 1 end}) + local function run() local n = 0 for i = 1, 400 do n = n + t.x; type(n) end return n end + return run() + """ + + assert_raises_lua(code, @budget, "instruction budget exceeded") + end + + for {name, failure} <- [{"an arithmetic error", "return nil + {}"}, {"a stack overflow", "return deep()"}] do + test "stays counted after #{name} is caught" do + code = """ + local function deep() return 1 + deep() end + local function run() for i = 1, 400 do pcall(function() #{@spin_loop} #{unquote(failure)} end) end end + return run() + """ + + assert_raises_lua(code, @budget_and_depth, "instruction budget exceeded") + end + end + end + + describe "call depth is released" do + @define_deep "local function deep(n) if n == 0 then return 0 end return 1 + deep(n - 1) end" + + test "after a caught stack overflow" do + code = """ + local function f() return pcall(f) end + local first = select('#', f()) + local second = select('#', f()) + #{@define_deep} + return first == second, deep(90) + """ + + assert_results(code, @budget_and_depth, [true, 90]) + end + + test "after calls return" do + code = """ + local proxy = setmetatable({}, {__index = function(_, k) return k end}) + local s = 0 + for i = 1, 300 do s = s + proxy[i] end + for i = 1, 300 do pcall(function() end) end + for i = 1, 300 do table.sort({3, 1, 2}, function(a, b) return a < b end) end + local callable = setmetatable({}, {__call = function(_, x) return x end}) + for i = 1, 300 do s = s + callable(1) end + #{@define_deep} + return s, deep(90) + """ + + assert_results(code, [max_call_depth: 100], [45_450, 90]) + end + + test "after caught errors" do + code = """ + local raising = setmetatable({}, {__index = function() error("boom") end}) + for i = 1, 300 do pcall(function() return raising.x end) end + #{@define_deep} + return deep(90) + """ + + assert_results(code, [max_call_depth: 100], [90]) + end + + test "default limits allow deep pcall recursion" do + code = "local function f(n) if n == 0 then return 0 end local _, v = pcall(f, n - 1) return v + 1 end return f(300)" + assert_results(code, [], [300]) + end + end + + describe "__call chain" do + for {name, code} <- [ + {"self-referential", "local a = {} setmetatable(a, {__call = a}) return a()"}, + {"self-referential in a function", + "local function f() local a = {} setmetatable(a, {__call = a}) return a() end return f()"}, + {"self-referential as a for iterator", + "local a = setmetatable({}, {}) getmetatable(a).__call = a for _ in a, nil, nil do end"} + ] do + test name, do: assert_raises_lua(unquote(code), [], "'__call' chain too long; possible loop") + end + + test "self-referential under pcall is catchable" do + code = """ + local a = {} setmetatable(a, {__call = a}) + local ok, err = pcall(a) + return ok, err, 1 + 1 + """ + + for engine <- @engines do + assert [false, err, 2] = results!(code, engine, []) + assert err =~ "'__call' chain too long" + end + end + + test "short chain resolves" do + # Each hop inserts the callable it went through ahead of the arguments. + code = """ + local inner + inner = setmetatable({}, {__call = function(self, outer_tbl, x) return self == inner, outer_tbl, x end}) + local outer = setmetatable({}, {__call = inner}) + local is_inner, got_outer, x = outer(42) + return is_inner, got_outer == outer, x + """ + + assert_results(code, [], [true, true, 42]) + end + end +end diff --git a/test/lua/vm/max_instructions_test.exs b/test/lua/vm/max_instructions_test.exs index ea9095d..3512a18 100644 --- a/test/lua/vm/max_instructions_test.exs +++ b/test/lua/vm/max_instructions_test.exs @@ -249,6 +249,15 @@ defmodule Lua.VM.MaxInstructionsTest do end end + test "a call refused at :max_call_depth still spends its instruction" do + code = "return pcall(pcall, type, 1)" + {[true, false, message], refused} = eval!(Lua.new(max_call_depth: 1, max_instructions: 1000), code) + {[true, true, "number"], allowed} = eval!(Lua.new(max_call_depth: 2, max_instructions: 1000), code) + + assert message =~ "stack overflow" + assert refused.state.instruction_count == allowed.state.instruction_count + end + test "require runs the module body against the same budget (no mid-eval reset)" do # `require` re-enters `Lua.VM.execute`, which resets the per-eval tally at # genuine top-level entry only. The pre-require work must still count: with