Skip to content

Commit

Permalink
Add missing regex position check after BOL optimization (#66216)
Browse files Browse the repository at this point in the history
* Add missing regex position check after BOL optimization

* Address PR feedback
  • Loading branch information
stephentoub authored Mar 7, 2022
1 parent 9f51335 commit 277e12b
Show file tree
Hide file tree
Showing 4 changed files with 62 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -535,6 +535,17 @@ bool EmitAnchors()
Goto(NoStartingPositionFound);
}
writer.WriteLine("pos = newlinePos + pos + 1;");

// We've updated the position. Make sure there's still enough room in the input for a possible match.
using (EmitBlock(writer, minRequiredLength switch
{
0 => "if (pos > inputSpan.Length)",
1 => "if (pos >= inputSpan.Length)",
_ => $"if (pos > inputSpan.Length - {minRequiredLength})"
}))
{
Goto(NoStartingPositionFound);
}
}
writer.WriteLine();
break;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -622,6 +622,18 @@ bool GenerateAnchors()
Ldc(1);
Add();
Stloc(pos);

// We've updated the position. Make sure there's still enough room in the input for a possible match.
// if (pos > inputSpan.Length - minRequiredLength) returnFalse;
Ldloca(inputSpan);
Call(s_spanGetLengthMethod);
if (minRequiredLength != 0)
{
Ldc(minRequiredLength);
Sub();
}
Ldloc(pos);
BltFar(returnFalse);
}

MarkLabel(label);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -281,7 +281,13 @@ public bool TryFindNextStartingPosition(ReadOnlySpan<char> textSpan, ref int pos
return false;
}

// We've updated the position. Make sure there's still enough room in the input for a possible match.
pos = newline + 1 + pos;
if (pos > textSpan.Length - MinRequiredLength)
{
pos = textSpan.Length;
return false;
}
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -176,7 +176,7 @@ public static IEnumerable<object[]> Matches_TestData()
}
};

// Using ^ with multiline
// Using ^ and $ with multiline
yield return new object[]
{
engine,
Expand Down Expand Up @@ -244,6 +244,38 @@ public static IEnumerable<object[]> Matches_TestData()
}
};

yield return new object[]
{
engine,
@"^[^a]a", "bar\n", RegexOptions.Multiline,
new[]
{
new CaptureData("ba", 0, 2)
}
};

yield return new object[]
{
engine,
@"^[^a]a", "car\nbar\n", RegexOptions.Multiline,
new[]
{
new CaptureData("ca", 0, 2),
new CaptureData("ba", 4, 2)
}
};

yield return new object[]
{
engine,
@"[0-9]cat$", "1cat\n2cat", RegexOptions.Multiline,
new[]
{
new CaptureData("1cat", 0, 4),
new CaptureData("2cat", 5, 4)
}
};

if (!PlatformDetection.IsNetFramework)
{
// .NET Framework missing fix in https://github.com/dotnet/runtime/pull/1075
Expand Down

0 comments on commit 277e12b

Please sign in to comment.