From mboxrd@z Thu Jan 1 00:00:00 1970 Return-Path: Received: from [87.239.111.99] (localhost [127.0.0.1]) by dev.tarantool.org (Postfix) with ESMTP id 2607C187848C; Tue, 3 Mar 2026 13:01:18 +0300 (MSK) DKIM-Filter: OpenDKIM Filter v2.11.0 dev.tarantool.org 2607C187848C DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=tarantool.org; s=dev; t=1772532078; bh=EqnOWh16MuvebcBkIoFEaQYNAQ1HgZABUuBAZyGGo3U=; h=Date:To:Cc:References:In-Reply-To:Subject:List-Id: List-Unsubscribe:List-Archive:List-Post:List-Help:List-Subscribe: From:Reply-To:From; b=RQ7ky5Hc3AqBKBZnuJ5d8hGSk8LLoLzzeCN48afA3WtkpRGZ+nyIKPq0dlJp2Wb6V aSwyI5zwMJVDoj2aoQM6T6ek4/jrW27A2OtlU/5vymZKB4erjzl6XG1PnJ31l4GEsf lYqq4qfNhE/teAmzr/zjKDIFIz1c3poVSiGs5TQw= Received: from send105.i.mail.ru (send105.i.mail.ru [89.221.237.200]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature RSA-PSS (2048 bits) server-digest SHA256) (No client certificate requested) by dev.tarantool.org (Postfix) with ESMTPS id 718A9759591 for ; Tue, 3 Mar 2026 13:01:16 +0300 (MSK) DKIM-Filter: OpenDKIM Filter v2.11.0 dev.tarantool.org 718A9759591 Received: by exim-smtp-558f87dcd7-nplqj with esmtpa (envelope-from ) id 1vxMZ0-000000009lA-3q2N; Tue, 03 Mar 2026 13:01:15 +0300 Content-Type: multipart/alternative; boundary="------------v04Zw11welwf0aBl5dBHY0DG" Message-ID: Date: Tue, 3 Mar 2026 13:01:14 +0300 MIME-Version: 1.0 User-Agent: Mozilla Thunderbird To: Sergey Kaplun Cc: tarantool-patches@dev.tarantool.org References: <20260225115740.13924-1-skaplun@tarantool.org> Content-Language: en-US In-Reply-To: <20260225115740.13924-1-skaplun@tarantool.org> X-Mailru-Src: smtp X-4EC0790: 10 X-7564579A: 646B95376F6C166E X-77F55803: 4F1203BC0FB41BD9FE49BA1A5307ACBF1C1BD57BFC988F7EF7F8D7D731B23D2900894C459B0CD1B9D11B94888736CC515D1BE6A8D71B10A5DBBBBD35A6C2AE0255EF089F4B04F4B7E1C7414A75FA687D X-7FA49CB5: FF5795518A3D127A4AD6D5ED66289B5278DA827A17800CE73F64378C139886A6EA1F7E6F0F101C67BD4B6F7A4D31EC0BCC500DACC3FED6E28638F802B75D45FF8AA50765F7900637AC83A81C8FD4AD23D82A6BABE6F325AC2E85FA5F3EDFCBAA7353EFBB55337566CF7C7957E4725328CAF9678F30D8E9A0979DEA304FD760E0824E88E239DD02D8389733CBF5DBD5E913377AFFFEAFD269176DF2183F8FC7C0ECC8AC47CD0EDEFF8941B15DA834481FCF19DD082D7633A0EF3E4896CB9E6436389733CBF5DBD5E9D5E8D9A59859A8B6E232F00D8D26902CA471835C12D1D977C4224003CC836476EB9C4185024447017B076A6E789B0E975F5C1EE8F4F765FCC8F1E0D322511BFE3AA81AA40904B5D9CF19DD082D7633A0C84D3B47A649675F3AA81AA40904B5D98AA50765F790063715C16F4D43E65A23D81D268191BDAD3D3666184CF4C3C14F3FC91FA280E0CE3D1A620F70A64A45A98AA50765F79006372E808ACE2090B5E1725E5C173C3A84C3C5EA940A35A165FF2DBA43225CD8A89F10D407B19AF7F750156CCFE7AF13BCA4B5C8C57E37DE458BEDA766A37F9254B7 X-C1DE0DAB: 0D63561A33F958A561E321E62D61DE495002B1117B3ED69680CD822A5D8531EA69995D676B7B4CBE823CB91A9FED034534781492E4B8EEAD2B25D9E4C92BC8ACBDAD6C7F3747799A X-C8649E89: 1C3962B70DF3F0AD73CAD6646DEDE191716CD42B3DD1D34CAB70F9BE574AE9C625B6776AC983F447FC0B9F89525902EE6F57B2FD27647F25E66C117BDB76D659A37ED8F3DC33BF39E122AD99FB5655F08CEF3613B35B55EA5E2FA299154B5F8D7E441FE9977A3DF6B8341EE9D5BE9A0A70116C488E9DF4E722AA28A8BE305CF8BA644668E5927AC18CD93680B12512CF4C41F94D744909CE2512F26BEC029E55448553D2254B8D95CD72808BE417F3B9E0E7457915DAA85F X-D57D3AED: 3ZO7eAau8CL7WIMRKs4sN3D3tLDjz0dLbV79QFUyzQ2Ujvy7cMT6pYYqY16iZVKkSc3dCLJ7zSJH7+u4VD18S7Vl4ZUrpaVfd2+vE6kuoey4m4VkSEu53w8ahmwBjZKM/YPHZyZHvz5uv+WouB9+ObcCpyrx6l7KImUglyhkEat/+ysWwi0gdhEs0JGjl6ggRWTy1haxBpVdbIX1nthFXMZebaIdHP2ghjoIc/363UZI6Kf1ptIMVbwN8XFWZxQUeQ4QnxTY2M8= X-Mailru-Sender: C4F68CFF4024C8867DFDF7C7F258845875C4EACD91FCDF92F6A6F50B1491C035F97B117F12965F408AEC6356D7CE5FAA645D15D82EE4B272BD6E4642A116CA93524AA66B5ACBE6721EF430B9A63E2A504198E0F3ECE9B5443453F38A29522196 X-Mras: Ok Subject: Re: [Tarantool-patches] [PATCH luajit] FFI: Avoid dangling cts->L. X-BeenThere: tarantool-patches@dev.tarantool.org X-Mailman-Version: 2.1.34 Precedence: list List-Id: Tarantool development patches List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , From: Sergey Bronnikov via Tarantool-patches Reply-To: Sergey Bronnikov Errors-To: tarantool-patches-bounces@dev.tarantool.org Sender: "Tarantool-patches" This is a multi-part message in MIME format. --------------v04Zw11welwf0aBl5dBHY0DG Content-Type: text/plain; charset=UTF-8; format=flowed Content-Transfer-Encoding: 7bit Hi, Sergey, thanks for the patch! The bug is not reproduced without patch. CMake configuration: cmake -S . -B build -DCMAKE_BUILD_TYPE=Debug Sergey On 2/25/26 14:57, Sergey Kaplun wrote: > From: Mike Pall > > Reported by ZumiKua. > > (cherry picked from commit c94312d348e3530b369b4e517fce4c65df6cd270) > > When executing cdata finalizer on some lua_State, this state is set to > `cts->L`. If the state will be GC-ed and freed later, this reference > becomes dangling, so any FFI callback will use this invalid reference. > > This patch fixes it by setting `cts->L` to the `mainthread` on the > destruction of the referenced one. > > Sergey Kaplun: > * added the description and the test for the problem > > Part of tarantool/tarantool#12134 > --- > > Branch:https://github.com/tarantool/luajit/tree/skaplun/lj-1405-dangling-cts-L > Related issues: > *https://github.com/LuaJIT/LuaJIT/issues/1405 > *https://github.com/tarantool/tarantool/issues/12134 > > src/lj_state.c | 4 ++ > test/tarantool-c-tests/CMakeLists.txt | 2 + > .../lj-1405-dangling-cts-L.test.c | 72 +++++++++++++++++++ > 3 files changed, 78 insertions(+) > create mode 100644 test/tarantool-c-tests/lj-1405-dangling-cts-L.test.c > > diff --git a/src/lj_state.c b/src/lj_state.c > index 053e5ec9..2eec5857 100644 > --- a/src/lj_state.c > +++ b/src/lj_state.c > @@ -360,6 +360,10 @@ void LJ_FASTCALL lj_state_free(global_State *g, lua_State *L) > lj_assertG(L != mainthread(g), "free of main thread"); > if (obj2gco(L) == gcref(g->cur_L)) > setgcrefnull(g->cur_L); > +#if LJ_HASFFI > + if (ctype_ctsG(g) && ctype_ctsG(g)->L == L) /* Avoid dangling cts->L. */ > + ctype_ctsG(g)->L = mainthread(g); > +#endif > lj_func_closeuv(L, tvref(L->stack)); > lj_assertG(gcref(L->openupval) == NULL, "stale open upvalues"); > lj_mem_freevec(g, tvref(L->stack), L->stacksize, TValue); > diff --git a/test/tarantool-c-tests/CMakeLists.txt b/test/tarantool-c-tests/CMakeLists.txt > index 32a8add0..3bb20bff 100644 > --- a/test/tarantool-c-tests/CMakeLists.txt > +++ b/test/tarantool-c-tests/CMakeLists.txt > @@ -59,6 +59,8 @@ foreach(test_source ${tests}) > OUTPUT_NAME "${exe}${C_TEST_SUFFIX}" > RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}" > ) > + # Allow to call non-static functions via FFI. > + target_link_options(${exe} PRIVATE "-rdynamic") > target_link_libraries(${exe} libtest ${LUAJIT_LIBRARY}) > add_dependencies(tarantool-c-tests-build ${exe}) > > diff --git a/test/tarantool-c-tests/lj-1405-dangling-cts-L.test.c b/test/tarantool-c-tests/lj-1405-dangling-cts-L.test.c > new file mode 100644 > index 00000000..b4ed4970 > --- /dev/null > +++ b/test/tarantool-c-tests/lj-1405-dangling-cts-L.test.c > @@ -0,0 +1,72 @@ > +#include "lua.h" > + > +#include "test.h" > +#include "utils.h" > + > +/* XXX: Still need normal assert inside `call_callback()`. */ > +#undef NDEBUG > +#include > + > +typedef void (*callback_t)(void); > +static callback_t callback = NULL; > + > +/* Function to be called via FFI. */ > +extern void add_callback(callback_t cb) > +{ > + callback = cb; > +} > + > +static void call_callback(void) > +{ > + assert(callback != NULL); > + callback(); > +} > + > +static int dangling_cts_L(void *test_state) > +{ > + lua_State *L = utils_lua_init(); > + luaopen_ffi(L); > + const char code[] = { > + " local ffi = require('ffi') \n" \ > + " ffi.cdef [[ \n" \ > + " struct test { int a; }; \n" \ > + " void add_callback(void (*cb)(void a)); \n" \ > + /* Simple finalizer, nop. */ > + " int getpid(void); \n" \ > + " ]] \n" \ > + " \n" \ > + " local C = ffi.C \n" \ > + " \n" \ > + " local function nop() end \n" \ > + /* Collected later. Set `cts->L` in the finalizer. */ > + " ffi.gc(ffi.new('struct test'), C.getpid); \n" \ > + /* Callback to be called on the old `cts->L`. */ > + " C.add_callback(ffi.cast('void (*)(void)', nop)) \n" > + }; > + if (luaL_dostring(L, code) != LUA_OK) { > + test_comment("error running Lua chunk: %s", > + lua_tostring(L, -1)); > + bail_out("error running Lua chunk"); > + } > + lua_State* newL = lua_newthread(L); > + /* Remove `newL` from `L`. */ > + lua_pop(L, 1); > + /* Set `cts->L = newL` in the finalizer. */ > + lua_gc(newL, LUA_GCCOLLECT, 0); > + /* Just to be sure we don't use it anymore. */ > + newL = NULL; > + /* Collect `newL`. */ > + lua_gc(L, LUA_GCCOLLECT, 0); > + /* Use after free before the patch. */ > + call_callback(); > + utils_lua_close(L); > + return TEST_EXIT_SUCCESS; > +} > + > +int main(void) > +{ > + const struct test_unit tgroup[] = { > + test_unit_def(dangling_cts_L), > + }; > + return test_run_group(tgroup, NULL); > +} --------------v04Zw11welwf0aBl5dBHY0DG Content-Type: text/html; charset=UTF-8 Content-Transfer-Encoding: 7bit

Hi, Sergey,

thanks for the patch!

The bug is not reproduced without patch.

CMake configuration: cmake -S . -B build -DCMAKE_BUILD_TYPE=Debug

Sergey

On 2/25/26 14:57, Sergey Kaplun wrote:
From: Mike Pall <mike>

Reported by ZumiKua.

(cherry picked from commit c94312d348e3530b369b4e517fce4c65df6cd270)

When executing cdata finalizer on some lua_State, this state is set to
`cts->L`. If the state will be GC-ed and freed later, this reference
becomes dangling, so any FFI callback will use this invalid reference.

This patch fixes it by setting `cts->L` to the `mainthread` on the
destruction of the referenced one.

Sergey Kaplun:
* added the description and the test for the problem

Part of tarantool/tarantool#12134
---

Branch: https://github.com/tarantool/luajit/tree/skaplun/lj-1405-dangling-cts-L
Related issues:
* https://github.com/LuaJIT/LuaJIT/issues/1405
* https://github.com/tarantool/tarantool/issues/12134

 src/lj_state.c                                |  4 ++
 test/tarantool-c-tests/CMakeLists.txt         |  2 +
 .../lj-1405-dangling-cts-L.test.c             | 72 +++++++++++++++++++
 3 files changed, 78 insertions(+)
 create mode 100644 test/tarantool-c-tests/lj-1405-dangling-cts-L.test.c

diff --git a/src/lj_state.c b/src/lj_state.c
index 053e5ec9..2eec5857 100644
--- a/src/lj_state.c
+++ b/src/lj_state.c
@@ -360,6 +360,10 @@ void LJ_FASTCALL lj_state_free(global_State *g, lua_State *L)
   lj_assertG(L != mainthread(g), "free of main thread");
   if (obj2gco(L) == gcref(g->cur_L))
     setgcrefnull(g->cur_L);
+#if LJ_HASFFI
+  if (ctype_ctsG(g) && ctype_ctsG(g)->L == L)  /* Avoid dangling cts->L. */
+    ctype_ctsG(g)->L = mainthread(g);
+#endif
   lj_func_closeuv(L, tvref(L->stack));
   lj_assertG(gcref(L->openupval) == NULL, "stale open upvalues");
   lj_mem_freevec(g, tvref(L->stack), L->stacksize, TValue);
diff --git a/test/tarantool-c-tests/CMakeLists.txt b/test/tarantool-c-tests/CMakeLists.txt
index 32a8add0..3bb20bff 100644
--- a/test/tarantool-c-tests/CMakeLists.txt
+++ b/test/tarantool-c-tests/CMakeLists.txt
@@ -59,6 +59,8 @@ foreach(test_source ${tests})
     OUTPUT_NAME "${exe}${C_TEST_SUFFIX}"
     RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}"
   )
+  # Allow to call non-static functions via FFI.
+  target_link_options(${exe} PRIVATE "-rdynamic")
   target_link_libraries(${exe} libtest ${LUAJIT_LIBRARY})
   add_dependencies(tarantool-c-tests-build ${exe})
 
diff --git a/test/tarantool-c-tests/lj-1405-dangling-cts-L.test.c b/test/tarantool-c-tests/lj-1405-dangling-cts-L.test.c
new file mode 100644
index 00000000..b4ed4970
--- /dev/null
+++ b/test/tarantool-c-tests/lj-1405-dangling-cts-L.test.c
@@ -0,0 +1,72 @@
+#include "lua.h"
+
+#include "test.h"
+#include "utils.h"
+
+/* XXX: Still need normal assert inside `call_callback()`. */
+#undef NDEBUG
+#include <assert.h>
+
+typedef void (*callback_t)(void);
+static callback_t callback = NULL;
+
+/* Function to be called via FFI. */
+extern void add_callback(callback_t cb)
+{
+	callback = cb;
+}
+
+static void call_callback(void)
+{
+	assert(callback != NULL);
+	callback();
+}
+
+static int dangling_cts_L(void *test_state)
+{
+	lua_State *L = utils_lua_init();
+	luaopen_ffi(L);
+	const char code[] = {
+		" local ffi = require('ffi')                               \n" \
+		" ffi.cdef [[                                              \n" \
+		"   struct test { int a; };                                \n" \
+		"   void add_callback(void (*cb)(void a));                 \n" \
+		    /* Simple finalizer, nop. */
+		"   int getpid(void);                                      \n" \
+		" ]]                                                       \n" \
+		"                                                          \n" \
+		" local C = ffi.C                                          \n" \
+		"                                                          \n" \
+		" local function nop() end                                 \n" \
+		/* Collected later. Set `cts->L` in the finalizer. */
+		" ffi.gc(ffi.new('struct test'), C.getpid);                \n" \
+		/* Callback to be called on the old `cts->L`. */
+		" C.add_callback(ffi.cast('void (*)(void)', nop))          \n"
+	};
+	if (luaL_dostring(L, code) != LUA_OK) {
+		test_comment("error running Lua chunk: %s",
+			     lua_tostring(L, -1));
+		bail_out("error running Lua chunk");
+	}
+	lua_State* newL = lua_newthread(L);
+	/* Remove `newL` from `L`. */
+	lua_pop(L, 1);
+	/* Set `cts->L = newL` in the finalizer. */
+	lua_gc(newL, LUA_GCCOLLECT, 0);
+	/* Just to be sure we don't use it anymore. */
+	newL = NULL;
+	/* Collect `newL`. */
+	lua_gc(L, LUA_GCCOLLECT, 0);
+	/* Use after free before the patch. */
+	call_callback();
+	utils_lua_close(L);
+	return TEST_EXIT_SUCCESS;
+}
+
+int main(void)
+{
+	const struct test_unit tgroup[] = {
+		test_unit_def(dangling_cts_L),
+	};
+	return test_run_group(tgroup, NULL);
+}
--------------v04Zw11welwf0aBl5dBHY0DG--