diff --git a/script_screens_doc.md b/script_screens_doc.md index 0be028952..723de28ea 100644 --- a/script_screens_doc.md +++ b/script_screens_doc.md @@ -137,6 +137,49 @@ 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, 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; +- 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 + 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; +- 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 07fe89a4b..a490a9814 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 "scripting/luasandbox.h" #include "utilities/Logs.h" @@ -28,11 +32,11 @@ http://mozilla.org/MPL/2.0/. #include #include +#include #include #include -#include -#include #include +#include #include #include #include @@ -44,20 +48,69 @@ namespace { constexpr int hook_interval{1000}; -constexpr char const *image_metatable{"eu07.image"}; -constexpr char const *font_metatable{"eu07.font"}; -constexpr char const *sprite_metatable{"eu07.sprite"}; +// the longest string string.rep makes +constexpr double max_repeat{1024 * 1024}; +// arrays, to be arguments of collect<> +constexpr char image_metatable[]{"eu07.image"}; +constexpr char font_metatable[]{"eu07.font"}; +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: - lua_program(std::string const &Script, script_screen_kind const Kind) : kind{Kind}, script{Script}, folder{substr_path(Script)} {} + lua_program(std::string const &Script, script_screen_kind const Kind) + : kind{Kind}, script{Script}, folder{substr_path(Script)}, output{std::format("Lua screen \"{}\"", Script)} + { + } ~lua_program() override { if (m_state != nullptr) { + // the finalizers lua_close runs aren't counted: the budget of the last call may be spent + lua_sethook(m_state, nullptr, 0, 0); lua_close(m_state); } } @@ -72,7 +125,15 @@ class lua_program final : public program std::string const folder; render_call *call{nullptr}; // the refresh in progress 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 @@ -93,6 +154,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)}; @@ -100,33 +179,63 @@ void count_hook(lua_State *L, lua_Debug * /*Debug*/) { return; } - self->budget -= hook_interval; - if (self->budget < 0) + if (self->stopped == nullptr) { - luaL_error(L, "instruction limit exceeded"); + 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, "%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; } -template int collect(lua_State *L) -{ - static_cast(lua_touserdata(L, 1))->~Type_(); - return 0; -} - // the object at the index when it has the metatable, otherwise nullptr template Type_ *test_object(lua_State *L, int const Index, char const *Metatable) { @@ -141,6 +250,25 @@ template Type_ *test_object(lua_State *L, int const Index, char return matches ? static_cast(object) : nullptr; } +// __gc. the metatables are locked (make_metatable), so only the collector calls it; all the same it destroys only an +// object of its own type, and once: the object loses its metatable, which its methods check for +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; +} + template Type_ &check_object(lua_State *L, int const Index, char const *Metatable) { auto *object{test_object(L, Index, Metatable)}; @@ -199,6 +327,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); @@ -263,6 +413,12 @@ std::optional read_png(std::string const &Folder, std::string_vie int width{0}; int height{0}; int channels{0}; + // the size first: a small file may declare an image of gigabytes + if (0 == stbi_info_from_memory(reinterpret_cast(file->data()), static_cast(file->size()), &width, &height, &channels) || + false == valid_image_side(width) || false == valid_image_side(height)) + { + return std::nullopt; + } // the texture loader turns every image bottom row first, for all threads (model/Texture.cpp): fonts and sprites are // read top row first, as led_util reads them stbi_set_flip_vertically_on_load_thread(0); @@ -286,7 +442,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; } @@ -301,9 +459,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; } } @@ -324,7 +485,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; } } @@ -363,9 +526,13 @@ int api_log(lua_State *L) { lua_concat(L, count * 2 - 1); } - auto const *self{program_of(L)}; - auto const *text{lua_tostring(L, -1)}; - WriteLog(std::format("Lua screen \"{}\": {}", self->script, text != nullptr ? text : "")); + auto *self{program_of(L)}; + std::size_t length{0}; + auto const *text{lua_tolstring(L, -1, &length)}; + if (auto const line{self->output.take_log(text != nullptr ? std::string_view{text, length} : std::string_view{})}; line.has_value()) + { + WriteLog(*line); + } return 0; } @@ -389,7 +556,10 @@ int api_command(lua_State *L) } return 0; } - self->call->commands.emplace_back(std::string{name}, param1, param2, self->call->vehicle); + if (self->output.take_command(*self->call, name)) + { + self->call->commands.emplace_back(std::string{name}, param1, param2, self->call->vehicle); + } return 0; } @@ -562,7 +732,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; } @@ -578,14 +748,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; } @@ -659,6 +831,226 @@ constexpr std::array api_functions{ luaL_Reg{nullptr, nullptr}, }; +// string.rep, which makes no string longer than max_repeat. a separator (a third argument, where LuaJIT takes one) +// is counted as well +int api_repeat(lua_State *L) +{ + std::size_t length{0}; + luaL_checklstring(L, 1, &length); + auto const count{luaL_checknumber(L, 2)}; + std::size_t separator{0}; + luaL_optlstring(L, 3, "", &separator); + // as a double: no overflow for any count, and a count of NaN fails both comparisons + if (false == (count <= 0) && false == (static_cast(length) * count + static_cast(separator) * (count - 1) <= max_repeat)) + { + return luaL_error(L, "string.rep: the result would be over %d bytes", static_cast(max_repeat)); + } + lua_pushvalue(L, lua_upvalueindex(1)); + lua_insert(L, 1); + lua_call(L, lua_gettop(L) - 1, 1); + return 1; +} + +// 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) +{ + lua_pushvalue(L, lua_upvalueindex(1)); + 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) + { + total += lua_type(L, idx) == LUA_TSTRING ? 4.0 * static_cast(lua_objlen(L, idx)) : 512.0; + } + if (total > static_cast(max_screen_memory)) + { + 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) + { + 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) + { + 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}; + 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(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(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"); + } +} + template void make_metatable(lua_State *L, char const *Name, std::array const &Methods, lua_CFunction Collect) { luaL_newmetatable(L, Name); @@ -675,6 +1067,9 @@ template void make_metatable(lua_State *L, char const *Name, lua_setfield(L, -2, "__index"); lua_pushcfunction(L, Collect); lua_setfield(L, -2, "__gc"); + // getmetatable() of an object gives this instead of the table + lua_pushboolean(L, 0); + lua_setfield(L, -2, "__metatable"); lua_pop(L, 1); } @@ -724,6 +1119,8 @@ void lua_program::open_libraries() { // base, table, string, math and bit, without what reaches files or loads code lua_sandbox::open_safe_libraries(m_state); + // what runs in C without the hook is held to limits of its own + limit_libraries(m_state); } void lua_program::register_api() @@ -733,9 +1130,9 @@ void lua_program::register_api() lua_pushlightuserdata(L, this); lua_rawset(L, LUA_REGISTRYINDEX); - make_metatable(L, image_metatable, image_methods, collect); - make_metatable(L, font_metatable, font_methods, collect); - make_metatable(L, sprite_metatable, sprite_methods, collect); + make_metatable(L, image_metatable, image_methods, collect); + make_metatable(L, font_metatable, font_methods, collect); + make_metatable(L, sprite_metatable, sprite_methods, collect); lua_newtable(L); for (auto const &function : api_functions) @@ -756,19 +1153,83 @@ void lua_program::register_api() bool lua_program::run(int const Arguments, int const Results, std::string_view const What) { budget = instruction_limit; - if (0 == lua_pcall(m_state, Arguments, Results, 0)) + 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(); + 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)); @@ -780,14 +1241,13 @@ bool lua_program::start() register_api(); lua_sethook(m_state, count_hook, LUA_MASKCOUNT, hook_interval); - std::ifstream file{script, std::ios::binary}; - if (false == file.is_open()) + auto const code{read_regular_file(script)}; + if (false == code.has_value()) { - ErrorLog(std::format("Lua screen \"{}\": file not found", script)); + ErrorLog(std::format("Lua screen \"{}\": file not found, or larger than {} bytes", script, max_screen_file)); return false; } - std::string const code{std::istreambuf_iterator{file}, std::istreambuf_iterator{}}; - if (false == load_chunk(m_state, code, script)) + if (false == load_chunk(m_state, *code, script)) { ErrorLog(std::format("Lua screen \"{}\": {}", script, lua_tostring(m_state, -1))); return false; @@ -801,19 +1261,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")) @@ -832,11 +1295,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) { @@ -878,6 +1340,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/scriptscreendrawing.cpp b/scripting/scriptscreendrawing.cpp index f738d9292..870b5b8a3 100644 --- a/scripting/scriptscreendrawing.cpp +++ b/scripting/scriptscreendrawing.cpp @@ -64,13 +64,11 @@ bool lit_pixel(std::span const Rgba, int const Width, int co glyph cut_glyph(std::span const Rgba, int const Width, int const Height, int const First, int const Count) { std::vector lit(static_cast(Count) * Height, false); - for (auto column = 0; column < Count; ++column) + // only the columns inside the image are read + auto const last{static_cast(std::min(static_cast(First) + Count, Width))}; + for (auto x = std::max(First, 0); x < last; ++x) { - auto const x{First + column}; - if (x < 0 || x >= Width) - { - continue; - } + auto const column{x - First}; for (auto y = 0; y < Height; ++y) { lit[static_cast(column) * Height + y] = lit_pixel(Rgba, Width, x, y); @@ -128,14 +126,15 @@ std::u32string decode_utf8(std::string_view const Text) std::optional bitmap_font::parse(std::span const Rgba, int const Width, int const Height, std::string_view const Description) { - if (Width <= 0 || Height <= 0 || Rgba.size() < static_cast(Width) * Height * 4) + if (Width <= 0 || Height <= 0 || Width > max_font_image_side || Height > max_font_image_side || Rgba.size() < static_cast(Width) * Height * 4) { return std::nullopt; } bitmap_font font; font.m_height = Height; auto const all{lines(Description)}; - auto x{0}; + auto x{0}; // where the glyph starts: at most max_font_columns + auto glyphs{0}; // the first line is a comment for (std::size_t line = 1; line < all.size(); ++line) { @@ -157,10 +156,14 @@ std::optional bitmap_font::parse(std::span cons digits.remove_suffix(1); } auto width{0}; - if (std::from_chars(digits.data(), digits.data() + digits.size(), width).ec != std::errc{} || width < 0) + if (std::from_chars(digits.data(), digits.data() + digits.size(), width).ec != std::errc{} || width < 0 || width > max_font_image_side) { continue; } + if (++glyphs > max_font_glyphs || x + width > max_font_columns) + { + return std::nullopt; + } auto cut{cut_glyph(Rgba, Width, Height, x, width)}; if (font.m_glyphs.empty()) { diff --git a/scripting/scriptscreendrawing.h b/scripting/scriptscreendrawing.h index 215f2bf73..5b8166efa 100644 --- a/scripting/scriptscreendrawing.h +++ b/scripting/scriptscreendrawing.h @@ -57,12 +57,19 @@ class glyph std::vector m_lit; }; +// what a font may be: an image no larger than a screen image, a glyph no wider; no more glyphs, nor columns of them +// side by side, than a font can use. a glyph past the image's edge is unlit there, as with led_util +constexpr int max_font_image_side{4096}; +constexpr int max_font_glyphs{4096}; +constexpr int max_font_columns{2 * max_font_image_side}; + class bitmap_font { public: // a font as led_util.load_font() reads it: Rgba (Width x Height) has the glyphs side by side, a column apart; // Description has a comment line, then a line per glyph: the character and its width. a pixel is lit unless it is - // opaque white. nothing for a description without glyphs + // opaque white. a glyph wider than max_font_image_side is skipped. nothing for a description without glyphs, or + // beyond the limits above static std::optional parse(std::span Rgba, int Width, int Height, std::string_view Description); // a sprite as led_util.load_spr() reads it: the whole image as one glyph static glyph sprite(std::span Rgba, int Width, int Height); diff --git a/scripting/scriptscreenprogram.h b/scripting/scriptscreenprogram.h index 6b0d1b70b..32fd493ef 100644 --- a/scripting/scriptscreenprogram.h +++ b/scripting/scriptscreenprogram.h @@ -14,11 +14,13 @@ http://mozilla.org/MPL/2.0/. #include "scripting/scriptscreens.h" +#include #include #include #include #include #include +#include #include namespace script_screens @@ -28,6 +30,25 @@ namespace script_screens constexpr int max_image_side{4096}; // the most instructions one call into a screen may run, so that a script stuck in a loop can't hang the worker constexpr std::int64_t instruction_limit{200'000'000}; +// what one call into a screen may send and log; the rest is dropped, which the log tells once per screen. the longest +// name of a command the engine knows is under 40 characters +constexpr std::size_t max_commands_per_call{64}; +constexpr std::size_t max_command_name{64}; +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 { @@ -86,6 +107,31 @@ std::unique_ptr make_wasm_runtime(); std::string utf8_text(std::string const &Text); // a file of the screen's folder or below; nothing for a path leading outside, or no such file std::optional read_screen_file(std::string const &Folder, std::string_view Path); +// the file, when it is a regular file of at most max_screen_file bytes: not a folder, a device or anything larger +std::optional read_regular_file(std::string const &Path); + +// what a screen sends and logs, held to the limits of one call. Name: how the log names the screen +class output_limits +{ + public: + explicit output_limits(std::string Name) : m_name{std::move(Name)} {} + + // a new call into the screen + void start_call() + { + m_log_lines = 0; + } + // true when the command may go with the call; a command over the limits is dropped + bool take_command(render_call const &Call, std::string_view Name); + // the line to log, cut to max_log_line; nothing when the call logged enough + std::optional take_log(std::string_view Text); + + private: + std::string m_name; + int m_log_lines{0}; + bool m_commands_dropped{false}; // logged once + bool m_logs_dropped{false}; // logged once +}; // seconds of a steady clock, the same for every screen, for animations that don't depend on how often the screen is // refreshed double screen_time(); diff --git a/scripting/scriptscreenrules.cpp b/scripting/scriptscreenrules.cpp index 58c69efde..5aa71cdd4 100644 --- a/scripting/scriptscreenrules.cpp +++ b/scripting/scriptscreenrules.cpp @@ -13,6 +13,9 @@ http://mozilla.org/MPL/2.0/. #include "utilities/parser.h" #include +#include +#include +#include namespace script_screens { @@ -123,4 +126,322 @@ bool is_safe_relative_path(std::string_view const Path) return true; } +std::optional screen_script_path(std::string const &Folder, std::string const &Script) +{ + // as substr_path() tells a folder + auto path{Script.find('/') == std::string::npos ? Folder + Script : Script}; + if (false == is_safe_relative_path(path)) + { + return std::nullopt; + } + 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; +} + +// one item of a pattern, as Lua's matcher takes them +struct pattern_item +{ + enum class kind + { + 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_items(std::string_view const Pattern, std::size_t idx) +{ + std::vector items; + while (idx < Pattern.size()) + { + auto const character{Pattern[idx]}; + if (character == '(' || character == ')') + { + items.push_back({pattern_item::kind::paren, idx, idx + 1}); + ++idx; + continue; + } + 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') + { + items.push_back({pattern_item::kind::scan, idx, idx + 4}); + idx += 4; + continue; + } + if (next == 'f') + { + 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') + { + items.push_back({pattern_item::kind::scan, idx, idx + 2}); + idx += 2; + continue; + } + end = idx + 2; + } + else if (character == '[') + { + end = set_end(Pattern, idx); + } + pattern_item item{pattern_item::kind::single, idx, end}; + if (end < Pattern.size() && (Pattern[end] == '*' || Pattern[end] == '+' || Pattern[end] == '-' || Pattern[end] == '?')) + { + item.quantifier = Pattern[end]; + ++end; + } + items.push_back(item); + idx = end; + } + 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(character)}; + auto const in{single.size() == 2 ? in_class(c, static_cast(single[1])) : c == static_cast(single[0])}; + run = in ? run + 1 : 0; + longest = std::max(longest, run); + } + return longest; +} + +// the characters Lua's matchbalance goes along for a %bxy tried in the subject: from each opening character to the one +// that closes it, or to the end of the subject when nothing does +struct balance_walks +{ + double longest{0.0}; // of one try + double total{0.0}; // of a try at every opening character +}; + +// the openings held while their closing characters are looked for; a subject nested deeper counts as never closed +constexpr std::size_t max_balance_depth{65536}; + +balance_walks balance_walks_of(char const Open, char const Close, std::string_view const Subject) +{ + balance_walks walks; + auto const size{Subject.size()}; + auto const add{[&walks](std::size_t const Walk) { + walks.longest = std::max(walks.longest, static_cast(Walk)); + walks.total += static_cast(Walk); + }}; + if (Open == Close) + { + // the next one closes it, and opens the try that starts there + auto previous{Subject.find(Open)}; + while (previous != std::string_view::npos) + { + auto const next{Subject.find(Open, previous + 1)}; + add((next != std::string_view::npos ? next : size) - previous); + previous = next; + } + return walks; + } + std::vector open; + for (std::size_t idx{0}; idx < size; ++idx) + { + if (Subject[idx] == Close) + { + if (false == open.empty()) + { + add(idx - open.back()); + open.pop_back(); + } + } + else if (Subject[idx] == Open) + { + if (open.size() >= max_balance_depth) + { + auto const openings{static_cast(std::count(Subject.begin(), Subject.end(), Open))}; + return {static_cast(size), openings * static_cast(size)}; + } + open.push_back(idx); + } + } + for (auto const idx : open) + { + add(size - idx); + } + return walks; +} + +// how many times over a %bxy counts: it goes along the subject on its own, whatever follows it, so it counts where it +// ends the pattern as well. without the subject, as many times as the subject has positions. with it: the longest walk +// of one try (plus one); or, when nothing but captures is before it in a pattern tried from every position, each +// opening character is tried once, and it's the walks of all of them over the positions (plus one) +double balance_cost(std::string_view const Pattern, pattern_item const &Item, std::string_view const *Subject, double const Positions, bool const Once) +{ + if (Subject == nullptr) + { + return Positions; + } + if (Item.begin + 3 >= Pattern.size()) + { + // malformed: the function raises its error + return 1.0; + } + auto const walks{balance_walks_of(Pattern[Item.begin + 2], Pattern[Item.begin + 3], *Subject)}; + return Once ? 1.0 + walks.total / Positions : 1.0 + walks.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(std::max(Pattern.size(), 1))}; + auto const positions{static_cast(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}; + // the first item that isn't a capture: a %bxy there is tried once from each position + auto const first{std::find_if(items.begin(), items.end(), [](pattern_item const &Item) { return Item.type != pattern_item::kind::paren; })}; + for (auto item{items.rbegin()}; item != items.rend(); ++item) + { + if (item->type == pattern_item::kind::single && item->quantifier == '?') + { + cost *= 2.0; + } + if (item->type == pattern_item::kind::scan && Pattern[item->begin + 1] == 'b') + { + cost *= balance_cost(Pattern, *item, Subject, positions, false == anchored && first != items.end() && &*item == &*first); + only_end = false; + rest = rest_match::maybe; + continue; + } + 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(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 diff --git a/scripting/scriptscreenrules.h b/scripting/scriptscreenrules.h index d7d753841..bd751e50b 100644 --- a/scripting/scriptscreenrules.h +++ b/scripting/scriptscreenrules.h @@ -10,6 +10,7 @@ http://mozilla.org/MPL/2.0/. #pragma once #include +#include #include #include @@ -72,4 +73,36 @@ class frame_schedule // drive or a leading separator bool is_safe_relative_path(std::string_view Path); +// the path the game opens the script of a screen by: a name without a folder is in the vehicle's folder (Folder), a +// path is from the game's folder. nothing for a path that leads outside the game's folder (as for the files a screen +// 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 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 %bxy goes along the subject on its own, whatever follows it, so it counts where it ends the pattern as well: +// ("("):rep(1e6):find("%b()") walks to the end of the subject from each of its characters +// 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 +// a %bxy counts as many times as the longest way from an opening character to the one that closes it (to the end of +// the subject when nothing does), plus one; when only captures are before it in a pattern tried from every position, +// each opening character is tried once, and it's the ways from all of them over the positions of the subject. so +// "%b()" on a long text of short balanced pairs is cheap, and on one that doesn't balance it's the subject squared +double lua_pattern_cost(std::string_view Pattern, std::string_view Subject, bool Plain, bool Anchorable); + } // namespace script_screens diff --git a/scripting/scriptscreens.cpp b/scripting/scriptscreens.cpp index 08314932e..224a2f27e 100644 --- a/scripting/scriptscreens.cpp +++ b/scripting/scriptscreens.cpp @@ -26,6 +26,7 @@ http://mozilla.org/MPL/2.0/. #include #include #include +#include #include #include #include @@ -34,6 +35,7 @@ http://mozilla.org/MPL/2.0/. #include #include #include +#include #include #include #include @@ -99,12 +101,73 @@ std::optional read_screen_file(std::string const &Folder, std::stri { return std::nullopt; } - std::ifstream file{Folder + std::string{Path}, std::ios::binary}; + return read_regular_file(Folder + std::string{Path}); +} + +std::optional read_regular_file(std::string const &Path) +{ + // a folder or a device (CON, NUL, COM1...) isn't a regular file + std::error_code error; + // in the code page of the system, as the game opens its files + std::filesystem::path const path{Path}; + if (false == std::filesystem::is_regular_file(path, error)) + { + return std::nullopt; + } + auto const size{std::filesystem::file_size(path, error)}; + if (error || size > max_screen_file) + { + return std::nullopt; + } + std::ifstream file{path, std::ios::binary}; if (false == file.is_open()) { return std::nullopt; } - return std::string{std::istreambuf_iterator{file}, std::istreambuf_iterator{}}; + std::string contents(static_cast(size), '\0'); + file.read(contents.data(), static_cast(contents.size())); + // what was read, should the file have shrunk meanwhile + contents.resize(static_cast(file.gcount())); + return contents; +} + +bool output_limits::take_command(render_call const &Call, std::string_view const Name) +{ + if (Call.commands.size() < max_commands_per_call && Name.size() <= max_command_name) + { + return true; + } + if (false == m_commands_dropped) + { + m_commands_dropped = true; + ErrorLog(std::format("{}: commands over {} in a refresh, or with names over {} characters, are dropped", m_name, max_commands_per_call, max_command_name)); + } + return false; +} + +std::optional output_limits::take_log(std::string_view Text) +{ + if (m_log_lines >= max_log_lines_per_call) + { + if (false == m_logs_dropped) + { + m_logs_dropped = true; + ErrorLog(std::format("{}: log lines over {} in a call are dropped", m_name, max_log_lines_per_call)); + } + return std::nullopt; + } + ++m_log_lines; + if (Text.size() <= max_log_line) + { + return std::format("{}: {}", m_name, Text); + } + // cut on the start of a UTF-8 character + auto end{max_log_line}; + while (end > 0 && (static_cast(Text[end]) & 0xC0) == 0x80) + { + --end; + } + return std::format("{}: {} [cut at {} of {} bytes]", m_name, Text.substr(0, end), end, Text.size()); } double screen_time() diff --git a/scripting/wasmprogram.cpp b/scripting/wasmprogram.cpp index d2f914cf0..422ce70dc 100644 --- a/scripting/wasmprogram.cpp +++ b/scripting/wasmprogram.cpp @@ -25,8 +25,6 @@ http://mozilla.org/MPL/2.0/. #include #include #include -#include -#include #include #include #include @@ -117,7 +115,10 @@ std::int32_t to_int32(std::size_t const Value) class wasm_program final : public program { public: - wasm_program(std::string const &Script, script_screen_kind const Kind) : kind{Kind}, script{Script}, folder{substr_path(Script)} {} + wasm_program(std::string const &Script, script_screen_kind const Kind) + : kind{Kind}, script{Script}, folder{substr_path(Script)}, output{std::format("WASM screen \"{}\"", Script)} + { + } ~wasm_program() override { if (exec_env != nullptr) @@ -142,6 +143,7 @@ class wasm_program final : public program input_view const *input{nullptr}; render_call *call{nullptr}; bool commands_ignored{false}; // a screen outside the cab tried to send a command, and it was logged + output_limits output; private: bool call_i32(wasm_function_inst_t Function, std::string_view Name, std::int32_t &Result); @@ -300,17 +302,23 @@ void native_command(wasm_exec_env_t Env, char const *Name, std::uint32_t const L } return; } - screen->call->commands.emplace_back(std::string{Name, Length}, Param1, Param2, screen->call->vehicle); + if (screen->output.take_command(*screen->call, std::string_view{Name, Length})) + { + screen->call->commands.emplace_back(std::string{Name, Length}, Param1, Param2, screen->call->vehicle); + } } void native_log(wasm_exec_env_t Env, char const *Text, std::uint32_t const Length) { - auto const *screen{program_of(Env)}; + auto *screen{program_of(Env)}; if (screen == nullptr || Text == nullptr) { return; } - WriteLog(std::format("WASM screen \"{}\": {}", screen->script, std::string_view{Text, Length})); + if (auto const line{screen->output.take_log(std::string_view{Text, Length})}; line.has_value()) + { + WriteLog(*line); + } } // reads a file from the screen's folder into the buffer. returns the size of the whole file, which may be more @@ -436,6 +444,7 @@ bool wasm_program::instantiate(wasm_module_t const Module) bool wasm_program::call_i32(wasm_function_inst_t Function, std::string_view const Name, std::int32_t &Result) { wasm_runtime_set_instruction_count_limit(exec_env, static_cast(instruction_limit)); + output.start_call(); std::array cells{}; if (false == wasm_runtime_call_wasm(exec_env, Function, 0, cells.data())) { @@ -579,13 +588,13 @@ wasm_module_t wasm_runtime_host::load_module(std::string const &Script) } // a failure is kept as well, so the module isn't tried again for every screen using it auto &entry{m_modules[Script]}; - std::ifstream file{Script, std::ios::binary}; - if (false == file.is_open()) + auto const file{read_regular_file(Script)}; + if (false == file.has_value()) { - ErrorLog(std::format("WASM screen \"{}\": file not found", Script)); + ErrorLog(std::format("WASM screen \"{}\": file not found, or larger than {} bytes", Script, max_screen_file)); return nullptr; } - entry.bytes.assign(std::istreambuf_iterator{file}, std::istreambuf_iterator{}); + entry.bytes.assign(file->begin(), file->end()); if (entry.bytes.empty() || entry.bytes.size() > std::numeric_limits::max()) { ErrorLog(std::format("WASM screen \"{}\": invalid module size", Script)); diff --git a/tests/unit/engine_stubs.cpp b/tests/unit/engine_stubs.cpp index 20cd008a1..d3ea80892 100644 --- a/tests/unit/engine_stubs.cpp +++ b/tests/unit/engine_stubs.cpp @@ -11,6 +11,10 @@ #include #include +#include +#include +#include +#include // settings --------------------------------------------------------------------------------------- @@ -27,9 +31,39 @@ bool log_enabled() { static bool const enabled{std::getenv("EU07_UNIT_TESTS_LOG") != nullptr}; return enabled; } + +// the lines kept for a test that checks what goes to the log, from any thread; see unit_tests_log_capture() +std::mutex &captured_mutex() { + static std::mutex mutex; + return mutex; +} + +std::optional> &captured_lines() { + static std::optional> lines; + return lines; +} + } // namespace +// for the tests: keeps every line logged from now on (true), or stops keeping them and forgets them (false) +void unit_tests_log_capture(bool const Enabled) { + std::scoped_lock lock{captured_mutex()}; + captured_lines() = Enabled ? std::make_optional>() : std::nullopt; +} + +// for the tests: the lines kept so far +std::vector unit_tests_logged_lines() { + std::scoped_lock lock{captured_mutex()}; + return captured_lines().value_or(std::vector{}); +} + void WriteLog(const char *str, logtype const, bool const isError) { + if (str != nullptr) { + std::scoped_lock lock{captured_mutex()}; + if (captured_lines().has_value()) { + captured_lines()->emplace_back(str); + } + } if (log_enabled() && str != nullptr) { (isError ? std::cerr : std::cout) << str << "\n"; } diff --git a/tests/unit/test_script_screen_drawing.cpp b/tests/unit/test_script_screen_drawing.cpp index ff822b02d..a68857ebe 100644 --- a/tests/unit/test_script_screen_drawing.cpp +++ b/tests/unit/test_script_screen_drawing.cpp @@ -5,6 +5,7 @@ #include #include +#include #include // the drawing the Lua screens get from the game: fonts read as scripts/led_util.py reads them, text and images @@ -85,6 +86,44 @@ TEST_CASE("script screen drawing: a description without glyphs, or one wider tha CHECK_FALSE(font->find(U'w').lit(4, 0)); } +TEST_CASE("script screen drawing: a glyph wider than the largest image is skipped") { + auto const pixels{image(2, 1, {})}; + auto const font{bitmap_font::parse(pixels, 2, 1, "//\nw5000\nv1\nx2147483647\n")}; + REQUIRE(font.has_value()); + // not in the font: the fallback, its first glyph + CHECK(font->find(U'w').width() == 1); + CHECK(font->find(U'x').width() == 1); + CHECK(font->find(U'v').width() == 1); + // the largest one is taken + auto const widest{bitmap_font::parse(pixels, 2, 1, "//\nw4096\n")}; + REQUIRE(widest.has_value()); + CHECK(widest->find(U'w').width() == 4096); +} + +TEST_CASE("script screen drawing: a font of too many glyphs, too many columns or too large an image is refused") { + auto const pixels{image(2, 1, {})}; + // more glyphs than any font has + std::string many{"//\n"}; + for (char32_t character = 0x100; character < 0x100 + 5000; ++character) { + // the character in UTF-8 (two bytes up to 0x7FF, three above), then its width + if (character < 0x800) { + many += static_cast(0xC0 | (character >> 6)); + } + else { + many += static_cast(0xE0 | (character >> 12)); + many += static_cast(0x80 | ((character >> 6) & 0x3F)); + } + many += static_cast(0x80 | (character & 0x3F)); + many += "0\n"; + } + CHECK_FALSE(bitmap_font::parse(pixels, 2, 1, many).has_value()); + // glyphs side by side much wider than the largest image + CHECK_FALSE(bitmap_font::parse(pixels, 2, 1, "//\na4000\nb4000\nc4000\n").has_value()); + // an image taller than the largest one + std::vector const tall(static_cast(1) * 5000 * 4, 255); + CHECK_FALSE(bitmap_font::parse(tall, 1, 5000, "//\na1\n").has_value()); +} + TEST_CASE("script screen drawing: text is drawn from x rightwards and returns where it ends") { auto const pixels{image(4, 1, {{0, 0}, {1, 0}, {3, 0}})}; auto const font{bitmap_font::parse(pixels, 4, 1, "//\na2\nb1\n")}; diff --git a/tests/unit/test_script_screen_host.cpp b/tests/unit/test_script_screen_host.cpp index 355b9b9e8..c4226da40 100644 --- a/tests/unit/test_script_screen_host.cpp +++ b/tests/unit/test_script_screen_host.cpp @@ -2,23 +2,27 @@ #include "doctest.h" // the script screen host (scripting/scriptscreens.cpp) with the real runtimes: a script reads its input, draws an -// image that goes to the screen's texture, bottom row first, and sends a command; a script stuck in a loop is stopped; -// a Lua script can't reach files, the system or precompiled code. the Lua cases need WITH_LUA, the WebAssembly ones -// WITH_WASM +// image that goes to the screen's texture, bottom row first, and sends a command; a script stuck in a loop is stopped, +// even when it catches the error; a Lua script can't reach files, the system, precompiled code or the metatables of the +// 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" #include "utilities/dictionary.h" +#include #include #include #include #include #include #include +#include #include +#include #include #include #include @@ -142,6 +146,47 @@ void refresh(script_screen_queue &Queue, std::shared_ptr const &S Queue.submit(Screen, std::move(Input), Vehicle); } +// runs frames for a while: long enough for the worker to load and run a screen that was submitted +void run_frames(script_screen_queue &Queue) { + for (int frame = 0; frame < 40; ++frame) { + Queue.update(); + std::this_thread::sleep_for(std::chrono::milliseconds(5)); + } +} + +// the limits of the sandbox (scripting/scriptscreenprogram.h), as the tests expect them +constexpr std::size_t commands_per_call{64}; +constexpr std::size_t log_lines_per_call{32}; +constexpr std::size_t log_line_length{1024}; +constexpr std::size_t screen_file_size{16 * 1024 * 1024}; + +} // namespace + +// the lines logged while the object lives, kept by the engine stubs (engine_stubs.cpp) +void unit_tests_log_capture(bool Enabled); +std::vector unit_tests_logged_lines(); + +namespace { + +class log_capture { + public: + log_capture() { unit_tests_log_capture(true); } + ~log_capture() { unit_tests_log_capture(false); } + log_capture(log_capture const &) = delete; + log_capture &operator=(log_capture const &) = delete; + + // the lines logged so far with the text in them + std::vector lines_with(std::string_view const Text) const { + std::vector result; + for (auto &line : unit_tests_logged_lines()) { + if (line.find(Text) != std::string::npos) { + result.push_back(std::move(line)); + } + } + return result; + } +}; + } // namespace TEST_CASE("script screens: a language that doesn't run gets no screens") { @@ -202,6 +247,39 @@ constexpr std::array spin_module{ 0x64, 0x65, 0x72, 0x00, 0x02, 0x0a, 0x15, 0x03, 0x04, 0x00, 0x41, 0x02, 0x0b, 0x04, 0x00, 0x41, 0x02, 0x0b, 0x09, 0x00, 0x03, 0x40, 0x0c, 0x00, 0x0b, 0x41, 0x00, 0x0b}; +// "flood": screen_render sends the command "cmdtest" 1000 times (with the parameters (i, 0)), then logs a line of +// 4000 'a' 100 times, and returns 0: +// (import "eu07" "command" (func $command (param i32 i32 i32 i32))) +// (import "eu07" "log" (func $log (param i32 i32))) +// (memory (export "memory") 1) +// (data (i32.const 0) "cmdtest") +// (func (export "screen_width") (result i32) i32.const 2) +// (func (export "screen_height") (result i32) i32.const 2) +// (func (export "screen_render") (result i32) (local $i i32) +// ;; for i in 0..1000: (call $command (i32.const 0) (i32.const 7) (local.get $i) (i32.const 0)) +// ;; for i in 0..4000: (i32.store8 (i32.add (local.get $i) (i32.const 64)) (i32.const 97)) +// ;; for i in 0..100: (call $log (i32.const 64) (i32.const 4000)) +// (i32.const 0)) +constexpr std::array flood_module{ + 0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00, 0x01, 0x11, 0x03, 0x60, 0x04, 0x7f, 0x7f, 0x7f, + 0x7f, 0x00, 0x60, 0x02, 0x7f, 0x7f, 0x00, 0x60, 0x00, 0x01, 0x7f, 0x02, 0x1b, 0x02, 0x04, 0x65, + 0x75, 0x30, 0x37, 0x07, 0x63, 0x6f, 0x6d, 0x6d, 0x61, 0x6e, 0x64, 0x00, 0x00, 0x04, 0x65, 0x75, + 0x30, 0x37, 0x03, 0x6c, 0x6f, 0x67, 0x00, 0x01, 0x03, 0x04, 0x03, 0x02, 0x02, 0x02, 0x05, 0x03, + 0x01, 0x00, 0x01, 0x07, 0x39, 0x04, 0x06, 0x6d, 0x65, 0x6d, 0x6f, 0x72, 0x79, 0x02, 0x00, 0x0c, + 0x73, 0x63, 0x72, 0x65, 0x65, 0x6e, 0x5f, 0x77, 0x69, 0x64, 0x74, 0x68, 0x00, 0x02, 0x0d, 0x73, + 0x63, 0x72, 0x65, 0x65, 0x6e, 0x5f, 0x68, 0x65, 0x69, 0x67, 0x68, 0x74, 0x00, 0x03, 0x0d, 0x73, + 0x63, 0x72, 0x65, 0x65, 0x6e, 0x5f, 0x72, 0x65, 0x6e, 0x64, 0x65, 0x72, 0x00, 0x04, 0x0a, 0x81, + 0x01, 0x03, 0x04, 0x00, 0x41, 0x02, 0x0b, 0x04, 0x00, 0x41, 0x02, 0x0b, 0x75, 0x01, 0x01, 0x7f, + 0x41, 0x00, 0x21, 0x00, 0x02, 0x40, 0x03, 0x40, 0x20, 0x00, 0x41, 0xe8, 0x07, 0x4e, 0x0d, 0x01, + 0x41, 0x00, 0x41, 0x07, 0x20, 0x00, 0x41, 0x00, 0x10, 0x00, 0x20, 0x00, 0x41, 0x01, 0x6a, 0x21, + 0x00, 0x0c, 0x00, 0x0b, 0x0b, 0x41, 0x00, 0x21, 0x00, 0x02, 0x40, 0x03, 0x40, 0x20, 0x00, 0x41, + 0xa0, 0x1f, 0x4e, 0x0d, 0x01, 0x20, 0x00, 0x41, 0xc0, 0x00, 0x6a, 0x41, 0xe1, 0x00, 0x3a, 0x00, + 0x00, 0x20, 0x00, 0x41, 0x01, 0x6a, 0x21, 0x00, 0x0c, 0x00, 0x0b, 0x0b, 0x41, 0x00, 0x21, 0x00, + 0x02, 0x40, 0x03, 0x40, 0x20, 0x00, 0x41, 0xe4, 0x00, 0x4e, 0x0d, 0x01, 0x41, 0xc0, 0x00, 0x41, + 0xa0, 0x1f, 0x10, 0x01, 0x20, 0x00, 0x41, 0x01, 0x6a, 0x21, 0x00, 0x0c, 0x00, 0x0b, 0x0b, 0x41, + 0x00, 0x0b, 0x0b, 0x0d, 0x01, 0x00, 0x41, 0x00, 0x0b, 0x07, 0x63, 0x6d, 0x64, 0x74, 0x65, 0x73, + 0x74}; + } // namespace TEST_CASE("wasm screens: a cab screen draws from its input and sends commands to its vehicle") { @@ -325,6 +403,60 @@ TEST_CASE("wasm screens: the screens outlive the queue without harm") { screen.reset(); } +TEST_CASE("wasm screens: the commands and the log lines of one call are capped") { + sent_commands().clear(); + log_capture const log; + script_folder const folder{"wasm_flood"}; + auto const module{folder.write("flood.wasm", flood_module)}; + script_screen_queue queue; + REQUIRE(queue.init()); + + recording_texture texture; + auto const screen{queue.acquire(request(script_language::wasm, module, "flood", &texture))}; + refresh(queue, screen, speed(0.0), 3); + REQUIRE(run_until(queue, [] { return false == sent_commands().empty(); })); + queue.update(); + // the first ones go, the rest is dropped + CHECK(sent_commands().size() == commands_per_call); + CHECK(sent_commands().back().first.param1 == static_cast(commands_per_call - 1)); + + auto const lines{log.lines_with("aaaaaaaaaa")}; + REQUIRE(false == lines.empty()); + CHECK(lines.size() <= log_lines_per_call); + auto const longest{std::ranges::max(lines, {}, [](std::string const &Line) { return Line.size(); })}; + CHECK(longest.size() < module.size() + log_line_length + 100); + queue.exit(); +} + +TEST_CASE("wasm screens: a module larger than the limit isn't loaded") { + // the screen of "paint", with a custom section that makes the file larger than a screen may read + std::vector bytes(paint_module.begin(), paint_module.end()); + auto const payload{screen_file_size}; + auto size{static_cast(payload + 2)}; // the name: its length and one letter + bytes.push_back(0x00); + do { + auto const low{static_cast(size & 0x7f)}; + size >>= 7; + bytes.push_back(size != 0 ? static_cast(low | 0x80) : low); + } while (size != 0); + bytes.push_back(0x01); + bytes.push_back('x'); + bytes.resize(bytes.size() + payload, 0); + + script_folder const folder{"wasm_large"}; + auto const module{folder.write("large.wasm", bytes)}; + script_screen_queue queue; + REQUIRE(queue.init()); + + recording_texture texture; + auto const screen{queue.acquire(request(script_language::wasm, module, "large", &texture))}; + refresh(queue, screen, speed(1.0), 1); + run_frames(queue); + CHECK_FALSE(queue.due(*screen)); + CHECK(texture.uploads == 0); + queue.exit(); +} + #endif #ifdef WITH_LUA @@ -750,4 +882,523 @@ TEST_CASE("lua screens: an image read after led_post has its post-processing don queue.exit(); } +namespace { + +// scripts that catch the error of the instruction limit and go on looping +constexpr std::string_view pcall_spin_script{R"( +local function spin() while true do end end +return { render = function(state) while true do pcall(spin) end end } +)"}; + +constexpr std::string_view nested_pcall_spin_script{R"( +local function spin() while true do end end +return { render = function(state) while true do pcall(function() while true do pcall(spin) end end) end end } +)"}; + +constexpr std::string_view xpcall_spin_script{R"( +local function spin() while true do end end +local function handler() while true do end end +return { render = function(state) while true do xpcall(spin, handler) end end } +)"}; + +constexpr std::string_view coroutine_spin_script{R"( +local function spin() while true do end end +return { render = function(state) while true do coroutine.resume(coroutine.create(spin)) end end } +)"}; + +// white when the metatable of an image can't be reached, and its __gc can't be called +constexpr std::string_view metatable_script{R"( +local image = eu07.image(1, 1) +local metatable = getmetatable(image) +local locked = type(metatable) ~= "table" +-- only where the metatable is locked: an unlocked one would destroy the image twice +local collected = locked and pcall(function() return metatable.__gc(image) end) +local usable = image:width() == 1 +return { + render = function(state) + return eu07.image(1, 1, (locked and not collected and usable) and { 255, 255, 255 } or { 0, 0, 0 }) + end +} +)"}; + +// white when string.rep refuses a result over the limit and makes the ones under it +constexpr std::string_view repeat_script{R"( +local huge = pcall(string.rep, "x", 64 * 1024 * 1024) +local method = pcall(function() return ("ab"):rep(16 * 1024 * 1024) end) +local endless = pcall(string.rep, "x", 1e300) +local fits = #string.rep("x", 1024 * 1024) == 1024 * 1024 and ("ab"):rep(3) == "ababab" and ("x"):rep(0) == "" and ("x"):rep(-1) == "" +return { + render = function(state) + return eu07.image(1, 1, (not huge and not method and not endless and fits) and { 255, 255, 255 } or { 0, 0, 0 }) + end +} +)"}; + +// white when an image larger than a screen can be isn't decoded, and a small one is +constexpr std::string_view large_png_script{R"( +local sprite = pcall(eu07.sprite, "large") +local font = pcall(eu07.font, "large") +local small = pcall(eu07.sprite, "small") +return { + render = function(state) + return eu07.image(1, 1, (not sprite and not font and small) and { 255, 255, 255 } or { 0, 0, 0 }) + end +} +)"}; + +// a long command name first, then too many commands and log lines for one call +constexpr std::string_view flood_script{R"( +return { + render = function(state) + eu07.command("cmdtest" .. ("q"):rep(100), 1, 0) + for i = 0, 999 do eu07.command("cmdtest", i, 0) end + for i = 1, 100 do eu07.log(("y"):rep(5000)) end + return eu07.image(1, 1) + end +} +)"}; + +// white when a file larger than a screen may read, and a folder, read as nothing +constexpr std::string_view large_file_script{R"( +local large = eu07.read_file("large.bin") +local folder = eu07.read_file("data") +local small = eu07.read_file("data/small.txt") +return { + render = function(state) + return eu07.image(1, 1, (large == nil and folder == nil and small == "small") and { 255, 255, 255 } or { 0, 0, 0 }) + end +} +)"}; + +// a white image of the size, as a .png +std::vector white_png(int const Width, int const Height) { + std::vector const pixels(static_cast(Width) * Height * 4, 255); + std::vector result; + auto const append{[](void *Target, void *Data, int const Size) { + auto *bytes{static_cast(Data)}; + static_cast *>(Target)->insert(static_cast *>(Target)->end(), bytes, bytes + Size); + }}; + stbi_write_png_to_func(append, &result, Width, Height, 4, pixels.data(), Width * 4); + return result; +} + +// runs the script of a screen once; the first pixel of what it drew, or -1 when it drew nothing (after a wait) +int first_pixel(std::string const &Script, std::string const &Key) { + script_screen_queue queue; + REQUIRE(queue.init()); + recording_texture texture; + auto const screen{queue.acquire(request(script_language::lua, Script, Key, &texture))}; + refresh(queue, screen, speed(0.0), 1); + auto const drawn{run_until(queue, [&texture] { return texture.uploads > 0; })}; + queue.exit(); + return drawn && false == texture.pixels.empty() ? texture.pixels[0] : -1; +} + +} // namespace + +TEST_CASE("lua screens: a script catching the instruction limit with pcall, xpcall or a coroutine is stopped all the same") { + script_folder const folder{"lua_pcall_spin"}; + auto const painting{folder.write("paint.lua", paint_script)}; + for (auto const &[name, code] : {std::pair{"pcall.lua", pcall_spin_script}, std::pair{"nested.lua", nested_pcall_spin_script}, + std::pair{"xpcall.lua", xpcall_spin_script}, std::pair{"coroutine.lua", coroutine_spin_script}}) { + CAPTURE(name); + auto const spinning{folder.write(name, code)}; + // a worker stuck for good would keep the queue's destructor waiting: such a queue is left behind, so the test + // fails instead of hanging the run + auto *queue{new script_screen_queue}; // NOSONAR see above + REQUIRE(queue->init()); + + recording_texture stuck; + recording_texture working; + auto const first{queue->acquire(request(script_language::lua, spinning, "spin", &stuck))}; + 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 stopped{run_until(*queue, [&working] { return working.uploads > 0; })}; + CHECK(stopped); + if (false == stopped) { + // the stuck worker doesn't touch the textures, and nothing uploads to them any more + continue; + } + CHECK(stuck.uploads == 0); + CHECK_FALSE(queue->due(*first)); + queue->exit(); + delete queue; // NOSONAR see above + } +} + +TEST_CASE("lua screens: xpcall passes the arguments, and the error to its handler") { + script_folder const folder{"lua_xpcall"}; + constexpr std::string_view script{R"( +local ok1, sum = xpcall(function(a, b) return a + b end, function(e) return "handled" end, 2, 3) +local ok2, handled = xpcall(function() error("boom") end, function(e) return "handled: " .. tostring(e) end) +local ok3 = xpcall(function() error("boom") end, function(e) error("again") end) +local good = ok1 and sum == 5 and not ok2 and handled:find("handled: .*boom") ~= nil and not ok3 +return { + render = function(state) + return eu07.image(1, 1, good and { 255, 255, 255 } or { 0, 0, 0 }) + end +} +)"}; + CHECK(first_pixel(folder.write("xpcall.lua", script), "xpcall") == 255); +} + +TEST_CASE("lua screens: the metatables of the api objects can't be reached from a script") { + script_folder const folder{"lua_metatable"}; + CHECK(first_pixel(folder.write("metatable.lua", metatable_script), "metatable") == 255); +} + +TEST_CASE("lua screens: string.rep makes no string over the limit") { + script_folder const folder{"lua_rep"}; + CHECK(first_pixel(folder.write("rep.lua", repeat_script), "rep") == 255); +} + +TEST_CASE("lua screens: a .png larger than a screen image isn't decoded") { + script_folder const folder{"lua_large_png"}; + folder.write("large.png", white_png(5000, 1)); + folder.write("large.txt", std::string_view{"//\na1\n"}); + folder.write("small.png", white_png(2, 2)); + CHECK(first_pixel(folder.write("png.lua", large_png_script), "png") == 255); +} + +TEST_CASE("lua screens: the commands and the log lines of one call are capped") { + sent_commands().clear(); + log_capture const log; + script_folder const folder{"lua_flood"}; + auto const script{folder.write("flood.lua", flood_script)}; + script_screen_queue queue; + REQUIRE(queue.init()); + + recording_texture texture; + auto const screen{queue.acquire(request(script_language::lua, script, "flood", &texture))}; + refresh(queue, screen, speed(0.0), 3); + REQUIRE(run_until(queue, [] { return false == sent_commands().empty(); })); + queue.update(); + // the long name is dropped, of the rest the first ones go + CHECK(sent_commands().size() == commands_per_call); + CHECK(sent_commands().front().first.param1 == 0.0); + CHECK(sent_commands().back().first.param1 == static_cast(commands_per_call - 1)); + // the command of the long name didn't get as far as the engine's command names + CHECK(log.lines_with("not found").empty()); + + auto const lines{log.lines_with("yyyyyyyyyy")}; + REQUIRE(false == lines.empty()); + CHECK(lines.size() <= log_lines_per_call); + auto const longest{std::ranges::max(lines, {}, [](std::string const &Line) { return Line.size(); })}; + CHECK(longest.size() < script.size() + log_line_length + 100); + queue.exit(); +} + +TEST_CASE("lua screens: a file larger than the limit, or a folder, reads as nothing") { + script_folder const folder{"lua_large_file"}; + folder.write("large.bin", std::string(screen_file_size + 1, 'x')); + folder.write("data/small.txt", std::string_view{"small"}); + CHECK(first_pixel(folder.write("file.lua", large_file_script), "file") == 255); +} + +TEST_CASE("lua screens: a script larger than the limit isn't loaded") { + script_folder const folder{"lua_large_script"}; + std::string code{"return { render = function(state) return eu07.image(1, 1, { 255, 255, 255 }) end }\n--"}; + code.append(screen_file_size, 'x'); + auto const script{folder.write("large.lua", code)}; + script_screen_queue queue; + REQUIRE(queue.init()); + + recording_texture texture; + auto const screen{queue.acquire(request(script_language::lua, script, "large", &texture))}; + refresh(queue, screen, speed(0.0), 1); + run_frames(queue); + CHECK_FALSE(queue.due(*screen)); + CHECK(texture.uploads == 0); + 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) +-- %b walks to the end of the subject from each opening character that nothing closes +local open = ("("):rep(1000000) +slow = slow and refused(string.find, open, '%b()') + and refused(string.gsub, open, '%b()', "") + and refused(function() for x in open:gmatch('%b()') do end end) +-- 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 calls = select(2, (("call(a, b) "):rep(10000)):gsub('%b()', "")) +local fast = lines == 10000 and key == "speed" and value == "120" and spaced == 300 and found and calls == 10000 + 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 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 = {} +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: 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); +} + +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 9e0bb7a92..af8678f2e 100644 --- a/tests/unit/test_script_screens.cpp +++ b/tests/unit/test_script_screens.cpp @@ -101,3 +101,146 @@ TEST_CASE("script screens: a screen reads files only below its own folder") { CHECK_FALSE(script_screens::is_safe_relative_path("\\windows")); CHECK_FALSE(script_screens::is_safe_relative_path("c:/windows/win.ini")); } + +TEST_CASE("script screens: the script of a screen is in the vehicle's folder, or from the game's, and not outside it") { + using script_screens::screen_script_path; + std::string const vehicle{"dynamic/pkp/ep07_v1/"}; + CHECK(screen_script_path(vehicle, "screen.lua") == "dynamic/pkp/ep07_v1/screen.lua"); + CHECK(screen_script_path(vehicle, "scripts/screen.lua") == "scripts/screen.lua"); + // a backslash isn't a folder to the game (substr_path), so the name goes in the vehicle's folder + CHECK(screen_script_path(vehicle, "lua\\screen.lua") == "dynamic/pkp/ep07_v1/lua\\screen.lua"); + + CHECK_FALSE(screen_script_path(vehicle, "../../../screen.lua").has_value()); + CHECK_FALSE(screen_script_path(vehicle, "scripts/../../screen.lua").has_value()); + CHECK_FALSE(screen_script_path(vehicle, "..\\..\\screen.lua").has_value()); + CHECK_FALSE(screen_script_path(vehicle, "/screen.lua").has_value()); + 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)); + // %b goes along the subject on its own: it counts where it ends the pattern too + CHECK(lua_pattern_cost("%b()", 999, false, true) == doctest::Approx(1000.0 * 1000 * 4)); + CHECK(lua_pattern_cost("(%b())", 999, false, true) == doctest::Approx(1000.0 * 1000 * 6)); + CHECK(lua_pattern_cost("%b().*", 999, false, true) == doctest::Approx(1000.0 * 1000 * 6)); + 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); +} + +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: %b counts the way from an opening character to the one that closes it") { + using script_screens::lua_pattern_cost; + using script_screens::max_pattern_cost; + // nothing closes: from each character to the end of the subject, the subject squared; whatever follows the %b + auto const open{std::string(1'000'000, '(')}; + CHECK(lua_pattern_cost("%b()", std::string_view{open}, false, true) > max_pattern_cost); + CHECK(lua_pattern_cost("%b()", std::string_view{open}, false, false) > max_pattern_cost); + CHECK(lua_pattern_cost("(%b())", std::string_view{open}, false, true) > max_pattern_cost); + CHECK(lua_pattern_cost("%b().*", std::string_view{open}, false, true) > max_pattern_cost); + CHECK(lua_pattern_cost("%b()x*", std::string_view{open}, false, true) > max_pattern_cost); + CHECK(lua_pattern_cost("%b()", std::string_view{open + open}, false, true) > max_pattern_cost); + CHECK(lua_pattern_cost("%b()", std::string_view{open}.substr(0, 10'000), false, true) > max_pattern_cost); + // the same with a hundred thousand of them, more than the openings held at a time + CHECK(lua_pattern_cost("%b()", std::string_view{open}.substr(0, 100'000), false, true) > max_pattern_cost); + // tried once from each position: the positions and the ways from the three openings, 2 + 5 + 2 + std::string_view const calls{"a(b)c(d(e))"}; + CHECK(lua_pattern_cost("%b()", calls, false, true) == doctest::Approx((12.0 + 9.0) * 4)); + CHECK(lua_pattern_cost("(%b())", calls, false, true) == doctest::Approx((12.0 + 9.0) * 6)); + // tried from the first position only, or after a repetition: the longest way of one try, and one + CHECK(lua_pattern_cost("^%b()", calls, false, true) == doctest::Approx(6.0 * 5)); + CHECK(lua_pattern_cost(".-%b()", calls, false, true) == doctest::Approx(12.0 * 12 * 6 * 6)); + // the same character opens and closes: to the next one + CHECK(lua_pattern_cost("%b\"\"", std::string_view{"a\"b\"c\""}, false, true) == doctest::Approx((7.0 + 5.0) * 4)); + // none in the subject: nothing to go along + CHECK(lua_pattern_cost("%b()", std::string_view{"abc"}, false, true) == doctest::Approx(4.0 * 4)); + // a long text of short calls is cheap, and so is one opening left unclosed in it + std::string text; + while (text.size() < 100'000) { + text += "call(a, b) "; + } + CHECK(lua_pattern_cost("%b()", std::string_view{text}, false, true) < max_pattern_cost); + text[9] = ' '; + CHECK(lua_pattern_cost("%b()", std::string_view{text}, false, true) < max_pattern_cost); + // nested deep, the ways add up to the subject squared again + auto const nested{std::string(20'000, '(') + std::string(20'000, ')')}; + CHECK(lua_pattern_cost("%b()x", std::string_view{nested}, false, true) > max_pattern_cost); + // malformed: the function raises its error + CHECK(lua_pattern_cost("%b(", std::string_view{open}, false, true) > 0.0); +} + +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); +} diff --git a/vehicle/DynObj.cpp b/vehicle/DynObj.cpp index d4b7ea7f4..63ef91f12 100644 --- a/vehicle/DynObj.cpp +++ b/vehicle/DynObj.cpp @@ -317,9 +317,13 @@ namespace { void deserialize_script_sign( cParser &Parser, script_screens::screen_config &Sign, std::string const &Folder ) { Sign.deserialize( Parser ); - if( false == Sign.script.empty() - && substr_path( Sign.script ).empty() ) { - Sign.script = Folder + Sign.script; + if( Sign.script.empty() ) { return; } + if( auto path { script_screens::screen_script_path( Folder, Sign.script ) }; path.has_value() ) { + Sign.script = std::move( *path ); + } + else { + ErrorLog( "Bad script sign: \"" + Sign.script + "\" leads outside the game's folder" ); + Sign.script.clear(); } } @@ -8173,6 +8177,10 @@ std::shared_ptr TDynamicObject::draw_script_texture( std::string auto const script { Name.substr( 5, query == std::string::npos ? std::string::npos : query - 5 ) }; auto const language { script_language_of( script ) }; if( false == language.has_value() ) { return nullptr; } // a python texture, made by the texture itself + if( false == script_screens::screen_script_path( "", script ).has_value() ) { + ErrorLog( "Bad script texture: \"" + script + "\" leads outside the game's folder" ); + return nullptr; + } auto &queue { Application.screens() }; auto &texture { GfxRenderer->Texture( GfxRenderer->Material( Material )->GetTexture( 0 ) ) }; diff --git a/vehicle/Train.cpp b/vehicle/Train.cpp index 4b68cba95..9c5c9d500 100644 --- a/vehicle/Train.cpp +++ b/vehicle/Train.cpp @@ -10685,9 +10685,14 @@ void TTrain::load_script_screen(cParser &Parser, script_language const Language) { return; } - if (substr_path(entry.config.script).empty()) + if (auto path{script_screens::screen_script_path(DynamicObject->asBaseDir, entry.config.script)}; path.has_value()) { - entry.config.script = DynamicObject->asBaseDir + entry.config.script; + entry.config.script = std::move(*path); + } + else + { + ErrorLog(std::format("Bad script screen: \"{}\" leads outside the game's folder", entry.config.script)); + return; } TSubModel *submodel{nullptr};