Files
Library/src/Script/Lua.cpp
T

229 lines
6.4 KiB
C++

#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