From 3f81494d4b14f3a8d6be0f9e9a489f0d26c88e37 Mon Sep 17 00:00:00 2001 From: MihailRis Date: Sun, 24 May 2026 14:48:00 +0300 Subject: [PATCH] fix lua::bytearray_as_string --- src/logic/scripting/lua/lua_commons.hpp | 5 ++++ src/logic/scripting/lua/lua_util.cpp | 32 +++++++++++++++++++------ 2 files changed, 30 insertions(+), 7 deletions(-) diff --git a/src/logic/scripting/lua/lua_commons.hpp b/src/logic/scripting/lua/lua_commons.hpp index bb3163c86..8e77cbbc0 100644 --- a/src/logic/scripting/lua/lua_commons.hpp +++ b/src/logic/scripting/lua/lua_commons.hpp @@ -17,6 +17,11 @@ #error LuaJIT required #endif +#ifndef LUA_TCDATA +// unsafe, use for filtering only +#define LUA_TCDATA 10 +#endif + namespace lua { class luaerror : public std::runtime_error { public: diff --git a/src/logic/scripting/lua/lua_util.cpp b/src/logic/scripting/lua/lua_util.cpp index ddd05cd19..090e47a5d 100644 --- a/src/logic/scripting/lua/lua_util.cpp +++ b/src/logic/scripting/lua/lua_util.cpp @@ -6,6 +6,7 @@ #include "util/stringutil.hpp" #include "engine/Engine.hpp" +#include "debug/Logger.hpp" using namespace lua; @@ -13,6 +14,8 @@ static int next_environment = 1; std::unordered_map lua::usertypeNames; +static debug::Logger logger("lua-util"); + int lua::userdata_destructor(lua::State* L) { if (auto obj = touserdata(L, 1)) { obj->~Userdata(); @@ -371,10 +374,23 @@ void lua::remove_environment(State* L, int id) { store_env(L, id); } +static inline std::string_view bytearray_as_string_indirect(lua::State* L, int idx) { + requireglobal(L, "Bytearray_as_string"); + pushvalue(L, -2); + call(L, 1, 1); + auto view = tolstring(L, -1); + pop(L, 2); + return view; +} + std::string_view lua::bytearray_as_string(lua::State* L, int idx) { const auto& settings = scripting::engine->getSettings(); - if (type(L, idx) == LUA_TSTRING) { + + int luaType = type(L, idx); + if (luaType == LUA_TSTRING) { return tolstring(L, idx); + } else if (luaType == LUA_TTABLE) { + return bytearray_as_string_indirect(L, idx); } pushvalue(L, idx); @@ -383,16 +399,18 @@ std::string_view lua::bytearray_as_string(lua::State* L, int idx) { pushvalue(L, -2); call(L, 1, 2); auto view = tolstring(L, -2); + if (view == "0") { + if (luaType == LUA_TCDATA) { + logger.error() << "FFI-based Bytearray_as_ptr returned null-pointer"; + } + pop(L, 2); + return bytearray_as_string_indirect(L, idx); + } uint64_t size = touinteger(L, -1); auto ptr = (const char*)std::stoull(std::string(view), nullptr, 16); pop(L, 3); return std::string_view(ptr, size); } else { - requireglobal(L, "Bytearray_as_string"); - pushvalue(L, -2); - call(L, 1, 1); - auto view = tolstring(L, -1); - pop(L, 2); - return view; + return bytearray_as_string_indirect(L, idx); } }