Repository navigation
fix(syntax): parse case patterns that run past the 1 KiB read buffer - #880
Merged
Merged
Conversation
Simplify dereferenced ParamExp.Param, which is nil for an invalid
expansion such as ${%}, so "((${%}))" crashed it. Found by
FuzzParsePrint.
Pattern parsing scans a pattern several times and re-parsed every nested group and shell part on each scan, so nesting took exponential time: 22 levels of "[[ x == @(@(...)) ]]" took about 2s and 8 levels of "case x in $(case x in $(...) ) ;; esac) ) ;; esac" about 1s. - Scans that only need where a group ends no longer build the group's arms, and memoize the end by the address of the group's first byte, reusing it only while the text still holds everything the scan looked at. Bare groups skip nested groups the same way instead of counting parentheses. - parseRawWordPart memoizes its results for the whole parse, shared by every sub-parser it starts. Callers pass different tails of the same source and the sub-parser's output can depend on what follows the part, so an entry is only reused when the new input holds exactly the bytes the sub-parser read for it. - Extended glob and bare pattern groups count toward MaxNestingDepth, since they are parsed recursively and could overflow the stack, and pattern scans stop once the limit is hit. DebugPrint output is unchanged on the filetests, error cases, repo scripts and fuzz corpora, and on 150k random pattern-heavy inputs. Nested groups now parse in linear time: 16000 levels of @( take about 20ms. Shell parts that nest patterns are parsed once each but every level still copies and re-lexes the text inside it, so they are quadratic: 1000 levels of nested case take about 0.2s, 4000 about 12s.
A case pattern was only scanned within the parser's 1 KiB read buffer.
When a shell part such as $(...) ran past it, the scan fell back to
getPattern, which failed on the cut-off part, so scripts bash accepts,
like `case x in $(<1 KiB of commands>) ) ;; esac`, gave
"syntax error near unexpected token `('".
- patternSourceAhead gives the case pattern scans (scanRawPatternSource
and casePatternUsesOptionalOpener) the whole pattern. Real readers are
read ahead in doubling steps until the scan ends inside the text and no
shell part or bracket expression ran into its end; the bytes go back
to the input through a prependReader. Interactive readers are not read
ahead.
- Sub-parsers read a string, so they scan a view of the rest of it at
once; doubling steps there rescanned every nesting level per step.
- Until the input ends, scans of text that may be cut off give up at the
cut, and their parse-cache entries are not kept, so cut text is not
re-parsed through the uncached fallback at every level.
- fill keeps the current token buffered while a case pattern's first
token is lexed, so a pattern whose first token straddles the buffer
end is still scanned from its start.
DebugPrint and error output are unchanged on the filetests, error cases,
fuzz corpora, benchmark files and repo scripts (5 dialects x 3 option
sets). Nested `case x in @($(case ...))) ;; esac` at 25 KB now parses in
about 0.9 s instead of about 9 s.
ewhauser
enabled auto-merge (squash)
October 20, 2026 03:50
…raday-65e34a # Conflicts: # shell/syntax/parser.go # shell/syntax/pattern_nesting_test.go # shell/syntax/raw_part_cache.go
Resolves conflicts with the squash-merged #877 by keeping this PR's own change on top of main.
# Conflicts: # shell/syntax/pattern_nesting_test.go
#879 capped shell code nested in patterns at 64 levels, so 1000 levels now fail to parse. 64 levels still run well past the 1KiB read buffer.
Merged
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
What
A case pattern whose shell part runs past the parser's 1 KiB read buffer no longer fails to parse. Bash accepts these, and gbash rejected them:
Why
scanRawPatternSourceandcasePatternUsesOptionalOpeneronly scanned the current 1 KiB buffer window. When the scan reached the window end before the input ended, it fell back togetPattern. A$(...)cut off by the window failed to parse there, so the scan ended early. The fallback path also defeats the parse cache, so nestedcase x in @($(case ...)))past 1 KiB was slow (about 9 s at 25 KB).How (shell/syntax)
patternSourceAheadgives both scans the whole pattern. A real reader is read ahead in doubling steps until the scan ends inside the text and no shell part or bracket expression ran into its end;scanPatternTextnow reports that throughsawEnd. The extra bytes go back to the input through aprependReader, so the lexer is unaffected. Interactive input is never read ahead.getPatternpath, which was exponential.fillkeeps the current token buffered while a case pattern's first token is lexed. A pattern whose first token straddles the buffer end is then still scanned from its start. Before, this failed at certain alignments, such as padding 1012/1013 with nested@($(case …, and with short reads.Verification
pattern_lookahead_test.gocover 15 pattern shapes across many paddings and three read sizes, plus 1,000-level nesting, source kept intact after a read-ahead, and read errors. A fuzz seed covers a hang found while developing this.case x in $(…),@($(…))and($(…))parse correctly at 2,000–4,000 levels.@($(case …)))at 25 KB takes 0.9 s, down from about 9 s. Time still grows with the square of depth (4,000 levels ≈ 13–16 s); that is a known separate issue.BenchmarkParseandBenchmarkParseBenchmarkFilesare unchanged.go test ./shell/...andmake lintpass.FuzzParsePrintandFuzzParseAdversarialeach ran 60 s clean.Known issue (not from this PR)
FuzzParseAttackMutationsfails within a minute on a slow input family that is just as slow on the base: an unterminated backquote followed by$( ((and heredocs, with no case pattern. A 175-byte script takes 6.5 s and a 304-byte one 25 s. A separate fix is in progress.No SPEC change: this is a parser bug fix with no change to the sandbox or API contract.