From 6015bd4604191ac968e5ede6f8f7f9d952e553fa Mon Sep 17 00:00:00 2001 From: Adrien Cohen <18153974+adriencohen@users.noreply.github.com> Date: Mon, 16 Nov 2026 11:53:17 +0100 Subject: [PATCH] fix(vm): keep host exception text out of pcall results pcall hands the script the text of host failures: the message of any Elixir exception raised in host code (a MatchError message contains host data), and the inspected return value of a Lua.set!/3 function that returns unencoded data. The script now gets "error in host function" for both. Base-library functions that crashed with an Elixir exception on a bad argument (rawget, rawset, os.date, ...) now raise Lua errors, so pcall still reports them to the script. --- CHANGELOG.md | 8 ++ lib/lua.ex | 33 +++--- lib/lua/api.ex | 5 + lib/lua/vm/protected_call.ex | 28 ++++- lib/lua/vm/stdlib.ex | 121 ++++++++++++--------- lib/lua/vm/stdlib/os.ex | 5 +- test/lua/pcall_host_error_test.exs | 88 +++++++++++++++ test/lua/vm/stdlib/base_arguments_test.exs | 33 ++++++ test/lua/vm/stdlib/os_test.exs | 5 + 9 files changed, 252 insertions(+), 74 deletions(-) create mode 100644 test/lua/pcall_host_error_test.exs create mode 100644 test/lua/vm/stdlib/base_arguments_test.exs diff --git a/CHANGELOG.md b/CHANGELOG.md index c26f0ca..86a0c84 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -55,6 +55,14 @@ is in the [`1.0.0-rc.0`](#100-rc0---2026-05-26) entry below. 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). +- `pcall` and `xpcall` return `"error in host function"` instead of the + message of an exception raised by host code, which can quote host data. + Errors raised for the script pass through unchanged. +- `rawget`, `rawset`, `rawequal`, `next`, `getmetatable`, `setmetatable`, + `tostring`, `tonumber` and `select` raise Lua's `"bad argument"` errors + instead of an Elixir exception or a silent default. +- `os.date` raises a Lua error for an out-of-range time instead of an Elixir + `ArgumentError`. ## [1.0.2] - 2026-07-28 diff --git a/lib/lua.ex b/lib/lua.ex index 242d83c..08b2c55 100644 --- a/lib/lua.ex +++ b/lib/lua.ex @@ -1253,26 +1253,12 @@ defmodule Lua do {data, %Lua{} = returned_lua} -> data = List.wrap(data) - - if not Util.list_encoded?(data) do - raise Lua.RuntimeException, - function: function_name, - scope: module.scope(), - message: "deflua functions must return encoded data, got #{inspect(data)}" - end - + validate_encoded!(data, function_name, module.scope()) {data, returned_lua} data -> data = List.wrap(data) - - if not Util.list_encoded?(data) do - raise Lua.RuntimeException, - function: function_name, - scope: module.scope(), - message: "deflua functions must return encoded data, got #{inspect(data)}" - end - + validate_encoded!(data, function_name, module.scope()) {data, lua} end catch @@ -1328,15 +1314,22 @@ defmodule Lua do end} end + # Raised as a host exception: the message quotes host data. defp validate_encoded!(value, function_name, scope) do if not Util.list_encoded?(value) do - raise Lua.RuntimeException, - function: function_name, - scope: scope, - message: "deflua functions must return encoded data, got #{inspect(value)}" + unencoded_return = + ArgumentError.exception( + "#{callback_label(scope, function_name)} failed, " <> + "deflua functions must return encoded data, got #{inspect(value)}" + ) + + raise Lua.RuntimeException, unencoded_return end end + defp callback_label([], function_name), do: "#{function_name}()" + defp callback_label(scope, function_name), do: "#{Enum.join(scope, ".")}.#{function_name}()" + defp to_lua_key(key) when is_atom(key), do: Atom.to_string(key) defp to_lua_key(key) when is_binary(key), do: key defp to_lua_key(key), do: key diff --git a/lib/lua/api.ex b/lib/lua/api.ex index dc19789..01cff99 100644 --- a/lib/lua/api.ex +++ b/lib/lua/api.ex @@ -85,6 +85,11 @@ defmodule Lua.API do Keep in mind that if you want to work with values passed to `deflua` functions, they still need to be decoded first. + + ## Errors + + Call `runtime_exception!/1` or return `{:error, reason}` to give `pcall` a + readable error. Other exceptions reach `pcall` as `"error in host function"`. """ defmacro __using__(opts) do diff --git a/lib/lua/vm/protected_call.ex b/lib/lua/vm/protected_call.ex index 2542726..10d3d9e 100644 --- a/lib/lua/vm/protected_call.ex +++ b/lib/lua/vm/protected_call.ex @@ -5,7 +5,10 @@ defmodule Lua.VM.ProtectedCall do # (`pcall`/`xpcall`, and `Lua.call_function/3`), per §6.1: the raised value # passes through verbatim. # - # Clause ordering is load-bearing: + # `caught_value/1` replaces host exception messages, which can quote host + # data, with `"error in host function"`. + # + # `error_value/1` clause ordering is load-bearing: # 1. `error()`'s §6.1-prefixed string view (`RuntimeError.lua_value`). # 2. Raw passthrough on KEY PRESENCE — `value: nil` (from `error()`) and # `value: false` must match here so the boundary returns nil/false like @@ -14,11 +17,30 @@ defmodule Lua.VM.ProtectedCall do # `:value` slot, so it gets its own clause that returns the raw # `"bad argument #N to 'F' ..."` string — never the terminal-rendered # `Exception.message/1` (ANSI + location header). - # 4. Plain Elixir exceptions keep their message string as a last resort. alias Lua.VM.ArgumentError + alias Lua.VM.AssertionError + alias Lua.VM.RuntimeError + alias Lua.VM.TypeError + + @vm_errors [RuntimeError, AssertionError, TypeError, ArgumentError] + + @host_error_message "error in host function" + + def caught_value(exception), do: caught_value(exception, raised_for_script?(exception)) + + defp caught_value(%module{} = vm_error, true) when module in @vm_errors, do: error_value(vm_error) + defp caught_value(runtime_exception, true), do: Exception.message(runtime_exception) + defp caught_value(_host_exception, false), do: @host_error_message + + defp raised_for_script?(%module{}) when module in @vm_errors, do: true + + defp raised_for_script?(%Lua.RuntimeException{original: original}) when is_exception(original), + do: raised_for_script?(original) + + defp raised_for_script?(%Lua.RuntimeException{}), do: true + defp raised_for_script?(_host_exception), do: false def error_value(%{lua_value: lv}) when not is_nil(lv), do: lv def error_value(%{value: value}), do: value def error_value(%ArgumentError{} = e), do: ArgumentError.raw_message(e) - def error_value(e), do: Exception.message(e) end diff --git a/lib/lua/vm/stdlib.ex b/lib/lua/vm/stdlib.ex index 6967692..b7b9783 100644 --- a/lib/lua/vm/stdlib.ex +++ b/lib/lua/vm/stdlib.ex @@ -15,7 +15,6 @@ defmodule Lua.VM.Stdlib do alias Lua.VM.RuntimeError alias Lua.VM.State alias Lua.VM.Table - alias Lua.VM.TypeError alias Lua.VM.Value # Installed in this order: it is the order `pairs(_G)` and @@ -121,31 +120,28 @@ defmodule Lua.VM.Stdlib do {[str], state} end - defp lua_tostring([], state), do: {["nil"], state} + defp lua_tostring([], _state), do: raise(ArgumentError.value_expected("tostring", 1)) # tonumber(v [, base]) — converts a string to a number - defp lua_tonumber([value | rest], state) do - base = List.first(rest) + defp lua_tonumber([], _state), do: raise(ArgumentError.value_expected("tonumber", 1)) - result = - case {value, base} do - {v, nil} when is_number(v) -> - v + defp lua_tonumber([value | base], state), do: {[tonumber(value, base)], state} - {v, nil} when is_binary(v) -> - Value.parse_number(v) + defp tonumber(value, []), do: to_number_or_nil(value) + defp tonumber(value, [nil | _]), do: to_number_or_nil(value) + defp tonumber(value, [base | _]), do: tonumber_in_base(value, integer_argument!(base, "tonumber", 2)) - {v, b} when is_binary(v) and is_integer(b) and b >= 2 and b <= 36 -> - parse_in_base(v, b) + defp to_number_or_nil(value) when is_number(value), do: value + defp to_number_or_nil(value) when is_binary(value), do: Value.parse_number(value) + defp to_number_or_nil(_value), do: nil - _ -> - nil - end + defp tonumber_in_base(value, _base) when not is_binary(value), + do: raise(ArgumentError.type_error("tonumber", 1, "string", Value.type_name(value))) - {[result], state} - end + defp tonumber_in_base(_value, base) when base not in 2..36, + do: raise(ArgumentError, function_name: "tonumber", arg_num: 2, details: "base out of range") - defp lua_tonumber([], state), do: {[nil], state} + defp tonumber_in_base(value, base), do: parse_in_base(value, base) # tonumber(s, base) per Lua 5.3 §6.1: surrounding whitespace is ignored, an # optional sign is allowed, digits a-z/A-Z map to 10-35 (case-insensitive), @@ -253,12 +249,7 @@ defmodule Lua.VM.Stdlib do {results, state} = Executor.call_function(func, args, state) {[true | results], state} rescue - e in [RuntimeError, AssertionError, TypeError, ArgumentError] -> - {[false, ProtectedCall.error_value(e)], State.unwind_to(state, e.state)} - - e -> - # Catch any other error - {[false, Exception.message(e)], State.unwind_to(state, raised_state(e))} + exception -> {[false, ProtectedCall.caught_value(exception)], State.unwind_to(state, raised_state(exception))} end defp lua_pcall([], state), do: {[false, "bad argument #1 to 'pcall' (value expected)"], state} @@ -273,12 +264,8 @@ defmodule Lua.VM.Stdlib do {results, state} = Executor.call_function(func, args, state) {[true | results], state} rescue - e in [RuntimeError, AssertionError, TypeError, ArgumentError] -> - run_xpcall_handler(handler, ProtectedCall.error_value(e), State.unwind_to(state, e.state)) - - e -> - # Catch any other error - run_xpcall_handler(handler, Exception.message(e), State.unwind_to(state, raised_state(e))) + exception -> + run_xpcall_handler(handler, ProtectedCall.caught_value(exception), State.unwind_to(state, raised_state(exception))) end defp lua_xpcall(_, state), do: {[false, "bad argument to 'xpcall'"], state} @@ -304,12 +291,27 @@ defmodule Lua.VM.Stdlib do {[Table.get(table, key)], state} end + defp lua_rawget(args, _state), do: raise(table_argument_error("rawget", args)) + # rawset(table, key, value) — set without metamethods defp lua_rawset([{:tref, _} = tref, key, value | _], state) do state = State.update_table(state, tref, fn table -> Table.put(table, key, value) end) {[tref], state} end + defp lua_rawset(args, _state), do: raise(table_argument_error("rawset", args)) + + defp table_argument_error(function_name, []), do: ArgumentError.value_expected(function_name, 1) + + defp table_argument_error(function_name, [{:tref, _} | _] = too_few_args), + do: missing_argument_error(function_name, too_few_args) + + defp table_argument_error(function_name, [non_table | _]), + do: ArgumentError.type_error(function_name, 1, "table", Value.type_name(non_table)) + + defp missing_argument_error(function_name, given_args), + do: ArgumentError.value_expected(function_name, length(given_args) + 1) + # rawlen(v) — length without metamethods. # # Lua 5.3 reference: rawlen requires a table or string argument and @@ -342,7 +344,7 @@ defmodule Lua.VM.Stdlib do {[a === b], state} end - defp lua_rawequal(_, state), do: {[false], state} + defp lua_rawequal(args, _state), do: raise(missing_argument_error("rawequal", args)) # next(table [, key]) — returns next key-value pair after key. # Per Lua 5.3 §6.1, when `key` is non-nil and was never a key in the @@ -381,7 +383,7 @@ defmodule Lua.VM.Stdlib do end end - defp lua_next(_, state), do: {[nil, nil], state} + defp lua_next(args, _state), do: raise(table_argument_error("next", args)) # pairs(table) — returns next, table, nil defp lua_pairs([{:tref, _} = tref | _], state) do @@ -421,24 +423,20 @@ defmodule Lua.VM.Stdlib do {[length(args)], state} end - defp lua_select([index | args], state) when is_integer(index) do - cond do - # Positive index: return from that position onward - index > 0 -> - selected = Enum.drop(args, index - 1) - {selected, state} - - # Negative index: count from end (take last n elements) - index < 0 -> - selected = Enum.take(args, index) - {selected, state} + defp lua_select([index | args], state) when is_integer(index) and index > 0 do + {Enum.drop(args, index - 1), state} + end - # Index 0 is invalid - true -> - raise RuntimeError, value: "bad argument #1 to 'select' (index out of range)" - end + defp lua_select([index | args], state) when is_integer(index) and index < 0 and -index <= length(args) do + {Enum.take(args, index), state} end + defp lua_select([index | _], _state) when is_integer(index), + do: raise(ArgumentError, function_name: "select", arg_num: 1, details: "index out of range") + + defp lua_select([index | args], state) when is_float(index), + do: lua_select([integer_argument!(index, "select", 1) | args], state) + defp lua_select([non_valid | _], _state) do raise ArgumentError, function_name: "select", @@ -451,6 +449,25 @@ defmodule Lua.VM.Stdlib do raise ArgumentError.value_expected("select", 1) end + # `luaL_checkinteger`: accepts a float with an exact integer value. + defp integer_argument!(value, _function_name, _arg_num) when is_integer(value), do: value + + defp integer_argument!(value, function_name, arg_num) when is_float(value) do + truncated = trunc(value) + + if value == truncated and Numeric.signed?(truncated) do + truncated + else + raise ArgumentError, + function_name: function_name, + arg_num: arg_num, + details: "number has no integer representation" + end + end + + defp integer_argument!(value, function_name, arg_num), + do: raise(ArgumentError.type_error(function_name, arg_num, "number", Value.type_name(value))) + # load(chunk, chunkname, mode, env) — loads a Lua chunk # `chunk` may be either a string or a reader function. A reader function # is called repeatedly; each call must return a string piece, and the @@ -565,7 +582,7 @@ defmodule Lua.VM.Stdlib do defp format_parse_error(error) when is_binary(error), do: error # setmetatable(table, metatable) — sets the metatable for a table - defp lua_setmetatable([{:tref, _} = tref, metatable], state) do + defp lua_setmetatable([{:tref, _} = tref, metatable | _], state) do # Check for __metatable protection on existing metatable table = State.get_table(state, tref) @@ -599,6 +616,10 @@ defmodule Lua.VM.Stdlib do end end + defp lua_setmetatable([{:tref, _}], _state) do + raise ArgumentError, function_name: "setmetatable", arg_num: 2, expected: "nil or table" + end + defp lua_setmetatable([non_table | _], _state) do raise ArgumentError, function_name: "setmetatable", @@ -642,8 +663,8 @@ defmodule Lua.VM.Stdlib do {[nil], state} end - defp lua_getmetatable([], state) do - {[nil], state} + defp lua_getmetatable([], _state) do + raise ArgumentError.value_expected("getmetatable", 1) end # Install package table with loaded and path fields diff --git a/lib/lua/vm/stdlib/os.ex b/lib/lua/vm/stdlib/os.ex index 65ee0c8..964c7c9 100644 --- a/lib/lua/vm/stdlib/os.ex +++ b/lib/lua/vm/stdlib/os.ex @@ -227,7 +227,10 @@ defmodule Lua.VM.Stdlib.Os do # treated as identical. The utc? flag is parsed for compatibility with # the leading '!' but does not change the result. defp to_datetime(time, _utc?) do - DateTime.from_unix!(time, :second) + case DateTime.from_unix(time, :second) do + {:ok, datetime} -> datetime + {:error, _reason} -> raise RuntimeError, value: "time result cannot be represented in this installation" + end end defp date_table(%DateTime{} = dt, state) do diff --git a/test/lua/pcall_host_error_test.exs b/test/lua/pcall_host_error_test.exs new file mode 100644 index 0000000..ab06b22 --- /dev/null +++ b/test/lua/pcall_host_error_test.exs @@ -0,0 +1,88 @@ +defmodule Lua.PcallHostErrorTest do + use ExUnit.Case, async: true + + @host_error_message "error in host function" + + defmodule HostAPI do + @moduledoc false + use Lua.API, scope: "host" + + deflua match_error() do + {:ok, _} = Process.get(:unset_host_value, {:error, "secret-token"}) + end + + deflua function_clause(value) do + String.upcase(value) + end + + deflua argument_error(id) do + raise ArgumentError, "employee #{id} not found in tenant acme" + end + + deflua deliberate() do + runtime_exception!("employee not found") + end + + deflua error_tuple() do + {:error, "employee not found"} + end + + deflua call_back(callback), state do + Lua.call_function!(state, callback, []) + end + end + + defp eval!(code), do: Lua.new() |> Lua.load_api(HostAPI) |> Lua.eval!(code) |> elem(0) + + describe "pcall over a host exception" do + for call <- ["host.match_error()", "host.function_clause(42)", "host.argument_error(7)"] do + test "#{call} reaches the script as the generic message" do + assert [false, @host_error_message] = eval!("return pcall(function() return #{unquote(call)} end)") + end + end + + test "an xpcall message handler receives the generic message" do + assert [false, "handled: " <> @host_error_message] = + eval!(~S[return xpcall(host.match_error, function(message) return "handled: " .. message end)]) + end + + test "a host exception wrapped by a nested Lua.call_function! stays hidden" do + assert [false, @host_error_message] = + eval!("return pcall(host.call_back, function() return host.match_error() end)") + end + + test "a Lua.set!/3 function returning unencoded data reaches the script as the generic message" do + lua = Lua.set!(Lua.new(), [:lookup], fn [_id] -> {:error, "secret-token"} end) + + assert {[false, @host_error_message], _} = Lua.eval!(lua, ~s|return pcall(lookup, "employee-42")|) + end + end + + describe "uncaught host exception" do + test "still reaches the host on :original" do + lua = Lua.load_api(Lua.new(), HostAPI) + + exception = assert_raise Lua.RuntimeException, fn -> Lua.eval!(lua, "return host.match_error()") end + + assert %MatchError{term: {:error, "secret-token"}} = exception.original + assert exception.kind == nil + end + end + + describe "errors raised for the script" do + test "runtime_exception!/1 reaches pcall unchanged" do + assert [false, "Lua runtime error: host.deliberate() failed, employee not found"] = + eval!("return pcall(host.deliberate)") + end + + test "an {:error, reason} return reaches pcall unchanged" do + assert [false, "employee not found"] = eval!("return pcall(host.error_tuple)") + end + + test "a Lua error raised through a nested Lua.call_function! reaches pcall" do + assert [false, error_value] = eval!(~S[return pcall(host.call_back, function() error("boom", 0) end)]) + + assert error_value =~ "boom" + end + end +end diff --git a/test/lua/vm/stdlib/base_arguments_test.exs b/test/lua/vm/stdlib/base_arguments_test.exs new file mode 100644 index 0000000..0c6f840 --- /dev/null +++ b/test/lua/vm/stdlib/base_arguments_test.exs @@ -0,0 +1,33 @@ +defmodule Lua.VM.Stdlib.BaseArgumentsTest do + use ExUnit.Case, async: true + + for {call, message} <- [ + {"rawset(1, 2, 3)", "bad argument #1 to 'rawset' (table expected, got number)"}, + {"rawset({}, 1)", "bad argument #3 to 'rawset' (value expected)"}, + {"rawget('x', 1)", "bad argument #1 to 'rawget' (table expected, got string)"}, + {"rawget({})", "bad argument #2 to 'rawget' (value expected)"}, + {"rawequal(1)", "bad argument #2 to 'rawequal' (value expected)"}, + {"setmetatable({})", "bad argument #2 to 'setmetatable' (nil or table expected)"}, + {"getmetatable()", "bad argument #1 to 'getmetatable' (value expected)"}, + {"next(1)", "bad argument #1 to 'next' (table expected, got number)"}, + {"tostring()", "bad argument #1 to 'tostring' (value expected)"}, + {"tonumber()", "bad argument #1 to 'tonumber' (value expected)"}, + {"tonumber(10, 16)", "bad argument #1 to 'tonumber' (string expected, got number)"}, + {"tonumber('10', 99)", "bad argument #2 to 'tonumber' (base out of range)"}, + {"tonumber('10', 1.5)", "bad argument #2 to 'tonumber' (number has no integer representation)"}, + {"select(1.5, 'a')", "bad argument #1 to 'select' (number has no integer representation)"}, + {"select(-2, 'a')", "bad argument #1 to 'select' (index out of range)"} + ] do + test "#{call} raises #{message}" do + assert {[false, unquote(message)], _} = Lua.eval!("return pcall(function() return #{unquote(call)} end)") + end + end + + test "setmetatable ignores arguments past the metatable" do + assert {[true], _} = Lua.eval!("local t = {} return setmetatable(t, {}, 'extra') == t") + end + + test "select accepts a float with an integer value as the index" do + assert {["b"], _} = Lua.eval!("return select(2.0, 'a', 'b')") + end +end diff --git a/test/lua/vm/stdlib/os_test.exs b/test/lua/vm/stdlib/os_test.exs index 954f580..279eb4c 100644 --- a/test/lua/vm/stdlib/os_test.exs +++ b/test/lua/vm/stdlib/os_test.exs @@ -25,6 +25,11 @@ defmodule Lua.VM.Stdlib.OsTest do assert t == 946_684_800 end + test "os.date rejects a time past the representable range" do + assert {[false, "time result cannot be represented in this installation"], _} = + Lua.eval!(~S[return pcall(os.date, "%Y", 2^60)]) + end + test "os.time_ms returns the current epoch in milliseconds" do {[t], _} = Lua.eval!("return os.time_ms()") assert is_integer(t)