Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Address some crashes found by fuzz testing. #43280

Merged
merged 6 commits into from
Apr 15, 2020
Merged
Show file tree
Hide file tree
Changes from 2 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
13 changes: 5 additions & 8 deletions src/Compilers/CSharp/Portable/Binder/Binder_Patterns.cs
Original file line number Diff line number Diff line change
Expand Up @@ -225,7 +225,7 @@ private BoundExpression BindExpressionOrTypeForPattern(
else
{
Debug.Assert(expression is { Kind: BoundKind.TypeExpression, Type: { } });
hasErrors |= CheckValidPatternType(patternExpression, inputType, expression.Type, patternTypeWasInSource: true, diagnostics: diagnostics);
hasErrors |= CheckValidPatternType(patternExpression, inputType, expression.Type, diagnostics: diagnostics);
return expression;
}
}
Expand Down Expand Up @@ -385,7 +385,6 @@ private bool CheckValidPatternType(
SyntaxNode typeSyntax,
TypeSymbol inputType,
TypeSymbol patternType,
bool patternTypeWasInSource,
DiagnosticBag diagnostics)
{
RoslynDebug.Assert((object)inputType != null);
Expand All @@ -401,7 +400,7 @@ private bool CheckValidPatternType(
diagnostics.Add(ErrorCode.ERR_PointerTypeInPatternMatching, typeSyntax.Location);
return true;
}
else if (patternType.IsNullableType() && patternTypeWasInSource)
else if (patternType.IsNullableType() || typeSyntax is NullableTypeSyntax)
{
// It is an error to use pattern-matching with a nullable type, because you'll never get null. Use the underlying type.
Error(diagnostics, ErrorCode.ERR_PatternNullableType, typeSyntax, patternType, patternType.GetNullableUnderlyingType());
Expand Down Expand Up @@ -505,12 +504,10 @@ private BoundTypeExpression BindTypeForPattern(
ref bool hasErrors)
{
RoslynDebug.Assert(inputType is { });
Debug.Assert(!typeSyntax.IsVar); // if the syntax had `var`, it would have been parsed as a var pattern.
TypeWithAnnotations declType = BindType(typeSyntax, diagnostics, out AliasSymbol aliasOpt);
Debug.Assert(declType.HasType);
Debug.Assert(typeSyntax.Kind() != SyntaxKind.NullableType); // the syntax does not permit nullable annotations
BoundTypeExpression boundDeclType = new BoundTypeExpression(typeSyntax, aliasOpt, typeWithAnnotations: declType);
hasErrors |= CheckValidPatternType(typeSyntax, inputType, declType.Type, patternTypeWasInSource: true, diagnostics: diagnostics);
hasErrors |= CheckValidPatternType(typeSyntax, inputType, declType.Type, diagnostics: diagnostics);
return boundDeclType;
}

Expand Down Expand Up @@ -708,7 +705,7 @@ deconstructMethod is null &&
syntax: node, declaredType: boundDeclType, deconstructMethod: deconstructMethod,
deconstruction: deconstructionSubpatterns, properties: properties, variable: variableSymbol,
variableAccess: variableAccess, isExplicitNotNullTest: isExplicitNotNullTest, inputType: inputType,
convertedType: boundDeclType?.Type ?? inputType, hasErrors: hasErrors);
convertedType: boundDeclType?.Type ?? inputType.StrippedType(), hasErrors: hasErrors);
}

private MethodSymbol? BindDeconstructSubpatterns(
Expand Down Expand Up @@ -1074,7 +1071,7 @@ private BoundPattern BindVarDesignation(
return new BoundRecursivePattern(
syntax: node, declaredType: null, deconstructMethod: deconstructMethod,
deconstruction: subPatterns.ToImmutableAndFree(), properties: default, variable: null, variableAccess: null,
isExplicitNotNullTest: false, inputType: inputType, convertedType: inputType, hasErrors: hasErrors);
isExplicitNotNullTest: false, inputType: inputType, convertedType: inputType.StrippedType(), hasErrors: hasErrors);

void addSubpatternsForTuple(ImmutableArray<TypeWithAnnotations> elementTypes)
{
Expand Down
4 changes: 2 additions & 2 deletions src/Compilers/CSharp/Portable/Binder/DecisionDagBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -471,7 +471,7 @@ private Tests MakeTestsAndBindingsForRecursivePattern(
out BoundDagTemp output,
ArrayBuilder<BoundPatternBinding> bindings)
{
RoslynDebug.Assert(input.Type.IsErrorType() || recursive.InputType.IsErrorType() || input.Type.Equals(recursive.InputType, TypeCompareKind.AllIgnoreOptions));
RoslynDebug.Assert(input.Type.IsErrorType() || recursive.HasErrors || recursive.InputType.IsErrorType() || input.Type.Equals(recursive.InputType, TypeCompareKind.AllIgnoreOptions));
var inputType = recursive.DeclaredType?.Type ?? input.Type.StrippedType();
var tests = ArrayBuilder<Tests>.GetInstance(5);
output = input = MakeConvertToType(input, recursive.Syntax, inputType, isExplicitTest: recursive.IsExplicitNotNullTest, tests);
Expand Down Expand Up @@ -601,7 +601,7 @@ private Tests MakeTestsAndBindingsForBinaryPattern(
builder.Add(MakeTestsAndBindings(input, bin.Left, out var leftOutput, bindings));
builder.Add(MakeTestsAndBindings(leftOutput, bin.Right, out var rightOutput, bindings));
output = rightOutput;
Debug.Assert(output.Type.Equals(bin.ConvertedType, TypeCompareKind.AllIgnoreOptions));
Debug.Assert(bin.HasErrors || output.Type.Equals(bin.ConvertedType, TypeCompareKind.AllIgnoreOptions));
return Tests.AndSequence.Create(builder);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -526,6 +526,9 @@ void addToTempMap(BoundDagTemp output, int slot, TypeSymbol type)
bool isDerivedType(TypeSymbol derivedType, TypeSymbol baseType)
{
HashSet<DiagnosticInfo> discardedDiagnostics = null;
if (derivedType.IsErrorType() || baseType.IsErrorType())
return true;

return _conversions.WithNullability(false).ClassifyConversionFromType(derivedType, baseType, ref discardedDiagnostics).Kind switch
{
ConversionKind.Identity => true,
Expand Down
135 changes: 126 additions & 9 deletions src/Compilers/CSharp/Test/Semantic/Semantics/PatternMatchingTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,11 @@
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
Expand Down Expand Up @@ -4829,17 +4831,102 @@ public static void Main(string[] args)
VerifyModelForDeclarationOrVarSimplePattern(model, x3Decl[0], x3Ref);
}

[Fact]
public void Fuzz_Conjunction_01()
{
var program = @"
public class Program
{
public static void Main(string[] args)
{
if (((int?)1) is {} and 1) { }
}
}";
var compilation = CreateCompilation(program, parseOptions: TestOptions.RegularWithPatternCombinators).VerifyDiagnostics(
);
}

[Fact]
public void Fuzz_738490379()
{
var program = @"
public class Program738490379
{
public static void Main(string[] args)
{
if (NotFound is var (M, not int _ or NotFound _) { }) {}
}
private static object M() => null;
}";
var compilation = CreateCompilation(program, parseOptions: TestOptions.RegularWithPatternCombinators).VerifyDiagnostics(
// (6,13): error CS0841: Cannot use local variable 'NotFound' before it is declared
// if (NotFound is var (M, not int _ or NotFound _) { }) {}
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "NotFound").WithArguments("NotFound").WithLocation(6, 13),
// (6,37): error CS1026: ) expected
// if (NotFound is var (M, not int _ or NotFound _) { }) {}
Diagnostic(ErrorCode.ERR_CloseParenExpected, "int").WithLocation(6, 37),
// (6,37): error CS1026: ) expected
// if (NotFound is var (M, not int _ or NotFound _) { }) {}
Diagnostic(ErrorCode.ERR_CloseParenExpected, "int").WithLocation(6, 37),
// (6,37): error CS1023: Embedded statement cannot be a declaration or labeled statement
// if (NotFound is var (M, not int _ or NotFound _) { }) {}
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "int _ ").WithLocation(6, 37),
// (6,41): warning CS0168: The variable '_' is declared but never used
// if (NotFound is var (M, not int _ or NotFound _) { }) {}
Diagnostic(ErrorCode.WRN_UnreferencedVar, "_").WithArguments("_").WithLocation(6, 41),
// (6,43): error CS1002: ; expected
// if (NotFound is var (M, not int _ or NotFound _) { }) {}
Diagnostic(ErrorCode.ERR_SemicolonExpected, "or").WithLocation(6, 43),
// (6,43): error CS0246: The type or namespace name 'or' could not be found (are you missing a using directive or an assembly reference?)
// if (NotFound is var (M, not int _ or NotFound _) { }) {}
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "or").WithArguments("or").WithLocation(6, 43),
// (6,55): error CS1002: ; expected
// if (NotFound is var (M, not int _ or NotFound _) { }) {}
Diagnostic(ErrorCode.ERR_SemicolonExpected, "_").WithLocation(6, 55),
// (6,55): error CS0103: The name '_' does not exist in the current context
// if (NotFound is var (M, not int _ or NotFound _) { }) {}
Diagnostic(ErrorCode.ERR_NameNotInContext, "_").WithArguments("_").WithLocation(6, 55),
// (6,56): error CS1002: ; expected
// if (NotFound is var (M, not int _ or NotFound _) { }) {}
Diagnostic(ErrorCode.ERR_SemicolonExpected, ")").WithLocation(6, 56),
// (6,56): error CS1513: } expected
// if (NotFound is var (M, not int _ or NotFound _) { }) {}
Diagnostic(ErrorCode.ERR_RbraceExpected, ")").WithLocation(6, 56),
// (6,62): error CS1513: } expected
// if (NotFound is var (M, not int _ or NotFound _) { }) {}
Diagnostic(ErrorCode.ERR_RbraceExpected, ")").WithLocation(6, 62)
);
}

[Fact(Skip = "https://github.com/dotnet/roslyn/issues/16721")]
public void Fuzz()
{
const int numTests = 1000000;
const int numTests = 1200000;
int dt = (int)Math.Abs(DateTime.Now.Ticks % 1000000000);
for (int i = 1; i < numTests; i++)
{
PatternMatchingFuzz(i + dt);
}
}

[Fact(Skip = "https://github.com/dotnet/roslyn/issues/16721")]
public void MultiFuzz()
{
// Just like Fuzz(), but take advantage of concurrency on the test host.
const int numTasks = 300;
const int numTestsPerTask = 4000;
int dt = (int)Math.Abs(DateTime.Now.Ticks % 1000000000);
var tasks = Enumerable.Range(0, numTasks).Select(t => Task.Run(() =>
{
int k = dt + t * numTestsPerTask;
for (int i = 1; i < numTestsPerTask; i++)
{
PatternMatchingFuzz(i + k);
}
}));
Task.WaitAll(tasks.ToArray());
Copy link
Member

@cston cston Apr 13, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Task.WaitAll(tasks.ToArray()) [](start = 12, length = 29)

Is it important that the tests run in parallel rather than sequentially? It's not clear where in PatternMatchingFuzz() there is shared state. If it's not important, consider making this sequential or include a comment. #Resolved

Copy link
Member Author

@gafter gafter Apr 13, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I have a 32-thread processor on my desk. This is just a way of getting much more testing done per unit time. It is otherwise the same as the adjacent sequential version. Both are skipped. #Resolved

}

private static void PatternMatchingFuzz(int dt)
{
Random r = new Random(dt);
Expand Down Expand Up @@ -4875,18 +4962,48 @@ string Expression()
"NotFound"
};
string Type() => types[r.Next(types.Length)];
string Pattern()
string Pattern(int d = 5)
{
switch (r.Next(3))
switch (r.Next(d <= 1 ? 9 : 12))
{
case 0:
default:
return Expression(); // a "constant" pattern
case 1:
return Type() + " x" + r.Next(10);
case 2:
case 3:
case 4:
return Type();
case 5:
return Type() + " _";
default:
throw null;
case 6:
return Type() + " x" + r.Next(10);
case 7:
return "not " + Pattern(d - 1);
case 8:
return "(" + Pattern(d - 1) + ")";
case 9:
return makeRecursivePattern(d);
case 10:
return Pattern(d - 1) + " and " + Pattern(d - 1);
case 11:
return Pattern(d - 1) + " or " + Pattern(d - 1);
}

string makeRecursivePattern(int d)
{
while (true)
{
bool haveParens = r.Next(2) == 0;
bool haveCurlies = r.Next(2) == 0;
if (!haveParens && !haveCurlies)
continue;
bool haveType = r.Next(2) == 0;
bool haveIdentifier = r.Next(2) == 0;
return $"{(haveType ? Type() : null)} {(haveParens ? $"({makePatternList(d - 1, false)})" : null)} {(haveCurlies ? $"{"{ "}{makePatternList(d - 1, true)}{" }"}" : null)} {(haveIdentifier ? " x" + r.Next(10) : null)}";
}
}

string makePatternList(int d, bool propNames)
{
return string.Join(", ", Enumerable.Range(0, r.Next(3)).Select(i => $"{(propNames ? $"P{r.Next(10)}: " : null)}{Pattern(d)}"));
}
}
string body = @"
Expand Down