Fix stack overflow relimit handling.

Thanks to Sergey Kaplun. #1471
This commit is contained in:
Mike Pall 2026-06-16 11:12:21 +02:00
parent 72d2061ae2
commit d2c1327f57

View File

@ -34,8 +34,9 @@
#define LJ_STACK_MAX LUAI_MAXSTACK /* Max. stack size. */
#define LJ_STACK_START (2*LJ_STACK_MIN) /* Starting stack size. */
#define LJ_STACK_MAXEX (LJ_STACK_MAX + 1 + LJ_STACK_EXTRA)
#define LJ_STACK_ERREX (1 + 2*LJ_STACK_MIN) /* Extra for error handling. */
/* Explanation of LJ_STACK_EXTRA:
/* Explanation for LJ_STACK_EXTRA:
**
** Calls to metamethods store their arguments beyond the current top
** without checking for the stack limit. This avoids stack resizes which
@ -47,6 +48,11 @@
** one extra slot if mobj is not a function. Only lj_meta_tset needs 5
** slots above top, but then mobj is always a function. So we can get by
** with 5 extra slots.
**
** Explanation for LJ_STACK_ERREX:
**
** The 1 is space for the error message, and 2 * LJ_STACK_MIN is for
** the lj_state_checkstack() call in lj_err_run().
*/
/* Resize stack slots and adjust pointers in state. */
@ -78,7 +84,8 @@ static void resizestack(lua_State *L, MSize n)
/* Relimit stack after error, in case the limit was overdrawn. */
void lj_state_relimitstack(lua_State *L)
{
if (L->stacksize > LJ_STACK_MAXEX && L->top-tvref(L->stack) < LJ_STACK_MAX-1)
if (L->stacksize > LJ_STACK_MAXEX &&
L->top-tvref(L->stack) < LJ_STACK_MAX - 1 - LJ_STACK_ERREX)
resizestack(L, LJ_STACK_MAX);
}
@ -119,11 +126,9 @@ void LJ_FASTCALL lj_state_growstack(lua_State *L, MSize need)
/* An error handler might want to inspect the stack overflow error, but
** will need some stack space to run in. We give it a stack size beyond
** the normal limit in order to do so, then rely on lj_state_relimitstack
** calls during unwinding to bring us back to a convential stack size.
** The + 1 is space for the error message, and 2 * LUA_MINSTACK is for
** the lj_state_checkstack() call in lj_err_run().
** calls during unwinding to bring us back to a conventional stack size.
*/
resizestack(L, LJ_STACK_MAX + 1 + 2 * LUA_MINSTACK);
resizestack(L, LJ_STACK_MAX + LJ_STACK_ERREX);
lj_err_stkov(L); /* May invoke an error handler. */
} else {
/* If we're here, then the stack overflow error handler is requesting