mirror of
https://github.com/luau-lang/luau.git
synced 2025-01-08 04:19:09 +00:00
7345891f6b
Some userdata objects may need to support manual destruction in addition to automatic GC. For example, files, threads, GPU resources and objects with large external allocations. With Lua, a finalizer can be _generically_ called by invoking the __gc metamethod manually, but this is currently not possible with tagged userdata in Luau because it's not possible to query the destructor associated with an userdata. While it is possible to workaround this by duplicating the destructor table locally on client side (*), it's more convenient to deduplicate the data and get the destructor using the API instead. (*) Note: a separate destructor table for each VM may be required if the VMs use different set of tags. Implementation notes: 1. I first considered adding a typedef for lua_Destructor but unfortunately there are two kinds of destructors, one with and one without the lua_State* argument, so I decided against it at this point. Maybe it should be added later if the destructor API is unified (by dropping the Lua state pointer argument?). 2. For some reason the conformance test produced warning "qualifier applied to function type has no meaning; ignored" on VS2017 (possibly because the test framework does not like function pointers for some reason?). I silenced this by pulling out the test expressions from those CHECKs.
43 lines
1.3 KiB
C++
43 lines
1.3 KiB
C++
// This file is part of the Luau programming language and is licensed under MIT License; see LICENSE.txt for details
|
|
// This code is based on Lua 5.x implementation licensed under MIT License; see lua_LICENSE.txt for details
|
|
#include "ludata.h"
|
|
|
|
#include "lgc.h"
|
|
#include "lmem.h"
|
|
|
|
#include <string.h>
|
|
|
|
Udata* luaU_newudata(lua_State* L, size_t s, int tag)
|
|
{
|
|
if (s > INT_MAX - sizeof(Udata))
|
|
luaM_toobig(L);
|
|
Udata* u = luaM_newgco(L, Udata, sizeudata(s), L->activememcat);
|
|
luaC_init(L, u, LUA_TUSERDATA);
|
|
u->len = int(s);
|
|
u->metatable = NULL;
|
|
LUAU_ASSERT(tag >= 0 && tag <= 255);
|
|
u->tag = uint8_t(tag);
|
|
return u;
|
|
}
|
|
|
|
void luaU_freeudata(lua_State* L, Udata* u, lua_Page* page)
|
|
{
|
|
if (u->tag < LUA_UTAG_LIMIT)
|
|
{
|
|
lua_Destructor dtor = L->global->udatagc[u->tag];
|
|
// TODO: access to L here is highly unsafe since this is called during internal GC traversal
|
|
// certain operations such as lua_getthreaddata are okay, but by and large this risks crashes on improper use
|
|
if (dtor)
|
|
dtor(L, u->data);
|
|
}
|
|
else if (u->tag == UTAG_IDTOR)
|
|
{
|
|
void (*dtor)(void*) = nullptr;
|
|
memcpy(&dtor, &u->data + u->len - sizeof(dtor), sizeof(dtor));
|
|
if (dtor)
|
|
dtor(u->data);
|
|
}
|
|
|
|
|
|
luaM_freegco(L, u, sizeudata(u->len), u->memcat, page);
|
|
}
|