From d6ce7168098b39b3cb41c3c1d80bcfb68010ac57 Mon Sep 17 00:00:00 2001 From: Isaac0-dev <62234577+Isaac0-dev@users.noreply.github.com> Date: Thu, 27 Feb 2025 15:43:26 +1000 Subject: [PATCH] smlua reduce key collisions and sanity check them --- src/pc/lua/smlua_utils.c | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/src/pc/lua/smlua_utils.c b/src/pc/lua/smlua_utils.c index 189db3fb8..82def95e8 100644 --- a/src/pc/lua/smlua_utils.c +++ b/src/pc/lua/smlua_utils.c @@ -355,13 +355,16 @@ void smlua_push_object(lua_State* L, u16 lot, void* p, void *extraInfo) { } LUA_STACK_CHECK_BEGIN_NUM(1); - uintptr_t key = lot ^ (uintptr_t) p; + uintptr_t key = (lot * 0x9E3779B97F4A7C15) ^ ((uintptr_t)p >> 3); lua_rawgeti(L, LUA_REGISTRYINDEX, gSmLuaCObjects); lua_pushinteger(L, key); lua_gettable(L, -2); if (lua_isuserdata(L, -1)) { - lua_remove(L, -2); // Remove gSmLuaCObjects table - return; + const CObject *cobj = lua_touserdata(L, -1); + if (cobj && cobj->lot == lot && cobj->pointer == p) { + lua_remove(L, -2); // Remove gSmLuaCObjects table + return; + } } lua_pop(L, 1); @@ -387,13 +390,16 @@ void smlua_push_pointer(lua_State* L, u16 lvt, void* p, void *extraInfo) { } LUA_STACK_CHECK_BEGIN_NUM(1); - uintptr_t key = lvt ^ (uintptr_t) p; + uintptr_t key = (lvt * 0x9E3779B97F4A7C15) ^ ((uintptr_t)p >> 3); lua_rawgeti(L, LUA_REGISTRYINDEX, gSmLuaCPointers); lua_pushinteger(L, key); lua_gettable(L, -2); if (lua_isuserdata(L, -1)) { - lua_remove(L, -2); // Remove gSmLuaCPointers table - return; + const CPointer *cptr = lua_touserdata(L, 1); + if (cptr && cptr->lvt == lvt && cptr->pointer == p) { + lua_remove(L, -2); // Remove gSmLuaCPointers table + return; + } } lua_pop(L, 1);