-
Notifications
You must be signed in to change notification settings - Fork 4.8k
/
UsageBasedMetadataManager.cs
1231 lines (1046 loc) · 59.5 KB
/
UsageBasedMetadataManager.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;
using System.Collections.Generic;
using System.IO;
using System.Reflection.Metadata;
using System.Reflection.PortableExecutable;
using System.Xml.XPath;
using ILCompiler.Dataflow;
using ILCompiler.DependencyAnalysis;
using ILCompiler.DependencyAnalysisFramework;
using ILCompiler.Metadata;
using ILLink.Shared;
using Internal.IL;
using Internal.TypeSystem;
using Internal.TypeSystem.Ecma;
using CombinedDependencyList = System.Collections.Generic.List<ILCompiler.DependencyAnalysisFramework.DependencyNodeCore<ILCompiler.DependencyAnalysis.NodeFactory>.CombinedDependencyListEntry>;
using CustomAttributeHandle = System.Reflection.Metadata.CustomAttributeHandle;
using CustomAttributeValue = System.Reflection.Metadata.CustomAttributeValue<Internal.TypeSystem.TypeDesc>;
using Debug = System.Diagnostics.Debug;
using DependencyList = ILCompiler.DependencyAnalysisFramework.DependencyNodeCore<ILCompiler.DependencyAnalysis.NodeFactory>.DependencyList;
using EcmaModule = Internal.TypeSystem.Ecma.EcmaModule;
using EcmaType = Internal.TypeSystem.Ecma.EcmaType;
using FlowAnnotations = ILLink.Shared.TrimAnalysis.FlowAnnotations;
namespace ILCompiler
{
/// <summary>
/// This class is responsible for managing native metadata to be emitted into the compiled
/// module. It applies a policy that every type/method that is statically used shall be reflectable.
/// </summary>
public sealed class UsageBasedMetadataManager : GeneratingMetadataManager
{
private readonly CompilationModuleGroup _compilationModuleGroup;
internal readonly UsageBasedMetadataGenerationOptions _generationOptions;
private readonly FeatureSwitchHashtable _featureSwitchHashtable;
private static (string AttributeName, DiagnosticId Id)[] _requiresAttributeMismatchNameAndId = new[]
{
(DiagnosticUtilities.RequiresUnreferencedCodeAttribute, DiagnosticId.RequiresUnreferencedCodeAttributeMismatch),
(DiagnosticUtilities.RequiresDynamicCodeAttribute, DiagnosticId.RequiresDynamicCodeAttributeMismatch),
(DiagnosticUtilities.RequiresAssemblyFilesAttribute, DiagnosticId.RequiresAssemblyFilesAttributeMismatch)
};
private readonly List<ModuleDesc> _modulesWithMetadata = new List<ModuleDesc>();
private readonly List<FieldDesc> _fieldsWithMetadata = new List<FieldDesc>();
private readonly List<MethodDesc> _methodsWithMetadata = new List<MethodDesc>();
private readonly List<MetadataType> _typesWithMetadata = new List<MetadataType>();
private readonly List<FieldDesc> _fieldsWithRuntimeMapping = new List<FieldDesc>();
private readonly List<ReflectableCustomAttribute> _customAttributesWithMetadata = new List<ReflectableCustomAttribute>();
internal IReadOnlyDictionary<string, bool> FeatureSwitches { get; }
private readonly HashSet<ModuleDesc> _rootEntireAssembliesExaminedModules = new HashSet<ModuleDesc>();
private readonly HashSet<string> _rootEntireAssembliesModules;
private readonly HashSet<string> _trimmedAssemblies;
internal FlowAnnotations FlowAnnotations { get; }
internal Logger Logger { get; }
public UsageBasedMetadataManager(
CompilationModuleGroup group,
CompilerTypeSystemContext typeSystemContext,
MetadataBlockingPolicy blockingPolicy,
ManifestResourceBlockingPolicy resourceBlockingPolicy,
string logFile,
StackTraceEmissionPolicy stackTracePolicy,
DynamicInvokeThunkGenerationPolicy invokeThunkGenerationPolicy,
FlowAnnotations flowAnnotations,
UsageBasedMetadataGenerationOptions generationOptions,
MetadataManagerOptions options,
Logger logger,
IEnumerable<KeyValuePair<string, bool>> featureSwitchValues,
IEnumerable<string> rootEntireAssembliesModules,
IEnumerable<string> additionalRootedAssemblies,
IEnumerable<string> trimmedAssemblies)
: base(typeSystemContext, blockingPolicy, resourceBlockingPolicy, logFile, stackTracePolicy, invokeThunkGenerationPolicy, options)
{
_compilationModuleGroup = group;
_generationOptions = generationOptions;
FlowAnnotations = flowAnnotations;
Logger = logger;
_featureSwitchHashtable = new FeatureSwitchHashtable(new Dictionary<string, bool>(featureSwitchValues));
FeatureSwitches = new Dictionary<string, bool>(featureSwitchValues);
_rootEntireAssembliesModules = new HashSet<string>(rootEntireAssembliesModules);
_rootEntireAssembliesModules.UnionWith(additionalRootedAssemblies);
_trimmedAssemblies = new HashSet<string>(trimmedAssemblies);
}
protected override void Graph_NewMarkedNode(DependencyNodeCore<NodeFactory> obj)
{
base.Graph_NewMarkedNode(obj);
var moduleMetadataNode = obj as ModuleMetadataNode;
if (moduleMetadataNode != null)
{
_modulesWithMetadata.Add(moduleMetadataNode.Module);
}
var fieldMetadataNode = obj as FieldMetadataNode;
if (fieldMetadataNode != null)
{
_fieldsWithMetadata.Add(fieldMetadataNode.Field);
}
var methodMetadataNode = obj as MethodMetadataNode;
if (methodMetadataNode != null)
{
_methodsWithMetadata.Add(methodMetadataNode.Method);
}
var typeMetadataNode = obj as TypeMetadataNode;
if (typeMetadataNode != null)
{
_typesWithMetadata.Add(typeMetadataNode.Type);
}
var customAttributeMetadataNode = obj as CustomAttributeMetadataNode;
if (customAttributeMetadataNode != null)
{
_customAttributesWithMetadata.Add(customAttributeMetadataNode.CustomAttribute);
}
var reflectableFieldNode = obj as ReflectableFieldNode;
if (reflectableFieldNode != null)
{
FieldDesc field = reflectableFieldNode.Field;
TypeDesc fieldOwningType = field.OwningType;
// Filter out to those that make sense to have in the mapping tables
if (!fieldOwningType.IsGenericDefinition
&& !field.IsLiteral
&& (!fieldOwningType.IsCanonicalSubtype(CanonicalFormKind.Specific) || !field.IsStatic))
{
Debug.Assert((GetMetadataCategory(field) & MetadataCategory.RuntimeMapping) != 0);
_fieldsWithRuntimeMapping.Add(field);
}
}
}
protected override MetadataCategory GetMetadataCategory(FieldDesc field)
{
MetadataCategory category = 0;
if (!IsReflectionBlocked(field))
{
// Can't do mapping for uninstantiated things
if (!field.OwningType.IsGenericDefinition)
category = MetadataCategory.RuntimeMapping;
if (_compilationModuleGroup.ContainsType(field.GetTypicalFieldDefinition().OwningType))
category |= MetadataCategory.Description;
}
return category;
}
protected override MetadataCategory GetMetadataCategory(MethodDesc method)
{
MetadataCategory category = 0;
if (!IsReflectionBlocked(method))
{
// Can't do mapping for uninstantiated things
if (!method.IsGenericMethodDefinition && !method.OwningType.IsGenericDefinition)
category = MetadataCategory.RuntimeMapping;
if (_compilationModuleGroup.ContainsType(method.GetTypicalMethodDefinition().OwningType))
category |= MetadataCategory.Description;
}
return category;
}
protected override MetadataCategory GetMetadataCategory(TypeDesc type)
{
MetadataCategory category = 0;
if (!IsReflectionBlocked(type))
{
category = MetadataCategory.RuntimeMapping;
if (_compilationModuleGroup.ContainsType(type.GetTypeDefinition()))
category |= MetadataCategory.Description;
}
return category;
}
protected override bool AllMethodsCanBeReflectable => (_generationOptions & UsageBasedMetadataGenerationOptions.CreateReflectableArtifacts) != 0;
protected override void ComputeMetadata(NodeFactory factory,
out byte[] metadataBlob,
out List<MetadataMapping<MetadataType>> typeMappings,
out List<MetadataMapping<MethodDesc>> methodMappings,
out List<MetadataMapping<FieldDesc>> fieldMappings,
out List<MetadataMapping<MethodDesc>> stackTraceMapping)
{
ComputeMetadata(new GeneratedTypesAndCodeMetadataPolicy(_blockingPolicy, factory),
factory, out metadataBlob, out typeMappings, out methodMappings, out fieldMappings, out stackTraceMapping);
}
protected override void GetMetadataDependenciesDueToReflectability(ref DependencyList dependencies, NodeFactory factory, MethodDesc method)
{
dependencies ??= new DependencyList();
dependencies.Add(factory.MethodMetadata(method.GetTypicalMethodDefinition()), "Reflectable method");
}
protected override void GetMetadataDependenciesDueToReflectability(ref DependencyList dependencies, NodeFactory factory, FieldDesc field)
{
dependencies ??= new DependencyList();
dependencies.Add(factory.FieldMetadata(field.GetTypicalFieldDefinition()), "Reflectable field");
}
internal override void GetDependenciesDueToModuleUse(ref DependencyList dependencies, NodeFactory factory, ModuleDesc module)
{
dependencies ??= new DependencyList();
if (module.GetGlobalModuleType().GetStaticConstructor() is MethodDesc moduleCctor)
{
dependencies.Add(factory.MethodEntrypoint(moduleCctor), "Module with a static constructor");
}
if (module is EcmaModule ecmaModule)
{
foreach (var resourceHandle in ecmaModule.MetadataReader.ManifestResources)
{
ManifestResource resource = ecmaModule.MetadataReader.GetManifestResource(resourceHandle);
// Don't try to process linked resources or resources in other assemblies
if (!resource.Implementation.IsNil)
{
continue;
}
string resourceName = ecmaModule.MetadataReader.GetString(resource.Name);
if (resourceName == "ILLink.Descriptors.xml")
{
dependencies.Add(factory.EmbeddedTrimmingDescriptor(ecmaModule), "Embedded descriptor file");
}
}
}
}
protected override void GetMetadataDependenciesDueToReflectability(ref DependencyList dependencies, NodeFactory factory, TypeDesc type)
{
TypeMetadataNode.GetMetadataDependencies(ref dependencies, factory, type, "Reflectable type");
if (type.IsDelegate)
{
// We've decided as a policy that delegate Invoke methods will be generated in full.
// The libraries (e.g. System.Linq.Expressions) have trimming warning suppressions
// in places where they assume IL-level trimming (where the method cannot be removed).
// We ask for a full reflectable method with its method body instead of just the
// metadata.
MethodDesc invokeMethod = type.GetMethod("Invoke", null);
if (!IsReflectionBlocked(invokeMethod))
{
dependencies ??= new DependencyList();
dependencies.Add(factory.ReflectableMethod(invokeMethod), "Delegate invoke method is always reflectable");
}
}
MetadataType mdType = type as MetadataType;
// If anonymous type heuristic is turned on and this is an anonymous type, make sure we have
// method bodies for all properties. It's common to have anonymous types used with reflection
// and it's hard to specify them in RD.XML.
if ((_generationOptions & UsageBasedMetadataGenerationOptions.AnonymousTypeHeuristic) != 0)
{
if (mdType != null &&
mdType.HasInstantiation &&
!mdType.IsGenericDefinition &&
mdType.HasCustomAttribute("System.Runtime.CompilerServices", "CompilerGeneratedAttribute") &&
mdType.Name.Contains("AnonymousType"))
{
foreach (MethodDesc method in type.GetMethods())
{
if (!method.Signature.IsStatic && method.IsSpecialName)
{
dependencies ??= new DependencyList();
dependencies.Add(factory.CanonicalEntrypoint(method), "Anonymous type accessor");
}
}
}
}
ModuleDesc module = mdType?.Module;
if (module != null && !_rootEntireAssembliesExaminedModules.Contains(module))
{
// If the owning assembly needs to be fully compiled, do that.
_rootEntireAssembliesExaminedModules.Add(module);
string assemblyName = module.Assembly.GetName().Name;
bool fullyRoot;
string reason;
// https://github.com/dotnet/runtime/issues/78752
// Compat with https://github.com/dotnet/linker/issues/1541 IL Linker bug:
// Asking to root an assembly with entrypoint will not actually root things in the assembly.
// We need to emulate this because the SDK injects a root for the entrypoint assembly right now
// because of IL Linker's implementation details (IL Linker won't root Main() by itself).
// TODO: We should technically reflection-root Main() here but hopefully the above issue
// will be fixed before it comes to that being necessary.
bool isEntrypointAssembly = module is EcmaModule ecmaModule && ecmaModule.PEReader.PEHeaders.IsExe;
if (!isEntrypointAssembly && _rootEntireAssembliesModules.Contains(assemblyName))
{
// If the assembly was specified as a root on the command line, root it
fullyRoot = true;
reason = "Rooted from command line";
}
else if (_trimmedAssemblies.Contains(assemblyName) || IsTrimmableAssembly(module))
{
// If the assembly was specified as trimmed on the command line, do not root
// If the assembly is marked trimmable via an attribute, do not root
fullyRoot = false;
reason = null;
}
else
{
// If rooting default assemblies was requested, root
fullyRoot = (_generationOptions & UsageBasedMetadataGenerationOptions.RootDefaultAssemblies) != 0;
reason = "Assemblies rooted from command line";
}
if (fullyRoot)
{
dependencies ??= new DependencyList();
var rootProvider = new RootingServiceProvider(factory, dependencies.Add);
foreach (TypeDesc t in mdType.Module.GetAllTypes())
{
RootingHelpers.TryRootType(rootProvider, t, reason);
}
}
}
// Event sources need their special nested types
if (mdType != null && mdType.HasCustomAttribute("System.Diagnostics.Tracing", "EventSourceAttribute"))
{
AddEventSourceSpecialTypeDependencies(ref dependencies, factory, mdType.GetNestedType("Keywords"));
AddEventSourceSpecialTypeDependencies(ref dependencies, factory, mdType.GetNestedType("Tasks"));
AddEventSourceSpecialTypeDependencies(ref dependencies, factory, mdType.GetNestedType("Opcodes"));
static void AddEventSourceSpecialTypeDependencies(ref DependencyList dependencies, NodeFactory factory, MetadataType type)
{
if (type != null)
{
const string reason = "Event source";
dependencies ??= new DependencyList();
dependencies.Add(factory.TypeMetadata(type), reason);
foreach (FieldDesc field in type.GetFields())
{
if (field.IsLiteral)
dependencies.Add(factory.FieldMetadata(field), reason);
}
}
}
}
}
private static bool IsTrimmableAssembly(ModuleDesc assembly)
{
if (assembly is EcmaAssembly ecmaAssembly)
{
foreach (var attribute in ecmaAssembly.GetDecodedCustomAttributes("System.Reflection", "AssemblyMetadataAttribute"))
{
if (attribute.FixedArguments.Length != 2)
continue;
if (!attribute.FixedArguments[0].Type.IsString
|| !((string)(attribute.FixedArguments[0].Value)).Equals("IsTrimmable", StringComparison.Ordinal))
continue;
if (!attribute.FixedArguments[1].Type.IsString)
continue;
string value = (string)attribute.FixedArguments[1].Value;
if (value.Equals("True", StringComparison.OrdinalIgnoreCase))
{
return true;
}
}
}
return false;
}
public override bool HasConditionalDependenciesDueToEETypePresence(TypeDesc type)
{
// Note: these are duplicated with the checks in GetConditionalDependenciesDueToEETypePresence
// If there's dataflow annotations on the type, we have conditional dependencies
if (type.IsDefType && !type.IsInterface && FlowAnnotations.GetTypeAnnotation(type) != default)
return true;
// If we need to ensure fields are consistently reflectable on various generic instances
if (type.HasInstantiation && !type.IsGenericDefinition && !IsReflectionBlocked(type))
return true;
return false;
}
public override void GetConditionalDependenciesDueToEETypePresence(ref CombinedDependencyList dependencies, NodeFactory factory, TypeDesc type)
{
// Check to see if we have any dataflow annotations on the type.
// The check below also covers flow annotations inherited through base classes and implemented interfaces.
if (type.IsDefType
&& !type.IsInterface /* "IFoo x; x.GetType();" -> this doesn't actually return an interface type */
&& FlowAnnotations.GetTypeAnnotation(type) != default)
{
// We have some flow annotations on this type.
//
// The flow annotations are supposed to ensure that should we call object.GetType on a location
// typed as one of the annotated subclasses of this type, this type is going to have the specified
// members kept. We don't keep them right away, but condition them on the object.GetType being called.
//
// Now we figure out where the annotations are coming from:
DefType baseType = type.BaseType;
if (baseType != null && FlowAnnotations.GetTypeAnnotation(baseType) != default)
{
// There's an annotation on the base type. If object.GetType was called on something
// statically typed as the base type, we might actually be calling it on this type.
// Ensure we have the flow dependencies.
dependencies ??= new CombinedDependencyList();
dependencies.Add(new DependencyNodeCore<NodeFactory>.CombinedDependencyListEntry(
factory.ObjectGetTypeFlowDependencies((MetadataType)type),
factory.ObjectGetTypeFlowDependencies((MetadataType)baseType),
"GetType called on the base type"));
// We don't have to follow all the bases since the base MethodTable will bubble this up
}
foreach (DefType interfaceType in type.RuntimeInterfaces)
{
if (FlowAnnotations.GetTypeAnnotation(interfaceType) != default)
{
// There's an annotation on the interface type. If object.GetType was called on something
// statically typed as the interface type, we might actually be calling it on this type.
// Ensure we have the flow dependencies.
dependencies ??= new CombinedDependencyList();
dependencies.Add(new DependencyNodeCore<NodeFactory>.CombinedDependencyListEntry(
factory.ObjectGetTypeFlowDependencies((MetadataType)type),
factory.ObjectGetTypeFlowDependencies((MetadataType)interfaceType),
"GetType called on the interface"));
}
// We don't have to recurse into the interface because we're inspecting runtime interfaces
// and this list is already flattened.
}
// Note we don't add any conditional dependencies if this type itself was annotated and none
// of the bases/interfaces are annotated.
// ObjectGetTypeFlowDependencies don't need to be conditional in that case. They'll be added as needed.
}
if (type.HasInstantiation && !type.IsTypeDefinition && !IsReflectionBlocked(type))
{
// Ensure fields can be consistently reflection set & get.
foreach (FieldDesc field in type.GetFields())
{
// Tiny optimization: no get/set for literal fields since they only exist in metadata
if (field.IsLiteral)
continue;
if (IsReflectionBlocked(field))
continue;
dependencies ??= new CombinedDependencyList();
dependencies.Add(new DependencyNodeCore<NodeFactory>.CombinedDependencyListEntry(
factory.ReflectableField(field),
factory.ReflectableField(field.GetTypicalFieldDefinition()),
"Fields have same reflectability"));
}
// Ensure methods can be consistently reflection-accessed
foreach (MethodDesc method in type.GetMethods())
{
if (IsReflectionBlocked(method))
continue;
// Generic methods need to be instantiated over something.
if (method.HasInstantiation)
continue;
dependencies ??= new CombinedDependencyList();
dependencies.Add(new DependencyNodeCore<NodeFactory>.CombinedDependencyListEntry(
factory.ReflectableMethod(method),
factory.ReflectableMethod(method.GetTypicalMethodDefinition()),
"Methods have same reflectability"));
}
}
}
public override void GetDependenciesDueToLdToken(ref DependencyList dependencies, NodeFactory factory, FieldDesc field)
{
if (!IsReflectionBlocked(field))
{
dependencies ??= new DependencyList();
dependencies.Add(factory.ReflectableField(field), "LDTOKEN field");
}
}
public override void GetDependenciesDueToLdToken(ref DependencyList dependencies, NodeFactory factory, MethodDesc method)
{
dependencies ??= new DependencyList();
if (!IsReflectionBlocked(method))
dependencies.Add(factory.ReflectableMethod(method), "LDTOKEN method");
}
public override void GetDependenciesDueToDelegateCreation(ref DependencyList dependencies, NodeFactory factory, MethodDesc target)
{
if (!IsReflectionBlocked(target))
{
dependencies ??= new DependencyList();
dependencies.Add(factory.ReflectableMethod(target), "Target of a delegate");
}
}
public override void GetDependenciesForOverridingMethod(ref CombinedDependencyList dependencies, NodeFactory factory, MethodDesc decl, MethodDesc impl)
{
Debug.Assert(decl.IsVirtual && MetadataVirtualMethodAlgorithm.FindSlotDefiningMethodForVirtualMethod(decl) == decl);
// If a virtual method slot is reflection visible, all implementations become reflection visible.
//
// We could technically come up with a weaker position on this because the code below just needs to
// to ensure that delegates to virtual methods can have their GetMethodInfo() called.
// Delegate construction introduces a ReflectableMethod for the slot defining method; it doesn't need to.
// We could have a specialized node type to track that specific thing and introduce a conditional dependency
// on that.
//
// class Base { abstract Boo(); }
// class Derived1 : Base { override Boo() { } }
// class Derived2 : Base { override Boo() { } }
//
// typeof(Derived2).GetMethods(...)
//
// In the above case, we don't really need Derived1.Boo to become reflection visible
// but the below code will do that because ReflectableMethodNode tracks all reflectable methods,
// without keeping information about subtleities like "reflectable delegate".
if (!IsReflectionBlocked(decl) && !IsReflectionBlocked(impl))
{
dependencies ??= new CombinedDependencyList();
dependencies.Add(new DependencyNodeCore<NodeFactory>.CombinedDependencyListEntry(
factory.ReflectableMethod(impl.GetCanonMethodTarget(CanonicalFormKind.Specific)),
factory.ReflectableMethod(decl.GetCanonMethodTarget(CanonicalFormKind.Specific)),
"Virtual method declaration is reflectable"));
}
}
protected override void GetDependenciesDueToMethodCodePresenceInternal(ref DependencyList dependencies, NodeFactory factory, MethodDesc method, MethodIL methodIL)
{
bool scanReflection = (_generationOptions & UsageBasedMetadataGenerationOptions.ReflectionILScanning) != 0;
Debug.Assert(methodIL != null || method.IsAbstract || method.IsPInvoke || method.IsInternalCall);
if (scanReflection)
{
if (methodIL != null && FlowAnnotations.RequiresDataflowAnalysis(method))
{
AddDataflowDependency(ref dependencies, factory, methodIL, "Method has annotated parameters");
}
if ((method.HasInstantiation && !method.IsCanonicalMethod(CanonicalFormKind.Any)))
{
MethodDesc typicalMethod = method.GetTypicalMethodDefinition();
Debug.Assert(typicalMethod != method);
GetFlowDependenciesForInstantiation(ref dependencies, factory, method.Instantiation, typicalMethod.Instantiation, method);
}
TypeDesc owningType = method.OwningType;
if (owningType.HasInstantiation && !owningType.IsCanonicalSubtype(CanonicalFormKind.Any))
{
TypeDesc owningTypeDefinition = owningType.GetTypeDefinition();
Debug.Assert(owningType != owningTypeDefinition);
GetFlowDependenciesForInstantiation(ref dependencies, factory, owningType.Instantiation, owningTypeDefinition.Instantiation, owningType);
}
}
if (method.GetTypicalMethodDefinition() is Internal.TypeSystem.Ecma.EcmaMethod ecmaMethod)
{
DynamicDependencyAttributeAlgorithm.AddDependenciesDueToDynamicDependencyAttribute(ref dependencies, factory, ecmaMethod);
}
// Presence of code might trigger the reflectability dependencies.
if ((_generationOptions & UsageBasedMetadataGenerationOptions.CreateReflectableArtifacts) != 0)
{
GetDependenciesDueToReflectability(ref dependencies, factory, method);
}
}
public override void GetConditionalDependenciesDueToMethodGenericDictionary(ref CombinedDependencyList dependencies, NodeFactory factory, MethodDesc method)
{
Debug.Assert(!method.IsSharedByGenericInstantiations && method.HasInstantiation && method.GetCanonMethodTarget(CanonicalFormKind.Specific) != method);
if ((_generationOptions & UsageBasedMetadataGenerationOptions.CreateReflectableArtifacts) == 0
&& !IsReflectionBlocked(method))
{
// Ensure that if SomeMethod<T> is considered reflectable, SomeMethod<ConcreteType> is also reflectable.
// We only need this because there's a file format limitation in the reflection mapping tables that
// requires generic methods to be concrete (i.e. SomeMethod<__Canon> can never be in the mapping table).
// If we ever lift this limitation, this code can be deleted: the reflectability is going to be covered
// by GetConditionalDependenciesDueToMethodCodePresence below (we get that callback for SomeMethod<__Canon>).
MethodDesc typicalMethod = method.GetTypicalMethodDefinition();
dependencies ??= new CombinedDependencyList();
dependencies.Add(new DependencyNodeCore<NodeFactory>.CombinedDependencyListEntry(
factory.ReflectableMethod(method), factory.ReflectableMethod(typicalMethod), "Reflectability of methods is same across genericness"));
}
}
public override void GetConditionalDependenciesDueToMethodCodePresence(ref CombinedDependencyList dependencies, NodeFactory factory, MethodDesc method)
{
MethodDesc typicalMethod = method.GetTypicalMethodDefinition();
// Ensure methods with genericness have the same reflectability by injecting a conditional dependency.
if ((_generationOptions & UsageBasedMetadataGenerationOptions.CreateReflectableArtifacts) == 0
&& method != typicalMethod)
{
dependencies ??= new CombinedDependencyList();
dependencies.Add(new DependencyNodeCore<NodeFactory>.CombinedDependencyListEntry(
factory.ReflectableMethod(method), factory.ReflectableMethod(typicalMethod), "Reflectability of methods is same across genericness"));
}
}
public override void GetDependenciesDueToVirtualMethodReflectability(ref DependencyList dependencies, NodeFactory factory, MethodDesc method)
{
if ((_generationOptions & UsageBasedMetadataGenerationOptions.CreateReflectableArtifacts) != 0)
{
// If we have a use of an abstract method, GetDependenciesDueToReflectability is not going to see the method
// as being used since there's no body. We inject a dependency on a new node that serves as a logical method body
// for the metadata manager. Metadata manager treats that node the same as a body.
if (method.IsAbstract && GetMetadataCategory(method) != 0)
{
dependencies ??= new DependencyList();
dependencies.Add(factory.ReflectableMethod(method), "Abstract reflectable method");
}
}
}
protected override IEnumerable<FieldDesc> GetFieldsWithRuntimeMapping()
{
return _fieldsWithRuntimeMapping;
}
public override IEnumerable<ModuleDesc> GetCompilationModulesWithMetadata()
{
return _modulesWithMetadata;
}
private IEnumerable<TypeDesc> GetTypesWithRuntimeMapping()
{
// All constructed types that are not blocked get runtime mapping
foreach (var constructedType in GetTypesWithConstructedEETypes())
{
if (!IsReflectionBlocked(constructedType))
yield return constructedType;
}
// All necessary types for which this is the highest load level that are not blocked
// get runtime mapping.
foreach (var necessaryType in GetTypesWithEETypes())
{
if (!ConstructedEETypeNode.CreationAllowed(necessaryType) &&
!IsReflectionBlocked(necessaryType))
yield return necessaryType;
}
}
public override void GetDependenciesDueToAccess(ref DependencyList dependencies, NodeFactory factory, MethodIL methodIL, FieldDesc writtenField)
{
bool scanReflection = (_generationOptions & UsageBasedMetadataGenerationOptions.ReflectionILScanning) != 0;
if (scanReflection && Dataflow.ReflectionMethodBodyScanner.RequiresReflectionMethodBodyScannerForAccess(FlowAnnotations, writtenField))
{
AddDataflowDependency(ref dependencies, factory, methodIL, "Access to interesting field");
}
string reason = "Use of a field";
bool generatesMetadata = false;
if (!IsReflectionBlocked(writtenField))
{
if ((_generationOptions & UsageBasedMetadataGenerationOptions.CreateReflectableArtifacts) != 0)
{
// If access to the field should trigger metadata generation, we should generate the field
generatesMetadata = true;
}
else
{
// There's an invalid suppression in the CoreLib that assumes used fields on attributes will be kept.
// It's used in the reflection-based implementation of Attribute.Equals and Attribute.GetHashCode.
// .NET Native used to have a non-reflection based implementation of Equals/GetHashCode to get around
// this problem. We could explore that as well, but for now, emulate the fact that accessed fields
// on custom attributes will be visible in reflection metadata.
MetadataType currentType = (MetadataType)writtenField.OwningType.BaseType;
while (currentType != null)
{
if (currentType.Module == factory.TypeSystemContext.SystemModule
&& currentType.Name == "Attribute" && currentType.Namespace == "System")
{
generatesMetadata = true;
reason = "Field of an attribute";
break;
}
currentType = currentType.MetadataBaseType;
}
}
}
if (generatesMetadata)
{
FieldDesc fieldToReport = writtenField;
// The field could be on something odd like Foo<__Canon, object>. Normalize to Foo<__Canon, __Canon>.
TypeDesc fieldOwningType = writtenField.OwningType;
if (fieldOwningType.IsCanonicalSubtype(CanonicalFormKind.Specific))
{
TypeDesc fieldOwningTypeNormalized = fieldOwningType.NormalizeInstantiation();
if (fieldOwningType != fieldOwningTypeNormalized)
{
fieldToReport = factory.TypeSystemContext.GetFieldForInstantiatedType(
writtenField.GetTypicalFieldDefinition(),
(InstantiatedType)fieldOwningTypeNormalized);
}
}
dependencies ??= new DependencyList();
dependencies.Add(factory.ReflectableField(fieldToReport), reason);
}
if (writtenField.GetTypicalFieldDefinition() is EcmaField ecmaField)
{
DynamicDependencyAttributeAlgorithm.AddDependenciesDueToDynamicDependencyAttribute(ref dependencies, factory, ecmaField);
}
}
public override void GetDependenciesDueToAccess(ref DependencyList dependencies, NodeFactory factory, MethodIL methodIL, MethodDesc calledMethod)
{
bool scanReflection = (_generationOptions & UsageBasedMetadataGenerationOptions.ReflectionILScanning) != 0;
if (scanReflection && Dataflow.ReflectionMethodBodyScanner.RequiresReflectionMethodBodyScannerForCallSite(FlowAnnotations, calledMethod))
{
AddDataflowDependency(ref dependencies, factory, methodIL, "Call to interesting method");
}
}
public override DependencyList GetDependenciesForCustomAttribute(NodeFactory factory, MethodDesc attributeCtor, CustomAttributeValue decodedValue, TypeSystemEntity parent)
{
bool scanReflection = (_generationOptions & UsageBasedMetadataGenerationOptions.ReflectionILScanning) != 0;
if (scanReflection)
{
return (new AttributeDataFlow(Logger, factory, FlowAnnotations, new Logging.MessageOrigin(parent))).ProcessAttributeDataflow(attributeCtor, decodedValue);
}
return null;
}
private void GetFlowDependenciesForInstantiation(ref DependencyList dependencies, NodeFactory factory, Instantiation instantiation, Instantiation typicalInstantiation, TypeSystemEntity source)
{
for (int i = 0; i < instantiation.Length; i++)
{
var genericParameter = (GenericParameterDesc)typicalInstantiation[i];
if (FlowAnnotations.GetGenericParameterAnnotation(genericParameter) != default)
{
try
{
var deps = (new ILCompiler.Dataflow.GenericArgumentDataFlow(Logger, factory, FlowAnnotations, new Logging.MessageOrigin(source))).ProcessGenericArgumentDataFlow(genericParameter, instantiation[i]);
if (deps.Count > 0)
{
if (dependencies == null)
dependencies = deps;
else
dependencies.AddRange(deps);
}
}
catch (TypeSystemException)
{
// Wasn't able to do dataflow because of missing references or something like that.
// This likely won't compile either, so we don't care about missing dependencies.
}
}
}
}
public override void GetDependenciesForGenericDictionary(ref DependencyList dependencies, NodeFactory factory, MethodDesc method)
{
TypeDesc owningType = method.OwningType;
if (FlowAnnotations.HasAnyAnnotations(owningType))
{
MethodDesc typicalMethod = method.GetTypicalMethodDefinition();
Debug.Assert(typicalMethod != method);
GetFlowDependenciesForInstantiation(ref dependencies, factory, method.Instantiation, typicalMethod.Instantiation, method);
if (owningType.HasInstantiation)
{
// Since this also introduces a new type instantiation into the system, collect the dependencies for that too.
// We might not see the instantiated type elsewhere.
GetFlowDependenciesForInstantiation(ref dependencies, factory, owningType.Instantiation, owningType.GetTypeDefinition().Instantiation, method);
}
}
// Presence of code might trigger the reflectability dependencies.
if ((_generationOptions & UsageBasedMetadataGenerationOptions.CreateReflectableArtifacts) != 0)
{
GetDependenciesDueToReflectability(ref dependencies, factory, method);
}
}
public override void GetDependenciesForGenericDictionary(ref DependencyList dependencies, NodeFactory factory, TypeDesc type)
{
if (FlowAnnotations.HasAnyAnnotations(type))
{
TypeDesc typeDefinition = type.GetTypeDefinition();
Debug.Assert(type != typeDefinition);
GetFlowDependenciesForInstantiation(ref dependencies, factory, type.Instantiation, typeDefinition.Instantiation, type);
}
}
public bool GeneratesAttributeMetadata(TypeDesc attributeType)
{
var ecmaType = attributeType.GetTypeDefinition() as EcmaType;
if (ecmaType != null)
{
var moduleInfo = _featureSwitchHashtable.GetOrCreateValue(ecmaType.EcmaModule);
return !moduleInfo.RemovedAttributes.Contains(ecmaType);
}
return true;
}
public override void NoteOverridingMethod(MethodDesc baseMethod, MethodDesc overridingMethod)
{
baseMethod = baseMethod.GetTypicalMethodDefinition();
overridingMethod = overridingMethod.GetTypicalMethodDefinition();
bool baseMethodTypeIsInterface = baseMethod.OwningType.IsInterface;
foreach (var requiresAttribute in _requiresAttributeMismatchNameAndId)
{
// We validate that the various dataflow/Requires* annotations are consistent across virtual method overrides
if (HasMismatchingAttributes(baseMethod, overridingMethod, requiresAttribute.AttributeName))
{
string overridingMethodName = overridingMethod.GetDisplayName();
string baseMethodName = baseMethod.GetDisplayName();
string message = MessageFormat.FormatRequiresAttributeMismatch(overridingMethod.DoesMethodRequire(requiresAttribute.AttributeName, out _),
baseMethodTypeIsInterface, requiresAttribute.AttributeName, overridingMethodName, baseMethodName);
Logger.LogWarning(overridingMethod, requiresAttribute.Id, message);
}
}
bool baseMethodRequiresDataflow = FlowAnnotations.RequiresVirtualMethodDataflowAnalysis(baseMethod);
bool overridingMethodRequiresDataflow = FlowAnnotations.RequiresVirtualMethodDataflowAnalysis(overridingMethod);
if (baseMethodRequiresDataflow || overridingMethodRequiresDataflow)
{
FlowAnnotations.ValidateMethodAnnotationsAreSame(overridingMethod, baseMethod);
}
}
public static bool HasMismatchingAttributes(MethodDesc baseMethod, MethodDesc overridingMethod, string requiresAttributeName)
{
bool baseMethodCreatesRequirement = baseMethod.DoesMethodRequire(requiresAttributeName, out _);
bool overridingMethodCreatesRequirement = overridingMethod.DoesMethodRequire(requiresAttributeName, out _);
bool baseMethodFulfillsRequirement = baseMethod.IsOverrideInRequiresScope(requiresAttributeName);
bool overridingMethodFulfillsRequirement = overridingMethod.IsOverrideInRequiresScope(requiresAttributeName);
return (baseMethodCreatesRequirement && !overridingMethodFulfillsRequirement) || (overridingMethodCreatesRequirement && !baseMethodFulfillsRequirement);
}
public MetadataManager ToAnalysisBasedMetadataManager()
{
var reflectableTypes = ReflectableEntityBuilder<TypeDesc>.Create();
// Collect the list of types that are generating reflection metadata
foreach (var typeWithMetadata in _typesWithMetadata)
{
reflectableTypes[typeWithMetadata] = MetadataCategory.Description;
}
foreach (var constructedType in GetTypesWithRuntimeMapping())
{
reflectableTypes[constructedType] |= MetadataCategory.RuntimeMapping;
// Also set the description bit if the definition is getting metadata.
TypeDesc constructedTypeDefinition = constructedType.GetTypeDefinition();
if (constructedType != constructedTypeDefinition &&
(reflectableTypes[constructedTypeDefinition] & MetadataCategory.Description) != 0)
{
reflectableTypes[constructedType] |= MetadataCategory.Description;
}
}
var reflectableMethods = ReflectableEntityBuilder<MethodDesc>.Create();
foreach (var methodWithMetadata in _methodsWithMetadata)
{
reflectableMethods[methodWithMetadata] = MetadataCategory.Description;
}
foreach (var method in GetReflectableMethods())
{
if (method.IsGenericMethodDefinition || method.OwningType.IsGenericDefinition)
continue;
if (!IsReflectionBlocked(method))
{
if ((reflectableTypes[method.OwningType] & MetadataCategory.RuntimeMapping) != 0)
reflectableMethods[method] |= MetadataCategory.RuntimeMapping;
// Also set the description bit if the definition is getting metadata.
MethodDesc typicalMethod = method.GetTypicalMethodDefinition();
if (method != typicalMethod &&
(reflectableMethods[typicalMethod] & MetadataCategory.Description) != 0)
{
reflectableMethods[method] |= MetadataCategory.Description;
reflectableTypes[method.OwningType] |= MetadataCategory.Description;
}
}
}
var reflectableFields = ReflectableEntityBuilder<FieldDesc>.Create();
foreach (var fieldWithMetadata in _fieldsWithMetadata)
{
reflectableFields[fieldWithMetadata] = MetadataCategory.Description;
}
foreach (var fieldWithRuntimeMapping in _fieldsWithRuntimeMapping)
{
reflectableFields[fieldWithRuntimeMapping] |= MetadataCategory.RuntimeMapping;
// Also set the description bit if the definition is getting metadata.
FieldDesc typicalField = fieldWithRuntimeMapping.GetTypicalFieldDefinition();
if (fieldWithRuntimeMapping != typicalField &&
(reflectableFields[typicalField] & MetadataCategory.Description) != 0)
{
reflectableFields[fieldWithRuntimeMapping] |= MetadataCategory.Description;
}
}
var rootedCctorContexts = new List<MetadataType>();
foreach (NonGCStaticsNode cctorContext in GetCctorContextMapping())
{
// If we generated a static constructor and the owning type, this might be something
// that gets fed to RuntimeHelpers.RunClassConstructor. RunClassConstructor
// also works on reflection blocked types and there is a possibility that we
// wouldn't have generated the cctor otherwise.
//
// This is a heuristic and we'll possibly root more cctor contexts than
// strictly necessary, but it's not worth introducing a new node type
// in the compiler just so we can propagate this knowledge from dataflow analysis
// (that detects RunClassConstructor usage) and this spot.
if (!TypeGeneratesEEType(cctorContext.Type))
continue;
rootedCctorContexts.Add(cctorContext.Type);
}
return new AnalysisBasedMetadataManager(
_typeSystemContext, _blockingPolicy, _resourceBlockingPolicy, _metadataLogFile, _stackTraceEmissionPolicy, _dynamicInvokeThunkGenerationPolicy,
_modulesWithMetadata, reflectableTypes.ToEnumerable(), reflectableMethods.ToEnumerable(),
reflectableFields.ToEnumerable(), _customAttributesWithMetadata, rootedCctorContexts, _options);
}
private void AddDataflowDependency(ref DependencyList dependencies, NodeFactory factory, MethodIL methodIL, string reason)
{
MethodIL methodILDefinition = methodIL.GetMethodILDefinition();
if (FlowAnnotations.CompilerGeneratedState.TryGetUserMethodForCompilerGeneratedMember(methodILDefinition.OwningMethod, out var userMethod))
{
Debug.Assert(userMethod != methodILDefinition.OwningMethod);
// It is possible that this will try to add the DatadlowAnalyzedMethod node multiple times for the same method
// but that's OK since the node factory will only add actually one node.
methodILDefinition = FlowAnnotations.ILProvider.GetMethodIL(userMethod);
}
// Data-flow (reflection scanning) for compiler-generated methods will happen as part of the
// data-flow scan of the user-defined method which uses this compiler-generated method.
if (CompilerGeneratedState.IsNestedFunctionOrStateMachineMember(methodILDefinition.OwningMethod))
return;
dependencies ??= new DependencyList();
dependencies.Add(factory.DataflowAnalyzedMethod(methodILDefinition), reason);
}
private struct ReflectableEntityBuilder<T>
{