Skip to content

Commit

Permalink
Fix segfault when Lua calls into a finalised script-bound object
Browse files Browse the repository at this point in the history
  • Loading branch information
GinjaNinja32 committed Sep 6, 2024
1 parent 7b4ceb8 commit 053d0e5
Showing 1 changed file with 22 additions and 0 deletions.
22 changes: 22 additions & 0 deletions src/scriptInterfaceMagic.h
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,16 @@ struct convert<T*>
lua_pushstring(L, "__ptr");
lua_rawget(L, idx++);

if (!lua_isuserdata(L, -1))
{
ptr = NULL;
if (lua_rawequal(L, -1, -2))
return; // GCed object, just convert to NULL
const char *msg = lua_pushfstring(L, "Object expected, got table");
luaL_argerror(L, idx-1, msg);
return;
}

P<PObject>** p = static_cast< P<PObject>** >(lua_touserdata(L, -1));
lua_pop(L, 1);
if (p == NULL)
Expand Down Expand Up @@ -155,6 +165,13 @@ struct convert<P<T>>
}
lua_pushstring(L, "__ptr");
lua_rawget(L, idx++);
if (!lua_isuserdata(L, -1))
{
ptr = NULL;
const char* msg = lua_pushfstring(L, "Object expected, got %s", lua_rawequal(L, -1, -2) ? "destroyed object" : "table");
luaL_argerror(L, idx-1, msg);
return;
}

P<PObject>** p = static_cast< P<PObject>** >(lua_touserdata(L, -1));
lua_pop(L, 1);
Expand Down Expand Up @@ -531,6 +548,11 @@ template<class T> class scriptBindObject
PT* p = static_cast< PT* >(lua_touserdata(L, -1));
if (*p)
delete *p;

// Clear the __ptr so we don't try to deref it if Lua can still see this table
lua_pushstring(L, "__ptr");
lua_pushvalue(L, -3); // set `v.__ptr = v` for easy checking that this has happened later
lua_rawset(L, -4);
}
lua_pop(L, 1);
return 0;
Expand Down

0 comments on commit 053d0e5

Please sign in to comment.