Skip to content

Commit f2cb5fe

Browse files
authored
Add DynamicallyAccessedMembers analyzer (#2184)
* Add DiagnosticId enum Add GetDiagnosticDescriptor * Check that the diagnostic id is in the range of the supported linker warnings * Lint * Share DiagnosticString * Noisy whitespace * Warnings go up to 6000 inclusive * PR feedback * Get diagnostic string Update test * Lint * Tests * Add warnings * Display members using the linker's format * Remove unused Xunit theory * Check for PublicParameterlessCtor Remove unused files * Refactor analyzer * Delete SemanticModelExtensions * Update DiagnosticString * Lint * Rename methods Use DiagnosticId names in for-loop Remove unnecessary if-def Add TryGetAttribute method Add Annotations to shared code in preparation for sharing the logic to retrieve unmatched DAM annotations between linker and analyzer Rename DiagnosticIds Add license headers where missing * Don't warn when the method is RUC annotated Share code between linker and analyzer for retrieving the missing type annotations * Add comments, add source/targetIsMethodReturnType parameters * Match with NamedType for consistency * Remove GetMembersTypesString
1 parent 397f69b commit f2cb5fe

13 files changed

+1529
-242
lines changed
Lines changed: 95 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,95 @@
1+
// Licensed to the .NET Foundation under one or more agreements.
2+
// The .NET Foundation licenses this file to you under the MIT license.
3+
4+
namespace System.Diagnostics.CodeAnalysis
5+
{
6+
/// <summary>
7+
/// Specifies the types of members that are dynamically accessed.
8+
///
9+
/// This enumeration has a <see cref="FlagsAttribute"/> attribute that allows a
10+
/// bitwise combination of its member values.
11+
/// </summary>
12+
[Flags]
13+
internal enum DynamicallyAccessedMemberTypes
14+
{
15+
/// <summary>
16+
/// Specifies no members.
17+
/// </summary>
18+
None = 0,
19+
20+
/// <summary>
21+
/// Specifies the default, parameterless public constructor.
22+
/// </summary>
23+
PublicParameterlessConstructor = 0x0001,
24+
25+
/// <summary>
26+
/// Specifies all public constructors.
27+
/// </summary>
28+
PublicConstructors = 0x0002 | PublicParameterlessConstructor,
29+
30+
/// <summary>
31+
/// Specifies all non-public constructors.
32+
/// </summary>
33+
NonPublicConstructors = 0x0004,
34+
35+
/// <summary>
36+
/// Specifies all public methods.
37+
/// </summary>
38+
PublicMethods = 0x0008,
39+
40+
/// <summary>
41+
/// Specifies all non-public methods.
42+
/// </summary>
43+
NonPublicMethods = 0x0010,
44+
45+
/// <summary>
46+
/// Specifies all public fields.
47+
/// </summary>
48+
PublicFields = 0x0020,
49+
50+
/// <summary>
51+
/// Specifies all non-public fields.
52+
/// </summary>
53+
NonPublicFields = 0x0040,
54+
55+
/// <summary>
56+
/// Specifies all public nested types.
57+
/// </summary>
58+
PublicNestedTypes = 0x0080,
59+
60+
/// <summary>
61+
/// Specifies all non-public nested types.
62+
/// </summary>
63+
NonPublicNestedTypes = 0x0100,
64+
65+
/// <summary>
66+
/// Specifies all public properties.
67+
/// </summary>
68+
PublicProperties = 0x0200,
69+
70+
/// <summary>
71+
/// Specifies all non-public properties.
72+
/// </summary>
73+
NonPublicProperties = 0x0400,
74+
75+
/// <summary>
76+
/// Specifies all public events.
77+
/// </summary>
78+
PublicEvents = 0x0800,
79+
80+
/// <summary>
81+
/// Specifies all non-public events.
82+
/// </summary>
83+
NonPublicEvents = 0x1000,
84+
85+
/// <summary>
86+
/// Specifies all interfaces implemented by the type.
87+
/// </summary>
88+
Interfaces = 0x2000,
89+
90+
/// <summary>
91+
/// Specifies all members.
92+
/// </summary>
93+
All = ~None
94+
}
95+
}
Lines changed: 243 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,243 @@
1+
// Licensed to the .NET Foundation under one or more agreements.
2+
// The .NET Foundation licenses this file to you under the MIT license.
3+
// See the LICENSE file in the project root for more information.
4+
5+
using System;
6+
using System.Collections.Generic;
7+
using System.Collections.Immutable;
8+
using ILLink.Shared;
9+
using Microsoft.CodeAnalysis;
10+
using Microsoft.CodeAnalysis.Diagnostics;
11+
using Microsoft.CodeAnalysis.Operations;
12+
13+
namespace ILLink.RoslynAnalyzer
14+
{
15+
[DiagnosticAnalyzer (LanguageNames.CSharp)]
16+
public class DynamicallyAccessedMembersAnalyzer : DiagnosticAnalyzer
17+
{
18+
internal const string DynamicallyAccessedMembers = nameof (DynamicallyAccessedMembers);
19+
internal const string DynamicallyAccessedMembersAttribute = nameof (DynamicallyAccessedMembersAttribute);
20+
21+
static ImmutableArray<DiagnosticDescriptor> GetSupportedDiagnostics ()
22+
{
23+
var diagDescriptorsArrayBuilder = ImmutableArray.CreateBuilder<DiagnosticDescriptor> (23);
24+
for (int i = (int) DiagnosticId.DynamicallyAccessedMembersMismatchParameterTargetsParameter;
25+
i <= (int) DiagnosticId.DynamicallyAccessedMembersMismatchTypeArgumentTargetsGenericParameter; i++) {
26+
diagDescriptorsArrayBuilder.Add (DiagnosticDescriptors.GetDiagnosticDescriptor ((DiagnosticId) i));
27+
}
28+
29+
return diagDescriptorsArrayBuilder.ToImmutable ();
30+
}
31+
32+
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => GetSupportedDiagnostics ();
33+
34+
public override void Initialize (AnalysisContext context)
35+
{
36+
context.EnableConcurrentExecution ();
37+
context.ConfigureGeneratedCodeAnalysis (GeneratedCodeAnalysisFlags.ReportDiagnostics);
38+
context.RegisterOperationAction (operationAnalysisContext => {
39+
var assignmentOperation = (IAssignmentOperation) operationAnalysisContext.Operation;
40+
ProcessAssignmentOperation (operationAnalysisContext, assignmentOperation);
41+
}, OperationKind.SimpleAssignment);
42+
43+
context.RegisterOperationAction (operationAnalysisContext => {
44+
var invocationOperation = (IInvocationOperation) operationAnalysisContext.Operation;
45+
ProcessInvocationOperation (operationAnalysisContext, invocationOperation);
46+
}, OperationKind.Invocation);
47+
48+
context.RegisterOperationAction (operationAnalysisContext => {
49+
var returnOperation = (IReturnOperation) operationAnalysisContext.Operation;
50+
ProcessReturnOperation (operationAnalysisContext, returnOperation);
51+
}, OperationKind.Return);
52+
}
53+
54+
static void ProcessAssignmentOperation (OperationAnalysisContext context, IAssignmentOperation assignmentOperation)
55+
{
56+
if (context.ContainingSymbol.HasAttribute (RequiresUnreferencedCodeAnalyzer.FullyQualifiedRequiresUnreferencedCodeAttribute))
57+
return;
58+
59+
if (TryGetSymbolFromOperation (assignmentOperation.Target) is not ISymbol target ||
60+
TryGetSymbolFromOperation (assignmentOperation.Value) is not ISymbol source)
61+
return;
62+
63+
if (!target.TryGetDynamicallyAccessedMemberTypes (out var damtOnTarget))
64+
return;
65+
66+
source.TryGetDynamicallyAccessedMemberTypes (out var damtOnSource);
67+
if (Annotations.SourceHasRequiredAnnotations (damtOnSource, damtOnTarget, out var missingAnnotations))
68+
return;
69+
70+
var diag = GetDiagnosticId (source.Kind, target.Kind);
71+
var diagArgs = GetDiagnosticArguments (source.Kind == SymbolKind.NamedType ? context.ContainingSymbol : source, target, missingAnnotations);
72+
context.ReportDiagnostic (Diagnostic.Create (DiagnosticDescriptors.GetDiagnosticDescriptor (diag), assignmentOperation.Syntax.GetLocation (), diagArgs));
73+
}
74+
75+
static void ProcessInvocationOperation (OperationAnalysisContext context, IInvocationOperation invocationOperation)
76+
{
77+
if (context.ContainingSymbol.HasAttribute (RequiresUnreferencedCodeAnalyzer.FullyQualifiedRequiresUnreferencedCodeAttribute))
78+
return;
79+
80+
ProcessTypeArguments (context, invocationOperation);
81+
ProcessArguments (context, invocationOperation);
82+
if (!invocationOperation.TargetMethod.TryGetDynamicallyAccessedMemberTypes (out var damtOnCalledMethod))
83+
return;
84+
85+
if (TryGetSymbolFromOperation (invocationOperation.Instance) is ISymbol instance &&
86+
!instance.HasAttribute (RequiresUnreferencedCodeAnalyzer.FullyQualifiedRequiresUnreferencedCodeAttribute)) {
87+
instance!.TryGetDynamicallyAccessedMemberTypes (out var damtOnCaller);
88+
if (Annotations.SourceHasRequiredAnnotations (damtOnCaller, damtOnCalledMethod, out var missingAnnotations))
89+
return;
90+
91+
var diag = GetDiagnosticId (instance!.Kind, invocationOperation.TargetMethod.Kind);
92+
var diagArgs = GetDiagnosticArguments (instance.Kind == SymbolKind.NamedType ? context.ContainingSymbol : instance, invocationOperation.TargetMethod, missingAnnotations);
93+
context.ReportDiagnostic (Diagnostic.Create (DiagnosticDescriptors.GetDiagnosticDescriptor (diag), invocationOperation.Syntax.GetLocation (), diagArgs));
94+
}
95+
}
96+
97+
static void ProcessReturnOperation (OperationAnalysisContext context, IReturnOperation returnOperation)
98+
{
99+
if (!context.ContainingSymbol.TryGetDynamicallyAccessedMemberTypesOnReturnType (out var damtOnReturnType) ||
100+
context.ContainingSymbol.HasAttribute (RequiresUnreferencedCodeAnalyzer.FullyQualifiedRequiresUnreferencedCodeAttribute))
101+
return;
102+
103+
if (TryGetSymbolFromOperation (returnOperation) is not ISymbol returnedSymbol)
104+
return;
105+
106+
returnedSymbol.TryGetDynamicallyAccessedMemberTypes (out var damtOnReturnedValue);
107+
if (Annotations.SourceHasRequiredAnnotations (damtOnReturnedValue, damtOnReturnType, out var missingAnnotations))
108+
return;
109+
110+
var diag = GetDiagnosticId (returnedSymbol.Kind, context.ContainingSymbol.Kind, true);
111+
var diagArgs = GetDiagnosticArguments (returnedSymbol.Kind == SymbolKind.NamedType ? context.ContainingSymbol : returnedSymbol, context.ContainingSymbol, missingAnnotations);
112+
context.ReportDiagnostic (Diagnostic.Create (DiagnosticDescriptors.GetDiagnosticDescriptor (diag), returnOperation.Syntax.GetLocation (), diagArgs));
113+
}
114+
115+
static void ProcessArguments (OperationAnalysisContext context, IInvocationOperation invocationOperation)
116+
{
117+
if (context.ContainingSymbol.HasAttribute (RequiresUnreferencedCodeAnalyzer.FullyQualifiedRequiresUnreferencedCodeAttribute))
118+
return;
119+
120+
foreach (var argument in invocationOperation.Arguments) {
121+
var targetParameter = argument.Parameter;
122+
if (targetParameter is null || !targetParameter.TryGetDynamicallyAccessedMemberTypes (out var damtOnParameter))
123+
return;
124+
125+
bool sourceIsMethodReturnType = argument.Value.Kind != OperationKind.Conversion;
126+
ISymbol sourceArgument = sourceIsMethodReturnType ? TryGetSymbolFromOperation (argument.Value)! : context.ContainingSymbol;
127+
if (sourceArgument is null)
128+
return;
129+
130+
sourceArgument.TryGetDynamicallyAccessedMemberTypes (out var damtOnArgument);
131+
if (Annotations.SourceHasRequiredAnnotations (damtOnArgument, damtOnParameter, out var missingAnnotations))
132+
return;
133+
134+
IMethodSymbol? callerMethod = null;
135+
// This can only happen within methods of System.Type and derived types.
136+
if (sourceArgument.Kind == SymbolKind.Method && !sourceIsMethodReturnType) {
137+
callerMethod = (IMethodSymbol?) sourceArgument;
138+
sourceArgument = sourceArgument.ContainingType;
139+
}
140+
141+
var diag = GetDiagnosticId (sourceArgument.Kind, targetParameter.Kind);
142+
var diagArgs = GetDiagnosticArguments (callerMethod ?? sourceArgument, targetParameter, missingAnnotations);
143+
context.ReportDiagnostic (Diagnostic.Create (DiagnosticDescriptors.GetDiagnosticDescriptor (diag), argument.Syntax.GetLocation (), diagArgs));
144+
}
145+
}
146+
147+
static void ProcessTypeArguments (OperationAnalysisContext context, IInvocationOperation invocationOperation)
148+
{
149+
var targetMethod = invocationOperation.TargetMethod;
150+
if (targetMethod.HasAttribute (RequiresUnreferencedCodeAnalyzer.FullyQualifiedRequiresUnreferencedCodeAttribute))
151+
return;
152+
153+
for (int i = 0; i < targetMethod.TypeParameters.Length; i++) {
154+
var arg = targetMethod.TypeArguments[i];
155+
var param = targetMethod.TypeParameters[i];
156+
if (!param.TryGetDynamicallyAccessedMemberTypes (out var damtOnTypeParameter))
157+
continue;
158+
159+
arg.TryGetDynamicallyAccessedMemberTypes (out var damtOnTypeArgument);
160+
if (Annotations.SourceHasRequiredAnnotations (damtOnTypeArgument, damtOnTypeParameter, out var missingAnnotations))
161+
continue;
162+
163+
var diag = GetDiagnosticId (arg.Kind, param.Kind);
164+
var diagArgs = GetDiagnosticArguments (arg, param, missingAnnotations);
165+
context.ReportDiagnostic (Diagnostic.Create (DiagnosticDescriptors.GetDiagnosticDescriptor (diag), invocationOperation.Syntax.GetLocation (), diagArgs));
166+
}
167+
}
168+
169+
static DiagnosticId GetDiagnosticId (SymbolKind source, SymbolKind target, bool targetIsMethodReturnType = false)
170+
=> (source, target) switch {
171+
(SymbolKind.Parameter, SymbolKind.Field) => DiagnosticId.DynamicallyAccessedMembersMismatchParameterTargetsField,
172+
(SymbolKind.Parameter, SymbolKind.Method) => targetIsMethodReturnType ?
173+
DiagnosticId.DynamicallyAccessedMembersMismatchParameterTargetsMethodReturnType :
174+
DiagnosticId.DynamicallyAccessedMembersMismatchParameterTargetsThisParameter,
175+
(SymbolKind.Parameter, SymbolKind.Parameter) => DiagnosticId.DynamicallyAccessedMembersMismatchParameterTargetsParameter,
176+
(SymbolKind.Field, SymbolKind.Parameter) => DiagnosticId.DynamicallyAccessedMembersMismatchFieldTargetsParameter,
177+
(SymbolKind.Field, SymbolKind.Field) => DiagnosticId.DynamicallyAccessedMembersMismatchFieldTargetsField,
178+
(SymbolKind.Field, SymbolKind.Method) => targetIsMethodReturnType ?
179+
DiagnosticId.DynamicallyAccessedMembersMismatchFieldTargetsMethodReturnType :
180+
DiagnosticId.DynamicallyAccessedMembersMismatchFieldTargetsThisParameter,
181+
(SymbolKind.Field, SymbolKind.TypeParameter) => DiagnosticId.DynamicallyAccessedMembersMismatchFieldTargetsGenericParameter,
182+
(SymbolKind.NamedType, SymbolKind.Method) => targetIsMethodReturnType ?
183+
DiagnosticId.DynamicallyAccessedMembersMismatchThisParameterTargetsMethodReturnType :
184+
DiagnosticId.DynamicallyAccessedMembersMismatchThisParameterTargetsThisParameter,
185+
(SymbolKind.Method, SymbolKind.Field) => DiagnosticId.DynamicallyAccessedMembersMismatchMethodReturnTypeTargetsField,
186+
(SymbolKind.Method, SymbolKind.Method) => targetIsMethodReturnType ?
187+
DiagnosticId.DynamicallyAccessedMembersMismatchMethodReturnTypeTargetsMethodReturnType :
188+
DiagnosticId.DynamicallyAccessedMembersMismatchMethodReturnTypeTargetsThisParameter,
189+
// Source here will always be a method's return type.
190+
(SymbolKind.Method, SymbolKind.Parameter) => DiagnosticId.DynamicallyAccessedMembersMismatchMethodReturnTypeTargetsParameter,
191+
(SymbolKind.NamedType, SymbolKind.Field) => DiagnosticId.DynamicallyAccessedMembersMismatchThisParameterTargetsField,
192+
(SymbolKind.NamedType, SymbolKind.Parameter) => DiagnosticId.DynamicallyAccessedMembersMismatchThisParameterTargetsParameter,
193+
(SymbolKind.TypeParameter, SymbolKind.Field) => DiagnosticId.DynamicallyAccessedMembersMismatchTypeArgumentTargetsField,
194+
(SymbolKind.TypeParameter, SymbolKind.Method) => DiagnosticId.DynamicallyAccessedMembersMismatchTypeArgumentTargetsMethodReturnType,
195+
(SymbolKind.TypeParameter, SymbolKind.Parameter) => DiagnosticId.DynamicallyAccessedMembersMismatchTypeArgumentTargetsParameter,
196+
(SymbolKind.TypeParameter, SymbolKind.TypeParameter) => DiagnosticId.DynamicallyAccessedMembersMismatchTypeArgumentTargetsGenericParameter,
197+
_ => throw new NotImplementedException ()
198+
};
199+
200+
static string[] GetDiagnosticArguments (ISymbol source, ISymbol target, string missingAnnotations)
201+
{
202+
var args = new List<string> ();
203+
args.AddRange (GetDiagnosticArguments (target));
204+
args.AddRange (GetDiagnosticArguments (source));
205+
args.Add (missingAnnotations);
206+
return args.ToArray ();
207+
}
208+
209+
static IEnumerable<string> GetDiagnosticArguments (ISymbol symbol)
210+
{
211+
var args = new List<string> ();
212+
args.AddRange (symbol.Kind switch {
213+
SymbolKind.Parameter => new string[] { symbol.GetDisplayName (), symbol.ContainingSymbol.GetDisplayName () },
214+
SymbolKind.NamedType => new string[] { symbol.GetDisplayName () },
215+
SymbolKind.Field => new string[] { symbol.GetDisplayName () },
216+
SymbolKind.Method => new string[] { symbol.GetDisplayName () },
217+
SymbolKind.TypeParameter => new string[] { symbol.GetDisplayName (), symbol.ContainingSymbol.GetDisplayName () },
218+
_ => throw new NotImplementedException ($"Unsupported source or target symbol {symbol}.")
219+
});
220+
221+
return args;
222+
}
223+
224+
static ISymbol? TryGetSymbolFromOperation (IOperation? operation) =>
225+
operation switch {
226+
IArgumentOperation argument => TryGetSymbolFromOperation (argument.Value),
227+
IAssignmentOperation assignment => TryGetSymbolFromOperation (assignment.Value),
228+
IConversionOperation conversion => TryGetSymbolFromOperation (conversion.Operand),
229+
// Represents an implicit/explicit reference to an instance. We grab the result type of this operation.
230+
// In cases where this is an implicit reference, this will result in returning the actual type of the
231+
// instance that 'this' represents.
232+
IInstanceReferenceOperation instanceReference => instanceReference.Type,
233+
// The target method of an invocation represents the called method. If this invocation is found within
234+
// a return operation, this representes the returned value, which might be annotated.
235+
IInvocationOperation invocation => invocation.TargetMethod,
236+
IMemberReferenceOperation memberReference => memberReference.Member,
237+
IParameterReferenceOperation parameterReference => parameterReference.Parameter,
238+
IReturnOperation returnOp => TryGetSymbolFromOperation (returnOp.ReturnedValue),
239+
ITypeOfOperation typeOf => typeOf.TypeOperand,
240+
_ => null
241+
};
242+
}
243+
}

src/ILLink.RoslynAnalyzer/ISymbolExtensions.cs

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,51 @@ internal static bool HasAttribute (this ISymbol symbol, string attributeName)
2222
return false;
2323
}
2424

25+
internal static bool TryGetAttribute (this ISymbol member, string attributeName, [NotNullWhen (returnValue: true)] out AttributeData? attribute)
26+
{
27+
attribute = null;
28+
foreach (var _attribute in member.GetAttributes ()) {
29+
if (_attribute.AttributeClass is { } attrClass &&
30+
attrClass.HasName (attributeName)) {
31+
attribute = _attribute;
32+
return true;
33+
}
34+
}
35+
36+
return false;
37+
}
38+
39+
internal static bool TryGetDynamicallyAccessedMemberTypes (this ISymbol symbol, out DynamicallyAccessedMemberTypes? dynamicallyAccessedMemberTypes)
40+
{
41+
dynamicallyAccessedMemberTypes = null;
42+
if (!TryGetAttribute (symbol, DynamicallyAccessedMembersAnalyzer.DynamicallyAccessedMembersAttribute, out var dynamicallyAccessedMembers))
43+
return false;
44+
45+
dynamicallyAccessedMemberTypes = (DynamicallyAccessedMemberTypes) dynamicallyAccessedMembers!.ConstructorArguments[0].Value!;
46+
return true;
47+
}
48+
49+
internal static bool TryGetDynamicallyAccessedMemberTypesOnReturnType (this ISymbol symbol, out DynamicallyAccessedMemberTypes? dynamicallyAccessedMemberTypes)
50+
{
51+
dynamicallyAccessedMemberTypes = null;
52+
if (symbol is not IMethodSymbol methodSymbol)
53+
return false;
54+
55+
AttributeData? dynamicallyAccessedMembers = null;
56+
foreach (var returnTypeAttribute in methodSymbol.GetReturnTypeAttributes ())
57+
if (returnTypeAttribute.AttributeClass is var attrClass && attrClass != null &&
58+
attrClass.HasName (DynamicallyAccessedMembersAnalyzer.DynamicallyAccessedMembersAttribute)) {
59+
dynamicallyAccessedMembers = returnTypeAttribute;
60+
break;
61+
}
62+
63+
if (dynamicallyAccessedMembers == null)
64+
return false;
65+
66+
dynamicallyAccessedMemberTypes = (DynamicallyAccessedMemberTypes) dynamicallyAccessedMembers.ConstructorArguments[0].Value!;
67+
return true;
68+
}
69+
2570
internal static bool TryGetOverriddenMember (this ISymbol? symbol, [NotNullWhen (returnValue: true)] out ISymbol? overridenMember)
2671
{
2772
overridenMember = symbol switch {

0 commit comments

Comments
 (0)