diff --git a/CHANGELOG.md b/CHANGELOG.md index ab8c373..453b733 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -62,6 +62,13 @@ is in the [`1.0.0-rc.0`](#100-rc0---2026-05-26) entry below. after the call (`pcall`, `xpcall`, or the error path of `Lua.call_function/3`) keeps the collector's bookkeeping, so a later minor collection does not free a table or closure cell that is still in use. +- `Lua.set_deadline/2` and `Lua.deadline/1`: past a `System.monotonic_time(:millisecond)` + deadline, running Lua raises a catchable `"deadline exceeded"` error, checked at loop + back-edges and call boundaries like `:max_instructions`. A `pcall` that traps it is + interrupted again on any further loop or call. It is a soft limit: Lua callbacks run by + the standard library and pattern matching are not interrupted. A host can give a + nested call from an Elixir function its own deadline (a `lua_sethook` count hook in + reference Lua). Without a deadline the hot path is unchanged. ### Changed - Writes to an existing table now go through `Lua.VM.State.put_table/3`, which diff --git a/lib/lua.ex b/lib/lua.ex index 6c0cac0..2bc5ff3 100644 --- a/lib/lua.ex +++ b/lib/lua.ex @@ -1134,6 +1134,50 @@ defmodule Lua do Lua.API.install(lua, module, scope, opts[:data]) end + @doc """ + Sets the instant after which Lua code running on `lua` raises a catchable + `"deadline exceeded"` error, as a `System.monotonic_time(:millisecond)` + value, or `:infinity` for none (the default). `:passed` is what `deadline/1` + returns once Lua has found the deadline passed; it is accepted so a value + read with `deadline/1` can always be set back. + + The deadline is checked at loop back-edges and call boundaries, every few + hundred of them, like the `:max_instructions` budget. It is a soft limit: + the clock is read once per stride of those, not on every one, and nothing + bounds how long the work between two of them takes. Elixir functions Lua + calls are not interrupted while they run, and neither are the Lua callbacks + the standard library runs (a `string.gsub` replacement function, a + `table.sort` comparator) nor pattern matching and `string.rep`. A host that + needs a hard limit on untrusted code must run the evaluation in a process it + can kill. + + Once Lua finds the deadline passed it stays passed on the state the + evaluation returns, and every later evaluation on that state raises again at + its first loop iteration or call, until the host sets a new deadline. A + `pcall` traps the error, and the protected call's result is returned + normally when nothing that ticks follows it (`return pcall(f)` returns + `false` and the message), but any further loop or call raises again. + + It is the deadline a `lua_sethook` count hook gives a host in reference Lua: + a host calling back into Lua from an Elixir function can give that call a + shorter deadline, and restore the previous one with `deadline/1` once it + returns, so only the callback fails. + + iex> lua = Lua.new() |> Lua.set_deadline(System.monotonic_time(:millisecond)) + iex> {[false, message], _lua} = Lua.eval!(lua, "return pcall(function() while true do end end)") + iex> message =~ "deadline exceeded" + true + """ + @spec set_deadline(t(), integer() | :infinity | :passed) :: t() + def set_deadline(%__MODULE__{state: state} = lua, deadline) + when is_integer(deadline) or deadline in [:infinity, :passed] do + %{lua | state: %{state | deadline: deadline}} + end + + @doc "Returns the deadline set with `set_deadline/2`, `:infinity`, or `:passed` once Lua found it passed." + @spec deadline(t()) :: integer() | :infinity | :passed + def deadline(%__MODULE__{state: state}), do: state.deadline + @doc """ Puts a private value in storage for use in Elixir functions diff --git a/lib/lua/vm/dispatcher.ex b/lib/lua/vm/dispatcher.ex index 9559ab8..28b9a3e 100644 --- a/lib/lua/vm/dispatcher.ex +++ b/lib/lua/vm/dispatcher.ex @@ -43,6 +43,7 @@ defmodule Lua.VM.Dispatcher do # in range, saving one function call per integer-arithmetic opcode. @max_int 0x7FFFFFFFFFFFFFFF @min_int -0x8000000000000000 + @deadline_stride State.deadline_stride() @op_load_constant 1 @op_load_boolean 2 @@ -2419,7 +2420,13 @@ defmodule Lua.VM.Dispatcher do :maps.filter(fn reg, _cell -> reg < threshold end, open_upvalues) end - defp tick(%{max_instructions: :infinity}, instruction_count, _call_stack, _call_depth), do: instruction_count + defp tick(%{max_instructions: :infinity, deadline: :infinity}, instruction_count, _call_stack, _call_depth), + do: instruction_count + + # A deadline with no budget reads the clock only every `@deadline_stride` ticks; the ticks + # between need no struct sync. + defp tick(%{max_instructions: :infinity, deadline: deadline}, instruction_count, _call_stack, _call_depth) + when is_integer(deadline) and rem(instruction_count + 1, @deadline_stride) != 0, do: instruction_count + 1 defp tick(state, instruction_count, call_stack, call_depth) do State.tick!(sync(state, call_stack, call_depth), instruction_count) diff --git a/lib/lua/vm/state.ex b/lib/lua/vm/state.ex index 627ef8b..c2edcd6 100644 --- a/lib/lua/vm/state.ex +++ b/lib/lua/vm/state.ex @@ -7,6 +7,15 @@ defmodule Lua.VM.State do alias Lua.VM.RuntimeError alias Lua.VM.Table + # How many ticks pass between reads of the clock while a deadline is set: a + # tick is a loop iteration or a call, so the clock is read once per stride + # rather than on every one. It counts ticks, not time: work between ticks + # is not bounded. + @deadline_stride 256 + + @doc false + def deadline_stride, do: @deadline_stride + # `call_stack`, `call_depth` and `open_upvalues` are control state, not # heap state. The interpreter keeps them here; the dispatcher threads # them as loop parameters (the same discipline as `instruction_count` @@ -40,6 +49,13 @@ defmodule Lua.VM.State do # `line`-off-State discipline so the default `:infinity` path # carries no per-instruction struct rebuild. See `tick!/2`. max_instructions: :infinity, + # `deadline` is a `System.monotonic_time(:millisecond)` instant after + # which execution raises a catchable `"deadline exceeded"` error; + # `:infinity` (the default) means none. Host-set per call with + # `Lua.set_deadline/2`, and checked by `tick!/2` at the same + # boundaries as the instruction budget, sampling the clock every + # `@deadline_stride` ticks. `:passed` once a tick found it passed. + deadline: :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 @@ -81,6 +97,7 @@ defmodule Lua.VM.State do entry_depth: non_neg_integer(), max_string_bytes: pos_integer() | :infinity, max_instructions: pos_integer() | :infinity, + deadline: integer() | :infinity | :passed, instruction_count: non_neg_integer(), metatables: map(), upvalue_cells: map(), @@ -156,13 +173,38 @@ 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. + + With a `deadline` set, the tally also counts when `max_instructions` is + `:infinity`, and every `@deadline_stride` ticks the monotonic clock is read: + once it reaches the deadline, a catchable `"deadline exceeded"` runtime + error is raised the same way, and the state it carries has `deadline: + :passed`. `unwind_to/2` keeps `:passed`, and every later tick raises at + once, so a protected call that traps the error is interrupted again on its + next tick and the error reaches the host's own call — the behaviour of a + `lua_sethook` count hook in reference Lua. The host's next + `Lua.set_deadline/2` replaces it. """ @spec tick!(t(), non_neg_integer()) :: non_neg_integer() - def tick!(%__MODULE__{max_instructions: :infinity}, instruction_count), do: instruction_count + def tick!(%__MODULE__{max_instructions: :infinity, deadline: :infinity}, instruction_count), do: instruction_count - def tick!(%__MODULE__{max_instructions: max}, instruction_count) when instruction_count + 1 < max, + def tick!(%__MODULE__{max_instructions: max, deadline: :infinity}, instruction_count) when instruction_count + 1 < max, do: instruction_count + 1 + def tick!(%__MODULE__{deadline: :passed} = state, instruction_count), + do: deadline_exceeded!(state, instruction_count + 1) + + # `:infinity` sorts above every integer, so an unbounded budget always passes this guard. + def tick!(%__MODULE__{max_instructions: max, deadline: deadline} = state, instruction_count) + when instruction_count + 1 < max do + instruction_count = instruction_count + 1 + + if rem(instruction_count, @deadline_stride) == 0 and System.monotonic_time(:millisecond) >= deadline do + deadline_exceeded!(state, instruction_count) + end + + instruction_count + end + def tick!(%__MODULE__{call_stack: call_stack} = state, instruction_count) do instruction_count = instruction_count + 1 @@ -172,6 +214,13 @@ defmodule Lua.VM.State do state: %{state | instruction_count: instruction_count} end + defp deadline_exceeded!(state, instruction_count) do + raise RuntimeError, + value: "deadline exceeded", + call_stack: state.call_stack, + state: %{state | instruction_count: instruction_count, deadline: :passed} + end + @doc """ Recovers the state a protected call should continue with after trapping an error. @@ -202,6 +251,9 @@ defmodule Lua.VM.State do against the one per-evaluation `:max_instructions` budget, so wrapping heavy work in `pcall` (or looping over `pcall`) cannot escape the cap. + A deadline the raise found passed (`deadline: :passed`) is kept the same way, + so a trapped `"deadline exceeded"` cannot be escaped either. + Keeping `upvalue_cells` while restoring `open_upvalues` matches reference upvalue semantics: cells captured before the protected call keep their mutated values, while cells opened by the unwound frames become @@ -226,10 +278,15 @@ defmodule Lua.VM.State do gc_remembered: raised.gc_remembered, gc_young_from: raised.gc_young_from, gc: raised.gc, - instruction_count: max(entry.instruction_count, raised.instruction_count) + instruction_count: max(entry.instruction_count, raised.instruction_count), + deadline: kept_deadline(entry.deadline, raised.deadline) } end + # A deadline the raise found passed stays passed: `pcall` cannot trap its way past it. + defp kept_deadline(_entry, :passed), do: :passed + defp kept_deadline(entry, _raised), do: entry + @doc """ Returns the `_G` table reference. """ diff --git a/test/lua/vm/deadline_test.exs b/test/lua/vm/deadline_test.exs new file mode 100644 index 0000000..1f9255c --- /dev/null +++ b/test/lua/vm/deadline_test.exs @@ -0,0 +1,145 @@ +defmodule Lua.VM.DeadlineTest do + @moduledoc """ + Pins `Lua.set_deadline/2`: once the deadline passes, running Lua raises a + catchable `"deadline exceeded"` error on both the interpreter and the + compiled-dispatcher path, a `pcall` that traps it cannot keep the script + running, and a host can give a nested call a shorter deadline so only that + call fails. + """ + use ExUnit.Case, async: true + + alias Lua.RuntimeException + + defp now, do: System.monotonic_time(:millisecond) + defp passed(lua), do: Lua.set_deadline(lua, now()) + + test "no deadline by default" do + assert Lua.deadline(Lua.new()) == :infinity + assert {[45], _lua} = Lua.eval!(Lua.new(), "local s = 0 for i = 1, 9 do s = s + i end return s") + end + + test "set_deadline/2 and deadline/1 round-trip" do + lua = Lua.set_deadline(Lua.new(), 123) + assert Lua.deadline(lua) == 123 + assert Lua.deadline(Lua.set_deadline(lua, :infinity)) == :infinity + end + + test "a passed deadline ends a top-level loop" do + assert_raise RuntimeException, ~r/deadline exceeded/, fn -> + Lua.eval!(passed(Lua.new()), "while true do end") + end + end + + test "a passed deadline ends a loop in a compiled function" do + assert_raise RuntimeException, ~r/deadline exceeded/, fn -> + Lua.eval!(passed(Lua.new()), "local function spin() while true do end end spin()") + end + end + + test "a passed deadline ends unbounded recursion" do + assert_raise RuntimeException, ~r/deadline exceeded/, fn -> + Lua.eval!(passed(Lua.new()), "local function f() return f() end f()") + end + end + + test "the deadline is read from the clock, not fixed when the call starts" do + lua = Lua.set_deadline(Lua.new(), now() + 50) + started = now() + + assert_raise RuntimeException, ~r/deadline exceeded/, fn -> + Lua.eval!(lua, "while true do end") + end + + assert now() - started >= 50 + end + + test "work that finishes before the deadline is not interrupted" do + lua = Lua.set_deadline(Lua.new(), now() + 60_000) + + assert {[500_000_500_000], _lua} = + Lua.eval!(lua, "local s = 0 for i = 1, 1000000 do s = s + i end return s") + end + + test "pcall traps the error, which comes back on the next ticks" do + {[false, message], _lua} = + Lua.eval!(passed(Lua.new()), "return pcall(function() while true do end end)") + + assert message =~ "deadline exceeded" + + assert_raise RuntimeException, ~r/deadline exceeded/, fn -> + Lua.eval!(passed(Lua.new()), """ + local spin = function() while true do end end + while true do pcall(spin) end + """) + end + end + + test "heap effects before the error are kept" do + lua = passed(Lua.new()) + {[false, _message], lua} = Lua.eval!(lua, "return pcall(function() seen = 1 while true do end end)") + assert {[1], _lua} = lua |> Lua.set_deadline(:infinity) |> Lua.eval!("return seen") + end + + test "the instruction budget still applies with a deadline set" do + lua = [max_instructions: 1000] |> Lua.new() |> Lua.set_deadline(now() + 60_000) + + assert_raise RuntimeException, ~r/instruction budget exceeded/, fn -> + Lua.eval!(lua, "while true do end") + end + end + + test "a host gives a nested call its own deadline, and only that call fails" do + # The Elixir function stands in for a host that calls back into Lua while an outer + # call waits on it: the callback runs on the same state with a passed deadline, the + # error ends it, and the outer call carries on once the old deadline is back. + lua = + Lua.set!(Lua.new(), [:host_call], fn [callback], lua -> + outer = Lua.deadline(lua) + nested = Lua.set_deadline(lua, now()) + + {result, lua} = + case Lua.call_function(nested, callback, []) do + {:ok, _values, lua} -> {"finished", lua} + {:error, %RuntimeException{} = error, lua} -> {Exception.message(error), lua} + end + + {[result], Lua.set_deadline(lua, outer)} + end) + + {[message, total], _lua} = + Lua.eval!(lua, """ + local message = host_call(function() while true do end end) + local s = 0 + for i = 1, 100000 do s = s + i end + return message, s + """) + + assert message =~ "deadline exceeded" + assert total == 5_000_050_000 + end + + test ":passed can be set back, so a saved deadline always restores" do + lua = Lua.set_deadline(Lua.new(), :passed) + assert Lua.deadline(lua) == :passed + assert Lua.deadline(Lua.set_deadline(lua, Lua.deadline(lua))) == :passed + end + + test "a host restores the outer deadline after a pcall trapped it" do + lua = + Lua.set!(Lua.new(), [:host_call], fn [callback], lua -> + outer = Lua.deadline(lua) + nested = Lua.set_deadline(lua, :infinity) + {:ok, _values, nested} = Lua.call_function(nested, callback, []) + {[outer == :passed], Lua.set_deadline(nested, outer)} + end) + + assert_raise RuntimeException, ~r/deadline exceeded/, fn -> + Lua.eval!(passed(lua), """ + pcall(function() while true do end end) + local passed = host_call(function() return 1 end) + local function f() return passed end + return f() + """) + end + end +end