From be73f72fcc944a8ebae2c60d2ce84139acb011b9 Mon Sep 17 00:00:00 2001 From: Roberto Ierusalimschy Date: Tue, 18 Jun 2019 16:52:22 -0300 Subject: New function 'setCstacklimit' Added new functions to dynamically set the C-stack limit ('lua_setCstacklimit' in the C-API, 'debug.setCstacklimit' in Lua). --- lstate.c | 28 ++++++++++++++++++++++++++-- 1 file changed, 26 insertions(+), 2 deletions(-) (limited to 'lstate.c') diff --git a/lstate.c b/lstate.c index 296cec2a..92d5165a 100644 --- a/lstate.c +++ b/lstate.c @@ -96,6 +96,29 @@ void luaE_setdebt (global_State *g, l_mem debt) { } +LUA_API int lua_setCstacklimit (lua_State *L, unsigned int limit) { + global_State *g = G(L); + int ccalls; + luaE_freeCI(L); /* release unused CIs */ + ccalls = getCcalls(L); + if (limit >= 40000) + return 0; /* out of bounds */ + limit += CSTACKERR; + if (L != g-> mainthread) + return 0; /* only main thread can change the C stack */ + else if (ccalls <= CSTACKERR) + return 0; /* handling overflow */ + else { + int diff = limit - g->Cstacklimit; + if (ccalls + diff <= CSTACKERR) + return 0; /* new limit would cause an overflow */ + g->Cstacklimit = limit; /* set new limit */ + L->nCcalls += diff; /* correct 'nCcalls' */ + return limit - diff - CSTACKERR; /* success; return previous limit */ + } +} + + /* ** Decrement count of "C calls" and check for overflows. In case of ** a stack overflow, check appropriate error ("regular" overflow or @@ -121,7 +144,7 @@ void luaE_enterCcall (lua_State *L) { else if (ncalls >= CSTACKMARK) { /* not in error-handling zone; raise the error now */ L->nCcalls = (CSTACKMARK - 1); /* enter error-handling zone */ - luaG_runerror(L, "C stack overflow1"); + luaG_runerror(L, "C stack overflow"); } /* else stack is in the error-handling zone; allow message handler to work */ @@ -263,7 +286,7 @@ static void preinit_thread (lua_State *L, global_State *g) { L->stacksize = 0; L->twups = L; /* thread has no upvalues */ L->errorJmp = NULL; - L->nCcalls = LUAI_MAXCSTACK + CSTACKERR; + L->nCcalls = CSTACKTHREAD; L->hook = NULL; L->hookmask = 0; L->basehookcount = 0; @@ -365,6 +388,7 @@ LUA_API lua_State *lua_newstate (lua_Alloc f, void *ud) { preinit_thread(L, g); g->allgc = obj2gco(L); /* by now, only object is the main thread */ L->next = NULL; + g->Cstacklimit = L->nCcalls = LUAI_MAXCSTACK; g->frealloc = f; g->ud = ud; g->warnf = NULL; -- cgit v1.2.3-55-g6feb