Skip to content

[JSC] A parser stack overflow ends the parse - #700

Open
robobun wants to merge 1 commit into
mainfrom
robobun/fa2a54fe/parser-stack-overflow-is-final
Open

robobun wants to merge 1 commit into
mainfrom
robobun/fa2a54fe/parser-stack-overflow-is-final

Conversation

@robobun

@robobun robobun commented Sep 19, 2026 •

Copy link
Copy Markdown
Collaborator

Problem

  • JavaScriptCore never finishes parsing an object or array literal nested one level past the parser's stack limit. (0, eval)("var x = " + "{v:".repeat(3043) + "1" + "}".repeat(3043)) spins one core and grows by about 250 MB per second. Node throws a RangeError in 44 ms.
  • When a parse of text that starts with { or [ fails, parseAssignmentExpression (Source/JavaScriptCore/parser/Parser.cpp:4417) parses it again as a destructuring pattern. The save point restore clears m_errorMessage, so "Stack exhausted" counts as such a failure. Each nesting level on the way out parses everything below it again.

Fix

  • failIfStackOverflow() also fails when m_hasStackOverflow is set. All eight recursion guards use it, so a second parse fails at once.
  • Parser::parse() already reports ParserError::StackOverflow for that flag, so these programs throw RangeError: Maximum call stack size exceeded.
  • A literal overflows at the same depth as before. Two rare kinds of program that recovered from an overflow no longer do. Notes has the numbers.
  • Verified: new JSTests/stress/parser-stack-overflow-is-final.js, 16 cases that all hang without the change. A filtered run-javascriptcore-tests run (586 tests, 5678 runs) has 0 failures.

Background

  • Each recursive parser function starts with failIfStackOverflow(), which compares the stack pointer with the VM's soft limit.
  • A save point records the lexer and parser state. The parser restores it to try another production: {a: b} can be a literal or a pattern, (a = 1) can be an expression or arrow function parameters.
  • Only failWithStackOverflow() sets m_hasStackOverflow. It belongs to one Parser instance, each instance parses once, and nothing clears the flag.
Notes

This replaces #297. That PR has the same one-line change. It also carries CI changes (Dockerfile, build-reusable.yml) that now conflict with main, and it has no test. This branch is one commit on ebd5a6145b, the commit Bun pins today, so the preview build is that pin plus this change.

All numbers below come from two jsc shells built from this tree in one configuration (Release, Linux x64), one without the Parser.cpp line.

Programs nested 100000 deep

program without with
var x = {v:{v: ... 1 ... }} never returns RangeError, 7 ms
var x = [[ ... 1 ... ]] never returns RangeError, 4 ms
[[ ... a ... ]] = [] never returns RangeError, 5 ms
({v:{v: ... a ... }} = {}) never returns RangeError, 5 ms
var x = (a = (a = ... 1 ... )) never returns RangeError, 7 ms
var x = (a = (a = ... 1 ... ) => 1) => 1 never returns RangeError, 6 ms
the same with async never returns RangeError, 6 ms

The same holds for new Function(program), which checks the body with SyntaxChecker, the parser's other instantiation. Shapes with no second parse already threw before: nested parentheses, calls, template literals, function bodies, blocks, classes.

What no longer parses

The old and the new parser do the same thing until the first overflow. After it, the new parser always fails. So the only programs that change are those where the old parser recovered from an overflow and then succeeded. That needs a second parse with smaller frames than the first. There are two such places. Deepest nesting that parses, found by bisection:

program without with
var x = {v: ... } 3042 3042
var x = [ ... ] 3664 3664
[ ... a ... ] = [] 3685 3665
({v: ... a ... } = {}) 3068 3041
var f = (a = [0,[0, ... ]]) => 1, definition only 8713 3663
the same, definition and a call 3666 3663
  • Rows 3 and 4: a destructuring assignment pattern is first parsed as a literal, which overflows, and then as a pattern, which has smaller frames and still fit for about 20 more levels. One level past that, the old parser never returns.
  • Rows 5 and 6: in code that is parsed with ASTBuilder, the parameters of an arrow function are first parsed as an expression with ASTBuilder and then as parameters with SyntaxChecker, which has much smaller frames. So the old parser accepted the definition up to depth 8713. Every call of such a function threw a RangeError, because the parse at the first call builds the AST. Now the program that contains it throws the RangeError.

What I did to look for other effects

  • Read every save point in Parser.cpp. Only parseArrowFunctionCandidate, parseDestructuringAssignment, parseAssignmentElement, the for statement head and parseYieldExpression parse recursively and then restore after a failure. The "use strict" restart and the async function body parse again only after a success. The others look ahead one or two tokens. After the flag is set, each of them enters a guarded function within a constant number of tokens.
  • About 58,000 generated programs against the shell with the change (pairs and random sequences of 68 constructs, 12 wrappers, depths 5000 to 100000, as a script, as a Function body and as a module). Each one that overflowed ended within 75 ms, and the time does not grow with the depth. No crash.
  • The filtered test run used --filter "stack-overflow|deep-recursion|destructuring|arrow|parser|syntax|nested|yield|parse|literal|pattern|recursion|stack-limit|StackOverflow". The new test ran in 17 modes there, among them bytecode-cache, mini-mode, lockdown and the eager JIT tiers. It also passes with --maxPerThreadStackUsage=262144.
  • Parse time of a 9.1 MB file (typescript.js), 12 interleaved rounds of 31 parses for each shell on a shared machine. Best parse: 102.1 ms without the change, 101.2 ms with it. Median of the rounds' best parses: 106.0 ms without, 105.5 ms with. The check costs nothing that this can measure.

Not part of this PR

  • Nested arrow functions with parameter defaults, (a = (a = 9) => a) => a, parse in exponential time with no stack overflow at all. [JSC] Parser: arrow functions nested in parameter defaults no longer parse in exponential time #699 is about that. It is why the arrow check at the end of the new test stays at depth 8.
  • Two shapes are quadratic in the depth, with and without this change, and with no overflow: [[[a] = []] = []] = [] (3 s at depth 6000) and a wide array assignment pattern with an invalid target deep inside.
  • eval of a program that is only a literal, ({v:{v: ... }}), goes to LiteralParser and never reaches this parser. The test uses var x = ... for that reason.

@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 finding, I also checked the two save-point paths that do not go through a retry of the same text: parseYieldExpression (Source/JavaScriptCore/parser/Parser.cpp:4519) restores after an overflowed argument and returns a bare yield, but the enclosing production then sees the argument's first token and fails, and any continuation reaches a guarded function within a few tokens, so the flag still ends the parse; and the flag itself is set only by failWithStackOverflow(), initialized false per Parser instance (Parser.cpp:146), never cleared, and already what Parser::parse() reports as ParserError::StackOverflow (Parser.h:2260). The new test's cost is one lexer pass over ~300 KB per case, ending at the first overflow, so it stays well inside the 200 ms budget in the tested lanes.

Extended reasoning...

The one inline finding records the depth narrowing the author already documented in the PR's "What no longer parses" table; this note only lists what else was examined. The yield save point was traced by hand: after restoreSavePoint clears m_errorMessage, next() consumes yield and control returns up parseAssignmentExpression with the argument's first token ([, {, () still current, which no caller accepts without entering another failIfStackOverflow()-guarded function, so the parse terminates with m_hasStackOverflow set and Parser::parse() reports StackOverflow. The flag is per-instance, initialized false, and never reset, so there is no stale-flag risk across parses. The test builds strings of ~300 KB and every case fails at the first overflow with one lexer pass, so runtime is linear in depth; asan and debug lanes are not tested in CI per the root CLAUDE.md.

Comment thread Source/JavaScriptCore/parser/Parser.cpp Resolved
@github-actions

github-actions Bot commented Sep 19, 2026 •

Copy link
Copy Markdown

Preview build of 8ddd387: autobuild-preview-pr-700-8ddd3871

@coderabbitai

coderabbitai Bot commented Sep 19, 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: 63ed7f94-64db-4429-95af-7edf349d5510

📥 Commits

Reviewing files that changed from the base of the PR and between ebd5a61 and ecbaab3.

📒 Files selected for processing (2)
  • JSTests/stress/parser-stack-overflow-is-final.js
  • Source/JavaScriptCore/parser/Parser.cpp

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


Walkthrough

The parser now stops repeated reparsing after a stack overflow. A stress test covers deeply nested literals, assignment patterns, and arrow-function parameters through eval and Function construction.

Changes

Parser stack-overflow handling

Layer / File(s) Summary
Persist stack-overflow failure state
Source/JavaScriptCore/Parser.cpp
failIfStackOverflow now fails when m_hasStackOverflow is already set.
Validate nested parser behavior
JSTests/stress/parser-stack-overflow-is-final.js
The stress test checks RangeError results at depth 100,000 and successful evaluation for shallower programs.

Priority: ➖ Normal

🚥 Pre-merge checks | ✅ 4
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Description check ✅ Passed The description clearly explains the problem, implementation, affected behavior, validation results, and scope. It does not include the template's Bugzilla link, reviewer line, or explicit changed-fil…
Title check ✅ Passed The title clearly and concisely identifies the primary change: a parser stack overflow now terminates parsing.

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.

The parser parses some text a second time as another production when the
first parse fails: an object or array literal as a destructuring pattern
(parseAssignmentExpression), a pattern element as a member expression
(parseAssignmentElement), a parenthesized expression as arrow function
parameters (parseArrowFunctionCandidate). Restoring the save point clears
m_errorMessage, so "Stack exhausted" counted as such a failure. Each nesting
level on the way out then parsed everything below it again, and each of
those parses did the same. `var x = {v:{v: ... 1 ... }}` nested one level
past the stack limit never finished parsing, and the process grew by about
250 MB per second.

failIfStackOverflow() now also fails when m_hasStackOverflow is set. Every
recursive path of the parser goes through it, so a second parse fails at
once and the error reaches the caller in time linear in the depth.
Parser::parse() already reports ParserError::StackOverflow when the flag is
set, so these programs throw "RangeError: Maximum call stack size exceeded."

The depth at which a literal overflows does not change (3042 levels of
`{v:` and 3664 of `[` in a release build on Linux x64). Two kinds of program
recovered from an overflow before, because their second parse uses smaller
frames than the first, and no longer do:

- A destructuring assignment pattern in expression position parsed about 20
  levels deeper than the literal. It now overflows at the same depth.
- An arrow function in code that is parsed with ASTBuilder, with an
  expression nested more than 3664 deep in its parameter list, was accepted
  up to depth 8713, because the second parse of the parameters uses
  SyntaxChecker. Every call of such a function threw a RangeError, because
  the parse at the first call builds the AST. Now the program that contains
  it throws the RangeError. The deepest such function that could be called
  was 3666 levels deep and is 3663 now.
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.

1 participant