18
0
mirror of https://github.com/MaSzyna-EU07/maszyna.git synced 2026-11-27 21:45:16 +01:00

fix(scripting): gsub with a metatable'd table, the trim idiom, the memory doc

- replacement_length() popped nothing after lua_getmetatable() pushed a metatable, so gsub got it
  as its 4th argument ("bad argument #4 to 'gsub'"); it is popped now.
- lua_pattern_cost(): a repetition followed by what always matches (as the first %s* of
  "^%s*(.-)%s*$") is tried once and doesn't multiply; a repetition of a character or a %class
  right before the final '$' counts the longest run of it in the subject, not the subject. The
  trim of a 10 KB line of words is allowed, a long run of spaces is still refused (it takes the
  square of the run). The doc names a trim that is linear on any string.
- the doc says every concatenation within one hook interval is made whole before the memory check.
This commit is contained in:
jerrrrycho
2026-11-17 09:10:08 +01:00
parent 8201ccb3b0
commit 178f5b63fe
6 changed files with 267 additions and 56 deletions

View File

@@ -146,8 +146,10 @@ Besides the 200 million instructions of a call, a Lua screen is held to what run
exceeded`), and a screen found holding more stops with that error. Garbage doesn't count: the check collects it
first. Where LuaJIT takes an allocator of the game's (2.1 in its GC64 mode), anything over twice the limit is refused
as it is asked for (`not enough memory`); the game's LuaJIT 2.0 on 64-bit Windows takes none, and there the heap is
checked every thousand instructions and before the calls below, but a single concatenation (`a .. b`) of large
strings is made whole first;
checked every thousand instructions and before the calls below, and whatever a script makes between two checks is
made whole first: every concatenation (`a .. b`) within one interval of a thousand instructions, so a loop doubling a
string (`for i = 1, 11 do s = s .. s end` on a 1 MB `s`) gets to LuaJIT's own heap limit of about 2 GB before the
check sees it;
- `string.rep` makes no string over 1 MB; `string.format`, `table.concat` and `string.gsub` (with a string or a table to
replace with) refuse a result that may be over the memory of a screen, counted from the lengths of what they are
given;
@@ -155,12 +157,23 @@ Besides the 200 million instructions of a call, a Lua screen is held to what run
subject (`("a"):rep(1e6):find(".-b")`). A call is refused (`the pattern may take too long`) when the steps it may
take at worst are over 100 million, about a tenth of a second at worst: the length of the subject (plus one), times the
length of the pattern, times the subject again for each repetition (`*`, `+`, `-`, `%b`, a back reference `%1`) but
a last one that ends the pattern, times 2 for each `?`, and taken once rather than from every position for a pattern
anchored with `^` (not in `gmatch`). A plain search (`find` with `plain`, or a pattern of no special characters) is
the subject times the pattern. So a pattern ending in its only repetition (`"[^
]+"`, `"%d+"`) works on any subject,
one more repetition (`"(%w+)=(%w+)"`, `"%s+$"`) on some 3 000 to 5 000 bytes, and each further one divides that
a lot;
one followed by what always matches (nothing, as in a repetition that ends the pattern, or `(.-)%s*$`), times 2 for
each `?`, and taken once rather than from every position for a pattern anchored with `^` (not in `gmatch`). A
repetition of a character or a `%` class right before the final `$` (`%s*$`) counts the longest run of it in the
subject rather than the whole subject. A plain search (`find` with `plain`, or a pattern of no special characters) is
the subject times the pattern. So a pattern ending in its only repetition (`"[^\n]+"`, `"%d+"`) works on any subject,
one more repetition (`"(%w+)=(%w+)"`) on some 3 000 to 5 000 bytes, and each further one divides that a lot. The
usual trim, `s:match("^%s*(.-)%s*$")`, costs the line times its longest run of spaces: a line of words, even a
megabyte long, is fine, but a long run of spaces inside it is refused, since the trim really takes the square of that.
A trim that stays linear on any string:
```lua
local function trim(s)
local first = s:find("%S")
if not first then return "" end
return s:sub(first, #s - s:reverse():find("%S") + 1)
end
```
- `xpcall` is made of `pcall`: the handler gets the error once it has left the function, and a coroutine may yield
inside either. There is no `newproxy`, so no finalizer (`__gc`) of the script's own: LuaJIT runs those without the
instruction count;

View File

@@ -942,8 +942,14 @@ std::optional<double> replacement_length(lua_State *L, int const Index, double c
// the matches don't overlap: a capture of each takes at most the subject; a position capture is a number
return Matches * static_cast<double>(length) + captures * (Subject + 24.0 * Matches);
}
if (lua_type(L, Index) == LUA_TTABLE && 0 == lua_getmetatable(L, Index))
if (lua_type(L, Index) == LUA_TTABLE)
{
if (lua_getmetatable(L, Index) != 0)
{
// pushed: off the stack again, or the library gets it as the 4th argument
lua_pop(L, 1);
return std::nullopt;
}
auto longest{0.0};
lua_pushnil(L);
while (lua_next(L, Index) != 0)
@@ -964,11 +970,11 @@ int api_pattern(lua_State *L)
auto const function{static_cast<pattern_function>(lua_tointeger(L, lua_upvalueindex(2)))};
auto const *name{pattern_function_names[static_cast<std::size_t>(function)]};
std::size_t subject{0};
luaL_checklstring(L, 1, &subject);
auto const *text{luaL_checklstring(L, 1, &subject)};
std::size_t length{0};
auto const *pattern{luaL_checklstring(L, 2, &length)};
auto const plain{function == pattern_function::find && lua_toboolean(L, 4) != 0};
if (lua_pattern_cost({pattern, length}, subject, plain, function != pattern_function::gmatch) > max_pattern_cost)
if (lua_pattern_cost(std::string_view{pattern, length}, std::string_view{text, subject}, plain, function != pattern_function::gmatch) > max_pattern_cost)
{
return luaL_error(L, "%s: the pattern may take too long on a subject of %d bytes", name, static_cast<int>(subject));
}

View File

@@ -13,7 +13,9 @@ http://mozilla.org/MPL/2.0/.
#include "utilities/parser.h"
#include <algorithm>
#include <cctype>
#include <cmath>
#include <vector>
namespace script_screens
{
@@ -161,55 +163,60 @@ std::size_t set_end(std::string_view const Pattern, std::size_t Start)
return idx + 1;
}
} // namespace
double lua_pattern_cost(std::string_view const Pattern, std::size_t const Subject, bool const Plain, bool const Anchorable)
// one item of a pattern, as Lua's matcher takes them
struct pattern_item
{
auto const length{static_cast<double>(std::max<std::size_t>(Pattern.size(), 1))};
auto const positions{static_cast<double>(Subject) + 1.0};
// LuaJIT searches plainly for a pattern without the special characters as well
if (Plain || Pattern.find_first_of("^$*+?.([%-") == std::string_view::npos)
enum class kind
{
return positions * length;
}
auto const anchored{Anchorable && Pattern.front() == '^'};
int repeats{0};
int optional{0};
// a repetition that ends the pattern doesn't multiply: past it the match is over
auto last_repeat{false};
std::size_t idx{anchored ? 1U : 0U};
single, // a character, '.', a %class or a [set], with its quantifier if any
paren, // '(' or ')': a capture costs nothing
scan, // %bxy or a back reference %1-%9: goes along the subject
frontier, // %f[set]: a test of one position
end_anchor // '$' that ends the pattern
};
kind type{kind::single};
std::size_t begin{0}; // of a single, without its quantifier
std::size_t end{0};
char quantifier{0}; // '*', '+', '-', '?' or none
};
std::vector<pattern_item> pattern_items(std::string_view const Pattern, std::size_t idx)
{
std::vector<pattern_item> items;
while (idx < Pattern.size())
{
auto const character{Pattern[idx]};
if (character == '(' || character == ')')
{
items.push_back({pattern_item::kind::paren, idx, idx + 1});
++idx;
// a ')' after the last repetition keeps it last
continue;
}
last_repeat = false;
if (character == '$' && idx + 1 == Pattern.size())
{
items.push_back({pattern_item::kind::end_anchor, idx, idx + 1});
break;
}
std::size_t end{idx + 1};
if (character == '%' && idx + 1 < Pattern.size())
{
auto const next{Pattern[idx + 1]};
if (next == 'b')
{
// %bxy goes along the subject to the balancing character
++repeats;
last_repeat = true;
items.push_back({pattern_item::kind::scan, idx, idx + 4});
idx += 4;
continue;
}
if (next == 'f')
{
idx = idx + 2 < Pattern.size() && Pattern[idx + 2] == '[' ? set_end(Pattern, idx + 2) : idx + 2;
auto const after{idx + 2 < Pattern.size() && Pattern[idx + 2] == '[' ? set_end(Pattern, idx + 2) : idx + 2};
items.push_back({pattern_item::kind::frontier, idx, after});
idx = after;
continue;
}
if (next >= '0' && next <= '9')
{
// a back reference compares the capture, as long as the subject
++repeats;
last_repeat = true;
items.push_back({pattern_item::kind::scan, idx, idx + 2});
idx += 2;
continue;
}
@@ -219,28 +226,135 @@ double lua_pattern_cost(std::string_view const Pattern, std::size_t const Subjec
{
end = set_end(Pattern, idx);
}
if (end < Pattern.size() && (Pattern[end] == '*' || Pattern[end] == '+' || Pattern[end] == '-'))
pattern_item item{pattern_item::kind::single, idx, end};
if (end < Pattern.size() && (Pattern[end] == '*' || Pattern[end] == '+' || Pattern[end] == '-' || Pattern[end] == '?'))
{
++repeats;
last_repeat = true;
idx = end + 1;
}
else if (end < Pattern.size() && Pattern[end] == '?')
{
++optional;
idx = end + 1;
}
else
{
idx = end;
item.quantifier = Pattern[end];
++end;
}
items.push_back(item);
idx = end;
}
if (last_repeat)
{
--repeats;
}
auto const starts{anchored ? 1.0 : positions};
return starts * std::pow(positions, repeats) * std::pow(2.0, optional) * length;
return items;
}
// when the rest of a pattern matches, once the matcher gets to it
enum class rest_match
{
always, // from any position: whatever comes before it is tried once
at_end, // at least at the end of the subject
maybe
};
rest_match match_with(std::string_view const Pattern, pattern_item const &Item, rest_match const Rest)
{
switch (Item.type)
{
case pattern_item::kind::paren:
return Rest;
case pattern_item::kind::end_anchor:
return rest_match::at_end;
case pattern_item::kind::single:
if (Item.quantifier == '*' || Item.quantifier == '-' || Item.quantifier == '?')
{
// matches nothing as well; '.' repeated goes on to the end of the subject
auto const dot{Item.quantifier != '?' && Item.end - Item.begin == 1 && Pattern[Item.begin] == '.'};
return dot && Rest == rest_match::at_end ? rest_match::always : Rest;
}
return rest_match::maybe;
default:
return rest_match::maybe;
}
}
// whether Character is in the %class Class, as Lua's match_class
bool in_class(unsigned char const Character, unsigned char const Class)
{
bool in{false};
switch (std::tolower(Class))
{
case 'a': in = std::isalpha(Character) != 0; break;
case 'c': in = std::iscntrl(Character) != 0; break;
case 'd': in = std::isdigit(Character) != 0; break;
case 'l': in = std::islower(Character) != 0; break;
case 'p': in = std::ispunct(Character) != 0; break;
case 's': in = std::isspace(Character) != 0; break;
case 'u': in = std::isupper(Character) != 0; break;
case 'w': in = std::isalnum(Character) != 0; break;
case 'x': in = std::isxdigit(Character) != 0; break;
case 'z': in = Character == 0; break;
default: return Class == Character;
}
return std::isupper(Class) != 0 ? !in : in;
}
// the longest run of the subject that the single item (a character, '.' or a %class) matches; the whole subject for a
// set, which isn't gone through here
std::size_t longest_run(std::string_view const Pattern, pattern_item const &Item, std::string_view const Subject)
{
auto const single{Pattern.substr(Item.begin, Item.end - Item.begin)};
if (single == "." || single.front() == '[')
{
return Subject.size();
}
std::size_t longest{0};
std::size_t run{0};
for (auto const character : Subject)
{
auto const c{static_cast<unsigned char>(character)};
auto const in{single.size() == 2 ? in_class(c, static_cast<unsigned char>(single[1])) : c == static_cast<unsigned char>(single[0])};
run = in ? run + 1 : 0;
longest = std::max(longest, run);
}
return longest;
}
double pattern_cost(std::string_view const Pattern, std::size_t const Size, std::string_view const *Subject, bool const Plain, bool const Anchorable)
{
auto const length{static_cast<double>(std::max<std::size_t>(Pattern.size(), 1))};
auto const positions{static_cast<double>(Size) + 1.0};
// LuaJIT searches plainly for a pattern without the special characters as well
if (Plain || Pattern.find_first_of("^$*+?.([%-") == std::string_view::npos)
{
return positions * length;
}
auto const anchored{Anchorable && Pattern.front() == '^'};
auto const items{pattern_items(Pattern, anchored ? 1U : 0U)};
auto cost{anchored ? 1.0 : positions};
// from the end: what follows each item, and whether that's only the end of the subject
auto rest{rest_match::always};
auto only_end{true};
for (auto item{items.rbegin()}; item != items.rend(); ++item)
{
if (item->type == pattern_item::kind::single && item->quantifier == '?')
{
cost *= 2.0;
}
auto const repeated{item->type == pattern_item::kind::scan
|| (item->type == pattern_item::kind::single && item->quantifier != 0 && item->quantifier != '?')};
// a repetition followed by what always matches is tried once (as one that ends the pattern): past it the match
// is over. otherwise the rest is tried at each length it takes, as many as the subject has positions; before
// '$' alone, as many as its longest run in the subject, past which it stops
if (repeated && rest != rest_match::always)
{
auto const before_end{only_end && rest == rest_match::at_end && item->type == pattern_item::kind::single};
cost *= before_end && Subject != nullptr ? static_cast<double>(longest_run(Pattern, *item, *Subject)) + 1.0 : positions;
}
only_end = only_end && (item->type == pattern_item::kind::paren || item->type == pattern_item::kind::end_anchor);
rest = match_with(Pattern, *item, rest);
}
return cost * length;
}
} // namespace
double lua_pattern_cost(std::string_view const Pattern, std::size_t const Subject, bool const Plain, bool const Anchorable)
{
return pattern_cost(Pattern, Subject, nullptr, Plain, Anchorable);
}
double lua_pattern_cost(std::string_view const Pattern, std::string_view const Subject, bool const Plain, bool const Anchorable)
{
return pattern_cost(Pattern, Subject.size(), &Subject, Plain, Anchorable);
}
} // namespace script_screens

View File

@@ -88,9 +88,15 @@ constexpr double max_pattern_cost{1e8};
// - a plain search (string.find with plain set, or a pattern without special characters): Subject x m;
// - a pattern: tried from every position of the subject (Subject + 1), or from the first only when Anchored (it starts
// with '^', and the function anchors: find, match, gsub, not gmatch), times (Subject + 1) for each repetition ('*',
// '+', '-', %b, a back reference %1-%9) but a last one (followed by nothing but ')', which ends the match where it
// stops), times 2 for each '?', times m for the work of each step (a set is gone through item by item)
// '+', '-', %b, a back reference %1-%9) but one followed by what always matches (nothing, ')', a repetition with '*'
// or '-' or a '?' of what always matches, '.*' / '.-' before '$'), where the match is over: so neither the last
// repetition nor the first %s* of "^%s*(.-)%s*$" multiplies. times 2 for each '?', times m for the work of each step
// (a set is gone through item by item)
// a malformed pattern costs nothing here: the function raises its error itself
double lua_pattern_cost(std::string_view Pattern, std::size_t Subject, bool Plain, bool Anchorable);
// as above, on the subject itself: a repetition of a character or a %class right before the final '$' ("%s*$") counts
// as many times as the longest run of it in the subject (plus one), not the whole subject: past that run it fails or
// gets to the end, so the trim "^%s*(.-)%s*$" costs about the subject times its longest run of spaces
double lua_pattern_cost(std::string_view Pattern, std::string_view Subject, bool Plain, bool Anchorable);
} // namespace script_screens

View File

@@ -1209,6 +1209,30 @@ return {
}
)"};
// white when gsub takes a table with a metatable as Lua does (the metatable doesn't get to the library as an argument),
// and a line is trimmed: with the usual idiom on a long line of words, without a pattern on a long run of spaces
constexpr std::string_view gsub_metatable_trim_script{R"(
local upper = setmetatable({}, { __index = function(_, k) return k:upper() end })
local replaced, count = ("one two"):gsub("%w+", upper)
local line = ("word next\tone "):rep(700)
local trimmed = (" " .. line .. " "):match("^%s*(.-)%s*$")
local ok, message = pcall(string.match, "x" .. (" "):rep(1000000) .. "x", "^%s*(.-)%s*$")
local refused = not ok and message:find("may take too long", 1, true) ~= nil
local function trim(s)
local first = s:find("%S")
if not first then return "" end
return s:sub(first, #s - s:reverse():find("%S") + 1)
end
local spaced = trim(" x" .. (" "):rep(1000000) .. "x ")
local good = replaced == "ONE TWO" and count == 2 and trimmed == line:sub(1, -2) and refused
and #spaced == 1000002 and trim(" ") == "" and trim(" a b ") == "a b"
return {
render = function(state)
return eu07.image(1, 1, good and { 255, 255, 255 } or { 0, 0, 0 })
end
}
)"};
// white when the images a screen holds are held to its memory, and the images it dropped don't count
constexpr std::string_view image_memory_script{R"(
local kept = {}
@@ -1338,6 +1362,13 @@ TEST_CASE("lua screens: what makes a large string in one call is held to the mem
CHECK(first_pixel(folder.write("large.lua", large_result_script), "large") == 255);
}
TEST_CASE("lua screens: gsub with a table that has a metatable, and the trim of a long line") {
script_folder const folder{"lua_gsub_metatable_trim"};
auto const started{std::chrono::steady_clock::now()};
CHECK(first_pixel(folder.write("trim.lua", gsub_metatable_trim_script), "trim") == 255);
CHECK(std::chrono::steady_clock::now() - started < std::chrono::seconds(10));
}
TEST_CASE("lua screens: the images a screen holds are held to its memory") {
script_folder const folder{"lua_image_memory"};
CHECK(first_pixel(folder.write("images.lua", image_memory_script), "images") == 255);

View File

@@ -159,3 +159,44 @@ TEST_CASE("script screens: the steps a Lua pattern function may take at worst")
}
CHECK(lua_pattern_cost(optional + std::string(30, 'a'), 100, false, true) > max_pattern_cost);
}
TEST_CASE("script screens: a repetition followed by what always matches doesn't multiply") {
using script_screens::lua_pattern_cost;
// the first %s* of the trim: past it, (.-)%s*$ matches from wherever it stopped, so it's tried once
CHECK(lua_pattern_cost("^%s*(.-)%s*$", 999, false, true) == doctest::Approx(1000.0 * 1000 * 12));
CHECK(lua_pattern_cost("^%s*(.*)", 999, false, true) == doctest::Approx(8.0));
CHECK(lua_pattern_cost("a*.-$", 999, false, true) == doctest::Approx(1000.0 * 1000 * 5));
// what may not match still multiplies
CHECK(lua_pattern_cost("^%s*(.*%S)", 999, false, true) == doctest::Approx(1000.0 * 1000 * 10));
CHECK(lua_pattern_cost("^%s*x%s*$", 999, false, true) == doctest::Approx(1000.0 * 1000 * 9));
// '$' is the end only at the end of the pattern
CHECK(lua_pattern_cost("a*$b", 999, false, true) == doctest::Approx(1000.0 * 1000 * 4));
}
TEST_CASE("script screens: a repetition right before the final $ counts its longest run in the subject") {
using script_screens::lua_pattern_cost;
using script_screens::max_pattern_cost;
std::string words;
while (words.size() < 10'000) {
words += "word next\tone ";
}
// a line of 10 KB trimmed: the subject times the longest run of spaces (2), where the length alone gives the
// subject squared
CHECK(lua_pattern_cost("^%s*(.-)%s*$", std::string_view{words}, false, true) == doctest::Approx((words.size() + 1.0) * 3 * 12));
CHECK(lua_pattern_cost("^%s*(.-)%s*$", std::string_view{words}, false, true) < max_pattern_cost);
CHECK(lua_pattern_cost("^%s*(.-)%s*$", words.size(), false, true) > max_pattern_cost);
CHECK(lua_pattern_cost("%s+$", std::string_view{words}, false, true) < max_pattern_cost);
CHECK(lua_pattern_cost("%d*$", std::string_view{words}, false, true) == doctest::Approx((words.size() + 1.0) * 1 * 4));
CHECK(lua_pattern_cost("x*$", std::string_view{"axxxa"}, false, true) == doctest::Approx(6.0 * 4 * 3));
CHECK(lua_pattern_cost("%%*$", std::string_view{"a%%%a"}, false, true) == doctest::Approx(6.0 * 4 * 4));
// a long run is still the subject squared: "x", 10 000 spaces, "x" takes the trim about 10^8 steps, and a
// megabyte of them hours
auto const spaces{"x" + std::string(10'000, ' ') + "x"};
CHECK(lua_pattern_cost("^%s*(.-)%s*$", std::string_view{spaces}, false, true) > max_pattern_cost);
auto const megabyte{"x" + std::string(1'000'000, ' ') + "x"};
CHECK(lua_pattern_cost("^%s*(.-)%s*$", std::string_view{megabyte}, false, true) > max_pattern_cost);
CHECK(lua_pattern_cost("%s*$", std::string_view{megabyte}, false, true) > max_pattern_cost);
// a set or '.' isn't gone through: the whole subject
CHECK(lua_pattern_cost("[ ]*$", std::string_view{words}, false, true) == doctest::Approx((words.size() + 1.0) * (words.size() + 1.0) * 5));
CHECK(lua_pattern_cost(".-b", std::string(1'000'000, 'a'), false, true) > max_pattern_cost);
}