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
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -49,12 +49,19 @@ is in the [`1.0.0-rc.0`](#100-rc0---2026-05-26) entry below.

## [Unreleased]

### Added
- `Lua.new/1` option `:max_decode_nodes` (default 5,000,000) caps the expanded
size of a decoded result.

### 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).
- Decoding walks a shared table once instead of once per path, so a few
tables referencing each other no longer expand exponentially after the
script ends.

## [1.0.2] - 2026-07-28

Expand Down
55 changes: 43 additions & 12 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 @@ -131,6 +132,14 @@ defmodule Lua do
iex> {[false, message], _lua} = Lua.eval!(lua, "return pcall(function() while true do end end)")
iex> message =~ "instruction budget exceeded"
true

* `:max_decode_nodes` - (default 5,000,000) caps the expanded size of a result decoded to
Elixir, counting the value and every table entry as one node. Past it, decoding raises
`Lua.RuntimeException`. Accepts a positive integer or `:infinity`.

iex> lua = Lua.new(max_decode_nodes: 100)
iex> Lua.eval!(lua, "local t = {} for i = 1, 20 do t = {t, t} end return t")
** (Lua.RuntimeException) Lua runtime error: decoded value exceeds :max_decode_nodes (100)
"""
@spec new(keyword()) :: t()
def new(opts \\ []) do
Expand All @@ -140,8 +149,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_decode_nodes: Limits.max_decode_nodes()
)

sandboxed = Keyword.fetch!(opts, :sandboxed)
Expand All @@ -150,6 +160,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_decode_nodes = validate_max_decode_nodes!(Keyword.fetch!(opts, :max_decode_nodes))

lua = template(sandboxed, exclude)

Expand All @@ -160,7 +171,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_decode_nodes: max_decode_nodes
}
}
end
Expand Down Expand Up @@ -217,6 +229,14 @@ defmodule Lua do
":max_instructions must be a positive integer or :infinity, got: #{inspect(other)}"
end

defp validate_max_decode_nodes!(:infinity), do: :infinity
defp validate_max_decode_nodes!(nodes) when is_integer(nodes) and nodes > 0, do: nodes

defp validate_max_decode_nodes!(other) do
raise ArgumentError,
":max_decode_nodes 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 @@ -1040,16 +1060,12 @@ defmodule Lua do
iex> Lua.decode!(lua, encoded)
[{"a", 1}]

A shared table is decoded once and its term reused. A reference back to a table
still being decoded is left as its `{:tref, id}`.
"""
@spec decode!(t(), term()) :: term()
def decode!(%__MODULE__{state: state}, value) do
value = Display.unwrap(value)

if not Util.encoded?(value) do
raise Lua.RuntimeException, "Failed to decode #{inspect(value)}"
end

Value.decode(value, state)
value |> unwrap_encoded!() |> Value.decode(state)
rescue
_e in [ArgumentError, KeyError] ->
reraise Lua.RuntimeException, "Failed to decode #{inspect(value)}", __STACKTRACE__
Expand All @@ -1063,10 +1079,25 @@ defmodule Lua do
iex> {encoded, lua} = Lua.encode_list!(Lua.new(), [1, %{a: 2}, true])
iex> Lua.decode_list!(lua, encoded)
[1, [{"a", 2}], true]

The values share one walk, so `:max_decode_nodes` applies to the whole list.
"""
@spec decode_list!(t(), [term()]) :: [term()]
def decode_list!(%__MODULE__{} = lua, list) when is_list(list) do
Enum.map(list, &decode!(lua, &1))
def decode_list!(%__MODULE__{state: state}, list) when is_list(list) do
list |> Enum.map(&unwrap_encoded!/1) |> Value.decode_list(state)
rescue
_e in [ArgumentError, KeyError] ->
reraise Lua.RuntimeException, "Failed to decode #{inspect(list)}", __STACKTRACE__
end

defp unwrap_encoded!(value) do
value = Display.unwrap(value)

if not Util.encoded?(value) do
raise Lua.RuntimeException, "Failed to decode #{inspect(value)}"
end

value
end

@doc """
Expand Down
122 changes: 70 additions & 52 deletions lib/lua/vm/display.ex
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,9 @@ defmodule Lua.VM.Display do
alias Lua.VM.Display.NativeFunc
alias Lua.VM.Display.Table, as: DTable
alias Lua.VM.Display.Userdata
alias Lua.VM.Limits
alias Lua.VM.State
alias Lua.VM.Table

@typedoc "Any of the four display structs produced at the eval boundary."
@type display_struct ::
Expand All @@ -49,14 +51,18 @@ defmodule Lua.VM.Display do
Elixir-friendly shapes (list of tuples and `{:userdata, term}`).
Closures and native funcs are wrapped in either mode.

When `decode: false`, all four tag kinds are wrapped; nested values
inside tables are also wrapped via `wrap_value/2`.
When `decode: false`, all four tag kinds are wrapped and table peeks
are walked like `Lua.VM.Value.decode_list/2`: shared tables once, with
tables past `state.max_decode_nodes` marked `:truncated`.
"""
@spec wrap_results([term()], State.t(), boolean()) :: [term()]
def wrap_results(values, state, decode?) when is_list(values) do
Enum.map(values, &wrap_value(&1, state, decode?))
def wrap_results(values, state, false) when is_list(values) do
{wrapped, _walk} = Enum.map_reduce(values, {%{}, 0}, &peek_result(&1, state, &2))
wrapped
end

def wrap_results(values, _state, _decode?) when is_list(values), do: Enum.map(values, &wrap_callable/1)

@doc """
Returns true when the value is one of the four display structs.

Expand Down Expand Up @@ -93,45 +99,39 @@ defmodule Lua.VM.Display do
see `Lua.VM.Display.Table`.
"""
@spec wrap_value(term(), State.t(), boolean()) :: term()
def wrap_value(value, state, decode?), do: wrap_value(value, state, decode?, %{})

# decode: true — only wrap closures/native; tables and userdata
# have already been decoded and are passed through unchanged.
defp wrap_value({:lua_closure, _, _} = ref, _state, _decode?, _ancestors) do
wrap_closure(ref)
def wrap_value(value, state, decode?) do
[wrapped] = wrap_results([value], state, decode?)
wrapped
end

defp wrap_value({:compiled_closure, _, _} = ref, _state, _decode?, _ancestors) do
wrap_closure(ref)
end
# ---- internal helpers ----

defp wrap_value({:native_func, fun} = ref, _state, _decode?, _ancestors) do
%NativeFunc{fun: fun, ref: ref}
end
defp wrap_callable({tag, _, _} = ref) when tag in [:lua_closure, :compiled_closure], do: wrap_closure(ref)
defp wrap_callable({:native_func, fun} = ref), do: %NativeFunc{fun: fun, ref: ref}
defp wrap_callable(value), do: value

# decode: false — wrap tref/udref too, and recurse into table peek.
# `ancestors` holds the tref ids currently being peeked higher up
# this walk; revisiting one means the table contains itself.
defp wrap_value({:tref, id} = ref, state, false, ancestors) do
peek =
if Map.has_key?(ancestors, id) do
:circular
else
peek_table(state, id, false, Map.put(ancestors, id, true))
end

%DTable{id: id, peek: peek, ref: ref}
# Budgeted like `Lua.VM.Value.decode_list/2`, but truncates instead of
# raising, so a result whose own node no longer fits is still wrapped.
defp peek_result(value, state, {memo, nodes_used} = walk) do
case Limits.reserve_decode_nodes(nodes_used, 1, state.max_decode_nodes) do
{:ok, nodes_used} -> peek_value(value, state, {memo, nodes_used})
:exhausted -> peek_value(value, state, walk)
end
end

defp wrap_value({:udref, id} = ref, state, false, _ancestors) do
term = State.get_userdata(state, ref)
%Userdata{id: id, term: term, ref: ref}
defp peek_value({:tref, id} = ref, state, {memo, _nodes_used} = walk) do
case memo do
%{^id => {peeked_table, subtree_nodes}} -> reuse_peek(peeked_table, subtree_nodes, state, walk)
%{^id => :in_progress} -> {wrap_table(ref, :circular), walk}
%{} -> peek_table(ref, state, walk)
end
end

# decode: true catch-all (already-decoded values pass through)
defp wrap_value(value, _state, _decode?, _ancestors), do: value
defp peek_value({:udref, id} = ref, state, walk) do
{%Userdata{id: id, term: State.get_userdata(state, ref), ref: ref}, walk}
end

# ---- internal helpers ----
defp peek_value(value, _state, walk), do: {wrap_callable(value), walk}

defp wrap_closure({tag, proto, _upvalues} = ref) when tag in [:lua_closure, :compiled_closure] do
{first_line, _last_line} = proto.lines || {0, 0}
Expand All @@ -150,27 +150,45 @@ defmodule Lua.VM.Display do
# (1..N keys) render as a list; mixed-key tables render as a map.
# Nested tables/closures are recursively wrapped so `Inspect` does
# not have to know about live VM state.
defp peek_table(state, id, decode?, ancestors) do
case Map.fetch(state.tables, id) do
{:ok, table} ->
data = Lua.VM.Table.to_map(table)

if sequence_like?(data) do
Enum.map(
1..map_size(data),
&wrap_value(Map.fetch!(data, &1), state, decode?, ancestors)
)
else
Map.new(data, fn {k, v} -> {k, wrap_value(v, state, decode?, ancestors)} end)
end

:error ->
# Stale or detached reference. Render an empty peek rather
# than crashing — the `id` field is enough to identify it.
[]
defp peek_table({:tref, id} = ref, state, {memo, nodes_used} = walk) do
with {:ok, table} <- Map.fetch(state.tables, id),
{:ok, nodes_used_with_entries} <-
Limits.reserve_decode_nodes(nodes_used, Table.entry_count(table), state.max_decode_nodes) do
{peek, {memo, nodes_used_after}} =
peek_entries(Table.to_map(table), state, {Map.put(memo, id, :in_progress), nodes_used_with_entries})

peeked_table = wrap_table(ref, peek)
{peeked_table, {Map.put(memo, id, {peeked_table, nodes_used_after - nodes_used}), nodes_used_after}}
else
# Stale or detached reference: the `id` is enough to identify it.
:error -> {wrap_table(ref, []), walk}
:exhausted -> {wrap_table(ref, :truncated), walk}
end
end

defp reuse_peek(peeked_table, subtree_nodes, state, {memo, nodes_used} = walk) do
case Limits.reserve_decode_nodes(nodes_used, subtree_nodes, state.max_decode_nodes) do
{:ok, nodes_used} -> {peeked_table, {memo, nodes_used}}
:exhausted -> {%{peeked_table | peek: :truncated}, walk}
end
end

defp peek_entries(entries, state, walk) do
if sequence_like?(entries) do
Enum.map_reduce(1..map_size(entries), walk, &peek_value(Map.fetch!(entries, &1), state, &2))
else
{peeked_entries, walk} = Enum.map_reduce(entries, walk, &peek_entry(&1, state, &2))
{Map.new(peeked_entries), walk}
end
end

defp peek_entry({key, value}, state, walk) do
{peeked, walk} = peek_value(value, state, walk)
{{key, peeked}, walk}
end

defp wrap_table({:tref, id} = ref, peek), do: %DTable{id: id, peek: peek, ref: ref}

defp sequence_like?(data) when map_size(data) == 0, do: false

defp sequence_like?(data) do
Expand Down
11 changes: 7 additions & 4 deletions lib/lua/vm/display/table.ex
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,8 @@ defmodule Lua.VM.Display.Table do
Truncated to `Inspect.Opts.limit` entries when rendered. When a
table (transitively) contains itself — e.g. the `T.__index = T`
OOP idiom — the recurring occurrence carries `:circular` instead
of a snapshot, bounding an otherwise infinite walk.
of a snapshot, bounding an otherwise infinite walk. Tables past
the `:max_decode_nodes` option of `Lua.new/1` carry `:truncated`.
- `:ref` — the original `{:tref, id}` tuple so callers can
round-trip the value back into the VM (via `Lua.set!/3`,
`Lua.encode!/2`, etc.).
Expand All @@ -30,7 +31,7 @@ defmodule Lua.VM.Display.Table do

@type t :: %__MODULE__{
id: non_neg_integer(),
peek: list() | map() | :circular,
peek: list() | map() | :circular | :truncated,
ref: tuple()
}

Expand All @@ -39,11 +40,13 @@ defmodule Lua.VM.Display.Table do
defimpl Inspect do
import Inspect.Algebra

def inspect(%Table{id: id, peek: :circular}, _opts) do
def inspect(%Table{id: id, peek: marker}, _opts) when marker in [:circular, :truncated] do
concat([
"#Lua.Table<id: ",
Integer.to_string(id),
", circular>"
", ",
Atom.to_string(marker),
">"
])
end

Expand Down
19 changes: 19 additions & 0 deletions lib/lua/vm/limits.ex
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,10 @@ defmodule Lua.VM.Limits do
# exhaust memory, while staying generous for real data.
@max_element_count 10_000_000

# 5 million nodes of roughly 5–10 words each: a few hundred MB for a
# consumer walking the expanded result.
@max_decode_nodes 5_000_000

@doc "The string-size ceiling, in bytes."
@spec max_string_bytes() :: pos_integer()
def max_string_bytes, do: @max_string_bytes
Expand All @@ -40,6 +44,21 @@ defmodule Lua.VM.Limits do
@spec max_element_count() :: pos_integer()
def max_element_count, do: @max_element_count

@doc "The ceiling on the expanded size of a value decoded to Elixir, in nodes."
@spec max_decode_nodes() :: pos_integer()
def max_decode_nodes, do: @max_decode_nodes

@doc "Adds `nodes` to `nodes_used`, or returns `:exhausted` past `max_nodes`."
@spec reserve_decode_nodes(non_neg_integer(), non_neg_integer(), pos_integer() | :infinity) ::
{:ok, non_neg_integer()} | :exhausted
# Under `:infinity` the count is left alone so it never grows into a bignum.
def reserve_decode_nodes(nodes_used, _nodes, :infinity), do: {:ok, nodes_used}

def reserve_decode_nodes(nodes_used, nodes, max_nodes) when nodes_used + nodes <= max_nodes,
do: {:ok, nodes_used + nodes}

def reserve_decode_nodes(_nodes_used, _nodes, _max_nodes), do: :exhausted

@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
Expand Down
3 changes: 3 additions & 0 deletions lib/lua/vm/state.ex
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@ defmodule Lua.VM.State do
# cap so an allocation bomb is refused deterministically instead
# of racing the GC-time heap check.
max_string_bytes: Limits.max_string_bytes(),
# Read only when decoding results to Elixir, never by the executor.
max_decode_nodes: Limits.max_decode_nodes(),
# `max_instructions` is the configured instruction ceiling; `:infinity`
# (the default) means no limit. The running tally is NOT stored
# here on the per-opcode hot path — it is threaded as a parameter
Expand Down Expand Up @@ -72,6 +74,7 @@ defmodule Lua.VM.State do
call_depth: non_neg_integer(),
max_call_depth: pos_integer() | :infinity,
max_string_bytes: pos_integer() | :infinity,
max_decode_nodes: pos_integer() | :infinity,
max_instructions: pos_integer() | :infinity,
instruction_count: non_neg_integer(),
metatables: map(),
Expand Down
Loading