forked from anydream/il2cpp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHelper.cs
More file actions
716 lines (634 loc) · 16.8 KB
/
Helper.cs
File metadata and controls
716 lines (634 loc) · 16.8 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
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using dnlib.DotNet;
using dnlib.Threading;
namespace il2cpp
{
// 泛型签名替换器
internal interface IGenericReplacer
{
TypeSig Replace(GenericVar genVarSig);
TypeSig Replace(GenericMVar genMVarSig);
}
internal class GenericReplacer : IGenericReplacer
{
public readonly TypeX OwnerType;
public readonly MethodX OwnerMethod;
public GenericReplacer(TypeX ownerTyX, MethodX ownerMetX)
{
OwnerType = ownerTyX;
OwnerMethod = ownerMetX;
}
public TypeSig Replace(GenericVar genVarSig)
{
if (genVarSig.OwnerType == OwnerType.Def)
return OwnerType.GenArgs[(int)genVarSig.Number];
return null;
}
public TypeSig Replace(GenericMVar genMVarSig)
{
if (genMVarSig.OwnerMethod == OwnerMethod.Def)
return OwnerMethod.GenArgs[(int)genMVarSig.Number];
return null;
}
}
internal class TypeDefGenReplacer : IGenericReplacer
{
public readonly TypeDef OwnerType;
public readonly IList<TypeSig> TypeGenArgs;
public TypeDefGenReplacer(TypeDef ownerTyDef, IList<TypeSig> tyGenArgs)
{
OwnerType = ownerTyDef;
TypeGenArgs = tyGenArgs;
}
public TypeSig Replace(GenericVar genVarSig)
{
if (genVarSig.OwnerType == OwnerType)
return TypeGenArgs[(int)genVarSig.Number];
return null;
}
public TypeSig Replace(GenericMVar genMVarSig)
{
return null;
}
}
// 辅助扩展方法
internal static class Helper
{
public static bool IsCollectionValid<T>(this ICollection<T> co)
{
return co != null && co.Count > 0;
}
public static TValue GetOrCreate<TKey, TValue>(
this IDictionary<TKey, TValue> dict,
TKey key,
Func<TValue> creator)
{
if (dict.TryGetValue(key, out TValue val))
return val;
val = creator();
dict.Add(key, val);
return val;
}
public static List<T> SortStable<T>(this List<T> ary, Comparison<T> comp)
{
List<int> idxAry = new List<int>();
for (int i = 0; i < ary.Count; ++i)
idxAry.Add(i);
idxAry.Sort((ilhs, irhs) =>
{
int res = comp(ary[ilhs], ary[irhs]);
if (res == 0)
return ilhs.CompareTo(irhs);
return res;
});
List<T> result = new List<T>();
foreach (int idx in idxAry)
result.Add(ary[idx]);
return result;
}
// 替换类型中的泛型签名
public static TypeSig ReplaceGenericSig(TypeSig tySig, IGenericReplacer replacer)
{
if (replacer == null || !IsReplaceNeeded(tySig))
return tySig;
return ReplaceGenericSigImpl(tySig, replacer);
}
private static TypeSig ReplaceGenericSigImpl(TypeSig tySig, IGenericReplacer replacer)
{
if (tySig == null)
return null;
switch (tySig.ElementType)
{
case ElementType.Class:
case ElementType.ValueType:
case ElementType.TypedByRef:
return tySig;
case ElementType.Ptr:
return new PtrSig(ReplaceGenericSigImpl(tySig.Next, replacer));
case ElementType.ByRef:
return new ByRefSig(ReplaceGenericSigImpl(tySig.Next, replacer));
case ElementType.Pinned:
return new PinnedSig(ReplaceGenericSigImpl(tySig.Next, replacer));
case ElementType.SZArray:
return new SZArraySig(ReplaceGenericSigImpl(tySig.Next, replacer));
case ElementType.Array:
{
ArraySig arySig = (ArraySig)tySig;
return new ArraySig(ReplaceGenericSigImpl(arySig.Next, replacer),
arySig.Rank,
arySig.Sizes,
arySig.LowerBounds);
}
case ElementType.CModReqd:
{
CModReqdSig modreqdSig = (CModReqdSig)tySig;
return new CModReqdSig(modreqdSig.Modifier, ReplaceGenericSigImpl(modreqdSig.Next, replacer));
}
case ElementType.CModOpt:
{
CModOptSig modoptSig = (CModOptSig)tySig;
return new CModOptSig(modoptSig.Modifier, ReplaceGenericSigImpl(modoptSig.Next, replacer));
}
case ElementType.GenericInst:
{
GenericInstSig genInstSig = (GenericInstSig)tySig;
return new GenericInstSig(genInstSig.GenericType, ReplaceGenericSigListImpl(genInstSig.GenericArguments, replacer));
}
case ElementType.Var:
{
GenericVar genVarSig = (GenericVar)tySig;
TypeSig result = replacer.Replace(genVarSig);
if (result != null)
return result;
return genVarSig;
}
case ElementType.MVar:
{
GenericMVar genMVarSig = (GenericMVar)tySig;
TypeSig result = replacer.Replace(genMVarSig);
if (result != null)
return result;
return genMVarSig;
}
default:
if (tySig is CorLibTypeSig)
return tySig;
throw new NotSupportedException();
}
}
// 替换类型签名列表
public static IList<TypeSig> ReplaceGenericSigList(IList<TypeSig> tySigList, IGenericReplacer replacer)
{
return tySigList?.Select(tySig => ReplaceGenericSig(tySig, replacer)).ToList();
}
private static IList<TypeSig> ReplaceGenericSigListImpl(IList<TypeSig> tySigList, IGenericReplacer replacer)
{
return tySigList?.Select(tySig => ReplaceGenericSigImpl(tySig, replacer)).ToList();
}
// 检查是否存在要替换的泛型签名
private static bool IsReplaceNeeded(TypeSig tySig)
{
while (tySig != null)
{
switch (tySig.ElementType)
{
case ElementType.Var:
case ElementType.MVar:
return true;
case ElementType.GenericInst:
{
GenericInstSig genInstSig = (GenericInstSig)tySig;
foreach (var arg in genInstSig.GenericArguments)
{
if (IsReplaceNeeded(arg))
return true;
}
}
break;
}
tySig = tySig.Next;
}
return false;
}
public static bool IsEnumType(TypeSig tySig, out TypeSig enumTypeSig)
{
if (tySig.IsValueType)
{
TypeDef tyDef = tySig.ToTypeDefOrRef().ResolveTypeDef();
if (tyDef.BaseType.FullName == "System.Enum")
{
FieldDef fldDef = tyDef.Fields.FirstOrDefault(f => !f.IsStatic);
Debug.Assert(fldDef != null);
enumTypeSig = fldDef.FieldType;
return true;
}
}
enumTypeSig = null;
return false;
}
public static void TypeNameKey(
StringBuilder sb,
TypeDef tyDef,
IList<TypeSig> genArgs)
{
ClassSigName(sb, tyDef);
if (genArgs.IsCollectionValid())
{
sb.Append('<');
TypeSigListName(sb, genArgs, true);
sb.Append('>');
}
}
public static void MethodNameKey(
StringBuilder sb,
string name,
int genCount,
TypeSig retType,
IList<TypeSig> paramTypes,
CallingConvention callConv)
{
sb.Append(name);
sb.Append('|');
TypeSigName(sb, retType, false);
if (genCount > 0)
{
sb.Append('<');
sb.Append(genCount);
sb.Append('>');
}
sb.Append('(');
TypeSigListName(sb, paramTypes, false);
sb.Append(')');
sb.Append('|');
sb.Append(((uint)callConv).ToString("X"));
}
public static void MethodNameKeyWithGen(
StringBuilder sb,
string name,
IList<TypeSig> genArgs,
TypeSig retType,
IList<TypeSig> paramTypes,
CallingConvention callConv)
{
sb.Append(name);
sb.Append('|');
TypeSigName(sb, retType, false);
if (genArgs.IsCollectionValid())
{
sb.Append('<');
TypeSigListName(sb, genArgs, false);
sb.Append('>');
}
sb.Append('(');
TypeSigListName(sb, paramTypes, false);
sb.Append(')');
sb.Append('|');
sb.Append(((uint)callConv).ToString("X"));
}
public static void MethodDefNameKey(
StringBuilder sb,
MethodDef metDef,
IGenericReplacer replacer)
{
if (replacer == null)
{
MethodNameKey(
sb,
metDef.Name,
metDef.GenericParameters.Count,
metDef.MethodSig.RetType,
metDef.MethodSig.Params,
metDef.MethodSig.CallingConvention);
}
else
{
TypeSig retType = Helper.ReplaceGenericSig(metDef.MethodSig.RetType, replacer);
IList<TypeSig> paramTypes = Helper.ReplaceGenericSigList(metDef.MethodSig.Params, replacer);
MethodNameKey(
sb,
metDef.Name,
metDef.GenericParameters.Count,
retType,
paramTypes,
metDef.MethodSig.CallingConvention);
}
}
public static void FieldNameKey(
StringBuilder sb,
string name,
TypeSig fldType)
{
sb.Append(name);
sb.Append('|');
TypeSigName(sb, fldType, false);
}
public static void TypeSigListName(StringBuilder sb, IList<TypeSig> tySigList, bool printGenOwner)
{
bool last = false;
foreach (var tySig in tySigList)
{
if (last)
sb.Append(',');
last = true;
TypeSigName(sb, tySig, printGenOwner);
}
}
public static void TypeSigName(StringBuilder sb, TypeSig tySig, bool printGenOwner, int depth = 0)
{
if (depth > 512)
throw new TypeLoadException("The TypeSig chain is too long. Or there are some recursive generics that are expanded");
if (tySig == null)
return;
switch (tySig.ElementType)
{
case ElementType.Class:
case ElementType.ValueType:
case ElementType.TypedByRef:
ClassSigName(sb, tySig);
return;
case ElementType.Ptr:
TypeSigName(sb, tySig.Next, printGenOwner, depth + 1);
sb.Append('*');
return;
case ElementType.ByRef:
TypeSigName(sb, tySig.Next, printGenOwner, depth + 1);
sb.Append('&');
return;
case ElementType.Pinned:
TypeSigName(sb, tySig.Next, printGenOwner, depth + 1);
return;
case ElementType.SZArray:
TypeSigName(sb, tySig.Next, printGenOwner, depth + 1);
sb.Append("[]");
return;
case ElementType.Array:
{
TypeSigName(sb, tySig.Next, printGenOwner, depth + 1);
ArraySig arySig = (ArraySig)tySig;
GetArraySigPostfix(sb, arySig);
return;
}
case ElementType.CModReqd:
TypeSigName(sb, tySig.Next, printGenOwner, depth + 1);
sb.Append(" modreq(");
ClassSigName(sb, ((CModReqdSig)tySig).Modifier.ToTypeSig());
sb.Append(')');
return;
case ElementType.CModOpt:
TypeSigName(sb, tySig.Next, printGenOwner, depth + 1);
sb.Append(" modopt(");
ClassSigName(sb, ((CModOptSig)tySig).Modifier.ToTypeSig());
sb.Append(')');
return;
case ElementType.GenericInst:
{
GenericInstSig genInstSig = (GenericInstSig)tySig;
TypeSigName(sb, genInstSig.GenericType, printGenOwner, depth + 1);
sb.Append('<');
TypeSigListName(sb, genInstSig.GenericArguments, printGenOwner);
sb.Append('>');
return;
}
case ElementType.Var:
case ElementType.MVar:
{
var genSig = (GenericSig)tySig;
if (genSig.IsMethodVar)
{
sb.Append("!!");
}
else
{
sb.Append('!');
if (printGenOwner)
{
sb.Append('(');
ClassSigName(sb, genSig.OwnerType);
sb.Append(')');
}
}
sb.Append(genSig.Number);
return;
}
default:
if (tySig is CorLibTypeSig)
{
ClassSigName(sb, tySig);
return;
}
throw new ArgumentOutOfRangeException();
}
}
public static void GetArraySigPostfix(StringBuilder sb, ArraySig arySig)
{
sb.Append('[');
uint rank = arySig.Rank;
if (rank == 0)
throw new NotSupportedException();
else if (rank == 1)
sb.Append('*');
else
{
for (int i = 0; i < (int)rank; i++)
{
if (i != 0)
sb.Append(',');
const int NO_LOWER = int.MinValue;
const uint NO_SIZE = uint.MaxValue;
int lower = arySig.LowerBounds.Get(i, NO_LOWER);
uint size = arySig.Sizes.Get(i, NO_SIZE);
if (lower != NO_LOWER)
{
sb.Append(lower);
sb.Append("..");
if (size != NO_SIZE)
sb.Append(lower + (int)size - 1);
else
sb.Append('.');
}
}
}
sb.Append(']');
}
private static void ClassSigName(StringBuilder sb, TypeSig tySig)
{
string fullName = tySig.FullName;
if (tySig.ElementType != ElementType.SZArray &&
tySig.ElementType != ElementType.Array &&
tySig.ElementType != ElementType.GenericInst &&
tySig.DefinitionAssembly.IsCorLib())
{
string basicName = IsBasicType(fullName);
if (basicName != null)
sb.Append(basicName);
else
sb.Append(fullName);
}
else
sb.AppendFormat("[{0}]{1}",
AssemblyName(tySig.DefinitionAssembly),
fullName);
}
private static void ClassSigName(StringBuilder sb, TypeDef tyDef)
{
string fullName = tyDef.FullName;
if (tyDef.DefinitionAssembly.IsCorLib())
{
string basicName = IsBasicType(fullName);
if (basicName != null)
sb.Append(basicName);
else
sb.Append(fullName);
}
else
sb.AppendFormat("[{0}]{1}",
AssemblyName(tyDef.DefinitionAssembly),
fullName);
}
public static bool IsExtern(MethodDef metDef)
{
return !metDef.HasBody && !metDef.IsAbstract;
}
public static bool IsInstanceField(FieldDef fldDef)
{
return !fldDef.IsStatic;
}
public static bool IsBasicValueType(ElementType elemType)
{
switch (elemType)
{
case ElementType.Boolean:
case ElementType.Char:
case ElementType.I1:
case ElementType.I2:
case ElementType.I4:
case ElementType.I8:
case ElementType.U1:
case ElementType.U2:
case ElementType.U4:
case ElementType.U8:
case ElementType.R4:
case ElementType.R8:
case ElementType.I:
case ElementType.U:
case ElementType.Ptr:
case ElementType.ByRef:
return true;
}
return false;
}
public static string IsBasicType(string fullName)
{
switch (fullName)
{
case "System.Void":
return "Void";
case "System.Boolean":
return "Boolean";
case "System.Char":
return "Char";
case "System.Object":
return "Object";
case "System.String":
return "String";
case "System.SByte":
return "SByte";
case "System.Byte":
return "Byte";
case "System.Int16":
return "Int16";
case "System.UInt16":
return "UInt16";
case "System.Int32":
return "Int32";
case "System.UInt32":
return "UInt32";
case "System.Int64":
return "Int64";
case "System.UInt64":
return "UInt64";
case "System.IntPtr":
return "IntPtr";
case "System.UIntPtr":
return "UIntPtr";
case "System.Single":
return "Single";
case "System.Double":
return "Double";
}
return null;
}
public static string AssemblyName(IAssembly asm)
{
var sb = new StringBuilder();
sb.Append(asm.Name);
if (asm.Version != null)
{
sb.AppendFormat(",ver={0}", asm.Version);
}
if (!UTF8String.IsNullOrEmpty(asm.Culture))
{
sb.AppendFormat(",cul={0}", asm.Culture.String);
}
var publicKey = asm.PublicKeyOrToken;
if (publicKey != null &&
publicKey.Data != null &&
publicKey.Data.Length != 0)
{
sb.AppendFormat(",{0}={1}",
publicKey is PublicKeyToken ? "tok=" : "key=",
publicKey);
}
return sb.ToString();
}
public static int CombineHash(params int[] hashCodes)
{
int result = 0;
foreach (int hash in hashCodes)
result = ((result << 5) + result) ^ hash;
return result;
}
public static string EscapeString(string str)
{
return ReplaceNonCharacters(str, '?')
.Replace("\\", "\\x5C")
.Replace("\n", "\\n")
.Replace("\r", "\\r")
.Replace("\x0B", "\\x0B")
.Replace("\x0C", "\\x0C")
.Replace("\x85", "\\x85")
.Replace("\u2028", "\\u2028")
.Replace("\u2029", "\\u2029");
}
private static string ReplaceNonCharacters(string aString, char replacement)
{
var sb = new StringBuilder(aString.Length);
for (var i = 0; i < aString.Length; i++)
{
if (char.IsSurrogatePair(aString, i))
{
int c = char.ConvertToUtf32(aString, i);
i++;
if (IsCharacter(c))
sb.Append(char.ConvertFromUtf32(c));
else
sb.Append(replacement);
}
else
{
char c = aString[i];
if (IsCharacter(c))
sb.Append(c);
else
sb.Append(replacement);
}
}
return sb.ToString();
}
private static bool IsCharacter(int point)
{
return point < 0xFDD0;
}
public static bool IsPowerOfTwo(ushort x)
{
return (x & (x - 1)) == 0;
}
public static string ByteArrayToCode(byte[] arr)
{
StringBuilder sb = new StringBuilder();
sb.Append('{');
for (int i = 0; i < arr.Length; ++i)
{
if (i != 0)
sb.Append(',');
sb.Append(arr[i].ToString());
}
sb.Append('}');
return sb.ToString();
}
}
}