Skip to content

[YARR] The interpreter backtracks a greedy backreference by what it took - #926

Merged
sosukesuzuki merged 2 commits into
mainfrom
robobun/98b0f79e/yarr-greedy-backreference-rewritten-capture
Oct 28, 2026
Merged

sosukesuzuki merged 2 commits into
mainfrom
robobun/98b0f79e/yarr-greedy-backreference-rewritten-capture

Conversation

@robobun

@robobun robobun commented Oct 27, 2026 •

Copy link
Copy Markdown
Collaborator

Problem

  • The interpreter and the JIT disagree on a greedy backreference whose group is written again between the two times the term runs. For "cqcIIxq".split(/(?:Z?)+(?:(?<x>qcIIx)|(?<x>c*(?:\k<x>*II)?))q/, 100) the JIT answers ["", undefined, "c", "cIIx", undefined, "", ""] and the interpreter answers something else. The (?:Z?)+ prefix matches the empty string only. It is there to leave the JIT.
  • backtrackBackReference (Source/JavaScriptCore/yarr/YarrInterpreter.cpp:1078) reads the capture again and moves the input cursor by the length the capture has then. \k<x> inside a group named x is a real backreference when x is a duplicate name (YarrPattern.cpp:1957), so that length is not the length the term took.
  • matchBackReference never writes BackTrackInfoBackReference::backReferenceSize, although the slot is there and the JIT keeps this value in it (YarrJIT.cpp:3956, YarrJIT.cpp:4082).

Fix

  • matchBackReference records the length of one repetition in backReferenceSize.
  • backtrackBackReference decides the FixedCount and Greedy cases from the frame alone (begin, matchAmount, backReferenceSize), in both match directions. NonGreedy still takes one more repetition from the capture as it stands, and now restores its start position on every path that fails. The frame holds what the term did, and only the term writes it.
  • InputStream::rewind() checks its amount in a release build. interpret() checks the span of a match before it returns it.
  • Verified: new JSTests/stress/regexp-greedy-backreference-rewritten-group.js, run with default options and with --useRegExpJIT=false. Also the regexp and yarr JSTests, 2218 test262 RegExp and String.prototype tests, and a full JSTests run.

Background

  • A backreference term keeps three words of state in its frame: begin, matchAmount and backReferenceSize (YarrPattern.h:802). The interpreter filled in the first two only.
  • Duplicate named groups share one name. \k<x> reads whichever of them matched last, through output[offsetForDuplicateNamedGroupId], so the capture behind one backreference changes while the match runs.
  • Every other backtrack in this file moves by a constant or restores a position it saved. The backreference was the only one that recomputed its amount from state another term writes. That is why this belongs in the frame, and not in the code that reads a finished match.

Downsides

  • Three patterns of one shape answer null where they answered a match. The short one is /(?:(?<x>qcIIx)|(?<x>I?\k<x>+)){2,}I/g on "cIIcIIx". That match came off the cursor this PR corrects. Take the quantifier off the backreference and both engines answer null on main already: /(?:(?<x>z)|(?<x>I?\k<x>)){2,}I/.exec("cIIcIIx"). A separate difference from V8 keeps the shape from matching, reported apart from this.
  • One store per greedy backreference match, into a slot that already exists, so no frame grows. Three compares per interpreted match. The backtrack itself loads fewer words than before. .text of jsc grows 312 bytes, 44,940,842 to 44,941,154 (size, release builds of the merge base and of this branch).
Notes

The fix, term by term. A greedy backreference consumes the capture as many times as it can, then gives one repetition back per backtrack. Before this change the amount it gave back came from output[], read again at backtrack time. The frame slot for it was already defined (YarrStackSpaceForBackTrackInfoBackReference is 4) and already used by the JIT, which stores the span at match time and reads it back when it backtracks. The interpreter now does the same. The FixedCount case restores begin whatever the capture says now, and the NonGreedy case restores begin on the paths that used to return without it.

How the two forms of each test case differ. A prefix of (?:Z?)+, (?:q*)+ or (?:){2} makes the JIT-compiled code give up at run time, and an alternative such as |z{2147483648} keeps the pattern out of the JIT. None of them changes the language of the pattern on these subjects, so the two forms must answer the same.

Differential run. 200 seeds of a generator of duplicate named groups with backreferences, 400 patterns each, each in two forms: 160,000 matches with exec, match and split. With this change the JIT and the interpreter agree on all of them. Before it they disagreed on 19 of the 200 seeds, and 34 of the 400 runs ended early. Against node 26.3 over the 153,250 cases that both builds complete: 710 answers differ before, 704 after. Eight move into agreement, two (one pattern in two forms) leave it, and that pattern is the one in Downsides. The 704 are differences in this corner that this change does not touch.

The full JSTests run (--quick, against a local JSCOnly release build) reports no regexp or yarr failure. Its other failures are the ones this box produces without this change as well (bigint, gc, dfg, structured-clone, and this build has WebAssembly off), and each of the ones that the baseline run did not report passes when it runs on its own. The regexp and yarr filter reports 0 failures.

A lookbehind corpus of the same shape (the backreference to the right of the group that writes it, so the Backward arm of the fix) answers exactly as before on 48,000 matches.

The separate difference from V8: JSC misses a match when an iteration of a quantified group has to match empty and a backreference inside it has to read the capture as it was before a later write that backtracking undoes. It reproduces on main, in both engines, with no quantifier on the backreference: /(?:(?<x>z)|(?<x>(?:I?)\k<x>)){2,}I/.exec("aIIcx") is null in JSC and ["II", undefined, ""] in V8.

A backreference to a duplicate named group reads whichever group of that name
matched last, so the capture a term read when it matched can say something else
when the term backtracks. backtrackBackReference() read the capture again and
moved the input cursor by its length, not by the length the term consumed, so
the cursor was wrong from then on and the interpreter and the JIT disagreed.

matchBackReference() now records the length of one repetition in the frame slot
the JIT already uses for it, and backtrackBackReference() decides the FixedCount
and Greedy cases from the frame alone. The NonGreedy case still takes one more
repetition from the capture as it stands, and now restores its start position on
every path that fails.

InputStream::rewind() checks its amount in a release build, and interpret()
checks the span of a match before it hands it back.
@github-actions

Copy link
Copy Markdown

Preview build of 589a30d: autobuild-preview-pr-926-589a30da

@sosukesuzuki
sosukesuzuki marked this pull request as ready for review October 28, 2026 00:51
@sosukesuzuki
sosukesuzuki merged commit 23d7f1d into main Oct 28, 2026
87 checks passed

@claude claude Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nothing blocking. The comments below are optional suggestions. There is no need to push a fix for them before merging.

Beyond the inline findings, I also checked the JIT side for parity: backtrackBackReference in YarrJIT.cpp (Greedy case, ~4075-4094) loads matchAmount, fails on zero, and moves the index by backReferenceSize (add for Backward, sub for Forward), which is what the interpreter now does. The Greedy early-return paths in matchBackReference (undefined or empty capture) leave matchAmount at 0, so the backtrack never reads a backReferenceSize that was not written. The four-argument RELEASE_ASSERT form resolves to the variadic macro in WTF/Assertions.h.

Extended reasoning...

The change touches the Yarr interpreter's backreference match/backtrack in YarrInterpreter.cpp plus one new stress test, and no security-sensitive surface beyond regexp input handling. A confirmed behavior change (a pattern shape that matched on the base and in V8 now returns null) is posted inline, which rules out approving. The ruled-out items above were verified by reading YarrJIT.cpp, matchBackReference, and Assertions.h.

robobun added a commit that referenced this pull request Oct 28, 2026
main got #886 (48a0ce9) and #926 (23d7f1d) after the merge of
0e10366.

There is no conflict. Both sides changed yarr/YarrJIT.cpp, and git merged
it. Upstream 1984003 changes how the frame slots of a ParenContext are
copied. #886 changes hasExceededCodeSizeLimit() and adds an assertion behind
the backtracking code. The two changes are in different functions. #926
changes yarr/YarrInterpreter.cpp, which upstream did not change in this
range. The other two files are the tests that #886 and #926 add.

Checked with a Release build of jsc for Linux x64 without the ahead-of-time
compiler: run-javascriptcore-tests with --filter="regex|regexp|yarr", 7278
runs from all collections, no failure. The two new tests are among them.
robobun added a commit to oven-sh/bun that referenced this pull request Oct 28, 2026
… RegExp throws when its second match fails

WEBKIT_VERSION is the preview build of oven-sh/WebKit#929
(autobuild-preview-pr-929-c5087553). From fcc1ea0973a4 the range is
oven-sh/WebKit#886, oven-sh/WebKit#926 and upstream
WebKit/WebKit@191803bb2304, cherry-picked with no change.

With the upstream commit, a read of RegExp.lastMatch or of another legacy
static property throws a RangeError when its second match fails. It used
to end the process: "Segmentation fault at address 0x4".

The engine's stress test for it is a fixture of
test/js/bun/jsc-stress/jsc-stress.test.ts.
robobun added a commit to oven-sh/bun that referenced this pull request Oct 29, 2026
Main's WebKit pin contains oven-sh/WebKit#886 and oven-sh/WebKit#926, and
nothing in this repository tests either.

- An inlined RegExp#test is not held to maximumRegExpJITCodeSize, which
  counted the code of the function around it.
- The interpreter and the JIT agree on a greedy backreference whose group is
  rewritten.

The test has one case for each, and runs the second with and without the
RegExp JIT.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants