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

MethodBodyScanner.cs « Linker « linker « src - github.com/mono/linker.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 8f2aa05a6cf7b51c3adf5eeb12b3b2e53323965c (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
// 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.

using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using Mono.Cecil;
using Mono.Cecil.Cil;

namespace Mono.Linker
{
	public static class MethodBodyScanner
	{
		public static bool IsWorthConvertingToThrow (MethodBody body)
		{
			// Some bodies are cheaper size wise to leave alone than to convert to a throw
			Instruction? previousMeaningful = null;
			int meaningfulCount = 0;
			foreach (var ins in body.Instructions) {
				// Handle ignoring noops because because (1) it's a valid case to ignore
				// and (2) When running the tests on .net core roslyn tosses in no ops
				// and that leads to a difference in test results between mcs and .net framework csc.
				if (ins.OpCode.Code == Code.Nop)
					continue;

				meaningfulCount++;

				if (meaningfulCount == 1 && ins.OpCode.Code == Code.Ret)
					return false;

				if (meaningfulCount == 2 && ins.OpCode.Code == Code.Ret && previousMeaningful != null) {
					if (previousMeaningful.OpCode.StackBehaviourPop == StackBehaviour.Pop0) {
						switch (previousMeaningful.OpCode.StackBehaviourPush) {
						case StackBehaviour.Pushi:
						case StackBehaviour.Pushi8:
						case StackBehaviour.Pushr4:
						case StackBehaviour.Pushr8:
							return false;
						}

						switch (previousMeaningful.OpCode.Code) {
						case Code.Ldnull:
							return false;
						}
					}
				}

				if (meaningfulCount >= 2)
					return true;

				previousMeaningful = ins;
			}

			return true;
		}
	}
	readonly struct InterfacesOnStackScanner
	{
		readonly LinkContext context;

		public InterfacesOnStackScanner (LinkContext context)
		{
			this.context = context;
		}

		public IEnumerable<(InterfaceImplementation, TypeDefinition)>? GetReferencedInterfaces (MethodBody body)
		{
			var possibleStackTypes = AllPossibleStackTypes (body.Method);
			if (possibleStackTypes.Count == 0)
				return null;

			var interfaceTypes = possibleStackTypes.Where (t => t.IsInterface).ToArray ();
			if (interfaceTypes.Length == 0)
				return null;

			var interfaceImplementations = new HashSet<(InterfaceImplementation, TypeDefinition)> ();

			// If a type could be on the stack in the body and an interface it implements could be on the stack on the body
			// then we need to mark that interface implementation.  When this occurs it is not safe to remove the interface implementation from the type
			// even if the type is never instantiated
			foreach (var type in possibleStackTypes) {
				// We only sweep interfaces on classes so that's why we only care about classes
				if (!type.IsClass)
					continue;

				TypeDefinition? currentType = type;
				while (currentType?.BaseType != null) // Checking BaseType != null to skip System.Object
				{
					AddMatchingInterfaces (interfaceImplementations, currentType, interfaceTypes);
					currentType = context.TryResolve (currentType.BaseType);
				}
			}

			return interfaceImplementations;
		}

		HashSet<TypeDefinition> AllPossibleStackTypes (MethodDefinition method)
		{
			if (!method.HasBody)
				throw new ArgumentException ("Method does not have body", nameof (method));

			var body = method.Body;
			var types = new HashSet<TypeDefinition> ();

			foreach (VariableDefinition var in body.Variables)
				AddIfResolved (types, var.VariableType);

			foreach (var param in method.GetParameters ())
				AddIfResolved (types, param.ParameterType);

			foreach (ExceptionHandler eh in body.ExceptionHandlers) {
				if (eh.HandlerType == ExceptionHandlerType.Catch) {
					AddIfResolved (types, eh.CatchType);
				}
			}

			foreach (Instruction instruction in body.Instructions) {
				if (instruction.Operand is FieldReference fieldReference) {
					if (context.TryResolve (fieldReference)?.FieldType is TypeReference fieldType)
						AddIfResolved (types, fieldType);
				} else if (instruction.Operand is MethodReference methodReference) {
					if (methodReference is GenericInstanceMethod genericInstanceMethod)
						AddFromGenericInstance (types, genericInstanceMethod);

					if (methodReference.DeclaringType is GenericInstanceType genericInstanceType)
						AddFromGenericInstance (types, genericInstanceType);

					var resolvedMethod = context.TryResolve (methodReference);
					if (resolvedMethod != null) {
						if (resolvedMethod.HasMetadataParameters ()) {
							foreach (var param in resolvedMethod.GetParameters ())
								AddIfResolved (types, param.ParameterType);
						}

						AddFromGenericParameterProvider (types, resolvedMethod);
						AddFromGenericParameterProvider (types, resolvedMethod.DeclaringType);
						AddIfResolved (types, resolvedMethod.ReturnType);
					}
				}
			}


			return types;
		}

		void AddMatchingInterfaces (HashSet<(InterfaceImplementation, TypeDefinition)> results, TypeDefinition type, TypeDefinition[] interfaceTypes)
		{
			if (!type.HasInterfaces)
				return;

			foreach (var interfaceType in interfaceTypes) {
				if (HasInterface (type, interfaceType, out InterfaceImplementation? implementation))
					results.Add ((implementation, type));
			}
		}

		bool HasInterface (TypeDefinition type, TypeDefinition interfaceType, [NotNullWhen (true)] out InterfaceImplementation? implementation)
		{
			implementation = null;
			if (!type.HasInterfaces)
				return false;

			foreach (var iface in type.Interfaces) {
				if (context.TryResolve (iface.InterfaceType) == interfaceType) {
					implementation = iface;
					return true;
				}
			}

			return false;
		}

		void AddFromGenericInstance (HashSet<TypeDefinition> set, IGenericInstance instance)
		{
			if (!instance.HasGenericArguments)
				return;

			foreach (var genericArgument in instance.GenericArguments)
				AddIfResolved (set, genericArgument);
		}

		void AddFromGenericParameterProvider (HashSet<TypeDefinition> set, IGenericParameterProvider provider)
		{
			if (!provider.HasGenericParameters)
				return;

			foreach (var genericParameter in provider.GenericParameters) {
				foreach (var constraint in genericParameter.Constraints)
					AddIfResolved (set, constraint.ConstraintType);
			}
		}

		void AddIfResolved (HashSet<TypeDefinition> set, TypeReference item)
		{
			var resolved = context.TryResolve (item);
			if (resolved == null)
				return;

			set.Add (resolved);
		}
	}
}