Skip to content

Fix out-of-bounds reads and sentinel handling in Matcher - #39

Merged
rameel merged 4 commits into
mainfrom
fix/matcher-bounds
Nov 15, 2026
Merged

rameel merged 4 commits into
mainfrom
fix/matcher-bounds

Conversation

@rameel

@rameel rameel commented Nov 15, 2026 •

Copy link
Copy Markdown
Owner

Matcher relied on look-ahead reads past the end of the pattern. This is harmless for string inputs, which always have a null terminator, but the public ReadOnlySpan<char> overload accepts arbitrary memory. There, such reads can produce wrong results or crash the process with an AccessViolationException.

While fixing this, two more bugs related to internal sentinel values were found.

Fixes

  • Out-of-bounds reads in character classes and escapes. Patterns ending with
    [, [!, [a-, [a-b or \ read up to two characters past the end of the span:

    • IsMatch("a", "[a-b]".AsSpan(0, 4)) returned true: the ] beyond the slice closed the class;
    • a pattern placed right before an inaccessible page crashed the process.

    An escaped ? is now matched literally: IsMatch("x", @"\?") used to return true.

  • Brace alternatives losing to the star-loop abort signal. (char*)-1 compares
    greater than any valid pointer, so it always won the longest-alternative selection:
    IsMatch("main.txt", "{*.cs,*.txt}") returned false.

  • Empty path spans backed by a null reference. For ReadOnlySpan<char>.Empty,
    the end-of-path pointer was equal to the null "no match" result:
    IsMatch(ReadOnlySpan<char>.Empty, "*.cs") returned true.

- Add bounds checks in character class parsing ('[', '!', '-')
- Check bounds after '\' and match the escaped character literally,
  so '\?' no longer acts as a wildcard
DoMatchSegment returns (char*)-1 to abort backtracking when a star
loop fails. MatchSubpattern picked the longest alternative by pointer
comparison, so this value always won over a real match, and patterns
like "{*.cs,*.txt}" failed to match "main.txt".
ReadOnlySpan<char>.Empty and default spans have a null reference,
which made the end-of-path pointer equal to the null "no match"
result, so non-matching patterns were reported as matches.
- Add GuardedBuffer that places input right before an inaccessible
  page, so any read beyond the buffer causes an access violation
- Add guard-page tests for boundary patterns in Unix and Windows modes
- Add tests for pattern slices, escaped '?', brace alternatives
  with stars, and empty path spans
@rameel
rameel merged commit 3050641 into main Nov 15, 2026
3 checks passed
@rameel
rameel deleted the fix/matcher-bounds branch November 15, 2026 07:47
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