338 lines
9.2 KiB
C++
338 lines
9.2 KiB
C++
#include <Void/Script/Lua.hpp>
|
|
|
|
#if defined(VOID_SCRIPT_HAS_LUA)
|
|
|
|
#include <algorithm>
|
|
#include <cstdlib>
|
|
#include <exception>
|
|
#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};
|
|
const CancelFunction* cancelled{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};
|
|
bool cancel_requested{false};
|
|
std::string host_error;
|
|
std::vector<Integer> scratch_arguments;
|
|
std::vector<HostInvocation> invocations;
|
|
};
|
|
|
|
[[nodiscard]] Context* context_of(lua_State* state)
|
|
{
|
|
return *static_cast<Context**>(lua_getextraspace(state));
|
|
}
|
|
|
|
/// Polls the cancellation callback. Exceptions thrown by the callback count as
|
|
/// a cancellation request so a misbehaving policy can never escape into Lua's
|
|
/// C error machinery.
|
|
[[nodiscard]] bool cancellation_pending(Context& context)
|
|
{
|
|
if (context.cancel_requested) {
|
|
return true;
|
|
}
|
|
if (context.cancelled == nullptr || !*context.cancelled) {
|
|
return false;
|
|
}
|
|
try {
|
|
if ((*context.cancelled)()) {
|
|
context.cancel_requested = true;
|
|
}
|
|
} catch (...) {
|
|
context.cancel_requested = true;
|
|
}
|
|
return context.cancel_requested;
|
|
}
|
|
|
|
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 >= context->used_bytes
|
|
? 0
|
|
: context->used_bytes - old_size;
|
|
std::free(pointer);
|
|
}
|
|
return nullptr;
|
|
}
|
|
const std::size_t current = pointer != nullptr ? old_size : 0;
|
|
const std::size_t limit = context->limits->max_allocator_bytes;
|
|
const std::size_t used = context->used_bytes;
|
|
if (new_size > current &&
|
|
(used > limit || new_size - current > limit - used)) {
|
|
context->allocator_limit_hit = true;
|
|
return nullptr;
|
|
}
|
|
void* result = std::realloc(pointer, new_size);
|
|
if (result != nullptr) {
|
|
context->used_bytes = used - current + new_size;
|
|
}
|
|
return result;
|
|
}
|
|
|
|
void instruction_hook(lua_State* state, lua_Debug*)
|
|
{
|
|
Context* context = context_of(state);
|
|
if (cancellation_pending(*context)) {
|
|
luaL_error(state, "evaluation cancelled");
|
|
}
|
|
context->executed += context->hook_step;
|
|
if (context->executed >= context->limits->max_instructions) {
|
|
context->instruction_limit_hit = true;
|
|
luaL_error(state, "instruction limit exceeded");
|
|
}
|
|
}
|
|
|
|
/// Removes the base-library entry points that reach outside the sandbox.
|
|
void harden_base(lua_State* state)
|
|
{
|
|
const char* const removed[] = {"load", "loadfile", "dofile",
|
|
"print", "collectgarbage"};
|
|
for (const char* name : removed) {
|
|
lua_pushnil(state);
|
|
lua_setglobal(state, name);
|
|
}
|
|
}
|
|
|
|
void open_bindings(lua_State* state, const Bindings& bindings)
|
|
{
|
|
struct Library {
|
|
bool enabled;
|
|
const char* name;
|
|
lua_CFunction open;
|
|
};
|
|
const Library libraries[] = {
|
|
{bindings.base, LUA_GNAME, luaopen_base},
|
|
{bindings.table, LUA_TABLIBNAME, luaopen_table},
|
|
{bindings.string, LUA_STRLIBNAME, luaopen_string},
|
|
{bindings.math, LUA_MATHLIBNAME, luaopen_math},
|
|
{bindings.coroutine, LUA_COLIBNAME, luaopen_coroutine},
|
|
};
|
|
for (const auto& library : libraries) {
|
|
if (!library.enabled) {
|
|
continue;
|
|
}
|
|
luaL_requiref(state, library.name, library.open, 1);
|
|
lua_pop(state, 1);
|
|
}
|
|
if (bindings.base) {
|
|
harden_base(state);
|
|
}
|
|
}
|
|
|
|
int host_trampoline(lua_State* state)
|
|
{
|
|
Context* context = context_of(state);
|
|
if (cancellation_pending(*context)) {
|
|
lua_pushliteral(state, "evaluation cancelled");
|
|
return lua_error(state);
|
|
}
|
|
|
|
std::vector<Integer>& arguments = context->scratch_arguments;
|
|
arguments.clear();
|
|
const int argument_count = lua_gettop(state);
|
|
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) {
|
|
lua_pushliteral(state, "host arguments must be integers");
|
|
return lua_error(state);
|
|
}
|
|
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;
|
|
lua_pushliteral(state, "host call limit exceeded");
|
|
return lua_error(state);
|
|
}
|
|
++context->host_calls;
|
|
|
|
bool succeeded = false;
|
|
Integer value = 0;
|
|
try {
|
|
auto result = host.function(arguments);
|
|
if (result.has_value()) {
|
|
succeeded = true;
|
|
value = *result;
|
|
} else {
|
|
context->host_error = result.error();
|
|
}
|
|
} catch (const std::exception& exception) {
|
|
context->host_error = exception.what();
|
|
} catch (...) {
|
|
context->host_error = "host threw an unknown exception";
|
|
}
|
|
|
|
if (!succeeded) {
|
|
lua_pushfstring(state, "host '%s' failed: %s", host.name.c_str(),
|
|
context->host_error.c_str());
|
|
return lua_error(state);
|
|
}
|
|
|
|
try {
|
|
context->invocations.push_back(
|
|
HostInvocation{.host = host.name,
|
|
.arguments = std::move(arguments),
|
|
.result = value});
|
|
} catch (...) {
|
|
lua_pushliteral(state, "host result allocation failed");
|
|
return lua_error(state);
|
|
}
|
|
lua_pushinteger(state, static_cast<lua_Integer>(value));
|
|
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
|
|
{
|
|
const Limits& limits = configuration_.limits;
|
|
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 = &configuration_.hosts;
|
|
context.cancelled = &configuration_.cancelled;
|
|
|
|
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;
|
|
|
|
open_bindings(state, configuration_.bindings);
|
|
|
|
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 < configuration_.hosts.size(); ++index) {
|
|
lua_pushinteger(state, static_cast<lua_Integer>(index));
|
|
lua_pushcclosure(state, host_trampoline, 1);
|
|
lua_setglobal(state, configuration_.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 (cancellation_pending(context)) {
|
|
lua_close(state);
|
|
return std::unexpected{
|
|
Error{.kind = ErrorKind::cancelled, .message = "evaluation cancelled"}};
|
|
}
|
|
|
|
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.cancel_requested) {
|
|
kind = ErrorKind::cancelled;
|
|
} 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
|
|
|
|
#else
|
|
|
|
namespace Void::Script
|
|
{
|
|
|
|
std::expected<Result, Error>
|
|
LuaEvaluator::evaluate(std::string_view, std::span<const Input>) const
|
|
{
|
|
return std::unexpected{
|
|
Error{.kind = ErrorKind::runtime,
|
|
.message = "Lua adapter not compiled in"}};
|
|
}
|
|
|
|
} // namespace Void::Script
|
|
|
|
#endif // VOID_SCRIPT_HAS_LUA
|