Merge pull request 'Bounded Lua evaluator with transactional host results (#17)' (#33) from issue/17-bounded-lua into main
This commit was merged in pull request #33.
This commit is contained in:
commit
706383e13f
6 files changed
+552
No files matched your search
@@ -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)
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Script/Types.hpp>
|
||||
|
||||
#include <expected>
|
||||
#include <functional>
|
||||
#include <span>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
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::expected<Integer, std::string>(
|
||||
std::span<const Integer>)>;
|
||||
|
||||
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<Host> hosts = {})
|
||||
: limits_(limits)
|
||||
, hosts_(std::move(hosts))
|
||||
{
|
||||
}
|
||||
|
||||
[[nodiscard]] const Limits& limits() const noexcept { return limits_; }
|
||||
|
||||
[[nodiscard]] std::expected<Result, Error>
|
||||
evaluate(std::string_view source,
|
||||
std::span<const Input> inputs = {}) const;
|
||||
|
||||
private:
|
||||
|
||||
Limits limits_;
|
||||
std::vector<Host> hosts_;
|
||||
};
|
||||
|
||||
} // namespace Void::Script
|
||||
@@ -0,0 +1,72 @@
|
||||
#pragma once
|
||||
|
||||
#include <compare>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
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<Integer> 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<Integer> integers;
|
||||
/// Host calls made by the script, in order.
|
||||
std::vector<HostInvocation> host_calls;
|
||||
};
|
||||
|
||||
} // namespace Void::Script
|
||||
@@ -0,0 +1,228 @@
|
||||
#include <Void/Script/Lua.hpp>
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstdlib>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
extern "C" {
|
||||
#include <lauxlib.h>
|
||||
#include <lua.h>
|
||||
#include <lualib.h>
|
||||
}
|
||||
|
||||
namespace Void::Script
|
||||
{
|
||||
|
||||
namespace
|
||||
{
|
||||
|
||||
struct Context {
|
||||
const Limits* limits{nullptr};
|
||||
const std::vector<Host>* 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<HostInvocation> invocations;
|
||||
};
|
||||
|
||||
[[nodiscard]] Context* context_of(lua_State* state)
|
||||
{
|
||||
return *static_cast<Context**>(lua_getextraspace(state));
|
||||
}
|
||||
|
||||
void* limited_alloc(void* user, void* pointer, std::size_t old_size,
|
||||
std::size_t new_size)
|
||||
{
|
||||
auto* context = static_cast<Context*>(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<Integer> arguments;
|
||||
arguments.reserve(static_cast<std::size_t>(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<Integer>(value));
|
||||
}
|
||||
|
||||
const auto host_index = static_cast<std::size_t>(
|
||||
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<lua_Integer>(*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<Result, Error>
|
||||
LuaEvaluator::evaluate(std::string_view source,
|
||||
std::span<const Input> 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<Context**>(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<int>(inputs.size()));
|
||||
for (const auto& input : inputs) {
|
||||
lua_pushinteger(state, static_cast<lua_Integer>(input.value));
|
||||
lua_seti(state, -2, static_cast<lua_Integer>(input.key));
|
||||
}
|
||||
lua_setglobal(state, "input");
|
||||
|
||||
for (std::size_t index = 0; index < hosts_.size(); ++index) {
|
||||
lua_pushinteger(state, static_cast<lua_Integer>(index));
|
||||
lua_pushcclosure(state, host_trampoline, 1);
|
||||
lua_setglobal(state, hosts_[index].name.c_str());
|
||||
}
|
||||
|
||||
context.hook_step =
|
||||
std::clamp<std::size_t>(limits_.max_instructions, 1, 1000);
|
||||
lua_sethook(state, instruction_hook, LUA_MASKCOUNT,
|
||||
static_cast<int>(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<Integer>(value));
|
||||
}
|
||||
result.host_calls = std::move(context.invocations);
|
||||
lua_close(state);
|
||||
return result;
|
||||
}
|
||||
|
||||
} // namespace Void::Script
|
||||
@@ -0,0 +1,3 @@
|
||||
void_add_module(Script
|
||||
EXTERNAL_DEPS Lua::Lua
|
||||
)
|
||||
@@ -0,0 +1,154 @@
|
||||
#include <Void/Script/Lua.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Test.hpp>
|
||||
|
||||
#include <cstdint>
|
||||
#include <expected>
|
||||
#include <span>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <vector>
|
||||
|
||||
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<const Integer> arguments)
|
||||
-> std::expected<Integer, std::string> {
|
||||
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<const Integer> arguments)
|
||||
-> std::expected<Integer, std::string> {
|
||||
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<Integer>{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<Integer>{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<Integer>{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);
|
||||
}
|
||||
Reference in new issue
Block a user