|
| 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 | + /// CX003 — an awareness/audit rule that surfaces every call to a dnlib <c>Resolve…Throw</c> |
| 10 | + /// helper (<c>ResolveThrow</c>, <c>ResolveTypeDefThrow</c>, <c>ResolveMethodDefThrow</c>, |
| 11 | + /// <c>ResolveFieldThrow</c>). These throw when a reference cannot be resolved, which crashes |
| 12 | + /// obfuscation on assemblies with external/unresolvable members. Most uses are intentional; |
| 13 | + /// this reports at <see cref="DiagnosticSeverity.Info" /> so the spots can be evaluated |
| 14 | + /// without adding build noise. |
| 15 | + /// </summary> |
| 16 | + [DiagnosticAnalyzer(LanguageNames.CSharp)] |
| 17 | + public sealed class ResolveThrowAuditAnalyzer : DiagnosticAnalyzer { |
| 18 | + static readonly DiagnosticDescriptor Rule = new DiagnosticDescriptor( |
| 19 | + DiagnosticIds.ResolveThrowAudit, |
| 20 | + "Throwing resolve helper used", |
| 21 | + "'{0}' throws when resolution fails; confirm the target is always resolvable or prefer the non-throwing overload with a null check", |
| 22 | + DiagnosticIds.Category, |
| 23 | + DiagnosticSeverity.Info, |
| 24 | + isEnabledByDefault: true, |
| 25 | + description: "dnlib's Resolve...Throw helpers throw when a type/member reference cannot be " + |
| 26 | + "resolved. This surfaces each usage for review; external or unresolvable references should " + |
| 27 | + "use the non-throwing Resolve... overload with a null check instead."); |
| 28 | + |
| 29 | + public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Rule); |
| 30 | + |
| 31 | + public override void Initialize(AnalysisContext context) { |
| 32 | + context.EnableConcurrentExecution(); |
| 33 | + context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); |
| 34 | + context.RegisterSyntaxNodeAction(Analyze, SyntaxKind.InvocationExpression); |
| 35 | + } |
| 36 | + |
| 37 | + static void Analyze(SyntaxNodeAnalysisContext context) { |
| 38 | + var invocation = (InvocationExpressionSyntax)context.Node; |
| 39 | + if (invocation.Expression is not MemberAccessExpressionSyntax member) |
| 40 | + return; |
| 41 | + |
| 42 | + var name = member.Name.Identifier.ValueText; |
| 43 | + if (!IsResolveThrowName(name)) |
| 44 | + return; |
| 45 | + |
| 46 | + context.ReportDiagnostic(Diagnostic.Create(Rule, member.Name.GetLocation(), name)); |
| 47 | + } |
| 48 | + |
| 49 | + static bool IsResolveThrowName(string name) => |
| 50 | + name.Length > "ResolveThrow".Length - 1 && |
| 51 | + name.StartsWith("Resolve", System.StringComparison.Ordinal) && |
| 52 | + name.EndsWith("Throw", System.StringComparison.Ordinal); |
| 53 | + } |
| 54 | +} |
0 commit comments