From ba490987982575018dc7c788a9fb21709653d3c7 Mon Sep 17 00:00:00 2001 From: Aleksey Selihov <1+faumaray@noreply@void.com> Date: Thu, 3 Dec 2026 07:02:45 +0000 Subject: [PATCH 1/6] feat(Script): bounded Lua evaluator with transactional host results (#17) --- cmake/Dependencies.cmake | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/cmake/Dependencies.cmake b/cmake/Dependencies.cmake index bad158b..901f89e 100644 --- a/cmake/Dependencies.cmake +++ b/cmake/Dependencies.cmake @@ -265,6 +265,43 @@ function(void_fetch_dependency DEP_NAME) endif() return() endif() + if(DEP_NAME STREQUAL "Lua") + if(TARGET Lua::Lua) + return() + endif() + # Prefer a system Lua 5.4 development package. + find_package(Lua 5.4 QUIET) + if(LUA_FOUND) + add_library(Lua::Lua INTERFACE IMPORTED) + set_property(TARGET Lua::Lua PROPERTY + INTERFACE_INCLUDE_DIRECTORIES "${LUA_INCLUDE_DIR}") + set_property(TARGET Lua::Lua PROPERTY + INTERFACE_LINK_LIBRARIES "${LUA_LIBRARIES}") + return() + endif() + + message(STATUS "[Void] Lua 5.4 not found - falling back to FetchContent") + FetchContent_Declare(Lua + URL https://www.lua.org/ftp/lua-5.4.9.tar.gz + URL_HASH SHA256=2335b6c582a52654f94612bf10d2f4672805d05329aa6568b1d8cd9e5c6fb8e6 + SYSTEM + ) + FetchContent_MakeAvailable(Lua) + file(GLOB _void_lua_sources "${lua_SOURCE_DIR}/src/*.c") + list(REMOVE_ITEM _void_lua_sources + "${lua_SOURCE_DIR}/src/lua.c" + "${lua_SOURCE_DIR}/src/luac.c") + add_library(void_lua STATIC ${_void_lua_sources}) + set_target_properties(void_lua PROPERTIES + POSITION_INDEPENDENT_CODE ON + C_STANDARD 99 + SYSTEM TRUE) + target_include_directories(void_lua SYSTEM PUBLIC + "${lua_SOURCE_DIR}/src") + add_library(Lua::Lua ALIAS void_lua) + return() + endif() + # FIXME: Add if needed external # if(DEP_NAME STREQUAL "glaze") # if(NOT glaze_POPULATED) -- 2.54.0 From 08038000ccb433f55528a1a95f63166bd6146e58 Mon Sep 17 00:00:00 2001 From: Aleksey Selihov <1+faumaray@noreply@void.com> Date: Thu, 3 Dec 2026 07:02:48 +0000 Subject: [PATCH 2/6] feat(Script): bounded Lua evaluator with transactional host results (#17) --- include/Void/Script/Lua.hpp | 58 +++++++++++++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 include/Void/Script/Lua.hpp diff --git a/include/Void/Script/Lua.hpp b/include/Void/Script/Lua.hpp new file mode 100644 index 0000000..33aa185 --- /dev/null +++ b/include/Void/Script/Lua.hpp @@ -0,0 +1,58 @@ +#pragma once + +#include + +#include +#include +#include +#include +#include + +namespace Void::Script +{ + +/// Host function: receives integer arguments, returns an integer or an error +/// message. It must not commit externally visible state itself; the evaluator +/// records each call in `Result::host_calls` so the caller can commit after a +/// successful evaluation. +using HostFunction = std::function( + std::span)>; + +struct Host { + std::string name; + HostFunction function; +}; + +/// Bounded Lua text evaluator. +/// +/// Each `evaluate` call creates a fresh, isolated Lua state, applies the +/// allocator, instruction and host-call limits, exposes the integer-keyed +/// inputs as `input[key]`, registers the host functions as globals, and runs +/// the chunk with a protected call. Only integer return values are accepted +/// and collected into an owned result. On failure the state is discarded, so +/// inputs and the caller's host state are untouched; a later valid evaluation +/// starts clean. +class LuaEvaluator +{ + public: + + explicit LuaEvaluator(Limits limits = Limits{}, + std::vector hosts = {}) + : limits_(limits) + , hosts_(std::move(hosts)) + { + } + + [[nodiscard]] const Limits& limits() const noexcept { return limits_; } + + [[nodiscard]] std::expected + evaluate(std::string_view source, + std::span inputs = {}) const; + + private: + + Limits limits_; + std::vector hosts_; +}; + +} // namespace Void::Script -- 2.54.0 From 025d97c6f66a974677d100d93a46d0063fb1be31 Mon Sep 17 00:00:00 2001 From: Aleksey Selihov <1+faumaray@noreply@void.com> Date: Thu, 3 Dec 2026 07:02:50 +0000 Subject: [PATCH 3/6] feat(Script): bounded Lua evaluator with transactional host results (#17) --- include/Void/Script/Types.hpp | 72 +++++++++++++++++++++++++++++++++++ 1 file changed, 72 insertions(+) create mode 100644 include/Void/Script/Types.hpp diff --git a/include/Void/Script/Types.hpp b/include/Void/Script/Types.hpp new file mode 100644 index 0000000..806ff42 --- /dev/null +++ b/include/Void/Script/Types.hpp @@ -0,0 +1,72 @@ +#pragma once + +#include +#include +#include +#include +#include + +namespace Void::Script +{ + +using Integer = std::int64_t; + +enum class ErrorKind : std::uint8_t { + compile = 0, + runtime, + allocator_limit, + instruction_limit, + host_call_limit, + result_limit, + host_error, + invalid_input, +}; + +struct Error { + ErrorKind kind{ErrorKind::runtime}; + std::string message; + + [[nodiscard]] bool operator==(const Error&) const = default; +}; + +struct Limits { + /// Total bytes the VM may allocate (including the state and libraries). + std::size_t max_allocator_bytes{1ULL * 1024ULL * 1024ULL}; + /// VM instructions before evaluation is aborted. + std::size_t max_instructions{100'000}; + /// Host function invocations before evaluation is aborted. + std::size_t max_host_calls{1'000}; + /// Maximum number of integer results collected. + std::size_t max_result_integers{1'024}; + /// Maximum number of integer-keyed inputs. + std::size_t max_inputs{256}; +}; + +/// Integer-keyed input exposed to the script as `input[key]`. +struct Input { + Integer key{0}; + Integer value{0}; + + [[nodiscard]] bool operator==(const Input&) const = default; +}; + +/// One host function call observed during a successful evaluation. The caller +/// may commit these effects after `evaluate` returns; the evaluator itself +/// never commits host state. +struct HostInvocation { + std::string host; + std::vector arguments; + Integer result{0}; + + [[nodiscard]] bool operator==(const HostInvocation&) const = default; +}; + +/// Owned result of a successful evaluation. +struct Result { + /// Integer values returned by the chunk, in order. + std::vector integers; + /// Host calls made by the script, in order. + std::vector host_calls; +}; + +} // namespace Void::Script -- 2.54.0 From 359e0630c7a1ad7a595a1e7f9244bdda2b1964d1 Mon Sep 17 00:00:00 2001 From: Aleksey Selihov <1+faumaray@noreply@void.com> Date: Thu, 3 Dec 2026 07:02:53 +0000 Subject: [PATCH 4/6] feat(Script): bounded Lua evaluator with transactional host results (#17) --- src/Script/Lua.cpp | 228 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 228 insertions(+) create mode 100644 src/Script/Lua.cpp diff --git a/src/Script/Lua.cpp b/src/Script/Lua.cpp new file mode 100644 index 0000000..6173997 --- /dev/null +++ b/src/Script/Lua.cpp @@ -0,0 +1,228 @@ +#include + +#include +#include +#include +#include +#include + +extern "C" { +#include +#include +#include +} + +namespace Void::Script +{ + +namespace +{ + +struct Context { + const Limits* limits{nullptr}; + const std::vector* hosts{nullptr}; + std::size_t used_bytes{0}; + std::size_t executed{0}; + std::size_t hook_step{1}; + std::size_t host_calls{0}; + bool allocator_limit_hit{false}; + bool instruction_limit_hit{false}; + bool host_call_limit_hit{false}; + std::string host_error; + std::vector invocations; +}; + +[[nodiscard]] Context* context_of(lua_State* state) +{ + return *static_cast(lua_getextraspace(state)); +} + +void* limited_alloc(void* user, void* pointer, std::size_t old_size, + std::size_t new_size) +{ + auto* context = static_cast(user); + if (new_size == 0) { + if (pointer != nullptr) { + context->used_bytes -= old_size; + std::free(pointer); + } + return nullptr; + } + const std::size_t current = pointer != nullptr ? old_size : 0; + if (new_size > current && + new_size - current > + context->limits->max_allocator_bytes - context->used_bytes) { + context->allocator_limit_hit = true; + return nullptr; + } + void* result = std::realloc(pointer, new_size); + if (result != nullptr) { + context->used_bytes = context->used_bytes - current + new_size; + } + return result; +} + +void instruction_hook(lua_State* state, lua_Debug*) +{ + Context* context = context_of(state); + context->executed += context->hook_step; + if (context->executed >= context->limits->max_instructions) { + context->instruction_limit_hit = true; + luaL_error(state, "instruction limit exceeded"); + } +} + +int host_trampoline(lua_State* state) +{ + Context* context = context_of(state); + const int argument_count = lua_gettop(state); + std::vector arguments; + arguments.reserve(static_cast(argument_count)); + for (int index = 1; index <= argument_count; ++index) { + int is_integer = 0; + const lua_Integer value = + lua_tointegerx(state, index, &is_integer); + if (is_integer == 0) { + return luaL_error(state, "host arguments must be integers"); + } + arguments.push_back(static_cast(value)); + } + + const auto host_index = static_cast( + lua_tointeger(state, lua_upvalueindex(1))); + const Host& host = (*context->hosts)[host_index]; + if (context->host_calls >= context->limits->max_host_calls) { + context->host_call_limit_hit = true; + return luaL_error(state, "host call limit exceeded"); + } + ++context->host_calls; + + auto result = host.function(arguments); + if (!result.has_value()) { + context->host_error = result.error(); + return luaL_error(state, "host '%s' failed: %s", + host.name.c_str(), result.error().c_str()); + } + context->invocations.push_back( + HostInvocation{.host = host.name, + .arguments = std::move(arguments), + .result = *result}); + lua_pushinteger(state, static_cast(*result)); + return 1; +} + +[[nodiscard]] std::string last_message(lua_State* state, + std::string_view fallback) +{ + const char* message = lua_tostring(state, -1); + return message != nullptr ? std::string{message} : std::string{fallback}; +} + +} // namespace + +std::expected + LuaEvaluator::evaluate(std::string_view source, + std::span inputs) const +{ + if (inputs.size() > limits_.max_inputs) { + return std::unexpected{Error{.kind = ErrorKind::invalid_input, + .message = "too many inputs"}}; + } + + Context context; + context.limits = &limits_; + context.hosts = &hosts_; + + lua_State* state = lua_newstate(limited_alloc, &context); + if (state == nullptr) { + return std::unexpected{ + Error{.kind = ErrorKind::allocator_limit, + .message = "cannot create Lua state"}}; + } + *static_cast(lua_getextraspace(state)) = &context; + + struct Library { + const char* name; + lua_CFunction open; + }; + const Library libraries[] = { + {LUA_GNAME, luaopen_base}, + {LUA_TABLIBNAME, luaopen_table}, + {LUA_STRLIBNAME, luaopen_string}, + {LUA_MATHLIBNAME, luaopen_math}, + {LUA_COLIBNAME, luaopen_coroutine}, + }; + for (const auto& library : libraries) { + luaL_requiref(state, library.name, library.open, 1); + lua_pop(state, 1); + } + + lua_createtable(state, 0, static_cast(inputs.size())); + for (const auto& input : inputs) { + lua_pushinteger(state, static_cast(input.value)); + lua_seti(state, -2, static_cast(input.key)); + } + lua_setglobal(state, "input"); + + for (std::size_t index = 0; index < hosts_.size(); ++index) { + lua_pushinteger(state, static_cast(index)); + lua_pushcclosure(state, host_trampoline, 1); + lua_setglobal(state, hosts_[index].name.c_str()); + } + + context.hook_step = + std::clamp(limits_.max_instructions, 1, 1000); + lua_sethook(state, instruction_hook, LUA_MASKCOUNT, + static_cast(context.hook_step)); + + if (luaL_loadbufferx(state, source.data(), source.size(), "chunk", "t") != + LUA_OK) { + std::string message = last_message(state, "compile error"); + lua_close(state); + return std::unexpected{ + Error{.kind = ErrorKind::compile, .message = std::move(message)}}; + } + + if (lua_pcall(state, 0, LUA_MULTRET, 0) != LUA_OK) { + std::string message = last_message(state, "runtime error"); + ErrorKind kind = ErrorKind::runtime; + if (context.allocator_limit_hit) { + kind = ErrorKind::allocator_limit; + } else if (context.instruction_limit_hit) { + kind = ErrorKind::instruction_limit; + } else if (context.host_call_limit_hit) { + kind = ErrorKind::host_call_limit; + } else if (!context.host_error.empty()) { + kind = ErrorKind::host_error; + } + lua_close(state); + return std::unexpected{ + Error{.kind = kind, .message = std::move(message)}}; + } + + Result result; + const int result_count = lua_gettop(state); + for (int index = 1; index <= result_count; ++index) { + int is_integer = 0; + const lua_Integer value = + lua_tointegerx(state, index, &is_integer); + if (is_integer == 0) { + lua_close(state); + return std::unexpected{ + Error{.kind = ErrorKind::runtime, + .message = "script results must be integers"}}; + } + if (result.integers.size() >= limits_.max_result_integers) { + lua_close(state); + return std::unexpected{ + Error{.kind = ErrorKind::result_limit, + .message = "result limit exceeded"}}; + } + result.integers.push_back(static_cast(value)); + } + result.host_calls = std::move(context.invocations); + lua_close(state); + return result; +} + +} // namespace Void::Script -- 2.54.0 From 2c6e4eab824da412390ce23b2270d48d2a16ade0 Mon Sep 17 00:00:00 2001 From: Aleksey Selihov <1+faumaray@noreply@void.com> Date: Thu, 3 Dec 2026 07:02:55 +0000 Subject: [PATCH 5/6] feat(Script): bounded Lua evaluator with transactional host results (#17) --- src/Script/module.cmake | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 src/Script/module.cmake diff --git a/src/Script/module.cmake b/src/Script/module.cmake new file mode 100644 index 0000000..a215abc --- /dev/null +++ b/src/Script/module.cmake @@ -0,0 +1,3 @@ +void_add_module(Script + EXTERNAL_DEPS Lua::Lua +) -- 2.54.0 From e8565c685745c35be64e46bbeb24a77eabefe10a Mon Sep 17 00:00:00 2001 From: Aleksey Selihov <1+faumaray@noreply@void.com> Date: Thu, 3 Dec 2026 07:02:57 +0000 Subject: [PATCH 6/6] feat(Script): bounded Lua evaluator with transactional host results (#17) --- tests/standalone/Script/Lua.cpp | 154 ++++++++++++++++++++++++++++++++ 1 file changed, 154 insertions(+) create mode 100644 tests/standalone/Script/Lua.cpp diff --git a/tests/standalone/Script/Lua.cpp b/tests/standalone/Script/Lua.cpp new file mode 100644 index 0000000..e8c4a5a --- /dev/null +++ b/tests/standalone/Script/Lua.cpp @@ -0,0 +1,154 @@ +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +namespace +{ + +using Void::Script::ErrorKind; +using Void::Script::Host; +using Void::Script::HostInvocation; +using Void::Script::Input; +using Void::Script::Integer; +using Void::Script::Limits; +using Void::Script::LuaEvaluator; + +[[nodiscard]] Host add_host() +{ + return Host{ + .name = "add", + .function = [](std::span arguments) + -> std::expected { + if (arguments.size() != 2) { + return std::unexpected{std::string{"add expects two arguments"}}; + } + return arguments[0] + arguments[1]; + }}; +} + +[[nodiscard]] Host fail_host() +{ + return Host{ + .name = "fail", + .function = [](std::span arguments) + -> std::expected { + if (!arguments.empty() && arguments[0] < 0) { + return std::unexpected{std::string{"negative"}}; + } + return arguments.empty() ? Integer{0} : arguments[0]; + }}; +} + +} // namespace + +Void::Testing::Test lua_evaluates_integer_results_and_inputs() +{ + LuaEvaluator evaluator; + const Input inputs[] = {Input{.key = 1, .value = 2}, + Input{.key = 2, .value = 3}}; + auto result = evaluator.evaluate("return input[1] + input[2]", inputs); + Void::Testing::require(result.has_value()); + Void::Testing::expect(result->integers == std::vector{5}); +} + +Void::Testing::Test lua_host_functions_are_recorded() +{ + LuaEvaluator evaluator{Limits{}, {add_host()}}; + auto result = evaluator.evaluate("return add(2, 3)"); + Void::Testing::require(result.has_value()); + Void::Testing::expect(result->integers == std::vector{5}); + Void::Testing::require(result->host_calls.size() == 1); + Void::Testing::expect(result->host_calls[0] == + HostInvocation{.host = "add", + .arguments = {2, 3}, + .result = 5}); +} + +Void::Testing::Test lua_host_error_is_structured_and_recovers() +{ + LuaEvaluator evaluator{Limits{}, {fail_host()}}; + auto failed = evaluator.evaluate("return fail(-1)"); + Void::Testing::require(!failed.has_value()); + Void::Testing::expect(failed.error().kind == ErrorKind::host_error); + + // A later valid evaluation starts from a clean state. + auto recovered = evaluator.evaluate("return fail(4)"); + Void::Testing::require(recovered.has_value()); + Void::Testing::expect(recovered->integers == std::vector{4}); +} + +Void::Testing::Test lua_instruction_limit() +{ + Limits limits; + limits.max_instructions = 1'000; + LuaEvaluator evaluator{limits}; + auto result = evaluator.evaluate("while true do end"); + Void::Testing::require(!result.has_value()); + Void::Testing::expect(result.error().kind == ErrorKind::instruction_limit); +} + +Void::Testing::Test lua_allocator_limit() +{ + Limits limits; + limits.max_allocator_bytes = 128 * 1024; + LuaEvaluator evaluator{limits}; + auto result = evaluator.evaluate( + "local s = string.rep('x', 1000000) return #s"); + Void::Testing::require(!result.has_value()); + Void::Testing::expect(result.error().kind == ErrorKind::allocator_limit); +} + +Void::Testing::Test lua_host_call_limit() +{ + Limits limits; + limits.max_host_calls = 2; + LuaEvaluator evaluator{limits, {fail_host()}}; + auto result = evaluator.evaluate("for i = 1, 10 do fail(i) end return 0"); + Void::Testing::require(!result.has_value()); + Void::Testing::expect(result.error().kind == ErrorKind::host_call_limit); +} + +Void::Testing::Test lua_compile_error() +{ + LuaEvaluator evaluator; + auto result = evaluator.evaluate("return ("); + Void::Testing::require(!result.has_value()); + Void::Testing::expect(result.error().kind == ErrorKind::compile); +} + +Void::Testing::Test lua_result_limit() +{ + Limits limits; + limits.max_result_integers = 2; + LuaEvaluator evaluator{limits}; + auto result = evaluator.evaluate("return 1, 2, 3"); + Void::Testing::require(!result.has_value()); + Void::Testing::expect(result.error().kind == ErrorKind::result_limit); +} + +Void::Testing::Test lua_rejects_non_integer_results() +{ + LuaEvaluator evaluator; + auto result = evaluator.evaluate("return 'text'"); + Void::Testing::require(!result.has_value()); + Void::Testing::expect(result.error().kind == ErrorKind::runtime); +} + +Void::Testing::Test lua_input_limit() +{ + Limits limits; + limits.max_inputs = 1; + LuaEvaluator evaluator{limits}; + const Input inputs[] = {Input{.key = 1, .value = 1}, + Input{.key = 2, .value = 2}}; + auto result = evaluator.evaluate("return 0", inputs); + Void::Testing::require(!result.has_value()); + Void::Testing::expect(result.error().kind == ErrorKind::invalid_input); +} -- 2.54.0