forked from kzu/InjectModuleInitializer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Injector.cs
214 lines (189 loc) · 7.73 KB
/
Injector.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
/*
InjectModuleInitializer
Command line program to inject a module initializer into a .NET assembly.
Copyright (C) 2009-2016 Einar Egilsson
http://einaregilsson.com/module-initializers-in-csharp/
This program is licensed under the MIT license: http://opensource.org/licenses/MIT
*/
using System;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using Mono.Cecil;
using Mono.Cecil.Cil;
using Mono.Cecil.Pdb;
using Mono.Collections.Generic;
using MethodAttributes = Mono.Cecil.MethodAttributes;
namespace EinarEgilsson.Utilities.InjectModuleInitializer
{
public class InjectionException : Exception
{
public InjectionException(string msg) : base(msg) { }
}
internal class Injector
{
public const string DefaultInitializerClassName = "ModuleInitializer";
public const string DefaultInitializerMethodName = "Run";
static Injector()
{
AppDomain.CurrentDomain.AssemblyResolve += LoadEmbeddedAssembly;
}
static Assembly LoadEmbeddedAssembly(object sender, ResolveEventArgs args)
{
string name = new AssemblyName(args.Name).Name;
string resourceName = typeof(Injector).Namespace + ".lib." + name + ".dll";
Stream stream = typeof(Injector).Assembly.GetManifestResourceStream(resourceName);
if (stream == null) {
return null;
}
using (stream) {
byte[] buf = new byte[stream.Length];
stream.Read(buf,0, buf.Length);
return System.Reflection.Assembly.Load(buf);
}
}
private AssemblyDefinition Assembly { get; set; }
private string PdbFile(string assemblyFile)
{
Debug.Assert(assemblyFile != null);
string path = Path.ChangeExtension(assemblyFile, ".pdb");
if (File.Exists(path))
{
return path;
}
return null;
}
public void Inject(string assemblyFile, string moduleInitializer=null, string keyfile=null)
{
try
{
if (!File.Exists(assemblyFile))
{
throw new InjectionException(Errors.AssemblyDoesNotExist(assemblyFile));
}
if (keyfile != null && !File.Exists(keyfile))
{
throw new InjectionException(Errors.KeyFileDoesNotExist(keyfile));
}
ReadAssembly(assemblyFile);
MethodReference callee = GetCalleeMethod(moduleInitializer);
InjectInitializer(callee);
WriteAssembly(assemblyFile, keyfile);
}
catch (Exception ex)
{
throw new InjectionException(ex.Message);
}
}
private void InjectInitializer(MethodReference callee)
{
Debug.Assert(Assembly != null);
TypeReference voidRef = Assembly.MainModule.Import(callee.ReturnType);
const MethodAttributes attributes = MethodAttributes.Static
| MethodAttributes.SpecialName
| MethodAttributes.RTSpecialName;
var cctor = new MethodDefinition(".cctor", attributes, voidRef);
ILProcessor il = cctor.Body.GetILProcessor();
il.Append(il.Create(OpCodes.Call, callee));
il.Append(il.Create(OpCodes.Ret));
TypeDefinition moduleClass = Find(Assembly.MainModule.Types, t => t.Name == "<Module>");
moduleClass.Methods.Add(cctor);
Debug.Assert(moduleClass != null, "Found no module class!");
}
private void WriteAssembly(string assemblyFile, string keyfile)
{
Debug.Assert(Assembly != null);
var writeParams = new WriterParameters();
if (PdbFile(assemblyFile) != null)
{
writeParams.WriteSymbols = true;
writeParams.SymbolWriterProvider = new PdbWriterProvider();
}
if (keyfile != null)
{
writeParams.StrongNameKeyPair = new StrongNameKeyPair(File.ReadAllBytes(keyfile));
}
Assembly.Write(assemblyFile, writeParams);
}
private void ReadAssembly(string assemblyFile)
{
Debug.Assert(Assembly == null);
var resolver = new DefaultAssemblyResolver();
resolver.AddSearchDirectory(Path.GetDirectoryName(assemblyFile));
var readParams = new ReaderParameters(ReadingMode.Immediate)
{
AssemblyResolver = resolver
};
if (PdbFile(assemblyFile) != null)
{
readParams.ReadSymbols = true;
readParams.SymbolReaderProvider = new PdbReaderProvider();
}
Assembly = AssemblyDefinition.ReadAssembly(assemblyFile, readParams);
}
private MethodReference GetCalleeMethod(string moduleInitializer)
{
Debug.Assert(Assembly != null);
ModuleDefinition module = Assembly.MainModule;
string methodName;
TypeDefinition moduleInitializerClass;
if (string.IsNullOrEmpty(moduleInitializer))
{
methodName = DefaultInitializerMethodName;
moduleInitializerClass = Find(module.Types, t => t.Name == DefaultInitializerClassName);
if (moduleInitializerClass == null)
{
throw new InjectionException(Errors.NoModuleInitializerTypeFound());
}
}
else
{
if (!moduleInitializer.Contains("::"))
{
throw new InjectionException(Errors.InvalidFormatForModuleInitializer());
}
string typeName = moduleInitializer.Substring(0, moduleInitializer.IndexOf("::"));
methodName = moduleInitializer.Substring(typeName.Length + 2);
moduleInitializerClass = Find(module.Types, t => t.FullName == typeName);
if (moduleInitializerClass == null)
{
throw new InjectionException(Errors.TypeNameDoesNotExist(typeName));
}
}
MethodDefinition callee = Find(moduleInitializerClass.Methods, m => m.Name == methodName);
if (callee == null)
{
throw new InjectionException(Errors.MethodNameDoesNotExist(moduleInitializerClass.FullName, methodName));
}
if (callee.Parameters.Count > 0)
{
throw new InjectionException(Errors.ModuleInitializerMayNotHaveParameters());
}
if (callee.IsPrivate || callee.IsFamily)
{
throw new InjectionException(Errors.ModuleInitializerMayNotBePrivate());
}
if (!callee.ReturnType.FullName.Equals(typeof(void).FullName)) //Don't compare the types themselves, they might be from different CLR versions.
{
throw new InjectionException(Errors.ModuleInitializerMustBeVoid());
}
if (!callee.IsStatic)
{
throw new InjectionException(Errors.ModuleInitializerMustBeStatic());
}
return callee;
}
//No LINQ, since we want to target 2.0
private static T Find<T>(Collection<T> objects, Predicate<T> condition) where T:class
{
foreach (T obj in objects)
{
if (condition(obj))
{
return obj;
}
}
return null;
}
}
}