-
Notifications
You must be signed in to change notification settings - Fork 4.8k
/
MarkStep.cs
3821 lines (3175 loc) · 154 KB
/
MarkStep.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
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
// MarkStep.cs
//
// Author:
// Jb Evain (jbevain@gmail.com)
//
// (C) 2006 Jb Evain
// (C) 2007 Novell, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text.RegularExpressions;
using ILCompiler.DependencyAnalysisFramework;
using ILLink.Shared;
using ILLink.Shared.TrimAnalysis;
using ILLink.Shared.TypeSystemProxy;
using Mono.Cecil;
using Mono.Cecil.Cil;
using Mono.Collections.Generic;
using Mono.Linker.Dataflow;
using AssemblyNameInfo = System.Reflection.Metadata.AssemblyNameInfo;
using TypeName = System.Reflection.Metadata.TypeName;
using TypeNameParseOptions = System.Reflection.Metadata.TypeNameParseOptions;
namespace Mono.Linker.Steps
{
public partial class MarkStep : IStep
{
LinkContext? _context;
protected LinkContext Context {
get {
Debug.Assert (_context != null);
return _context;
}
}
private bool _completed;
protected Dictionary<MethodDefinition, MessageOrigin> _interface_methods;
protected Queue<AttributeProviderPair> _assemblyLevelAttributes;
protected Queue<(AttributeProviderPair, DependencyInfo, MessageOrigin)> _lateMarkedAttributes;
protected List<(TypeDefinition, MessageOrigin)> _typesWithInterfaces;
protected HashSet<AssemblyDefinition> _dynamicInterfaceCastableImplementationTypesDiscovered;
protected List<TypeDefinition> _dynamicInterfaceCastableImplementationTypes;
protected List<(MethodBody, MessageOrigin)> _unreachableBodies;
readonly List<(TypeDefinition Type, MethodBody Body, Instruction Instr)> _pending_isinst_instr;
// Stores, for compiler-generated methods only, whether they require the reflection
// method body scanner.
readonly Dictionary<MethodBody, bool> _compilerGeneratedMethodRequiresScanner;
private readonly NodeFactory _nodeFactory;
private readonly DependencyAnalyzer<NoLogStrategy<NodeFactory>, NodeFactory> _dependencyGraph;
MarkStepContext? _markContext;
MarkStepContext MarkContext {
get {
Debug.Assert (_markContext != null);
return _markContext;
}
}
readonly HashSet<TypeDefinition> _entireTypesMarked;
DynamicallyAccessedMembersTypeHierarchy? _dynamicallyAccessedMembersTypeHierarchy;
internal DynamicallyAccessedMembersTypeHierarchy DynamicallyAccessedMembersTypeHierarchy {
get {
Debug.Assert (_dynamicallyAccessedMembersTypeHierarchy != null);
return _dynamicallyAccessedMembersTypeHierarchy;
}
}
#if DEBUG
static readonly DependencyKind[] _entireTypeReasons = new DependencyKind[] {
DependencyKind.AccessedViaReflection,
DependencyKind.BaseType,
DependencyKind.PreservedDependency,
DependencyKind.NestedType,
DependencyKind.TypeInAssembly,
DependencyKind.Unspecified,
};
static readonly DependencyKind[] _fieldReasons = new DependencyKind[] {
DependencyKind.Unspecified,
DependencyKind.AccessedViaReflection,
DependencyKind.AlreadyMarked,
DependencyKind.Custom,
DependencyKind.CustomAttributeField,
DependencyKind.DynamicallyAccessedMember,
DependencyKind.DynamicallyAccessedMemberOnType,
DependencyKind.EventSourceProviderField,
DependencyKind.FieldAccess,
DependencyKind.FieldOnGenericInstance,
DependencyKind.InteropMethodDependency,
DependencyKind.Ldtoken,
DependencyKind.MemberOfType,
DependencyKind.DynamicDependency,
DependencyKind.ReferencedBySpecialAttribute,
DependencyKind.TypePreserve,
DependencyKind.XmlDescriptor,
DependencyKind.UnsafeAccessorTarget,
};
static readonly DependencyKind[] _typeReasons = new DependencyKind[] {
DependencyKind.Unspecified,
DependencyKind.AccessedViaReflection,
DependencyKind.AlreadyMarked,
DependencyKind.AttributeType,
DependencyKind.BaseType,
DependencyKind.CatchType,
DependencyKind.Custom,
DependencyKind.CustomAttributeArgumentType,
DependencyKind.CustomAttributeArgumentValue,
DependencyKind.DeclaringType,
DependencyKind.DeclaringTypeOfCalledMethod,
DependencyKind.DynamicallyAccessedMember,
DependencyKind.DynamicallyAccessedMemberOnType,
DependencyKind.DynamicDependency,
DependencyKind.ElementType,
DependencyKind.FieldType,
DependencyKind.GenericArgumentType,
DependencyKind.GenericParameterConstraintType,
DependencyKind.InterfaceImplementationInterfaceType,
DependencyKind.Ldtoken,
DependencyKind.ModifierType,
DependencyKind.NestedType,
DependencyKind.InstructionTypeRef,
DependencyKind.ParameterType,
DependencyKind.ReferencedBySpecialAttribute,
DependencyKind.ReturnType,
DependencyKind.TypeInAssembly,
DependencyKind.UnreachableBodyRequirement,
DependencyKind.VariableType,
DependencyKind.ParameterMarshalSpec,
DependencyKind.FieldMarshalSpec,
DependencyKind.ReturnTypeMarshalSpec,
DependencyKind.DynamicInterfaceCastableImplementation,
DependencyKind.XmlDescriptor,
};
static readonly DependencyKind[] _methodReasons = new DependencyKind[] {
DependencyKind.Unspecified,
DependencyKind.AccessedViaReflection,
DependencyKind.AlreadyMarked,
DependencyKind.AttributeConstructor,
DependencyKind.AttributeProperty,
DependencyKind.BaseDefaultCtorForStubbedMethod,
DependencyKind.BaseMethod,
DependencyKind.CctorForType,
DependencyKind.CctorForField,
DependencyKind.Custom,
DependencyKind.DefaultCtorForNewConstrainedGenericArgument,
DependencyKind.DirectCall,
DependencyKind.DynamicallyAccessedMember,
DependencyKind.DynamicallyAccessedMemberOnType,
DependencyKind.DynamicDependency,
DependencyKind.ElementMethod,
DependencyKind.EventMethod,
DependencyKind.EventOfEventMethod,
DependencyKind.InteropMethodDependency,
DependencyKind.KeptForSpecialAttribute,
DependencyKind.Ldftn,
DependencyKind.Ldtoken,
DependencyKind.Ldvirtftn,
DependencyKind.MemberOfType,
DependencyKind.MethodForInstantiatedType,
DependencyKind.MethodForSpecialType,
DependencyKind.MethodImplOverride,
DependencyKind.MethodOnGenericInstance,
DependencyKind.Newobj,
DependencyKind.Override,
DependencyKind.OverrideOnInstantiatedType,
DependencyKind.DynamicDependency,
DependencyKind.PreservedMethod,
DependencyKind.ReferencedBySpecialAttribute,
DependencyKind.SerializationMethodForType,
DependencyKind.TriggersCctorForCalledMethod,
DependencyKind.TriggersCctorThroughFieldAccess,
DependencyKind.TypePreserve,
DependencyKind.UnreachableBodyRequirement,
DependencyKind.VirtualCall,
DependencyKind.VirtualNeededDueToPreservedScope,
DependencyKind.ParameterMarshalSpec,
DependencyKind.FieldMarshalSpec,
DependencyKind.ReturnTypeMarshalSpec,
DependencyKind.XmlDescriptor,
DependencyKind.UnsafeAccessorTarget,
};
#endif
public MarkStep ()
{
_completed = false;
_interface_methods = new Dictionary<MethodDefinition, MessageOrigin> ();
_assemblyLevelAttributes = new Queue<AttributeProviderPair> ();
_lateMarkedAttributes = new Queue<(AttributeProviderPair, DependencyInfo, MessageOrigin)> ();
_typesWithInterfaces = new List<(TypeDefinition, MessageOrigin)> ();
_dynamicInterfaceCastableImplementationTypesDiscovered = new HashSet<AssemblyDefinition> ();
_dynamicInterfaceCastableImplementationTypes = new List<TypeDefinition> ();
_unreachableBodies = new List<(MethodBody, MessageOrigin)> ();
_pending_isinst_instr = new List<(TypeDefinition, MethodBody, Instruction)> ();
_entireTypesMarked = new HashSet<TypeDefinition> ();
_compilerGeneratedMethodRequiresScanner = new Dictionary<MethodBody, bool> ();
_nodeFactory = new NodeFactory (this);
_dependencyGraph = new DependencyAnalyzer<NoLogStrategy<NodeFactory>, NodeFactory> (_nodeFactory, null);
}
public AnnotationStore Annotations => Context.Annotations;
public MarkingHelpers MarkingHelpers => Context.MarkingHelpers;
public Tracer Tracer => Context.Tracer;
public EmbeddedXmlInfo EmbeddedXmlInfo => Context.EmbeddedXmlInfo;
public virtual void Process (LinkContext context)
{
_context = context;
_markContext = new MarkStepContext ();
_dynamicallyAccessedMembersTypeHierarchy = new DynamicallyAccessedMembersTypeHierarchy (_context, this);
Initialize ();
Process ();
Complete ();
}
protected virtual void Initialize ()
{
InitializeCorelibAttributeXml ();
Context.Pipeline.InitializeMarkHandlers (Context, MarkContext);
ProcessMarkedPending ();
}
void InitializeCorelibAttributeXml ()
{
// Pre-load corelib and process its attribute XML first. This is necessary because the
// corelib attribute XML can contain modifications to other assemblies.
// We could just mark it here, but the attribute processing isn't necessarily tied to marking,
// so this would rely on implementation details of corelib.
var coreLib = Context.TryResolve (PlatformAssemblies.CoreLib);
if (coreLib == null)
return;
var xmlInfo = EmbeddedXmlInfo.ProcessAttributes (coreLib, Context);
if (xmlInfo == null)
return;
// Because the attribute XML can reference other assemblies, they must go in the global store,
// instead of the per-assembly stores.
foreach (var (provider, annotations) in xmlInfo.CustomAttributes)
Context.CustomAttributes.PrimaryAttributeInfo.AddCustomAttributes (provider, annotations);
foreach (var (ca, origin) in xmlInfo.CustomAttributesOrigins)
Context.CustomAttributes.PrimaryAttributeInfo.CustomAttributesOrigins.Add (ca, origin);
}
protected virtual void Complete ()
{
foreach ((var body, var _) in _unreachableBodies) {
Annotations.SetAction (body.Method, MethodAction.ConvertToThrow);
}
}
static bool TypeIsDynamicInterfaceCastableImplementation (TypeDefinition type)
{
if (!type.IsInterface || !type.HasInterfaces || !type.HasCustomAttributes)
return false;
foreach (var ca in type.CustomAttributes) {
if (ca.AttributeType.IsTypeOf ("System.Runtime.InteropServices", "DynamicInterfaceCastableImplementationAttribute"))
return true;
}
return false;
}
protected bool IsFullyPreserved (TypeDefinition type)
{
if (Annotations.TryGetPreserve (type, out TypePreserve preserve) && preserve == TypePreserve.All)
return true;
switch (Annotations.GetAction (type.Module.Assembly)) {
case AssemblyAction.Save:
case AssemblyAction.Copy:
case AssemblyAction.CopyUsed:
case AssemblyAction.AddBypassNGen:
case AssemblyAction.AddBypassNGenUsed:
return true;
}
return false;
}
internal void MarkEntireType (TypeDefinition type, in DependencyInfo reason, MessageOrigin origin)
{
#if DEBUG
if (!_entireTypeReasons.Contains (reason.Kind))
throw new InternalErrorException ($"Unsupported type dependency '{reason.Kind}'.");
#endif
// Prevent cases where there's nothing on the stack (can happen when marking entire assemblies)
// In which case we would generate warnings with no source (hard to debug)
origin = origin.Provider is not null ? origin : new MessageOrigin (type);
if (!_entireTypesMarked.Add (type))
return;
if (type.HasNestedTypes) {
foreach (TypeDefinition nested in type.NestedTypes)
MarkEntireType (nested, new DependencyInfo (DependencyKind.NestedType, type), origin);
}
MarkTypeVisibleToReflection (type, type, reason, origin);
MarkCustomAttributes (type, new DependencyInfo (DependencyKind.CustomAttribute, type), origin);
MarkTypeSpecialCustomAttributes (type, origin);
if (type.HasInterfaces) {
foreach (InterfaceImplementation iface in type.Interfaces)
MarkInterfaceImplementation (iface, new MessageOrigin (type));
}
MarkGenericParameterProvider (type, origin);
MarkFieldsVisibleToReflection (type, new DependencyInfo (DependencyKind.MemberOfType, type), origin);
MarkMethodsVisibleToReflection (type, new DependencyInfo (DependencyKind.MemberOfType, type), origin);
if (type.HasProperties) {
foreach (var property in type.Properties) {
MarkPropertyVisibleToReflection (property, new DependencyInfo (DependencyKind.MemberOfType, type), origin);
}
}
if (type.HasEvents) {
foreach (var ev in type.Events) {
MarkEventVisibleToReflection (ev, new DependencyInfo (DependencyKind.MemberOfType, type), origin);
}
}
}
void Process ()
{
_dependencyGraph.ComputeDependencyRoutine += (List<DependencyNodeCore<NodeFactory>> nodes) => {
foreach (DependencyNodeCore<NodeFactory> node in nodes) {
if (node is ProcessCallbackNode processNode)
processNode.Process ();
}
};
_dependencyGraph.AddRoot (new ProcessCallbackNode (ProcessAllPendingItems), "start");
_dependencyGraph.ComputeMarkedNodes ();
ProcessPendingTypeChecks ();
bool ProcessAllPendingItems ()
=> ProcessPrimaryQueue () ||
ProcessMarkedPending () ||
ProcessLazyAttributes () ||
ProcessLateMarkedAttributes () ||
MarkFullyPreservedAssemblies ();
}
static bool IsFullyPreservedAction (AssemblyAction action) => action == AssemblyAction.Copy || action == AssemblyAction.Save;
bool MarkFullyPreservedAssemblies ()
{
// Fully mark any assemblies with copy/save action.
// Unresolved references could get the copy/save action if this is the default action.
bool scanReferences = IsFullyPreservedAction (Context.TrimAction) || IsFullyPreservedAction (Context.DefaultAction);
if (!scanReferences) {
// Unresolved references could get the copy/save action if it was set explicitly
// for some referenced assembly that has not been resolved yet
foreach (var (assemblyName, action) in Context.Actions) {
if (!IsFullyPreservedAction (action))
continue;
var assembly = Context.GetLoadedAssembly (assemblyName);
if (assembly == null) {
scanReferences = true;
break;
}
// The action should not change from the explicit command-line action
Debug.Assert (Annotations.GetAction (assembly) == action);
}
}
// Setup empty origin - there has to be some origin setup since we're doing marking below
// but there's no "origin" right now (command line is the origin really)
var emptyOrigin = new MessageOrigin (null as ICustomAttributeProvider);
// Beware: this works on loaded assemblies, not marked assemblies, so it should not be tied to marking.
// We could further optimize this to only iterate through assemblies if the last mark iteration loaded
// a new assembly, since this is the only way that the set we need to consider could have changed.
var assembliesToCheck = scanReferences ? Context.GetReferencedAssemblies ().ToArray () : Context.GetAssemblies ();
bool markedNewAssembly = false;
foreach (var assembly in assembliesToCheck) {
var action = Annotations.GetAction (assembly);
if (!IsFullyPreservedAction (action))
continue;
if (!Annotations.IsProcessed (assembly))
markedNewAssembly = true;
MarkAssembly (assembly, new DependencyInfo (DependencyKind.AssemblyAction, null), emptyOrigin);
}
return markedNewAssembly;
}
bool ProcessPrimaryQueue ()
{
if (_completed)
return false;
while (!_completed) {
_completed = true;
ProcessInterfaceMethods ();
ProcessMarkedTypesWithInterfaces ();
ProcessDynamicCastableImplementationInterfaces ();
ProcessPendingBodies ();
DoAdditionalProcessing ();
}
return true;
}
bool ProcessMarkedPending ()
{
bool marked = false;
foreach (var pending in Annotations.GetMarkedPending ()) {
marked = true;
// Some pending items might be processed by the time we get to them.
if (Annotations.IsProcessed (pending.Key))
continue;
switch (pending.Key) {
case TypeDefinition type:
MarkType (type, DependencyInfo.AlreadyMarked, pending.Value);
break;
case MethodDefinition method:
MarkMethod (method, DependencyInfo.AlreadyMarked, pending.Value);
// Methods will not actually be processed until we drain the method queue.
break;
case FieldDefinition field:
MarkField (field, DependencyInfo.AlreadyMarked, pending.Value);
break;
case ModuleDefinition module:
MarkModule (module, DependencyInfo.AlreadyMarked, pending.Value);
break;
case ExportedType exportedType:
Annotations.SetProcessed (exportedType);
// No additional processing is done for exported types.
break;
default:
throw new NotImplementedException (pending.GetType ().ToString ());
}
}
foreach (var type in Annotations.GetPendingPreserve ()) {
marked = true;
ApplyPreserveInfo (type);
}
return marked;
}
void ProcessPendingTypeChecks ()
{
for (int i = 0; i < _pending_isinst_instr.Count; ++i) {
var item = _pending_isinst_instr[i];
TypeDefinition type = item.Type;
if (Annotations.IsInstantiated (type))
continue;
Instruction instr = item.Instr;
LinkerILProcessor ilProcessor = item.Body.GetLinkerILProcessor ();
ilProcessor.InsertAfter (instr, Instruction.Create (OpCodes.Ldnull));
Instruction new_instr = Instruction.Create (OpCodes.Pop);
ilProcessor.Replace (instr, new_instr);
Context.LogMessage ($"Removing typecheck of '{type.FullName}' inside '{item.Body.Method.GetDisplayName ()}' method.");
}
}
void ProcessInterfaceMethods ()
{
foreach ((var method, var origin) in _interface_methods) {
ProcessInterfaceMethod (method, origin);
}
}
/// <summary>
/// Handles marking of interface implementations, and the marking of methods that implement interfaces
/// once ILLink knows whether a type is instantiated or relevant to variant casting,
/// and after interfaces and interface methods have been marked.
/// </summary>
void ProcessMarkedTypesWithInterfaces ()
{
// We may mark an interface type later on. Which means we need to reprocess any time with one or more interface implementations that have not been marked
// and if an interface type is found to be marked and implementation is not marked, then we need to mark that implementation
for (int i = 0; i < _typesWithInterfaces.Count; i++) {
(var type, var origin) = _typesWithInterfaces[i];
// Exception, types that have not been flagged as instantiated yet. These types may not need their interfaces even if the
// interface type is marked
// UnusedInterfaces optimization is turned off mark all interface implementations
bool unusedInterfacesOptimizationEnabled = Context.IsOptimizationEnabled (CodeOptimizations.UnusedInterfaces, type);
if (Annotations.IsInstantiated (type) || Annotations.IsRelevantToVariantCasting (type) ||
!unusedInterfacesOptimizationEnabled) {
MarkInterfaceImplementations (type);
}
// Interfaces in PreservedScope should have their methods added to _virtual_methods so that they are properly processed
foreach (var method in type.Methods) {
var baseMethods = Annotations.GetBaseMethods (method);
if (baseMethods is null)
continue;
foreach (var ov in baseMethods) {
if (ov.Base.DeclaringType is not null && ov.Base.DeclaringType.IsInterface && IgnoreScope (ov.Base.DeclaringType.Scope)) {
MarkMethodAsVirtual (ov.Base, origin);
}
}
}
}
}
void DiscoverDynamicCastableImplementationInterfaces ()
{
// We could potentially avoid loading all references here: https://github.com/dotnet/linker/issues/1788
foreach (var assembly in Context.GetReferencedAssemblies ().ToArray ()) {
switch (Annotations.GetAction (assembly)) {
// We only need to search assemblies where we don't mark everything
// Assemblies that are fully marked already mark these types.
case AssemblyAction.Link:
case AssemblyAction.AddBypassNGen:
case AssemblyAction.AddBypassNGenUsed:
if (!_dynamicInterfaceCastableImplementationTypesDiscovered.Add (assembly))
continue;
foreach (TypeDefinition type in assembly.MainModule.Types)
CheckIfTypeOrNestedTypesIsDynamicCastableImplementation (type);
break;
}
}
void CheckIfTypeOrNestedTypesIsDynamicCastableImplementation (TypeDefinition type)
{
if (!Annotations.IsMarked (type) && TypeIsDynamicInterfaceCastableImplementation (type))
_dynamicInterfaceCastableImplementationTypes.Add (type);
if (type.HasNestedTypes) {
foreach (var nestedType in type.NestedTypes)
CheckIfTypeOrNestedTypesIsDynamicCastableImplementation (nestedType);
}
}
}
void ProcessDynamicCastableImplementationInterfaces ()
{
DiscoverDynamicCastableImplementationInterfaces ();
// We may mark an interface type later on. Which means we need to reprocess any time with one or more interface implementations that have not been marked
// and if an interface type is found to be marked and implementation is not marked, then we need to mark that implementation
for (int i = 0; i < _dynamicInterfaceCastableImplementationTypes.Count; i++) {
var type = _dynamicInterfaceCastableImplementationTypes[i];
Debug.Assert (TypeIsDynamicInterfaceCastableImplementation (type));
// If the type has already been marked, we can remove it from this list.
if (Annotations.IsMarked (type)) {
_dynamicInterfaceCastableImplementationTypes.RemoveAt (i--);
continue;
}
foreach (var iface in type.Interfaces) {
if (Annotations.IsMarked (iface.InterfaceType)) {
// We only need to mark the type definition because ILLink will ensure that all marked implemented interfaces and used method implementations
// will be marked on this type as well.
MarkType (type, new DependencyInfo (DependencyKind.DynamicInterfaceCastableImplementation, iface.InterfaceType), new MessageOrigin (Context.TryResolve (iface.InterfaceType)));
_dynamicInterfaceCastableImplementationTypes.RemoveAt (i--);
break;
}
}
}
}
void ProcessPendingBodies ()
{
for (int i = 0; i < _unreachableBodies.Count; i++) {
(var body, var origin) = _unreachableBodies[i];
if (Annotations.IsInstantiated (body.Method.DeclaringType)) {
MarkMethodBody (body, origin);
_unreachableBodies.RemoveAt (i--);
}
}
}
void MarkMethodAsVirtual (MethodDefinition method, MessageOrigin origin)
{
Annotations.EnqueueVirtualMethod (method);
if (method.DeclaringType.IsInterface) {
_interface_methods.TryAdd (method, origin);
}
}
void ProcessInterfaceMethod (MethodDefinition method, MessageOrigin origin)
{
Debug.Assert (method.DeclaringType.IsInterface);
var defaultImplementations = Annotations.GetDefaultInterfaceImplementations (method);
if (defaultImplementations is not null) {
foreach (var dimInfo in defaultImplementations) {
ProcessDefaultImplementation (dimInfo, origin);
if (IsInterfaceImplementationMethodNeededByTypeDueToInterface (dimInfo))
MarkMethod (dimInfo.Override, new DependencyInfo (DependencyKind.Override, dimInfo.Base), origin);
}
}
List<OverrideInformation>? overridingMethods = (List<OverrideInformation>?) Annotations.GetOverrides (method);
if (overridingMethods is not null) {
for (int i = 0; i < overridingMethods.Count; i++) {
OverrideInformation ov = overridingMethods[i];
if (IsInterfaceImplementationMethodNeededByTypeDueToInterface (ov))
MarkMethod (ov.Override, new DependencyInfo (DependencyKind.Override, ov.Base), origin);
}
}
}
/// <summary>
/// Returns true if the Override in <paramref name="overrideInformation"/> should be marked because it is needed by the base method.
/// Does not take into account if the base method is in a preserved scope.
/// Assumes the base method is marked or comes from a preserved scope.
/// </summary>
// TODO: Move interface method marking logic here https://github.com/dotnet/linker/issues/3090
bool ShouldMarkOverrideForBase (OverrideInformation overrideInformation)
{
Debug.Assert (Annotations.IsMarked (overrideInformation.Base) || IgnoreScope (overrideInformation.Base.DeclaringType.Scope));
if (!Annotations.IsMarked (overrideInformation.Override.DeclaringType))
return false;
if (overrideInformation.IsOverrideOfInterfaceMember)
return false;
if (!Context.IsOptimizationEnabled (CodeOptimizations.OverrideRemoval, overrideInformation.Override))
return true;
// In this context, an override needs to be kept if
// a) it's an override on an instantiated type (of a marked base) or
// b) it's an override of an abstract base (required for valid IL)
if (Annotations.IsInstantiated (overrideInformation.Override.DeclaringType))
return true;
// Direct overrides of marked abstract ov.Overrides must be marked or we get invalid IL.
// Overrides further in the hierarchy will override the direct override (which will be implemented by the above rule), so we don't need to worry about invalid IL.
if (overrideInformation.Base.IsAbstract)
return true;
return false;
}
/// <summary>
/// Marks the Override of <paramref name="overrideInformation"/> with the correct reason. Should be called when <see cref="ShouldMarkOverrideForBase(OverrideInformation, bool)"/> returns true.
/// </summary>
// TODO: Take into account a base method in preserved scope
void MarkOverrideForBaseMethod (OverrideInformation overrideInformation, MessageOrigin origin)
{
Debug.Assert (ShouldMarkOverrideForBase (overrideInformation));
if (Context.IsOptimizationEnabled (CodeOptimizations.OverrideRemoval, overrideInformation.Override) && Annotations.IsInstantiated (overrideInformation.Override.DeclaringType)) {
MarkMethod (overrideInformation.Override, new DependencyInfo (DependencyKind.OverrideOnInstantiatedType, overrideInformation.Override.DeclaringType), origin);
} else {
// If the optimization is disabled or it's an abstract type, we just mark it as a normal override.
Debug.Assert (!Context.IsOptimizationEnabled (CodeOptimizations.OverrideRemoval, overrideInformation.Override) || overrideInformation.Base.IsAbstract);
MarkMethod (overrideInformation.Override, new DependencyInfo (DependencyKind.Override, overrideInformation.Base), origin);
}
}
void MarkMethodIfNeededByBaseMethod (MethodDefinition method, MessageOrigin origin)
{
Debug.Assert (Annotations.IsMarked (method.DeclaringType));
var bases = Annotations.GetBaseMethods (method);
if (bases is null)
return;
var markedBaseMethods = bases.Where (ov => Annotations.IsMarked (ov.Base) || IgnoreScope (ov.Base.DeclaringType.Scope));
foreach (var ov in markedBaseMethods) {
if (ShouldMarkOverrideForBase (ov))
MarkOverrideForBaseMethod (ov, origin);
}
}
/// <summary>
/// Returns true if <paramref name="type"/> implements <paramref name="interfaceType"/> and the interface implementation is marked,
/// or if any marked interface implementations on <paramref name="type"/> are interfaces that implement <paramref name="interfaceType"/> and that interface implementation is marked
/// </summary>
bool IsInterfaceImplementationMarkedRecursively (TypeDefinition type, TypeDefinition interfaceType)
=> IsInterfaceImplementationMarkedRecursively (type, interfaceType, Context);
/// <summary>
/// Returns true if <paramref name="type"/> implements <paramref name="interfaceType"/> and the interface implementation is marked,
/// or if any marked interface implementations on <paramref name="type"/> are interfaces that implement <paramref name="interfaceType"/> and that interface implementation is marked
/// </summary>
internal static bool IsInterfaceImplementationMarkedRecursively (TypeDefinition type, TypeDefinition interfaceType, LinkContext context)
{
if (type.HasInterfaces) {
foreach (var intf in type.Interfaces) {
TypeDefinition? resolvedInterface = context.Resolve (intf.InterfaceType);
if (resolvedInterface == null)
continue;
if (!context.Annotations.IsMarked (intf))
continue;
if (resolvedInterface == interfaceType)
return true;
if (IsInterfaceImplementationMarkedRecursively (resolvedInterface, interfaceType, context))
return true;
}
}
return false;
}
void ProcessDefaultImplementation (OverrideInformation ov, MessageOrigin origin)
{
Debug.Assert (ov.IsOverrideOfInterfaceMember);
if ((!ov.Override.IsStatic && !Annotations.IsInstantiated (ov.InterfaceImplementor.Implementor))
|| ov.Override.IsStatic && !Annotations.IsRelevantToVariantCasting (ov.InterfaceImplementor.Implementor))
return;
MarkInterfaceImplementation (ov.InterfaceImplementor.InterfaceImplementation, origin);
}
void MarkMarshalSpec (IMarshalInfoProvider spec, in DependencyInfo reason, MessageOrigin origin)
{
if (!spec.HasMarshalInfo)
return;
if (spec.MarshalInfo is CustomMarshalInfo marshaler) {
MarkType (marshaler.ManagedType, reason, origin);
TypeDefinition? type = Context.Resolve (marshaler.ManagedType);
if (type != null) {
MarkICustomMarshalerMethods (type, in reason, origin);
MarkCustomMarshalerGetInstance (type, in reason, origin);
}
}
}
void MarkCustomAttributes (ICustomAttributeProvider provider, in DependencyInfo reason, MessageOrigin origin)
{
if (provider.HasCustomAttributes) {
bool providerInLinkedAssembly = Annotations.GetAction (CustomAttributeSource.GetAssemblyFromCustomAttributeProvider (provider)) == AssemblyAction.Link;
bool markOnUse = Context.KeepUsedAttributeTypesOnly && providerInLinkedAssembly;
foreach (CustomAttribute ca in provider.CustomAttributes) {
if (ProcessLinkerSpecialAttribute (ca, provider, reason, origin))
continue;
if (markOnUse) {
_lateMarkedAttributes.Enqueue ((new AttributeProviderPair (ca, provider), reason, origin));
continue;
}
var resolvedAttributeType = Context.Resolve (ca.AttributeType);
if (resolvedAttributeType == null) {
continue;
}
if (providerInLinkedAssembly && IsAttributeRemoved (ca, resolvedAttributeType))
continue;
MarkCustomAttribute (ca, reason, origin);
}
}
if (!(provider is MethodDefinition || provider is FieldDefinition))
return;
IMemberDefinition providerMember = (IMemberDefinition) provider; ;
MessageOrigin providerOrigin = new MessageOrigin (providerMember);
foreach (var dynamicDependency in Annotations.GetLinkerAttributes<DynamicDependency> (providerMember))
MarkDynamicDependency (dynamicDependency, providerMember, providerOrigin);
}
bool IsAttributeRemoved (CustomAttribute ca, TypeDefinition attributeType)
{
foreach (var attr in Annotations.GetLinkerAttributes<RemoveAttributeInstancesAttribute> (attributeType)) {
var args = attr.Arguments;
if (args.Length == 0)
return true;
if (args.Length > ca.ConstructorArguments.Count)
continue;
if (HasMatchingArguments (args, ca.ConstructorArguments))
return true;
}
return false;
static bool HasMatchingArguments (CustomAttributeArgument[] removeAttrInstancesArgs, Collection<CustomAttributeArgument> attributeInstanceArgs)
{
for (int i = 0; i < removeAttrInstancesArgs.Length; ++i) {
if (!removeAttrInstancesArgs[i].IsEqualTo (attributeInstanceArgs[i]))
return false;
}
return true;
}
}
protected virtual bool ProcessLinkerSpecialAttribute (CustomAttribute ca, ICustomAttributeProvider provider, in DependencyInfo reason, MessageOrigin origin)
{
var isPreserveDependency = IsUserDependencyMarker (ca.AttributeType);
var isDynamicDependency = ca.AttributeType.IsTypeOf<DynamicDependencyAttribute> ();
if (!((isPreserveDependency || isDynamicDependency) && provider is IMemberDefinition member))
return false;
if (isPreserveDependency)
MarkUserDependency (member, ca, origin);
if (Context.CanApplyOptimization (CodeOptimizations.RemoveDynamicDependencyAttribute, member.DeclaringType.Module.Assembly)) {
// Record the custom attribute so that it has a reason, without actually marking it.
Tracer.AddDirectDependency (ca, reason, marked: false);
} else {
MarkCustomAttribute (ca, reason, origin);
}
return true;
}
void MarkDynamicDependency (DynamicDependency dynamicDependency, IMemberDefinition context, MessageOrigin origin)
{
Debug.Assert (context is MethodDefinition || context is FieldDefinition);
AssemblyDefinition? assembly;
if (dynamicDependency.AssemblyName != null) {
assembly = Context.TryResolve (dynamicDependency.AssemblyName);
if (assembly == null) {
Context.LogWarning (origin, DiagnosticId.UnresolvedAssemblyInDynamicDependencyAttribute, dynamicDependency.AssemblyName);
return;
}
} else {
assembly = context.DeclaringType.Module.Assembly;
Debug.Assert (assembly != null);
}
TypeDefinition? type;
if (dynamicDependency.TypeName is string typeName) {
type = DocumentationSignatureParser.GetTypeByDocumentationSignature (assembly, typeName, Context);
if (type == null) {
Context.LogWarning (origin, DiagnosticId.UnresolvedTypeInDynamicDependencyAttribute, typeName);
return;
}
MarkingHelpers.MarkMatchingExportedType (type, assembly, new DependencyInfo (DependencyKind.DynamicDependency, type), origin);
} else if (dynamicDependency.Type is TypeReference typeReference) {
type = Context.TryResolve (typeReference);
if (type == null) {
Context.LogWarning (origin, DiagnosticId.UnresolvedTypeInDynamicDependencyAttribute, typeReference.GetDisplayName ());
return;
}
} else {
type = Context.TryResolve (context.DeclaringType);
if (type == null) {
Context.LogWarning (context, DiagnosticId.UnresolvedTypeInDynamicDependencyAttribute, context.DeclaringType.GetDisplayName ());
return;
}
}
IEnumerable<IMetadataTokenProvider> members;
if (dynamicDependency.MemberSignature is string memberSignature) {
members = DocumentationSignatureParser.GetMembersByDocumentationSignature (type, memberSignature, Context, acceptName: true);
if (!members.Any ()) {
Context.LogWarning (origin, DiagnosticId.NoMembersResolvedForMemberSignatureOrType, memberSignature, type.GetDisplayName ());
return;
}
} else {
var memberTypes = dynamicDependency.MemberTypes;
members = type.GetDynamicallyAccessedMembers (Context, memberTypes);
if (!members.Any ()) {
Context.LogWarning (origin, DiagnosticId.NoMembersResolvedForMemberSignatureOrType, memberTypes.ToString (), type.GetDisplayName ());
return;
}
}
MarkMembersVisibleToReflection (members, new DependencyInfo (DependencyKind.DynamicDependency, context), origin);
}
void MarkMembersVisibleToReflection (IEnumerable<IMetadataTokenProvider> members, in DependencyInfo reason, MessageOrigin origin)
{
foreach (var member in members) {
switch (member) {
case TypeDefinition type:
MarkTypeVisibleToReflection (type, type, reason, origin);
break;
case MethodDefinition method:
MarkMethodVisibleToReflection (method, reason, origin);
break;
case FieldDefinition field:
MarkFieldVisibleToReflection (field, reason, origin);
break;
case PropertyDefinition property:
MarkPropertyVisibleToReflection (property, reason, origin);
break;
case EventDefinition @event:
MarkEventVisibleToReflection (@event, reason, origin);
break;
case InterfaceImplementation interfaceType:
MarkInterfaceImplementation (interfaceType, origin, reason);
break;
}
}
}
protected virtual bool IsUserDependencyMarker (TypeReference type)
{
return type.Name == "PreserveDependencyAttribute" && type.Namespace == "System.Runtime.CompilerServices";
}
protected virtual void MarkUserDependency (IMemberDefinition context, CustomAttribute ca, MessageOrigin origin)
{
Context.LogWarning (context, DiagnosticId.DeprecatedPreserveDependencyAttribute);
if (!DynamicDependency.ShouldProcess (Context, ca))
return;
AssemblyDefinition? assembly;
var args = ca.ConstructorArguments;
if (args.Count >= 3 && args[2].Value is string assemblyName) {
assembly = Context.TryResolve (assemblyName);
if (assembly == null) {
Context.LogWarning (context, DiagnosticId.CouldNotResolveDependencyAssembly, assemblyName);
return;
}
} else {
assembly = null;
}
TypeDefinition? td;
if (args.Count >= 2 && args[1].Value is string typeName) {
AssemblyDefinition assemblyDef = assembly ?? ((MemberReference) context).Module.Assembly;
td = Context.TryResolve (assemblyDef, typeName);
if (td == null) {
Context.LogWarning (context, DiagnosticId.CouldNotResolveDependencyType, typeName);
return;
}
MarkingHelpers.MarkMatchingExportedType (td, assemblyDef, new DependencyInfo (DependencyKind.PreservedDependency, ca), origin);
} else {
td = context.DeclaringType;
}
string? member = null;
string[]? signature = null;
if (args.Count >= 1 && args[0].Value is string memberSignature) {
memberSignature = memberSignature.Replace (" ", "");
var sign_start = memberSignature.IndexOf ('(');
var sign_end = memberSignature.LastIndexOf (')');
if (sign_start > 0 && sign_end > sign_start) {
var parameters = memberSignature.Substring (sign_start + 1, sign_end - sign_start - 1);
signature = string.IsNullOrEmpty (parameters) ? Array.Empty<string> () : parameters.Split (',');
member = memberSignature.Substring (0, sign_start);
} else {
member = memberSignature;
}
}
if (member == "*") {
MarkEntireType (td, new DependencyInfo (DependencyKind.PreservedDependency, ca), origin);
return;
}
if (member != null) {
if (MarkDependencyMethod (td, member, signature, new DependencyInfo (DependencyKind.PreservedDependency, ca), origin))
return;