diff --git a/CHANGELOG.md b/CHANGELOG.md index 2c326427..3f0f2cb0 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`: `Lua.set_deadline(lua, to_timeout(second: 5))` + gives Lua a time limit in milliseconds from now (`:infinity` removes it), and + `deadline/1` returns the milliseconds left. When the time is up, running Lua raises a + catchable `"deadline exceeded"` error, checked at loop iterations and calls 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. 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 6c0cac06..a22b855a 100644 --- a/lib/lua.ex +++ b/lib/lua.ex @@ -1134,6 +1134,71 @@ defmodule Lua do Lua.API.install(lua, module, scope, opts[:data]) end + @doc """ + Gives Lua code running on `lua` a time limit, in milliseconds from now. + + `timeout` is a non-negative integer, or `:infinity` to remove the limit (the + default). Any other value raises `ArgumentError`. + + iex> lua = Lua.new() |> Lua.set_deadline(to_timeout(minute: 1)) + iex> {[45], _lua} = Lua.eval!(lua, "local s = 0 for i = 1, 9 do s = s + i end return s") + + When the time is up, running Lua raises a catchable `"deadline exceeded"` + error. A `0` timeout is already up: + + iex> lua = Lua.new() |> Lua.set_deadline(0) + iex> {[false, message], _lua} = Lua.eval!(lua, "return pcall(function() while true do end end)") + iex> message =~ "deadline exceeded" + true + + The limit is soft. Lua checks the clock at loop iterations and function + calls, a few hundred of them apart, so it can run a little past the time. + Nothing interrupts work between two checks: Elixir functions that Lua calls, + Lua functions run by the standard library (a `string.gsub` replacement or a + `table.sort` comparator), pattern matching and `string.rep`. To stop + untrusted code for certain, run it in a process you can kill. + + Once the time is up, it stays up on the state that `eval!/2` returns. Every + later evaluation on that state raises again at its first loop or call, until + you call `set_deadline/2` again. A `pcall` can catch the error, but any + loop or call after it raises again. + """ + @spec set_deadline(t(), timeout()) :: t() + def set_deadline(%__MODULE__{state: state} = lua, :infinity), do: %{lua | state: %{state | deadline: :infinity}} + + # A zero timeout is up already, so it takes the same form as a deadline Lua found passed: + # every later loop or call raises, not only one that lands on a clock read. + def set_deadline(%__MODULE__{state: state} = lua, 0), do: %{lua | state: %{state | deadline: :passed}} + + def set_deadline(%__MODULE__{state: state} = lua, timeout) when is_integer(timeout) and timeout > 0 do + %{lua | state: %{state | deadline: System.monotonic_time(:millisecond) + timeout}} + end + + def set_deadline(%__MODULE__{}, timeout) do + raise ArgumentError, + "expected a non-negative integer number of milliseconds or :infinity, got: #{inspect(timeout)}" + end + + @doc """ + Returns the milliseconds left before the deadline, or `:infinity` if none is set. + + It returns `0` once the time is up and never a negative number. + + iex> Lua.new() |> Lua.deadline() + :infinity + + iex> Lua.new() |> Lua.set_deadline(60_000) |> Lua.deadline() > 0 + true + + To give a nested call a shorter limit and then put the old one back, read + the time left first and set it again afterwards. The time the nested call + used is not taken off it, so subtract that yourself if it matters. + """ + @spec deadline(t()) :: non_neg_integer() | :infinity + def deadline(%__MODULE__{state: %{deadline: :infinity}}), do: :infinity + def deadline(%__MODULE__{state: %{deadline: :passed}}), do: 0 + def deadline(%__MODULE__{state: %{deadline: at}}), do: max(at - System.monotonic_time(:millisecond), 0) + @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 9559ab8a..628b87b2 100644 --- a/lib/lua/vm/dispatcher.ex +++ b/lib/lua/vm/dispatcher.ex @@ -43,6 +43,10 @@ defmodule Lua.VM.Dispatcher do # in range, saving one function call per integer-arithmetic opcode. @max_int 0x7FFFFFFFFFFFFFFF @min_int -0x8000000000000000 + # Ticks between clock reads while a deadline is set. A literal, not a call to + # `State`, so this module has no compile-time dependency on it; a test pins it + # equal to `State.deadline_stride/0`. + @deadline_stride 256 @op_load_constant 1 @op_load_boolean 2 @@ -2419,7 +2423,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 627ef8b7..c2edcd68 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 00000000..57e90706 --- /dev/null +++ b/test/lua/vm/deadline_test.exs @@ -0,0 +1,181 @@ +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, 0) + + 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 "deadline/1 returns the milliseconds left, counting down" do + lua = Lua.set_deadline(Lua.new(), 60_000) + assert Lua.deadline(lua) in 59_000..60_000 + Process.sleep(20) + assert Lua.deadline(lua) <= 59_980 + end + + test "deadline/1 is 0 once the time is up, never negative" do + lua = Lua.set_deadline(Lua.new(), 1) + Process.sleep(5) + assert Lua.deadline(lua) == 0 + assert Lua.deadline(passed(Lua.new())) == 0 + end + + test ":infinity clears the deadline" do + lua = Lua.set_deadline(Lua.new(), 10) + assert Lua.deadline(Lua.set_deadline(lua, :infinity)) == :infinity + end + + test "to_timeout/1 values are accepted" do + lua = Lua.set_deadline(Lua.new(), to_timeout(minute: 1)) + assert Lua.deadline(lua) in 59_000..60_000 + end + + test "set_deadline/2 rejects anything but a non-negative integer or :infinity" do + for bad <- [-1, 1.5, "10", nil, :passed, :soon] do + assert_raise ArgumentError, ~r/non-negative integer number of milliseconds or :infinity/, fn -> + Lua.set_deadline(Lua.new(), bad) + end + end + end + + test "a deadline of 0 is passed immediately" do + assert_raise RuntimeException, ~r/deadline exceeded/, fn -> + Lua.eval!(Lua.set_deadline(Lua.new(), 0), "while true do end") + end + end + + test "a passed deadline stays on the returned state" do + {[false, _message], lua} = Lua.eval!(passed(Lua.new()), "return pcall(function() while true do end end)") + assert Lua.deadline(lua) == 0 + end + + test "the dispatcher's clock stride matches the state's" do + assert {:ok, source} = File.read(Path.join(File.cwd!(), "lib/lua/vm/dispatcher.ex")) + assert source =~ "@deadline_stride #{Lua.VM.State.deadline_stride()}\n" + 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(), 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(), 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(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, 0) + + {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 "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 == 0], 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