Skip to content

fix(syntax): stop slow parses and hangs around heredoc bodies - #885

Merged
ewhauser merged 2 commits into
mainfrom
claude/fix-backtick-parse-slow
Oct 20, 2026
Merged

ewhauser merged 2 commits into
mainfrom
claude/fix-backtick-parse-slow

Conversation

@ewhauser

Copy link
Copy Markdown
Owner

What changed

Two parser fixes in shell/syntax, both found by FuzzParseAttackMutations.

1. Nested (( probes with heredocs parsed in exponential time

To resolve (( and $((, the parser parses the text after them three times: as arithmetic, as a subshell or command substitution, and finally as the chosen form. Heredoc bodies get a fresh sub-parser, which resolves every (( in them the same way. An unterminated heredoc body runs to end of input. So when each $( (( level opened a heredoc whose body held the next level, the work tripled per level. Every pass over a body also re-parsed each line that might hold its closing delimiter, using a fresh, fully probing parser.

The new per-parse heredocCache (heredoc_cache.go) is shared by the owning parser, its probe clones and its heredoc body sub-parsers. It memoizes:

  • Probe body parses. Probe trees are thrown away, so the final tree never shares nodes. Like rawPartCache, an entry serves any nesting and pattern-nesting depth that can't reach the limits, and a nesting-failure entry only serves the same depths.
  • Near-miss heredoc close candidates. Hits return a copy.

There was a tempting smaller fix: the probe depth handed to body sub-parsers is zeroed by reset(), and keeping it would also cut the work. But it changes parse results (the mksh reproducer's error moved from 9:5 to 2:6), so this PR leaves that as is.

Input Before After
175-byte mksh reproducer (RecoverErrors(1)) 6.5 s ~1 ms
304-byte zsh reproducer (KeepComments, RecoverErrors(3)) 25 s 2–4 ms
4 KB versions of the five shapes in the test don't finish ≤ ~100 ms
Plain nested unterminated heredocs at 4 KB ~400 ms ~13 ms

2. Hang after a heredoc body error

The heredoc body sub-parser's error was assigned directly to p.err, leaving the outer lexer on its current token. callExpr then spun forever on a token it couldn't consume: curUnexpectedErr is a no-op once an error is set. Repro (zsh): cat <(echo hi followed by two ${$(EOF heredoc levels. The fix stops the lexer the way errPass does, without errPass's heredoc-warning rewrite.

Visible change for reviewers: parsing no longer runs on past a heredoc body's error. On main, a later backquote recovery could replace that error with one at a nonexistent position. For example, $(x\nEOF\n followed by two `$((1+2))${x} <<EOF\n $( { EOF\n blocks reported 5:5 on the three-byte line EOF. It now reports the unmatched { at 4:5, which is also what main reports for the one-block version. TestHeredocBodyErrorKeepsFirstError pins this.

Verification

  • Corpus comparison against main (bfd6646): DebugPrint and error output were compared over 10,813 inputs (fileTests*, errorCases, known attacks, testdata/fuzz, the local fuzz caches for the three parser fuzz targets, and every .sh/.bash/.bats/.zsh/.ksh in the repo). Each input ran in 5 dialects × {default, KeepComments, RecoverErrors(3)}, plus each fuzz entry's own options: 168,156 results.
    • All results match except two groups. 38 results time out on main but finish here. The 16 results of the one input above differ as described.
    • The whole run takes ~20 s here versus 742 s on main, including main's timeouts.
  • Sweeps around the limits, identical to main:
    • MaxNestingDepth: 6 shapes × 91 depths × RecoverErrors 0/3; 58 s here versus 307 s on main.
    • MaxPatternNestingDepth: 5 shapes × depths 55–70 × bash/zsh × RecoverErrors 0/3; both include the point where the limit kicks in.
  • New tests: TestParenAmbiguityHeredocsParseInPolynomialTime and TestHeredocBodyErrorStopsParse both time out on main. TestHeredocBodyErrorKeepsFirstError covers the error-position change, and the hang seed is added to testdata/fuzz.
  • go test ./shell/... and make lint pass.
  • FuzzParseAttackMutations, FuzzParseAdversarial and FuzzParsePrint each ran 60 s clean.

SPEC

SPEC.md gains one sentence in the parser-limits paragraph, saying heredoc bodies and near-miss closes are memoized while resolving (( and $((.

…nential time

Resolving `((` and `$((` parses the text after them as arithmetic, as a
subshell or command substitution, and finally as the chosen one. Heredoc
bodies are parsed by fresh sub-parsers that resolve every `((` in them the
same way, and an unterminated body runs to the end of the input, so each
`$( ((` level holding a heredoc with the next level tripled the work.
Every pass over a body also re-parsed each line that might hold its
delimiter with a fresh, fully probing parser.

Add a per-parse heredoc cache shared by the owner, its probes and heredoc
body sub-parsers. It memoizes the body parses of probes (whose trees are
thrown away), serving any nesting depth that cannot reach the limit like
rawPartCache, and near-miss close candidates (returned as copies).

The 175-byte mksh and 304-byte zsh fuzz finds from the
unterminated-backticks attack took 6.5s and 25s; they now take a few
milliseconds, and 4 KB versions take under 100ms. DebugPrint and error
output are unchanged on fileTests, errorCases, known attacks, the fuzz
corpora and the repo's scripts in all dialects.
The error of a heredoc body's sub-parser was assigned straight to p.err,
leaving the outer lexer on its current token. callExpr then kept meeting
a token it could not consume, and since curUnexpectedErr keeps only the
first error, it looped forever. Stop the lexer as errPass does.

Found by FuzzParseAttackMutations from the process-subst-unclosed attack:
`cat <(echo hi` followed by two `${$(EOF` heredoc levels hung in zsh mode.

Parsing also no longer runs on past the body's error. Before, a backquote
recovery further on could replace it with an error at a position that does
not exist (5:5 on a three-byte line instead of the unmatched `{` at 4:5).
@ewhauser
ewhauser merged commit 19ff56a into main Oct 20, 2026
17 checks passed
@ewhauser
ewhauser deleted the claude/fix-backtick-parse-slow branch October 20, 2026 10:57
@ewhauser ewhauser mentioned this pull request Oct 20, 2026
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