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.
This commit is contained in:
Roberto I
2026-01-11 15:36:03 -03:00
parent 5cfc725a8b
commit 2a7cf4f319
8 changed files with 118 additions and 16 deletions

20
ldo.c
View File

@@ -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))
/*