diff --git a/CHANGELOG.md b/CHANGELOG.md index c26f0ca..9e293a4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -49,12 +49,37 @@ is in the [`1.0.0-rc.0`](#100-rc0---2026-05-26) entry below. ## [Unreleased] +### Added +- `Lua.new/1` option `:max_table_elements` (default 1,000,000, was a fixed + 10,000,000) caps the elements one stdlib call may produce or walk, now + also for `string.byte`, `string.unpack`, `utf8.codepoint` and + `table.insert`/`remove`. + +### Changed +- Pattern matching and stdlib calls whose work grows with their input are + charged to `:max_instructions`, one instruction per 16 units of work, so a + backtracking pattern raises `"instruction budget exceeded"` instead of + running for minutes. +- `string.gmatch` matches lazily, one match per iteration. + ### Fixed - `:max_string_bytes` is now enforced by `table.concat`, `string.gsub`, `string.format`, `string.pack` and `os.date`, which previously built results 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`. +- `table.sort` with a comparator calls it O(n log n) times, not O(n²). +- Passing many values through a call (`table.unpack`, `...`) is linear, not + quadratic. +- Patterns raise `"too many captures"` past 32 captures and + `"pattern too complex"` past 200 nested backtracks, as in PUC-Lua. ## [1.0.2] - 2026-07-28 diff --git a/lib/lua.ex b/lib/lua.ex index 242d83c..a82ddba 100644 --- a/lib/lua.ex +++ b/lib/lua.ex @@ -12,6 +12,7 @@ defmodule Lua do alias Lua.VM.Display alias Lua.VM.Executor alias Lua.VM.InternalError + alias Lua.VM.Limits alias Lua.VM.RuntimeError alias Lua.VM.State alias Lua.VM.Table @@ -90,7 +91,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 @@ -127,10 +129,22 @@ defmodule Lua do back-edges and call boundaries, so the default `:infinity` path carries no per-instruction cost. The budget is fresh per top-level evaluation and recoverable via `pcall`. + Work inside stdlib calls is charged too, one instruction per 16 units: a byte scanned or + built, an element visited or returned, a pattern-matcher step. + iex> lua = Lua.new(max_instructions: 1000) iex> {[false, message], _lua} = Lua.eval!(lua, "return pcall(function() while true do end end)") iex> message =~ "instruction budget exceeded" true + + * `:max_table_elements` - (default 1,000,000) the most elements one stdlib call may produce + or walk (`table.unpack`, `table.concat`, `string.byte`, …), checked before the work starts. + Accepts a positive integer or `:infinity`. + + iex> lua = Lua.new(max_table_elements: 100) + iex> {[false, message], _lua} = Lua.eval!(lua, "return pcall(table.unpack, {}, 1, 1000)") + iex> message =~ "too many results to unpack" + true """ @spec new(keyword()) :: t() def new(opts \\ []) do @@ -140,8 +154,9 @@ defmodule Lua do exclude: [], debug: false, max_call_depth: :infinity, - max_string_bytes: Lua.VM.Limits.max_string_bytes(), - max_instructions: :infinity + max_string_bytes: Limits.max_string_bytes(), + max_instructions: :infinity, + max_table_elements: Limits.max_element_count() ) sandboxed = Keyword.fetch!(opts, :sandboxed) @@ -150,6 +165,7 @@ defmodule Lua do max_call_depth = validate_max_call_depth!(Keyword.fetch!(opts, :max_call_depth)) max_string_bytes = validate_max_string_bytes!(Keyword.fetch!(opts, :max_string_bytes)) max_instructions = validate_max_instructions!(Keyword.fetch!(opts, :max_instructions)) + max_table_elements = validate_max_table_elements!(Keyword.fetch!(opts, :max_table_elements)) lua = template(sandboxed, exclude) @@ -160,7 +176,8 @@ defmodule Lua do lua.state | max_call_depth: max_call_depth, max_string_bytes: max_string_bytes, - max_instructions: max_instructions + max_instructions: max_instructions, + max_table_elements: max_table_elements } } end @@ -217,6 +234,14 @@ defmodule Lua do ":max_instructions must be a positive integer or :infinity, got: #{inspect(other)}" end + defp validate_max_table_elements!(:infinity), do: :infinity + defp validate_max_table_elements!(count) when is_integer(count) and count > 0, do: count + + defp validate_max_table_elements!(other) do + raise ArgumentError, + ":max_table_elements must be a positive integer or :infinity, got: #{inspect(other)}" + end + @doc """ Write Lua code that is parsed at compile-time. @@ -849,14 +874,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 +913,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)} + {results, new_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)} - 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..0186f99 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) @@ -2806,15 +2931,8 @@ defmodule Lua.VM.Dispatcher do # (e.g. `f(...)` where the variadic call site has more args than # the caller's other locals require). defp write_varargs(regs, base, varargs, _n) do - n = length(varargs) - regs = grow_regs(regs, base + n) - write_varargs_loop(regs, base, varargs, 0) - end - - defp write_varargs_loop(regs, _base, [], n), do: {regs, n} - - defp write_varargs_loop(regs, base, [v | rest], n) do - write_varargs_loop(:erlang.setelement(base + n + 1, regs, v), base, rest, n + 1) + count = length(varargs) + {write_values(regs, base, varargs, count), count} end # `:vararg` count>0 form: write the first `n` varargs, pad with nil. @@ -2854,9 +2972,19 @@ defmodule Lua.VM.Dispatcher do # statically reserved size — mirrors the interpreter's # `ensure_regs_capacity/2` at the post-call site (executor.ex:1873). - defp write_results(regs, base, results) do - regs = grow_regs(regs, base + length(results)) - write_results_loop(regs, base, results) + defp write_results(regs, base, results), do: write_values(regs, base, results, length(results)) + + # Longer runtime-sized lists are spliced in with one tuple rebuild: a + # `setelement` per value copies the tuple each time, which is quadratic. + @splice_threshold 32 + + defp write_values(regs, base, values, count) when count > @splice_threshold do + {head, tail} = regs |> grow_regs(base + count) |> Tuple.to_list() |> Enum.split(base) + List.to_tuple(head ++ values ++ Enum.drop(tail, count)) + end + + defp write_values(regs, base, values, count) do + regs |> grow_regs(base + count) |> write_results_loop(base, values) end defp write_results_loop(regs, _base, []), do: regs @@ -3012,21 +3140,11 @@ defmodule Lua.VM.Dispatcher do # Lazy regs-tuple growth. Used at the points where multi-return # expansion or vararg writes can exceed the statically reserved size. - # `Tuple.insert_at/3` is O(n) per insert; this is fine because growth - # is rare and bounded by the call's actual result count. - defp grow_regs(regs, needed) do - current = tuple_size(regs) + # A few slots are cheaper to append one by one than to rebuild for. + defp grow_regs(regs, needed) when needed <= tuple_size(regs), do: regs - if needed > current do - grow_tuple(regs, needed - current) - else - regs - end - end - - defp grow_tuple(tuple, 0), do: tuple + defp grow_regs(regs, needed) when needed - tuple_size(regs) < 4, + do: grow_regs(:erlang.append_element(regs, nil), needed) - defp grow_tuple(tuple, n) do - grow_tuple(Tuple.insert_at(tuple, tuple_size(tuple), nil), n - 1) - end + defp grow_regs(regs, needed), do: List.to_tuple(Tuple.to_list(regs) ++ List.duplicate(nil, needed - tuple_size(regs))) end diff --git a/lib/lua/vm/executor.ex b/lib/lua/vm/executor.ex index ccad361..a116d9c 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 @@ -1619,11 +1612,7 @@ defmodule Lua.VM.Executor do # honors now that no fixed register buffer absorbs the overflow. n = length(varargs) regs = ensure_regs_capacity(regs, base + n) - - regs = - Enum.reduce(Enum.with_index(varargs), regs, fn {val, i}, r -> - put_elem(r, base + i, val) - end) + regs = write_many_to_regs(regs, base, varargs, n) {regs, %{state | multi_return_count: n}} else @@ -2966,13 +2955,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 %{ @@ -3009,7 +3013,7 @@ defmodule Lua.VM.Executor do results_list = List.wrap(results) count = length(results_list) caller_regs = ensure_regs_capacity(caller_regs, base + count) - caller_regs = write_list_to_regs(caller_regs, base, results_list) + caller_regs = write_many_to_regs(caller_regs, base, results_list, count) state = %{state | multi_return_count: count} @@ -3114,7 +3118,7 @@ defmodule Lua.VM.Executor do results_list = List.wrap(results) count = length(results_list) regs = ensure_regs_capacity(regs, base + count) - regs = write_list_to_regs(regs, base, results_list) + regs = write_many_to_regs(regs, base, results_list, count) state = %{state | multi_return_count: count} do_execute(rest, regs, upvalues, proto, state, cont, frames, line, instruction_count) @@ -3159,75 +3163,42 @@ defmodule Lua.VM.Executor do # Append nil slots with a small headroom so back-to-back expansions # don't repeatedly reallocate. extra = needed_size - current_size + 16 - grow_tuple(regs, extra) + List.to_tuple(Tuple.to_list(regs) ++ List.duplicate(nil, extra)) else regs end end - defp grow_tuple(tuple, 0), do: tuple - defp grow_tuple(tuple, n), do: grow_tuple(Tuple.insert_at(tuple, tuple_size(tuple), nil), n - 1) - # ── find_loop_exit — scan cont for the nearest {:loop_exit, _} marker ────── defp find_loop_exit([{:loop_exit, exit_is} | rest_cont]), do: {exit_is, rest_cont} 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)) - - 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) + # ── charge_goto — a backward goto is a loop back-edge ───────────────────── - 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 +3224,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 +3235,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 +3250,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 +3291,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 @@ -4137,6 +4094,17 @@ defmodule Lua.VM.Executor do # ── Return helpers: write a list of values into a contiguous register range ─ + # Longer runtime-sized lists are spliced in with one tuple rebuild: a + # `setelement` per value copies the tuple each time, which is quadratic. + @splice_threshold 32 + + defp write_many_to_regs(regs, off, list, count) when count > @splice_threshold do + {head, tail} = regs |> Tuple.to_list() |> Enum.split(off) + List.to_tuple(head ++ list ++ Enum.drop(tail, count)) + end + + defp write_many_to_regs(regs, off, list, _count), do: write_list_to_regs(regs, off, list) + defp write_list_to_regs(regs, _off, []), do: regs defp write_list_to_regs(regs, off, [v | rest]) do diff --git a/lib/lua/vm/limits.ex b/lib/lua/vm/limits.ex index 46be991..b1f40ae 100644 --- a/lib/lua/vm/limits.ex +++ b/lib/lua/vm/limits.ex @@ -18,28 +18,59 @@ defmodule Lua.VM.Limits do This is the deterministic, OTP-independent layer: it never relies on the garbage collector or heap accounting to notice a bomb, because the bomb is refused before a byte is allocated. + + Work a stdlib call does outside the dispatch loop is charged to the + `:max_instructions` budget in units: a byte scanned or built, an element + visited or returned, a pattern-matcher step. See `charge!/2`. """ alias Lua.VM.ArgumentError alias Lua.VM.RuntimeError + alias Lua.VM.State # 256 MiB. A single string this large is already pathological for an # embedded interpreter; legitimate snippets never approach it. @max_string_bytes 256 * 1024 * 1024 - # 10 million elements. Bounds the result list of `table.unpack` and the - # element reads of `table.concat`/`table.move` well under what would - # exhaust memory, while staying generous for real data. - @max_element_count 10_000_000 + # PUC-Lua's `LUAI_MAXSTACK`. + @max_element_count 1_000_000 + + # Sixteen units cost about the CPU of one Lua loop iteration. + @work_per_instruction 16 @doc "The string-size ceiling, in bytes." @spec max_string_bytes() :: pos_integer() def max_string_bytes, do: @max_string_bytes - @doc "The element-count ceiling for range-based table operations." + @doc "The default element-count ceiling (`:max_table_elements`)." @spec max_element_count() :: pos_integer() def max_element_count, do: @max_element_count + @doc "Units of native work charged as one instruction." + @spec work_per_instruction() :: pos_integer() + def work_per_instruction, do: @work_per_instruction + + @doc """ + Charges `units` of native work to `:max_instructions`, one instruction per + `work_per_instruction/0` units. Call it before the work, so an over-budget + call raises without doing it. + """ + @spec charge!(State.t(), integer()) :: State.t() + def charge!(%{max_instructions: :infinity} = state, _units), do: state + def charge!(state, units) when units < @work_per_instruction, do: state + + def charge!(%{max_instructions: max, instruction_count: tally} = state, units) do + case tally + div(units, @work_per_instruction) do + charged when charged < max -> %{state | instruction_count: charged} + _overdrawn -> State.tick!(state, max - 1) + end + end + + @doc "Like `charge!/2`, one unit per element of `list`." + @spec charge_elements!(State.t(), list()) :: State.t() + def charge_elements!(%{max_instructions: :infinity} = state, _list), do: state + def charge_elements!(state, list), do: charge!(state, length(list)) + @doc """ Asserts that an as-yet-unallocated string of `bytes` bytes is within the given ceiling (a state's `max_string_bytes`, defaulting to the practical @@ -54,7 +85,7 @@ defmodule Lua.VM.Limits do # Erlang term ordering places every number below every atom, so an integer # `bytes <= :infinity` is always true and the check passes unconditionally — # no separate clause is needed. - @spec check_string_size!(integer(), pos_integer() | :infinity, Lua.VM.State.t() | nil) :: :ok + @spec check_string_size!(integer(), pos_integer() | :infinity, State.t() | nil) :: :ok def check_string_size!(bytes, max \\ @max_string_bytes, state \\ nil) def check_string_size!(bytes, max, _state) when is_integer(bytes) and bytes <= max, do: :ok @@ -64,14 +95,33 @@ defmodule Lua.VM.Limits do end @doc """ - Asserts that a range-based table operation (`concat`, `move`) would not - touch more than the element ceiling. Raises a catchable bad-argument - error attributed to `function_name` otherwise. + Raises a catchable `"range too large"` bad-argument error, attributed to + `function_name`, when `count` exceeds `max` (`:infinity` always passes). """ - @spec check_range_count!(integer(), String.t()) :: :ok - def check_range_count!(count, _function_name) when is_integer(count) and count <= @max_element_count, do: :ok + @spec check_range_count!(integer(), pos_integer() | :infinity, String.t()) :: :ok + def check_range_count!(count, max, _function_name) when is_integer(count) and count <= max, do: :ok - def check_range_count!(_count, function_name) do + def check_range_count!(_count, _max, function_name) do raise ArgumentError, function_name: function_name, details: "range too large" end + + @doc """ + Raises a catchable `"string slice too long"` error when `count` exceeds `max`. + """ + @spec check_slice_count!(integer(), pos_integer() | :infinity) :: :ok + def check_slice_count!(count, max) when is_integer(count) and count <= max, do: :ok + + def check_slice_count!(_count, _max) do + raise RuntimeError, value: "string slice too long" + end + + @doc """ + Raises a catchable `"too many results"` error when `count` exceeds `max`. + """ + @spec check_result_count!(integer(), pos_integer() | :infinity) :: :ok + def check_result_count!(count, max) when is_integer(count) and count <= max, do: :ok + + def check_result_count!(_count, _max) do + raise RuntimeError, value: "too many results" + end end diff --git a/lib/lua/vm/state.ex b/lib/lua/vm/state.ex index 054bfc5..a8f870e 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,12 +40,11 @@ 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, + max_table_elements: Limits.max_element_count(), metatables: %{}, upvalue_cells: %{}, open_upvalues: %{}, @@ -74,6 +74,7 @@ defmodule Lua.VM.State do max_string_bytes: pos_integer() | :infinity, max_instructions: pos_integer() | :infinity, instruction_count: non_neg_integer(), + max_table_elements: pos_integer() | :infinity, metatables: map(), upvalue_cells: map(), tables: %{optional(non_neg_integer()) => Table.t()}, @@ -132,8 +133,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 +142,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 +164,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/lib/lua/vm/stdlib.ex b/lib/lua/vm/stdlib.ex index 6967692..f7c2bb3 100644 --- a/lib/lua/vm/stdlib.ex +++ b/lib/lua/vm/stdlib.ex @@ -124,29 +124,20 @@ defmodule Lua.VM.Stdlib do defp lua_tostring([], state), do: {["nil"], state} # tonumber(v [, base]) — converts a string to a number - defp lua_tonumber([value | rest], state) do - base = List.first(rest) - - result = - case {value, base} do - {v, nil} when is_number(v) -> - v - - {v, nil} when is_binary(v) -> - Value.parse_number(v) - - {v, b} when is_binary(v) and is_integer(b) and b >= 2 and b <= 36 -> - parse_in_base(v, b) - - _ -> - nil - end - - {[result], state} + defp lua_tonumber([value | rest], state) when is_binary(value) do + state = Limits.charge!(state, byte_size(value)) + {[string_to_number(value, List.first(rest))], state} end + defp lua_tonumber([value], state) when is_number(value), do: {[value], state} + defp lua_tonumber([value, nil | _rest], state) when is_number(value), do: {[value], state} + defp lua_tonumber([_value | _rest], state), do: {[nil], state} defp lua_tonumber([], state), do: {[nil], state} + defp string_to_number(string, nil), do: Value.parse_number(string) + defp string_to_number(string, base) when is_integer(base) and base >= 2 and base <= 36, do: parse_in_base(string, base) + defp string_to_number(_string, _base), do: nil + # tonumber(s, base) per Lua 5.3 §6.1: surrounding whitespace is ignored, an # optional sign is allowed, digits a-z/A-Z map to 10-35 (case-insensitive), # and the result is always an integer (wrapping into the signed 64-bit range @@ -173,7 +164,8 @@ defmodule Lua.VM.Stdlib do {[str | acc], st} end) - output = strings |> Enum.reverse() |> Enum.join("\t") + output = strings |> Enum.reverse() |> Enum.map_intersperse("\t", &to_string/1) + state = Limits.charge!(state, IO.iodata_length(output)) IO.puts(output) {[], state} end @@ -418,25 +410,22 @@ defmodule Lua.VM.Stdlib do # select(index, ...) — returns arguments starting from index # select('#', ...) — returns count of arguments defp lua_select(["#" | args], state) do - {[length(args)], state} + count = length(args) + {[count], Limits.charge!(state, count)} end - defp lua_select([index | args], state) when is_integer(index) do - cond do - # Positive index: return from that position onward - index > 0 -> - selected = Enum.drop(args, index - 1) - {selected, state} + defp lua_select([index | args], state) when is_integer(index) and index > 0 do + state = Limits.charge_elements!(state, args) + {Enum.drop(args, index - 1), state} + end - # Negative index: count from end (take last n elements) - index < 0 -> - selected = Enum.take(args, index) - {selected, state} + defp lua_select([index | args], state) when is_integer(index) and index < 0 do + state = Limits.charge_elements!(state, args) + {Enum.take(args, index), state} + end - # Index 0 is invalid - true -> - raise RuntimeError, value: "bad argument #1 to 'select' (index out of range)" - end + defp lua_select([0 | _args], _state) do + raise RuntimeError, value: "bad argument #1 to 'select' (index out of range)" end defp lua_select([non_valid | _], _state) do @@ -532,6 +521,8 @@ defmodule Lua.VM.Stdlib do end defp compile_loaded_chunk(source, env, state) do + state = Limits.charge!(state, byte_size(source)) + case Lua.Parser.parse(source) do {:ok, ast} -> # Compiler currently never returns errors, always succeeds — see diff --git a/lib/lua/vm/stdlib/math.ex b/lib/lua/vm/stdlib/math.ex index f605449..0f20c91 100644 --- a/lib/lua/vm/stdlib/math.ex +++ b/lib/lua/vm/stdlib/math.ex @@ -37,6 +37,7 @@ defmodule Lua.VM.Stdlib.Math do import Bitwise alias Lua.VM.ArgumentError + alias Lua.VM.Limits alias Lua.VM.Numeric alias Lua.VM.State alias Lua.VM.Stdlib.Util @@ -388,7 +389,9 @@ defmodule Lua.VM.Stdlib.Math do end # math.max(x, ...) - defp math_max(args, state) when length(args) > 0 do + defp math_max([_ | _] = args, state) do + state = Limits.charge_elements!(state, args) + if Enum.all?(args, &is_number/1) do {[Enum.max(args)], state} else @@ -408,7 +411,9 @@ defmodule Lua.VM.Stdlib.Math do end # math.min(x, ...) - defp math_min(args, state) when length(args) > 0 do + defp math_min([_ | _] = args, state) do + state = Limits.charge_elements!(state, args) + if Enum.all?(args, &is_number/1) do {[Enum.min(args)], state} else @@ -570,6 +575,8 @@ defmodule Lua.VM.Stdlib.Math do end defp math_tointeger([x], state) when is_binary(x) do + state = Limits.charge!(state, byte_size(x)) + case Value.parse_number(x) do n when is_integer(n) -> {[n], state} n when is_float(n) -> {[float_to_integer_or_nil(n)], state} diff --git a/lib/lua/vm/stdlib/os.ex b/lib/lua/vm/stdlib/os.ex index 65ee0c8..96be512 100644 --- a/lib/lua/vm/stdlib/os.ex +++ b/lib/lua/vm/stdlib/os.ex @@ -137,6 +137,7 @@ defmodule Lua.VM.Stdlib.Os do defp os_date([nil | rest], state), do: os_date(["%c" | rest], state) defp os_date([format | rest], state) when is_binary(format) do + state = Limits.charge!(state, byte_size(format)) {format, utc?} = strip_utc_flag(format) time = diff --git a/lib/lua/vm/stdlib/pattern.ex b/lib/lua/vm/stdlib/pattern.ex index 1b332e8..1ee0a3e 100644 --- a/lib/lua/vm/stdlib/pattern.ex +++ b/lib/lua/vm/stdlib/pattern.ex @@ -11,35 +11,61 @@ defmodule Lua.VM.Stdlib.Pattern do - Captures: (pattern), %1-%9 backreferences - Balanced: %bxy - Escape: % + non-alphanumeric = literal + + Functions taking a VM state charge matcher steps to its `:max_instructions` + budget. Captures per match and backtracking depth are capped as in PUC-Lua. """ + import Bitwise + alias Lua.VM.Limits alias Lua.VM.RuntimeError alias Lua.VM.State alias Lua.VM.Stdlib.Util + # A matcher step and a byte of the result are each one unit of work. + @steps_per_instruction Limits.work_per_instruction() + # PUC-Lua's MAXCCALLS and LUA_MAXCAPTURES. + @max_match_depth 200 + @max_captures 32 + + # Largest 64-bit small integer: never runs out, never allocates. + @unbounded_fuel 0x07FF_FFFF_FFFF_FFFF + + defguardp is_fuel_left(result) when is_integer(result) and result >= 0 + @doc """ Find first match of pattern in subject starting at position `init` (1-based). Returns `{start, stop, captures}` or `:nomatch`. """ def find(subject, pattern, init \\ 1) do + {result, _state} = find(subject, pattern, init, %State{}) + result + end + + @doc """ + Like `find/3`, charging the matcher's steps to `state`. Returns `{result, state}`. + """ + def find(subject, pattern, init, %State{} = state) do + {result, fuel} = find_fueled(subject, pattern, init, available_fuel(state)) + {result, settle!(fuel, state)} + end + + defp find_fueled(subject, pattern, init, fuel) do len = byte_size(subject) case normalize_init(init, len) do :out_of_range -> - :nomatch + {:nomatch, fuel} - start_pos -> + # One step per pattern byte, charged before compiling. + start_pos when fuel >= byte_size(pattern) -> {anchored, pattern_elems} = compile(pattern) + last_start = if anchored, do: start_pos, else: len + find_from(subject, start_pos, last_start, pattern_elems, fuel - byte_size(pattern)) - if anchored do - case match_pattern(subject, start_pos, pattern_elems, subject) do - {:match, end_pos, captures} -> {start_pos + 1, end_pos, captures} - :nomatch -> :nomatch - end - else - find_from(subject, start_pos, len, pattern_elems) - end + _start_pos -> + {:nomatch, fuel - byte_size(pattern)} end end @@ -52,12 +78,13 @@ defmodule Lua.VM.Stdlib.Pattern do defp normalize_init(init, len) when init < 0, do: max(len + init, 0) defp normalize_init(_init, _len), do: 0 - defp find_from(_subject, pos, len, _pattern) when pos > len, do: :nomatch + defp find_from(_subject, pos, last_start, _pattern, fuel) when pos > last_start, do: {:nomatch, fuel} - defp find_from(subject, pos, len, pattern) do - case match_pattern(subject, pos, pattern, subject) do - {:match, end_pos, captures} -> {pos + 1, end_pos, captures} - :nomatch -> find_from(subject, pos + 1, len, pattern) + defp find_from(subject, pos, last_start, pattern, fuel) do + case match_pattern(subject, pos, pattern, fuel) do + {:match, end_pos, captures, fuel} -> {{pos + 1, end_pos, captures}, fuel} + fuel when is_fuel_left(fuel) -> find_from(subject, pos + 1, last_start, pattern, fuel) + stop -> {:nomatch, stop} end end @@ -65,45 +92,87 @@ defmodule Lua.VM.Stdlib.Pattern do Match pattern against subject, returning captures or :nomatch. """ def match(subject, pattern, init \\ 1) do - case find(subject, pattern, init) do - {_start, _stop, captures} when captures != [] -> {:match, captures} - {start, stop, []} -> {:match, [binary_part(subject, start - 1, stop - start + 1)]} - :nomatch -> :nomatch - end + subject |> find(pattern, init) |> to_match(subject) end @doc """ - Global match - returns list of all matches as {start, stop, captures}. + Like `match/3`, charging the matcher's steps to `state`. Returns `{result, state}`. + """ + def match(subject, pattern, init, %State{} = state) do + {found, state} = find(subject, pattern, init, state) + {to_match(found, subject), state} + end + + defp to_match({_start, _stop, captures}, _subject) when captures != [], do: {:match, captures} + defp to_match({start, stop, []}, subject), do: {:match, [binary_part(subject, start - 1, stop - start + 1)]} + defp to_match(:nomatch, _subject), do: :nomatch + + @doc """ + Global match - returns the list of every match's captures (or whole match). """ def gmatch(subject, pattern) do - # Lua 5.3 §6.4 (`string.gmatch`): a leading `^` does not work as an anchor - # (it would prevent the iteration). PUC-Lua's gmatch_aux never strips - # it, so `match` sees it as an ordinary character — recompile the - # pattern with the caret kept as a literal. - pattern_elems = - case compile(pattern) do - {false, elems} -> elems - {true, _elems} -> compile_elements(pattern, []) - end + {iterator, state} = gmatch_start(pattern, %State{}) + gmatch_all(subject, iterator, state, []) + end - gmatch_from(subject, 0, byte_size(subject), pattern_elems, [], -1) + defp gmatch_all(subject, iterator, state, matches) do + case gmatch_next(subject, iterator, state) do + {nil, _iterator, _state} -> Enum.reverse(matches) + {result, iterator, state} -> gmatch_all(subject, iterator, state, [result | matches]) + end + end + + @doc """ + Compiles `pattern` into an opaque iterator for `gmatch_next/3`, charging + the compile to `state`. Returns `{iterator, state}`. + """ + def gmatch_start(pattern, %State{} = state) do + state = settle!(available_fuel(state) - byte_size(pattern), state) + {{gmatch_elements(pattern), 0, -1}, state} end - defp gmatch_from(_subject, pos, len, _pattern, acc, _lastmatch) when pos > len do - Enum.reverse(acc) + @doc """ + Advances a `gmatch_start/2` iterator to the next match in `subject`, + charging the steps to `state`. Returns `{captures, iterator, state}`, with + `nil` captures once the subject is exhausted. + """ + def gmatch_next(subject, {pattern_elems, pos, lastmatch}, %State{} = state) do + len = byte_size(subject) + + case gmatch_step(subject, pos, len, pattern_elems, lastmatch, available_fuel(state)) do + {:match, result, next_pos, end_pos, fuel} -> + {result, {pattern_elems, next_pos, end_pos}, settle!(fuel, state)} + + # Parked past the end, so further calls return at once. + {:done, fuel} -> + {nil, {pattern_elems, len + 1, lastmatch}, settle!(fuel, state)} + end end + # Lua 5.3 §6.4 (`string.gmatch`): a leading `^` does not work as an anchor + # (it would prevent the iteration). PUC-Lua's gmatch_aux never strips + # it, so `match` sees it as an ordinary character — recompile the + # pattern with the caret kept as a literal. + defp gmatch_elements(pattern) do + case compile(pattern) do + {false, elems} -> elems + {true, _elems} -> compile_elements(pattern, []) + end + end + + defp gmatch_step(_subject, pos, len, _pattern, _lastmatch, fuel) when pos > len, do: {:done, fuel} + # PUC Lua's `gmatch_aux` skips a match whose end equals the previous match's # end — this prevents an empty match that fires immediately after a previous # non-empty match from being returned twice (once at the boundary, once on # the empty-advance step). - defp gmatch_from(subject, pos, len, pattern, acc, lastmatch) do - case match_pattern(subject, pos, pattern, subject) do - {:match, end_pos, _} when end_pos == lastmatch -> + defp gmatch_step(subject, pos, len, pattern, lastmatch, fuel) do + case match_pattern(subject, pos, pattern, fuel) do + {:match, end_pos, _, fuel} when end_pos == lastmatch -> # Same end as previous match — skip and try at next position. - gmatch_from(subject, pos + 1, len, pattern, acc, lastmatch) + gmatch_step(subject, pos + 1, len, pattern, lastmatch, fuel) - {:match, end_pos, captures} -> + {:match, end_pos, captures, fuel} -> result = if captures == [] do [binary_part(subject, pos, max(end_pos - pos, 0))] @@ -113,10 +182,13 @@ defmodule Lua.VM.Stdlib.Pattern do # Advance at least 1 to prevent infinite loop on empty match next_pos = if end_pos == pos, do: pos + 1, else: end_pos - gmatch_from(subject, next_pos, len, pattern, [result | acc], end_pos) + {:match, result, next_pos, end_pos, fuel} + + fuel when is_fuel_left(fuel) -> + gmatch_step(subject, pos + 1, len, pattern, lastmatch, fuel) - :nomatch -> - gmatch_from(subject, pos + 1, len, pattern, acc, lastmatch) + stop -> + {:done, stop} end end @@ -132,8 +204,6 @@ defmodule Lua.VM.Stdlib.Pattern do `gsub_stateful/5` instead. """ def gsub(subject, pattern, repl, max_n \\ nil) do - {anchored, pattern_elems} = compile(pattern) - stateful_repl = if is_function(repl, 1) do fn args, state -> {repl.(args), state} end @@ -141,7 +211,7 @@ defmodule Lua.VM.Stdlib.Pattern do repl end - {result, count, _state} = do_gsub(subject, anchored, pattern_elems, stateful_repl, max_n, nil) + {result, count, _state} = gsub_stateful(subject, pattern, stateful_repl, nil, max_n) {result, count} end @@ -152,37 +222,46 @@ defmodule Lua.VM.Stdlib.Pattern do When `repl` is a function it must have arity 2 — `(args, state) -> {result, state}` — so callbacks that mutate Lua state (upvalues, tables) thread their changes back out. String and table replacements are state-pass-through. + + The matcher and a function replacement charge the same instruction budget. """ def gsub_stateful(subject, pattern, repl, state, max_n \\ nil) do - {anchored, pattern_elems} = compile(pattern) - do_gsub(subject, anchored, pattern_elems, repl, max_n, state) + case available_fuel(state) - byte_size(pattern) do + fuel when is_fuel_left(fuel) -> + {anchored, pattern_elems} = compile(pattern) + {result, count, state, fuel} = do_gsub(subject, anchored, pattern_elems, repl, max_n, state, fuel) + {result, count, settle!(fuel, state)} + + overdrawn -> + settle!(overdrawn, state) + end end # A `^`-anchored pattern matches only at the start of the subject # (Lua 5.3 §6.4.1), so gsub performs at most one replacement there and # keeps the remainder untouched — PUC-Lua str_gsub's `anchor` flag makes # its scan loop run exactly once. An unanchored pattern scans every - # position via gsub_from/11. + # position via gsub_from/12. - defp do_gsub(subject, true, _pattern, _repl, max_n, state) when max_n != nil and max_n <= 0 do - {subject, 0, state} + defp do_gsub(subject, true, _pattern, _repl, max_n, state, fuel) when max_n != nil and max_n <= 0 do + {subject, 0, state, fuel} end - defp do_gsub(subject, true, pattern, repl, _max_n, state) do - case match_pattern(subject, 0, pattern, subject) do - {:match, end_pos, captures} -> + defp do_gsub(subject, true, pattern, repl, _max_n, state, fuel) do + case match_pattern(subject, 0, pattern, fuel) do + {:match, end_pos, captures, fuel} -> whole_match = binary_part(subject, 0, end_pos) - {replacement, state} = apply_replacement(repl, whole_match, captures, 0, state) + {replacement, state, fuel} = apply_replacement(repl, whole_match, captures, 0, state, fuel) rest = binary_part(subject, end_pos, byte_size(subject) - end_pos) - finish_gsub([replacement], rest, byte_size(replacement), 1, state) + finish_gsub([replacement], rest, byte_size(replacement), 1, state, fuel) - :nomatch -> - {subject, 0, state} + fuel -> + {subject, 0, state, fuel} end end - defp do_gsub(subject, false, pattern, repl, max_n, state) do - gsub_from(subject, 0, byte_size(subject), pattern, repl, max_n, 0, [], 0, state, false) + defp do_gsub(subject, false, pattern, repl, max_n, state, fuel) do + gsub_from(subject, 0, byte_size(subject), pattern, repl, max_n, 0, [], 0, state, false, fuel) end # Lua 5.3.3+ semantics: an empty match that starts where the *previous* @@ -197,37 +276,40 @@ defmodule Lua.VM.Stdlib.Pattern do # # `size` is the byte count accumulated in `acc`. Replacements can grow the # result without bound relative to the subject, so it is checked against - # the string ceiling as each one is produced (see apply_replacement/5) and + # the string ceiling as each one is produced (see apply_replacement/6) and # once more, with the unmatched remainder, before the result is built. + # + # A stop value raises here with the latest `state`, keeping the heap + # effects of earlier replacement callbacks. - defp gsub_from(subject, pos, len, _pattern, _repl, max_n, count, acc, size, state, _skip_empty?) + defp gsub_from(subject, pos, len, _pattern, _repl, max_n, count, acc, size, state, _skip_empty?, fuel) when pos > len or (max_n != nil and count >= max_n) do # Append remaining subject (clamp pos so we never read past end_of_string) remaining = if pos < len, do: binary_part(subject, pos, len - pos), else: "" - finish_gsub(acc, remaining, size, count, state) + finish_gsub(acc, remaining, size, count, state, fuel) end - defp gsub_from(subject, pos, len, pattern, repl, max_n, count, acc, size, state, skip_empty?) do - case match_pattern(subject, pos, pattern, subject) do - {:match, end_pos, _captures} when skip_empty? and end_pos == pos -> + defp gsub_from(subject, pos, len, pattern, repl, max_n, count, acc, size, state, skip_empty?, fuel) do + case match_pattern(subject, pos, pattern, fuel) do + {:match, end_pos, _captures, fuel} when skip_empty? and end_pos == pos -> # Empty match immediately after a previous match — skip without # replacing, advance by one byte (or terminate at end of subject). if pos < len do char = <<:binary.at(subject, pos)>> - gsub_from(subject, pos + 1, len, pattern, repl, max_n, count, [char | acc], size + 1, state, false) + gsub_from(subject, pos + 1, len, pattern, repl, max_n, count, [char | acc], size + 1, state, false, fuel) else - finish_gsub(acc, "", size, count, state) + finish_gsub(acc, "", size, count, state, fuel) end - {:match, end_pos, captures} -> + {:match, end_pos, captures, fuel} -> if max_n != nil and count >= max_n do remaining = binary_part(subject, pos, len - pos) - finish_gsub(acc, remaining, size, count, state) + finish_gsub(acc, remaining, size, count, state, fuel) else whole_match = binary_part(subject, pos, max(end_pos - pos, 0)) - {replacement, state} = apply_replacement(repl, whole_match, captures, size, state) + {replacement, state, fuel} = apply_replacement(repl, whole_match, captures, size, state, fuel) empty_match? = end_pos == pos next_pos = if empty_match?, do: pos + 1, else: end_pos prefix = if empty_match? and pos < len, do: <<:binary.at(subject, pos)>>, else: "" @@ -248,23 +330,32 @@ defmodule Lua.VM.Stdlib.Pattern do [prefix, replacement | acc], size + byte_size(replacement) + byte_size(prefix), state, - not empty_match? + not empty_match?, + fuel ) end - :nomatch -> + fuel when is_fuel_left(fuel) -> if pos < len do char = <<:binary.at(subject, pos)>> - gsub_from(subject, pos + 1, len, pattern, repl, max_n, count, [char | acc], size + 1, state, false) + gsub_from(subject, pos + 1, len, pattern, repl, max_n, count, [char | acc], size + 1, state, false, fuel) else - finish_gsub(acc, "", size, count, state) + finish_gsub(acc, "", size, count, state, fuel) end + + stop -> + settle!(stop, state) end end - defp finish_gsub(acc, remaining, size, count, state) do - check_result_size!(size + byte_size(remaining), state) - {IO.iodata_to_binary([Enum.reverse(acc), remaining]), count, state} + defp finish_gsub(acc, remaining, size, count, state, fuel) do + result_size = size + byte_size(remaining) + check_result_size!(result_size, state) + + case fuel - result_size do + fuel when is_fuel_left(fuel) -> {IO.iodata_to_binary([Enum.reverse(acc), remaining]), count, state, fuel} + overdrawn -> settle!(overdrawn, state) + end end # The non-stateful `gsub/4` entry calls with `state == nil` and falls back @@ -279,24 +370,25 @@ defmodule Lua.VM.Stdlib.Pattern do # Produces the replacement for one match, refusing it when it would take # the result — `size` bytes so far — past the string ceiling. - defp apply_replacement(repl, whole_match, captures, size, state) when is_binary(repl) do + defp apply_replacement(repl, whole_match, captures, size, state, fuel) when is_binary(repl) do # Replace %0 with whole match, %1-%9 with captures. A replacement with # no `%` comes back as the same binary; otherwise the expansion is # iodata, sized and checked before it is flattened. case replace_captures(repl, whole_match, captures) do literal when is_binary(literal) -> check_result_size!(size + byte_size(literal), state) - {literal, state} + {literal, state, fuel} expansion -> check_result_size!(size + IO.iodata_length(expansion), state) - {IO.iodata_to_binary(expansion), state} + {IO.iodata_to_binary(expansion), state, fuel} end end - defp apply_replacement(repl, whole_match, captures, size, state) when is_function(repl, 2) do + # A callback runs Lua on the same tally: lend it the fuel, take back the rest. + defp apply_replacement(repl, whole_match, captures, size, state, fuel) when is_function(repl, 2) do args = if captures == [], do: [whole_match], else: captures - {result, state} = repl.(args, state) + {result, state} = repl.(args, store_fuel(state, fuel)) replacement = case result do @@ -308,12 +400,12 @@ defmodule Lua.VM.Stdlib.Pattern do end check_result_size!(size + byte_size(replacement), state) - {replacement, state} + {replacement, state, fuel_after_callback(state, fuel)} end - defp apply_replacement(_repl, whole_match, _captures, size, state) do + defp apply_replacement(_repl, whole_match, _captures, size, state, fuel) do check_result_size!(size + byte_size(whole_match), state) - {whole_match, state} + {whole_match, state, fuel} end # The callback may have made heap mutations (global/table/upvalue/metatable @@ -459,13 +551,42 @@ defmodule Lua.VM.Stdlib.Pattern do end {set_elements, rest} = compile_set(rest, []) - {{:set, negated, set_elements}, rest} + {bitmap, classes} = set_membership(set_elements) + {{:set, negated, bitmap, classes}, rest} end defp compile_one_element(<>) do {{:literal, c}, rest} end + # Letters `match_char_class/2` treats as classes; `%` before any other byte + # is that byte. + @class_letters ~c"aAcCdDgGlLpPsSuUwWxXzZ" + + # A 256-bit membership bitmap plus the distinct classes, so a set test does + # not grow with the number of items. + defp set_membership(elements) do + {mask, classes} = + Enum.reduce(elements, {0, []}, fn + {:literal, c}, {mask, classes} -> + {mask ||| 1 <<< c, classes} + + {:range, lo, hi}, {mask, classes} when lo <= hi -> + {mask ||| ((1 <<< (hi - lo + 1)) - 1) <<< lo, classes} + + {:range, _lo, _hi}, membership -> + membership + + {:class, c}, {mask, classes} when c in @class_letters -> + if c in classes, do: {mask, classes}, else: {mask, [c | classes]} + + {:class, c}, {mask, classes} -> + {mask ||| 1 <<< c, classes} + end) + + {<>, classes} + end + defp compile_set("]" <> rest, acc) when acc != [] do {Enum.reverse(acc), rest} end @@ -485,7 +606,11 @@ defmodule Lua.VM.Stdlib.Pattern do # --- Pattern Matcher --- # Match a compiled pattern against subject starting at pos. - # Returns {:match, end_pos, captures} or :nomatch. + # + # Returns `{:match, end_pos, captures, fuel}`, or the fuel on failure: a + # non-negative fuel is no match; a negative one (budget spent) or a binary + # (structural limit) is a stop value callers return untouched. Each call + # costs one step; backtracking calls also spend one level of `depth`. # # Capture model: # `captures` is a list in OPENING order. Each entry is `{:open, start_pos}` @@ -498,141 +623,155 @@ defmodule Lua.VM.Stdlib.Pattern do # # This preserves the Lua-required ordering (captures numbered by opening # position) even for nested groups like `(((.).).* (%w*))`. - defp match_pattern(subject, pos, pattern, full_subject) do - match_elements(subject, pos, pattern, full_subject, [], []) + defp match_pattern(subject, pos, pattern, fuel) do + match_elements(subject, pos, pattern, [], [], fuel - 1, @max_match_depth) end + defp match_elements(_subject, _pos, _pattern, _cstack, _captures, fuel, _depth) when fuel < 0, do: fuel + + defp match_elements(_subject, _pos, _pattern, _cstack, _captures, _fuel, 0), do: "pattern too complex" + # All pattern elements consumed — success - defp match_elements(_subject, pos, [], _full, _cstack, captures) do - {:match, pos, finalize_captures(captures)} + defp match_elements(_subject, pos, [], _cstack, captures, fuel, _depth) do + {:match, pos, finalize_captures(captures), fuel} end # Anchor end — must be at end of string - defp match_elements(subject, pos, [:anchor_end | rest], full, cstack, captures) do + defp match_elements(subject, pos, [:anchor_end | rest], cstack, captures, fuel, depth) do if pos == byte_size(subject) do - match_elements(subject, pos, rest, full, cstack, captures) + match_elements(subject, pos, rest, cstack, captures, fuel - 1, depth) else - :nomatch + fuel end end + defp match_elements(_subject, _pos, [:capture_start | _rest], _cstack, captures, _fuel, _depth) + when length(captures) >= @max_captures, do: "too many captures" + + defp match_elements(_subject, _pos, [:position_capture | _rest], _cstack, captures, _fuel, _depth) + when length(captures) >= @max_captures, do: "too many captures" + # Capture start — append open marker, remember its index on the stack - defp match_elements(subject, pos, [:capture_start | rest], full, cstack, captures) do + defp match_elements(subject, pos, [:capture_start | rest], cstack, captures, fuel, depth) do index = length(captures) - match_elements(subject, pos, rest, full, [index | cstack], captures ++ [{:open, pos}]) + match_elements(subject, pos, rest, [index | cstack], captures ++ [{:open, pos}], fuel - 1, depth) end # Position capture — record the current 1-based byte position as a number - defp match_elements(subject, pos, [:position_capture | rest], full, cstack, captures) do - match_elements(subject, pos, rest, full, cstack, captures ++ [{:done, pos + 1}]) + defp match_elements(subject, pos, [:position_capture | rest], cstack, captures, fuel, depth) do + match_elements(subject, pos, rest, cstack, captures ++ [{:done, pos + 1}], fuel - 1, depth) end # Capture end — replace the topmost open marker with its captured value - defp match_elements(subject, pos, [:capture_end | rest], full, [index | cstack], captures) do + defp match_elements(subject, pos, [:capture_end | rest], [index | cstack], captures, fuel, depth) do {:open, start} = Enum.at(captures, index) captured = binary_part(subject, start, pos - start) captures = List.replace_at(captures, index, {:done, captured}) - match_elements(subject, pos, rest, full, cstack, captures) + match_elements(subject, pos, rest, cstack, captures, fuel - 1, depth) end - # Greedy star (0 or more, greedy) - defp match_elements(subject, pos, [{:greedy_star, elem} | rest], full, cstack, captures) do + # Greedy star (0 or more, greedy). One step per byte scanned. + defp match_elements(subject, pos, [{:greedy_star, elem} | rest], cstack, captures, fuel, depth) do # Find max consecutive matches max_pos = greedy_count(subject, pos, elem) # Try from max down to 0 - backtrack_greedy(subject, pos, max_pos, rest, full, cstack, captures) + backtrack_greedy(subject, pos, max_pos, rest, cstack, captures, fuel - (max_pos - pos), depth) end # Greedy plus (1 or more, greedy) - defp match_elements(subject, pos, [{:greedy_plus, elem} | rest], full, cstack, captures) do + defp match_elements(subject, pos, [{:greedy_plus, elem} | rest], cstack, captures, fuel, depth) do if match_class(subject, pos, elem) do max_pos = greedy_count(subject, pos, elem) - backtrack_greedy(subject, pos + 1, max_pos, rest, full, cstack, captures) + backtrack_greedy(subject, pos + 1, max_pos, rest, cstack, captures, fuel - (max_pos - pos), depth) else - :nomatch + fuel end end # Lazy star (0 or more, lazy) - defp match_elements(subject, pos, [{:lazy_star, elem} | rest], full, cstack, captures) do - lazy_match(subject, pos, elem, rest, full, cstack, captures) + defp match_elements(subject, pos, [{:lazy_star, elem} | rest], cstack, captures, fuel, depth) do + lazy_match(subject, pos, elem, rest, cstack, captures, fuel, depth) end # Optional (0 or 1) - defp match_elements(subject, pos, [{:optional, elem} | rest], full, cstack, captures) do + defp match_elements(subject, pos, [{:optional, elem} | rest], cstack, captures, fuel, depth) do # Try with 1 match first if match_class(subject, pos, elem) do - case match_elements(subject, pos + 1, rest, full, cstack, captures) do - {:match, _, _} = result -> result - :nomatch -> match_elements(subject, pos, rest, full, cstack, captures) + case match_elements(subject, pos + 1, rest, cstack, captures, fuel - 1, depth - 1) do + fuel when is_fuel_left(fuel) -> match_elements(subject, pos, rest, cstack, captures, fuel - 1, depth) + result -> result end else - match_elements(subject, pos, rest, full, cstack, captures) + match_elements(subject, pos, rest, cstack, captures, fuel - 1, depth) end end # Backref — references a previously-closed capture by 1-based index. - # Open captures and out-of-range references fall through to :nomatch. - defp match_elements(subject, pos, [{:backref, n} | rest], full, cstack, captures) do + # Open captures and out-of-range references fail to match. One step per + # byte compared. + defp match_elements(subject, pos, [{:backref, n} | rest], cstack, captures, fuel, depth) do case Enum.at(captures, n - 1) do {:done, captured} when is_binary(captured) -> cap_len = byte_size(captured) if pos + cap_len <= byte_size(subject) and binary_part(subject, pos, cap_len) == captured do - match_elements(subject, pos + cap_len, rest, full, cstack, captures) + match_elements(subject, pos + cap_len, rest, cstack, captures, fuel - 1 - cap_len, depth) else - :nomatch + fuel - cap_len end _ -> - :nomatch + fuel end end - # Balanced match %bxy - defp match_elements(subject, pos, [{:balanced, open, close} | rest], full, cstack, captures) do + # Balanced match %bxy. One step per byte scanned. + defp match_elements(subject, pos, [{:balanced, open, close} | rest], cstack, captures, fuel, depth) do case match_balanced(subject, pos, open, close) do - {:ok, end_pos} -> match_elements(subject, end_pos, rest, full, cstack, captures) - :nomatch -> :nomatch + {:ok, end_pos} -> match_elements(subject, end_pos, rest, cstack, captures, fuel - 1 - (end_pos - pos), depth) + {:nomatch, scan_end} -> fuel - (scan_end - pos) end end # Single element match - defp match_elements(subject, pos, [elem | rest], full, cstack, captures) do + defp match_elements(subject, pos, [elem | rest], cstack, captures, fuel, depth) do if match_class(subject, pos, elem) do - match_elements(subject, pos + 1, rest, full, cstack, captures) + match_elements(subject, pos + 1, rest, cstack, captures, fuel - 1, depth) else - :nomatch + fuel end end # Greedy backtracking: try longest match first - defp backtrack_greedy(_subject, min_pos, pos, _rest, _full, _cstack, _captures) when pos < min_pos do - :nomatch + defp backtrack_greedy(_subject, min_pos, pos, _rest, _cstack, _captures, fuel, _depth) when pos < min_pos do + fuel end - defp backtrack_greedy(subject, min_pos, pos, rest, full, cstack, captures) do - case match_elements(subject, pos, rest, full, cstack, captures) do - {:match, _, _} = result -> result - :nomatch -> backtrack_greedy(subject, min_pos, pos - 1, rest, full, cstack, captures) + defp backtrack_greedy(subject, min_pos, pos, rest, cstack, captures, fuel, depth) do + case match_elements(subject, pos, rest, cstack, captures, fuel - 1, depth - 1) do + fuel when is_fuel_left(fuel) -> + backtrack_greedy(subject, min_pos, pos - 1, rest, cstack, captures, fuel, depth) + + result -> + result end end # Lazy matching: try shortest match first - defp lazy_match(subject, pos, elem, rest, full, cstack, captures) do + defp lazy_match(subject, pos, elem, rest, cstack, captures, fuel, depth) do # Try matching 0 characters first - case match_elements(subject, pos, rest, full, cstack, captures) do - {:match, _, _} = result -> - result - - :nomatch -> + case match_elements(subject, pos, rest, cstack, captures, fuel - 1, depth - 1) do + fuel when is_fuel_left(fuel) -> # Try consuming one more character if match_class(subject, pos, elem) do - lazy_match(subject, pos + 1, elem, rest, full, cstack, captures) + lazy_match(subject, pos + 1, elem, rest, cstack, captures, fuel, depth) else - :nomatch + fuel end + + result -> + result end end @@ -645,18 +784,18 @@ defmodule Lua.VM.Stdlib.Pattern do end end - # Match balanced %bxy + # Match balanced %bxy. Returns `{:ok, end_pos}` or `{:nomatch, scan_end}`. defp match_balanced(subject, pos, open, close) do len = byte_size(subject) if pos >= len or :binary.at(subject, pos) != open do - :nomatch + {:nomatch, pos} else match_balanced_inner(subject, pos + 1, len, open, close, 1) end end - defp match_balanced_inner(_subject, pos, len, _open, _close, _depth) when pos >= len, do: :nomatch + defp match_balanced_inner(_subject, pos, len, _open, _close, _depth) when pos >= len, do: {:nomatch, len} defp match_balanced_inner(subject, pos, len, open, close, depth) do c = :binary.at(subject, pos) @@ -687,19 +826,15 @@ defmodule Lua.VM.Stdlib.Pattern do match_char_class(ch, c) end - defp match_class(subject, pos, {:set, negated, elements}) do + defp match_class(subject, pos, {:set, negated, bitmap, classes}) do ch = :binary.at(subject, pos) - - matched = - Enum.any?(elements, fn - {:literal, c} -> ch == c - {:class, c} -> match_char_class(ch, c) - {:range, lo, hi} -> ch >= lo and ch <= hi - end) - - if negated, do: not matched, else: matched + matched = (:binary.at(bitmap, ch >>> 3) >>> (ch &&& 7) &&& 1) == 1 or in_classes?(ch, classes) + matched != negated end + defp in_classes?(_ch, []), do: false + defp in_classes?(ch, [c | rest]), do: match_char_class(ch, c) or in_classes?(ch, rest) + # Character class matchers defp match_char_class(ch, ?a), do: ch in ?a..?z or ch in ?A..?Z defp match_char_class(ch, ?A), do: not (ch in ?a..?z or ch in ?A..?Z) @@ -757,4 +892,38 @@ defmodule Lua.VM.Stdlib.Pattern do acc -> Enum.reverse(acc) end end + + # --- Step budget --- + # + # Fuel is the steps left before the tally reaches `max_instructions`, so it + # alone determines the tally to charge back. + + defp available_fuel(%State{max_instructions: max, instruction_count: tally}) when is_integer(max) do + (max - 1 - tally) * @steps_per_instruction + end + + defp available_fuel(_state), do: @unbounded_fuel + + defp store_fuel(%State{max_instructions: max} = state, fuel) when is_integer(max) do + %{state | instruction_count: max - 1 - div(fuel, @steps_per_instruction)} + end + + defp store_fuel(state, _fuel), do: state + + # `store_fuel/2` kept whole instructions only; the lent remainder comes back. + defp fuel_after_callback(%State{max_instructions: max} = state, lent_fuel) when is_integer(max) do + available_fuel(state) + rem(lent_fuel, @steps_per_instruction) + end + + defp fuel_after_callback(_state, lent_fuel), do: lent_fuel + + # Charges what is left, or raises with `state` so `pcall` keeps heap effects. + defp settle!(fuel, state) when is_fuel_left(fuel), do: store_fuel(state, fuel) + + # Ticking past the last allowed instruction raises the budget error. + defp settle!(fuel, %State{max_instructions: max} = state) when is_integer(fuel), do: State.tick!(state, max - 1) + + defp settle!(message, state) when is_binary(message) do + raise RuntimeError, value: message, state: state + end end diff --git a/lib/lua/vm/stdlib/string.ex b/lib/lua/vm/stdlib/string.ex index 28f5753..3742edb 100644 --- a/lib/lua/vm/stdlib/string.ex +++ b/lib/lua/vm/stdlib/string.ex @@ -79,6 +79,7 @@ defmodule Lua.VM.Stdlib.String do # string.lower(s) - converts string to lowercase defp string_lower([str | _], state) when is_binary(str) do + state = Limits.charge!(state, byte_size(str)) {[String.downcase(str)], state} end @@ -92,6 +93,7 @@ defmodule Lua.VM.Stdlib.String do # string.upper(s) - converts string to uppercase defp string_upper([str | _], state) when is_binary(str) do + state = Limits.charge!(state, byte_size(str)) {[String.upcase(str)], state} end @@ -209,18 +211,17 @@ defmodule Lua.VM.Stdlib.String do got: Util.typeof(sep) end - result = - if n <= 0 do - "" - else - # Compute the result size from the count *before* building it, so an - # oversized request fails with a catchable error instead of trying to - # allocate (and OOM the host on) a multi-petabyte binary. - Limits.check_string_size!(n * byte_size(str) + (n - 1) * byte_size(sep), state.max_string_bytes) - build_rep(str, n, sep) - end - - {[result], state} + if n <= 0 do + {[""], state} + else + # Compute the result size from the count *before* building it, so an + # oversized request fails with a catchable error instead of trying to + # allocate (and OOM the host on) a multi-petabyte binary. + size = n * byte_size(str) + (n - 1) * byte_size(sep) + Limits.check_string_size!(size, state.max_string_bytes) + state = Limits.charge!(state, size) + {[build_rep(str, n, sep)], state} + end end # Build the repeated string with allocation proportional to the *result* @@ -238,6 +239,7 @@ defmodule Lua.VM.Stdlib.String do # byte arrays, not codepoint sequences — so a NUL or non-UTF-8 byte # must come back at the mirror position). defp string_reverse([str | _], state) when is_binary(str) do + state = Limits.charge!(state, byte_size(str)) reversed = str |> :binary.bin_to_list() |> Enum.reverse() |> :binary.list_to_bin() {[reversed], state} end @@ -276,14 +278,14 @@ defmodule Lua.VM.Stdlib.String do posi = if i < 0, do: max(len + i + 1, 1), else: max(i, 1) posj = if j < 0, do: len + j + 1, else: min(j, len) - bytes = - if posj < posi or posi > len or posj < 1 do - [] - else - Enum.map(posi..posj//1, fn idx -> :binary.at(str, idx - 1) end) - end - - {bytes, state} + if posj < posi or posi > len or posj < 1 do + {[], state} + else + count = posj - posi + 1 + Limits.check_slice_count!(count, state.max_table_elements) + state = Limits.charge!(state, count) + {:binary.bin_to_list(str, posi - 1, count), state} + end end defp string_byte([other | _], _state) do @@ -296,6 +298,8 @@ defmodule Lua.VM.Stdlib.String do # string.char(...) - converts byte values to characters defp string_char(args, state) do + state = Limits.charge_elements!(state, args) + result = args |> Enum.with_index(1) @@ -338,6 +342,7 @@ defmodule Lua.VM.Stdlib.String do # string.format(formatstring, ...) - formats strings with C-style format specifiers defp string_format([fmt | args], state) when is_binary(fmt) do + state = charge_format!(state, fmt, args) {segments, state} = compiled_format(fmt, state) # `argn` is the 1-based position of the next value argument. The format # string is arg #1, so the first conversion consumes arg #2; PUC reports a @@ -356,6 +361,15 @@ defmodule Lua.VM.Stdlib.String do raise_arg_expected(1, "format") end + defp charge_format!(%State{max_instructions: :infinity} = state, _fmt, _args), do: state + defp charge_format!(state, fmt, args), do: Limits.charge!(state, byte_size(fmt) + string_argument_bytes(args, 0)) + + defp string_argument_bytes([arg | rest], total) when is_binary(arg), + do: string_argument_bytes(rest, total + byte_size(arg)) + + defp string_argument_bytes([_arg | rest], total), do: string_argument_bytes(rest, total) + defp string_argument_bytes([], total), do: total + # Look the format string up in the per-VM template cache, compiling and # memoizing it on a miss. The parse (literal splitting + spec scanning) is # independent of the arguments, so a format string reused across calls is @@ -1065,6 +1079,8 @@ defmodule Lua.VM.Stdlib.String do true -> 0 end + state = Limits.charge!(state, len - search_pos + byte_size(pattern)) + case :binary.match(s, pattern, scope: {search_pos, len - search_pos}) do {start, found_len} -> {[start + 1, start + found_len], state} @@ -1074,11 +1090,11 @@ defmodule Lua.VM.Stdlib.String do end end else - case Pattern.find(s, pattern, init) do - {start, stop, captures} -> + case Pattern.find(s, pattern, init, state) do + {{start, stop, captures}, state} -> {[start, stop | captures], state} - :nomatch -> + {:nomatch, state} -> {[nil], state} end end @@ -1095,9 +1111,9 @@ defmodule Lua.VM.Stdlib.String do init = Enum.at(rest, 0, 1) init = if is_number(init), do: trunc(init), else: 1 - case Pattern.match(s, pattern, init) do - {:match, captures} -> {captures, state} - :nomatch -> {[nil], state} + case Pattern.match(s, pattern, init, state) do + {{:match, captures}, state} -> {captures, state} + {:nomatch, state} -> {[nil], state} end end @@ -1109,23 +1125,16 @@ defmodule Lua.VM.Stdlib.String do # string.gmatch(s, pattern) - returns iterator function defp string_gmatch([s, pattern | _], state) when is_binary(s) and is_binary(pattern) do - # Pre-compute all matches, return an iterator that yields them one by one - matches = Pattern.gmatch(s, pattern) - idx_ref = make_ref() - state = %{state | private: Map.put(state.private, idx_ref, {matches, 0})} + {iterator, state} = Pattern.gmatch_start(pattern, state) + iterator_key = make_ref() + state = State.put_private(state, iterator_key, iterator) iter_func = {:native_func, - fn _args, st -> - {match_list, current_idx} = Map.get(st.private, idx_ref) - - if current_idx >= length(match_list) do - {[nil], st} - else - result = Enum.at(match_list, current_idx) - st = %{st | private: Map.put(st.private, idx_ref, {match_list, current_idx + 1})} - {result, st} - end + fn _args, call_state -> + iterator = State.get_private(call_state, iterator_key) + {result, iterator, call_state} = Pattern.gmatch_next(s, iterator, call_state) + {result || [nil], State.put_private(call_state, iterator_key, iterator)} end} {[iter_func], state} @@ -1261,8 +1270,11 @@ defmodule Lua.VM.Stdlib.String do end # string.pack(fmt, v1, v2, ...) — pack values per fmt + # Padding and `c` make the result's size unknown until it is built. defp string_pack([fmt | args], state) when is_binary(fmt) do - {[Pack.pack(fmt, args, state.max_string_bytes)], state} + state = Limits.charge!(state, byte_size(fmt)) + packed = Pack.pack(fmt, args, state.max_string_bytes) + {[packed], Limits.charge!(state, byte_size(packed))} end defp string_pack([other | _], _state), do: raise_string_expected(1, "pack", other) @@ -1278,8 +1290,8 @@ defmodule Lua.VM.Stdlib.String do _ -> raise ArgumentError, function_name: "string.unpack", arg_num: 3, expected: "number" end - results = Pack.unpack(fmt, s, pos) - {results, state} + state = Limits.charge!(state, byte_size(fmt)) + {Pack.unpack(fmt, s, pos, state.max_table_elements), state} end defp string_unpack([fmt, other | _], _state) when is_binary(fmt) do @@ -1291,6 +1303,7 @@ defmodule Lua.VM.Stdlib.String do # string.packsize(fmt) — return size in bytes for fixed-size formats defp string_packsize([fmt | _], state) when is_binary(fmt) do + state = Limits.charge!(state, byte_size(fmt)) {[Pack.packsize(fmt)], state} end diff --git a/lib/lua/vm/stdlib/string/pack.ex b/lib/lua/vm/stdlib/string/pack.ex index 3bfe29f..c38d71f 100644 --- a/lib/lua/vm/stdlib/string/pack.ex +++ b/lib/lua/vm/stdlib/string/pack.ex @@ -54,10 +54,16 @@ defmodule Lua.VM.Stdlib.String.Pack do do_pack(ops, args, <<>>, max_bytes) end - @doc "Implements string.unpack(fmt, s [, pos])." - def unpack(fmt, s, pos) when is_binary(fmt) and is_binary(s) and is_integer(pos) do + @doc """ + Implements string.unpack(fmt, s [, pos]). + + `max_results` is the element ceiling (a state's `max_table_elements`); a + format that would return more values raises "too many results". + """ + def unpack(fmt, s, pos, max_results) when is_binary(fmt) and is_binary(s) and is_integer(pos) do init_pos = normalize_init_pos(pos, byte_size(s)) ops = parse(fmt) + Limits.check_result_count!(Enum.count(ops, &value_op?/1) + 1, max_results) do_unpack(ops, s, init_pos, []) end @@ -475,6 +481,10 @@ defmodule Lua.VM.Stdlib.String.Pack do end end + defp value_op?({:align, _alignment}), do: false + defp value_op?({:padding, _n}), do: false + defp value_op?(_op), do: true + defp ensure_available(s, pos, size, msg) do if pos + size > byte_size(s) do raise_runtime(msg) diff --git a/lib/lua/vm/stdlib/table.ex b/lib/lua/vm/stdlib/table.ex index 6cb7a5d..2568e0e 100644 --- a/lib/lua/vm/stdlib/table.ex +++ b/lib/lua/vm/stdlib/table.ex @@ -77,6 +77,11 @@ defmodule Lua.VM.Stdlib.Table do details: "position out of bounds" end + # `len` may come from `__len`. + shift_count = len - pos + 1 + Limits.check_range_count!(shift_count, state.max_table_elements, "table.insert") + state = Limits.charge!(state, shift_count) + # Shift t[pos..len] up by one (top-down so reads stay coherent), then # write `value` into t[pos]. Reads route through __index, writes # through __newindex. @@ -161,7 +166,10 @@ defmodule Lua.VM.Stdlib.Table do # t[len + 1], which was already nil. state = if pos < len do - Enum.reduce((pos + 1)..len//1, state, fn i, st -> + shift_count = len - pos + Limits.check_range_count!(shift_count, state.max_table_elements, "table.remove") + + Enum.reduce((pos + 1)..len//1, Limits.charge!(state, shift_count), fn i, st -> {v, st} = Executor.table_index(tref, i, st) Executor.table_newindex(tref, i - 1, v, st) end) @@ -220,7 +228,8 @@ defmodule Lua.VM.Stdlib.Table do table = Map.fetch!(state.tables, id) # Refuse an oversized range before allocating the result list. - if i <= j, do: Limits.check_range_count!(j - i + 1, "table.concat") + if i <= j, do: Limits.check_range_count!(j - i + 1, state.max_table_elements, "table.concat") + state = Limits.charge!(state, j - i + 1) {elements, state} = cond do @@ -247,8 +256,9 @@ defmodule Lua.VM.Stdlib.Table do # A table can hold one string many times for a few words each, so the # joined size is unrelated to the table's own footprint. Sum the pieces # and refuse an oversized result before the join allocates it. - separator_bytes = max(j - i, 0) * byte_size(sep) - Limits.check_string_size!(IO.iodata_length(elements) + separator_bytes, state.max_string_bytes, state) + size = IO.iodata_length(elements) + max(j - i, 0) * byte_size(sep) + Limits.check_string_size!(size, state.max_string_bytes, state) + state = Limits.charge!(state, size) # concat_value/2 made every element a binary, so with no separator the # list is already the result's iodata. @@ -289,28 +299,16 @@ defmodule Lua.VM.Stdlib.Table do # than mutating the raw table mid-sort. {len, state} = Executor.table_length(tref, state) - # Mirror ltablib.c sort: reject lengths at/above INT_MAX before - # touching the table, so a `__len` that returns a huge value raises - # "array too big" instead of materialising billions of slots. - if len > 1 and len >= @max_sort_length do - raise ArgumentError, - function_name: "table.sort", - arg_num: 1, - details: "array too big" - end - - # Host-protection ceiling below INT_MAX. `sort_via_metamethods` eagerly - # materialises `len` slots via __index before any comparator runs, so a - # hostile `__len` returning e.g. ~100M (well under INT_MAX) would still - # exhaust the BEAM. Share `Limits.max_element_count` with - # `concat`/`unpack`/`move` so the deterministic ceiling is uniform. - if len > Limits.max_element_count() do + # ltablib.c rejects at INT_MAX; `sort_via_metamethods` materialises every + # slot up front, so the element ceiling applies too. + if (len > 1 and len >= @max_sort_length) or len > state.max_table_elements do raise ArgumentError, function_name: "table.sort", arg_num: 1, details: "array too big" end + state = Limits.charge!(state, sort_comparisons(len)) table = Map.fetch!(state.tables, id) if table.metatable == nil do @@ -332,6 +330,9 @@ defmodule Lua.VM.Stdlib.Table do raise ArgumentError.value_expected("table.sort", 1) end + defp sort_comparisons(len) when len < 2, do: 0 + defp sort_comparisons(len), do: len * ceil(:math.log2(len)) + # Fast path for a metatable-less table: read each slot directly from # `data`, sort, then merge the sorted slice back over `data` in one pass. # Skips the __index/__newindex dispatch machinery entirely, which is safe @@ -400,28 +401,27 @@ defmodule Lua.VM.Stdlib.Table do {Enum.sort(values, &default_compare/2), state} end - defp sort_values(values, comp, state) do - # `Enum.sort/2` cannot thread external state through its comparator, - # so we use a stable insertion sort that does. Sort sizes here track - # the table being sorted, so for a 1000-element table this is - # O(n^2). Acceptable for now — matches the cost ceiling of calling - # `comp` n*log(n) times in any case (comp is the dominant cost). - Enum.reduce(values, {[], state}, fn val, {sorted, st} -> - {inserted, st} = insert_sorted(sorted, val, comp, st) - {inserted, st} - end) - end + # `Enum.sort/2` cannot thread state through the comparator. A stable merge + # sort does, and stays within the `sort_comparisons/1` calls charged above. + defp sort_values(values, comp, state), do: merge_sort(values, length(values), comp, state) - defp insert_sorted([], val, _comp, state), do: {[val], state} + defp merge_sort(values, count, _comp, state) when count < 2, do: {values, state} - defp insert_sorted([head | tail] = list, val, comp, state) do - {less?, state} = invoke_compare(comp, val, head, state) + defp merge_sort(values, count, comp, state) do + left_count = div(count, 2) + {left, right} = Enum.split(values, left_count) + {left, state} = merge_sort(left, left_count, comp, state) + {right, state} = merge_sort(right, count - left_count, comp, state) + merge_sorted(left, right, comp, state, []) + end - if less? do - {[val | list], state} - else - {rest, state} = insert_sorted(tail, val, comp, state) - {[head | rest], state} + defp merge_sorted([], right, _comp, state, merged), do: {Enum.reverse(merged, right), state} + defp merge_sorted(left, [], _comp, state, merged), do: {Enum.reverse(merged, left), state} + + defp merge_sorted([left_head | left_rest] = left, [right_head | right_rest] = right, comp, state, merged) do + case invoke_compare(comp, right_head, left_head, state) do + {true, state} -> merge_sorted(left, right_rest, comp, state, [right_head | merged]) + {false, state} -> merge_sorted(left_rest, right, comp, state, [left_head | merged]) end end @@ -443,12 +443,15 @@ defmodule Lua.VM.Stdlib.Table do # table.pack(...) defp table_pack(args, state) do + count = length(args) + state = Limits.charge!(state, count) + # Create a table with all arguments and 'n' field data = args |> Enum.with_index(1) |> Map.new(fn {val, idx} -> {idx, val} end) - |> Map.put("n", length(args)) + |> Map.put("n", count) {tref, state} = State.alloc_table(state, data) {[tref], state} @@ -485,18 +488,14 @@ defmodule Lua.VM.Stdlib.Table do got: Util.typeof(j) end - # Reject an oversized result count before materialising anything. - # `ltablib.c` rejects only at INT_MAX (count overflow plus the - # `lua_checkstack` arm), but on the BEAM even a sub-INT_MAX count like - # `table.unpack({}, 1, 5e8)` would build hundreds of millions of nils - # and exhaust the host. We share `Limits.max_element_count` with - # `concat`/`move` so the deterministic ceiling is uniform, well below - # INT_MAX yet far above any legitimate unpack. The subtraction stays - # within Elixir's arbitrary-precision integers, so it cannot overflow. - if i <= j and j - i >= Limits.max_element_count() do + # Reject an oversized result count before materialising anything, with + # the message `lua_checkstack` gives at PUC's stack limit. + if i <= j and j - i >= state.max_table_elements do raise RuntimeError.exception(value: "too many results to unpack") end + state = Limits.charge!(state, j - i + 1) + # Read each element via __index. Empty range (i > j) returns no # values. Matches `ltablib.c` which uses `lua_geti` per slot. {results, state} = @@ -655,9 +654,11 @@ defmodule Lua.VM.Stdlib.Table do # *does* take the ceiling: sort eagerly materialises every slot before # any comparator runs, so it has no per-step abort to rely on.) if plain_tables?(tref1, tref2, state) do - Limits.check_range_count!(n, "table.move") + Limits.check_range_count!(n, state.max_table_elements, "table.move") end + state = Limits.charge!(state, n) + # PUC chooses copy direction so an in-place overlapping move stays # coherent: copy forward when the destination cannot clobber an # un-read source slot (t > e || t <= f), otherwise copy backward. diff --git a/lib/lua/vm/stdlib/utf8.ex b/lib/lua/vm/stdlib/utf8.ex index 114c288..33b3ef7 100644 --- a/lib/lua/vm/stdlib/utf8.ex +++ b/lib/lua/vm/stdlib/utf8.ex @@ -25,6 +25,7 @@ defmodule Lua.VM.Stdlib.Utf8 do import Bitwise alias Lua.VM.ArgumentError + alias Lua.VM.Limits alias Lua.VM.RuntimeError alias Lua.VM.State alias Lua.VM.Stdlib.Util @@ -55,6 +56,8 @@ defmodule Lua.VM.Stdlib.Utf8 do # --------------------------------------------------------------------------- defp utf8_char(args, state) do + state = Limits.charge_elements!(state, args) + iolist = args |> Enum.with_index(1) @@ -128,16 +131,20 @@ defmodule Lua.VM.Stdlib.Utf8 do details: "out of range" end - {collect_codepoints(s, posi, posj, []), state} + state = Limits.charge!(state, posj - posi + 1) + + {collect_codepoints(s, posi, posj, [], 0, state.max_table_elements), state} end - defp collect_codepoints(_s, posi, posj, acc) when posi > posj do + defp collect_codepoints(_s, posi, posj, acc, _count, _max_count) when posi > posj do Enum.reverse(acc) end - defp collect_codepoints(s, posi, posj, acc) do + defp collect_codepoints(s, posi, posj, acc, count, max_count) do + Limits.check_slice_count!(count + 1, max_count) + case decode_at(s, posi) do - {cp, len} -> collect_codepoints(s, posi + len, posj, [cp | acc]) + {cp, len} -> collect_codepoints(s, posi + len, posj, [cp | acc], count + 1, max_count) :invalid -> raise RuntimeError, value: "invalid UTF-8 code" end end @@ -180,6 +187,7 @@ defmodule Lua.VM.Stdlib.Utf8 do details: "final position out of string" end + state = Limits.charge!(state, posj - posi + 1) {do_utf8_len(s, posi, posj, 0), state} end @@ -230,9 +238,14 @@ defmodule Lua.VM.Stdlib.Utf8 do # Operate in 0-based byte index internally (`pos`); convert back at end. pos = posi - 1 result = do_offset(s, n, pos, len) - {result, state} + {result, Limits.charge!(state, scanned_bytes(result, n, posi, len))} end + # A scan that finds no character has run to the end it was moving toward. + defp scanned_bytes([nil], n, posi, len) when n > 0, do: len + 1 - posi + defp scanned_bytes([nil], _n, posi, _len), do: posi - 1 + defp scanned_bytes([pos], _n, posi, _len), do: abs(pos - posi) + defp do_offset(s, 0, pos, _len) do pos = scan_back_to_char_start(s, pos) [pos + 1] 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 diff --git a/test/lua/vm/max_table_elements_test.exs b/test/lua/vm/max_table_elements_test.exs new file mode 100644 index 0000000..8c096da --- /dev/null +++ b/test/lua/vm/max_table_elements_test.exs @@ -0,0 +1,132 @@ +defmodule Lua.VM.MaxTableElementsTest do + @moduledoc "Pins the `:max_table_elements` ceiling." + use ExUnit.Case, async: true + + import Lua.Test.Bounded, only: [eval: 2, eval: 3] + + defp small_ceiling_lua, do: Lua.new(max_table_elements: 100) + + describe "default ceiling" do + test "refuses the table.unpack bomb before allocating" do + code = ~S|return pcall(function() return select('#', table.unpack({}, 1, 9999999)) end)| + assert {:ok, [false, message]} = eval(Lua.new(), code, timeout_ms: 5_000, heap_bytes: 64 * 1024 * 1024) + assert message =~ "too many results to unpack" + end + + test "is one million" do + assert {:ok, [1_000_000]} = eval(Lua.new(), ~S|return select('#', table.unpack({}, 1, 1000000))|) + assert {:ok, [false, message]} = eval(Lua.new(), ~S|return pcall(table.unpack, {}, 1, 1000001)|) + assert message =~ "too many results to unpack" + end + end + + describe "a lowered ceiling" do + test "bounds table.unpack" do + assert {:ok, [100]} = eval(small_ceiling_lua(), ~S|return select('#', table.unpack({}, 1, 100))|) + assert {:ok, [false, message]} = eval(small_ceiling_lua(), ~S|return pcall(table.unpack, {}, 1, 101)|) + assert message =~ "too many results to unpack" + end + + test "bounds table.concat, table.move and table.sort" do + assert {:ok, [false, concat]} = eval(small_ceiling_lua(), ~S|return pcall(table.concat, {}, ",", 1, 101)|) + assert concat =~ "range too large" + + assert {:ok, [false, move]} = eval(small_ceiling_lua(), ~S|return pcall(table.move, {}, 1, 101, 1)|) + assert move =~ "range too large" + + sort = ~S|local t = {} for i = 1, 101 do t[i] = i end return pcall(table.sort, t)| + assert {:ok, [false, sort_message]} = eval(small_ceiling_lua(), sort) + assert sort_message =~ "array too big" + + in_bounds = ~S""" + local t = {} + for i = 1, 100 do t[i] = 101 - i end + table.sort(t) + local moved = table.move(t, 1, 100, 1, {}) + return t[1], t[100], #table.concat(moved, ","), moved[100] + """ + + assert {:ok, [1, 100, 291, 100]} = eval(small_ceiling_lua(), in_bounds) + end + + test "bounds string.byte and utf8.codepoint" do + byte = ~S|return pcall(string.byte, string.rep("a", 101), 1, -1)| + assert {:ok, [false, byte_message]} = eval(small_ceiling_lua(), byte) + assert byte_message =~ "string slice too long" + + codepoint = ~S|return pcall(utf8.codepoint, string.rep("a", 101), 1, -1)| + assert {:ok, [false, codepoint_message]} = eval(small_ceiling_lua(), codepoint) + assert codepoint_message =~ "string slice too long" + + in_bounds = + ~S|local s = string.rep("a", 100) return select('#', string.byte(s, 1, -1)), select('#', utf8.codepoint(s, 1, -1))| + + assert {:ok, [100, 100]} = eval(small_ceiling_lua(), in_bounds) + end + + test "counts utf8.codepoint results, not the bytes they span" do + in_bounds = ~S|return select('#', utf8.codepoint(string.rep("é", 100), 1, -1))| + assert {:ok, [100]} = eval(small_ceiling_lua(), in_bounds) + + over = ~S|return pcall(utf8.codepoint, string.rep("é", 101), 1, -1)| + assert {:ok, [false, message]} = eval(small_ceiling_lua(), over) + assert message =~ "string slice too long" + end + + test "bounds string.unpack, counting the trailing position" do + over = ~S|return pcall(string.unpack, string.rep("b", 100), string.rep("x", 100))| + assert {:ok, [false, message]} = eval(small_ceiling_lua(), over) + assert message =~ "too many results" + + in_bounds = ~S|return select('#', string.unpack(string.rep("b", 99), string.rep("x", 99)))| + assert {:ok, [100]} = eval(small_ceiling_lua(), in_bounds) + end + end + + describe "table.insert and table.remove" do + @lying_len ~S|setmetatable({}, {__len = function() return math.maxinteger end})| + + test "refuse a shift past the ceiling" do + assert {:ok, [false, insert]} = eval(Lua.new(), "return pcall(table.insert, #{@lying_len}, 1, 'x')") + assert insert =~ "range too large" + + assert {:ok, [false, remove]} = eval(Lua.new(), "return pcall(table.remove, #{@lying_len}, 1)") + assert remove =~ "range too large" + end + + test "still shift ordinary lists" do + code = ~S""" + local t = {1, 2, 3} + table.insert(t, 1, 0) + table.insert(t, 9) + local removed = table.remove(t, 2) + return removed, table.concat(t, ",") + """ + + assert {:ok, [1, "0,2,3,9"]} = eval(small_ceiling_lua(), code) + end + end + + test ":infinity lifts the ceiling" do + unbounded = Lua.new(max_table_elements: :infinity) + assert {:ok, [1_000_001]} = eval(unbounded, ~S|return select('#', table.unpack({}, 1, 1000001))|) + + assert {:ok, [1_000_001]} = + eval(unbounded, ~S|local s = string.rep("a", 1000001) return select('#', string.byte(s, 1, -1))|) + end + + describe "option validation" do + test "rejects non-positive and non-integer values" do + for bad <- [0, -1, 1.5, "1m", nil] do + assert_raise ArgumentError, ~r/:max_table_elements must be a positive integer or :infinity/, fn -> + Lua.new(max_table_elements: bad) + end + end + end + + test "accepts a positive integer or :infinity" do + assert %Lua{} = Lua.new(max_table_elements: 1) + assert %Lua{} = Lua.new(max_table_elements: :infinity) + end + end +end diff --git a/test/lua/vm/multi_value_scaling_test.exs b/test/lua/vm/multi_value_scaling_test.exs new file mode 100644 index 0000000..b57ff7b --- /dev/null +++ b/test/lua/vm/multi_value_scaling_test.exs @@ -0,0 +1,33 @@ +defmodule Lua.VM.MultiValueScalingTest do + @moduledoc "Pins linear-time placement of multi-results and varargs into registers." + use ExUnit.Case, async: true + + import Lua.Test.Bounded, only: [eval: 3] + + defp eval(code), do: eval(Lua.new(), code, timeout_ms: 5_000) + + test "at the top level of a chunk" do + code = ~S""" + local s = string.rep("a", 200000) + local t = {string.byte(s, 1, -1)} + return #t, select('#', table.unpack(t)), select('#', string.byte(s, 1, -1)) + """ + + assert {:ok, [200_000, 200_000, 200_000]} = eval(code) + end + + test "through varargs and forwarded calls" do + code = ~S""" + local function count(...) return select('#', ...) end + local function forward(...) return count(...) end + local function pack(...) local t = {...} return #t end + local function run(n) + local s = string.rep("a", n) + return forward(string.byte(s, 1, -1)), pack(string.byte(s, 1, -1)), select('#', table.unpack({}, 1, n)) + end + return run(200000) + """ + + assert {:ok, [200_000, 200_000, 200_000]} = eval(code) + end +end diff --git a/test/lua/vm/native_work_budget_test.exs b/test/lua/vm/native_work_budget_test.exs new file mode 100644 index 0000000..6ef8f44 --- /dev/null +++ b/test/lua/vm/native_work_budget_test.exs @@ -0,0 +1,142 @@ +defmodule Lua.VM.NativeWorkBudgetTest do + @moduledoc "Pins the instruction budget's charge for work done inside stdlib calls." + use ExUnit.Case, async: true + + import Lua.Test.Bounded, only: [eval: 3] + + @single_call_bombs [ + ~S|return select("#", string.byte(string.rep("x", 1000000), 1, -1))|, + ~S|local t = {string.byte(string.rep("x", 1000000), 1, -1)} return #t|, + ~S|return select("#", utf8.codepoint(string.rep("x", 1000000), 1, -1))|, + ~S|local s = string.rep("a", 1000000) local p = string.rep("a", 500000) .. "b" for i = 1, 200 do string.find(s, p, 1, true) end|, + ~S|return #string.format("%q", string.rep("\n", 900000))|, + ~S|return #os.date(string.rep("%Y", 300000))|, + ~S|return #string.pack(string.rep("x", 1000000))|, + ~S|local t = {string.byte(string.rep("1", 400000), 1, -1)} return #table.concat(t)|, + ~S|local t = {string.byte(string.rep("x", 1000000), 1, -1)} table.sort(t) return #t|, + ~S|local s = string.rep("a", 1000000) return #string.upper(s), #string.lower(s), #string.reverse(s)| + ] + + defp budgeted, do: Lua.new(max_instructions: 10_000, max_call_depth: 100, max_string_bytes: 1024 * 1024) + + defp budget_error?({:raised, message}), do: message =~ "instruction budget exceeded" + defp budget_error?({:ok, [false, message]}), do: message =~ "instruction budget exceeded" + defp budget_error?(_result), do: false + + defp assert_charged(lua, call) do + result = eval(lua, "return pcall(function() return #{call} end)", timeout_ms: 1_000) + assert {:ok, [false, message]} = result, "#{call}\n => #{inspect(result, limit: 5)}" + assert message =~ "instruction budget exceeded", call + end + + test "single-call bombs fail fast under a small budget" do + for code <- @single_call_bombs do + result = eval(budgeted(), code, timeout_ms: 1_000) + assert budget_error?(result), "#{code}\n => #{inspect(result, limit: 5)}" + end + end + + describe "a call is charged for its input, before the work" do + setup do + lua = + budgeted() + |> Lua.set!([:s], String.duplicate("x", 1_000_000)) + |> Lua.set!([:dates], String.duplicate("%Y", 200_000)) + |> Lua.set!([:padding], String.duplicate("x", 1_000_000)) + |> Lua.set!([:digits], String.duplicate("9", 300_000)) + |> Lua.set!([:t], Enum.to_list(1..200_000)) + + %{lua: lua} + end + + test "string and utf8 calls, per byte scanned or built", %{lua: lua} do + for call <- [ + ~S|string.byte(s, 1, -1)|, + ~S|utf8.codepoint(s, 1, -1)|, + ~S|utf8.len(s)|, + ~S|utf8.offset(s, 1000000)|, + ~S|string.upper(s)|, + ~S|string.lower(s)|, + ~S|string.reverse(s)|, + ~S|string.find(s, "y", 1, true)|, + ~S|string.format("%q", s)|, + ~S|string.format("%s", s)|, + ~S|string.rep("ab", 500000)|, + ~S|os.date(dates)|, + ~S|string.pack(padding)|, + ~S|string.packsize(padding)|, + ~S|string.unpack(padding, s)|, + ~S|string.gsub("x", "x", s)| + ] do + assert_charged(lua, call) + end + end + + test "string to number conversions, per byte scanned", %{lua: lua} do + for call <- [ + ~S|tonumber(digits)|, + ~S|tonumber(s, 36)|, + ~S|math.tointeger(digits)| + ] do + assert_charged(lua, call) + end + end + + test "table calls, per element visited or returned", %{lua: lua} do + for call <- [ + ~S|table.unpack(t)|, + ~S|table.concat(t, ",")|, + ~S|table.sort(t)|, + ~S|table.insert(t, 1, 0)|, + ~S|table.remove(t, 1)|, + ~S|table.move(t, 1, #t, 2)| + ] do + assert_charged(lua, call) + end + end + end + + test "charges accumulate across calls" do + lua = Lua.set!(budgeted(), [:s], String.duplicate("a", 100_000)) + + assert {:ok, [100_000]} = eval(lua, "return #string.upper(s)", timeout_ms: 1_000) + assert budget_error?(eval(lua, "return pcall(function() string.upper(s) string.upper(s) end)", timeout_ms: 1_000)) + end + + test "utf8.offset is charged for the bytes it crosses, not the whole string" do + lua = Lua.set!(budgeted(), [:s], String.duplicate("x", 200_000)) + + assert {:ok, [nil, nil]} = eval(lua, "return utf8.offset(s, -1, 1), utf8.offset(s, 3, -1)", timeout_ms: 1_000) + end + + test "table.sort calls a comparator no more often than it charges for" do + code = ~S""" + local t, calls = {}, 0 + for i = 1, 1000 do t[i] = i end + table.sort(t, function(a, b) calls = calls + 1 return false end) + return calls + """ + + assert {:ok, [calls]} = eval(Lua.new(), code, timeout_ms: 1_000) + assert calls <= 1000 * ceil(:math.log2(1000)) + end + + test "ordinary calls still run under a small budget" do + code = ~S""" + local words = {} + for w in string.gmatch("the quick brown fox jumps over the lazy dog", "%a+") do + words[#words + 1] = string.upper(w) + end + table.sort(words) + local n, z = string.unpack(" "| 3.14", 10_000, 5, 42, "hi", 255, 13, 8999, "1970"]} = + eval(budgeted(), code, timeout_ms: 1_000) + end +end diff --git a/test/lua/vm/stdlib/pattern_budget_test.exs b/test/lua/vm/stdlib/pattern_budget_test.exs new file mode 100644 index 0000000..5e973a4 --- /dev/null +++ b/test/lua/vm/stdlib/pattern_budget_test.exs @@ -0,0 +1,196 @@ +defmodule Lua.VM.Stdlib.PatternBudgetTest do + @moduledoc "Pins pattern-matching limits: instruction budget, captures, depth." + use ExUnit.Case, async: true + + import Lua.Test.Bounded, only: [eval: 3] + + @lazy_bomb ~S|string.rep("a", 5000), ".-.-.-.-.-.-.-.-b"| + @greedy_bomb ~S|string.rep("a", 60), "a*a*a*a*a*a*a*a*a*a*a*a*a*a*b"| + + defp budgeted, do: Lua.new(max_instructions: 10_000, max_string_bytes: 1024 * 1024) + + defp eval(lua, code), do: eval(lua, code, timeout_ms: 5_000) + + describe "instruction budget" do + test "string.find bombs raise a catchable budget error" do + for bomb <- [@lazy_bomb, @greedy_bomb] do + assert {:ok, [false, message]} = eval(budgeted(), "return pcall(string.find, #{bomb})") + assert message =~ "instruction budget exceeded" + end + end + + test "string.match, string.gsub and string.gmatch are metered" do + for code <- [ + "return pcall(string.match, #{@greedy_bomb})", + ~s|return pcall(string.gsub, #{@greedy_bomb}, "x")|, + "return pcall(function() for _ in string.gmatch(#{@greedy_bomb}) do end end)" + ] do + assert {:ok, [false, message]} = eval(budgeted(), code) + assert message =~ "instruction budget exceeded" + end + end + + test "aborts an unprotected evaluation" do + assert {:raised, message} = eval(budgeted(), "return string.find(#{@lazy_bomb})") + assert message =~ "instruction budget exceeded" + end + + test "gsub charges every match" do + code = ~S|return pcall(string.gsub, string.rep("ab", 50000), "%w", "x")| + assert {:ok, [false, message]} = eval(budgeted(), code) + assert message =~ "instruction budget exceeded" + end + + test "gmatch charges each iteration as it runs" do + full = ~S|return pcall(function() for _ in string.gmatch(string.rep("a", 100000), "a") do end end)| + assert {:ok, [false, message]} = eval(budgeted(), full) + assert message =~ "instruction budget exceeded" + + early = ~S|for w in string.gmatch(string.rep("a", 100000), "a") do return w end| + assert {:ok, ["a"]} = eval(budgeted(), early) + end + + test "charges accumulate across calls" do + code = ~S""" + local n = 0 + for i = 1, 5000 do + if string.find("hello world, hello lua", "l+u") then n = n + 1 end + end + return n + """ + + assert {:ok, [20, 21]} = eval(budgeted(), ~S|return string.find("hello world, hello lua", "l+u")|) + assert {:ok, [false, message]} = eval(budgeted(), "return pcall(function() #{code} end)") + assert message =~ "instruction budget exceeded" + assert {:ok, [5000]} = eval(Lua.new(max_instructions: 1_000_000), code) + end + + test "pcall does not refund the budget" do + code = """ + local ok, err = pcall(string.find, #{@lazy_bomb}) + local ok2, err2 = pcall(function() for _ = 1, 10 do end end) + return ok, err, ok2, err2 + """ + + assert {:ok, [false, err, false, err2]} = eval(budgeted(), code) + assert err =~ "instruction budget exceeded" + assert err2 =~ "instruction budget exceeded" + end + + test "a gsub callback and the matcher share one tally" do + gsub = ~S|string.gsub(string.rep("ab", 500), "%w", function(c) for _ = 1, 6 do end return c end)| + loop = "for _ = 1, 5000 do end" + + assert {:ok, ["ok"]} = eval(budgeted(), "#{gsub} return 'ok'") + assert {:ok, ["ok"]} = eval(budgeted(), "#{loop} return 'ok'") + assert {:raised, message} = eval(budgeted(), "#{gsub} #{loop} return 'ok'") + assert message =~ "instruction budget exceeded" + end + + test "gsub callback effects survive the budget error" do + code = ~S""" + calls = 0 + local ok, err = pcall(string.gsub, string.rep("ab", 50000), "%w", function(c) + calls = calls + 1 + return c + end) + return ok, err, calls + """ + + assert {:ok, [false, err, calls]} = eval(budgeted(), code) + assert err =~ "instruction budget exceeded" + assert calls > 0 and calls < 100_000 + end + + test ":infinity does not meter" do + code = ~S|return string.find(string.rep("a", 25), "a*a*a*a*b")| + assert {:ok, [false, message]} = eval(Lua.new(max_instructions: 100), "return pcall(function() #{code} end)") + assert message =~ "instruction budget exceeded" + assert {:ok, [nil]} = eval(Lua.new(), code) + end + end + + describe "realistic workloads" do + test "log parsing" do + line = "2024-05-01 12:34:56 [warn] request_id=a1b2c3 latency=42ms status=503 path=/api/v1/items\n" + log = String.duplicate(line, 1000) + + code = ~s""" + local log = string.rep(#{inspect(line)}, 1000) + local total, ids = 0, 0 + for l in log:gmatch("[^\\n]+") do + local status = l:match("status=(%d+)") + local s, e = l:find("%[%a+%]") + if l:match("request_id=(%w+)") then ids = ids + 1 end + total = total + tonumber(status) + (e - s) + end + local squeezed = log:gsub("%s+", " ") + local filled = ("${a}-${b}"):gsub("%${(%w+)}", {a = "x", b = "y"}) + return total, ids, #squeezed, filled + """ + + squeezed = byte_size(String.replace(log, ~r/\s+/, " ")) + assert {:ok, [508_000, 1000, ^squeezed, "x-y"]} = eval(Lua.new(max_instructions: 1_000_000), code) + end + + test "a set test is constant time in its item count" do + code = ~S""" + local big = "[" .. string.rep("xyz", 100000) .. "a]+" + local s, e = string.find(string.rep("a", 10000) .. "b", big) + return s, e, + string.match("ab_9-Z!", "[%a_%d]+"), + string.match("ab_9-Z!", "[^%a_]+"), + string.match("hello-world", "[a-f]+"), + string.match("]x", "[]]"), + string.match("a-b", "[a%-]+") + """ + + assert {:ok, [1, 10_000, "ab_9", "9-", "e", "]", "a-"]} = eval(Lua.new(max_instructions: 1_000_000), code) + end + end + + describe "structural limits" do + test "more than 32 captures raises 'too many captures'" do + for lua <- [Lua.new(), budgeted()] do + assert {:ok, [false, message]} = eval(lua, ~S|return pcall(string.find, "abc", string.rep("()", 33))|) + assert message =~ "too many captures" + + assert {:ok, [true, 1, 0 | positions]} = eval(lua, ~S|return pcall(string.find, "abc", string.rep("()", 32))|) + assert positions == List.duplicate(1, 32) + end + end + + test "backtracking past 200 levels raises 'pattern too complex'" do + deep = ~S|return pcall(string.match, string.rep("a", 200000), string.rep(".?", 200000))| + shallow = ~S|return pcall(string.match, string.rep("a", 80), string.rep(".?", 80))| + + for lua <- [Lua.new(), Lua.new(max_instructions: 1_000_000)] do + assert {:ok, [false, message]} = eval(lua, deep) + assert message =~ "pattern too complex" + + assert {:ok, [true, match]} = eval(lua, shallow) + assert match == String.duplicate("a", 80) + end + end + + test "plain characters spend no depth" do + code = ~S|return #string.match(string.rep("a", 5000), string.rep("a", 5000))| + assert {:ok, [5000]} = eval(Lua.new(), code) + end + + test "a structural error keeps earlier gsub callback effects" do + # Matches 1-3 are shallow; the 4th trips the depth limit. + code = ~S""" + seen = 0 + local subject = "xa xb xc x" .. string.rep("1", 300) + local ok, err = pcall(string.gsub, subject, "x" .. string.rep("%d?", 300), function() + seen = seen + 1 + end) + return ok, err, seen + """ + + assert {:ok, [false, err, 3]} = eval(Lua.new(), code) + assert err =~ "pattern too complex" + end + end +end diff --git a/test/lua53_skips.exs b/test/lua53_skips.exs index 2c3d75f..675c226 100644 --- a/test/lua53_skips.exs +++ b/test/lua53_skips.exs @@ -244,12 +244,6 @@ "pattern backreferences %0 and %1 inside a capture body should raise 'invalid capture index' (pattern-engine gap, not gsub replacement validation)", issue: 257 }, - %{ - lines: 250..250, - category: :unimplemented, - reason: "'pattern too complex' recursion-depth limit not yet implemented", - issue: 257 - }, %{ lines: 277..277, category: :unimplemented, @@ -286,14 +280,14 @@ lines: 201..209, category: :semantic, reason: - "table.sort with a deliberately-inconsistent comparator should raise 'invalid order function'; our insertion sort never detects it (PUC's quicksort-specific bounds check)", + "table.sort with a deliberately-inconsistent comparator should raise 'invalid order function'; our merge sort never detects it (PUC's quicksort-specific bounds check)", issue: 262 }, %{ lines: 260..308, category: :performance, reason: - "50000-element table.sort timing block: the comparator path is O(n^2) and one comparator calls load() (excluded in the sandbox). The perm block above (lines 240-249) and test/lua/vm/stdlib/table_test.exs cover plain `<` ordering on numbers/strings and explicit-comparator dispatch (including a comparator that drives a __lt metamethod). The trailing `setmetatable(.., {__lt=..}); table.sort(a)` case is NOT covered: our default (no-comparator) sort compares only numbers and strings and never dispatches __lt, so a default sort over table elements raises 'attempt to compare table with table' instead of ordering through __lt.", + "50000-element table.sort timing block: one comparator calls load() (excluded in the sandbox). The perm block above (lines 240-249) and test/lua/vm/stdlib/table_test.exs cover plain `<` ordering on numbers/strings and explicit-comparator dispatch (including a comparator that drives a __lt metamethod). The trailing `setmetatable(.., {__lt=..}); table.sort(a)` case is NOT covered: our default (no-comparator) sort compares only numbers and strings and never dispatches __lt, so a default sort over table elements raises 'attempt to compare table with table' instead of ordering through __lt.", issue: 262 } ], diff --git a/test/support/bounded.ex b/test/support/bounded.ex new file mode 100644 index 0000000..292e1a6 --- /dev/null +++ b/test/support/bounded.ex @@ -0,0 +1,49 @@ +defmodule Lua.Test.Bounded do + @moduledoc false + + @doc """ + Evaluates `code` on `lua` in a time- and heap-capped worker, so a regressed + resource guard fails instead of hanging or exhausting the host. The heap cap + counts off-heap binaries too. + + Returns `{:ok, results}`, `{:raised, message}`, `:timeout`, or + `{:error, reason}` (`:killed` when over the heap cap). + """ + def eval(lua, code, opts \\ []) do + heap_bytes = Keyword.get(opts, :heap_bytes, 512 * 1024 * 1024) + timeout_ms = Keyword.get(opts, :timeout_ms, 10_000) + parent = self() + + cap = %{ + size: div(heap_bytes, :erlang.system_info(:wordsize)), + kill: true, + error_logger: false, + include_shared_binaries: true + } + + worker = fn -> send(parent, {:bounded_result, self(), safe_eval(lua, code)}) end + {pid, ref} = :erlang.spawn_opt(worker, [:monitor, max_heap_size: cap]) + + receive do + {:bounded_result, ^pid, result} -> + Process.demonitor(ref, [:flush]) + result + + {:DOWN, ^ref, :process, ^pid, reason} -> + {:error, reason} + after + timeout_ms -> + Process.exit(pid, :kill) + + receive do + {:DOWN, ^ref, :process, ^pid, _} -> :timeout + end + end + end + + defp safe_eval(lua, code) do + {:ok, lua |> Lua.eval!(code) |> elem(0)} + rescue + e -> {:raised, Exception.message(e)} + end +end