-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathProgram.cs
306 lines (237 loc) · 16.8 KB
/
Program.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
using Mono.Cecil;
using Mono.Cecil.Cil;
using Mono.Collections.Generic;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ilgen_convert {
class Program {
public static ModuleDefinition Module = null;
public static Dictionary<string, MethodReference> MethodReferences = new Dictionary<string, MethodReference>();
public static Dictionary<string, TypeReference> TypeReferences = new Dictionary<string, TypeReference>();
static void Main(string[] args) {
string assembly = "test.exe";
Module = ModuleDefinition.ReadModule(assembly);
MethodReferences.Add("FinallyBlock", Module.ImportReference(typeof(System.Reflection.Emit.ILGenerator).GetMethod("BeginFinallyBlock", new Type[0])));
MethodReferences.Add("CatchBlock", Module.ImportReference(typeof(System.Reflection.Emit.ILGenerator).GetMethod("BeginCatchBlock", new Type[] { typeof(Type) })));
MethodReferences.Add("TryEnd", Module.ImportReference(typeof(System.Reflection.Emit.ILGenerator).GetMethod("EndExceptionBlock", new Type[0])));
MethodReferences.Add("TryStart", Module.ImportReference(typeof(System.Reflection.Emit.ILGenerator).GetMethod("BeginExceptionBlock", new Type[0])));
MethodReferences.Add("DeclareLocal", Module.ImportReference(typeof(System.Reflection.Emit.ILGenerator).GetMethod("DeclareLocal", new Type[] { typeof(Type) })));
MethodReferences.Add("MarkLabel", Module.ImportReference(typeof(System.Reflection.Emit.ILGenerator).GetMethod("MarkLabel", new Type[] { typeof(System.Reflection.Emit.Label) })));
MethodReferences.Add("DefineLabel", Module.ImportReference(typeof(System.Reflection.Emit.ILGenerator).GetMethod("DefineLabel")));
MethodReferences.Add("GetMethodInfo", Module.ImportReference(typeof(Type).GetMethod("GetMethod", new Type[] { typeof(string), typeof(System.Reflection.BindingFlags), typeof(System.Reflection.Binder), typeof(Type[]), typeof(System.Reflection.ParameterModifier[]) })));
MethodReferences.Add("GetMethodInfoTypes", Module.ImportReference(typeof(Type).GetMethod("GetMethod", new Type[] { typeof(string), typeof(Type[]) })));
MethodReferences.Add("GetTypeFromHandle", Module.ImportReference(typeof(System.Type).GetMethod("GetTypeFromHandle")));
MethodReferences.Add("DynamicMethodConstructor", Module.ImportReference(typeof(System.Reflection.Emit.DynamicMethod).GetConstructor(new Type[] { typeof(string), typeof(System.Reflection.MethodAttributes), typeof(System.Reflection.CallingConventions), typeof(Type), typeof(Type[]), typeof(Type), typeof(bool) })));
MethodReferences.Add("GetILGenerator", Module.ImportReference(typeof(System.Reflection.Emit.DynamicMethod).GetMethod("GetILGenerator", new Type[] { })));
MethodReferences.Add("GetFieldInfo", Module.ImportReference(typeof(Type).GetMethod("GetField", new Type[] { typeof(string), typeof(System.Reflection.BindingFlags) })));
MethodReferences.Add("GetConstructorInfoTypes", Module.ImportReference(typeof(Type).GetMethod("GetConstructor", new Type[] { typeof(Type[]) })));
MethodReferences.Add("Invoker", Module.ImportReference(typeof(System.Reflection.MethodBase).GetMethod("Invoke", new Type[] { typeof(object), typeof(object[]) })));
MethodReferences.Add("EmitCall", Module.ImportReference(typeof(System.Reflection.Emit.ILGenerator).GetMethod("EmitCall", new Type[] { typeof(System.Reflection.Emit.OpCode), typeof(System.Reflection.MethodInfo), typeof(Type[]) })));
TypeReferences.Add("Type", Module.ImportReference(typeof(Type)));
TypeReferences.Add("Label", Module.ImportReference(typeof(System.Reflection.Emit.Label)));
TypeReferences.Add("LocalBuilder", Module.ImportReference(typeof(System.Reflection.Emit.LocalBuilder)));
TypeReferences.Add("ILGenerator", Module.ImportReference(typeof(System.Reflection.Emit.ILGenerator)));
TypeReferences.Add("DynamicMethod", Module.ImportReference(typeof(System.Reflection.Emit.DynamicMethod)));
foreach (TypeDefinition type in Module.Types) {
foreach (MethodDefinition method in type.Methods) {
if (method.Name == ".ctor" || method.Name == ".cctor" || !method.HasBody)
continue;
Console.WriteLine(" ===== " + method.FullName + " ===== ");
method.Body = GenerateBody(method);
Console.WriteLine("\n");
// make sure the class is public so it can be accessed when the DynamicMethod is invoked
type.IsNotPublic = false;
type.IsPublic = true;
}
}
Console.ReadKey();
Module.Write("test_dynamic.exe");
}
private static MethodBody GenerateBody(MethodDefinition method) {
MethodBody body = new MethodBody(method);
ILProcessor processor = body.GetILProcessor();
Dictionary<Instruction, VariableDefinition> Branches = new Dictionary<Instruction, VariableDefinition>();
Dictionary<int, VariableDefinition> Locals = new Dictionary<int, VariableDefinition>();
// create an instance of DynamicMethod
processor.CreateDynamicMethod(method);
VariableDefinition dynamicMethod = new VariableDefinition(TypeReferences["DynamicMethod"]);
processor.Body.Variables.Add(dynamicMethod);
processor.Emit(OpCodes.Stloc, dynamicMethod);
processor.Emit(OpCodes.Ldloc, dynamicMethod);
// generate an ILGenerator object from the DynamicMethod
VariableDefinition ilgenerator = new VariableDefinition(TypeReferences["ILGenerator"]);
processor.Body.Variables.Add(ilgenerator);
processor.Emit(OpCodes.Callvirt, MethodReferences["GetILGenerator"]);
processor.Emit(OpCodes.Stloc, ilgenerator);
// pre-emission phase (runs after DynamicMethod and ILGenerator are instantiated)
foreach (Instruction instruction in method.Body.Instructions) {
// output instructions & operand types to console
Console.Write(instruction.Offset + ": " + instruction.OpCode.Name);
Console.Write(instruction.Operand == null ? "\n" : " -> " + instruction.Operand.GetType() + "\n");
// define branch variables ('Label' objects)
if (instruction.Operand is Instruction) {
// ignore leave.s branching, since it's used for exception handling
if (instruction.OpCode == OpCodes.Leave_S)
continue;
Instruction target = instruction.Operand as Instruction;
if (Branches.ContainsKey(target))
continue;
VariableDefinition label = new VariableDefinition(TypeReferences["Label"]);
processor.Body.Variables.Add(label);
processor.Emit(OpCodes.Ldloc, ilgenerator);
processor.Emit(OpCodes.Callvirt, MethodReferences["DefineLabel"]);
processor.Emit(OpCodes.Stloc, label);
Branches.Add(target, label);
}
}
// define local variables
for (int vI = 0; vI < method.Body.Variables.Count; vI++) {
VariableDefinition local = new VariableDefinition(TypeReferences["LocalBuilder"]);
processor.Body.Variables.Add(local);
TypeReference variableType = method.Body.Variables[vI].VariableType;
processor.Emit(OpCodes.Ldloc, ilgenerator);
processor.EmitType(variableType);
processor.Emit(OpCodes.Callvirt, MethodReferences["DeclareLocal"]);
processor.Emit(OpCodes.Stloc, local);
Locals.Add(vI, local);
}
// iterate through instructions, writer ILGenerator.Emit calls
for (int iI = 0; iI < method.Body.Instructions.Count; iI++) {
// the current instruction
Instruction instruction = method.Body.Instructions[iI];
foreach (ExceptionHandler exH in method.Body.ExceptionHandlers) {
if (exH.TryStart == instruction) {
processor.Emit(OpCodes.Ldloc, ilgenerator);
processor.Emit(OpCodes.Callvirt, MethodReferences["TryStart"]);
processor.Emit(OpCodes.Pop); // pop TryStart return value from eval stack
} else if (exH.HandlerStart == instruction) {
processor.Emit(OpCodes.Ldloc, ilgenerator);
if (exH.HandlerType == ExceptionHandlerType.Catch) {
processor.EmitType(exH.CatchType);
processor.Emit(OpCodes.Callvirt, MethodReferences["CatchBlock"]);
} else if (exH.HandlerType == ExceptionHandlerType.Finally) {
processor.Emit(OpCodes.Callvirt, MethodReferences["FinallyBlock"]);
}
} else if (exH.TryEnd == instruction || exH.HandlerEnd == instruction) {
processor.Emit(OpCodes.Ldloc, ilgenerator);
processor.Emit(OpCodes.Callvirt, MethodReferences["TryEnd"]);
}
}
// ignore leave.s branching, since it's used for exception handling
if (instruction.OpCode == OpCodes.Leave_S)
continue;
// mark a label for this instruction, if we have a branch going here
if (Branches.ContainsKey(instruction)) {
processor.Emit(OpCodes.Ldloc, ilgenerator);
processor.EmitMarkLabel(Branches[instruction]);
}
// load ilgenerator object into memory to make Emit call from it
processor.Emit(OpCodes.Ldloc, ilgenerator);
// determine index of stloc/ldloc call based on OpCode
int stlocIndex = instruction.GetStlocIndex();
int ldlocIndex = instruction.GetLdlocIndex();
// modify stloc/ldloc implementation to use LocalBuilder
if (stlocIndex > -1 || ldlocIndex > -1) {
// new determine new OpCode & local variable index
bool isStloc = stlocIndex > -1;
instruction.OpCode = isStloc ? OpCodes.Stloc : OpCodes.Ldloc;
int localIndex = isStloc ? stlocIndex : ldlocIndex;
// load OpCode (param #1) and LocalBuilder object (param #2) onto eval stack
// make ILGenerator.Emit call with these 2 params to fix local variables in ILGenerator methods
processor.Emit(OpCodes.Ldsfld, Utils.GetReflectedOpCode(instruction));
processor.Emit(OpCodes.Ldloc, Locals[localIndex]);
processor.Emit(OpCodes.Callvirt, Utils.GetILGeneratorEmitter(typeof(System.Reflection.Emit.LocalBuilder)));
continue;
}
// load the OpCode to be emitted onto the eval stack (param #1)
processor.Emit(OpCodes.Ldsfld, Utils.GetReflectedOpCode(instruction));
// type of ILGenerator.Emit function to invoke.
// if null, Emit will be invoked without an operand.
// all operands must be handled in the following if/else blocks
Type EmitType = null;
// handle operands (note: each operand needs to be handled differently)
// this will be used in the ILGenerator.Emit call (param #2)
if (instruction.Operand != null) {
if (instruction.Operand is FieldDefinition) {
FieldDefinition fieldDefinition = instruction.Operand as FieldDefinition;
processor.EmitFieldGetter(fieldDefinition);
EmitType = typeof(System.Reflection.FieldInfo);
} else if (instruction.Operand is MethodDefinition) {
MethodDefinition methodDefinition = instruction.Operand as MethodDefinition;
processor.EmitMethodGetter(methodDefinition);
EmitType = methodDefinition.IsConstructor ? typeof(System.Reflection.ConstructorInfo) : typeof(System.Reflection.MethodInfo);
} else if (instruction.Operand is MethodReference) {
MethodReference methodReference = instruction.Operand as MethodReference;
processor.EmitMethodGetter(methodReference);
EmitType = typeof(System.Reflection.MethodInfo);
} else if (instruction.Operand.GetType() == typeof(sbyte)) {
sbyte value = Convert.ToSByte(instruction.Operand);
processor.Emit(OpCodes.Ldc_I4_S, value);
EmitType = typeof(sbyte);
} else if (instruction.Operand.GetType() == typeof(string)) {
string value = Convert.ToString(instruction.Operand);
processor.Emit(OpCodes.Ldstr, value);
EmitType = typeof(string);
} else if (instruction.Operand.GetType() == typeof(int)) {
int value = Convert.ToInt32(instruction.Operand);
processor.Emit(OpCodes.Ldc_I4, value);
EmitType = typeof(int);
} else if (instruction.Operand.GetType() == typeof(float)) {
float value = Convert.ToSingle(instruction.Operand);
processor.Emit(OpCodes.Ldc_R4, value);
EmitType = typeof(float);
} else if (instruction.Operand is Instruction) {
Instruction targetInstruction = instruction.Operand as Instruction;
processor.Emit(OpCodes.Ldloc, Branches[targetInstruction]);
EmitType = typeof(System.Reflection.Emit.Label);
} else if (instruction.Operand is TypeReference) {
TypeReference typeReference = instruction.Operand as TypeReference;
processor.EmitType(typeReference);
EmitType = typeof(Type);
} else {
Console.WriteLine("UNHANDLED OPERAND: opcode = " + instruction.OpCode.Name + ", type = " + instruction.Operand.GetType());
}
}
// if we're emitting a 'call' or 'callvirt' opcode, use the ILGenerator.EmitCall function
if (instruction.OpCode == OpCodes.Call || instruction.OpCode == OpCodes.Callvirt) {
// null = 3rd param in EmitCall (1st was the opcode, 2nd was the MethodInfo)
processor.Emit(OpCodes.Ldnull);
processor.Emit(OpCodes.Callvirt, MethodReferences["EmitCall"]);
continue;
}
// call the ILGenerator.Emit func
// if EmitType is null, second parameter (operand) is ignored
processor.Emit(OpCodes.Callvirt, Utils.GetILGeneratorEmitter(EmitType));
}
// load the DynamicMethod object back onto the stack
processor.Emit(OpCodes.Ldloc, dynamicMethod);
// object parameter in DynamicMethod.Invoke, should always be null (param #1)
processor.Emit(OpCodes.Ldnull);
// create an array of objects to hold parameters to send to DynamicMethod.Invoke (param #2)
processor.Emit(OpCodes.Ldc_I4_S, Convert.ToSByte(method.Parameters.Count));
processor.Emit(OpCodes.Newarr, Module.TypeSystem.Object);
// load parameters into the created array
for (int pI = 0; pI < method.Parameters.Count; pI++) {
ParameterDefinition parameter = method.Parameters[pI];
processor.Emit(OpCodes.Dup);
processor.Emit(OpCodes.Ldc_I4_S, Convert.ToSByte(pI));
processor.Emit(OpCodes.Ldarg_S, parameter);
processor.Emit(OpCodes.Box, parameter.ParameterType);
processor.Emit(OpCodes.Stelem_Ref);
}
// call the invoker
processor.Emit(OpCodes.Callvirt, MethodReferences["Invoker"]);
// cast the returned object to the return type
if (method.ReturnType != Module.TypeSystem.Void)
processor.Emit(OpCodes.Unbox_Any, method.ReturnType);
else
processor.Emit(OpCodes.Pop);
// return the remaining value on the stack (result of dynamic method)
processor.Emit(OpCodes.Ret);
return body;
}
}
}