Skip to content

Commit e00aa51

Browse files
committed
Fix excessive backtracking in regex engine by introducing backtracking limit
The regex engine was prone to excessive backtracking, leading to timeouts and infinite loops, particularly with patterns involving nested quantifiers. This commit introduces a backtracking counter and a limit of 1000 backtracking steps. When this limit is exceeded, the regex engine aborts to prevent excessive backtracking.
1 parent d378a9f commit e00aa51

File tree

1 file changed

+6
-0
lines changed

1 file changed

+6
-0
lines changed

libregexp.c

+6
Original file line numberDiff line numberDiff line change
@@ -1929,6 +1929,7 @@ typedef struct {
19291929
/* 0 = 8 bit chars, 1 = 16 bit chars, 2 = 16 bit chars, UTF-16 */
19301930
int cbuf_type;
19311931
int capture_count;
1932+
int backtrack_count;
19321933
int stack_size_max;
19331934
BOOL multi_line;
19341935
BOOL ignore_case;
@@ -1995,6 +1996,10 @@ static intptr_t lre_exec_backtrack(REExecContext *s, uint8_t **capture,
19951996

19961997
for(;;) {
19971998
// printf("top=%p: pc=%d\n", th_list.top, (int)(pc - (bc_buf + RE_HEADER_LEN)));
1999+
if (++s->backtrack_count > 1000) {
2000+
return -1; // backtracking limit exceeded
2001+
}
2002+
19982003
opcode = *pc++;
19992004
switch(opcode) {
20002005
case REOP_match:
@@ -2401,6 +2406,7 @@ int lre_exec(uint8_t **capture,
24012406
s->ignore_case = (re_flags & LRE_FLAG_IGNORECASE) != 0;
24022407
s->is_unicode = (re_flags & LRE_FLAG_UNICODE) != 0;
24032408
s->capture_count = bc_buf[RE_HEADER_CAPTURE_COUNT];
2409+
s->backtrack_count = 0;
24042410
s->stack_size_max = bc_buf[RE_HEADER_STACK_SIZE];
24052411
s->cbuf = cbuf;
24062412
s->cbuf_end = cbuf + (clen << cbuf_type);

0 commit comments

Comments
 (0)