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] 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