From d2c1327f57dc96f6ed8b11474f3bc5e09a9d227a Mon Sep 17 00:00:00 2001 From: Mike Pall Date: Tue, 16 Jun 2026 11:12:21 +0200 Subject: Fix stack overflow relimit handling. Thanks to Sergey Kaplun. #1471 --- src/lj_state.c | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) (limited to 'src') diff --git a/src/lj_state.c b/src/lj_state.c index 302c721c1..d1eff6174 100644 --- a/src/lj_state.c +++ b/src/lj_state.c @@ -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 -- cgit v1.2.3-55-g6feb