Commit 4ba5204f

4ba5204f5ea0Merged

Yukihiro "Matz" Matsumoto <[email protected]> · 6 months ago · 1 file · ~1 modified

Description

fix(regexp): cap code buffer growth to avoid uint32_t overflow (#821)

The bytecode emit hook doubled c->code_capa every time it ran out of room. Above 2^31, the next * 2 wrapped to 0 (or a small value), realloc'd a tiny buffer, then wrote past it.

Cap at 2^30 instructions before doubling, so the subsequent * 2 stays in uint32_t range. If we're already past the cap, raise through compile_error ("regexp too large"). Also check realloc return so OOM raises rather than dereferencing NULL.

Closes #821

Co-Authored-By: Claude Opus 4.7 [email protected]

Details

Commit
4ba5204f5ea0
Parent
eb1e6fbd518c

lib/regexp/re_compile.cmodifiedView file

@@ -45,8 +45,19 @@
4545 emit(re_compiler *c, uint8_t op, uint8_t a, uint16_t offset)
4646 {
4747 if (c->code_len >= c->code_capa) {
48- c->code_capa = c->code_capa ? c->code_capa * 2 : 64;
49- c->code = (re_inst*)realloc(c->code, sizeof(re_inst) * c->code_capa);
48+ /* Issue #821: detect uint32_t overflow on doubling. The previous
49+ form silently wrapped to a small value (e.g. 2^31 doubles to
50+ 0), realloc'd a tiny buffer, then wrote past it. Cap at
51+ (UINT32_MAX / 2) before doubling so the next * 2 stays in
52+ range; if we're already past that, raise instead of overflowing. */
53+ if (c->code_capa > (uint32_t)0x40000000u) {
54+ compile_error(c, "regexp too large");
55+ }
56+ uint32_t new_capa = c->code_capa ? c->code_capa * 2 : 64;
57+ re_inst *nc = (re_inst*)realloc(c->code, sizeof(re_inst) * new_capa);
58+ if (!nc) compile_error(c, "regexp too large");
59+ c->code = nc;
60+ c->code_capa = new_capa;
5061 }
5162 uint32_t pos = c->code_len++;
5263 c->code[pos].op = op;