Commit 62496fbc

62496fbccef0Merged

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

Description

fix(regexp): parse_quantifier overflow + min>max checks (#819, #822)

Two bounds issues in the same function -- {N,M} parser:

  • #819: min/max = ... * 10 + digit silently wrapped to negative for large quantifiers (e.g. {2147483648}). CRuby raises RegexpError "too big number"; spinel emitted bogus bytecode and ran the surrounding loop forever. Cap each quantifier at 100000 (much larger than any reasonable pattern but small enough that the emit loop can't loop forever) and raise compile_error if the digit accumulator would exceed it.
  • #822: {7,3} (min > max) used to compile silently, then produce no matches at runtime. CRuby raises RegexpError; emit the same.

Both checks call compile_error which today fprintf+exit(1). That's a known limitation (#781) -- a follow-up commit will introduce an extern raise hook so the library can route through sp_raise_cls without violating per-translation-unit static inline linkage.

Closes #819 Closes #822

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

Details

Commit
62496fbccef0
Parent
4ba5204f5ea0

lib/regexp/re_compile.cmodifiedView file

@@ -33,6 +33,12 @@
3333
3434 static void compile_alt(re_compiler *c); /* forward */
3535
36+/* Issue #781: kept exit(1) for now -- routing through sp_raise_cls
37+ would require a non-static linkage hook (the runtime's
38+ sp_raise_cls is `static inline` per translation unit, so the
39+ library cannot reference the user program's copy directly). A
40+ later commit can introduce an extern raise hook + populate it
41+ from the user program. */
3642 static void
3743 compile_error(re_compiler *c, const char *msg)
3844 {
@@ -313,17 +319,31 @@
313319 parse_quantifier(re_compiler *c, int *min_out, int *max_out)
314320 {
315321 const char *save = c->p;
322+ /* Issue #819: integer overflow in `min/max = ... * 10 + digit`
323+ used to wrap to negative. CRuby caps quantifiers at a sane
324+ internal limit. We pick 100000 -- larger than any reasonable
325+ pattern but small enough that the subsequent emit loop can't
326+ run forever. */
327+ enum { RE_QUANT_MAX = 100000 };
316328 int min = 0, max = -1;
317329
318330 while (peek(c) >= '0' && peek(c) <= '9') {
319- min = min * 10 + (next_char(c) - '0');
331+ int d = next_char(c) - '0';
332+ if (min > RE_QUANT_MAX || min * 10 + d > RE_QUANT_MAX) {
333+ compile_error(c, "quantifier too big");
334+ }
335+ min = min * 10 + d;
320336 }
321337 if (peek(c) == ',') {
322338 next_char(c);
323339 if (peek(c) >= '0' && peek(c) <= '9') {
324340 max = 0;
325341 while (peek(c) >= '0' && peek(c) <= '9') {
326- max = max * 10 + (next_char(c) - '0');
342+ int d = next_char(c) - '0';
343+ if (max > RE_QUANT_MAX || max * 10 + d > RE_QUANT_MAX) {
344+ compile_error(c, "quantifier too big");
345+ }
346+ max = max * 10 + d;
327347 }
328348 }
329349 /* else max = -1 (unlimited) */