This repository was archived by the owner on Jan 27, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Expand file tree
/
Copy pathDnlibUtils.cs
More file actions
476 lines (415 loc) · 15.7 KB
/
DnlibUtils.cs
File metadata and controls
476 lines (415 loc) · 15.7 KB
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
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using dnlib.DotNet;
using dnlib.DotNet.Emit;
using dnlib.IO;
namespace Confuser.Core {
/// <summary>
/// Provides a set of utility methods about dnlib
/// </summary>
public static class DnlibUtils {
/// <summary>
/// Finds all definitions of interest in a module.
/// </summary>
/// <param name="module">The module.</param>
/// <returns>A collection of all required definitions</returns>
public static IEnumerable<IDnlibDef> FindDefinitions(this ModuleDef module) {
yield return module;
foreach (TypeDef type in module.GetTypes()) {
yield return type;
foreach (MethodDef method in type.Methods)
yield return method;
foreach (FieldDef field in type.Fields)
yield return field;
foreach (PropertyDef prop in type.Properties)
yield return prop;
foreach (EventDef evt in type.Events)
yield return evt;
}
}
/// <summary>
/// Finds all definitions of interest in a type.
/// </summary>
/// <param name="typeDef">The type.</param>
/// <returns>A collection of all required definitions</returns>
public static IEnumerable<IDnlibDef> FindDefinitions(this TypeDef typeDef) {
yield return typeDef;
foreach (TypeDef nestedType in typeDef.NestedTypes)
yield return nestedType;
foreach (MethodDef method in typeDef.Methods)
yield return method;
foreach (FieldDef field in typeDef.Fields)
yield return field;
foreach (PropertyDef prop in typeDef.Properties)
yield return prop;
foreach (EventDef evt in typeDef.Events)
yield return evt;
}
/// <summary>
/// Determines whether the specified type is visible outside the containing assembly.
/// </summary>
/// <param name="typeDef">The type.</param>
/// <param name="exeNonPublic">Visibility of executable modules.</param>
/// <returns><c>true</c> if the specified type is visible outside the containing assembly; otherwise, <c>false</c>.</returns>
public static bool IsVisibleOutside(this TypeDef typeDef, bool exeNonPublic = true) {
// Assume executable modules' type is not visible
if (exeNonPublic && (typeDef.Module.Kind == ModuleKind.Windows || typeDef.Module.Kind == ModuleKind.Console))
return false;
do {
if (typeDef.DeclaringType == null)
return typeDef.IsPublic;
if (!typeDef.IsNestedPublic && !typeDef.IsNestedFamily && !typeDef.IsNestedFamilyOrAssembly)
return false;
typeDef = typeDef.DeclaringType;
} while (typeDef != null);
throw new UnreachableException();
}
/// <summary>
/// Determines whether the object has the specified custom attribute.
/// </summary>
/// <param name="obj">The object.</param>
/// <param name="fullName">The full name of the type of custom attribute.</param>
/// <returns><c>true</c> if the specified object has custom attribute; otherwise, <c>false</c>.</returns>
public static bool HasAttribute(this IHasCustomAttribute obj, string fullName) {
return obj.CustomAttributes.Any(attr => attr.TypeFullName == fullName);
}
/// <summary>
/// Determines whether the specified type is COM import.
/// </summary>
/// <param name="type">The type.</param>
/// <returns><c>true</c> if specified type is COM import; otherwise, <c>false</c>.</returns>
public static bool IsComImport(this TypeDef type) {
return type.IsImport ||
type.HasAttribute("System.Runtime.InteropServices.ComImportAttribute") ||
type.HasAttribute("System.Runtime.InteropServices.TypeLibTypeAttribute");
}
/// <summary>
/// Determines whether the specified type is compiler generated.
/// </summary>
/// <param name="type">The type.</param>
/// <returns><c>true</c> if specified type is compiler generated; otherwise, <c>false</c>.</returns>
public static bool IsCompilerGenerated(this TypeDef type) {
return type.HasAttribute("System.Runtime.CompilerServices.CompilerGeneratedAttribute");
}
/// <summary>
/// Determines whether the specified type is a delegate.
/// </summary>
/// <param name="type">The type.</param>
/// <returns><c>true</c> if the specified type is a delegate; otherwise, <c>false</c>.</returns>
public static bool IsDelegate(this TypeDef type) {
if (type.BaseType == null)
return false;
string fullName = type.BaseType.FullName;
return fullName == "System.Delegate" || fullName == "System.MulticastDelegate";
}
/// <summary>
/// Determines whether the specified type is inherited from a base type in corlib.
/// </summary>
/// <param name="type">The type.</param>
/// <param name="baseType">The full name of base type.</param>
/// <returns><c>true</c> if the specified type is inherited from a base type; otherwise, <c>false</c>.</returns>
public static bool InheritsFromCorlib(this TypeDef type, string baseType) {
if (type.BaseType == null)
return false;
TypeDef bas = type;
do {
bas = bas.BaseType.ResolveTypeDefThrow();
if (bas.ReflectionFullName == baseType)
return true;
} while (bas.BaseType != null && bas.BaseType.DefinitionAssembly.IsCorLib());
return false;
}
/// <summary>
/// Determines whether the specified type is inherited from a base type.
/// </summary>
/// <param name="type">The type.</param>
/// <param name="baseType">The full name of base type.</param>
/// <returns><c>true</c> if the specified type is inherited from a base type; otherwise, <c>false</c>.</returns>
public static bool InheritsFrom(this TypeDef type, string baseType) {
if (type.BaseType == null)
return false;
TypeDef bas = type;
do {
bas = bas.BaseType.ResolveTypeDefThrow();
if (bas.ReflectionFullName == baseType)
return true;
} while (bas.BaseType != null);
return false;
}
/// <summary>
/// Determines whether the specified type implements the specified interface.
/// </summary>
/// <param name="type">The type.</param>
/// <param name="fullName">The full name of the type of interface.</param>
/// <returns><c>true</c> if the specified type implements the interface; otherwise, <c>false</c>.</returns>
public static bool Implements(this TypeDef type, string fullName) {
do {
foreach (InterfaceImpl iface in type.Interfaces) {
if (iface.Interface.ReflectionFullName == fullName)
return true;
}
if (type.BaseType == null)
return false;
type = type.BaseType.ResolveTypeDefThrow();
} while (type != null);
throw new UnreachableException();
}
/// <summary>
/// Resolves the method.
/// </summary>
/// <param name="method">The method to resolve.</param>
/// <returns>A <see cref="MethodDef" /> instance.</returns>
/// <exception cref="MemberRefResolveException">The method couldn't be resolved.</exception>
public static MethodDef ResolveThrow(this IMethod method) {
var def = method as MethodDef;
if (def != null)
return def;
var spec = method as MethodSpec;
if (spec != null)
return spec.Method.ResolveThrow();
return ((MemberRef)method).ResolveMethodThrow();
}
/// <summary>
/// Resolves the field.
/// </summary>
/// <param name="field">The field to resolve.</param>
/// <returns>A <see cref="FieldDef" /> instance.</returns>
/// <exception cref="MemberRefResolveException">The method couldn't be resolved.</exception>
public static FieldDef ResolveThrow(this IField field) {
var def = field as FieldDef;
if (def != null)
return def;
return ((MemberRef)field).ResolveFieldThrow();
}
/// <summary>
/// Find the basic type reference.
/// </summary>
/// <param name="typeSig">The type signature to get the basic type.</param>
/// <returns>A <see cref="ITypeDefOrRef" /> instance, or null if the typeSig cannot be resolved to basic type.</returns>
public static ITypeDefOrRef ToBasicTypeDefOrRef(this TypeSig typeSig) {
while (typeSig.Next != null)
typeSig = typeSig.Next;
if (typeSig is GenericInstSig)
return ((GenericInstSig)typeSig).GenericType.TypeDefOrRef;
if (typeSig is TypeDefOrRefSig)
return ((TypeDefOrRefSig)typeSig).TypeDefOrRef;
return null;
}
/// <summary>
/// Find the type references within the specified type signature.
/// </summary>
/// <param name="typeSig">The type signature to find the type references.</param>
/// <returns>A list of <see cref="ITypeDefOrRef" /> instance.</returns>
public static IList<ITypeDefOrRef> FindTypeRefs(this TypeSig typeSig) {
var ret = new List<ITypeDefOrRef>();
FindTypeRefsInternal(typeSig, ret);
return ret;
}
static void FindTypeRefsInternal(TypeSig typeSig, IList<ITypeDefOrRef> ret) {
while (typeSig.Next != null) {
if (typeSig is ModifierSig)
ret.Add(((ModifierSig)typeSig).Modifier);
typeSig = typeSig.Next;
}
if (typeSig is GenericInstSig) {
var genInst = (GenericInstSig)typeSig;
ret.Add(genInst.GenericType.TypeDefOrRef);
foreach (TypeSig genArg in genInst.GenericArguments)
FindTypeRefsInternal(genArg, ret);
}
else if (typeSig is TypeDefOrRefSig) {
var type = ((TypeDefOrRefSig)typeSig).TypeDefOrRef;
while (type != null) {
ret.Add(type);
type = type.DeclaringType;
}
}
}
/// <summary>
/// Determines whether the specified property is public.
/// </summary>
/// <param name="property">The property.</param>
/// <returns><c>true</c> if the specified property is public; otherwise, <c>false</c>.</returns>
public static bool IsPublic (this PropertyDef property)
{
return property.AllMethods ().Any (method => method.IsPublic);
}
/// <summary>
/// Determines whether the specified property is static.
/// </summary>
/// <param name="property">The property.</param>
/// <returns><c>true</c> if the specified property is static; otherwise, <c>false</c>.</returns>
public static bool IsStatic (this PropertyDef property)
{
return property.AllMethods ().Any (method => method.IsStatic);
}
/// <summary>
/// Determines whether the specified event is public.
/// </summary>
/// <param name="evt">The event.</param>
/// <returns><c>true</c> if the specified event is public; otherwise, <c>false</c>.</returns>
public static bool IsPublic (this EventDef evt)
{
return evt.AllMethods ().Any (method => method.IsPublic);
}
/// <summary>
/// Determines whether the specified event is static.
/// </summary>
/// <param name="evt">The event.</param>
/// <returns><c>true</c> if the specified event is static; otherwise, <c>false</c>.</returns>
public static bool IsStatic (this EventDef evt)
{
return evt.AllMethods ().Any (method => method.IsStatic);
}
/// <summary>
/// Determines whether the specified method is an explictly implemented interface member.
/// </summary>
/// <param name="method">The method.</param>
/// <returns><c>true</c> if the specified method is an explictly implemented interface member; otherwise, <c>false</c>.</returns>
public static bool IsExplicitlyImplementedInterfaceMember (this MethodDef method)
{
return method.IsFinal && method.IsPrivate;
}
/// <summary>
/// Determines whether the specified property is an explictly implemented interface member.
/// </summary>
/// <param name="property">The method.</param>
/// <returns><c>true</c> if the specified property is an explictly implemented interface member; otherwise, <c>false</c>.</returns>
public static bool IsExplicitlyImplementedInterfaceMember (this PropertyDef property)
{
return property.AllMethods ().Any (IsExplicitlyImplementedInterfaceMember);
}
/// <summary>
/// Determines whether the specified event is an explictly implemented interface member.
/// </summary>
/// <param name="evt">The event.</param>
/// <returns><c>true</c> if the specified eve is an explictly implemented interface member; otherwise, <c>false</c>.</returns>
public static bool IsExplicitlyImplementedInterfaceMember (this EventDef evt)
{
return evt.AllMethods ().Any (IsExplicitlyImplementedInterfaceMember);
}
private static IEnumerable<MethodDef> AllMethods (this EventDef evt)
{
return new [] { evt.AddMethod, evt.RemoveMethod, evt.InvokeMethod }
.Concat (evt.OtherMethods)
.Where (m => m != null);
}
private static IEnumerable<MethodDef> AllMethods (this PropertyDef property)
{
return new [] { property.GetMethod, property.SetMethod }
.Concat (property.OtherMethods)
.Where (m => m != null);
}
/// <summary>
/// Replaces the specified instruction reference with another instruction.
/// </summary>
/// <param name="body">The method body.</param>
/// <param name="target">The instruction to replace.</param>
/// <param name="newInstr">The new instruction.</param>
public static void ReplaceReference(this CilBody body, Instruction target, Instruction newInstr) {
foreach (ExceptionHandler eh in body.ExceptionHandlers) {
if (eh.TryStart == target)
eh.TryStart = newInstr;
if (eh.TryEnd == target)
eh.TryEnd = newInstr;
if (eh.HandlerStart == target)
eh.HandlerStart = newInstr;
if (eh.HandlerEnd == target)
eh.HandlerEnd = newInstr;
}
foreach (Instruction instr in body.Instructions) {
if (instr.Operand == target)
instr.Operand = newInstr;
else if (instr.Operand is Instruction[]) {
var targets = (Instruction[])instr.Operand;
for (int i = 0; i < targets.Length; i++)
if (targets[i] == target)
targets[i] = newInstr;
}
}
}
/// <summary>
/// Determines whether the specified method is array accessors.
/// </summary>
/// <param name="method">The method.</param>
/// <returns><c>true</c> if the specified method is array accessors; otherwise, <c>false</c>.</returns>
public static bool IsArrayAccessors(this IMethod method) {
var declType = method.DeclaringType.ToTypeSig();
if (declType is GenericInstSig)
declType = ((GenericInstSig)declType).GenericType;
if (declType.IsArray) {
return method.Name == "Get" || method.Name == "Set" || method.Name == "Address";
}
return false;
}
}
/// <summary>
/// <see cref="Stream" /> wrapper of <see cref="IImageStream" />.
/// </summary>
public class ImageStream : Stream {
/// <summary>
/// Initializes a new instance of the <see cref="ImageStream" /> class.
/// </summary>
/// <param name="baseStream">The base stream.</param>
public ImageStream(IImageStream baseStream) {
BaseStream = baseStream;
}
/// <summary>
/// Gets the base stream of this instance.
/// </summary>
/// <value>The base stream.</value>
public IImageStream BaseStream { get; private set; }
/// <inheritdoc />
public override bool CanRead {
get { return true; }
}
/// <inheritdoc />
public override bool CanSeek {
get { return true; }
}
/// <inheritdoc />
public override bool CanWrite {
get { return false; }
}
/// <inheritdoc />
public override long Length {
get { return BaseStream.Length; }
}
/// <inheritdoc />
public override long Position {
get { return BaseStream.Position; }
set { BaseStream.Position = value; }
}
/// <inheritdoc />
public override void Flush() { }
/// <inheritdoc />
public override int Read(byte[] buffer, int offset, int count) {
return BaseStream.Read(buffer, offset, count);
}
/// <inheritdoc />
public override long Seek(long offset, SeekOrigin origin) {
switch (origin) {
case SeekOrigin.Begin:
BaseStream.Position = offset;
break;
case SeekOrigin.Current:
BaseStream.Position += offset;
break;
case SeekOrigin.End:
BaseStream.Position = BaseStream.Length + offset;
break;
}
return BaseStream.Position;
}
/// <inheritdoc />
public override void SetLength(long value) {
throw new NotSupportedException();
}
/// <inheritdoc />
public override void Write(byte[] buffer, int offset, int count) {
throw new NotSupportedException();
}
}
}