-
Notifications
You must be signed in to change notification settings - Fork 428
Expand file tree
/
Copy pathCodeTranslator.cs
More file actions
4177 lines (3839 loc) · 190 KB
/
CodeTranslator.cs
File metadata and controls
4177 lines (3839 loc) · 190 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
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Tencent is pleased to support the open source community by making InjectFix available.
* Copyright (C) 2019 Tencent. All rights reserved.
* InjectFix is licensed under the MIT License, except for the third-party components listed in the file 'LICENSE' which may be subject to their corresponding license terms.
* This file is subject to the terms and conditions defined in file 'LICENSE', which is part of this source code package.
*/
using System;
using System.Linq;
using System.Collections.Generic;
using System.IO;
using Mono.Cecil;
using Mono.Cecil.Cil;
namespace IFix
{
enum ProcessMode
{
Inject,
Patch
}
class CodeTranslator
{
private Dictionary<int, List<Core.Instruction>> codes = new Dictionary<int, List<Core.Instruction>>();
private HashSet<int> codeMustWriteToPatch = new HashSet<int>();
private Dictionary<MethodReference, int> methodToId = new Dictionary<MethodReference, int>();
private Dictionary<int, Core.ExceptionHandler[]> methodIdToExceptionHandler =
new Dictionary<int, Core.ExceptionHandler[]>();
private List<TypeReference> externTypes = new List<TypeReference>();
private List<TypeReference> contextTypeOfExternType = new List<TypeReference>();
private Dictionary<TypeReference, int> externTypeToId = new Dictionary<TypeReference, int>();
private Dictionary<string, TypeReference> nameToExternType = new Dictionary<string, TypeReference>();
private List<MethodReference> externMethods = new List<MethodReference>();
private Dictionary<MethodReference, int> externMethodToId = new Dictionary<MethodReference, int>();
private List<string> internStrings = new List<string>();
private Dictionary<string, int> internStringsToId = new Dictionary<string, int>();
private List<FieldReference> fields = new List<FieldReference>();
private List<FieldDefinition> fieldsStoreInVirtualMachine = new List<FieldDefinition>();
private Dictionary<FieldReference, int> fieldToId = new Dictionary<FieldReference, int>();
private Dictionary<MethodReference, int> virtualMethodToIndex = new Dictionary<MethodReference, int>();
const string Wrap_Perfix = "__Gen_Wrap_";
int nextAllocId = 0;
bool isCompilerGenerated(TypeReference type)
{
if (type.IsGenericInstance)
{
return isCompilerGenerated((type as GenericInstanceType).ElementType);
}
var td = type as TypeDefinition;
if (td != null && td.IsNested)
{
if (isCompilerGenerated(td.DeclaringType))
{
return true;
}
}
return td != null && !td.IsInterface && td
.CustomAttributes
.Any(ca => ca.AttributeType.FullName == "System.Runtime.CompilerServices.CompilerGeneratedAttribute");
}
bool isCompilerGenerated(MethodReference method)
{
if (method.IsGenericInstance)
{
return isCompilerGenerated((method as GenericInstanceMethod).ElementMethod);
}
var md = method as MethodDefinition;
return md != null && md.CustomAttributes.Any(ca => ca.AttributeType.FullName
== "System.Runtime.CompilerServices.CompilerGeneratedAttribute");
}
bool isCompilerGenerated(FieldReference field)
{
var fd = field as FieldDefinition;
return fd != null && fd.CustomAttributes.Any(ca => ca.AttributeType.FullName
== "System.Runtime.CompilerServices.CompilerGeneratedAttribute");
}
bool isCompilerGeneratedPlainObject(TypeReference type)
{
var td = type as TypeDefinition;
return td != null
&& !td.IsInterface
//&& td.Interfaces.Count == 0
&& isCompilerGenerated(type)
&& td.BaseType.IsSameType(objType);
}
bool isCustomClassPlainObject(TypeReference type)
{
var td = type as TypeDefinition;
return td != null
&& !td.IsInterface
&& isNewClass(td)
&& (td.BaseType.IsSameType(objType) || isCustomClassPlainObject(td.BaseType as TypeReference));
}
bool isCompilerGeneratedByNotPlainObject(TypeReference type)
{
var td = type as TypeDefinition;
return (type.IsGenericInstance || (td != null
&& !td.IsInterface
//&& (!td.BaseType.IsSameType(objType) || td.Interfaces.Count != 0)))
&& !td.BaseType.IsSameType(objType)))
&& isCompilerGenerated(type);
}
Dictionary<TypeDefinition, HashSet<FieldDefinition>> typeToSpecialGeneratedFields
= new Dictionary<TypeDefinition, HashSet<FieldDefinition>>();
Dictionary<TypeDefinition, int> typeToCctor = new Dictionary<TypeDefinition, int>();
Dictionary<FieldDefinition, int> newFieldToCtor = new Dictionary<FieldDefinition, int>();
/// <summary>
/// 获取简写属性(例如public int a{get;set;}),事件等所生成的字段
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
HashSet<FieldDefinition> getSpecialGeneratedFields(TypeDefinition type)
{
HashSet<FieldDefinition> ret;
if (!typeToSpecialGeneratedFields.TryGetValue(type, out ret))
{
ret = new HashSet<FieldDefinition>();
typeToSpecialGeneratedFields[type] = ret;
if (!typeToCctor.ContainsKey(type))
{
typeToCctor[type] = -1;
var cctor = type.Methods.FirstOrDefault(m => m.Name == ".cctor");
if (cctor != null)
{
var cctorInfo = getMethodId(cctor, null,false, false, InjectType.Redirect);
typeToCctor[type] = cctorInfo.Type == CallType.Internal ? cctorInfo.Id : -2;
}
}
foreach (var field in ( from method in type.Methods
where method.IsSpecialName && method.Body != null
&& method.Body.Instructions != null
from instruction in method.Body.Instructions
where instruction.OpCode.Code == Code.Ldsfld
|| instruction.OpCode.Code == Code.Stsfld
|| instruction.OpCode.Code == Code.Ldsflda
where isCompilerGenerated(instruction.Operand as FieldReference)
select (instruction.Operand as FieldReference).Resolve()).Distinct())
{
ret.Add(field);
}
}
return ret;
}
//再补丁新增一个对原生方法的引用
int addExternType(TypeReference type, TypeReference contextType = null)
{
if (type.IsRequiredModifier) return addExternType((type as RequiredModifierType).ElementType, contextType);
if (type.IsGenericParameter || type.HasGenericArgumentFromMethod())
{
var genericTypeInfo = "{None}";
try {
var genericType = (GenericParameter)type;
var owner = (TypeDefinition)genericType.Owner;
genericTypeInfo = string.Format("{{Owner: {0}, Scope: {1}}}", owner.FullName, genericType.Scope.Name);
} catch { }
throw new InvalidProgramException("try to use a generic type definition: " + type + ", generic type info: " + genericTypeInfo);
}
if (externTypeToId.ContainsKey(type))
{
return externTypeToId[type];
}
if (isNewClass(type as TypeDefinition))
{
throw new Exception(type + " is new class, cannot be treated as extern type");
}
if (isCompilerGenerated(type))
{
throw new Exception(type + " is CompilerGenerated");
}
TypeReference theSameNameType;
var typeName = type.GetAssemblyQualifiedName(contextType);
if (nameToExternType.TryGetValue(typeName, out theSameNameType))
{
var ret = addExternType(theSameNameType, contextType);
externTypeToId.Add(type, ret);
return ret;
}
nameToExternType.Add(typeName, type);
externTypeToId.Add(type, externTypes.Count);
externTypes.Add(type);
contextTypeOfExternType.Add(contextType);
return externTypes.Count - 1;
}
//假如是注入模式,而且该函数配置是IFix的话,不需要真的为其访问的资源分配id
//TODO: 更理想的做法是剥离一个分析代码流程,仅分析要生产哪些适配器,反向适配器,反剪裁配置
bool doNoAdd(MethodDefinition caller)
{
InjectType injectType;
return mode == ProcessMode.Inject && caller != null && methodToInjectType.TryGetValue(caller,
out injectType) && injectType == InjectType.Switch;
}
//原生字段
int addRefField(FieldReference field, MethodDefinition caller)
{
if (doNoAdd(caller))
{
return int.MaxValue;
}
int id;
if (!fieldToId.TryGetValue(field, out id))
{
id = fields.Count;
fieldToId.Add(field, id);
fields.Add(field);
addExternType(field.DeclaringType);
}
return id;
}
//虚拟机存储字段
int addStoreField(FieldDefinition field, MethodDefinition caller)
{
if (doNoAdd(caller))
{
return int.MaxValue;
}
int id;
if (!fieldToId.TryGetValue(field, out id))
{
id = -(fieldsStoreInVirtualMachine.Count + 1);
fieldToId.Add(field, id);
fieldsStoreInVirtualMachine.Add(field);
addExternType((isCompilerGenerated(field.FieldType) || isNewClass(field.FieldType as TypeDefinition)) ? objType : field.FieldType);
}
return id;
}
//新增一个字符串字面值
int addInternString(string str, MethodDefinition caller)
{
if (doNoAdd(caller))
{
return int.MaxValue;
}
int id;
if (!internStringsToId.TryGetValue(str, out id))
{
id = internStrings.Count;
internStrings.Add(str);
internStringsToId.Add(str, id);
}
return id;
}
//原生方法的引用
int addExternMethod(MethodReference callee, MethodDefinition caller)
{
if (doNoAdd(caller))
{
return ushort.MaxValue;
}
if (callee.Name == "AwaitUnsafeOnCompleted")
{
if (!awaitUnsafeOnCompletedMethods.Any(m => ((GenericInstanceMethod)callee).GenericArguments[0] == ((GenericInstanceMethod)m).GenericArguments[0]))
{
awaitUnsafeOnCompletedMethods.Add(callee);
}
}
if (externMethodToId.ContainsKey(callee))
{
return externMethodToId[callee];
}
if (callee.IsGeneric())
{
throw new InvalidProgramException("try to call a generic method definition: " + callee
+ ", caller is:" + caller);
}
if (isCompilerGenerated(callee) && !(callee as MethodDefinition).IsSpecialName)
{
throw new Exception(callee + " is CompilerGenerated");
}
if (callee.IsGenericInstance)
{
foreach (var typeArg in ((GenericInstanceMethod)callee).GenericArguments)
{
if (!isCompilerGenerated(typeArg))
{
addExternType(typeArg);
}
}
}
if (callee.ReturnType.IsGenericParameter)
{
var resolveType = (callee.ReturnType as GenericParameter).ResolveGenericArgument(callee.DeclaringType);
if (resolveType != null)
{
addExternType(resolveType);
}
}
else if (!callee.ReturnType.HasGenericArgumentFromMethod())
{
addExternType(callee.ReturnType, callee.DeclaringType);
}
addExternType(callee.DeclaringType);
foreach (var p in callee.Parameters)
{
if (p.ParameterType.IsGenericParameter)
{
var resolveType = (p.ParameterType as GenericParameter).ResolveGenericArgument(
callee.DeclaringType);
if (resolveType != null)
{
addExternType(resolveType);
}
}
else if (!p.ParameterType.HasGenericArgumentFromMethod())
{
addExternType(p.ParameterType, callee.DeclaringType);
}
}
int methodId = externMethods.Count;
if (methodId > ushort.MaxValue)
{
throw new OverflowException("too many extern methods");
}
externMethodToId[callee] = methodId;
externMethods.Add(callee);
return methodId;
}
HashSet<MethodDefinition> antiLoop = new HashSet<MethodDefinition>();
Dictionary<MethodDefinition, bool> cacheCheckResult = new Dictionary<MethodDefinition, bool>();
bool checkILAndGetOffset(MethodDefinition method,
Mono.Collections.Generic.Collection<Instruction> instructions)
{
if (cacheCheckResult.ContainsKey(method)) return cacheCheckResult[method];
if (antiLoop.Contains(method)) return true;
antiLoop.Add(method);
int p;
bool ret = checkILAndGetOffset(method, instructions, null, out p);
cacheCheckResult[method] = ret;
return ret;
}
/// <summary>
/// 判断一个名字是否是一个合法id
/// </summary>
/// <param name="text"></param>
/// <returns></returns>
public static bool IsVaildIdentifierName(string text)
{
if (string.IsNullOrEmpty(text))
return false;
if (!char.IsLetter(text[0]) && text[0] != '_')
return false;
for (int ix = 1; ix < text.Length; ++ix)
if (!char.IsLetterOrDigit(text[ix]) && text[ix] != '_')
return false;
return true;
}
public bool isRefBySpecialMethodNoCache(FieldDefinition field)
{
foreach(var instructions in field.DeclaringType.Methods
.Where(m => m.IsSpecialName && m.Body != null && m.Body.Instructions != null)
.Select(m => m.Body.Instructions))
{
if (instructions.Any(i => i.Operand == field))
{
return true;
}
}
return false;
}
Dictionary<FieldDefinition, bool> isRefBySpecialMethodCache = new Dictionary<FieldDefinition, bool>();
public bool isRefBySpecialMethod(FieldDefinition field)
{
bool ret;
if (!isRefBySpecialMethodCache.TryGetValue(field, out ret))
{
ret = isRefBySpecialMethodNoCache(field);
isRefBySpecialMethodCache.Add(field, ret);
}
return ret;
}
// #lizard forgives
bool checkILAndGetOffset(MethodDefinition method,
Mono.Collections.Generic.Collection<Instruction> instructions,
Dictionary<Instruction, int> ilOffset, out int stopPos)
{
int offset = 0;
stopPos = 0;
for (int i = 0; i < instructions.Count; i++)
{
if (ilOffset != null)
{
ilOffset.Add(instructions[i], offset + 1);
}
stopPos = i;
//Console.WriteLine(i + " instruction:" + instructions[i].OpCode + " offset:" + offset);
switch (instructions[i].OpCode.Code)
{
case Code.Nop://先忽略
break;
case Code.Constrained:
{
TypeReference tr = instructions[i].Operand as TypeReference;
if (tr != null && !tr.IsGeneric())
{
offset += 2;
break;
}
else
{
return false;
}
}
case Code.Ldc_I8:
case Code.Ldc_R8:
case Code.Leave:
case Code.Leave_S:
offset += 2;
break;
case Code.Switch:
Instruction[] jmpTargets = instructions[i].Operand as Instruction[];
offset += ((jmpTargets.Length + 1) >> 1) + 1;
break;
case Code.Castclass:
case Code.Initobj:
case Code.Newarr:
case Code.Stobj:
case Code.Box:
case Code.Isinst:
case Code.Unbox_Any:
case Code.Unbox:
case Code.Ldobj:
case Code.Ldtoken:
{
TypeReference tr = instructions[i].Operand as TypeReference;
if (tr != null && !tr.IsGeneric())
{
offset += 1;
break;
}
else
{
return false;
}
}
case Code.Stfld:
case Code.Ldfld:
case Code.Ldflda:
{
FieldReference fr = instructions[i].Operand as FieldReference;
//如果是生成的字段,而且不是Getter/Setter/Adder/Remover
if (isCompilerGenerated(fr) && !method.IsSpecialName)
{
if (!IsVaildIdentifierName(fr.Name)//不是合法名字,就肯定是随机变量
//如果是合法名字,但不被任何SpecialName方法引用,也归为随机变量
|| !isRefBySpecialMethod(fr as FieldDefinition))
{
return false;
}
}
if (fr != null/* && !fr.IsGeneric()*/)
{
offset += 1;
break;
}
else
{
return false;
}
}
case Code.Stsfld:
case Code.Ldsfld:
case Code.Ldsflda:
{
FieldReference fr = instructions[i].Operand as FieldReference;
//如果访问了生成的静态字段,而且不能存到虚拟机,不是Getter/Setter/Adder/Remover
//if ((isCompilerGenerated(fr) || isCompilerGenerated(fr.DeclaringType))
// && !isFieldStoreInVitualMachine(fr) && !method.IsSpecialName)
//{
// return false;
//}
if (fr != null/* && !fr.IsGeneric()*/)
{
offset += 1;
break;
}
else
{
return false;
}
}
case Code.Newobj:
case Code.Callvirt:
case Code.Call:
case Code.Ldftn:
case Code.Ldvirtftn:
{
//LINQ通常是ldftn,要验证ldftn所加载的函数是否含非法指令(不支持,或者引用了个生成字段,
//或者一个生成NotPlainObject)
MethodReference mr = instructions[i].Operand as MethodReference;
if (mr != null && !mr.IsGeneric()
&& !isCompilerGeneratedByNotPlainObject(mr.DeclaringType))
{
if (isCompilerGenerated(mr)
|| (/*instructions[i].OpCode.Code != Code.Newobj && */
isCompilerGeneratedPlainObject(mr.DeclaringType))
|| isCustomClassPlainObject(mr.DeclaringType))
{
var md = mr as MethodDefinition;
if (md == null)//闭包中调用一个泛型,在unity2018的.net 3.5设置下,编译器是先生成一个泛型的闭包实现,然后实例化,很奇怪的做法,老版本unity,新unity的.net 4.0设置都不会这样,先返回false,不支持这种编译器
{
return false;
}
if (md.Body != null && !checkILAndGetOffset(md, md.Body.Instructions))
{
//Console.WriteLine("check " + md + " fail il = " + md.Body.Instructions[p]
// + ",caller=" + method);
return false;
}
//编译器生成类要检查所有实现方法
if (instructions[i].OpCode.Code == Code.Newobj
&& (isCompilerGeneratedPlainObject(mr.DeclaringType) || isCustomClassPlainObject(mr.DeclaringType)))
{
foreach (var m in mr.DeclaringType.Resolve().Methods
.Where(m => !m.IsConstructor))
{
if (m.Body != null && !checkILAndGetOffset(m, m.Body.Instructions))
{
//Console.WriteLine("check " + md + " fail il = "
// + md.Body.Instructions[p] + ",caller=" + method);
return false;
}
}
}
}
offset += 1;
break;
}
else
{
return false;
}
}
case Code.Conv_I: //Convert to native int, pushing native int on stack.
//case Code.Conv_U: //Convert to unsigned native int, pushing native int on stack.
case Code.Conv_Ovf_U:
case Code.Conv_Ovf_U_Un:
case Code.Calli: // not support op
case Code.Cpobj:
case Code.Refanyval:
case Code.Ckfinite:
case Code.Mkrefany:
case Code.Arglist:
case Code.Localloc:
case Code.Endfilter:
case Code.Unaligned:
case Code.Tail:
case Code.Cpblk:
case Code.Initblk:
case Code.No:
case Code.Sizeof: // support?
case Code.Refanytype:
case Code.Readonly:
return false;
default:
offset += 1;
break;
}
}
return true;
}
void processMethod(MethodDefinition method)
{
getMethodId(method, null,true);
}
Core.ExceptionHandler findExceptionHandler(Core.ExceptionHandler[] ehs, Core.ExceptionHandlerType type,
int offset)
{
int dummy;
return findExceptionHandler(ehs, type, offset, out dummy);
}
/// <summary>
/// 查找一个指令异常时的异常处理块
/// </summary>
/// <param name="ehs">当前函数的所有异常处理块</param>
/// <param name="type">异常类型</param>
/// <param name="offset">指令偏移</param>
/// <param name="idx">异常处理块的索引</param>
/// <returns></returns>
Core.ExceptionHandler findExceptionHandler(Core.ExceptionHandler[] ehs, Core.ExceptionHandlerType type,
int offset, out int idx)
{
Core.ExceptionHandler ret = null;
idx = -1;
for (int i = 0; i < ehs.Length; i++)
{
var eh = ehs[i];
if (eh.HandlerType == type && eh.TryStart <= offset && eh.TryEnd > offset)
{
if (ret == null || ((eh.TryEnd - eh.TryStart) < (ret.TryEnd - ret.TryStart)))
{
ret = eh;
idx = i;
}
}
}
return ret;
}
MethodDefinition findOverride(TypeDefinition type, MethodReference vmethod, bool allowAbstractMethod = false)
{
foreach (var method in type.Methods)
{
if (method.IsVirtual && (allowAbstractMethod || !method.IsAbstract) && isTheSameDeclare(method, vmethod))
{
return method;
}
}
return null;
}
bool isTheSameDeclare(MethodReference m1, MethodReference m2)
{
if (m1.Name == m2.Name && m1.ReturnType.IsSameName(m2.ReturnType)
&& m1.Parameters.Count == m2.Parameters.Count)
{
bool isParamsMatch = true;
for (int i = 0; i < m1.Parameters.Count; i++)
{
if (m1.Parameters[i].Attributes != m2.Parameters[i].Attributes
|| !m1.Parameters[i].ParameterType.IsSameName(m2.Parameters[i].ParameterType))
{
isParamsMatch = false;
break;
}
}
return isParamsMatch;
}
return false;
}
MethodReference _findBase(TypeReference type, MethodDefinition method)
{
TypeDefinition td = type.Resolve();
if (td == null)
{
return null;
}
var m = findOverride(td, method);
if (m != null)
{
if (type.IsGenericInstance)
{
return m.MakeGeneric(method.DeclaringType);
}
else
{
return m.TryImport(method.DeclaringType.Module);
}
}
return _findBase(td.BaseType, method);
}
MethodReference _findInitDefineVirtualMethod(TypeReference type, MethodDefinition method)
{
TypeDefinition td = type.Resolve();
if (td == null)
{
return null;
}
MethodReference baseM = null;
if (td.BaseType != null && isNewClass(td.BaseType as TypeDefinition))
{
baseM = _findInitDefineVirtualMethod(td.BaseType, method);
}
if (baseM != null)
{
return baseM;
}
var m = findOverride(td, method, true);
if (m != null)
{
if (type.IsGenericInstance)
{
return m.MakeGeneric(method.DeclaringType);
}
else
{
return m.TryImport(method.DeclaringType.Module);
}
}
return null;
}
MethodReference findInitDefineVirtualMethod(TypeDefinition type, MethodDefinition method)
{
if (method.IsVirtual)
{
foreach (var objVirtualMethod in ObjectVirtualMethodDefinitionList)
{
if (isTheSameDeclare(objVirtualMethod,method))
{
return objVirtualMethod;
}
}
if (method.IsNewSlot)
{
return method;
}
return _findInitDefineVirtualMethod(type.BaseType, method);
}
return null;
}
MethodReference findBase(TypeDefinition type, MethodDefinition method)
{
if (method.IsVirtual && !method.IsNewSlot) //表明override
{
try
{
//TODO: 如果后续支持泛型解析,需要考虑这块的实现,xlua目前泛型直接不支持base调用
return _findBase(type.BaseType, method);
}
catch { }
}
return null;
}
const string BASE_RPOXY_PERFIX = "<>iFixBaseProxy_";
Dictionary<MethodReference, Dictionary<TypeDefinition, MethodReference>> baseProxys = new Dictionary<MethodReference, Dictionary<TypeDefinition, MethodReference>>();
//方案2
//var method = typeof(object).GetMethod("ToString");
//var ftn = method.MethodHandle.GetFunctionPointer();
//var func = (Func<string>)Activator.CreateInstance(typeof(Func<string>), obj, ftn);
MethodReference tryAddBaseProxy(TypeDefinition type, MethodDefinition method)
{
var mbase = findBase(type, method);
if (mbase != null)
{
if (!isNewClass(type))
{
var proxyMethod = new MethodDefinition(BASE_RPOXY_PERFIX + method.Name, MethodAttributes.Public,
method.ReturnType);
for (int i = 0; i < method.Parameters.Count; i++)
{
proxyMethod.Parameters.Add(new ParameterDefinition("P" + i, method.Parameters[i].IsOut
? ParameterAttributes.Out : ParameterAttributes.None, method.Parameters[i].ParameterType));
}
var instructions = proxyMethod.Body.Instructions;
var ilProcessor = proxyMethod.Body.GetILProcessor();
int paramCount = method.Parameters.Count + 1;
for (int i = 0; i < paramCount; i++)
{
emitLdarg(instructions, ilProcessor, i);
if (i == 0 && type.IsValueType)
{
instructions.Add(Instruction.Create(OpCodes.Ldobj, type));
instructions.Add(Instruction.Create(OpCodes.Box, type));
}
}
instructions.Add(Instruction.Create(OpCodes.Call, mbase));
instructions.Add(Instruction.Create(OpCodes.Ret));
type.Methods.Add(proxyMethod);
Dictionary<TypeDefinition, MethodReference> typeToProxy;
if (!baseProxys.TryGetValue(mbase, out typeToProxy))
{
typeToProxy = new Dictionary<TypeDefinition, MethodReference>();
baseProxys.Add(mbase, typeToProxy);
}
typeToProxy.Add(type, proxyMethod);
return proxyMethod;
}
else if(isNewClass(type) && !isNewClass(type.BaseType as TypeDefinition))
{
return objectVirtualMethodReferenceList.FirstOrDefault( m => m.Name == ("Object" + method.Name));
}
}
return null;
}
MethodReference findProxy(TypeDefinition type, MethodReference methodToCall)
{
Dictionary<TypeDefinition, MethodReference> typeToProxy;
if (baseProxys.TryGetValue(methodToCall, out typeToProxy))
{
TypeDefinition ptype = type;
while (ptype != null)
{
if (typeToProxy.ContainsKey(ptype))
{
return typeToProxy[ptype];
}
ptype = ptype.DeclaringType;
}
}
return null;
}
enum CallType
{
Extern,
Internal,
InteralVirtual,
Invalid
}
struct MethodIdInfo
{
public int Id;
public CallType Type;
}
enum InjectType
{
Redirect,
Switch
}
bool isFieldStoreInVitualMachine(FieldReference field)
{
var fieldDef = field.Resolve();
if (fieldDef == null)
{
return false;
}
if (!fieldDef.IsStatic)
{
return false;
}
if ((!isCompilerGenerated(field) && !isCompilerGenerated(field.DeclaringType)) || !isNewClass(field.DeclaringType as TypeDefinition))
{
return false;
}
if (field.FieldType.Resolve().IsDelegate())
{
return true;
}
//TODO: switch(str)
return false;
}
bool isNewMethod(MethodDefinition method)
{
return configure.IsNewMethod(method);
}
bool isNewClass(TypeDefinition type)
{
return configure.IsNewClass(type);
}
bool isNewField(FieldDefinition field)
{
return configure.isNewField(field);
}
Dictionary<MethodDefinition, int> interpretMethods = new Dictionary<MethodDefinition, int>();
void addInterpretMethod(MethodDefinition method, int methodId)
{
if (method.IsGenericInstance || method.HasGenericParameters)
{
throw new NotSupportedException("generic method definition");
}
addExternType(method.ReturnType, method.DeclaringType);
addExternType(method.DeclaringType);
foreach(var pinfo in method.Parameters)
{
addExternType(pinfo.ParameterType, method.DeclaringType);
}
interpretMethods.Add(method, methodId);
}
bool isFieldAccessInject(MethodDefinition method, int methodId)
{
return false;
}
//字段注入方式处理逻辑
//目前用不上,但后续支持泛型修复需要用到
void fieldAccessInject(InjectType injectType, MethodDefinition method, int methodId)
{
var redirectBridge = getRedirectField(method);
var body = method.Body;
var msIls = body.Instructions;
var ilProcessor = body.GetILProcessor();
var redirectTo = getWrapperMethod(wrapperType, anonObjOfWrapper, method, false, false);
Instruction insertPoint;
if (injectType == InjectType.Redirect)
{
msIls.Clear();
body.ExceptionHandlers.Clear();
body.Variables.Clear();
msIls.Add(Instruction.Create(OpCodes.Ret));
insertPoint = msIls[0];
ilProcessor.InsertBefore(insertPoint, ilProcessor.Create(OpCodes.Ldsfld, redirectBridge));
}
else
{
ilProcessor.InsertBefore(msIls[0], Instruction.Create(OpCodes.Ret));
insertPoint = msIls[0];
var redirectBridgeTmp = new VariableDefinition(wrapperType);
method.Body.Variables.Add(redirectBridgeTmp);
ilProcessor.InsertBefore(insertPoint, ilProcessor.Create(OpCodes.Ldsfld, redirectBridge));
ilProcessor.InsertBefore(insertPoint, ilProcessor.Create(OpCodes.Stloc, redirectBridgeTmp));
ilProcessor.InsertBefore(insertPoint, ilProcessor.Create(OpCodes.Ldloc, redirectBridgeTmp));
ilProcessor.InsertBefore(insertPoint, ilProcessor.Create(OpCodes.Brfalse, insertPoint.Next));
ilProcessor.InsertBefore(insertPoint, ilProcessor.Create(OpCodes.Ldloc, redirectBridgeTmp));
}
int argPos = 0;
if (method.HasThis)
{
ilProcessor.InsertBefore(insertPoint, createLdarg(ilProcessor, 0));
argPos = 1;
}
for (int i = 0; i < method.Parameters.Count; i++)
{
ilProcessor.InsertBefore(insertPoint, createLdarg(ilProcessor, argPos++));
var ptype = method.Parameters[i].ParameterType;
if (wrapperParamerterType(ptype) != ptype && ptype.IsValueType)
{
ilProcessor.InsertBefore(insertPoint, Instruction.Create(OpCodes.Box, ptype));
}
}
ilProcessor.InsertBefore(insertPoint, Instruction.Create(OpCodes.Callvirt, redirectTo));
}
//id注入方式处理逻辑
void idAccessInject(InjectType injectType, MethodDefinition method, int methodId)
{
addRedirectIdInfo(method, methodId);
var body = method.Body;
var msIls = body.Instructions;
var ilProcessor = body.GetILProcessor();
var redirectTo = getWrapperMethod(wrapperType, anonObjOfWrapper, method, false, false);
Instruction insertPoint;
if (injectType == InjectType.Redirect)
{
msIls.Clear();
body.ExceptionHandlers.Clear();
body.Variables.Clear();
msIls.Add(Instruction.Create(OpCodes.Ret));
insertPoint = msIls[0];
}
else
{
ilProcessor.InsertBefore(msIls[0], Instruction.Create(OpCodes.Ret));
insertPoint = msIls[0];