-
Notifications
You must be signed in to change notification settings - Fork 292
Expand file tree
/
Copy pathReflectionOperations.cs
More file actions
362 lines (313 loc) · 15.4 KB
/
ReflectionOperations.cs
File metadata and controls
362 lines (313 loc) · 15.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.Interface;
namespace Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices;
/// <summary>
/// This service is responsible for platform specific reflection operations.
/// </summary>
internal sealed class ReflectionOperations : IReflectionOperations
{
private const BindingFlags DeclaredOnlyLookup = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly;
private const BindingFlags Everything = BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance;
/// <summary>
/// Gets all the custom attributes adorned on a member.
/// </summary>
/// <param name="memberInfo"> The member. </param>
/// <returns> The list of attributes on the member. Empty list if none found. </returns>
[return: NotNullIfNotNull(nameof(memberInfo))]
public object[]? GetCustomAttributes(MemberInfo memberInfo)
#if NETFRAMEWORK
=> [.. GetCustomAttributesImpl(memberInfo)];
#else
{
object[] attributes = memberInfo.GetCustomAttributes(typeof(Attribute), inherit: true);
// Ensures that when the return of this method is used here:
// https://github.com/microsoft/testfx/blob/e101a9d48773cc935c7b536d25d378d9a3211fee/src/Adapter/MSTest.TestAdapter/Helpers/ReflectHelper.cs#L461
// then we are already Attribute[] to avoid LINQ Cast and extra array allocation.
// This assert is solely for performance. Nothing "functional" will go wrong if the assert failed.
Debug.Assert(attributes is Attribute[], $"Expected Attribute[], found '{attributes.GetType()}'.");
return attributes;
}
#endif
/// <summary>
/// Gets all the custom attributes of a given type adorned on a member.
/// </summary>
/// <param name="memberInfo"> The member info. </param>
/// <param name="type"> The attribute type. </param>
/// <returns> The list of attributes on the member. Empty list if none found. </returns>
[return: NotNullIfNotNull(nameof(memberInfo))]
public object[]? GetCustomAttributes(MemberInfo memberInfo, Type type) =>
#if NETFRAMEWORK
[.. GetCustomAttributesCoreImpl(memberInfo, type)];
#else
memberInfo.GetCustomAttributes(type, inherit: true);
#endif
/// <summary>
/// Gets all the custom attributes of a given type on an assembly.
/// </summary>
/// <param name="assembly"> The assembly. </param>
/// <param name="type"> The attribute type. </param>
/// <returns> The list of attributes of the given type on the member. Empty list if none found. </returns>
public object[] GetCustomAttributes(Assembly assembly, Type type) =>
#if NETFRAMEWORK
GetCustomAttributesFromAssembly(assembly, type).ToArray();
#else
assembly.GetCustomAttributes(type, inherit: true);
#endif
#if NETFRAMEWORK
/// <summary>
/// Gets all the custom attributes adorned on a member.
/// </summary>
/// <param name="memberInfo"> The member. </param>
/// <returns> The list of attributes on the member. Empty list if none found. </returns>
private static IReadOnlyList<object> GetCustomAttributesImpl(MemberInfo memberInfo)
=> GetCustomAttributesCoreImpl(memberInfo, type: null);
/// <summary>
/// Get custom attributes on a member for both normal and reflection only load.
/// </summary>
/// <param name="memberInfo">Member for which attributes needs to be retrieved.</param>
/// <param name="type">Type of attribute to retrieve.</param>
/// <returns>All attributes of give type on member.</returns>
#pragma warning disable CA1859 // Use concrete types when possible for improved performance
private static IReadOnlyList<object> GetCustomAttributesCoreImpl(MemberInfo memberInfo, Type? type)
#pragma warning restore CA1859
{
bool shouldGetAllAttributes = type == null;
if (!IsReflectionOnlyLoad(memberInfo))
{
return shouldGetAllAttributes ? memberInfo.GetCustomAttributes(inherit: true) : memberInfo.GetCustomAttributes(type, inherit: true);
}
List<object> nonUniqueAttributes = [];
Dictionary<string, object> uniqueAttributes = [];
int inheritanceThreshold = 10;
int inheritanceLevel = 0;
if (memberInfo.MemberType == MemberTypes.TypeInfo)
{
// This code is based on the code for fetching CustomAttributes in System.Reflection.CustomAttribute(RuntimeType type, RuntimeType caType, bool inherit)
var tempTypeInfo = memberInfo as TypeInfo;
do
{
IList<CustomAttributeData> attributes = CustomAttributeData.GetCustomAttributes(tempTypeInfo);
AddNewAttributes(
attributes,
shouldGetAllAttributes,
type!,
uniqueAttributes,
nonUniqueAttributes);
tempTypeInfo = tempTypeInfo!.BaseType?.GetTypeInfo();
inheritanceLevel++;
}
while (tempTypeInfo != null && tempTypeInfo != typeof(object).GetTypeInfo()
&& inheritanceLevel < inheritanceThreshold);
}
else if (memberInfo.MemberType == MemberTypes.Method)
{
// This code is based on the code for fetching CustomAttributes in System.Reflection.CustomAttribute(RuntimeMethodInfo method, RuntimeType caType, bool inherit).
var tempMethodInfo = memberInfo as MethodInfo;
do
{
IList<CustomAttributeData> attributes = CustomAttributeData.GetCustomAttributes(tempMethodInfo);
AddNewAttributes(
attributes,
shouldGetAllAttributes,
type!,
uniqueAttributes,
nonUniqueAttributes);
MethodInfo? baseDefinition = tempMethodInfo!.GetBaseDefinition();
if (baseDefinition != null
&& string.Equals(
string.Concat(tempMethodInfo.DeclaringType.FullName, tempMethodInfo.Name),
string.Concat(baseDefinition.DeclaringType.FullName, baseDefinition.Name), StringComparison.Ordinal))
{
break;
}
tempMethodInfo = baseDefinition;
inheritanceLevel++;
}
while (tempMethodInfo != null && inheritanceLevel < inheritanceThreshold);
}
else
{
// Ideally we should not be reaching here. We only query for attributes on types/methods currently.
// Return the attributes that CustomAttributeData returns in this cases not considering inheritance.
IList<CustomAttributeData> firstLevelAttributes =
CustomAttributeData.GetCustomAttributes(memberInfo);
AddNewAttributes(firstLevelAttributes, shouldGetAllAttributes, type!, uniqueAttributes, nonUniqueAttributes);
}
nonUniqueAttributes.AddRange(uniqueAttributes.Values);
return nonUniqueAttributes;
}
private static List<Attribute> GetCustomAttributesFromAssembly(Assembly assembly, Type type)
{
if (!assembly.ReflectionOnly)
{
return [.. assembly.GetCustomAttributes(type)];
}
List<CustomAttributeData> customAttributes = [.. CustomAttributeData.GetCustomAttributes(assembly)];
List<Attribute> attributesArray = [];
foreach (CustomAttributeData attribute in customAttributes)
{
if (!IsTypeInheriting(attribute.Constructor.DeclaringType, type)
&& !attribute.Constructor.DeclaringType.AssemblyQualifiedName.Equals(
type.AssemblyQualifiedName, StringComparison.Ordinal))
{
continue;
}
Attribute? attributeInstance = CreateAttributeInstance(attribute);
if (attributeInstance != null)
{
attributesArray.Add(attributeInstance);
}
}
return attributesArray;
}
/// <summary>
/// Create instance of the attribute for reflection only load.
/// </summary>
/// <param name="attributeData">The attribute data.</param>
/// <returns>An attribute.</returns>
private static Attribute? CreateAttributeInstance(CustomAttributeData attributeData)
{
object? attribute = null;
try
{
// Create instance of attribute. For some case, constructor param is returned as ReadOnlyCollection
// instead of array. So convert it to array else constructor invoke will fail.
var attributeType = Type.GetType(attributeData.Constructor.DeclaringType.AssemblyQualifiedName);
List<Type> constructorParameters = [];
List<object> constructorArguments = [];
foreach (CustomAttributeTypedArgument parameter in attributeData.ConstructorArguments)
{
var parameterType = Type.GetType(parameter.ArgumentType.AssemblyQualifiedName);
constructorParameters.Add(parameterType);
if (!parameterType.IsArray
|| parameter.Value is not IEnumerable enumerable)
{
constructorArguments.Add(parameter.Value);
continue;
}
ArrayList list = [];
foreach (object? item in enumerable)
{
if (item is CustomAttributeTypedArgument argument)
{
list.Add(argument.Value);
}
else
{
list.Add(item);
}
}
constructorArguments.Add(list.ToArray(parameterType.GetElementType()));
}
ConstructorInfo constructor = attributeType.GetConstructor([.. constructorParameters]);
attribute = constructor.Invoke([.. constructorArguments]);
foreach (CustomAttributeNamedArgument namedArgument in attributeData.NamedArguments)
{
attributeType.GetProperty(namedArgument.MemberInfo.Name).SetValue(attribute, namedArgument.TypedValue.Value, null);
}
}
// If not able to create instance of attribute ignore attribute. (May happen for custom user defined attributes).
catch (BadImageFormatException)
{
}
catch (FileLoadException)
{
}
catch (TypeLoadException)
{
}
return attribute as Attribute;
}
private static void AddNewAttributes(
IList<CustomAttributeData> customAttributes,
bool shouldGetAllAttributes,
Type type,
Dictionary<string, object> uniqueAttributes,
List<object> nonUniqueAttributes)
{
foreach (CustomAttributeData attribute in customAttributes)
{
if (!shouldGetAllAttributes
&& !IsTypeInheriting(attribute.Constructor.DeclaringType, type)
&& !attribute.Constructor.DeclaringType.AssemblyQualifiedName.Equals(
type.AssemblyQualifiedName, StringComparison.Ordinal))
{
continue;
}
Attribute? attributeInstance = CreateAttributeInstance(attribute);
if (attributeInstance == null)
{
continue;
}
Type attributeType = attributeInstance.GetType();
IReadOnlyList<object> attributeUsageAttributes = GetCustomAttributesCoreImpl(
attributeType,
typeof(AttributeUsageAttribute));
if (attributeUsageAttributes.Count > 0
&& attributeUsageAttributes[0] is AttributeUsageAttribute { AllowMultiple: false })
{
if (!uniqueAttributes.ContainsKey(attributeType.FullName))
{
uniqueAttributes.Add(attributeType.FullName, attributeInstance);
}
}
else
{
nonUniqueAttributes.Add(attributeInstance);
}
}
}
/// <summary>
/// Check whether the member is loaded in a reflection only context.
/// </summary>
/// <param name="memberInfo"> The member Info. </param>
/// <returns> True if the member is loaded in a reflection only context. </returns>
private static bool IsReflectionOnlyLoad(MemberInfo? memberInfo)
=> memberInfo != null && memberInfo.Module.Assembly.ReflectionOnly;
private static bool IsTypeInheriting(Type? type1, Type type2)
{
while (type1 != null)
{
if (type1.AssemblyQualifiedName.Equals(type2.AssemblyQualifiedName, StringComparison.Ordinal))
{
return true;
}
type1 = type1.BaseType;
}
return false;
}
#endif
#pragma warning disable IL2070 // this' argument does not satisfy 'DynamicallyAccessedMembersAttribute' in call to 'target method'.
#pragma warning disable IL2026 // Members attributed with RequiresUnreferencedCode may break when trimming
#pragma warning disable IL2067 // 'target parameter' argument does not satisfy 'DynamicallyAccessedMembersAttribute' in call to 'target method'.
#pragma warning disable IL2057 // Unrecognized value passed to the typeName parameter of 'System.Type.GetType(String)'
public ConstructorInfo[] GetDeclaredConstructors(Type classType)
=> classType.GetConstructors(DeclaredOnlyLookup);
public MethodInfo[] GetDeclaredMethods(Type classType)
=> classType.GetMethods(DeclaredOnlyLookup);
public PropertyInfo[] GetDeclaredProperties(Type type)
=> type.GetProperties(DeclaredOnlyLookup);
public Type[] GetDefinedTypes(Assembly assembly)
=> assembly.GetTypes();
public MethodInfo[] GetRuntimeMethods(Type type)
=> type.GetMethods(Everything);
public MethodInfo? GetRuntimeMethod(Type declaringType, string methodName, Type[] parameters, bool includeNonPublic)
=> includeNonPublic
? declaringType.GetMethod(methodName, Everything, null, parameters, null)
: declaringType.GetMethod(methodName, parameters);
public PropertyInfo? GetRuntimeProperty(Type classType, string testContextPropertyName, bool includeNonPublic)
=> includeNonPublic
? classType.GetProperty(testContextPropertyName, Everything)
: classType.GetProperty(testContextPropertyName);
public Type? GetType(string typeName)
=> Type.GetType(typeName);
public Type? GetType(Assembly assembly, string typeName)
=> assembly.GetType(typeName);
public object? CreateInstance(Type type, object?[] parameters)
=> Activator.CreateInstance(type, parameters);
#pragma warning restore IL2070 // this' argument does not satisfy 'DynamicallyAccessedMembersAttribute' in call to 'target method'.
#pragma warning restore IL2026 // Members attributed with RequiresUnreferencedCode may break when trimming
#pragma warning restore IL2067 // 'target parameter' argument does not satisfy 'DynamicallyAccessedMembersAttribute' in call to 'target method'.
#pragma warning restore IL2057 // Unrecognized value passed to the typeName parameter of 'System.Type.GetType(String)'
}