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

CodeRewriterStep.cs « Linker.Steps « linker « src - github.com/mono/linker.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 6d70b1a09edf3d7d2ae6c7a69cec214d4195b04d (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
// 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.Diagnostics;
using System.Linq;
using Mono.Cecil;
using Mono.Cecil.Cil;

namespace Mono.Linker.Steps
{
	public class CodeRewriterStep : BaseStep
	{
		AssemblyDefinition? assembly;
		AssemblyDefinition Assembly {
			get {
				Debug.Assert (assembly != null);
				return assembly;
			}
		}

		protected override void ProcessAssembly (AssemblyDefinition assembly)
		{
			if (Annotations.GetAction (assembly) != AssemblyAction.Link)
				return;

			this.assembly = assembly;

			foreach (var type in assembly.MainModule.Types)
				ProcessType (type);
		}

		void ProcessType (TypeDefinition type)
		{
			foreach (var method in type.Methods) {
				if (method.HasBody)
					ProcessMethod (method);
			}

			if (type.HasFields && Annotations.HasSubstitutedInit (type)) {
				AddFieldsInitializations (type);
			}

			foreach (var nested in type.NestedTypes)
				ProcessType (nested);
		}

		void AddFieldsInitializations (TypeDefinition type)
		{
			Instruction ret;
			LinkerILProcessor processor;

			var cctor = type.Methods.FirstOrDefault (MethodDefinitionExtensions.IsStaticConstructor);
			if (cctor == null) {
				type.Attributes |= TypeAttributes.BeforeFieldInit;

				var method = new MethodDefinition (".cctor",
					MethodAttributes.Static | MethodAttributes.Private | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName | MethodAttributes.HideBySig,
					Assembly.MainModule.TypeSystem.Void);

				type.Methods.Add (method);

				processor = method.Body.GetLinkerILProcessor ();
				ret = Instruction.Create (OpCodes.Ret);
				processor.Append (ret);
			} else {
				ret = cctor.Body.Instructions.Last (l => l.OpCode.Code == Code.Ret);
				var body = cctor.Body;
				processor = cctor.Body.GetLinkerILProcessor ();

				for (int i = 0; i < body.Instructions.Count; ++i) {
					var instr = body.Instructions[i];
					if (instr.OpCode.Code != Code.Stsfld)
						continue;

					var field = (FieldReference) instr.Operand;
					if (!Annotations.HasSubstitutedInit (field.Resolve ()))
						continue;

					processor.Replace (instr, Instruction.Create (OpCodes.Pop));
				}
			}

			foreach (var field in type.Fields) {
				if (!Annotations.HasSubstitutedInit (field))
					continue;

				Context.Annotations.TryGetFieldUserValue (field, out object? value);

				var valueInstr = CreateConstantResultInstruction (Context, field.FieldType, value);
				if (valueInstr == null)
					throw new NotImplementedException (field.FieldType.ToString ());

				processor.InsertBefore (ret, valueInstr);
				processor.InsertBefore (ret, Instruction.Create (OpCodes.Stsfld, field));
			}
		}

		void ProcessMethod (MethodDefinition method)
		{
			switch (Annotations.GetAction (method)) {
			case MethodAction.ConvertToStub:
				RewriteBodyToStub (method);
				break;
			case MethodAction.ConvertToThrow:
				RewriteBodyToLinkedAway (method);
				break;
			}
		}

		protected virtual void RewriteBodyToLinkedAway (MethodDefinition method)
		{
			method.ImplAttributes &= ~(MethodImplAttributes.AggressiveInlining | MethodImplAttributes.Synchronized);
			method.ImplAttributes |= MethodImplAttributes.NoInlining;

			method.Body = CreateThrowLinkedAwayBody (method);

			method.ClearDebugInformation ();
		}

		protected virtual void RewriteBodyToStub (MethodDefinition method)
		{
			if (!method.IsIL)
				throw new NotImplementedException ();

			method.Body = CreateStubBody (method);

			method.ClearDebugInformation ();
		}

		MethodBody CreateThrowLinkedAwayBody (MethodDefinition method)
		{
			var body = new MethodBody (method);
			var il = body.GetLinkerILProcessor ();
			MethodReference? ctor;

			// Makes the body verifiable
			if (method.IsConstructor && !method.DeclaringType.IsValueType) {
				ctor = Assembly.MainModule.ImportReference (Context.MarkedKnownMembers.ObjectCtor);

				il.Emit (OpCodes.Ldarg_0);
				il.Emit (OpCodes.Call, ctor);
			}

			// import the method into the current assembly
			ctor = Context.MarkedKnownMembers.NotSupportedExceptionCtorString;
			ctor = Assembly.MainModule.ImportReference (ctor);

			il.Emit (OpCodes.Ldstr, "Linked away");
			il.Emit (OpCodes.Newobj, ctor);
			il.Emit (OpCodes.Throw);

			return body;
		}

		MethodBody CreateStubBody (MethodDefinition method)
		{
			var body = new MethodBody (method);

#pragma warning disable RS0030 // MethodReference.Parameters is banned. This code already works and doesn't need to be changed
			if (method.HasParameters && method.Parameters.Any (l => l.IsOut))
				throw new NotSupportedException ($"Cannot replace body of method '{method.GetDisplayName ()}' because it has an out parameter.");
#pragma warning restore RS0030

			var il = body.GetLinkerILProcessor ();
			if (method.IsInstanceConstructor () && !method.DeclaringType.IsValueType) {
				var baseType = Context.Resolve (method.DeclaringType.BaseType);
				if (baseType is null)
					return body;

				MethodReference base_ctor = baseType.GetDefaultInstanceConstructor (Context);
				if (base_ctor == null)
					throw new NotSupportedException ($"Cannot replace constructor for '{method.DeclaringType}' when no base default constructor exists");

				base_ctor = Assembly.MainModule.ImportReference (base_ctor);

				il.Emit (OpCodes.Ldarg_0);
				il.Emit (OpCodes.Call, base_ctor);
			}

			switch (method.ReturnType.MetadataType) {
			case MetadataType.Void:
				break;
			default:
				var instruction = CreateConstantResultInstruction (Context, method);
				if (instruction != null) {
					il.Append (instruction);
				} else {
					StubComplexBody (method, body, il);
				}
				break;
			}

			il.Emit (OpCodes.Ret);
			return body;
		}

		static void StubComplexBody (MethodDefinition method, MethodBody body, LinkerILProcessor il)
		{
			switch (method.ReturnType.MetadataType) {
			case MetadataType.MVar:
			case MetadataType.ValueType:
				var vd = new VariableDefinition (method.ReturnType);
				body.Variables.Add (vd);
				body.InitLocals = true;

				il.Emit (OpCodes.Ldloca_S, vd);
				il.Emit (OpCodes.Initobj, method.ReturnType);
				il.Emit (OpCodes.Ldloc_0);
				return;
			case MetadataType.Pointer:
			case MetadataType.IntPtr:
			case MetadataType.UIntPtr:
				il.Emit (OpCodes.Ldc_I4_0);
				il.Emit (OpCodes.Conv_I);
				return;
			}

			throw new NotImplementedException (method.FullName);
		}

		public static Instruction? CreateConstantResultInstruction (LinkContext context, MethodDefinition method)
		{
			context.Annotations.TryGetMethodStubValue (method, out object? value);
			return CreateConstantResultInstruction (context, method.ReturnType, value);
		}

		public static Instruction? CreateConstantResultInstruction (LinkContext context, TypeReference inputRtype, object? value = null)
		{
			TypeReference? rtype = inputRtype;
			switch (rtype.MetadataType) {
			case MetadataType.ValueType:
				var definition = context.TryResolve (rtype);
				if (definition?.IsEnum == true) {
					rtype = definition.GetEnumUnderlyingType ();
				}

				break;
			case MetadataType.GenericInstance:
				rtype = context.TryResolve (rtype);
				break;
			}

			if (rtype == null)
				return null;

			switch (rtype.MetadataType) {
			case MetadataType.Boolean:
				if (value is int bintValue && bintValue == 1)
					return Instruction.Create (OpCodes.Ldc_I4_1);

				return Instruction.Create (OpCodes.Ldc_I4_0);

			case MetadataType.String:
				if (value is string svalue)
					return Instruction.Create (OpCodes.Ldstr, svalue);

				return Instruction.Create (OpCodes.Ldnull);

			case MetadataType.Object:
			case MetadataType.Array:
			case MetadataType.Class:
				Debug.Assert (value == null);
				return Instruction.Create (OpCodes.Ldnull);

			case MetadataType.Double:
				if (value is double dvalue)
					return Instruction.Create (OpCodes.Ldc_R8, dvalue);

				Debug.Assert (value == null);
				return Instruction.Create (OpCodes.Ldc_R8, 0.0);

			case MetadataType.Single:
				if (value is float fvalue)
					return Instruction.Create (OpCodes.Ldc_R4, fvalue);

				Debug.Assert (value == null);
				return Instruction.Create (OpCodes.Ldc_R4, 0.0f);

			case MetadataType.Char:
			case MetadataType.Byte:
			case MetadataType.SByte:
			case MetadataType.Int16:
			case MetadataType.UInt16:
			case MetadataType.Int32:
			case MetadataType.UInt32:
				if (value is int intValue)
					return Instruction.Create (OpCodes.Ldc_I4, intValue);

				Debug.Assert (value == null);
				return Instruction.Create (OpCodes.Ldc_I4_0);

			case MetadataType.UInt64:
			case MetadataType.Int64:
				if (value is long longValue)
					return Instruction.Create (OpCodes.Ldc_I8, longValue);

				Debug.Assert (value == null);
				return Instruction.Create (OpCodes.Ldc_I8, 0L);
			}

			return null;
		}
	}
}