Skip to content

Commit

Permalink
Merge pull request #868 from bluetarpmedia/Fix485
Browse files Browse the repository at this point in the history
Avoid compiler hang from invalid text in AdditionalFiles
  • Loading branch information
AArnott committed Aug 18, 2021
2 parents 981fb43 + 352508b commit 51ddca0
Showing 1 changed file with 24 additions and 4 deletions.
28 changes: 24 additions & 4 deletions src/Microsoft.VisualStudio.Threading.Analyzers/CommonInterest.cs
Expand Up @@ -63,9 +63,11 @@ internal static class CommonInterest

private const RegexOptions FileNamePatternRegexOptions = RegexOptions.IgnoreCase | RegexOptions.Singleline;

private static readonly Regex NegatableTypeOrMemberReferenceRegex = new Regex(@"^(?<negated>!)?\[(?<typeName>[^\[\]\:]+)+\](?:\:\:(?<memberName>\S+))?\s*$", RegexOptions.Singleline | RegexOptions.CultureInvariant);
private static readonly TimeSpan RegexMatchTimeout = TimeSpan.FromSeconds(5); // Prevent expensive CPU hang in Regex.Match if backtracking occurs due to pathological input (see #485).

private static readonly Regex MemberReferenceRegex = new Regex(@"^\[(?<typeName>[^\[\]\:]+)+\]::(?<memberName>\S+)\s*$", RegexOptions.Singleline | RegexOptions.CultureInvariant);
private static readonly Regex NegatableTypeOrMemberReferenceRegex = new Regex(@"^(?<negated>!)?\[(?<typeName>[^\[\]\:]+)+\](?:\:\:(?<memberName>\S+))?\s*$", RegexOptions.Singleline | RegexOptions.CultureInvariant, RegexMatchTimeout);

private static readonly Regex MemberReferenceRegex = new Regex(@"^\[(?<typeName>[^\[\]\:]+)+\]::(?<memberName>\S+)\s*$", RegexOptions.Singleline | RegexOptions.CultureInvariant, RegexMatchTimeout);

/// <summary>
/// An array with '.' as its only element.
Expand All @@ -84,7 +86,16 @@ internal static IEnumerable<TypeMatchSpec> ReadTypesAndMembers(AnalyzerOptions a
{
foreach (string line in ReadAdditionalFiles(analyzerOptions, fileNamePattern, cancellationToken))
{
Match match = NegatableTypeOrMemberReferenceRegex.Match(line);
Match? match = null;
try
{
match = NegatableTypeOrMemberReferenceRegex.Match(line);
}
catch (RegexMatchTimeoutException)
{
throw new InvalidOperationException($"Regex.Match timeout when parsing line: {line}");
}

if (!match.Success)
{
throw new InvalidOperationException($"Parsing error on line: {line}");
Expand Down Expand Up @@ -175,7 +186,16 @@ internal static IEnumerable<string> ReadLinesFromAdditionalFile(SourceText text)

internal static QualifiedMember ParseAdditionalFileMethodLine(string line)
{
Match match = MemberReferenceRegex.Match(line);
Match? match = null;
try
{
match = MemberReferenceRegex.Match(line);
}
catch (RegexMatchTimeoutException)
{
throw new InvalidOperationException($"Regex.Match timeout when parsing line: {line}");
}

if (!match.Success)
{
throw new InvalidOperationException($"Parsing error on line: {line}");
Expand Down

0 comments on commit 51ddca0

Please sign in to comment.