|
| 1 | +using System.Collections.Immutable; |
| 2 | +using Microsoft.CodeAnalysis; |
| 3 | +using Microsoft.CodeAnalysis.CSharp; |
| 4 | +using Microsoft.CodeAnalysis.CSharp.Syntax; |
| 5 | +using Microsoft.CodeAnalysis.Diagnostics; |
| 6 | + |
| 7 | +namespace Confuser.Analyzers { |
| 8 | + /// <summary> |
| 9 | + /// CX004 — flags <c>Assembly.GetTypes()</c> / <c>Module.GetTypes()</c> that are not guarded |
| 10 | + /// against <see cref="System.Reflection.ReflectionTypeLoadException" />. That exception is |
| 11 | + /// thrown whenever a contained type cannot be loaded (common for plugin assemblies with |
| 12 | + /// unresolved dependencies) and caused packer/plugin startup crashes. |
| 13 | + /// </summary> |
| 14 | + [DiagnosticAnalyzer(LanguageNames.CSharp)] |
| 15 | + public sealed class UnhandledReflectionTypeLoadAnalyzer : DiagnosticAnalyzer { |
| 16 | + static readonly DiagnosticDescriptor Rule = new DiagnosticDescriptor( |
| 17 | + DiagnosticIds.UnhandledReflectionTypeLoad, |
| 18 | + "GetTypes() without ReflectionTypeLoadException handling", |
| 19 | + "'{0}.GetTypes()' can throw ReflectionTypeLoadException when a contained type is unresolvable; wrap it in a try/catch", |
| 20 | + DiagnosticIds.Category, |
| 21 | + DiagnosticSeverity.Warning, |
| 22 | + isEnabledByDefault: true, |
| 23 | + description: "Assembly.GetTypes() and Module.GetTypes() throw ReflectionTypeLoadException when any " + |
| 24 | + "contained type cannot be loaded. Guard the call (and prefer ex.Types on the exception) to avoid " + |
| 25 | + "startup crashes when loading plugin or external assemblies."); |
| 26 | + |
| 27 | + public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Rule); |
| 28 | + |
| 29 | + public override void Initialize(AnalysisContext context) { |
| 30 | + context.EnableConcurrentExecution(); |
| 31 | + context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); |
| 32 | + context.RegisterSyntaxNodeAction(Analyze, SyntaxKind.InvocationExpression); |
| 33 | + } |
| 34 | + |
| 35 | + static void Analyze(SyntaxNodeAnalysisContext context) { |
| 36 | + var invocation = (InvocationExpressionSyntax)context.Node; |
| 37 | + if (invocation.Expression is not MemberAccessExpressionSyntax member || |
| 38 | + member.Name.Identifier.ValueText != "GetTypes") |
| 39 | + return; |
| 40 | + |
| 41 | + if (context.SemanticModel.GetSymbolInfo(invocation, context.CancellationToken).Symbol is not IMethodSymbol method || |
| 42 | + method.Name != "GetTypes" || !method.Parameters.IsEmpty) |
| 43 | + return; |
| 44 | + |
| 45 | + var containingType = method.ContainingType?.ToDisplayString(); |
| 46 | + if (containingType != "System.Reflection.Assembly" && containingType != "System.Reflection.Module") |
| 47 | + return; |
| 48 | + |
| 49 | + var rtle = context.Compilation.GetTypeByMetadataName("System.Reflection.ReflectionTypeLoadException"); |
| 50 | + if (IsGuarded(invocation, context.SemanticModel, rtle, context.CancellationToken)) |
| 51 | + return; |
| 52 | + |
| 53 | + context.ReportDiagnostic(Diagnostic.Create(Rule, member.Name.GetLocation(), containingType)); |
| 54 | + } |
| 55 | + |
| 56 | + static bool IsGuarded(SyntaxNode node, SemanticModel model, INamedTypeSymbol? rtle, System.Threading.CancellationToken ct) { |
| 57 | + for (var current = node.Parent; current != null; current = current.Parent) { |
| 58 | + if (current is TryStatementSyntax tryStmt && |
| 59 | + tryStmt.Block.Span.Contains(node.Span) && |
| 60 | + CatchesReflectionTypeLoad(tryStmt, model, rtle, ct)) |
| 61 | + return true; |
| 62 | + |
| 63 | + // Do not walk past the enclosing method / lambda / local-function boundary. |
| 64 | + if (current is BaseMethodDeclarationSyntax || |
| 65 | + current is AnonymousFunctionExpressionSyntax || |
| 66 | + current is LocalFunctionStatementSyntax) |
| 67 | + break; |
| 68 | + } |
| 69 | + |
| 70 | + return false; |
| 71 | + } |
| 72 | + |
| 73 | + static bool CatchesReflectionTypeLoad(TryStatementSyntax tryStmt, SemanticModel model, INamedTypeSymbol? rtle, |
| 74 | + System.Threading.CancellationToken ct) { |
| 75 | + foreach (var clause in tryStmt.Catches) { |
| 76 | + // A general 'catch { }' (no declared type) catches everything. |
| 77 | + if (clause.Declaration is null) |
| 78 | + return true; |
| 79 | + |
| 80 | + var caught = model.GetTypeInfo(clause.Declaration.Type, ct).Type as INamedTypeSymbol; |
| 81 | + if (caught is null) |
| 82 | + continue; |
| 83 | + |
| 84 | + // The catch guards the call if ReflectionTypeLoadException is assignable to the caught |
| 85 | + // type (i.e. the caught type is RTLE or one of its base types such as SystemException / |
| 86 | + // Exception). If we cannot resolve RTLE, fall back to name matching on the base chain. |
| 87 | + if (rtle is not null) { |
| 88 | + for (var t = rtle; t is not null; t = t.BaseType) { |
| 89 | + if (SymbolEqualityComparer.Default.Equals(t, caught)) |
| 90 | + return true; |
| 91 | + } |
| 92 | + } |
| 93 | + else { |
| 94 | + var name = caught.ToDisplayString(); |
| 95 | + if (name == "System.Exception" || name == "System.SystemException" || |
| 96 | + name == "System.Reflection.ReflectionTypeLoadException") |
| 97 | + return true; |
| 98 | + } |
| 99 | + } |
| 100 | + |
| 101 | + return false; |
| 102 | + } |
| 103 | + } |
| 104 | +} |
0 commit comments