Skip to content

[JSC] DFG RegExpTest asserts when the RegExp is also the argument (cherry-pick WebKit/WebKit#74030) - #654

Closed
robobun wants to merge 1 commit into
mainfrom
robobun/c6613da2/regexp-test-base-is-argument
Closed

robobun wants to merge 1 commit into
mainfrom
robobun/c6613da2/regexp-test-base-is-argument

Conversation

@robobun

@robobun robobun commented Sep 14, 2026 •

Copy link
Copy Markdown
Collaborator

Cherry-pick of WebKit#74030 (upstream commit d22fa241f19e4a2ab3565132df3bc7db82d0b684, https://commits.webkit.org/321146@main, https://bugs.webkit.org/show_bug.cgi?id=324211). The commit applies cleanly on main. The author and the commit message are unchanged.

This PR had the same source change before upstream landed it on 2026-09-15. The branch now holds the upstream commit itself. Upstream adds its test at the same path, JSTests/stress/regexp-test-regexp-is-also-the-argument.js, so with identical content a later upstream merge does not conflict here.

Problem

  • regExp.test(regExp) aborts a build with assertions when the function reaches the DFG: ASSERTION FAILED: noOverlap(baseGPR, argumentGPR, scratch1GPR, scratch2GPR) at dfg/DFGSpeculativeJIT64.cpp:10401, in emitRegExpMinimumLengthFilterGuards.
  • The RegExp and the argument of RegExpTest are the same node there, so both operands get the same register. The assertion does not permit that.
  • Release builds are not affected. ASSERT compiles to nothing there, and the generated code is correct.

Fix

  • Assert each input register against the scratch registers, in two assertions. emitRegExpStickyFirstCharacterFilterGuards, the function above this one, already does that.
  • Correct because the function only reads baseGPR and argumentGPR. It writes scratch1GPR and scratch2GPR only.
  • The generated code does not change. A RegExp argument is not a string, so emitRegExpTestWithFilter sends it to the slow path call (branchIfNotString) before a guard runs.
  • Verified with the upstream test file, JSTests/stress/regexp-test-regexp-is-also-the-argument.js. The debug jsc from the autobuild-d3720d515e14 release (bun-webkit-linux-amd64-debug-asan), which does not have the change, fails it with the assertion above. The same jsc passes it with --useDFGJIT=0 and with --useJIT=0, so the expected values in the test are right. The debug jsc of the preview build of this head (autobuild-preview-pr-654-cb4a0b23) passes it with default options, with --useConcurrentJIT=0, with --useFTLJIT=0, and with low tier-up thresholds.
  • The CI of this repository ran run-javascriptcore-tests on this head. The only failure was one run of stress/sampling-profiler-bound-function-name.js in the linux-amd64-lto test lane, a release build where this change compiles to nothing. The re-run of that lane passed.

Background

  • The minimum-length filter and its assertion came with the upstream change "RegExp#test should fast-fail on an input shorter than the pattern's minimum size" (https://bugs.webkit.org/show_bug.cgi?id=322689). Upstream fixed the assertion in 321146@main, the commit that this PR picks.
  • The DFG keeps the value of one node in one register. Two edges to the same node read the same register. x.test(x) gives RegExpTest two such edges.
  • noOverlap(a, b, c) is true when no two of its arguments are the same register.
Notes

Smallest repro for a debug jsc:

function test(regExp) { return regExp.test(regExp); }
noInline(test);
var regExp = /^abc$/;
for (var i = 0; i < testLoopCount; ++i)
    test(regExp);

The test covers four shapes. All have the RegExp as the argument:

  • A RegExp that is not a constant. The filter reads RegExp::m_minimumSize at run time. This shape and the next one fail the assertion.
  • A constant RegExp that has code. The filter compares against a constant minimum size.
  • A constant RegExp that starts with ^. This one uses emitRegExpAnchoredFirstCharacterFilterGuards, which has no RegExp register.
  • A constant sticky RegExp. This one uses emitRegExpStickyFirstCharacterFilterGuards, which already permits one register for both.

How it was found: a fuzzer run of Bun's debug build, with this script.

const v0 = /za\S\p{gc=Nd}a|bqja*b|c/g;
function f1() {
    v0.test(v0);
    return f1;
}
v0.valueOf = f1;
function f3() {
    return v0;
}
v0.toString = f3;
const v4 = [-2.2250738585072014e-308,-0.0,-9.32419020495346e+307,1.3436572898162654e+308,1000.0,2.220446049250313e-16];
try { v4.slice(v0); } catch (e) {}
  • slice converts v0 to a number, so it calls valueOf, which is f1. test converts v0 to a string. toString gives back an object, so the conversion calls valueOf again. The recursion makes f1 hot before the stack overflows.
  • In a fresh process this script does not fail. The fuzzer ran it in a process that had run other scripts before.
  • v0 is a constant in f1. RegExpTest gets a CheckStructure against the original RegExp structure before it (addRegExpPrimordialStructureCheck). In a fresh process the DFG can watch the structure of v0 (RegExp plus valueOf plus toString). It then proves that the check fails and emits no code for the rest of the block.
  • The failure needs optimized code that watches the original RegExp structure at the time of v0.valueOf = f1. That store is then a transition away from a watched structure, so Structure::didTransitionFromThisStructureWithoutFiringWatchpoint sets transitionWatchpointIsLikelyToBeFired. The new structures of v0 inherit the flag, so Graph::tryWatch refuses them.
  • The bytecode parser then guards the v0.test load with an absence condition on v0 and adds no CheckStructure (ByteCodeParser::load). The DFG now knows nothing about the structure of v0, so it keeps the check as a run-time check and emits code for RegExpTest.
  • This earlier script is enough to make the script above fail 3 of 3 runs in Bun's debug build:
const w = /x/;
function watchPrimordial() { return w.test("x"); }
for (let i = 0; i < 200000; i++) watchPrimordial();

Later fuzzer reports have a script that fails on every run in a fresh process, with no earlier script:

function F0(...a2) {
    if (!new.target) { throw 'must be called with new'; }
    const v3 = this.constructor;
    try { new v3(); } catch (e) {}
    const v5 = /za\S\p{gc=Nd}a|bqja*b|c/g;
    function f6() {
        return v5.test(v5);
    }
    f6();
}
new F0(F0);
  • F0 calls itself through new this.constructor() until the stack overflows. Each level then calls f6, so f6 gets hot.
  • v5 is a new closure variable at each level, so it is not a constant in f6. The DFG merges the two loads of v5 into one node, and the structure check passes at run time.

The branch is based on main of this repository (b54a4733d8f7). Earlier heads of this branch followed the WebKit pin of Bun main so that oven-sh/bun#42694 could pin their preview builds. That PR no longer follows each pin move.

Bun PR that adds the test as a jsc-stress fixture: oven-sh/bun#42694. With the preview build of an earlier head of this branch, the fuzzer scripts pass in a fresh process and after the earlier script above (3 of 3 runs each). That PR waits for this change to reach the WebKit pin of Bun main.

@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.

LGTM — debug-only assertion relaxation matching the established pattern in the sibling function.

What was reviewed:

  • Verified emitRegExpMinimumLengthFilterGuards only reads baseGPR/argumentGPR (loads at lines 10402, 10410, 10417, 10423) and writes only the scratch registers, so base/argument aliasing is safe.
  • Confirmed the split-assert pattern is copied exactly from emitRegExpStickyFirstCharacterFilterGuards (lines 10373-10374); no codegen change, release builds unaffected.
  • Checked the stress test against JSTests/README.md rules — uses testLoopCount, throws on failure, no logging; walked through each shouldBe expectation (including the sticky /\/ab/y lastIndex bookkeeping) and they are correct.
Extended reasoning...

Overview

The PR changes one debug ASSERT in Source/JavaScriptCore/dfg/DFGSpeculativeJIT64.cpp::emitRegExpMinimumLengthFilterGuards, splitting noOverlap(baseGPR, argumentGPR, scratch1GPR, scratch2GPR) into two assertions that permit baseGPR == argumentGPR while still guaranteeing neither operand aliases a scratch register. It also adds JSTests/stress/regexp-test-regexp-is-also-the-argument.js, which drives regExp.test(regExp) through DFG/FTL for non-constant, constant, anchored, sticky, and global RegExps and checks results plus lastIndex.

Security risks

None. The modification is to a debug-build ASSERT only; ASSERT compiles away in release, so shipped codegen is byte-identical. Reading the full function body confirms baseGPR and argumentGPR are used solely as base addresses for loads and are never written, so allowing them to share a register cannot corrupt state. The scratch-vs-operand and scratch-vs-scratch invariants are still enforced (noOverlap on three args still checks pairwise distinctness among scratch1/scratch2). The new test is pure JS with no I/O.

Level of scrutiny

Low. This is a one-line-to-two-line change that copies the exact idiom already used 24 lines above in emitRegExpStickyFirstCharacterFilterGuards. It follows an established pattern with no ambiguity, is self-contained, and the intent (fix a false-positive debug assertion when the DFG allocates one register for two edges to the same node) is clear and well-documented in the PR description. The bug-hunt ran to dry_streak with no findings.

Other factors

CODEOWNERS lists /Source/JavaScriptCore and /JSTests under WebKit/jsc-reviewers, but the file's own header states "Contributors do not 'own' WebKit components. This file is used to automatically add reviewers to pull requests" — it is upstream WebKit's reviewer-suggestion list carried into the Bun fork, not an ownership gate. The stress test complies with JSTests/README.md requirements (throws on failure, testLoopCount-driven, no printing). I hand-checked every expected value in the test, including the /\/ab/y case where the string form is the 7-char "/\\/ab/y" and /ab matches at index 2 giving lastIndex 5. Given zero release-build impact and trivially verifiable correctness, this is safe to approve.

@coderabbitai

coderabbitai Bot commented Sep 14, 2026 •

Copy link
Copy Markdown

Review Change StackReview Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Essentials

Run ID: 93533b3b-b473-4934-9d56-7a24cd371341

📥 Commits

Reviewing files that changed from the base of the PR and between 8d308b7 and 17b2731.

📒 Files selected for processing (1)
  • Source/JavaScriptCore/dfg/DFGSpeculativeJIT64.cpp

Included review availability: Your plan provides up to 5 included reviews per hour; 1 remains after this review.


Walkthrough

The change relaxes DFG register assertions for RegExp minimum-length guards and adds stress coverage for RegExp.prototype.test when the regular expression is also the input argument.

Changes

RegExp self-argument handling

Layer / File(s) Summary
Register overlap assertions
Source/JavaScriptCore/dfg/DFGSpeculativeJIT64.cpp
The guard assertions require both operand registers to remain separate from scratch registers. They no longer require the base and argument registers to differ.
RegExp stress coverage
JSTests/stress/regexp-test-regexp-is-also-the-argument.js
The new test covers unanchored, anchored, sticky, global, constant, and oversized patterns. It also checks repeated calls and lastIndex updates and resets.

Priority: ⬇️ Low

Merge Risk: ⚪ Minimal · up to 17b27

The change addresses a reachable RegExp self-argument assertion failure, and no merge-blocking risk is established.

🚥 Pre-merge checks | ✅ 4
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly identifies the JSC assertion failure and the specific RegExpTest case addressed by the pull request.
Description check ✅ Passed The description provides the Bugzilla link, problem statement, fix, affected files, testing details, and relevant implementation context. It is complete and aligned with the repository template.
Linked Issues check ✅ Passed The description links Bugzilla issue 324211 and identifies the upstream WebKit commit associated with the fix.
Out of Scope Changes check ✅ Passed The changes are limited to the DFG assertion update and the related JavaScriptCore stress test. They match the stated objectives.

Warning

Git: CodeRabbit could not clone the repository, so clone-backed analysis was skipped and this review may be incomplete. Verify repository clone access, such as SSH credentials, before requesting another full review. If clone access is intentionally unavailable, use path_filters to narrow the review scope.


Comment @coderabbitai help to get the list of available commands.

@github-actions

github-actions Bot commented Sep 14, 2026 •

Copy link
Copy Markdown

Preview build of cb4a0b2: autobuild-preview-pr-654-cb4a0b23

@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.

LGTM — debug-only assertion split that mirrors the sibling function.

What was reviewed:

  • emitRegExpMinimumLengthFilterGuards only reads baseGPR/argumentGPR and writes only the scratch registers, so aliasing the two inputs is safe; the split matches emitRegExpStickyFirstCharacterFilterGuards right above it.
  • Confirmed the caller diverts non-string arguments to the slow path via branchIfNotString before the guards run, so generated code is unchanged.
  • Checked FTL (FTLLowerDFGToB3.cpp) and the 32-bit SpeculativeJIT for an equivalent assertion — FTL uses B3 LValues (no noOverlap), and there is no 32-bit implementation of this function.
  • New stress test follows JSTests rules (uses testLoopCount, throws on failure, no logging); walked each shouldBe against the RegExp's own toString() and the values check out.
Extended reasoning...

Overview

The PR relaxes a single debug ASSERT in SpeculativeJIT::emitRegExpMinimumLengthFilterGuards (Source/JavaScriptCore/dfg/DFGSpeculativeJIT64.cpp) from a four-way noOverlap(baseGPR, argumentGPR, scratch1GPR, scratch2GPR) into two three-way checks that permit baseGPR == argumentGPR. It adds JSTests/stress/regexp-test-regexp-is-also-the-argument.js, which drives regExp.test(regExp) through DFG with plain, anchored, longer-than-source, global, constant, constant-anchored and constant-sticky RegExps. That is the entire diff.

Security risks

None. ASSERT compiles away in release builds, so this change alters no shipped code path. The relaxed invariant is sound: reading the function body, baseGPR and argumentGPR are used only as load addresses; all stores go to scratch1GPR/scratch2GPR, which are still asserted distinct from both inputs and from each other. At run time the aliased case cannot even reach the guard body — emitRegExpTestWithFilter sends a non-string argument (which a RegExp is) to the slow-path operationRegExpTest via branchIfNotString before any guard executes.

Level of scrutiny

Low. This is a two-line, debug-only assertion adjustment that copies the exact pattern already used 25 lines above in emitRegExpStickyFirstCharacterFilterGuards. I checked whether the same over-strict assertion exists elsewhere: the FTL lowering (compileRegExpTestMinimumLengthFilter / emitMinimumLengthGuardChain) works on B3 LValues and has no register-overlap assertion, and there is no 32-bit implementation of this helper. Nothing else needs the same fix.

Other factors

The new stress test conforms to JSTests/README.md: it uses testLoopCount, fails by throwing from shouldBe, and prints nothing on success. It is a new file (not a modified upstream test), so no // Bun: marker or BUN-TEST-DIFFERENCES.md entry is required. I hand-checked each expected value against the RegExp's toString() output (including the global lastIndex progression to 4 then reset to 0, and the sticky match at index 2 advancing lastIndex to 5). A commit was pushed after the earlier bot review, so a fresh verdict is appropriate; there are no outstanding CHANGES_REQUESTED reviews.

robobun added a commit to oven-sh/bun that referenced this pull request Sep 15, 2026
…the DFG register assertion

The DFG gives the RegExp and the argument of RegExpTest one register when
both are the same value. The minimum-length filter of RegExp#test asserted
that the two registers differ, so a debug or ASAN build aborted in the DFG
compiler. oven-sh/WebKit#654 asserts each input against the scratch
registers only.

Pin WEBKIT_VERSION to the preview build of that PR and add its stress test
as a jsc-stress fixture.
@robobun
robobun force-pushed the robobun/c6613da2/regexp-test-base-is-argument branch from ede7410 to 17b2731 Compare September 16, 2026 07:10
robobun added a commit to oven-sh/bun that referenced this pull request Sep 16, 2026
…the DFG register assertion

The DFG gives the RegExp and the argument of RegExpTest one register when
both are the same value. The minimum-length filter of RegExp#test asserted
that the two registers differ, so a debug or ASAN build aborted in the DFG
compiler. oven-sh/WebKit#654 asserts each input against the scratch
registers only.

Pin WEBKIT_VERSION to the preview build of that PR and add its stress test
as a jsc-stress fixture.
@robobun

robobun commented Sep 19, 2026

Copy link
Copy Markdown
Collaborator Author

Upstream landed the same change after I opened this PR. The description says that upstream main has the same assertion. That is no longer true.

The upstream commit is WebKit/WebKit@d22fa24 (https://commits.webkit.org/321146@main, https://bugs.webkit.org/show_bug.cgi?id=324211). Yusuke Suzuki reviewed it, and it landed on 2026-09-15. Its change to emitRegExpMinimumLengthFilterGuards is the same two assertions as in this PR.

The upstream merge in #651 does not include that commit. #651 targets 6b58d86abe (2026-09-13), which is 136 commits before d22fa241f19e. So main here gets the fix from this PR, or from a later upstream merge.

The fuzzer reported this assertion a third time, at the current pin 000c48997255. This repro needs no earlier script. It fails in a fresh process, 3 of 3 runs, in Bun's debug build:

function f() {
    const re = /abcdef/;
    return re.test(re);
}
for (let i = 0; i < 100000; i++) f();

The release build of the same Bun revision returns true for each call. That is the correct result.

https://bugs.webkit.org/show_bug.cgi?id=324211

Reviewed by Yusuke Suzuki.

In `regExp.test(regExp)` both operands of RegExpTest are the same node, so
baseGPR and argumentGPR are the same register. Debug builds then hit
ASSERT(noOverlap(baseGPR, argumentGPR, scratch1GPR, scratch2GPR)) in
emitRegExpMinimumLengthFilterGuards(), added in 320487@main.

The function only reads baseGPR and argumentGPR and only writes the scratch
registers, so assert each input against the scratch registers separately, as
emitRegExpStickyFirstCharacterFilterGuards() already does. The generated code
does not change: a RegExp argument is not a string, so it branches to the
slow path call before the guards run.

Test: JSTests/stress/regexp-test-regexp-is-also-the-argument.js

* JSTests/stress/regexp-test-regexp-is-also-the-argument.js: Added.
(shouldBe):
(testConstant):
(testConstantAnchored):
(testConstantSticky):
* Source/JavaScriptCore/dfg/DFGSpeculativeJIT64.cpp:
(JSC::DFG::SpeculativeJIT::emitRegExpMinimumLengthFilterGuards):

Canonical link: https://commits.webkit.org/321146@main

(cherry picked from commit d22fa24)
@robobun
robobun force-pushed the robobun/c6613da2/regexp-test-base-is-argument branch from 17b2731 to cb4a0b2 Compare September 20, 2026 08:03
@robobun robobun changed the title [JSC] DFG RegExpTest: regExp.test(regExp) fails a register assertion in the minimum-length filter [JSC] DFG RegExpTest asserts when the RegExp is also the argument (cherry-pick WebKit/WebKit#74030) Sep 20, 2026
@robobun

robobun commented Sep 20, 2026

Copy link
Copy Markdown
Collaborator Author

The branch now holds the upstream commit itself: a cherry-pick of WebKit/WebKit@d22fa24 on the current main, with the author and the commit message unchanged. I updated the title and the description.

The source change is the same as before. The test file is now byte-identical to the upstream one (my version had three more comment lines). Upstream uses the same path, so a later upstream merge does not conflict on it.

I ran the upstream test file on two debug jsc builds. The one from autobuild-d3720d515e14 fails it with the assertion. The one from autobuild-preview-pr-654-17b2731a, which has the same source change, passes it.

@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.

Code review found no issues

No high-confidence issues detected in this change.

@robobun

robobun commented Sep 24, 2026

Copy link
Copy Markdown
Collaborator Author

#725 (upstream merge to 7b485a76e9) contains this commit: upstream d22fa241f19e is an ancestor of 7b485a76e9, and on the head of #725 the source lines and the test file are the same as here.

So the fix can reach main through either PR. If #725 merges first, this PR has no diff left and I close it. If this PR merges first, #725 does not conflict with it, because both files are byte-identical to upstream.

main and the WebKit that Bun pins today (299c5323879e) still have the combined assertion.

@robobun

robobun commented Sep 27, 2026

Copy link
Copy Markdown
Collaborator Author

Closing: main has this commit since #725, the merge of upstream 7b485a76e9. Upstream d22fa241f19e is part of that merge, so the source lines and the test file on main are the same as in this PR.

Bun has the fix since oven-sh/bun#43882, which moved the WebKit pin to that merge. oven-sh/bun#42694 now only adds the test as a jsc-stress fixture.

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