Skip to content

Commit efddc23

Browse files
committed
Bug: wrong initialization in result from 'gmatch'
Function returned by 'string.gmatch' can be left in an inconsistent state after an error.
1 parent f1bb277 commit efddc23

2 files changed

Lines changed: 18 additions & 2 deletions

File tree

lstrlib.c

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -757,19 +757,25 @@ static int nospecials (const char *p, size_t l) {
757757
}
758758

759759

760+
/*
761+
** Prepare state for matches. These fields are not affected by each match.
762+
*/
760763
static void prepstate (MatchState *ms, lua_State *L,
761764
const char *s, size_t ls, const char *p, size_t lp) {
762765
ms->L = L;
763-
ms->matchdepth = MAXCCALLS;
764766
ms->src_init = s;
765767
ms->src_end = s + ls;
766768
ms->p_end = p + lp;
767769
}
768770

769771

772+
/*
773+
** (Re)prepare state for a match, setting fields that change during
774+
** each match.
775+
*/
770776
static void reprepstate (MatchState *ms) {
777+
ms->matchdepth = MAXCCALLS;
771778
ms->level = 0;
772-
lua_assert(ms->matchdepth == MAXCCALLS);
773779
}
774780

775781

testes/pm.lua

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -347,6 +347,16 @@ do -- init parameter in gmatch
347347
end
348348

349349

350+
do -- bug since 5.3
351+
local N = 20000
352+
local iter = string.gmatch(string.rep("a", N), string.rep("a?", N))
353+
pcall(iter) -- error for pattern too complex
354+
-- calling function again found recursion count ('matchdepth') equal
355+
-- to -1, so it did not detect next C-stack overflow
356+
pcall(iter)
357+
end
358+
359+
350360
-- tests for `%f' (`frontiers')
351361

352362
assert(string.gsub("aaa aa a aaa a", "%f[%w]a", "x") == "xaa xa x xaa x")

0 commit comments

Comments
 (0)