From 2a7cf4f319fc276f4554a8f6364e6b1ba4eb2ded Mon Sep 17 00:00:00 2001 From: Roberto I Date: Sun, 11 Jan 2026 15:36:03 -0300 Subject: More effort in avoiding errors in finalizers Before calling a finalizer, Lua not only checks stack limits, but actually ensures that a minimum number of slots are already allocated for the call. (If it cannot ensure that, it postpones the finalizer.) That avoids finalizers not running due to memory errors that the programmer cannot control. --- ldo.c | 20 ++++++++++++++------ 1 file changed, 14 insertions(+), 6 deletions(-) (limited to 'ldo.c') diff --git a/ldo.c b/ldo.c index 6d0184ec..12e0364b 100644 --- a/ldo.c +++ b/ldo.c @@ -221,13 +221,21 @@ l_noret luaD_errerr (lua_State *L) { /* -** Check whether stack has enough space to run a simple function (such -** as a finalizer): At least BASIC_STACK_SIZE in the Lua stack and -** 2 slots in the C stack. +** Check whether stacks have enough space to run a simple function (such +** as a finalizer): At least BASIC_STACK_SIZE in the Lua stack, two +** available CallInfos, and two "slots" in the C stack. */ int luaD_checkminstack (lua_State *L) { - return ((stacksize(L) < MAXSTACK - BASIC_STACK_SIZE) && - (getCcalls(L) < LUAI_MAXCCALLS - 2)); + if (getCcalls(L) >= LUAI_MAXCCALLS - 2) + return 0; /* not enough C-stack slots */ + if (L->ci->next == NULL && luaE_extendCI(L, 0) == NULL) + return 0; /* unable to allocate first ci */ + if (L->ci->next->next == NULL && luaE_extendCI(L, 0) == NULL) + return 0; /* unable to allocate second ci */ + if (L->stack_last.p - L->top.p >= BASIC_STACK_SIZE) + return 1; /* enough (BASIC_STACK_SIZE) free slots in the Lua stack */ + else /* try to grow stack to a size with enough free slots */ + return luaD_growstack(L, BASIC_STACK_SIZE, 0); } @@ -616,7 +624,7 @@ void luaD_poscall (lua_State *L, CallInfo *ci, int nres) { -#define next_ci(L) (L->ci->next ? L->ci->next : luaE_extendCI(L)) +#define next_ci(L) (L->ci->next ? L->ci->next : luaE_extendCI(L, 1)) /* -- cgit v1.2.3-55-g6feb