Commit a711baca

a711baca34dbMerged

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

Description

fix(regexp): RE_BACKREF bounds-checks group index against ncap (#753)

/(\\1)/ (backref to a group that doesn't exist) used to read past captures[]: group * 2 was beyond the array, gs/ge picked up garbage, then the memcmp behaved unpredictably (-1 was reported in the issue, but the actual value is undefined-behavior land).

Bound the group index against ncap before indexing; on out of range, return FALSE (no-match). Matches CRuby's nil result for the same pattern.

Closes #753

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

Details

Commit
a711baca34db
Parent
4f675b400716

lib/regexp/re_exec.cmodifiedView file

@@ -545,6 +545,12 @@
545545 case RE_BACKREF:
546546 {
547547 int group = inst.a;
548+ /* Issue #753: bounds-check the group index against the
549+ captures array. A backref to a non-existent group (e.g.
550+ `/(\\1)/`) would read past captures[] and use garbage as
551+ the start/end. CRuby returns nil (no match) -- match the
552+ same by returning FALSE without dereferencing. */
553+ if (group * 2 + 1 >= ncap) return FALSE;
548554 int gs = captures[group * 2];
549555 int ge = captures[group * 2 + 1];
550556 if (gs < 0 || ge < 0) return FALSE;