Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
87 changes: 54 additions & 33 deletions lib/lua.ex
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand All @@ -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)
Expand All @@ -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)

Expand All @@ -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
Expand Down Expand Up @@ -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.

Expand Down Expand Up @@ -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 =
Expand All @@ -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
Expand Down
16 changes: 12 additions & 4 deletions lib/lua/compiler/bytecode.ex
Original file line number Diff line number Diff line change
Expand Up @@ -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 [
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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
Expand Down
24 changes: 15 additions & 9 deletions lib/lua/compiler/goto_resolution.ex
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand All @@ -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
Expand Down
2 changes: 1 addition & 1 deletion lib/lua/compiler/prototype.ex
Original file line number Diff line number Diff line change
Expand Up @@ -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}
}
}

Expand Down
Loading