From 4bab58749b9fe82e2341885d6c21b792f5e35e45 Mon Sep 17 00:00:00 2001 From: rameel Date: Sat, 14 Nov 2026 22:11:09 +0500 Subject: [PATCH 1/4] Fix out-of-bounds reads in character class and escape parsing - Add bounds checks in character class parsing ('[', '!', '-') - Check bounds after '\' and match the escaped character literally, so '\?' no longer acts as a wildcard --- Ramstack.Globbing/Matcher.cs | 31 ++++++++++++++++++++----------- 1 file changed, 20 insertions(+), 11 deletions(-) diff --git a/Ramstack.Globbing/Matcher.cs b/Ramstack.Globbing/Matcher.cs index bd17a5d..f54ab00 100644 --- a/Ramstack.Globbing/Matcher.cs +++ b/Ramstack.Globbing/Matcher.cs @@ -290,16 +290,20 @@ static bool IsMatchImpl(ref char rv, int vlen, ref char rp, int plen) { case '[': { - // We check an overrun slightly further below - p++; - var inverse = false; var matched = false; + // Malformed + if (++p >= pend) + return null; + if (p[0] == '!') { inverse = true; - p++; + + // Malformed + if (++p >= pend) + return null; } var a = p[0]; @@ -312,14 +316,13 @@ static bool IsMatchImpl(ref char rv, int vlen, ref char rp, int plen) var b = a; - if (p[0] == '-' && p[1] != ']') + if (p[0] == '-' && p + 1 < pend && p[1] != ']') { + b = p[1]; + // Malformed - if (++p >= pend) + if ((p += 2) >= pend) return null; - - b = p[0]; - p++; } matched |= a <= v[0] & v[0] <= b; @@ -426,11 +429,17 @@ static bool IsMatchImpl(ref char rv, int vlen, ref char rp, int plen) case '\\': { // Invalid escape sequence - if (p == pend) + if (++p >= pend) + return null; + + // The escaped character is always compared literally, + // so an escaped '?' must not act as a wildcard. + if (p[0] != v[0]) return null; p++; - goto default; + v++; + break; } default: From 14112b5b6a1a86a181d03c3a77ca88f38b3a5ef0 Mon Sep 17 00:00:00 2001 From: rameel Date: Sat, 14 Nov 2026 22:12:42 +0500 Subject: [PATCH 2/4] Fix brace alternatives losing to the star-loop abort signal 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". --- Ramstack.Globbing/Matcher.cs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/Ramstack.Globbing/Matcher.cs b/Ramstack.Globbing/Matcher.cs index f54ab00..b2340f3 100644 --- a/Ramstack.Globbing/Matcher.cs +++ b/Ramstack.Globbing/Matcher.cs @@ -498,7 +498,10 @@ static bool IsMatchImpl(ref char rv, int vlen, ref char rp, int plen) var e = ExtractSubpattern(p, pend); var r = DoMatchSegment(p + 1, e, v, vend, subpattern: 1); - if (r > last) + // (char*)-1 is the star-loop abort signal. For an alternative it only means + // that this particular alternative doesn't match, so it must not win here: + // as an unsigned address it is greater than any valid pointer. + if (r > last && r != (char*)-1) last = r; p = e; From 71e5598d6bba6de55189b30929090556f91ccce1 Mon Sep 17 00:00:00 2001 From: rameel Date: Sat, 14 Nov 2026 22:13:05 +0500 Subject: [PATCH 3/4] Fix matching of empty path spans backed by a null reference ReadOnlySpan.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. --- Ramstack.Globbing/Matcher.cs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/Ramstack.Globbing/Matcher.cs b/Ramstack.Globbing/Matcher.cs index b2340f3..ac6a6a8 100644 --- a/Ramstack.Globbing/Matcher.cs +++ b/Ramstack.Globbing/Matcher.cs @@ -159,6 +159,12 @@ ref MemoryMarshal.GetReference(pattern), [MethodImpl(MethodImplOptions.NoInlining)] static bool IsMatchImpl(ref char rv, int vlen, ref char rp, int plen) { + // An empty span may be backed by a null reference (default, ReadOnlySpan.Empty). + // Since null is used internally as the "no match" result, it must never be + // the end-of-path pointer, so an empty path is redirected to a valid location. + if (vlen == 0) + rv = ref MemoryMarshal.GetReference(string.Empty.AsSpan()); + fixed (char* v = &rv, p = &rp) { var vend = v + (uint)vlen; From 597598233c19a6613c9f2b7a9f84c6e48e0cd480 Mon Sep 17 00:00:00 2001 From: rameel Date: Sat, 14 Nov 2026 23:55:11 +0500 Subject: [PATCH 4/4] Add tests for out-of-bounds reads and sentinel handling - 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 --- Ramstack.Globbing.Tests/GuardedBuffer.cs | 121 +++++++++++++++++++++++ Ramstack.Globbing.Tests/MatcherTests.cs | 71 +++++++++++++ 2 files changed, 192 insertions(+) create mode 100644 Ramstack.Globbing.Tests/GuardedBuffer.cs diff --git a/Ramstack.Globbing.Tests/GuardedBuffer.cs b/Ramstack.Globbing.Tests/GuardedBuffer.cs new file mode 100644 index 0000000..7143847 --- /dev/null +++ b/Ramstack.Globbing.Tests/GuardedBuffer.cs @@ -0,0 +1,121 @@ +using System.Diagnostics.CodeAnalysis; +using System.Runtime.InteropServices; + +namespace Ramstack.Globbing; + +/// +/// Represents a text buffer located at the very end of a readable memory page +/// that is immediately followed by an inaccessible (guard) page, so any read past +/// the end of the text results in an access violation instead of silently reading +/// neighboring memory. +/// +[SuppressMessage("ReSharper", "InconsistentNaming")] +internal sealed unsafe class GuardedBuffer : IDisposable +{ + // libc: mmap/mprotect/munmap + private const int PROT_NONE = 0; + private const int PROT_READ = 1; + private const int PROT_WRITE = 2; + private const int MAP_PRIVATE = 0x02; + private const int MAP_ANON_LINUX = 0x20; + private const int MAP_ANON_MACOS = 0x1000; + + // winnt.h + private const uint MEM_COMMIT = 0x1000; + private const uint MEM_RESERVE = 0x2000; + private const uint MEM_RELEASE = 0x8000; + private const uint PAGE_NOACCESS = 0x01; + private const uint PAGE_READWRITE = 0x04; + + private readonly byte* _memory; + private readonly nuint _size; + private readonly char* _text; + private readonly int _length; + + public static bool IsSupported => + OperatingSystem.IsLinux() || OperatingSystem.IsMacOS() || OperatingSystem.IsWindows(); + + public ReadOnlySpan Span => new(_text, _length); + + public GuardedBuffer(string text) + { + var page = (nuint)Environment.SystemPageSize; + var data = ((nuint)text.Length * sizeof(char) + page - 1) / page * page; + + if (data == 0) + data = page; + + _size = data + page; + _memory = Allocate(_size); + + Protect(_memory + data, page); + + _length = text.Length; + _text = (char*)(_memory + data) - _length; + + text.AsSpan().CopyTo(new Span(_text, _length)); + } + + public void Dispose() + { + var released = OperatingSystem.IsWindows() + ? VirtualFree(_memory, 0, MEM_RELEASE) + : munmap(_memory, _size) == 0; + + if (!released) + throw new InvalidOperationException($"Failed to release memory: {Marshal.GetLastWin32Error()}"); + } + + private static byte* Allocate(nuint size) + { + if (OperatingSystem.IsWindows()) + { + var p = VirtualAlloc(null, size, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE); + if (p == null) + throw new InvalidOperationException($"VirtualAlloc failed: {Marshal.GetLastWin32Error()}"); + + return (byte*)p; + } + else + { + var flags = MAP_PRIVATE | (OperatingSystem.IsMacOS() ? MAP_ANON_MACOS : MAP_ANON_LINUX); + var p = mmap(null, size, PROT_READ | PROT_WRITE, flags, -1, 0); + if (p == (void*)-1) + throw new InvalidOperationException($"mmap failed: {Marshal.GetLastWin32Error()}"); + + return (byte*)p; + } + } + + private static void Protect(byte* address, nuint size) + { + if (OperatingSystem.IsWindows()) + { + if (!VirtualProtect(address, size, PAGE_NOACCESS, out _)) + throw new InvalidOperationException($"VirtualProtect failed: {Marshal.GetLastWin32Error()}"); + } + else + { + if (mprotect(address, size, PROT_NONE) != 0) + throw new InvalidOperationException($"mprotect failed: {Marshal.GetLastWin32Error()}"); + } + } + + [DllImport("libc", SetLastError = true)] + private static extern void* mmap(void* addr, nuint length, int prot, int flags, int fd, nint offset); + + [DllImport("libc", SetLastError = true)] + private static extern int mprotect(void* addr, nuint length, int prot); + + [DllImport("libc", SetLastError = true)] + private static extern int munmap(void* addr, nuint length); + + [DllImport("kernel32", SetLastError = true)] + private static extern void* VirtualAlloc(void* address, nuint size, uint allocationType, uint protect); + + [DllImport("kernel32", SetLastError = true)] + private static extern bool VirtualProtect(void* address, nuint size, uint newProtect, out uint oldProtect); + + [DllImport("kernel32", SetLastError = true)] + private static extern bool VirtualFree(void* address, nuint size, uint freeType); +} diff --git a/Ramstack.Globbing.Tests/MatcherTests.cs b/Ramstack.Globbing.Tests/MatcherTests.cs index fd1c495..79e5d07 100644 --- a/Ramstack.Globbing.Tests/MatcherTests.cs +++ b/Ramstack.Globbing.Tests/MatcherTests.cs @@ -247,6 +247,13 @@ public class MatcherTests [TestCase(@"\[", "[", ExpectedResult = true)] [TestCase(@"\[\?\{name]", "[?{name]", ExpectedResult = true)] [TestCase(@"\a\b\c\d\e\f", "abcdef", ExpectedResult = true)] + [TestCase(@"\*", "a", ExpectedResult = false)] + [TestCase(@"\?", "?", ExpectedResult = true)] + [TestCase(@"\?", "a", ExpectedResult = false)] + [TestCase(@"main.\?", "main.c", ExpectedResult = false)] + [TestCase(@"*\?", "main?", ExpectedResult = true)] + [TestCase(@"*\?", "main", ExpectedResult = false)] + [TestCase(@"a\", @"a\", ExpectedResult = false)] [TestCase("[Зз]емля", "Земля", ExpectedResult = true)] [TestCase("[Зз]емля", "земля", ExpectedResult = true)] @@ -277,6 +284,11 @@ public class MatcherTests [TestCase("*{,cs}", "main.c", ExpectedResult = true)] [TestCase("*{,cs}", "main.cpp", ExpectedResult = true)] [TestCase("*{,*}", "main.bak", ExpectedResult = true)] + [TestCase("{*.cs,*.txt}", "main.cs", ExpectedResult = true)] + [TestCase("{*.cs,*.txt}", "main.txt", ExpectedResult = true)] + [TestCase("{*.cs,*.txt}", "main.c", ExpectedResult = false)] + [TestCase("{*a,b}", "b", ExpectedResult = true)] + [TestCase("main.{*a,b}", "main.b", ExpectedResult = true)] [TestCase("*.{[a-z],p?[a-z]}", "main.0", ExpectedResult = false)] [TestCase("*.{[a-z],p?[a-z]}", "main.pd", ExpectedResult = false)] @@ -413,6 +425,65 @@ public bool IsMatch_Unix(string pattern, string path) => public bool IsMatch_Windows(string pattern, string path) => Matcher.IsMatch(path, pattern, MatchFlags.Windows); + [TestCase("", ExpectedResult = true)] + [TestCase("*", ExpectedResult = true)] + [TestCase("**", ExpectedResult = true)] + [TestCase("{,a}", ExpectedResult = true)] + [TestCase("abc", ExpectedResult = false)] + [TestCase("*.cs", ExpectedResult = false)] + [TestCase("*/*", ExpectedResult = false)] + [TestCase("{a", ExpectedResult = false)] + public bool IsMatch_EmptySpanPath(string pattern) => + // ReadOnlySpan.Empty is backed by a null reference + Matcher.IsMatch(ReadOnlySpan.Empty, pattern.AsSpan(), MatchFlags.Unix); + + [TestCase("[a-b]", 4, "a")] + [TestCase("[a-b]", 4, "b")] + [TestCase("[!a]", 2, "a")] + [TestCase("[a-]", 3, "a")] + [TestCase(@"a\?", 2, "ax")] + [TestCase(@"a\b", 2, "ab")] + public void IsMatch_PatternSlice_IgnoresCharsBeyondSlice(string text, int length, string path) + { + var expected = Matcher.IsMatch(path, text[..length], MatchFlags.Unix); + var actual = Matcher.IsMatch(path.AsSpan(), text.AsSpan(0, length), MatchFlags.Unix); + + Assert.That(actual, Is.EqualTo(expected)); + } + + [TestCase(MatchFlags.Unix)] + [TestCase(MatchFlags.Windows)] + public void IsMatch_DoesNotReadBeyondBuffers(MatchFlags flags) + { + if (!GuardedBuffer.IsSupported) + Assert.Ignore("Guard pages are not supported on this platform."); + + // A read past the end of either buffer terminates the test host with an AccessViolationException. + string[] patterns = + [ + "", "[", "[!", "[a", "[!a", "[a-", "[!a-", "[a-b", "[a-b]", "[!a-b]", "[a-]", + @"\", @"a\", @"\a", @"*\", "*[", "*[a-", "{", "{a", "{a,", "{a,b", "{a,b}", "{*a,b}", + "{[a-", "{[a-,b}", "*", "**", "a*", "*a", "?", "**/", "a/**", "**/a", "*/*", "a/[", + ]; + + string[] paths = ["", "a", "b", "-", "ab", "a/b", "a/", @"a\"]; + + Assert.Multiple(() => + { + foreach (var pattern in patterns) + foreach (var path in paths) + { + using var p = new GuardedBuffer(pattern); + using var v = new GuardedBuffer(path); + + var expected = Matcher.IsMatch(path, pattern, flags); + var actual = Matcher.IsMatch(v.Span, p.Span, flags); + + Assert.That(actual, Is.EqualTo(expected), $"pattern: \"{pattern}\", path: \"{path}\""); + } + }); + } + [Test] public void Bang() {