Welcome to mirror list, hosted at ThFree Co, Russian Federation.

SweepStep.cs « Linker.Steps « linker « src - github.com/mono/linker.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 5da72ea659d7e35645164a263893961bf76e2f54 (plain)
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
// 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.

//
// SweepStep.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.Linq;
using Mono.Cecil;
using Mono.Cecil.Cil;
using Mono.Collections.Generic;

namespace Mono.Linker.Steps
{
	public class SweepStep : BaseStep
	{
		readonly bool sweepSymbols;

		public SweepStep (bool sweepSymbols = true)
		{
			this.sweepSymbols = sweepSymbols;
		}

		protected override void Process ()
		{
			var assemblies = Annotations.GetAssemblies ().ToArray ();

			// Ensure that any assemblies which need to be removed are marked for deletion,
			// including assemblies which are not referenced by any others.
			foreach (var assembly in assemblies)
				RemoveUnmarkedAssembly (assembly);

			// Look for references (included to previously unresolved assemblies) marked for deletion
			foreach (var assembly in assemblies)
				UpdateAssemblyReferencesToRemovedAssemblies (assembly);

			// Update scopes before removing any type forwarder.
			foreach (var assembly in assemblies) {
				var action = Annotations.GetAction (assembly);
				switch (action) {
				case AssemblyAction.CopyUsed:
				case AssemblyAction.Link:
				case AssemblyAction.Save:
					bool changed = AssemblyReferencesCorrector.SweepAssemblyReferences (assembly);
					if (changed && action == AssemblyAction.CopyUsed)
						Annotations.SetAction (assembly, AssemblyAction.Save);
					break;
				}
			}

			foreach (var assembly in assemblies)
				ProcessAssemblyAction (assembly);

			// Ensure that we remove any assemblies which were resolved while sweeping references
			foreach (var assembly in Annotations.GetAssemblies ().ToArray ()) {
				if (!assemblies.Any (processedAssembly => processedAssembly == assembly)) {
					Debug.Assert (!IsMarkedAssembly (assembly));
					Annotations.SetAction (assembly, AssemblyAction.Delete);
				}
			}
		}

		void RemoveUnmarkedAssembly (AssemblyDefinition assembly)
		{
			// Check if unmarked whole assembly can be turned into full
			// assembly removal (AssemblyAction.Delete)
			switch (Annotations.GetAction (assembly)) {
			case AssemblyAction.AddBypassNGenUsed:
			case AssemblyAction.CopyUsed:
			case AssemblyAction.Link:
				if (!IsMarkedAssembly (assembly))
					RemoveAssembly (assembly);

				break;
			}
		}

		void UpdateAssemblyReferencesToRemovedAssemblies (AssemblyDefinition assembly)
		{
			var action = Annotations.GetAction (assembly);
			switch (action) {
			case AssemblyAction.Copy:
			case AssemblyAction.Delete:
			case AssemblyAction.Link:
			case AssemblyAction.Save:
			case AssemblyAction.Skip:
				return;

			case AssemblyAction.CopyUsed:
			case AssemblyAction.AddBypassNGen:
			case AssemblyAction.AddBypassNGenUsed:
				foreach (var reference in assembly.MainModule.AssemblyReferences) {
					AssemblyDefinition? ad = Context.Resolver.Resolve (reference);
					if (ad == null)
						continue;

					RemoveUnmarkedAssembly (ad);
					if (Annotations.GetAction (ad) != AssemblyAction.Delete)
						continue;

					// Assembly was removed in the output but it's referenced by
					// other assembly with action which does not update references

					switch (action) {
					case AssemblyAction.CopyUsed:
						//
						// Assembly has a reference to another assembly which has been fully removed. This can
						// happen when for example the reference assembly is 'copy-used' and it's not needed.
						//
						// or
						//
						// Assembly can contain type references with
						// type forwarders to deleted assembly (facade) when
						// facade assemblies are not kept. For that reason we need to
						// rewrite the copy to save to update the scopes not to point
						// forwarding assembly (facade).
						//
						//		foo.dll -> facade.dll    -> lib.dll
						//		copy    |  copy (delete) |  link
						//
						Annotations.SetAction (assembly, AssemblyAction.Save);
						continue;

					case AssemblyAction.AddBypassNGenUsed:
						Annotations.SetAction (assembly, AssemblyAction.AddBypassNGen);
						goto case AssemblyAction.AddBypassNGen;

					case AssemblyAction.AddBypassNGen:
						continue;
					}
				}
				break;
			default:
				throw new ArgumentOutOfRangeException (action.ToString ());
			}
		}

		protected void ProcessAssemblyAction (AssemblyDefinition assembly)
		{
			switch (Annotations.GetAction (assembly)) {
			case AssemblyAction.AddBypassNGenUsed:
				Annotations.SetAction (assembly, AssemblyAction.AddBypassNGen);
				goto case AssemblyAction.AddBypassNGen;

			case AssemblyAction.CopyUsed:
				AssemblyAction assemblyAction = AssemblyAction.Copy;
				if (SweepTypeForwarders (assembly)) {
					// Need to sweep references, in case sweeping type forwarders removed any
					AssemblyReferencesCorrector.SweepAssemblyReferences (assembly);
					assemblyAction = AssemblyAction.Save;
				}

				Annotations.SetAction (assembly, assemblyAction);
				break;

			case AssemblyAction.Copy:
				break;

			case AssemblyAction.Link:
				SweepAssembly (assembly);
				break;

			case AssemblyAction.AddBypassNGen:
			// FIXME: AddBypassNGen is just wrong, it should not be action as we need to
			// turn it to Action.Save here to e.g. correctly update debug symbols
			case AssemblyAction.Save:
				if (SweepTypeForwarders (assembly)) {
					// Need to sweep references, in case sweeping type forwarders removed any
					AssemblyReferencesCorrector.SweepAssemblyReferences (assembly);
				}
				break;
			}
		}

		protected virtual void SweepAssembly (AssemblyDefinition assembly)
		{
			var types = new List<TypeDefinition> ();
			ModuleDefinition main = assembly.MainModule;
			bool updateScopes = false;

			foreach (TypeDefinition type in main.Types) {
				if (!ShouldRemove (type)) {
					SweepType (type);
					types.Add (type);
					updateScopes = true;
					continue;
				}

				// Is <Module> type.
				if (type.MetadataToken.RID == 1)
					types.Add (type);
				else
					ElementRemoved (type);
			}

			main.Types.Clear ();
			foreach (TypeDefinition type in types)
				main.Types.Add (type);

			SweepResources (assembly);
			updateScopes |= SweepCustomAttributes (assembly);

			foreach (var module in assembly.Modules)
				updateScopes |= SweepCustomAttributes (module);

			//
			// MainModule module references are used by pinvoke
			//
			if (main.HasModuleReferences)
				updateScopes |= SweepCollectionMetadata (main.ModuleReferences);

			if (main.EntryPoint != null && !Annotations.IsMarked (main.EntryPoint)) {
				main.EntryPoint = null;
			}

			if (SweepTypeForwarders (assembly) || updateScopes)
				AssemblyReferencesCorrector.SweepAssemblyReferences (assembly);
		}

		bool IsMarkedAssembly (AssemblyDefinition assembly)
		{
			return Annotations.IsMarked (assembly.MainModule);
		}

		bool CanSweepNamesForMember (IMemberDefinition member, MetadataTrimming metadataTrimming)
		{
			return (Context.MetadataTrimming & metadataTrimming) != 0 && !Annotations.IsReflectionUsed (member);
		}

		protected virtual void RemoveAssembly (AssemblyDefinition assembly)
		{
			Annotations.SetAction (assembly, AssemblyAction.Delete);
		}

		void SweepResources (AssemblyDefinition assembly)
		{
			var resourcesToRemove = Annotations.GetResourcesToRemove (assembly);
			if (resourcesToRemove == null)
				return;

			var resources = assembly.MainModule.Resources;
			foreach (var resource in resourcesToRemove)
				resources.Remove (resource);
		}

		bool SweepTypeForwarders (AssemblyDefinition assembly)
		{
			return assembly.MainModule.HasExportedTypes &&
				SweepCollectionMetadata (assembly.MainModule.ExportedTypes);
		}

		protected virtual void SweepType (TypeDefinition type)
		{
			if (type.HasFields)
				SweepCollectionWithCustomAttributes (type.Fields);

			if (type.HasMethods)
				SweepMethods (type.Methods);

			if (type.HasNestedTypes)
				SweepNestedTypes (type);

			if (type.HasInterfaces)
				SweepInterfaces (type);

			if (type.HasCustomAttributes)
				SweepCustomAttributes (type);

			if (type.HasGenericParameters)
				SweepGenericParameters (type.GenericParameters);

			if (type.HasProperties)
				SweepCustomAttributeCollection (type.Properties);

			if (type.HasEvents)
				SweepCustomAttributeCollection (type.Events);

			if (type.HasFields && !type.IsBeforeFieldInit && !Annotations.HasPreservedStaticCtor (type) && !type.IsEnum)
				type.IsBeforeFieldInit = true;
		}

		protected void SweepNestedTypes (TypeDefinition type)
		{
			for (int i = 0; i < type.NestedTypes.Count; i++) {
				var nested = type.NestedTypes[i];
				if (ShouldRemove (nested)) {
					ElementRemoved (type.NestedTypes[i]);
					type.NestedTypes.RemoveAt (i--);
				} else {
					SweepType (nested);
				}
			}
		}

		protected void SweepInterfaces (TypeDefinition type)
		{
			for (int i = type.Interfaces.Count - 1; i >= 0; i--) {
				var iface = type.Interfaces[i];
				if (ShouldRemove (iface)) {
					InterfaceRemoved (type, iface);
					type.Interfaces.RemoveAt (i);
				} else {
					SweepCustomAttributes (iface);
				}
			}
		}

		protected void SweepGenericParameters (Collection<GenericParameter> genericParameters)
		{
			foreach (var gp in genericParameters) {
				SweepCustomAttributes (gp);

				if (gp.HasConstraints)
					SweepCustomAttributeCollection (gp.Constraints);
			}
		}

		protected void SweepCustomAttributes (TypeDefinition type)
		{
			bool removed = SweepCustomAttributes (type as ICustomAttributeProvider);

			if (removed && type.HasSecurity && ShouldSetHasSecurityToFalse (type, type))
				type.HasSecurity = false;
		}

		protected void SweepCustomAttributes (MethodDefinition method)
		{
			bool removed = SweepCustomAttributes (method as ICustomAttributeProvider);

			if (removed && method.HasSecurity && ShouldSetHasSecurityToFalse (method, method))
				method.HasSecurity = false;
		}

		bool ShouldSetHasSecurityToFalse (ISecurityDeclarationProvider providerAsSecurity, ICustomAttributeProvider provider)
		{
			if (!providerAsSecurity.HasSecurityDeclarations) {
				// If the method or type had security before and all attributes were removed, or no remaining attributes are security attributes,
				// then we need to set HasSecurity to false
				if (!provider.HasCustomAttributes || provider.CustomAttributes.All (attr => {
					TypeDefinition? attributeType = Context.TryResolve (attr.AttributeType);
					return attributeType == null || !IsSecurityAttributeType (attributeType);
				}))
					return true;
			}

			return false;
		}

		bool IsSecurityAttributeType (TypeDefinition definition)
		{
			if (definition == null)
				return false;

			if (definition.Namespace == "System.Security") {
				return definition.FullName switch {
					// This seems to be one attribute in the System.Security namespace that doesn't count
					// as an attribute that requires HasSecurity to be true
					"System.Security.SecurityCriticalAttribute" => false,
					_ => true,
				};
			}

			var baseDefinition = Context.TryResolve (definition.BaseType);
			if (baseDefinition == null)
				return false;

			return IsSecurityAttributeType (baseDefinition);
		}

		protected bool SweepCustomAttributes (ICustomAttributeProvider provider)
		{
			bool removed = false;

			for (int i = provider.CustomAttributes.Count - 1; i >= 0; i--) {
				var attribute = provider.CustomAttributes[i];
				if (!Annotations.IsMarked (attribute)) {
					CustomAttributeUsageRemoved (provider, attribute);
					provider.CustomAttributes.RemoveAt (i);
					removed = true;
				}
			}

			return removed;
		}

		protected void SweepCustomAttributeCollection<T> (Collection<T> providers) where T : ICustomAttributeProvider
		{
			foreach (var provider in providers)
				SweepCustomAttributes (provider);
		}

		protected virtual void SweepMethods (Collection<MethodDefinition> methods)
		{
			SweepCollectionWithCustomAttributes (methods);
			if (sweepSymbols)
				SweepDebugInfo (methods);

			foreach (var method in methods) {
				if (method.HasGenericParameters)
					SweepGenericParameters (method.GenericParameters);

				SweepCustomAttributes (method.MethodReturnType);

				SweepOverrides (method);

				if (!method.HasParameters)
					continue;

				bool sweepNames = CanSweepNamesForMember (method, MetadataTrimming.ParameterName);

				foreach (var parameter in method.Parameters) {
					if (sweepNames)
						parameter.Name = null;

					SweepCustomAttributes (parameter);
				}
			}
		}
		void SweepOverrides (MethodDefinition method)
		{
			for (int i = 0; i < method.Overrides.Count;) {
				// We can't rely on the context resolution cache anymore, since it may remember methods which are already removed
				// So call the direct Resolve here and avoid the cache.
				// We want to remove a method from the list of Overrides if:
				//	Resolve() is null
				//		This can happen for a couple of reasons, but it indicates the method isn't in the final assembly.
				//		Resolve also may return a removed value if method.Overrides[i] is a MethodDefinition. In this case, Resolve short circuits and returns `this`.
				//	OR
				//	ov.DeclaringType is null
				//		ov.DeclaringType may be null if Resolve short circuited and returned a removed method. In this case, we want to remove the override.
				//	OR
				//	ov is in a `link` scope and is unmarked
				//		ShouldRemove returns true if the method is unmarked, but we also We need to make sure the override is in a link scope.
				//		Only things in a link scope are marked, so ShouldRemove is only valid for items in a `link` scope.
				if (method.Overrides[i].Resolve () is not MethodDefinition ov || ov.DeclaringType is null || (IsLinkScope (ov.DeclaringType.Scope) && ShouldRemove (ov)))
					method.Overrides.RemoveAt (i);
				else
					i++;
			}
		}

		/// <summary>
		/// Returns true if the assembly of the <paramref name="scope"></paramref> is set to link
		/// </summary>
		private bool IsLinkScope (IMetadataScope scope)
		{
			AssemblyDefinition? assembly = Context.Resolve (scope);
			return assembly != null && Annotations.GetAction (assembly) == AssemblyAction.Link;
		}

		void SweepDebugInfo (Collection<MethodDefinition> methods)
		{
			List<ScopeDebugInformation>? sweptScopes = null;
			foreach (var m in methods) {
				if (m.DebugInformation == null)
					continue;

				var scope = m.DebugInformation.Scope;
				if (scope == null)
					continue;

				if (sweptScopes == null) {
					sweptScopes = new List<ScopeDebugInformation> ();
				} else if (sweptScopes.Contains (scope)) {
					continue;
				}

				sweptScopes.Add (scope);

				if (scope.HasConstants) {
					var constants = scope.Constants;
					for (int i = 0; i < constants.Count; ++i) {
						if (!Annotations.IsMarked (constants[i].ConstantType))
							constants.RemoveAt (i--);
					}
				}

				var import = scope.Import;
				while (import != null) {
					if (import.HasTargets) {
						var targets = import.Targets;
						for (int i = 0; i < targets.Count; ++i) {
							var ttype = targets[i].Type;
							if (ttype != null && !Annotations.IsMarked (ttype))
								targets.RemoveAt (i--);

							// TODO: Clear also AssemblyReference and Namespace when not marked
						}
					}

					import = import.Parent;
				}
			}
		}

		protected void SweepCollectionWithCustomAttributes<T> (IList<T> list) where T : ICustomAttributeProvider
		{
			for (int i = 0; i < list.Count; i++)
				if (ShouldRemove (list[i])) {
					ElementRemoved (list[i]);
					list.RemoveAt (i--);
				} else {
					SweepCustomAttributes (list[i]);
				}
		}

		protected bool SweepCollectionMetadata<T> (IList<T> list) where T : IMetadataTokenProvider
		{
			bool removed = false;

			for (int i = 0; i < list.Count; i++) {
				if (ShouldRemove (list[i])) {
					ElementRemoved (list[i]);
					list.RemoveAt (i--);
					removed = true;
				}
			}

			return removed;
		}

		protected virtual bool ShouldRemove<T> (T element) where T : IMetadataTokenProvider
		{
			return !Annotations.IsMarked (element);
		}

		protected virtual void ElementRemoved (IMetadataTokenProvider element)
		{
		}

		protected virtual void InterfaceRemoved (TypeDefinition type, InterfaceImplementation iface)
		{
		}

		protected virtual void CustomAttributeUsageRemoved (ICustomAttributeProvider provider, CustomAttribute attribute)
		{
		}

		sealed class AssemblyReferencesCorrector : TypeReferenceWalker
		{
			readonly DefaultMetadataImporter importer;

			bool changedAnyScopes;

			AssemblyReferencesCorrector (AssemblyDefinition assembly) : base (assembly)
			{
				this.importer = new DefaultMetadataImporter (assembly.MainModule);
				changedAnyScopes = false;
			}

			public static bool SweepAssemblyReferences (AssemblyDefinition assembly)
			{
				//
				// We used to run over list returned by GetTypeReferences but
				// that returns typeref(s) of original assembly and we don't track
				// which types are needed for which assembly which left us
				// with dangling assembly references
				//
				assembly.MainModule.AssemblyReferences.Clear ();

				var arc = new AssemblyReferencesCorrector (assembly);
				arc.Process ();

				return arc.changedAnyScopes;
			}

			protected override void ProcessTypeReference (TypeReference type)
			{
				//
				// Resolve to type definition to remove any type forwarding imports
				//
				// Workaround for https://github.com/dotnet/linker/issues/2260
				// Context has a cache which stores ref->def mapping. This code runs during sweeping
				// which can remove the type-def from its assembly, effectively making the ref unresolvable.
				// But the cache doesn't know that, it would still "resolve" the type-ref to now defunct type-def.
				// For this reason we can't use the context resolution here, and must force Cecil to perform
				// real type resolution again (since it can fail, and that's OK).
#pragma warning disable RS0030 // Do not used banned APIs
				TypeDefinition td = type.Resolve ();
#pragma warning restore RS0030 // Do not used banned APIs
				if (td == null) {
					//
					// This can happen when not all assembly refences were provided and we
					// run in `--skip-unresolved` mode. We cannot fully sweep and keep the
					// original assembly reference
					//
					var anr = (AssemblyNameReference) type.Scope;
					type.Scope = importer.ImportReference (anr);
					return;
				}

				var tr = assembly.MainModule.ImportReference (td);
				if (type.Scope == tr.Scope)
					return;

				type.Scope = tr.Scope;
				changedAnyScopes = true;
			}

			protected override void ProcessExportedType (ExportedType exportedType)
			{
				TypeDefinition td = exportedType.Resolve ();
				if (td == null) {
					// Forwarded type cannot be resolved but it was marked
					// linker is running in --skip-unresolved true mode
					var anr = (AssemblyNameReference) exportedType.Scope;
					exportedType.Scope = importer.ImportReference (anr);
					return;
				}

				var tr = assembly.MainModule.ImportReference (td);
				if (exportedType.Scope == tr.Scope)
					return;

				exportedType.Scope = tr.Scope;
				changedAnyScopes = true;
			}
		}
	}
}