From 1bd7187db7166b998cb61b6a24294a8a8dcfe9a2 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Fri, 13 Nov 2026 14:25:18 +0100 Subject: [PATCH] fix(scripting): close the small holes in the script screen sandbox - Lua: once the instruction budget of a call is spent, the count hook runs at every instruction and raises again, so pcall, nested pcall and coroutine.resume can't swallow the limit; xpcall is rebuilt on pcall so its handler runs after the error left f, while the hook works - Lua: the metatables of eu07.image/font/sprite are locked (__metatable = false); __gc destroys only an object of its own type, once - Lua: read_png checks the size with stbi_info before decoding - Lua: string.rep makes no string over 1 MiB - Lua and WASM: at most 64 commands per call, names up to 64 bytes, 32 log lines per call cut at 1024 bytes; the drops are logged once - fonts: a glyph wider than 4096 is skipped; more than 4096 glyphs, 8192 columns or an image side over 4096 refuse the font; cut_glyph reads only the columns inside the image - the script path from the .mmd (cab screens, destination signs, make: textures) must stay inside the game folder; the files a screen reads, its script and its module must be regular files of 16 MiB at most Tests for each in test_script_screen_host.cpp, test_script_screen_drawing.cpp and test_script_screens.cpp; the test stubs can capture the log. --- scripting/luaprogram.cpp | 145 +++++++-- scripting/scriptscreendrawing.cpp | 21 +- scripting/scriptscreendrawing.h | 9 +- scripting/scriptscreenprogram.h | 35 ++ scripting/scriptscreenrules.cpp | 11 + scripting/scriptscreenrules.h | 6 + scripting/scriptscreens.cpp | 67 +++- scripting/wasmprogram.cpp | 29 +- tests/unit/engine_stubs.cpp | 34 ++ tests/unit/test_script_screen_drawing.cpp | 39 +++ tests/unit/test_script_screen_host.cpp | 369 +++++++++++++++++++++- tests/unit/test_script_screens.cpp | 16 + vehicle/DynObj.cpp | 14 +- vehicle/Train.cpp | 9 +- 14 files changed, 750 insertions(+), 54 deletions(-) diff --git a/scripting/luaprogram.cpp b/scripting/luaprogram.cpp index 36d95d271..4e3c0eea4 100644 --- a/scripting/luaprogram.cpp +++ b/scripting/luaprogram.cpp @@ -29,8 +29,6 @@ http://mozilla.org/MPL/2.0/. #include #include #include -#include -#include #include #include #include @@ -43,20 +41,28 @@ 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}; 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); } } @@ -71,6 +77,7 @@ 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 private: @@ -102,6 +109,11 @@ void count_hook(lua_State *L, lua_Debug * /*Debug*/) self->budget -= hook_interval; if (self->budget < 0) { + // from now on the hook runs at every instruction, and raises the error again. a script that catches it (pcall, + // xpcall, coroutine.resume) gets it again at its next instruction, so the error comes out of every level of the + // script in turn, and the call ends. run() sets the interval back for the next call. the hook is the state's, + // shared by its coroutines + lua_sethook(L, count_hook, LUA_MASKCOUNT, 1); luaL_error(L, "instruction limit exceeded"); } } @@ -120,12 +132,6 @@ template std::remove_cvref_t *push_object(lua_State *L, 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) { @@ -140,6 +146,19 @@ 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) + { + object->~Type_(); + lua_pushnil(L); + lua_setmetatable(L, 1); + } + return 0; +} + template Type_ &check_object(lua_State *L, int const Index, char const *Metatable) { auto *object{test_object(L, Index, Metatable)}; @@ -262,6 +281,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); @@ -362,9 +387,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; } @@ -388,7 +417,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; } @@ -663,6 +695,58 @@ 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; +} + +// xpcall(f, handler, ...). LuaJIT calls the handler where the error was raised, before the stack unwinds: for the error +// of the instruction hook that is while the hook still runs, when no hook is called, so a handler that loops would never +// be stopped. here f runs under pcall (the upvalue), and the handler is called, under pcall as well, once the error +// has left f. a script has no debug library to look at the stack with, so the handler gets what it got before +int api_xpcall(lua_State *L) +{ + auto const arguments{lua_gettop(L)}; + luaL_checkany(L, 2); + lua_pushvalue(L, lua_upvalueindex(1)); + lua_pushvalue(L, 1); + for (int idx = 3; idx <= arguments; ++idx) + { + lua_pushvalue(L, idx); + } + lua_call(L, arguments - 1, LUA_MULTRET); + if (lua_toboolean(L, arguments + 1) != 0) + { + // true and the results of f + return lua_gettop(L) - arguments; + } + // false and what the handler made of the error + auto const error{lua_gettop(L)}; + lua_pushboolean(L, 0); + lua_pushvalue(L, lua_upvalueindex(1)); + lua_pushvalue(L, 2); + lua_pushvalue(L, error); + lua_call(L, 2, 2); + // pcall(handler, error) gave true and the handler's value, or false and the handler's own error + lua_remove(L, -2); + return 2; +} + template void make_metatable(lua_State *L, char const *Name, std::array const &Methods, lua_CFunction Collect) { luaL_newmetatable(L, Name); @@ -679,6 +763,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); } @@ -747,7 +834,15 @@ void lua_program::open_libraries() lua_getglobal(m_state, LUA_STRLIBNAME); lua_pushnil(m_state); lua_setfield(m_state, -2, "dump"); + // string.rep with a cap on the length, around the library's own. strings share the table as their methods + lua_getfield(m_state, -1, "rep"); + lua_pushcclosure(m_state, api_repeat, 1); + lua_setfield(m_state, -2, "rep"); lua_pop(m_state, 1); + // xpcall made of pcall, see api_xpcall + lua_getglobal(m_state, "pcall"); + lua_pushcclosure(m_state, api_xpcall, 1); + lua_setglobal(m_state, "xpcall"); } void lua_program::register_api() @@ -757,9 +852,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) @@ -780,6 +875,9 @@ void lua_program::register_api() bool lua_program::run(int const Arguments, int const Results, std::string_view const What) { budget = instruction_limit; + // the interval, which the hook shortens once the budget of a call is spent + lua_sethook(m_state, count_hook, LUA_MASKCOUNT, hook_interval); + output.start_call(); if (0 == lua_pcall(m_state, Arguments, Results, 0)) { return true; @@ -804,14 +902,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; 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..86e59859b 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,14 @@ 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}; struct pending_command { @@ -86,6 +96,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..6f47565ef 100644 --- a/scripting/scriptscreenrules.cpp +++ b/scripting/scriptscreenrules.cpp @@ -123,4 +123,15 @@ 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 script_screens diff --git a/scripting/scriptscreenrules.h b/scripting/scriptscreenrules.h index d7d753841..37cf0bd83 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,9 @@ 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); + } // 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..697175c35 100644 --- a/tests/unit/test_script_screen_host.cpp +++ b/tests/unit/test_script_screen_host.cpp @@ -2,9 +2,9 @@ #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 "input/command.h" @@ -12,13 +12,16 @@ #include "utilities/Globals.h" #include "utilities/dictionary.h" +#include #include #include #include #include #include #include +#include #include +#include #include #include #include @@ -142,6 +145,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 +246,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 +402,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 +881,236 @@ 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(); +} + #endif diff --git a/tests/unit/test_script_screens.cpp b/tests/unit/test_script_screens.cpp index 9e0bb7a92..4fc688928 100644 --- a/tests/unit/test_script_screens.cpp +++ b/tests/unit/test_script_screens.cpp @@ -101,3 +101,19 @@ 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()); +} diff --git a/vehicle/DynObj.cpp b/vehicle/DynObj.cpp index 24810a2e7..002a03196 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(); } } @@ -8096,6 +8100,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 50659934c..f0324e85b 100644 --- a/vehicle/Train.cpp +++ b/vehicle/Train.cpp @@ -10625,9 +10625,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};