From 8201ccb3b040d4b76247529f74e64b74d4cfd266 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Mon, 16 Nov 2026 08:54:29 +0100 Subject: [PATCH] fix(scripting): hold what runs without the hook in the Lua screens - no newproxy: LuaJIT runs a __gc without the hook, at any allocation and in lua_close, so a looping finalizer hung the worker. a table's __gc isn't run, ffi isn't opened: the screens have no finalizer of their own - render and init of the script's table are read inside the protected, counted call, as is the state table of a refresh: an __index that fails or loops switches the screen off instead of ending the program, and one that gives render works - string.find, match, gmatch and gsub are refused when the steps they may take at worst (script_screens::lua_pattern_cost) are over 1e8, about a tenth of a second of LuaJIT's backtracking - a screen holds at most 128 MB, its heap and the pixels of its images, fonts and sprites: the hook checks it with a full collection, the api reserves pixels before making them, and string.format, table.concat and string.gsub refuse a result over it from the lengths of their arguments. where LuaJIT takes an allocator of the game's (2.1 GC64) the heap gets one that refuses past twice the limit, which also stops a single large concatenation; LuaJIT 2.0 on x64 takes none - xpcall is made in Lua on top of pcall, so a coroutine yields across it - the limits go into limit_libraries(), apart from opening the libraries --- script_screens_doc.md | 30 ++ scripting/luaprogram.cpp | 492 +++++++++++++++++++++---- scripting/scriptscreenprogram.h | 11 + scripting/scriptscreenrules.cpp | 109 ++++++ scripting/scriptscreenrules.h | 15 + tests/unit/test_script_screen_host.cpp | 251 +++++++++++++ tests/unit/test_script_screens.cpp | 42 +++ 7 files changed, 886 insertions(+), 64 deletions(-) diff --git a/script_screens_doc.md b/script_screens_doc.md index 52ccc9ced..3919cda7d 100644 --- a/script_screens_doc.md +++ b/script_screens_doc.md @@ -137,6 +137,36 @@ used: - on the cpu, in the screens' worker, when the renderer can't do it on the gpu (the NVRHI renderer, OpenGL ES, a shader that failed to load) or `screens.gpupost` is 0. A shader that fails is logged once, and the cpu takes over. +### Limits of a Lua script + +Besides the 200 million instructions of a call, a Lua screen is held to what runs in C, where the count doesn't reach: + +- memory: a screen holds at most 128 MB: its Lua heap and the pixels of its images, fonts and sprites (4 bytes a pixel + of an image, 1 of a font or a sprite). An object that would take the screen over is refused (`memory limit + 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; +- `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; +- the pattern functions (`string.find`, `match`, `gmatch`, `gsub`) backtrack, and some patterns take hours on a long + 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; +- `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; +- the game reads `render` and `init` of the script's table in protected mode, so a metatable of the script's + (`__index`) may provide them; one that fails or runs over switches the screen off. + ## WebAssembly modules A module exports: diff --git a/scripting/luaprogram.cpp b/scripting/luaprogram.cpp index 4e3c0eea4..9a5de6c9e 100644 --- a/scripting/luaprogram.cpp +++ b/scripting/luaprogram.cpp @@ -8,14 +8,18 @@ http://mozilla.org/MPL/2.0/. */ // the Lua screens: scripts run by LuaJIT, each screen in a state of its own, with the eu07 table of -// script_screens_doc.md. the state has no io, os, ffi, debug or require, reads files only through eu07 and below the -// script's folder, takes no precompiled code, and runs without the JIT compiler, so that the instruction count hook -// can stop a script stuck in a loop (LuaJIT calls no hooks in compiled code) +// script_screens_doc.md. the state has no io, os, ffi, debug, require or newproxy, reads files only through eu07 and +// below the script's folder, takes no precompiled code, and runs without the JIT compiler, so that the instruction +// count hook can stop a script stuck in a loop (LuaJIT calls no hooks in compiled code). what runs in C without the +// hook is held to limits of its own: the pattern functions to the steps they may take, what makes large strings and +// images to the memory of the screen. the game reads the script's table in protected mode, as its metamethods may +// fail #include "stdafx.h" #include "scripting/scriptscreenprogram.h" #include "scripting/scriptscreendrawing.h" #include "scripting/scriptscreenkernels.h" +#include "scripting/scriptscreenrules.h" #include "utilities/Logs.h" #include "utilities/dictionary.h" @@ -27,9 +31,11 @@ http://mozilla.org/MPL/2.0/. #include #include +#include #include #include #include +#include #include #include #include @@ -50,6 +56,47 @@ constexpr char sprite_metatable[]{"eu07.sprite"}; // the address is the key of the program in the registry of its state constexpr char program_key{0}; +// the memory of a screen: what its Lua heap holds, when the allocator counts it, and the pixels of its images, fonts +// and sprites, which the objects keep outside the heap +struct screen_memory +{ + std::size_t heap{0}; + std::size_t objects{0}; + bool counted{false}; // the state was made with limited_alloc + bool enforced{false}; // a call into the script is in progress: the allocator refuses what goes over the limit + // what the screen holds when it is checked next (lua_program::over_memory) with a full collection + std::size_t collect_at{max_screen_memory}; +}; + +// the allocator of a screen's state (lua_newstate), which refuses a block that would take the screen over twice +// max_screen_memory (what it holds, and its garbage between the collections) while a call into the script is in +// progress: LuaJIT raises "not enough memory" there, in the protected call. the game's own work between the calls isn't +// refused, as it isn't protected +void *limited_alloc(void *Data, void *Block, std::size_t Old, std::size_t New) +{ + auto &memory{*static_cast(Data)}; + if (Block == nullptr) + { + Old = 0; + } + if (New == 0) + { + std::free(Block); + memory.heap -= Old; + return nullptr; + } + if (New > Old && memory.enforced && memory.heap - Old + New + memory.objects > 2 * max_screen_memory) + { + return nullptr; + } + auto *result{std::realloc(Block, New)}; + if (result != nullptr) + { + memory.heap = memory.heap - Old + New; + } + return result; +} + class lua_program final : public program { public: @@ -79,6 +126,13 @@ class lua_program final : public program bool commands_ignored{false}; // a screen outside the cab tried to send a command, and it was logged output_limits output; std::int64_t budget{0}; // instructions left to the call in progress + char const *stopped{nullptr}; // why the call in progress is being stopped: the hook raises it at every instruction + screen_memory memory; + + // true when the screen would hold more than max_screen_memory with Adding bytes more. checked with a full collection + // once it has made a quarter of the limit since the last one, so a screen near its limit isn't collected over and + // over + bool over_memory(lua_State *L, std::size_t Adding); private: // calls what's on the stack, with the instruction limit. logs a failure @@ -99,6 +153,24 @@ lua_program *program_of(lua_State *L) return self; } +bool lua_program::over_memory(lua_State *L, std::size_t const Adding) +{ + auto const used{[this, L] { + auto const heap{memory.counted ? memory.heap + : static_cast(lua_gc(L, LUA_GCCOUNT, 0)) * 1024 + static_cast(lua_gc(L, LUA_GCCOUNTB, 0))}; + return heap + memory.objects; + }}; + if (used() + Adding <= memory.collect_at) + { + return false; + } + // what is garbage doesn't count + lua_gc(L, LUA_GCCOLLECT, 0); + auto const held{used()}; + memory.collect_at = std::max(max_screen_memory, held + max_screen_memory / 4); + return held + Adding > max_screen_memory; +} + void count_hook(lua_State *L, lua_Debug * /*Debug*/) { auto *self{program_of(L)}; @@ -106,27 +178,58 @@ void count_hook(lua_State *L, lua_Debug * /*Debug*/) { return; } - self->budget -= hook_interval; - if (self->budget < 0) + if (self->stopped == nullptr) + { + self->budget -= hook_interval; + if (self->budget < 0) + { + self->stopped = "instruction limit exceeded"; + } + else if (self->over_memory(L, 0)) + { + // what the allocator doesn't refuse (where the screen has none of its own) is caught here + self->stopped = "memory limit exceeded"; + } + } + if (self->stopped != nullptr) { // from now on the hook runs at every instruction, and raises the error again. a script that catches it (pcall, // xpcall, coroutine.resume) gets it again at its next instruction, so the error comes out of every level of the // script in turn, and the call ends. run() sets the interval back for the next call. the hook is the state's, // shared by its coroutines lua_sethook(L, count_hook, LUA_MASKCOUNT, 1); - luaL_error(L, "instruction limit exceeded"); + luaL_error(L, "%s", self->stopped); + } +} + +// raises a Lua error when the screen can't take Bytes more: called before an object of the api is made +void reserve_memory(lua_State *L, std::size_t const Bytes) +{ + if (auto *self{program_of(L)}; self != nullptr && self->over_memory(L, Bytes)) + { + luaL_error(L, "memory limit exceeded (%d MB)", static_cast(max_screen_memory / (1024 * 1024))); } } // objects of the api ------------------------------------------------------------------------------------------------- +// where the userdata of an object keeps the bytes it counts in the screen's memory, after the object +template constexpr std::size_t charge_offset{(sizeof(Type_) + alignof(std::size_t) - 1) / alignof(std::size_t) * alignof(std::size_t)}; + // puts the object in a new userdata with the metatable, left on the stack: an rvalue is moved in, an lvalue copied. -// what's stored is the plain type (no reference, no const), the one collect<> and check_object<> are given -template std::remove_cvref_t *push_object(lua_State *L, Type_ &&Object, char const *Metatable) +// what's stored is the plain type (no reference, no const), the one collect<> and check_object<> are given. Bytes: what +// the object holds outside the heap (its pixels), counted in the screen's memory until it is collected, and checked +// with reserve_memory() before the object was made +template std::remove_cvref_t *push_object(lua_State *L, Type_ &&Object, char const *Metatable, std::size_t const Bytes) { using object_type = std::remove_cvref_t; - auto *memory{lua_newuserdata(L, sizeof(object_type))}; + auto *memory{static_cast(lua_newuserdata(L, charge_offset + sizeof(std::size_t)))}; auto *object{new (memory) object_type(std::forward(Object))}; + std::memcpy(memory + charge_offset, &Bytes, sizeof(Bytes)); + if (auto *self{program_of(L)}; self != nullptr) + { + self->memory.objects += Bytes; + } luaL_getmetatable(L, Metatable); lua_setmetatable(L, -2); return object; @@ -152,9 +255,15 @@ template int collect(lua_State *L) { if (auto *object{test_object(L, 1, Metatable_)}; object != nullptr) { + std::size_t bytes{0}; + std::memcpy(&bytes, reinterpret_cast(object) + charge_offset, sizeof(bytes)); object->~Type_(); lua_pushnil(L); lua_setmetatable(L, 1); + if (auto *self{program_of(L)}; self != nullptr) + { + self->memory.objects -= std::min(bytes, self->memory.objects); + } } return 0; } @@ -217,6 +326,28 @@ struct lua_image } }; +// the pixels an image holds: as drawn, and as its post-processing leaves it +std::size_t image_bytes(int const Width, int const Height, int const Finalwidth, int const Finalheight) +{ + auto const drawn{static_cast(Width) * static_cast(Height)}; + auto const done{Width == Finalwidth && Height == Finalheight ? 0 : static_cast(Finalwidth) * static_cast(Finalheight)}; + return (drawn + done) * 4; +} + +std::size_t image_bytes(lua_image const &Image) +{ + return image_bytes(Image.drawn.width(), Image.drawn.height(), Image.width(), Image.height()); +} + +// a new image, Image a step further, counted in the screen's memory +void push_image_then(lua_State *L, lua_image const &Image, post_step const &Step) +{ + reserve_memory(L, image_bytes(Image.drawn.width(), Image.drawn.height(), width_after(Step, Image.width()), height_after(Step, Image.height()))); + auto next{Image.then(Step)}; + auto const bytes{image_bytes(next)}; + push_object(L, std::move(next), image_metatable, bytes); +} + lua_image &check_lua_image(lua_State *L, int const Index) { return check_object(L, Index, image_metatable); @@ -310,7 +441,9 @@ int api_image(lua_State *L) luaL_argcheck(L, valid_image_side(width), 1, "between 1 and 4096"); luaL_argcheck(L, valid_image_side(height), 2, "between 1 and 4096"); auto const color{lua_isnoneornil(L, 3) ? rgb{0, 0, 0} : check_color(L, 3)}; - push_object(L, lua_image{canvas{width, height, color}, {}}, image_metatable); + auto const bytes{image_bytes(width, height, width, height)}; + reserve_memory(L, bytes); + push_object(L, lua_image{canvas{width, height, color}, {}}, image_metatable, bytes); return 1; } @@ -325,9 +458,12 @@ int api_font(lua_State *L) auto const description{read_screen_file(self->folder, std::string{path} + ".txt")}; if (image.has_value() && description.has_value()) { + // the glyphs keep a bit of each pixel; a byte is counted + auto const bytes{static_cast(image->width) * static_cast(image->height)}; + reserve_memory(L, bytes); if (auto font{bitmap_font::parse(image->pixels, image->width, image->height, *description)}; font.has_value()) { - push_object(L, std::move(*font), font_metatable); + push_object(L, std::move(*font), font_metatable, bytes); loaded = true; } } @@ -348,7 +484,9 @@ int api_sprite(lua_State *L) { if (auto const image{read_png(self->folder, std::string{path} + ".png")}; image.has_value()) { - push_object(L, bitmap_font::sprite(image->pixels, image->width, image->height), sprite_metatable); + auto const bytes{static_cast(image->width) * static_cast(image->height)}; + reserve_memory(L, bytes); + push_object(L, bitmap_font::sprite(image->pixels, image->width, image->height), sprite_metatable, bytes); loaded = true; } } @@ -598,7 +736,7 @@ int image_led_post(lua_State *L) post_step step; step.type = post_step::kind::led; step.bloom = bloom; - push_object(L, image.then(step), image_metatable); + push_image_then(L, image, step); return 1; } @@ -614,14 +752,16 @@ int image_resize(lua_State *L) step.type = post_step::kind::resize; step.width = width; step.height = height; - push_object(L, image.then(step), image_metatable); + push_image_then(L, image, step); return 1; } int image_copy(lua_State *L) { auto const &image{check_lua_image(L, 1)}; - push_object(L, lua_image{image}, image_metatable); + auto const bytes{image_bytes(image)}; + reserve_memory(L, bytes); + push_object(L, lua_image{image}, image_metatable, bytes); return 1; } @@ -715,36 +855,198 @@ int api_repeat(lua_State *L) return 1; } -// xpcall(f, handler, ...). LuaJIT calls the handler where the error was raised, before the stack unwinds: for the error -// of the instruction hook that is while the hook still runs, when no hook is called, so a handler that loops would never -// be stopped. here f runs under pcall (the upvalue), and the handler is called, under pcall as well, once the error -// has left f. a script has no debug library to look at the stack with, so the handler gets what it got before -int api_xpcall(lua_State *L) +// the functions of the libraries that make a string in one call, around the library's own (the upvalue): refused when +// the result may be over the memory of a screen. what they make otherwise is counted with the rest of the heap +int too_large(lua_State *L, char const *Function) +{ + return luaL_error(L, "%s: the result may be over the memory of a screen (%d MB)", Function, static_cast(max_screen_memory / (1024 * 1024))); +} + +// calls the library's own function, the upvalue, with the arguments, and returns what it returns +int call_library(lua_State *L) { - auto const arguments{lua_gettop(L)}; - luaL_checkany(L, 2); lua_pushvalue(L, lua_upvalueindex(1)); - lua_pushvalue(L, 1); - for (int idx = 3; idx <= arguments; ++idx) + lua_insert(L, 1); + lua_call(L, lua_gettop(L) - 1, LUA_MULTRET); + return lua_gettop(L); +} + +// string.format: no longer than the format and its arguments, each string as %q writes it (a character as up to 4, +// "\0" as "\000"), anything else in at most 512 characters +int api_format(lua_State *L) +{ + std::size_t length{0}; + luaL_checklstring(L, 1, &length); + auto total{static_cast(length)}; + for (int idx = 2; idx <= lua_gettop(L); ++idx) { - lua_pushvalue(L, idx); + total += lua_type(L, idx) == LUA_TSTRING ? 4.0 * static_cast(lua_objlen(L, idx)) : 512.0; } - lua_call(L, arguments - 1, LUA_MULTRET); - if (lua_toboolean(L, arguments + 1) != 0) + if (total > static_cast(max_screen_memory)) { - // true and the results of f - return lua_gettop(L) - arguments; + return too_large(L, "string.format"); + } + return call_library(L); +} + +// table.concat: the items and the separators between them. the items are read as the library reads them, up to the +// first one that isn't a string or a number, on which the library raises its error +int api_concat(lua_State *L) +{ + luaL_checktype(L, 1, LUA_TTABLE); + std::size_t separator{0}; + luaL_optlstring(L, 2, "", &separator); + auto const first{luaL_optinteger(L, 3, 1)}; + auto const last{lua_isnoneornil(L, 4) ? static_cast(lua_objlen(L, 1)) : luaL_checkinteger(L, 4)}; + auto total{0.0}; + for (auto idx = first; idx <= last; ++idx) + { + lua_rawgeti(L, 1, static_cast(idx)); + auto const type{lua_type(L, -1)}; + // a number in at most 32 characters + total += (type == LUA_TSTRING ? static_cast(lua_objlen(L, -1)) : 32.0) + (idx > first ? static_cast(separator) : 0.0); + lua_pop(L, 1); + if (type != LUA_TSTRING && type != LUA_TNUMBER) + { + break; + } + if (total > static_cast(max_screen_memory)) + { + return too_large(L, "table.concat"); + } + } + return call_library(L); +} + +// the pattern functions, upvalue 2 telling which +enum class pattern_function +{ + find, + match, + gmatch, + gsub +}; + +constexpr std::array pattern_function_names{"string.find", "string.match", "string.gmatch", "string.gsub"}; + +// the longest text a replacement of gsub puts in place of the matches: a string (or a number) as it is, with each %0-%9 +// as long as a match, a table by its longest value. nothing when it can't be told (a function, a table with a +// metatable): what those give is made in Lua, under the hook +std::optional replacement_length(lua_State *L, int const Index, double const Subject, double const Matches) +{ + if (lua_type(L, Index) == LUA_TSTRING || lua_type(L, Index) == LUA_TNUMBER) + { + std::size_t length{0}; + auto const *text{lua_tolstring(L, Index, &length)}; + auto const captures{static_cast(std::count(text, text + length, '%'))}; + // the matches don't overlap: a capture of each takes at most the subject; a position capture is a number + return Matches * static_cast(length) + captures * (Subject + 24.0 * Matches); + } + if (lua_type(L, Index) == LUA_TTABLE && 0 == lua_getmetatable(L, Index)) + { + auto longest{0.0}; + lua_pushnil(L); + while (lua_next(L, Index) != 0) + { + longest = std::max(longest, lua_type(L, -1) == LUA_TSTRING ? static_cast(lua_objlen(L, -1)) : 32.0); + lua_pop(L, 1); + } + return Matches * longest; + } + return std::nullopt; +} + +// string.find, match, gmatch and gsub, refused for a pattern that may take too long on the subject: they run in C, +// without the instruction hook (see lua_pattern_cost() and max_pattern_cost). gsub with a string or a table is refused +// as well when its result may be over the memory of a screen +int api_pattern(lua_State *L) +{ + auto const function{static_cast(lua_tointeger(L, lua_upvalueindex(2)))}; + auto const *name{pattern_function_names[static_cast(function)]}; + std::size_t subject{0}; + 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) + { + return luaL_error(L, "%s: the pattern may take too long on a subject of %d bytes", name, static_cast(subject)); + } + if (function == pattern_function::gsub) + { + auto const size{static_cast(subject)}; + auto const matches{lua_isnumber(L, 4) ? std::clamp(static_cast(lua_tonumber(L, 4)), 0.0, size + 1.0) : size + 1.0}; + if (auto const replaced{replacement_length(L, 3, size, matches)}; replaced.has_value() && size + *replaced > static_cast(max_screen_memory)) + { + return too_large(L, name); + } + } + return call_library(L); +} + +// xpcall(f, handler, ...), in Lua on top of pcall: LuaJIT calls the handler of its own xpcall where the error was +// raised, before the stack unwinds, which for the error of the instruction hook is while the hook still runs, when no +// hook is called, so a handler that loops would never be stopped. here the handler is called once the error has left +// f, under pcall as well, and a script has no debug library to look at the stack with. made in Lua, a coroutine yields +// across it as across pcall +constexpr std::string_view xpcall_source{R"lua( +local pcall, select, error = pcall, select, error +local function finish(handler, ok, ...) + if ok then + return true, ... + end + local _, handled = pcall(handler, (...)) + return false, handled +end +return function(...) + if select("#", ...) < 2 then + error("bad argument #2 to 'xpcall' (value expected)", 2) + end + local f, handler = ... + return finish(handler, pcall(f, select(3, ...))) +end +)lua"}; + +// what the screens get of the libraries in place of the library's own functions, which run in C without the hook: +// string.rep, string.format and table.concat with a cap on the length of the result, the pattern functions with a cap +// on the steps they take, and xpcall made of pcall. strings share the string table as their methods +void limit_libraries(lua_State *L) +{ + lua_getglobal(L, LUA_STRLIBNAME); + lua_getfield(L, -1, "rep"); + lua_pushcclosure(L, api_repeat, 1); + lua_setfield(L, -2, "rep"); + lua_getfield(L, -1, "format"); + lua_pushcclosure(L, api_format, 1); + lua_setfield(L, -2, "format"); + for (std::size_t idx = 0; idx < pattern_function_names.size(); ++idx) + { + // "string.find": the name in the table is past the dot + auto const *name{pattern_function_names[idx] + sizeof("string.") - 1}; + lua_getfield(L, -1, name); + lua_pushinteger(L, static_cast(idx)); + lua_pushcclosure(L, api_pattern, 2); + lua_setfield(L, -2, name); + } + lua_pop(L, 1); + + lua_getglobal(L, LUA_TABLIBNAME); + lua_getfield(L, -1, "concat"); + lua_pushcclosure(L, api_concat, 1); + lua_setfield(L, -2, "concat"); + lua_pop(L, 1); + + if (0 == luaL_loadbuffer(L, xpcall_source.data(), xpcall_source.size(), "=xpcall") && 0 == lua_pcall(L, 0, 1, 0)) + { + lua_setglobal(L, "xpcall"); + } + else + { + // a script then gets no xpcall rather than the one the hook doesn't reach + lua_pop(L, 1); + lua_pushnil(L); + lua_setglobal(L, "xpcall"); } - // false and what the handler made of the error - auto const error{lua_gettop(L)}; - lua_pushboolean(L, 0); - lua_pushvalue(L, lua_upvalueindex(1)); - lua_pushvalue(L, 2); - lua_pushvalue(L, error); - lua_call(L, 2, 2); - // pcall(handler, error) gave true and the handler's value, or false and the handler's own error - lua_remove(L, -2); - return 2; } template void make_metatable(lua_State *L, char const *Name, std::array const &Methods, lua_CFunction Collect) @@ -825,8 +1127,9 @@ void lua_program::open_libraries() open_library(m_state, luaopen_string, LUA_STRLIBNAME); open_library(m_state, luaopen_math, LUA_MATHLIBNAME); open_library(m_state, luaopen_bit, LUA_BITLIBNAME); - // what reaches files or loads code - for (auto const *name : {"dofile", "loadfile", "load", "loadstring", "module", "require"}) + // what reaches files or loads code, and newproxy: a userdata of a metatable of the script's own, whose __gc LuaJIT + // runs without the hook, at any allocation and in lua_close, where a loop in it would never be stopped + for (auto const *name : {"dofile", "loadfile", "load", "loadstring", "module", "require", "newproxy"}) { lua_pushnil(m_state); lua_setglobal(m_state, name); @@ -834,15 +1137,8 @@ void lua_program::open_libraries() lua_getglobal(m_state, LUA_STRLIBNAME); lua_pushnil(m_state); lua_setfield(m_state, -2, "dump"); - // string.rep with a cap on the length, around the library's own. strings share the table as their methods - lua_getfield(m_state, -1, "rep"); - lua_pushcclosure(m_state, api_repeat, 1); - lua_setfield(m_state, -2, "rep"); lua_pop(m_state, 1); - // xpcall made of pcall, see api_xpcall - lua_getglobal(m_state, "pcall"); - lua_pushcclosure(m_state, api_xpcall, 1); - lua_setglobal(m_state, "xpcall"); + limit_libraries(m_state); } void lua_program::register_api() @@ -875,22 +1171,83 @@ void lua_program::register_api() bool lua_program::run(int const Arguments, int const Results, std::string_view const What) { budget = instruction_limit; + stopped = nullptr; // the interval, which the hook shortens once the budget of a call is spent lua_sethook(m_state, count_hook, LUA_MASKCOUNT, hook_interval); output.start_call(); - if (0 == lua_pcall(m_state, Arguments, Results, 0)) + memory.enforced = true; + auto const status{lua_pcall(m_state, Arguments, Results, 0)}; + memory.enforced = false; + if (0 == status) { return true; } auto const *message{lua_tostring(m_state, -1)}; ErrorLog(std::format("Lua screen \"{}\": {} failed: {}", script, What, message != nullptr ? message : "unknown error")); lua_pop(m_state, 1); + // what the call left behind, a heap run over the limit + lua_gc(m_state, LUA_GCCOLLECT, 0); return false; } +// render and init of the table the script returned (the argument), read in protected mode: the table may have a +// metatable of the script's, whose __index runs the script and may fail +int screen_functions(lua_State *L) +{ + lua_getfield(L, 1, "render"); + lua_getfield(L, 1, "init"); + return 2; +} + +// a refresh: render of the screen's table (its reference, the second argument) called with the state of the refresh +// (the dictionary_source, the first). in protected mode, the reading of render and the making of the state as well +int call_render(lua_State *L) +{ + auto const &input{*static_cast(lua_touserdata(L, 1))}; + auto const screen{static_cast(lua_tointeger(L, 2))}; + lua_settop(L, 0); + lua_rawgeti(L, LUA_REGISTRYINDEX, screen); + lua_getfield(L, 1, "render"); + push_state(L, input); + lua_call(L, 1, 1); + return 1; +} + +// true when a screen's state can be made with an allocator of its own: LuaJIT 2.0 on x64, and 2.1 on x64 without GC64, +// refuse one (lua_newstate gives nullptr, and writes so to stderr: 2.0 isn't asked) +bool custom_allocator_works() +{ +#if LUAJIT_VERSION_NUM < 20100 + if constexpr (sizeof(void *) == 8) + { + return false; + } +#endif + static bool const works{[] { + screen_memory probe; + auto *state{lua_newstate(limited_alloc, &probe)}; + if (state == nullptr) + { + return false; + } + lua_close(state); + return true; + }()}; + return works; +} + bool lua_program::start() { - m_state = luaL_newstate(); + // the screen's own allocator counts its memory, where LuaJIT takes one + if (custom_allocator_works()) + { + m_state = lua_newstate(limited_alloc, &memory); + memory.counted = m_state != nullptr; + } + if (m_state == nullptr) + { + m_state = luaL_newstate(); + } if (m_state == nullptr) { ErrorLog(std::format("Lua screen \"{}\": failed to create the state", script)); @@ -922,19 +1279,22 @@ bool lua_program::start() ErrorLog(std::format("Lua screen \"{}\": the script has to return a table with a render function", script)); return false; } - lua_getfield(m_state, -1, "render"); - auto const renders{lua_isfunction(m_state, -1)}; - lua_pop(m_state, 1); - if (false == renders) + lua_pushcfunction(m_state, screen_functions); + lua_pushvalue(m_state, -2); + if (false == run(1, 2, "reading render and init")) + { + return false; + } + // the table, render, init + if (false == lua_isfunction(m_state, -2)) { ErrorLog(std::format("Lua screen \"{}\": the script has to return a table with a render function", script)); return false; } - m_screen = luaL_ref(m_state, LUA_REGISTRYINDEX); - - lua_rawgeti(m_state, LUA_REGISTRYINDEX, m_screen); - lua_getfield(m_state, -1, "init"); lua_remove(m_state, -2); + lua_insert(m_state, -2); + // init, the table + m_screen = luaL_ref(m_state, LUA_REGISTRYINDEX); if (lua_isfunction(m_state, -1)) { if (false == run(0, 0, "init")) @@ -953,11 +1313,10 @@ bool lua_program::start() bool lua_program::render(render_call &Call) { call = &Call; - lua_rawgeti(m_state, LUA_REGISTRYINDEX, m_screen); - lua_getfield(m_state, -1, "render"); - lua_remove(m_state, -2); - push_state(m_state, Call.input); - auto const rendered{run(1, 1, "render")}; + lua_pushcfunction(m_state, call_render); + lua_pushlightuserdata(m_state, const_cast(&Call.input)); + lua_pushinteger(m_state, m_screen); + auto const rendered{run(2, 1, "render")}; call = nullptr; if (false == rendered) { @@ -999,6 +1358,11 @@ class lua_runtime_host final : public runtime } // namespace +bool lua_screen_memory_allocator() +{ + return custom_allocator_works(); +} + std::unique_ptr make_lua_runtime() { return std::make_unique(); diff --git a/scripting/scriptscreenprogram.h b/scripting/scriptscreenprogram.h index 86e59859b..32fd493ef 100644 --- a/scripting/scriptscreenprogram.h +++ b/scripting/scriptscreenprogram.h @@ -38,6 +38,17 @@ constexpr int max_log_lines_per_call{32}; constexpr std::size_t max_log_line{1024}; // bytes of the text, a longer one is cut // the largest file a screen reads: its script or module, a file below its folder constexpr std::uintmax_t max_screen_file{16 * 1024 * 1024}; +// the memory a Lua screen may hold: its Lua heap, and the pixels of its images, fonts and sprites. checked with a full +// collection, so its garbage doesn't count; between the collections it may take the screen up to twice this +constexpr std::size_t max_screen_memory{128 * 1024 * 1024}; + +// true when the Lua screens count their memory in an allocator of their own, which refuses what goes over +// max_screen_memory as it is asked for: LuaJIT 2.1 in its GC64 mode, a 32-bit build. LuaJIT 2.0 on x64 (the game's on +// Windows) and 2.1 on x64 without GC64 take no allocator; there the memory is checked by the instruction hook every +// so many instructions, and before what makes images and large strings in one call (string.rep, string.format, +// table.concat, string.gsub), but not at the concatenation operator: one concatenation of large strings is made +// whole, as far as LuaJIT's own heap goes (2 GB on x64), and the screen is stopped at the next check +bool lua_screen_memory_allocator(); struct pending_command { diff --git a/scripting/scriptscreenrules.cpp b/scripting/scriptscreenrules.cpp index 6f47565ef..35f918618 100644 --- a/scripting/scriptscreenrules.cpp +++ b/scripting/scriptscreenrules.cpp @@ -13,6 +13,7 @@ http://mozilla.org/MPL/2.0/. #include "utilities/parser.h" #include +#include namespace script_screens { @@ -134,4 +135,112 @@ std::optional screen_script_path(std::string const &Folder, std::st return path; } +namespace +{ + +// the end of the set that starts at Start ('['), past its ']'; Pattern.size() for a set that doesn't end. as Lua's +// classEnd: a ']' right after '[' or '[^' is in the set, and '%' escapes the character after it +std::size_t set_end(std::string_view const Pattern, std::size_t Start) +{ + auto idx{Start + 1}; + if (idx < Pattern.size() && Pattern[idx] == '^') + { + ++idx; + } + do + { + if (idx >= Pattern.size()) + { + return Pattern.size(); + } + if (Pattern[idx++] == '%') + { + ++idx; + } + } while (idx >= Pattern.size() || Pattern[idx] != ']'); + return idx + 1; +} + +} // namespace + +double lua_pattern_cost(std::string_view const Pattern, std::size_t const Subject, bool const Plain, bool const Anchorable) +{ + auto const length{static_cast(std::max(Pattern.size(), 1))}; + auto const positions{static_cast(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) + { + 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}; + while (idx < Pattern.size()) + { + auto const character{Pattern[idx]}; + if (character == '(' || character == ')') + { + ++idx; + // a ')' after the last repetition keeps it last + continue; + } + last_repeat = false; + 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; + idx += 4; + continue; + } + if (next == 'f') + { + idx = idx + 2 < Pattern.size() && Pattern[idx + 2] == '[' ? set_end(Pattern, idx + 2) : idx + 2; + continue; + } + if (next >= '0' && next <= '9') + { + // a back reference compares the capture, as long as the subject + ++repeats; + last_repeat = true; + idx += 2; + continue; + } + end = idx + 2; + } + else if (character == '[') + { + end = set_end(Pattern, idx); + } + if (end < Pattern.size() && (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; + } + } + if (last_repeat) + { + --repeats; + } + auto const starts{anchored ? 1.0 : positions}; + return starts * std::pow(positions, repeats) * std::pow(2.0, optional) * length; +} + } // namespace script_screens diff --git a/scripting/scriptscreenrules.h b/scripting/scriptscreenrules.h index 37cf0bd83..8690793e6 100644 --- a/scripting/scriptscreenrules.h +++ b/scripting/scriptscreenrules.h @@ -78,4 +78,19 @@ bool is_safe_relative_path(std::string_view Path); // reads: absolute, with a drive, or with ".."), since the script's folder is the one the screen then reads files from std::optional screen_script_path(std::string const &Folder, std::string const &Script); +// the Lua pattern functions (string.find, match, gmatch, gsub) run in C, where the instruction limit doesn't reach, and +// backtrack: ("a"):rep(1e6):find(".-b") would take hours. a call is refused when the steps it may take at worst, by +// lua_pattern_cost(), are over this: LuaJIT 2.0 goes through the worst patterns that cost as much (a):rep(5770) and +// .-b) in about a tenth of a second +constexpr double max_pattern_cost{1e8}; + +// the steps a Lua pattern function may take at worst on a subject of Subject bytes, Pattern being m bytes long: +// - 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) +// 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); + } // namespace script_screens diff --git a/tests/unit/test_script_screen_host.cpp b/tests/unit/test_script_screen_host.cpp index 697175c35..8fd4de2f4 100644 --- a/tests/unit/test_script_screen_host.cpp +++ b/tests/unit/test_script_screen_host.cpp @@ -7,6 +7,7 @@ // api; what a call may send, log, read or make is capped. the Lua cases need WITH_LUA, the WebAssembly ones WITH_WASM #include "scripting/scriptscreens.h" +#include "scripting/scriptscreenprogram.h" #include "input/command.h" #include "interfaces/ITexture.h" #include "utilities/Globals.h" @@ -1113,4 +1114,254 @@ TEST_CASE("lua screens: a script larger than the limit isn't loaded") { queue.exit(); } +namespace { + +// white when the script gets no userdata of its own (newproxy), and a table's __gc isn't called: no finalizer of the +// script's, which LuaJIT would run without the hook +constexpr std::string_view finalizer_script{R"( +local collected = false +setmetatable({}, { __gc = function() collected = true end }) +collectgarbage() +collectgarbage() +local good = newproxy == nil and ffi == nil and require == nil and not collected +return { + render = function(state) + return eu07.image(1, 1, good and { 255, 255, 255 } or { 0, 0, 0 }) + end +} +)"}; + +// a table whose metatable fails, loops, or gives render: the game reads the table in protected mode +constexpr std::string_view failing_index_script{R"( +return setmetatable({}, { __index = function() error("x") end }) +)"}; + +constexpr std::string_view looping_index_script{R"( +return setmetatable({}, { __index = function() while true do end end }) +)"}; + +constexpr std::string_view inherited_render_script{R"( +local base = { render = function(state) return eu07.image(1, 1, { 255, 255, 255 }) end } +return setmetatable({}, { __index = base }) +)"}; + +// starts, then fails when render is read for a refresh +constexpr std::string_view failing_later_script{R"( +local started = false +return setmetatable({}, { __index = function(t, key) + if key == "init" then return function() started = true end end + if key == "render" then + if started then error("render can't be read any more") end + return function() end + end +end }) +)"}; + +// white when the pattern functions refuse what may take too long, and do what doesn't +constexpr std::string_view pattern_script{R"( +local long = ("a"):rep(1000000) +local function refused(...) + local ok, message = pcall(...) + return not ok and message:find("may take too long", 1, true) ~= nil +end +local slow = refused(string.find, long, ".-b") + and refused(function() return long:find(".-b") end) + and refused(string.match, long, "(a*)b") + and refused(string.gsub, long, "a-b", "") + and refused(function() for x in long:gmatch("a-b") do end end) + and refused(string.find, ("a"):rep(1000), "a?a?a?a?a?a?a?a?a?a?a?a?a?a?a?a?a?a?a?a?a?a?a?a?a?a?a?a?a?a?aaaaaaaaaaaaaaaaaaaaaaaaaaaaaab") + and refused(string.find, long, ("a"):rep(1000) .. "b", 1, true) +-- what a screen does: lines of a file, fields of a line, a plain search, short subjects +local text = ("key=value\n"):rep(10000) +local lines = 0 +for line in text:gmatch("[^\n]+") do lines = lines + 1 end +local key, value = ("speed=120"):match("^(%w+)=(%d+)$") +local spaced = select(2, (("a b c "):rep(100)):gsub("%s+", " ")) +local found = long:find("aaab", 1, true) == nil and (long .. "b"):find("ab", 1, true) == 1000000 +local fast = lines == 10000 and key == "speed" and value == "120" and spaced == 300 and found + and ("x = 1"):find("=") == 3 and ("abc"):gsub("b", "%0%0") == "abbc" +return { + render = function(state) + return eu07.image(1, 1, (slow and fast) and { 255, 255, 255 } or { 0, 0, 0 }) + end +} +)"}; + +// white when what makes a large string in one call is refused past the memory of a screen +constexpr std::string_view large_result_script{R"( +local mega = ("x"):rep(1024 * 1024) +local function refused(...) + local ok, message = pcall(...) + return not ok and message:find("over the memory of a screen", 1, true) ~= nil +end +local parts = {} +for i = 1, 200 do parts[i] = mega end +local format = refused(string.format, ("%s"):rep(200), unpack(parts)) +local concat = refused(table.concat, parts) +local gsub = refused(string.gsub, mega, "", ("y"):rep(1000)) +local gsub_table = refused(string.gsub, mega, ".", { x = ("y"):rep(1000) }) +local fits = #table.concat({ mega, mega }, ",") == 2 * 1024 * 1024 + 1 and #string.format("%s%s", mega, mega) == 2 * 1024 * 1024 + and select(2, mega:gsub("x", "yy")) == 1024 * 1024 +return { + render = function(state) + return eu07.image(1, 1, (format and concat and gsub and gsub_table and fits) 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 = {} +local ok, message = pcall(function() + for i = 1, 100 do kept[i] = eu07.image(4096, 4096) end +end) +local refused = not ok and message:find("memory limit exceeded", 1, true) ~= nil and #kept < 100 +kept = nil +local dropped = pcall(function() + for i = 1, 20 do local image = eu07.image(4096, 4096) end +end) +return { + render = function(state) + return eu07.image(1, 1, (refused and dropped) and { 255, 255, 255 } or { 0, 0, 0 }) + end +} +)"}; + +// holds more and more memory, a little at a time +constexpr std::string_view growing_script{R"( +local kept = {} +for i = 1, 10000000 do kept[i] = ("x"):rep(1000) .. i end +return { render = function(state) return eu07.image(1, 1, { 255, 255, 255 }) end } +)"}; + +// a concatenation of 320 MB in one operation, from a string of 64 MB: only an allocator of the screen's own refuses +// it as it is made +constexpr std::string_view one_concatenation_script{R"( +local a = ("x"):rep(1024 * 1024) +for i = 1, 6 do a = a .. a end +local ok, message = pcall(function() return #(a .. a .. a .. a .. a) end) +local refused = #a == 64 * 1024 * 1024 and not ok and message:find("not enough memory", 1, true) ~= nil +a = nil +return { + render = function(state) + return eu07.image(1, 1, refused and { 255, 255, 255 } or { 0, 0, 0 }) + end +} +)"}; + +// white when a coroutine yields across xpcall, and xpcall without a handler is an error +constexpr std::string_view xpcall_yield_script{R"( +local resume = coroutine.wrap(function() + local ok, value = xpcall(function() + coroutine.yield(1) + return 2 + end, function(e) return e end) + coroutine.yield(ok and value) + local caught, handled = xpcall(function() + coroutine.yield(3) + error("boom") + end, function(e) return "handled: " .. e end) + coroutine.yield(not caught and handled:find("handled: .*boom") ~= nil) +end) +local first, second, third, fourth = resume(), resume(), resume(), resume() +local missing = not pcall(xpcall, print) +local good = first == 1 and second == 2 and third == 3 and fourth == true and missing +return { + render = function(state) + return eu07.image(1, 1, good and { 255, 255, 255 } or { 0, 0, 0 }) + end +} +)"}; + +// loads the script as a screen next to a working one: the working one draws, the script's screen draws nothing, and +// nothing hangs or ends the program +void check_switched_off(script_folder const &Folder, std::string const &Name, std::string_view const Code) { + auto const painting{Folder.write("paint.lua", paint_script)}; + auto const failing{Folder.write(Name, Code)}; + auto *queue{new script_screen_queue}; // NOSONAR a stuck worker would keep the destructor waiting, see above + REQUIRE(queue->init()); + recording_texture switched_off; + recording_texture working; + auto const first{queue->acquire(request(script_language::lua, failing, Name, &switched_off))}; + auto const second{queue->acquire(request(script_language::lua, painting, "paint", &working))}; + refresh(*queue, first, speed(1.0), 1); + refresh(*queue, second, speed(2.0), 1); + auto const drawn{run_until(*queue, [&working] { return working.uploads > 0; })}; + CHECK(drawn); + if (false == drawn) { + return; + } + run_frames(*queue); + CHECK(switched_off.uploads == 0); + CHECK_FALSE(queue->due(*first)); + queue->exit(); + delete queue; // NOSONAR see above +} + +} // namespace + +TEST_CASE("lua screens: a script makes no finalizer of its own") { + script_folder const folder{"lua_finalizer"}; + CHECK(first_pixel(folder.write("finalizer.lua", finalizer_script), "finalizer") == 255); +} + +TEST_CASE("lua screens: the table of a script is read in protected mode") { + log_capture const log; + script_folder const folder{"lua_index"}; + SUBCASE("a metatable that fails") { + check_switched_off(folder, "failing.lua", failing_index_script); + CHECK_FALSE(log.lines_with("reading render and init failed").empty()); + } + SUBCASE("a metatable that loops") { + check_switched_off(folder, "looping.lua", looping_index_script); + CHECK_FALSE(log.lines_with("instruction limit exceeded").empty()); + } + SUBCASE("a metatable that fails once the screen runs") { + check_switched_off(folder, "later.lua", failing_later_script); + CHECK_FALSE(log.lines_with("render can't be read any more").empty()); + } + SUBCASE("a metatable that gives render") { + CHECK(first_pixel(folder.write("inherited.lua", inherited_render_script), "inherited") == 255); + } +} + +TEST_CASE("lua screens: the pattern functions refuse what may take too long, and do the rest") { + script_folder const folder{"lua_patterns"}; + auto const started{std::chrono::steady_clock::now()}; + CHECK(first_pixel(folder.write("patterns.lua", pattern_script), "patterns") == 255); + // the refused calls take no time, the others little + CHECK(std::chrono::steady_clock::now() - started < std::chrono::seconds(10)); +} + +TEST_CASE("lua screens: what makes a large string in one call is held to the memory of a screen") { + script_folder const folder{"lua_large_result"}; + CHECK(first_pixel(folder.write("large.lua", large_result_script), "large") == 255); +} + +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); +} + +TEST_CASE("lua screens: a screen holding more than its memory is switched off") { + log_capture const log; + script_folder const folder{"lua_growing"}; + check_switched_off(folder, "growing.lua", growing_script); + CHECK(log.lines_with("memory limit exceeded").size() + log.lines_with("not enough memory").size() > 0); +} + +TEST_CASE("lua screens: with an allocator of the screen's own, a string made over the memory in one operation is refused") { + if (false == script_screens::lua_screen_memory_allocator()) { + MESSAGE("LuaJIT takes no allocator of the game's here (2.0, or 2.1 without GC64 on x64): not tested"); + return; + } + script_folder const folder{"lua_one_concatenation"}; + CHECK(first_pixel(folder.write("concatenation.lua", one_concatenation_script), "concatenation") == 255); +} + +TEST_CASE("lua screens: a coroutine yields across xpcall") { + script_folder const folder{"lua_xpcall_yield"}; + CHECK(first_pixel(folder.write("yield.lua", xpcall_yield_script), "yield") == 255); +} + #endif diff --git a/tests/unit/test_script_screens.cpp b/tests/unit/test_script_screens.cpp index 4fc688928..0b92e7505 100644 --- a/tests/unit/test_script_screens.cpp +++ b/tests/unit/test_script_screens.cpp @@ -117,3 +117,45 @@ TEST_CASE("script screens: the script of a screen is in the vehicle's folder, or CHECK_FALSE(screen_script_path(vehicle, "c:/games/screen.lua").has_value()); CHECK_FALSE(screen_script_path("../outside/", "screen.lua").has_value()); } + +TEST_CASE("script screens: the steps a Lua pattern function may take at worst") { + using script_screens::lua_pattern_cost; + using script_screens::max_pattern_cost; + // a plain search: the subject (and one past it) times the pattern + CHECK(lua_pattern_cost("abc", 999, true, true) == doctest::Approx(1000.0 * 3)); + CHECK(lua_pattern_cost(".-b", 999, true, true) == doctest::Approx(1000.0 * 3)); + // a pattern without special characters is searched plainly as well + CHECK(lua_pattern_cost("abc", 999, false, true) == doctest::Approx(1000.0 * 3)); + CHECK(lua_pattern_cost("", 999, false, true) == doctest::Approx(1000.0)); + // from every position, times the subject for each repetition but a last one + CHECK(lua_pattern_cost(".-b", 999, false, true) == doctest::Approx(1000.0 * 1000 * 3)); + CHECK(lua_pattern_cost("a*", 999, false, true) == doctest::Approx(1000.0 * 2)); + CHECK(lua_pattern_cost("(a+)", 999, false, true) == doctest::Approx(1000.0 * 4)); + CHECK(lua_pattern_cost("a+$", 999, false, true) == doctest::Approx(1000.0 * 1000 * 3)); + CHECK(lua_pattern_cost("(%d+):(%d+)", 999, false, true) == doctest::Approx(1000.0 * 1000 * 11)); + CHECK(lua_pattern_cost("[^\n]+", 999, false, false) == doctest::Approx(1000.0 * 5)); + CHECK(lua_pattern_cost("[%]x]*y", 999, false, true) == doctest::Approx(1000.0 * 1000 * 7)); + CHECK(lua_pattern_cost("%bxyz", 999, false, true) == doctest::Approx(1000.0 * 1000 * 5)); + CHECK(lua_pattern_cost("(a)%1x", 999, false, true) == doctest::Approx(1000.0 * 1000 * 6)); + CHECK(lua_pattern_cost("%f[%w]%w+", 999, false, true) == doctest::Approx(1000.0 * 9)); + // '?' doubles + CHECK(lua_pattern_cost("a?a?b", 999, false, true) == doctest::Approx(1000.0 * 4 * 5)); + // '^' anchors find, match and gsub to the first position; gmatch takes it as a character + CHECK(lua_pattern_cost("^.-b", 999, false, true) == doctest::Approx(1000.0 * 4)); + CHECK(lua_pattern_cost("^.-b", 999, false, false) == doctest::Approx(1000.0 * 1000 * 4)); + // a malformed pattern is the library's to refuse + CHECK(lua_pattern_cost("[a", 999, false, true) > 0.0); + CHECK(lua_pattern_cost("%", 999, false, true) > 0.0); + CHECK(lua_pattern_cost("%b", 999, false, true) > 0.0); + + // the review's case, and what a screen does + CHECK(lua_pattern_cost(".-b", 1'000'000, false, true) > max_pattern_cost); + CHECK(lua_pattern_cost("[^\n]+", 1'000'000, false, false) < max_pattern_cost); + CHECK(lua_pattern_cost("^(%w+)=(%d+)$", 1'000, false, true) < max_pattern_cost); + CHECK(lua_pattern_cost("%s+$", 4'000, false, true) < max_pattern_cost); + std::string optional; + for (int idx = 0; idx < 30; ++idx) { + optional += "a?"; + } + CHECK(lua_pattern_cost(optional + std::string(30, 'a'), 100, false, true) > max_pattern_cost); +}