Skip to content

Commit 42d4058

Browse files
committed
Save stack space while handling errors
Because error handling (luaG_errormsg) uses slots from EXTRA_STACK, and some errors can recur (e.g., string overflow while creating an error message in 'luaG_runerror', or a C-stack overflow before calling the message handler), the code should use stack slots with parsimony. This commit fixes the bug "Lua-stack overflow when C stack overflows while handling an error".
1 parent e435aaa commit 42d4058

File tree

2 files changed

+8
-3
lines changed

2 files changed

+8
-3
lines changed

Diff for: ldebug.c

+4-1
Original file line numberDiff line numberDiff line change
@@ -824,8 +824,11 @@ l_noret luaG_runerror (lua_State *L, const char *fmt, ...) {
824824
va_start(argp, fmt);
825825
msg = luaO_pushvfstring(L, fmt, argp); /* format message */
826826
va_end(argp);
827-
if (isLua(ci)) /* if Lua function, add source:line information */
827+
if (isLua(ci)) { /* if Lua function, add source:line information */
828828
luaG_addinfo(L, msg, ci_func(ci)->p->source, getcurrentline(ci));
829+
setobjs2s(L, L->top - 2, L->top - 1); /* remove 'msg' from the stack */
830+
L->top--;
831+
}
829832
luaG_errormsg(L);
830833
}
831834

Diff for: lvm.c

+4-2
Original file line numberDiff line numberDiff line change
@@ -656,8 +656,10 @@ void luaV_concat (lua_State *L, int total) {
656656
/* collect total length and number of strings */
657657
for (n = 1; n < total && tostring(L, s2v(top - n - 1)); n++) {
658658
size_t l = vslen(s2v(top - n - 1));
659-
if (l_unlikely(l >= (MAX_SIZE/sizeof(char)) - tl))
659+
if (l_unlikely(l >= (MAX_SIZE/sizeof(char)) - tl)) {
660+
L->top = top - total; /* pop strings to avoid wasting stack */
660661
luaG_runerror(L, "string length overflow");
662+
}
661663
tl += l;
662664
}
663665
if (tl <= LUAI_MAXSHORTLEN) { /* is result a short string? */
@@ -672,7 +674,7 @@ void luaV_concat (lua_State *L, int total) {
672674
setsvalue2s(L, top - n, ts); /* create result */
673675
}
674676
total -= n-1; /* got 'n' strings to create 1 new */
675-
L->top -= n-1; /* popped 'n' strings and pushed one */
677+
L->top = top - (n - 1); /* popped 'n' strings and pushed one */
676678
} while (total > 1); /* repeat until only 1 result left */
677679
}
678680

0 commit comments

Comments
 (0)