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
10 changes: 10 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,16 @@ 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).
- `:max_string_bytes` is now also enforced by `print`, `string.char`,
`utf8.char` and `debug.traceback`. `print` previously joined all of its
arguments into one string with no check, so a script could make a write far
larger than the ceiling; it now raises `"resulting string too large"` before
anything is written. The documentation of the option now says which strings
it does not bound: the `error/2` position prefix, and the one conversion
piece `string.format` is building when it refuses.
- `string.format` reports a bad argument or invalid conversion with its own
error again when `:max_string_bytes` is smaller than the conversion's width,
instead of `"resulting string too large"`.

## [1.0.2] - 2026-07-28

Expand Down
15 changes: 12 additions & 3 deletions lib/lua.ex
Original file line number Diff line number Diff line change
Expand Up @@ -102,13 +102,22 @@ defmodule Lua do
iex> message =~ "stack overflow"
true

* `:max_string_bytes` - (default 256 MiB) ceiling for any single string the VM will build,
whether via `..`, `string.rep`, `string.format`, `string.gsub`, `string.pack`,
`table.concat`, `os.date`, or a `load` reader. An oversized result raises a catchable
* `:max_string_bytes` - (default 256 MiB) ceiling for the strings the VM builds from
other values, whether via `..`, `string.rep`, `string.format`, `string.gsub`,
`string.pack`, `string.char`, `utf8.char`, `table.concat`, `debug.traceback`,
`os.date`, or a `load` reader, and for the line `print` writes. An oversized result raises a catchable
`"resulting string too large"` error — the size is computed *before* allocating, so the
bomb is refused rather than detected after the fact. Accepts a positive integer or
`:infinity` for no limit (matching `:max_call_depth` and `:max_instructions`).

The ceiling is not a cap on every string a script can hold. A string a script already
has is never re-checked, and a string that is only a message may go past it by a
bounded amount: `error/2` with a string message prepends a `source:line: ` position
prefix (the length of the chunk name plus a few bytes) to a message that was itself
already within the ceiling, and `string.format` builds the one conversion piece it is
working on (at most 99 bytes of padding, or one escaped `%q` argument) before it
refuses. Neither grows with the number of arguments or frames.

When running the VM inside a process capped with `:max_heap_size`, set this comfortably
below the heap cap: the default ceiling permits strings large enough to trip a smaller
heap cap mid-allocation, where the kill depends on garbage-collection timing rather than
Expand Down
14 changes: 9 additions & 5 deletions lib/lua/vm/stdlib.ex
Original file line number Diff line number Diff line change
Expand Up @@ -167,14 +167,18 @@ defmodule Lua.VM.Stdlib do

# print(...) — prints values separated by tabs, followed by a newline
defp lua_print(args, state) do
{strings, state} =
Enum.reduce(args, {[], state}, fn val, {acc, st} ->
{strings, _size, state} =
Enum.reduce(args, {[], -1, state}, fn val, {acc, size, st} ->
{str, st} = value_to_string_with_mt(val, st)
{[str | acc], st}

# `size` starts at -1 so the tab before every piece but the first is
# counted; the check runs before the line is assembled.
size = size + 1 + byte_size(str)
Limits.check_string_size!(size, st.max_string_bytes, st)
{[str | acc], size, st}
end)

output = strings |> Enum.reverse() |> Enum.join("\t")
IO.puts(output)
strings |> Enum.reverse() |> Enum.intersperse("\t") |> IO.puts()
{[], state}
end

Expand Down
33 changes: 19 additions & 14 deletions lib/lua/vm/stdlib/debug.ex
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ defmodule Lua.VM.Stdlib.Debug do
@behaviour Lua.VM.Stdlib.Library

alias Lua.VM.Executor
alias Lua.VM.Limits
alias Lua.VM.State
alias Lua.VM.Value

Expand Down Expand Up @@ -168,26 +169,30 @@ defmodule Lua.VM.Stdlib.Debug do
message = List.first(args)
_level = Enum.at(args, 1, 1)

traceback =
state.call_stack
|> Enum.with_index(1)
|> Enum.map(fn {frame, _i} ->
source = Executor.frame_source(frame) || "?"
line = Executor.frame_line(frame) || 0
"\t#{source}:#{line}: in ?"
end)

header = "stack traceback:"
body = Enum.join([header | traceback], "\n")

result =
prefix =
if message do
"#{Value.to_string(message)}\n#{body}"
"#{Value.to_string(message)}\n#{header}"
else
body
header
end

{[result], state}
# A deep stack makes a long traceback, so the size is tracked per frame
# and the walk refuses as soon as it passes the ceiling.
Limits.check_string_size!(byte_size(prefix), state.max_string_bytes, state)

{lines, _size} =
Enum.reduce(state.call_stack, {[prefix], byte_size(prefix)}, fn frame, {acc, size} ->
source = Executor.frame_source(frame) || "?"
line = Executor.frame_line(frame) || 0
entry = "\n\t#{source}:#{line}: in ?"
size = size + byte_size(entry)
Limits.check_string_size!(size, state.max_string_bytes, state)
{[entry | acc], size}
end)

{[lines |> Enum.reverse() |> IO.iodata_to_binary()], state}
end

# debug.getmetatable(obj) — returns metatable bypassing __metatable protection
Expand Down
34 changes: 17 additions & 17 deletions lib/lua/vm/stdlib/string.ex
Original file line number Diff line number Diff line change
Expand Up @@ -296,21 +296,27 @@ defmodule Lua.VM.Stdlib.String do

# string.char(...) - converts byte values to characters
defp string_char(args, state) do
# Every argument is one byte, so the result's size is the argument count.
# Validate first (a bad argument keeps its own error), then refuse an
# oversized result before building it.
result =
args
|> Enum.with_index(1)
|> Enum.reduce_while("", fn {arg, idx}, acc ->
|> Enum.find_value(fn {arg, idx} ->
cond do
not is_integer(arg) ->
{:halt, {:error, idx, "number expected"}}

arg < 0 or arg > 255 ->
{:halt, {:error, idx, "value out of range"}}

true ->
{:cont, acc <> <<arg>>}
not is_integer(arg) -> {:error, idx, "number expected"}
arg < 0 or arg > 255 -> {:error, idx, "value out of range"}
true -> nil
end
end)
|> case do
nil ->
Limits.check_string_size!(length(args), state.max_string_bytes, state)
:erlang.list_to_binary(args)

error ->
error
end

case result do
{:error, arg_num, "number expected"} ->
Expand Down Expand Up @@ -424,8 +430,8 @@ defmodule Lua.VM.Stdlib.String do
# ceiling, not after the rest of it has been built. A conversion that makes
# a fresh binary (width padding, a large `%f`, `%q` escaping) is held in the
# iolist until the flatten, so the check must come before the next piece is
# built. A padded field is at least `width` bytes, which is known before
# anything is built, so `%99s` is refused without making the padding.
# built. One piece (at most 99 bytes of padding, or an escaped `%q`
# argument) can still be built before the call is refused.
defp render_format([], _args, acc, _argn, _size, _max_bytes) do
IO.iodata_to_binary(acc)
end
Expand All @@ -444,7 +450,6 @@ defmodule Lua.VM.Stdlib.String do
end

defp render_format([{:spec, spec} | rest], [arg | remaining_args], acc, argn, size, max_bytes) do
Limits.check_string_size!(size + padded_width(spec), max_bytes)
piece = apply_format_spec(spec, arg)
size = size + piece_size(piece)
Limits.check_string_size!(size, max_bytes)
Expand Down Expand Up @@ -563,11 +568,6 @@ defmodule Lua.VM.Stdlib.String do
# corrupt that literal, so %q never threads through the width/sign machinery
# (PUC-Lua likewise refuses to apply modifiers to %q). Every other conversion
# takes the padding pipeline below.
# Lower bound on a conversion's output from its width alone, known before the
# padding is built. %q ignores width, so it contributes nothing.
defp padded_width({_flags, _width, _precision, ?q}), do: 0
defp padded_width({_flags, width, _precision, _specifier}), do: width || 0

defp apply_format_spec({_flags, _width, _precision, ?q}, arg) do
format_quoted(arg)
end
Expand Down
14 changes: 10 additions & 4 deletions lib/lua/vm/stdlib/utf8.ex
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ defmodule Lua.VM.Stdlib.Utf8 do
import Bitwise

alias Lua.VM.ArgumentError
alias Lua.VM.Limits
alias Lua.VM.RuntimeError
alias Lua.VM.State
alias Lua.VM.Stdlib.Util
Expand Down Expand Up @@ -55,12 +56,17 @@ defmodule Lua.VM.Stdlib.Utf8 do
# ---------------------------------------------------------------------------

defp utf8_char(args, state) do
iolist =
{pieces, _size} =
args
|> Enum.with_index(1)
|> Enum.map(fn {cp, idx} -> encode_one(cp, idx) end)

{[IO.iodata_to_binary(iolist)], state}
|> Enum.reduce({[], 0}, fn {cp, idx}, {acc, size} ->
piece = encode_one(cp, idx)
size = size + byte_size(piece)
Limits.check_string_size!(size, state.max_string_bytes, state)
{[piece | acc], size}
end)

{[pieces |> Enum.reverse() |> IO.iodata_to_binary()], state}
end

defp encode_one(cp, idx) do
Expand Down
98 changes: 98 additions & 0 deletions test/lua/vm/builder_ceiling_test.exs
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
defmodule Lua.VM.BuilderCeilingTest do
@moduledoc """
Pins `max_string_bytes` on the builders that assemble a string from many
arguments or frames: `print`, `string.char`, `utf8.char` and
`debug.traceback`, plus the `string.format` error order under a ceiling
smaller than a conversion's width.
"""
use ExUnit.Case, async: true

import ExUnit.CaptureIO

defp eval_error(ceiling, code) do
lua = Lua.new(max_string_bytes: ceiling)

{[false, message], _} = Lua.eval!(lua, "return pcall(function() #{code} end)")
message
end

describe "print" do
test "refuses a line over the ceiling and writes nothing" do
code = ~s|local s = string.rep("x", 1024) local t = {} for i = 1, 64 do t[i] = s end print(table.unpack(t))|

output =
capture_io(fn ->
assert eval_error(2048, code) =~ "resulting string too large"
end)

assert output == ""
end

test "counts the tab separators" do
# "ab" and "cd" joined by a tab make a 5-byte line.
output = capture_io(fn -> Lua.eval!(Lua.new(max_string_bytes: 5), ~s|print("ab", "cd")|) end)
assert output == "ab\tcd\n"

capture_io(fn ->
assert eval_error(4, ~s|print("ab", "cd")|) =~ "resulting string too large"
end)
end

test "prints normally under the default ceiling" do
assert capture_io(fn -> Lua.eval!(Lua.new(), ~s|print("a", 1, nil)|) end) == "a\t1\tnil\n"
end
end

describe "string.char" do
test "refuses more bytes than the ceiling" do
code = "local t = {} for i = 1, 100 do t[i] = 65 end return string.char(table.unpack(t))"
assert eval_error(64, code) =~ "resulting string too large"
end

test "allows exactly the ceiling and keeps its own argument errors" do
lua = Lua.new(max_string_bytes: 3)
assert {["ABC"], _} = Lua.eval!(lua, "return string.char(65, 66, 67)")
assert eval_error(1, "return string.char(65, 66, 'x')") =~ "number expected"
end
end

describe "utf8.char" do
test "counts encoded bytes, not arguments" do
code = "local t = {} for i = 1, 100 do t[i] = 0x10FFFF end return utf8.char(table.unpack(t))"
assert eval_error(64, code) =~ "resulting string too large"
end

test "allows exactly the ceiling" do
lua = Lua.new(max_string_bytes: 8)
assert {[8], _} = Lua.eval!(lua, "return #utf8.char(0x10FFFF, 0x10FFFF)")
assert eval_error(7, "return utf8.char(0x10FFFF, 0x10FFFF)") =~ "resulting string too large"
end
end

describe "debug.traceback" do
test "counts the message and the frames" do
assert eval_error(64, ~s|return debug.traceback(string.rep("x", 64))|) =~ "resulting string too large"
end

test "refuses a deep stack before building the whole traceback" do
code = "local function f(n) if n == 0 then return debug.traceback() end return (f(n - 1)) end return f(2000)"
assert eval_error(4096, code) =~ "resulting string too large"
end

test "returns a short traceback under the default ceiling" do
assert {[tb], _} = Lua.eval!(Lua.new(), ~s|return debug.traceback("msg")|)
assert tb =~ "msg\nstack traceback:"
end
end

describe "string.format under a tiny ceiling" do
test "a bad argument reports its own error, not the size" do
assert eval_error(10, ~s|return string.format("%99d", "abc")|) =~ "number expected"
assert eval_error(10, ~s|return string.format("%99z", 1)|) =~ "invalid option"
end

test "a wide conversion is still refused" do
assert eval_error(10, ~s|return string.format("%99d", 1)|) =~ "resulting string too large"
end
end
end
Loading