/
RuntimeCustomAttributeData.cs
1891 lines (1561 loc) · 82.1 KB
/
RuntimeCustomAttributeData.cs
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
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using Internal.Runtime.CompilerServices;
namespace System.Reflection
{
internal sealed class RuntimeCustomAttributeData : CustomAttributeData
{
#region Internal Static Members
internal static IList<CustomAttributeData> GetCustomAttributesInternal(RuntimeType target)
{
Debug.Assert(target is not null);
IList<CustomAttributeData> cad = GetCustomAttributes(target.GetRuntimeModule(), target.MetadataToken);
RuntimeType.ListBuilder<Attribute> pcas = default;
PseudoCustomAttribute.GetCustomAttributes(target, (RuntimeType)typeof(object), ref pcas);
return pcas.Count > 0 ? GetCombinedList(cad, ref pcas) : cad;
}
internal static IList<CustomAttributeData> GetCustomAttributesInternal(RuntimeFieldInfo target)
{
Debug.Assert(target is not null);
IList<CustomAttributeData> cad = GetCustomAttributes(target.GetRuntimeModule(), target.MetadataToken);
RuntimeType.ListBuilder<Attribute> pcas = default;
PseudoCustomAttribute.GetCustomAttributes(target, (RuntimeType)typeof(object), ref pcas);
return pcas.Count > 0 ? GetCombinedList(cad, ref pcas) : cad;
}
internal static IList<CustomAttributeData> GetCustomAttributesInternal(RuntimeMethodInfo target)
{
Debug.Assert(target is not null);
IList<CustomAttributeData> cad = GetCustomAttributes(target.GetRuntimeModule(), target.MetadataToken);
RuntimeType.ListBuilder<Attribute> pcas = default;
PseudoCustomAttribute.GetCustomAttributes(target, (RuntimeType)typeof(object), ref pcas);
return pcas.Count > 0 ? GetCombinedList(cad, ref pcas) : cad;
}
internal static IList<CustomAttributeData> GetCustomAttributesInternal(RuntimeConstructorInfo target)
{
Debug.Assert(target is not null);
return GetCustomAttributes(target.GetRuntimeModule(), target.MetadataToken);
}
internal static IList<CustomAttributeData> GetCustomAttributesInternal(RuntimeEventInfo target)
{
Debug.Assert(target is not null);
return GetCustomAttributes(target.GetRuntimeModule(), target.MetadataToken);
}
internal static IList<CustomAttributeData> GetCustomAttributesInternal(RuntimePropertyInfo target)
{
Debug.Assert(target is not null);
return GetCustomAttributes(target.GetRuntimeModule(), target.MetadataToken);
}
internal static IList<CustomAttributeData> GetCustomAttributesInternal(RuntimeModule target)
{
Debug.Assert(target is not null);
if (target.IsResource())
return new List<CustomAttributeData>();
return GetCustomAttributes(target, target.MetadataToken);
}
internal static IList<CustomAttributeData> GetCustomAttributesInternal(RuntimeAssembly target)
{
Debug.Assert(target is not null);
// No pseudo attributes for RuntimeAssembly
return GetCustomAttributes((RuntimeModule)target.ManifestModule, RuntimeAssembly.GetToken(target.GetNativeHandle()));
}
internal static IList<CustomAttributeData> GetCustomAttributesInternal(RuntimeParameterInfo target)
{
Debug.Assert(target is not null);
RuntimeType.ListBuilder<Attribute> pcas = default;
IList<CustomAttributeData> cad = GetCustomAttributes(target.GetRuntimeModule()!, target.MetadataToken);
PseudoCustomAttribute.GetCustomAttributes(target, (RuntimeType)typeof(object), ref pcas);
return pcas.Count > 0 ? GetCombinedList(cad, ref pcas) : cad;
}
private static IList<CustomAttributeData> GetCombinedList(IList<CustomAttributeData> customAttributes, ref RuntimeType.ListBuilder<Attribute> pseudoAttributes)
{
Debug.Assert(pseudoAttributes.Count != 0);
CustomAttributeData[] pca = new CustomAttributeData[customAttributes.Count + pseudoAttributes.Count];
customAttributes.CopyTo(pca, pseudoAttributes.Count);
for (int i = 0; i < pseudoAttributes.Count; i++)
{
pca[i] = new RuntimeCustomAttributeData(pseudoAttributes[i]);
}
return Array.AsReadOnly(pca);
}
#endregion
#region Private Static Methods
private static CustomAttributeEncoding TypeToCustomAttributeEncoding(RuntimeType type)
{
if (type == typeof(int))
return CustomAttributeEncoding.Int32;
if (type.IsEnum)
return CustomAttributeEncoding.Enum;
if (type == typeof(string))
return CustomAttributeEncoding.String;
if (type == typeof(Type))
return CustomAttributeEncoding.Type;
if (type == typeof(object))
return CustomAttributeEncoding.Object;
if (type.IsArray)
return CustomAttributeEncoding.Array;
if (type == typeof(char))
return CustomAttributeEncoding.Char;
if (type == typeof(bool))
return CustomAttributeEncoding.Boolean;
if (type == typeof(byte))
return CustomAttributeEncoding.Byte;
if (type == typeof(sbyte))
return CustomAttributeEncoding.SByte;
if (type == typeof(short))
return CustomAttributeEncoding.Int16;
if (type == typeof(ushort))
return CustomAttributeEncoding.UInt16;
if (type == typeof(uint))
return CustomAttributeEncoding.UInt32;
if (type == typeof(long))
return CustomAttributeEncoding.Int64;
if (type == typeof(ulong))
return CustomAttributeEncoding.UInt64;
if (type == typeof(float))
return CustomAttributeEncoding.Float;
if (type == typeof(double))
return CustomAttributeEncoding.Double;
// System.Enum is neither an Enum nor a Class
if (type == typeof(Enum))
return CustomAttributeEncoding.Object;
if (type.IsClass)
return CustomAttributeEncoding.Object;
if (type.IsInterface)
return CustomAttributeEncoding.Object;
if (type.IsValueType)
return CustomAttributeEncoding.Undefined;
throw new ArgumentException(SR.Argument_InvalidKindOfTypeForCA, nameof(type));
}
private static CustomAttributeType InitCustomAttributeType(RuntimeType parameterType)
{
CustomAttributeEncoding encodedType = TypeToCustomAttributeEncoding(parameterType);
CustomAttributeEncoding encodedArrayType = CustomAttributeEncoding.Undefined;
CustomAttributeEncoding encodedEnumType = CustomAttributeEncoding.Undefined;
string? enumName = null;
if (encodedType == CustomAttributeEncoding.Array)
{
parameterType = (RuntimeType)parameterType.GetElementType();
encodedArrayType = TypeToCustomAttributeEncoding(parameterType);
}
if (encodedType == CustomAttributeEncoding.Enum || encodedArrayType == CustomAttributeEncoding.Enum)
{
encodedEnumType = TypeToCustomAttributeEncoding((RuntimeType)Enum.GetUnderlyingType(parameterType));
enumName = parameterType.AssemblyQualifiedName;
}
return new CustomAttributeType(encodedType, encodedArrayType, encodedEnumType, enumName);
}
private static IList<CustomAttributeData> GetCustomAttributes(RuntimeModule module, int tkTarget)
{
CustomAttributeRecord[] records = GetCustomAttributeRecords(module, tkTarget);
if (records.Length == 0)
{
return Array.Empty<CustomAttributeData>();
}
CustomAttributeData[] customAttributes = new CustomAttributeData[records.Length];
for (int i = 0; i < records.Length; i++)
customAttributes[i] = new RuntimeCustomAttributeData(module, records[i].tkCtor, in records[i].blob);
return Array.AsReadOnly(customAttributes);
}
#endregion
#region Internal Static Members
internal static CustomAttributeRecord[] GetCustomAttributeRecords(RuntimeModule module, int targetToken)
{
MetadataImport scope = module.MetadataImport;
scope.EnumCustomAttributes(targetToken, out MetadataEnumResult tkCustomAttributeTokens);
if (tkCustomAttributeTokens.Length == 0)
{
return Array.Empty<CustomAttributeRecord>();
}
CustomAttributeRecord[] records = new CustomAttributeRecord[tkCustomAttributeTokens.Length];
for (int i = 0; i < records.Length; i++)
{
scope.GetCustomAttributeProps(tkCustomAttributeTokens[i],
out records[i].tkCtor.Value, out records[i].blob);
}
return records;
}
internal static CustomAttributeTypedArgument Filter(IList<CustomAttributeData> attrs, Type? caType, int parameter)
{
for (int i = 0; i < attrs.Count; i++)
{
if (attrs[i].Constructor.DeclaringType == caType)
{
return attrs[i].ConstructorArguments[parameter];
}
}
return default;
}
#endregion
private ConstructorInfo m_ctor = null!;
private readonly RuntimeModule m_scope = null!;
private readonly MemberInfo[] m_members = null!;
private readonly CustomAttributeCtorParameter[] m_ctorParams = null!;
private readonly CustomAttributeNamedParameter[] m_namedParams = null!;
private IList<CustomAttributeTypedArgument> m_typedCtorArgs = null!;
private IList<CustomAttributeNamedArgument> m_namedArgs = null!;
#region Constructor
[UnconditionalSuppressMessage("ReflectionAnalysis", "IL2075:UnrecognizedReflectionPattern",
Justification = "Property setters and fields which are accessed by any attribute instantiation which is present in the code linker has analyzed." +
"As such enumerating all fields and properties may return different results after trimming" +
"but all those which are needed to actually have data will be there.")]
[UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:UnrecognizedReflectionPattern",
Justification = "We're getting a MethodBase of a constructor that we found in the metadata. The attribute constructor won't be trimmed.")]
private RuntimeCustomAttributeData(RuntimeModule scope, MetadataToken caCtorToken, in ConstArray blob)
{
m_scope = scope;
m_ctor = (RuntimeConstructorInfo)RuntimeType.GetMethodBase(scope, caCtorToken)!;
if (m_ctor!.DeclaringType!.IsGenericType)
{
MetadataImport metadataScope = scope.MetadataImport;
var attributeType = scope.ResolveType(metadataScope.GetParentToken(caCtorToken), null, null)!;
m_ctor = (RuntimeConstructorInfo)scope.ResolveMethod(caCtorToken, attributeType.GenericTypeArguments, null)!.MethodHandle.GetMethodInfo();
}
ParameterInfo[] parameters = m_ctor.GetParametersNoCopy();
m_ctorParams = new CustomAttributeCtorParameter[parameters.Length];
for (int i = 0; i < parameters.Length; i++)
m_ctorParams[i] = new CustomAttributeCtorParameter(InitCustomAttributeType((RuntimeType)parameters[i].ParameterType));
FieldInfo[] fields = m_ctor.DeclaringType!.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
PropertyInfo[] properties = m_ctor.DeclaringType.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
m_namedParams = new CustomAttributeNamedParameter[properties.Length + fields.Length];
for (int i = 0; i < fields.Length; i++)
m_namedParams[i] = new CustomAttributeNamedParameter(
fields[i].Name, CustomAttributeEncoding.Field, InitCustomAttributeType((RuntimeType)fields[i].FieldType));
for (int i = 0; i < properties.Length; i++)
m_namedParams[i + fields.Length] = new CustomAttributeNamedParameter(
properties[i].Name, CustomAttributeEncoding.Property, InitCustomAttributeType((RuntimeType)properties[i].PropertyType));
m_members = new MemberInfo[fields.Length + properties.Length];
fields.CopyTo(m_members, 0);
properties.CopyTo(m_members, fields.Length);
CustomAttributeEncodedArgument.ParseAttributeArguments(blob, ref m_ctorParams, ref m_namedParams, m_scope);
}
#endregion
#region Pseudo Custom Attribute Constructor
internal RuntimeCustomAttributeData(Attribute attribute)
{
if (attribute is DllImportAttribute dllImportAttribute)
Init(dllImportAttribute);
else if (attribute is FieldOffsetAttribute fieldOffsetAttribute)
Init(fieldOffsetAttribute);
else if (attribute is MarshalAsAttribute marshalAsAttribute)
Init(marshalAsAttribute);
else if (attribute is TypeForwardedToAttribute typeForwardedToAttribute)
Init(typeForwardedToAttribute);
else
Init(attribute);
}
private void Init(DllImportAttribute dllImport)
{
Type type = typeof(DllImportAttribute);
m_ctor = type.GetConstructors(BindingFlags.Public | BindingFlags.Instance)[0];
m_typedCtorArgs = Array.AsReadOnly(new CustomAttributeTypedArgument[]
{
new CustomAttributeTypedArgument(dllImport.Value),
});
m_namedArgs = Array.AsReadOnly(new CustomAttributeNamedArgument[]
{
new CustomAttributeNamedArgument(type.GetField("EntryPoint")!, dllImport.EntryPoint),
new CustomAttributeNamedArgument(type.GetField("CharSet")!, dllImport.CharSet),
new CustomAttributeNamedArgument(type.GetField("ExactSpelling")!, dllImport.ExactSpelling),
new CustomAttributeNamedArgument(type.GetField("SetLastError")!, dllImport.SetLastError),
new CustomAttributeNamedArgument(type.GetField("PreserveSig")!, dllImport.PreserveSig),
new CustomAttributeNamedArgument(type.GetField("CallingConvention")!, dllImport.CallingConvention),
new CustomAttributeNamedArgument(type.GetField("BestFitMapping")!, dllImport.BestFitMapping),
new CustomAttributeNamedArgument(type.GetField("ThrowOnUnmappableChar")!, dllImport.ThrowOnUnmappableChar)
});
}
private void Init(FieldOffsetAttribute fieldOffset)
{
m_ctor = typeof(FieldOffsetAttribute).GetConstructors(BindingFlags.Public | BindingFlags.Instance)[0];
m_typedCtorArgs = Array.AsReadOnly(new CustomAttributeTypedArgument[] {
new CustomAttributeTypedArgument(fieldOffset.Value)
});
m_namedArgs = Array.AsReadOnly(Array.Empty<CustomAttributeNamedArgument>());
}
private void Init(MarshalAsAttribute marshalAs)
{
Type type = typeof(MarshalAsAttribute);
m_ctor = type.GetConstructors(BindingFlags.Public | BindingFlags.Instance)[0];
m_typedCtorArgs = Array.AsReadOnly(new CustomAttributeTypedArgument[]
{
new CustomAttributeTypedArgument(marshalAs.Value),
});
int i = 3; // ArraySubType, SizeParamIndex, SizeConst
if (marshalAs.MarshalType is not null) i++;
if (marshalAs.MarshalTypeRef is not null) i++;
if (marshalAs.MarshalCookie is not null) i++;
i++; // IidParameterIndex
i++; // SafeArraySubType
if (marshalAs.SafeArrayUserDefinedSubType is not null) i++;
CustomAttributeNamedArgument[] namedArgs = new CustomAttributeNamedArgument[i];
// For compatibility with previous runtimes, we always include the following 5 attributes, regardless
// of if they apply to the UnmanagedType being marshaled or not.
i = 0;
namedArgs[i++] = new CustomAttributeNamedArgument(type.GetField("ArraySubType")!, marshalAs.ArraySubType);
namedArgs[i++] = new CustomAttributeNamedArgument(type.GetField("SizeParamIndex")!, marshalAs.SizeParamIndex);
namedArgs[i++] = new CustomAttributeNamedArgument(type.GetField("SizeConst")!, marshalAs.SizeConst);
namedArgs[i++] = new CustomAttributeNamedArgument(type.GetField("IidParameterIndex")!, marshalAs.IidParameterIndex);
namedArgs[i++] = new CustomAttributeNamedArgument(type.GetField("SafeArraySubType")!, marshalAs.SafeArraySubType);
if (marshalAs.MarshalType is not null)
namedArgs[i++] = new CustomAttributeNamedArgument(type.GetField("MarshalType")!, marshalAs.MarshalType);
if (marshalAs.MarshalTypeRef is not null)
namedArgs[i++] = new CustomAttributeNamedArgument(type.GetField("MarshalTypeRef")!, marshalAs.MarshalTypeRef);
if (marshalAs.MarshalCookie is not null)
namedArgs[i++] = new CustomAttributeNamedArgument(type.GetField("MarshalCookie")!, marshalAs.MarshalCookie);
if (marshalAs.SafeArrayUserDefinedSubType is not null)
namedArgs[i++] = new CustomAttributeNamedArgument(type.GetField("SafeArrayUserDefinedSubType")!, marshalAs.SafeArrayUserDefinedSubType);
m_namedArgs = Array.AsReadOnly(namedArgs);
}
private void Init(TypeForwardedToAttribute forwardedTo)
{
Type type = typeof(TypeForwardedToAttribute);
Type[] sig = new Type[] { typeof(Type) };
m_ctor = type.GetConstructor(BindingFlags.Public | BindingFlags.Instance, null, sig, null)!;
CustomAttributeTypedArgument[] typedArgs = new CustomAttributeTypedArgument[1];
typedArgs[0] = new CustomAttributeTypedArgument(typeof(Type), forwardedTo.Destination);
m_typedCtorArgs = Array.AsReadOnly(typedArgs);
CustomAttributeNamedArgument[] namedArgs = Array.Empty<CustomAttributeNamedArgument>();
m_namedArgs = Array.AsReadOnly(namedArgs);
}
[UnconditionalSuppressMessage("ReflectionAnalysis", "IL2075:UnrecognizedReflectionPattern",
Justification = "The pca object had to be created by the single ctor on the Type. So the ctor couldn't have been trimmed.")]
private void Init(object pca)
{
Type type = pca.GetType();
#if DEBUG
// Ensure there is only a single constructor for 'pca', so it is safe to suppress IL2075
ConstructorInfo[] allCtors = type.GetConstructors(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
Debug.Assert(allCtors.Length == 1);
Debug.Assert(allCtors[0].GetParameters().Length == 0);
#endif
m_ctor = type.GetConstructors(BindingFlags.Public | BindingFlags.Instance)[0];
m_typedCtorArgs = Array.AsReadOnly(Array.Empty<CustomAttributeTypedArgument>());
m_namedArgs = Array.AsReadOnly(Array.Empty<CustomAttributeNamedArgument>());
}
#endregion
#region Public Members
public override ConstructorInfo Constructor => m_ctor;
public override IList<CustomAttributeTypedArgument> ConstructorArguments
{
get
{
if (m_typedCtorArgs is null)
{
CustomAttributeTypedArgument[] typedCtorArgs = new CustomAttributeTypedArgument[m_ctorParams.Length];
for (int i = 0; i < typedCtorArgs.Length; i++)
{
CustomAttributeEncodedArgument encodedArg = m_ctorParams[i].CustomAttributeEncodedArgument;
typedCtorArgs[i] = new CustomAttributeTypedArgument(m_scope, encodedArg);
}
m_typedCtorArgs = Array.AsReadOnly(typedCtorArgs);
}
return m_typedCtorArgs;
}
}
public override IList<CustomAttributeNamedArgument> NamedArguments
{
get
{
if (m_namedArgs is null)
{
if (m_namedParams is null)
return null!;
int cNamedArgs = 0;
for (int i = 0; i < m_namedParams.Length; i++)
{
if (m_namedParams[i].EncodedArgument.CustomAttributeType.EncodedType != CustomAttributeEncoding.Undefined)
cNamedArgs++;
}
CustomAttributeNamedArgument[] namedArgs = new CustomAttributeNamedArgument[cNamedArgs];
for (int i = 0, j = 0; i < m_namedParams.Length; i++)
{
if (m_namedParams[i].EncodedArgument.CustomAttributeType.EncodedType != CustomAttributeEncoding.Undefined)
namedArgs[j++] = new CustomAttributeNamedArgument(
m_members[i], new CustomAttributeTypedArgument(m_scope, m_namedParams[i].EncodedArgument));
}
m_namedArgs = Array.AsReadOnly(namedArgs);
}
return m_namedArgs;
}
}
#endregion
}
public readonly partial struct CustomAttributeTypedArgument
{
#region Private Static Methods
private static Type CustomAttributeEncodingToType(CustomAttributeEncoding encodedType)
{
return encodedType switch
{
CustomAttributeEncoding.Enum => typeof(Enum),
CustomAttributeEncoding.Int32 => typeof(int),
CustomAttributeEncoding.String => typeof(string),
CustomAttributeEncoding.Type => typeof(Type),
CustomAttributeEncoding.Array => typeof(Array),
CustomAttributeEncoding.Char => typeof(char),
CustomAttributeEncoding.Boolean => typeof(bool),
CustomAttributeEncoding.SByte => typeof(sbyte),
CustomAttributeEncoding.Byte => typeof(byte),
CustomAttributeEncoding.Int16 => typeof(short),
CustomAttributeEncoding.UInt16 => typeof(ushort),
CustomAttributeEncoding.UInt32 => typeof(uint),
CustomAttributeEncoding.Int64 => typeof(long),
CustomAttributeEncoding.UInt64 => typeof(ulong),
CustomAttributeEncoding.Float => typeof(float),
CustomAttributeEncoding.Double => typeof(double),
CustomAttributeEncoding.Object => typeof(object),
_ => throw new ArgumentException(SR.Format(SR.Arg_EnumIllegalVal, (int)encodedType), nameof(encodedType)),
};
}
private static object EncodedValueToRawValue(long val, CustomAttributeEncoding encodedType)
{
switch (encodedType)
{
case CustomAttributeEncoding.Boolean:
return (byte)val != 0;
case CustomAttributeEncoding.Char:
return (char)val;
case CustomAttributeEncoding.Byte:
return (byte)val;
case CustomAttributeEncoding.SByte:
return (sbyte)val;
case CustomAttributeEncoding.Int16:
return (short)val;
case CustomAttributeEncoding.UInt16:
return (ushort)val;
case CustomAttributeEncoding.Int32:
return (int)val;
case CustomAttributeEncoding.UInt32:
return (uint)val;
case CustomAttributeEncoding.Int64:
return (long)val;
case CustomAttributeEncoding.UInt64:
return (ulong)val;
case CustomAttributeEncoding.Float:
unsafe { return *(float*)&val; }
case CustomAttributeEncoding.Double:
unsafe { return *(double*)&val; }
default:
throw new ArgumentException(SR.Format(SR.Arg_EnumIllegalVal, (int)val), nameof(val));
}
}
private static RuntimeType ResolveType(RuntimeModule scope, string typeName)
{
RuntimeType type = RuntimeTypeHandle.GetTypeByNameUsingCARules(typeName, scope);
if (type is null)
throw new InvalidOperationException(
SR.Format(SR.Arg_CATypeResolutionFailed, typeName));
return type;
}
#endregion
internal CustomAttributeTypedArgument(RuntimeModule scope, CustomAttributeEncodedArgument encodedArg)
{
CustomAttributeEncoding encodedType = encodedArg.CustomAttributeType.EncodedType;
if (encodedType == CustomAttributeEncoding.Undefined)
throw new ArgumentException(null, nameof(encodedArg));
if (encodedType == CustomAttributeEncoding.Enum)
{
_argumentType = ResolveType(scope, encodedArg.CustomAttributeType.EnumName!);
_value = EncodedValueToRawValue(encodedArg.PrimitiveValue, encodedArg.CustomAttributeType.EncodedEnumType);
}
else if (encodedType == CustomAttributeEncoding.String)
{
_argumentType = typeof(string);
_value = encodedArg.StringValue;
}
else if (encodedType == CustomAttributeEncoding.Type)
{
_argumentType = typeof(Type);
_value = null;
if (encodedArg.StringValue is not null)
_value = ResolveType(scope, encodedArg.StringValue);
}
else if (encodedType == CustomAttributeEncoding.Array)
{
encodedType = encodedArg.CustomAttributeType.EncodedArrayType;
Type elementType;
if (encodedType == CustomAttributeEncoding.Enum)
{
elementType = ResolveType(scope, encodedArg.CustomAttributeType.EnumName!);
}
else
{
elementType = CustomAttributeEncodingToType(encodedType);
}
_argumentType = elementType.MakeArrayType();
if (encodedArg.ArrayValue is null)
{
_value = null;
}
else
{
CustomAttributeTypedArgument[] arrayValue = new CustomAttributeTypedArgument[encodedArg.ArrayValue.Length];
for (int i = 0; i < arrayValue.Length; i++)
arrayValue[i] = new CustomAttributeTypedArgument(scope, encodedArg.ArrayValue[i]);
_value = Array.AsReadOnly(arrayValue);
}
}
else
{
_argumentType = CustomAttributeEncodingToType(encodedType);
_value = EncodedValueToRawValue(encodedArg.PrimitiveValue, encodedType);
}
}
}
[StructLayout(LayoutKind.Auto)]
internal struct CustomAttributeRecord
{
internal ConstArray blob;
internal MetadataToken tkCtor;
public CustomAttributeRecord(int token, ConstArray blob)
{
tkCtor = new MetadataToken(token);
this.blob = blob;
}
}
internal enum CustomAttributeEncoding : int
{
Undefined = 0,
Boolean = CorElementType.ELEMENT_TYPE_BOOLEAN,
Char = CorElementType.ELEMENT_TYPE_CHAR,
SByte = CorElementType.ELEMENT_TYPE_I1,
Byte = CorElementType.ELEMENT_TYPE_U1,
Int16 = CorElementType.ELEMENT_TYPE_I2,
UInt16 = CorElementType.ELEMENT_TYPE_U2,
Int32 = CorElementType.ELEMENT_TYPE_I4,
UInt32 = CorElementType.ELEMENT_TYPE_U4,
Int64 = CorElementType.ELEMENT_TYPE_I8,
UInt64 = CorElementType.ELEMENT_TYPE_U8,
Float = CorElementType.ELEMENT_TYPE_R4,
Double = CorElementType.ELEMENT_TYPE_R8,
String = CorElementType.ELEMENT_TYPE_STRING,
Array = CorElementType.ELEMENT_TYPE_SZARRAY,
Type = 0x50,
Object = 0x51,
Field = 0x53,
Property = 0x54,
Enum = 0x55
}
[StructLayout(LayoutKind.Auto)]
internal readonly struct CustomAttributeEncodedArgument
{
private readonly long m_primitiveValue;
private readonly CustomAttributeEncodedArgument[] m_arrayValue;
private readonly string m_stringValue;
private readonly CustomAttributeType m_type;
[MethodImpl(MethodImplOptions.InternalCall)]
private static extern void ParseAttributeArguments(
IntPtr pCa,
int cCa,
ref CustomAttributeCtorParameter[] CustomAttributeCtorParameters,
ref CustomAttributeNamedParameter[] CustomAttributeTypedArgument,
RuntimeAssembly assembly);
internal static void ParseAttributeArguments(ConstArray attributeBlob,
ref CustomAttributeCtorParameter[] customAttributeCtorParameters,
ref CustomAttributeNamedParameter[] customAttributeNamedParameters,
RuntimeModule customAttributeModule)
{
if (customAttributeModule is null)
throw new ArgumentNullException(nameof(customAttributeModule));
Debug.Assert(customAttributeCtorParameters is not null);
Debug.Assert(customAttributeNamedParameters is not null);
if (customAttributeCtorParameters.Length != 0 || customAttributeNamedParameters.Length != 0)
{
ParseAttributeArguments(
attributeBlob.Signature,
(int)attributeBlob.Length,
ref customAttributeCtorParameters,
ref customAttributeNamedParameters,
(RuntimeAssembly)customAttributeModule.Assembly);
}
}
public CustomAttributeType CustomAttributeType => m_type;
public long PrimitiveValue => m_primitiveValue;
public CustomAttributeEncodedArgument[] ArrayValue => m_arrayValue;
public string StringValue => m_stringValue;
}
[StructLayout(LayoutKind.Auto)]
internal readonly struct CustomAttributeNamedParameter
{
private readonly string m_argumentName;
private readonly CustomAttributeEncoding m_fieldOrProperty;
private readonly CustomAttributeEncoding m_padding;
private readonly CustomAttributeType m_type;
private readonly CustomAttributeEncodedArgument m_encodedArgument;
public CustomAttributeNamedParameter(string argumentName, CustomAttributeEncoding fieldOrProperty, CustomAttributeType type)
{
if (argumentName is null)
throw new ArgumentNullException(nameof(argumentName));
m_argumentName = argumentName;
m_fieldOrProperty = fieldOrProperty;
m_padding = fieldOrProperty;
m_type = type;
m_encodedArgument = default;
}
public CustomAttributeEncodedArgument EncodedArgument => m_encodedArgument;
}
[StructLayout(LayoutKind.Auto)]
internal readonly struct CustomAttributeCtorParameter
{
private readonly CustomAttributeType m_type;
private readonly CustomAttributeEncodedArgument m_encodedArgument;
public CustomAttributeCtorParameter(CustomAttributeType type)
{
m_type = type;
m_encodedArgument = default;
}
public CustomAttributeEncodedArgument CustomAttributeEncodedArgument => m_encodedArgument;
}
[StructLayout(LayoutKind.Auto)]
internal readonly struct CustomAttributeType
{
/// The most complicated type is an enum[] in which case...
private readonly string? m_enumName; // ...enum name
private readonly CustomAttributeEncoding m_encodedType; // ...array
private readonly CustomAttributeEncoding m_encodedEnumType; // ...enum
private readonly CustomAttributeEncoding m_encodedArrayType; // ...enum type
private readonly CustomAttributeEncoding m_padding;
public CustomAttributeType(CustomAttributeEncoding encodedType, CustomAttributeEncoding encodedArrayType,
CustomAttributeEncoding encodedEnumType, string? enumName)
{
m_encodedType = encodedType;
m_encodedArrayType = encodedArrayType;
m_encodedEnumType = encodedEnumType;
m_enumName = enumName;
m_padding = m_encodedType;
}
public CustomAttributeEncoding EncodedType => m_encodedType;
public CustomAttributeEncoding EncodedEnumType => m_encodedEnumType;
public CustomAttributeEncoding EncodedArrayType => m_encodedArrayType;
public string? EnumName => m_enumName;
}
internal static unsafe class CustomAttribute
{
private static readonly RuntimeType Type_RuntimeType = (RuntimeType)typeof(RuntimeType);
private static readonly RuntimeType Type_Type = (RuntimeType)typeof(Type);
#region Internal Static Members
internal static bool IsDefined(RuntimeType type, RuntimeType? caType, bool inherit)
{
Debug.Assert(type is not null);
if (type.GetElementType() is not null)
return false;
if (PseudoCustomAttribute.IsDefined(type, caType))
return true;
if (IsCustomAttributeDefined(type.GetRuntimeModule(), type.MetadataToken, caType))
return true;
if (!inherit)
return false;
type = (type.BaseType as RuntimeType)!;
while (type is not null)
{
if (IsCustomAttributeDefined(type.GetRuntimeModule(), type.MetadataToken, caType, 0, inherit))
return true;
type = (type.BaseType as RuntimeType)!;
}
return false;
}
internal static bool IsDefined(RuntimeMethodInfo method, RuntimeType caType, bool inherit)
{
Debug.Assert(method is not null);
Debug.Assert(caType is not null);
if (PseudoCustomAttribute.IsDefined(method, caType))
return true;
if (IsCustomAttributeDefined(method.GetRuntimeModule(), method.MetadataToken, caType))
return true;
if (!inherit)
return false;
method = method.GetParentDefinition()!;
while (method is not null)
{
if (IsCustomAttributeDefined(method.GetRuntimeModule(), method.MetadataToken, caType, 0, inherit))
return true;
method = method.GetParentDefinition()!;
}
return false;
}
internal static bool IsDefined(RuntimeConstructorInfo ctor, RuntimeType caType)
{
Debug.Assert(ctor is not null);
Debug.Assert(caType is not null);
// No pseudo attributes for RuntimeConstructorInfo
return IsCustomAttributeDefined(ctor.GetRuntimeModule(), ctor.MetadataToken, caType);
}
internal static bool IsDefined(RuntimePropertyInfo property, RuntimeType caType)
{
Debug.Assert(property is not null);
Debug.Assert(caType is not null);
// No pseudo attributes for RuntimePropertyInfo
return IsCustomAttributeDefined(property.GetRuntimeModule(), property.MetadataToken, caType);
}
internal static bool IsDefined(RuntimeEventInfo e, RuntimeType caType)
{
Debug.Assert(e is not null);
Debug.Assert(caType is not null);
// No pseudo attributes for RuntimeEventInfo
return IsCustomAttributeDefined(e.GetRuntimeModule(), e.MetadataToken, caType);
}
internal static bool IsDefined(RuntimeFieldInfo field, RuntimeType caType)
{
Debug.Assert(field is not null);
Debug.Assert(caType is not null);
if (PseudoCustomAttribute.IsDefined(field, caType))
return true;
return IsCustomAttributeDefined(field.GetRuntimeModule(), field.MetadataToken, caType);
}
internal static bool IsDefined(RuntimeParameterInfo parameter, RuntimeType caType)
{
Debug.Assert(parameter is not null);
Debug.Assert(caType is not null);
if (PseudoCustomAttribute.IsDefined(parameter, caType))
return true;
return IsCustomAttributeDefined(parameter.GetRuntimeModule()!, parameter.MetadataToken, caType);
}
internal static bool IsDefined(RuntimeAssembly assembly, RuntimeType caType)
{
Debug.Assert(assembly is not null);
Debug.Assert(caType is not null);
// No pseudo attributes for RuntimeAssembly
return IsCustomAttributeDefined((assembly.ManifestModule as RuntimeModule)!, RuntimeAssembly.GetToken(assembly.GetNativeHandle()), caType);
}
internal static bool IsDefined(RuntimeModule module, RuntimeType caType)
{
Debug.Assert(module is not null);
Debug.Assert(caType is not null);
// No pseudo attributes for RuntimeModule
return IsCustomAttributeDefined(module, module.MetadataToken, caType);
}
internal static object[] GetCustomAttributes(RuntimeType type, RuntimeType caType, bool inherit)
{
Debug.Assert(type is not null);
Debug.Assert(caType is not null);
if (type.GetElementType() is not null)
return (caType.IsValueType) ? Array.Empty<object>() : CreateAttributeArrayHelper(caType, 0);
if (type.IsGenericType && !type.IsGenericTypeDefinition)
type = (type.GetGenericTypeDefinition() as RuntimeType)!;
RuntimeType.ListBuilder<Attribute> pcas = default;
PseudoCustomAttribute.GetCustomAttributes(type, caType, ref pcas);
// if we are asked to go up the hierarchy chain we have to do it now and regardless of the
// attribute usage for the specific attribute because a derived attribute may override the usage...
// ... however if the attribute is sealed we can rely on the attribute usage
if (!inherit || (caType.IsSealed && !CustomAttribute.GetAttributeUsage(caType).Inherited))
{
object[] attributes = GetCustomAttributes(type.GetRuntimeModule(), type.MetadataToken, pcas.Count, caType);
if (pcas.Count > 0) pcas.CopyTo(attributes, attributes.Length - pcas.Count);
return attributes;
}
RuntimeType.ListBuilder<object> result = default;
bool mustBeInheritable = false;
bool useObjectArray = (caType.IsValueType || caType.ContainsGenericParameters);
RuntimeType arrayType = useObjectArray ? (RuntimeType)typeof(object) : caType;
for (int i = 0; i < pcas.Count; i++)
result.Add(pcas[i]);
while (type != (RuntimeType)typeof(object) && type != null)
{
AddCustomAttributes(ref result, type.GetRuntimeModule(), type.MetadataToken, caType, mustBeInheritable, result);
mustBeInheritable = true;
type = (type.BaseType as RuntimeType)!;
}
object[] typedResult = CreateAttributeArrayHelper(arrayType, result.Count);
for (int i = 0; i < result.Count; i++)
{
typedResult[i] = result[i];
}
return typedResult;
}
internal static object[] GetCustomAttributes(RuntimeMethodInfo method, RuntimeType caType, bool inherit)
{
Debug.Assert(method is not null);
Debug.Assert(caType is not null);
if (method.IsGenericMethod && !method.IsGenericMethodDefinition)
method = (method.GetGenericMethodDefinition() as RuntimeMethodInfo)!;
RuntimeType.ListBuilder<Attribute> pcas = default;
PseudoCustomAttribute.GetCustomAttributes(method, caType, ref pcas);
// if we are asked to go up the hierarchy chain we have to do it now and regardless of the
// attribute usage for the specific attribute because a derived attribute may override the usage...
// ... however if the attribute is sealed we can rely on the attribute usage
if (!inherit || (caType.IsSealed && !CustomAttribute.GetAttributeUsage(caType).Inherited))
{
object[] attributes = GetCustomAttributes(method.GetRuntimeModule(), method.MetadataToken, pcas.Count, caType);
if (pcas.Count > 0) pcas.CopyTo(attributes, attributes.Length - pcas.Count);
return attributes;
}
RuntimeType.ListBuilder<object> result = default;
bool mustBeInheritable = false;
bool useObjectArray = (caType.IsValueType || caType.ContainsGenericParameters);
RuntimeType arrayType = useObjectArray ? (RuntimeType)typeof(object) : caType;
for (int i = 0; i < pcas.Count; i++)
result.Add(pcas[i]);
while (method != null)
{
AddCustomAttributes(ref result, method.GetRuntimeModule(), method.MetadataToken, caType, mustBeInheritable, result);
mustBeInheritable = true;
method = method.GetParentDefinition()!;
}
object[] typedResult = CreateAttributeArrayHelper(arrayType, result.Count);
for (int i = 0; i < result.Count; i++)
{
typedResult[i] = result[i];
}
return typedResult;
}
internal static object[] GetCustomAttributes(RuntimeConstructorInfo ctor, RuntimeType caType)
{
Debug.Assert(ctor != null);
Debug.Assert(caType != null);