From 3a3b2d12c9d1fd7fa007cf6b54b42850ea7632d0 Mon Sep 17 00:00:00 2001 From: maelstrom Date: Tue, 27 May 2025 22:13:45 +0200 Subject: [PATCH] fix(lua): use-after-free in signal connection (thread) --- core/src/datatypes/signal.cpp | 22 ++++++++++++++++++---- core/src/datatypes/signal.h | 2 +- 2 files changed, 19 insertions(+), 5 deletions(-) diff --git a/core/src/datatypes/signal.cpp b/core/src/datatypes/signal.cpp index 5fbec19..e0ae5ca 100644 --- a/core/src/datatypes/signal.cpp +++ b/core/src/datatypes/signal.cpp @@ -2,6 +2,8 @@ #include "datatypes/base.h" #include "meta.h" #include "lua.h" +#include +#include #include #include #include @@ -22,24 +24,36 @@ LuaSignalConnection::LuaSignalConnection(lua_State* L, std::weak_ptr par // https://stackoverflow.com/a/31952046/16255372 - // Save function so it doesn't get GC'd + // Save function and current thread so they don't get GC'd function = luaL_ref(L, LUA_REGISTRYINDEX); + lua_pushthread(L); + thread = luaL_ref(L, LUA_REGISTRYINDEX); } LuaSignalConnection::~LuaSignalConnection() { // Remove LuaSignalConnectionthread so that it can get properly GC'd luaL_unref(state, LUA_REGISTRYINDEX, function); + luaL_unref(state, LUA_REGISTRYINDEX, thread); } static void stackdump(lua_State* L) { - for (int i = lua_gettop(L); i >= 1; i--) { - printf("Obj: %s\n", lua_typename(L, lua_type(L, i))); + printf("%d\n", lua_gettop(L)); + fflush(stdout); + lua_getfield(L, LUA_GLOBALSINDEX, "tostring"); + for (int i = lua_gettop(L)-1; i >= 1; i--) { + lua_pushvalue(L, -1); + lua_pushvalue(L, i); + lua_call(L, 1, 1); + const char* str = lua_tostring(L, -1); + lua_pop(L, 1); + printf("%s: %s\n", lua_typename(L, lua_type(L, i)), str); } + lua_pop(L, 1); printf("\n\n"); + fflush(stdout); } void LuaSignalConnection::Call(std::vector args) { - // stackdump(state); lua_State* thread = lua_newthread(state); // Push function diff --git a/core/src/datatypes/signal.h b/core/src/datatypes/signal.h index 9d2e096..5b23652 100644 --- a/core/src/datatypes/signal.h +++ b/core/src/datatypes/signal.h @@ -44,7 +44,7 @@ public: class LuaSignalConnection : public SignalConnection { lua_State* state; - int function; + int function, thread; friend Signal; protected: