Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
121 changes: 121 additions & 0 deletions Ramstack.Globbing.Tests/GuardedBuffer.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
using System.Diagnostics.CodeAnalysis;
using System.Runtime.InteropServices;

namespace Ramstack.Globbing;

/// <summary>
/// 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.
/// </summary>
[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<char> 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<char>(_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);
}
71 changes: 71 additions & 0 deletions Ramstack.Globbing.Tests/MatcherTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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)]
Expand Down Expand Up @@ -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)]
Expand Down Expand Up @@ -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<char>.Empty is backed by a null reference
Matcher.IsMatch(ReadOnlySpan<char>.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()
{
Expand Down
42 changes: 30 additions & 12 deletions Ramstack.Globbing/Matcher.cs
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,12 @@ ref MemoryMarshal.GetReference(pattern),
[MethodImpl(MethodImplOptions.NoInlining)]
static bool IsMatchImpl<TFlags>(ref char rv, int vlen, ref char rp, int plen)
{
// An empty span may be backed by a null reference (default, ReadOnlySpan<char>.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;
Expand Down Expand Up @@ -290,16 +296,20 @@ static bool IsMatchImpl<TFlags>(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];
Expand All @@ -312,14 +322,13 @@ static bool IsMatchImpl<TFlags>(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;
Expand Down Expand Up @@ -426,11 +435,17 @@ static bool IsMatchImpl<TFlags>(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:
Expand Down Expand Up @@ -489,7 +504,10 @@ static bool IsMatchImpl<TFlags>(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;
Expand Down
Loading