diff --git a/CHANGELOG.md b/CHANGELOG.md index c26f0ca..d4ed380 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/lib/lua.ex b/lib/lua.ex index 242d83c..aac3bc2 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 @@ -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 @@ -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) @@ -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) @@ -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 @@ -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. @@ -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__ @@ -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 """ diff --git a/lib/lua/vm/display.ex b/lib/lua/vm/display.ex index f190a9a..73d6aa5 100644 --- a/lib/lua/vm/display.ex +++ b/lib/lua/vm/display.ex @@ -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 :: @@ -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. @@ -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} @@ -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 diff --git a/lib/lua/vm/display/table.ex b/lib/lua/vm/display/table.ex index c2085c1..9c186b0 100644 --- a/lib/lua/vm/display/table.ex +++ b/lib/lua/vm/display/table.ex @@ -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.). @@ -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() } @@ -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" + ", ", + Atom.to_string(marker), + ">" ]) end diff --git a/lib/lua/vm/limits.ex b/lib/lua/vm/limits.ex index 46be991..6629ca9 100644 --- a/lib/lua/vm/limits.ex +++ b/lib/lua/vm/limits.ex @@ -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 @@ -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 diff --git a/lib/lua/vm/state.ex b/lib/lua/vm/state.ex index 054bfc5..3e9da00 100644 --- a/lib/lua/vm/state.ex +++ b/lib/lua/vm/state.ex @@ -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 @@ -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(), diff --git a/lib/lua/vm/table.ex b/lib/lua/vm/table.ex index 4a2b5bc..cf90f2b 100644 --- a/lib/lua/vm/table.ex +++ b/lib/lua/vm/table.ex @@ -531,6 +531,15 @@ defmodule Lua.VM.Table do end) end + @doc false + @spec entry_count(t()) :: non_neg_integer() + def entry_count(%__MODULE__{arr: :undefined, data: data}), do: map_size(data) + def entry_count(%__MODULE__{arr_n: n, border: n, data: data}), do: n + map_size(data) + + def entry_count(%__MODULE__{arr: arr, arr_n: n, data: data}) do + Enum.count(1..n//1, &(:array.get(&1 - 1, arr) != nil)) + map_size(data) + end + @doc """ Returns the next key/value pair in iteration order after `key`. diff --git a/lib/lua/vm/value.ex b/lib/lua/vm/value.ex index cd55225..d37903a 100644 --- a/lib/lua/vm/value.ex +++ b/lib/lua/vm/value.ex @@ -7,8 +7,10 @@ defmodule Lua.VM.Value do the executor and stdlib. """ + alias Lua.VM.Limits alias Lua.VM.Numeric alias Lua.VM.State + alias Lua.VM.Table @doc """ Returns the Lua type name as a string for the given value. @@ -333,47 +335,67 @@ defmodule Lua.VM.Value do @doc """ Decodes a Lua VM value into an Elixir-friendly representation. - Tables are returned as lists of `{key, decoded_value}` tuples. - Functions (closures, native) pass through as-is. + Tables become lists of `{key, decoded_value}` tuples; functions pass + through as-is. Each table is decoded once and reused; a reference back to + a table still being decoded stays a `{:tref, id}`. - Cyclic tables (e.g. the common `T.__index = T` idiom) cannot be - represented as acyclic Elixir data, so the walk terminates at the - point of recurrence and leaves the table's `{:tref, id}` reference - there — mirroring how functions already pass through as opaque - references. Shared references that do not form a cycle decode - normally. + Raises `Lua.RuntimeException` past `state.max_decode_nodes`. """ @spec decode(term(), State.t()) :: term() - def decode(value, state), do: decode(value, state, %{}) - - defp decode(nil, _state, _ancestors), do: nil - defp decode(value, _state, _ancestors) when is_boolean(value), do: value - defp decode(value, _state, _ancestors) when is_number(value), do: value - defp decode(value, _state, _ancestors) when is_binary(value), do: value + def decode(value, %State{} = state) do + [decoded] = decode_list([value], state) + decoded + end - defp decode({:udref, _} = ref, state, _ancestors) do - value = State.get_userdata(state, ref) - {:userdata, value} + @doc """ + Decodes a list of Lua VM values as one walk, sharing tables and the + `max_decode_nodes` budget across them. + """ + @spec decode_list([term()], State.t()) :: [term()] + def decode_list(values, %State{} = state) do + {decoded, _walk} = Enum.map_reduce(values, {%{}, 0}, &decode_result(&1, state, &2)) + decoded end - defp decode({:tref, id} = ref, state, ancestors) do - if Map.has_key?(ancestors, id) do - ref - else - table = Map.fetch!(state.tables, id) - ancestors = Map.put(ancestors, id, true) + defp decode_result(value, state, walk) do + decode_value(value, state, reserve_nodes!(walk, 1, state)) + end - Enum.map(Lua.VM.Table.to_map(table), fn {k, v} -> {k, decode(v, state, ancestors)} end) + # A reused table is charged its `subtree_nodes` again, so the budget counts + # the expanded size without re-walking it. + defp decode_value({:tref, id} = ref, state, {memo, _nodes_used} = walk) do + case memo do + %{^id => {decoded, subtree_nodes}} -> {decoded, reserve_nodes!(walk, subtree_nodes, state)} + %{^id => :in_progress} -> {ref, walk} + %{} -> decode_table(ref, state, walk) end end - defp decode(value, _state, _ancestors), do: value + defp decode_value({:udref, _} = ref, state, walk), do: {{:userdata, State.get_userdata(state, ref)}, walk} + defp decode_value(value, _state, walk), do: {value, walk} - @doc """ - Decodes a list of Lua VM values. - """ - @spec decode_list([term()], State.t()) :: [term()] - def decode_list(values, state) do - Enum.map(values, &decode(&1, state)) + defp decode_table({:tref, id}, state, {memo, nodes_used}) do + table = Map.fetch!(state.tables, id) + walk = reserve_nodes!({Map.put(memo, id, :in_progress), nodes_used}, Table.entry_count(table), state) + {decoded, {memo, nodes_used_after}} = Enum.map_reduce(Table.to_map(table), walk, &decode_entry(&1, state, &2)) + {decoded, {Map.put(memo, id, {decoded, nodes_used_after - nodes_used}), nodes_used_after}} + end + + # Reuse the entry tuple when its value decodes to itself. + defp decode_entry({key, {tag, _} = ref}, state, walk) when tag in [:tref, :udref] do + {decoded, walk} = decode_value(ref, state, walk) + {{key, decoded}, walk} + end + + defp decode_entry(entry, _state, walk), do: {entry, walk} + + defp reserve_nodes!({memo, nodes_used}, nodes, %State{max_decode_nodes: max_decode_nodes}) do + case Limits.reserve_decode_nodes(nodes_used, nodes, max_decode_nodes) do + {:ok, nodes_used} -> + {memo, nodes_used} + + :exhausted -> + raise Lua.RuntimeException, "decoded value exceeds :max_decode_nodes (#{max_decode_nodes})" + end end end diff --git a/test/lua/vm/decode_limits_test.exs b/test/lua/vm/decode_limits_test.exs new file mode 100644 index 0000000..5c4ec02 --- /dev/null +++ b/test/lua/vm/decode_limits_test.exs @@ -0,0 +1,483 @@ +defmodule Lua.VM.DecodeLimitsTest do + @moduledoc "Pins shared-table decoding and the `:max_decode_nodes` ceiling." + + use ExUnit.Case, async: true + use ExUnitProperties + + alias Lua.VM.Display.Table, as: DTable + alias Lua.VM.Limits + alias Lua.VM.State + alias Lua.VM.Table + alias Lua.VM.Value + + @heap_cap_bytes 64 * 1024 * 1024 + @time_cap_ms 10_000 + + describe "shared tables" do + test "the default limit refuses a doubling DAG" do + # 2^28 nodes once expanded, from a script well inside its instruction budget. + exception = assert_too_large(fn -> Lua.eval!(Lua.new(max_instructions: 10_000), doubling(28)) end) + assert Exception.message(exception) =~ ":max_decode_nodes (#{Limits.max_decode_nodes()})" + end + + test "decode to one shared term per table" do + levels = 16 + + assert {:ok, facts} = + bounded(fn -> + {[decoded], _} = Lua.eval!(Lua.new(), doubling(levels)) + [{1, left}, {2, right}] = decoded + expected = doubled_term(levels) + + %{ + equal?: decoded === expected, + shared?: :erts_debug.same(left, right), + size: :erts_debug.size(decoded), + expected_size: :erts_debug.size(expected), + flat_size: :erts_debug.flat_size(decoded) + } + end) + + assert facts.equal? + assert facts.shared? + assert facts.size == facts.expected_size + assert facts.flat_size > 1_000 * facts.size + end + + test ":infinity decodes in memory linear in the distinct tables" do + levels = 64 + + assert {:ok, facts} = + bounded(fn -> + lua = Lua.new(max_decode_nodes: :infinity) + {[decoded], _} = Lua.eval!(lua, doubling(levels)) + %{size: :erts_debug.size(decoded), depth: spine_depth(decoded)} + end) + + # 2^65 nodes expanded: never compare or flatten it. + assert facts.size == :erts_debug.size(doubled_term(levels)) + assert facts.depth == levels + end + end + + describe "node counting" do + test "the value and each table entry count as one node" do + # 1 + 3 + 2 + code = "return {1, 2, {3, 4}}" + + assert {[[{1, 1}, {2, 2}, {3, [{1, 3}, {2, 4}]}]], _} = + Lua.eval!(Lua.new(max_decode_nodes: 6), code) + + assert_too_large(fn -> Lua.eval!(Lua.new(max_decode_nodes: 5), code) end) + assert {[42], _} = Lua.eval!(Lua.new(max_decode_nodes: 1), "return 42") + end + + test "a shared table counts once per place it appears" do + # 1 + 2 + 2 × 2 + code = "local s = {1, 2} return {s, s}" + + assert {[[{1, inner}, {2, inner}]], _} = Lua.eval!(Lua.new(max_decode_nodes: 7), code) + assert inner == [{1, 1}, {2, 2}] + assert_too_large(fn -> Lua.eval!(Lua.new(max_decode_nodes: 6), code) end) + end + + test "a cycle cut counts as one node" do + code = "local t = {} t.self = t return t" + + assert {[[{"self", {:tref, _}}]], _} = Lua.eval!(Lua.new(max_decode_nodes: 2), code) + assert_too_large(fn -> Lua.eval!(Lua.new(max_decode_nodes: 1), code) end) + end + + test "the limit spans all values an eval returns" do + # 3 × (1 + 3) + code = "local s = {1, 2, 3} return s, s, s" + + assert {[first, second, third], _} = Lua.eval!(Lua.new(max_decode_nodes: 12), code) + assert first == [{1, 1}, {2, 2}, {3, 3}] + assert :erts_debug.same(first, second) and :erts_debug.same(second, third) + assert_too_large(fn -> Lua.eval!(Lua.new(max_decode_nodes: 11), code) end) + end + end + + describe "cyclic tables" do + test "a cyclic table reached by another path keeps its first cuts" do + code = """ + local a = {} + local b = {a = a} + a.b = b + return {x = a, y = b} + """ + + {[decoded], _} = Lua.eval!(Lua.new(), code) + + assert [{"x", [{"b", b_under_x}]}, {"y", b_under_y}] = decoded + assert [{"a", {:tref, _}}] = b_under_x + assert :erts_debug.same(b_under_x, b_under_y) + end + + test "a cyclic table under two keys is shared" do + code = "local T = {} T.__index = T return {x = T, y = T}" + + assert {[[{"x", x}, {"y", y}]], _} = Lua.eval!(Lua.new(), code) + assert [{"__index", {:tref, _}}] = x + assert :erts_debug.same(x, y) + end + + test "a strongly connected tangle decodes linearly" do + # Every table points back at `top`: one cycle with 2^levels paths from it. + tangle = fn levels -> + """ + local top = {} + local t = {top} + for _ = 1, #{levels} do t = {t, t, top} end + top[1] = t + return top + """ + end + + assert_too_large(fn -> + Lua.eval!(Lua.new(max_instructions: 10_000, max_decode_nodes: 1_000), tangle.(28)) + end) + + assert {:ok, facts} = + bounded(fn -> + lua = Lua.new(max_decode_nodes: :infinity) + {[big], _} = Lua.eval!(lua, tangle.(28)) + {[small], _} = Lua.eval!(lua, tangle.(10)) + [{1, [_, _, {3, {:tref, top_id}}]}] = small + + %{ + big_size: :erts_debug.size(big), + small_equal?: small === tangle_term(10, {:tref, top_id}) + } + end) + + assert facts.big_size < 30 * 28 + assert facts.small_equal? + end + end + + describe "deep nesting" do + test "thousands of nested levels decode and peek" do + levels = 10_000 + code = "local t = {} for _ = 1, #{levels} do t = {t} end return t" + + assert {:ok, facts} = + bounded(fn -> + {[decoded], _} = Lua.eval!(Lua.new(), code) + {[peek], _} = Lua.eval!(Lua.new(), code, decode: false) + + %{ + equal?: decoded == Enum.reduce(1..levels, [], fn _, inner -> [{1, inner}] end), + peek_depth: peek_depth(peek) + } + end) + + assert facts.equal? + assert facts.peek_depth == levels + end + + test "a deep chain past the limit is refused" do + code = "local t = {} for _ = 1, 10000 do t = {t} end return t" + assert_too_large(fn -> Lua.eval!(Lua.new(max_decode_nodes: 5_000), code) end) + end + end + + describe ":max_decode_nodes option" do + test "defaults to 5 million" do + assert Limits.max_decode_nodes() == 5_000_000 + assert Lua.new().state.max_decode_nodes == Limits.max_decode_nodes() + assert %State{}.max_decode_nodes == Limits.max_decode_nodes() + end + + test "accepts a positive integer or :infinity" do + assert Lua.new(max_decode_nodes: 1).state.max_decode_nodes == 1 + assert Lua.new(max_decode_nodes: 123_456).state.max_decode_nodes == 123_456 + assert Lua.new(max_decode_nodes: :infinity).state.max_decode_nodes == :infinity + end + + test "rejects anything else" do + for bad <- [0, -1, 1.5, :none, "100", nil] do + assert_raise ArgumentError, + ~r/:max_decode_nodes must be a positive integer or :infinity, got: /, + fn -> Lua.new(max_decode_nodes: bad) end + end + end + end + + describe "entry points" do + setup do + %{lua: Lua.new(max_instructions: 10_000, max_decode_nodes: 100)} + end + + test "eval! of a precompiled chunk", %{lua: lua} do + {:ok, chunk} = Lua.parse_chunk(doubling(28)) + assert_too_large(fn -> Lua.eval!(lua, chunk) end) + end + + test "get!/3", %{lua: lua} do + {_, lua} = Lua.eval!(lua, doubling(28, "big = t")) + + assert_too_large(fn -> Lua.get!(lua, [:big]) end) + assert {:tref, _} = Lua.get!(lua, [:big], decode: false) + end + + test "decode!/2", %{lua: lua} do + # `get!/3` with `decode: false` takes no display peek, so nothing outside + # `bounded/1` walks the table. + {_, lua} = Lua.eval!(lua, doubling(28, "big = t")) + ref = Lua.get!(lua, [:big], decode: false) + + assert_too_large(fn -> Lua.decode!(lua, ref) end) + end + + test "decode_list!/2 shares one budget across the list" do + {refs, lua} = + Lua.eval!(Lua.new(max_decode_nodes: 12), "local s = {1, 2, 3} return s, s, s", decode: false) + + assert [first, second, third] = Lua.decode_list!(lua, refs) + assert :erts_debug.same(first, second) and :erts_debug.same(second, third) + + tight = %{lua | state: %{lua.state | max_decode_nodes: 11}} + assert_too_large(fn -> Lua.decode_list!(tight, refs) end) + end + + test "decode: false truncates the peek instead of raising", %{lua: lua} do + assert {:ok, facts} = + bounded(fn -> + {[peeked], _} = Lua.eval!(lua, doubling(28), decode: false) + rendered = inspect(peeked, limit: :infinity) + + %{ + nodes: 1 + peek_nodes(peeked), + truncated?: rendered =~ "truncated", + bytes: byte_size(rendered) + } + end) + + assert facts.nodes <= 100 + assert facts.truncated? + assert facts.bytes < 10_000 + end + + test "decode: false shares peeks and truncates at the exact budget" do + # 1 + 2 + 1 × 2 + code = "local s = {1} return {s, s}" + + {[peeked], _} = Lua.eval!(Lua.new(max_decode_nodes: 5), code, decode: false) + assert %DTable{peek: [%DTable{peek: [1]} = first, second]} = peeked + assert :erts_debug.same(first, second) + + {[peeked], _} = Lua.eval!(Lua.new(max_decode_nodes: 4), code, decode: false) + assert %DTable{peek: [%DTable{peek: [1]}, %DTable{peek: :truncated} = cut]} = peeked + assert inspect(cut) == "#Lua.Table" + end + end + + describe "acyclic values" do + property "trees decode as a path-by-path walk" do + check all(data <- tree_gen(), max_runs: 200) do + {ref, state} = Value.encode(data, State.new()) + assert Value.decode(ref, state) === decode_path_by_path(ref, state) + end + end + + property "shared tables decode as a path-by-path walk, in less memory" do + check all(tables <- graph_gen(), max_runs: 200) do + {root, state} = build_graph(tables, :acyclic) + decoded = Value.decode(root, state) + expected = decode_path_by_path(root, state) + + assert decoded === expected + assert :erts_debug.size(decoded) <= :erts_debug.size(expected) + end + end + end + + describe "arbitrary graphs" do + property "the limit equals the expanded size" do + check all(tables <- graph_gen(), max_runs: 200) do + {root, state} = build_graph(tables, :any) + full = Value.decode(root, %{state | max_decode_nodes: :infinity}) + nodes = expanded_nodes(full) + + assert Value.decode(root, %{state | max_decode_nodes: nodes}) === full + + if nodes > 1 do + assert_too_large(fn -> Value.decode(root, %{state | max_decode_nodes: nodes - 1}) end) + end + end + end + + property "every cut is a table on a cycle" do + check all(tables <- graph_gen(), max_runs: 200) do + {root, state} = build_graph(tables, :any) + + for id <- cut_ids(Value.decode(root, state)) do + assert reaches?(state, id, id), "table #{id} was cut but is not on a cycle" + end + end + end + end + + # -- helpers --------------------------------------------------------------- + + defp doubling(levels, finish \\ "return t"), do: "local t = {} for _ = 1, #{levels} do t = {t, t} end #{finish}" + + defp doubled_term(levels), do: Enum.reduce(1..levels, [], fn _, inner -> [{1, inner}, {2, inner}] end) + + defp tangle_term(levels, cut) do + inner = Enum.reduce(1..levels, [{1, cut}], fn _, inner -> [{1, inner}, {2, inner}, {3, cut}] end) + [{1, inner}] + end + + defp spine_depth([{1, inner} | _]), do: 1 + spine_depth(inner) + defp spine_depth([]), do: 0 + + defp peek_depth(%DTable{peek: [inner]}), do: 1 + peek_depth(inner) + defp peek_depth(%DTable{peek: peek}) when peek == %{}, do: 0 + + defp peek_nodes(%DTable{peek: peek}) when is_list(peek) do + Enum.reduce(peek, 0, fn value, count -> count + 1 + peek_nodes(value) end) + end + + defp peek_nodes(%DTable{peek: peek}) when is_map(peek) do + Enum.reduce(peek, 0, fn {_key, value}, count -> count + 1 + peek_nodes(value) end) + end + + defp peek_nodes(_), do: 0 + + defp expanded_nodes(decoded), do: 1 + nodes_below(decoded) + + defp nodes_below(table) when is_list(table) do + Enum.reduce(table, 0, fn {_key, value}, count -> count + 1 + nodes_below(value) end) + end + + defp nodes_below(_), do: 0 + + defp cut_ids({:tref, id}), do: [id] + defp cut_ids(table) when is_list(table), do: Enum.flat_map(table, fn {_key, value} -> cut_ids(value) end) + defp cut_ids(_), do: [] + + defp reaches?(state, from, target), do: reaches?(state, children(state, from), target, MapSet.new()) + + defp reaches?(_state, [], _target, _seen), do: false + defp reaches?(_state, [target | _], target, _seen), do: true + + defp reaches?(state, [id | rest], target, seen) do + if MapSet.member?(seen, id) do + reaches?(state, rest, target, seen) + else + reaches?(state, children(state, id) ++ rest, target, MapSet.put(seen, id)) + end + end + + defp children(state, id) do + for {_k, {:tref, child}} <- Table.to_map(Map.fetch!(state.tables, id)), do: child + end + + defp assert_too_large(fun) do + assert {:raised, %Lua.RuntimeException{} = exception} = bounded(fun) + assert Exception.message(exception) =~ "decoded value exceeds :max_decode_nodes" + exception + end + + defp decode_path_by_path(value, state), do: decode_path_by_path(value, state, %{}) + + defp decode_path_by_path({:tref, id} = ref, _state, ancestors) when is_map_key(ancestors, id), do: ref + + defp decode_path_by_path({:tref, id}, state, ancestors) do + ancestors = Map.put(ancestors, id, true) + + Enum.map(Table.to_map(Map.fetch!(state.tables, id)), fn {key, value} -> + {key, decode_path_by_path(value, state, ancestors)} + end) + end + + defp decode_path_by_path({:udref, _} = ref, state, _ancestors), do: {:userdata, State.get_userdata(state, ref)} + defp decode_path_by_path(value, _state, _ancestors), do: value + + defp tree_gen do + leaf = one_of([integer(), float(), boolean(), string(:alphanumeric, max_length: 6)]) + key = string(:alphanumeric, min_length: 1, max_length: 4) + + leaf + |> tree(fn child -> + one_of([ + list_of(child, max_length: 40), + map_of(key, child, max_length: 40) + ]) + end) + |> resize(30) + end + + # Each entry is a scalar or a `{:ref, seed}` that `build_graph/2` resolves to a table. + defp graph_gen do + key = one_of([integer(1..6), string(:alphanumeric, min_length: 1, max_length: 3)]) + entry = one_of([tuple({constant(:scalar), integer()}), tuple({constant(:ref), non_negative_integer()})]) + list_of(map_of(key, entry, max_length: 4), min_length: 1, max_length: 8) + end + + # Under `:acyclic`, table `i` only points at earlier tables. The root is the last one. + defp build_graph(tables, mode) do + count = length(tables) + + {refs, state} = + Enum.map_reduce(1..count, State.new(), fn _, state -> State.alloc_table(state) end) + + state = + tables + |> Enum.with_index() + |> Enum.reduce(state, fn {entries, index}, state -> + State.update_table(state, Enum.at(refs, index), fn table -> + Enum.reduce(entries, table, fn {key, entry}, table -> + Table.put(table, key, resolve(entry, refs, index, mode)) + end) + end) + end) + + {List.last(refs), state} + end + + defp resolve({:scalar, value}, _refs, _index, _mode), do: value + defp resolve({:ref, seed}, _refs, 0, :acyclic), do: seed + defp resolve({:ref, seed}, refs, index, :acyclic), do: Enum.at(refs, rem(seed, index)) + defp resolve({:ref, seed}, refs, _index, :any), do: Enum.at(refs, rem(seed, length(refs))) + + # Runs `fun` in a heap- and time-capped process so a regression fails + # instead of exhausting the machine. Only send back small facts: message + # passing copies a term without its sharing. + defp bounded(fun) do + parent = self() + tag = make_ref() + words = div(@heap_cap_bytes, :erlang.system_info(:wordsize)) + + {pid, monitor} = + :erlang.spawn_opt( + fn -> + result = + try do + {:ok, fun.()} + rescue + exception -> {:raised, exception} + end + + send(parent, {tag, result}) + end, + [:monitor, max_heap_size: %{size: words, kill: true, error_logger: false}] + ) + + receive do + {^tag, result} -> + Process.demonitor(monitor, [:flush]) + result + + {:DOWN, ^monitor, :process, ^pid, reason} -> + {:exit, reason} + after + @time_cap_ms -> + Process.exit(pid, :kill) + :timeout + end + end +end