3 Copyright (C) 2022 sfan5 <sfan5@live.de>
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU Lesser General Public License for more details.
15 You should have received a copy of the GNU Lesser General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
24 #include <unordered_set>
25 #include <unordered_map>
27 #include "c_internal.h"
30 #include "threading/mutex_auto_lock.h"
40 // convert negative index to absolute position on Lua stack
41 static inline int absidx(lua_State *L, int idx)
44 return lua_gettop(L) + idx + 1;
47 // does the type put anything into PackedInstr::sdata?
48 static inline bool uses_sdata(int type)
60 // does the type put anything into PackedInstr::<union>?
61 static inline bool uses_union(int type)
73 static inline bool can_set_into(int ktype, int vtype)
77 return !uses_union(vtype);
79 return !uses_sdata(vtype);
85 // is the key suitable for use with set_into?
86 static inline bool suitable_key(lua_State *L, int idx)
88 if (lua_type(L, idx) == LUA_TSTRING) {
89 // strings may not have a NULL byte (-> lua_setfield)
91 const char *str = lua_tolstring(L, idx, &len);
92 return strlen(str) == len;
94 assert(lua_type(L, idx) == LUA_TNUMBER);
95 // numbers must fit into an s32 and be integers (-> lua_rawseti)
96 lua_Number n = lua_tonumber(L, idx);
97 return std::floor(n) == n && n >= S32_MIN && n <= S32_MAX;
102 // checks if you left any values on the stack, for debugging
107 StackChecker(lua_State *L) : L(L), top(lua_gettop(L)) {}
109 assert(lua_gettop(L) >= top);
110 if (lua_gettop(L) > top) {
111 rawstream << "Lua stack not cleaned up: "
112 << lua_gettop(L) << " != " << top
113 << " (false-positive if exception thrown)" << std::endl;
118 // Since an std::vector may reallocate, this is the only safe way to keep
119 // a reference to a particular element.
120 template <typename T>
124 VectorRef(std::vector<T> *vec, size_t idx) : vec(vec), idx(idx) {}
126 static VectorRef<T> front(std::vector<T> &vec) {
127 return VectorRef(&vec, 0);
129 static VectorRef<T> back(std::vector<T> &vec) {
130 return VectorRef(&vec, vec.size() - 1);
132 T &operator*() { return (*vec)[idx]; }
133 T *operator->() { return &(*vec)[idx]; }
141 typedef std::pair<std::string, Packer> PackerTuple;
144 static inline auto emplace(PackedValue &pv, s16 type)
147 auto ref = VectorRef<PackedInstr>::back(pv.i);
149 // Initialize fields that may be left untouched
150 if (type == LUA_TTABLE) {
153 } else if (type == LUA_TUSERDATA) {
154 ref->ptrdata = nullptr;
155 } else if (type == INSTR_POP) {
162 // Management of registered packers
165 static std::unordered_map<std::string, Packer> g_packers;
166 static std::mutex g_packers_lock;
168 void script_register_packer(lua_State *L, const char *regname,
169 PackInFunc fin, PackOutFunc fout)
171 // Store away callbacks
173 MutexAutoLock autolock(g_packers_lock);
174 auto it = g_packers.find(regname);
175 if (it == g_packers.end()) {
176 auto &ref = g_packers[regname];
180 FATAL_ERROR_IF(it->second.fin != fin || it->second.fout != fout,
181 "Packer registered twice with mismatching callbacks");
185 // Save metatable so we can identify instances later
186 lua_rawgeti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_METATABLE_MAP);
187 if (lua_isnil(L, -1)) {
189 lua_pushvalue(L, -1);
190 lua_rawseti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_METATABLE_MAP);
193 luaL_getmetatable(L, regname);
194 FATAL_ERROR_IF(lua_isnil(L, -1), "No metatable registered with that name");
196 // CUSTOM_RIDX_METATABLE_MAP contains { [metatable] = "regname", ... }
198 lua_pushstring(L, regname);
200 if (!lua_isnil(L, -1)) {
201 FATAL_ERROR_IF(lua_topointer(L, -1) != lua_topointer(L, -2),
202 "Packer registered twice with inconsistent metatable");
206 lua_pushstring(L, regname);
212 static bool find_packer(const char *regname, PackerTuple &out)
214 MutexAutoLock autolock(g_packers_lock);
215 auto it = g_packers.find(regname);
216 if (it == g_packers.end())
218 // copy data for thread safety
219 out.first = it->first;
220 out.second = it->second;
224 static bool find_packer(lua_State *L, int idx, PackerTuple &out)
227 StackChecker checker(L);
230 // retrieve metatable of the object
231 if (lua_getmetatable(L, idx) != 1)
234 // use our global table to map it to the registry name
235 lua_rawgeti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_METATABLE_MAP);
236 assert(lua_istable(L, -1));
237 lua_pushvalue(L, -2);
239 if (lua_isnil(L, -1)) {
244 // load the associated data
245 bool found = find_packer(lua_tostring(L, -1), out);
246 FATAL_ERROR_IF(!found, "Inconsistent internal state");
252 // Packing implementation
255 // recursively goes through the structure and ensures there are no circular references
256 static void pack_validate(lua_State *L, int idx, std::unordered_set<const void*> &seen)
259 StackChecker checker(L);
263 if (lua_type(L, idx) != LUA_TTABLE)
266 const void *ptr = lua_topointer(L, idx);
269 if (seen.find(ptr) != seen.end())
270 throw LuaError("Circular references cannot be packed (yet)");
273 lua_checkstack(L, 5);
275 while (lua_next(L, idx) != 0) {
276 // key at -2, value at -1
277 pack_validate(L, absidx(L, -2), seen);
278 pack_validate(L, absidx(L, -1), seen);
286 static VectorRef<PackedInstr> pack_inner(lua_State *L, int idx, int vidx, PackedValue &pv)
289 StackChecker checker(L);
294 switch (lua_type(L, idx)) {
297 return emplace(pv, LUA_TNIL);
299 auto r = emplace(pv, LUA_TBOOLEAN);
300 r->bdata = lua_toboolean(L, idx);
304 auto r = emplace(pv, LUA_TNUMBER);
305 r->ndata = lua_tonumber(L, idx);
309 auto r = emplace(pv, LUA_TSTRING);
311 const char *str = lua_tolstring(L, idx, &len);
313 r->sdata.assign(str, len);
317 break; // execution continues
318 case LUA_TFUNCTION: {
319 auto r = emplace(pv, LUA_TFUNCTION);
320 call_string_dump(L, idx);
322 const char *str = lua_tolstring(L, -1, &len);
324 r->sdata.assign(str, len);
328 case LUA_TUSERDATA: {
330 if (!find_packer(L, idx, ser))
331 throw LuaError("Cannot serialize unsupported userdata");
332 pv.contains_userdata = true;
333 auto r = emplace(pv, LUA_TUSERDATA);
334 r->sdata = ser.first;
335 r->ptrdata = ser.second.fin(L, idx);
339 std::string err = "Cannot serialize type ";
340 err += lua_typename(L, lua_type(L, idx));
346 lua_checkstack(L, 5);
348 auto rtable = emplace(pv, LUA_TTABLE);
349 const int vi_table = vidx++;
352 while (lua_next(L, idx) != 0) {
353 // key at -2, value at -1
354 const int ktype = lua_type(L, -2), vtype = lua_type(L, -1);
355 if (ktype == LUA_TNUMBER)
356 rtable->uidata1++; // narr
358 rtable->uidata2++; // nrec
360 // check if we can use a shortcut
361 if (can_set_into(ktype, vtype) && suitable_key(L, -2)) {
362 // push only the value
363 auto rval = pack_inner(L, absidx(L, -1), vidx, pv);
364 rval->pop = vtype != LUA_TTABLE;
365 // and where to put it:
366 rval->set_into = vi_table;
367 if (ktype == LUA_TSTRING)
368 rval->sdata = lua_tostring(L, -2);
370 rval->sidata1 = lua_tointeger(L, -2);
371 // pop tables after the fact
373 auto ri1 = emplace(pv, INSTR_POP);
377 // push the key and value
378 pack_inner(L, absidx(L, -2), vidx, pv);
380 pack_inner(L, absidx(L, -1), vidx, pv);
382 // push an instruction to set them
383 auto ri1 = emplace(pv, INSTR_SETTABLE);
384 ri1->set_into = vi_table;
385 ri1->sidata1 = vidx - 2;
386 ri1->sidata2 = vidx - 1;
394 assert(vidx == vi_table + 1);
398 PackedValue *script_pack(lua_State *L, int idx)
401 idx = absidx(L, idx);
403 std::unordered_set<const void*> seen;
404 pack_validate(L, idx, seen);
405 assert(seen.size() == 0);
407 // Actual serialization
409 pack_inner(L, idx, 1, pv);
411 return new PackedValue(std::move(pv));
415 // Unpacking implementation
418 void script_unpack(lua_State *L, PackedValue *pv)
420 const int top = lua_gettop(L);
423 for (auto &i : pv->i) {
424 // If leaving values on stack make sure there's space (every 5th iteration)
425 if (!i.pop && (ctr++) >= 5) {
426 lua_checkstack(L, 5);
433 lua_pushvalue(L, top + i.sidata1); // key
434 lua_pushvalue(L, top + i.sidata2); // value
435 lua_rawset(L, top + i.set_into);
437 if (i.sidata1 != i.sidata2) {
438 // removing moves indices so pop higher index first
439 lua_remove(L, top + std::max(i.sidata1, i.sidata2));
440 lua_remove(L, top + std::min(i.sidata1, i.sidata2));
442 lua_remove(L, top + i.sidata1);
447 lua_remove(L, top + i.sidata1);
449 lua_remove(L, top + i.sidata2);
461 lua_pushboolean(L, i.bdata);
464 lua_pushnumber(L, i.ndata);
467 lua_pushlstring(L, i.sdata.data(), i.sdata.size());
470 lua_createtable(L, i.uidata1, i.uidata2);
473 luaL_loadbuffer(L, i.sdata.data(), i.sdata.size(), nullptr);
475 case LUA_TUSERDATA: {
477 sanity_check(find_packer(i.sdata.c_str(), ser));
478 ser.second.fout(L, i.ptrdata);
479 i.ptrdata = nullptr; // ownership taken by callback
489 lua_pushvalue(L, -1);
490 if (uses_sdata(i.type))
491 lua_rawseti(L, top + i.set_into, i.sidata1);
493 lua_setfield(L, top + i.set_into, i.sdata.c_str());
500 // as part of the unpacking process we take ownership of all userdata
501 pv->contains_userdata = false;
502 // leave exactly one value on the stack
503 lua_settop(L, top+1);
510 PackedValue::~PackedValue()
512 if (!contains_userdata)
514 for (auto &i : this->i) {
515 if (i.type == LUA_TUSERDATA && i.ptrdata) {
517 if (find_packer(i.sdata.c_str(), ser)) {
518 // tell it to deallocate object
519 ser.second.fout(nullptr, i.ptrdata);
528 // script_dump_packed
532 void script_dump_packed(const PackedValue *val)
534 printf("instruction stream: [\n");
535 for (const auto &i : val->i) {
539 printf("SETTABLE(%d, %d)", i.sidata1, i.sidata2);
542 printf(i.sidata2 ? "POP(%d, %d)" : "POP(%d)", i.sidata1, i.sidata2);
548 printf(i.bdata ? "true" : "false");
551 printf("%f", i.ndata);
554 printf("\"%s\"", i.sdata.c_str());
557 printf("table(%d, %d)", i.uidata1, i.uidata2);
560 printf("function(%d byte)", i.sdata.size());
563 printf("userdata %s %p", i.sdata.c_str(), i.ptrdata);
566 printf("!!UNKNOWN!!");
570 if (i.type >= 0 && uses_sdata(i.type))
571 printf(", k=%d, into=%d", i.sidata1, i.set_into);
572 else if (i.type >= 0)
573 printf(", k=\"%s\", into=%d", i.sdata.c_str(), i.set_into);
575 printf(", into=%d", i.set_into);