少年修仙传客户端基础资源
client_Wu Xijin
2018-10-23 6c398e30b6ca7e83b05cab3743fde8e8e6c07d89
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
/*
 * Tencent is pleased to support the open source community by making xLua available.
 * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved.
 * Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
 * http://opensource.org/licenses/MIT
 * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
*/
 
#if HOTFIX_ENABLE
using System.Collections.Generic;
using System;
using System.Reflection;
using System.Linq;
using System.IO;
using System.Text.RegularExpressions;
 
#if XLUA_GENERAL
using Mono.Cecil;
using Mono.Cecil.Cil;
#endif
 
#if !XLUA_GENERAL
using UnityEngine;
using UnityEditor;
using UnityEditor.Callbacks;
using System.Diagnostics;
#endif
 
namespace XLua
{
    public static class HotfixConfig
    {
        //返回-1表示没有标签
        static int getHotfixType(MemberInfo memberInfo)
        {
            foreach (var ca in memberInfo.GetCustomAttributes(false))
            {
                var ca_type = ca.GetType();
                if (ca_type.ToString() == "XLua.HotfixAttribute")
                {
                    return (int)(ca_type.GetProperty("Flag").GetValue(ca, null));
                }
            }
            return -1;
        }
 
        static void mergeConfig(MemberInfo test, Type cfg_type, Func<IEnumerable<Type>> get_cfg, Action<Type, int> on_cfg)
        {
            int hotfixType = getHotfixType(test);
            if (-1 == hotfixType || !typeof(IEnumerable<Type>).IsAssignableFrom(cfg_type))
            {
                return;
            }
 
            foreach (var type in get_cfg())
            {
                if (!type.IsDefined(typeof(ObsoleteAttribute), false)
                    && !type.IsEnum && !typeof(Delegate).IsAssignableFrom(type)
                    && (!type.IsGenericType || type.IsGenericTypeDefinition))
                {
                    if ((type.Namespace == null || (type.Namespace != "XLua" && !type.Namespace.StartsWith("XLua."))))
                    {
                        on_cfg(type, hotfixType);
                    }
                }
            }
        }
 
        public static void GetConfig(Dictionary<string, int> hotfixCfg, IEnumerable<Type> cfg_check_types)
        {
            if (cfg_check_types != null)
            {
                Action<Type, int> on_cfg = (type, hotfixType) =>
                {
                    string key = type.FullName.Replace('+', '/');
                    if (!hotfixCfg.ContainsKey(key))
                    {
                        hotfixCfg.Add(key, hotfixType);
                    }
                };
                foreach (var type in cfg_check_types.Where(t => !t.IsGenericTypeDefinition && t.IsAbstract && t.IsSealed))
                {
                    var flags = BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly;
                    foreach (var field in type.GetFields(flags))
                    {
                        mergeConfig(field, field.FieldType, () => field.GetValue(null) as IEnumerable<Type>, on_cfg);
                    }
                    foreach (var prop in type.GetProperties(flags))
                    {
                        mergeConfig(prop, prop.PropertyType, () => prop.GetValue(null, null) as IEnumerable<Type>, on_cfg);
                    }
                }
            }
        }
 
        public static List<Assembly> GetHotfixAssembly()
        {
            var projectPath = Assembly.Load("Assembly-CSharp").ManifestModule.FullyQualifiedName;
            Regex rgx = new Regex(@"^(.*)[\\/]Library[\\/]ScriptAssemblies[\\/]Assembly-CSharp.dll$");
            MatchCollection matches = rgx.Matches(projectPath);
            projectPath = matches[0].Groups[1].Value;
 
            List<Type> types = new List<Type>();
            Action<Type, int> on_cfg = (type, hotfixType) =>
            {
                types.Add(type);
            };
            foreach (var type in (from assmbly in AppDomain.CurrentDomain.GetAssemblies()
                                  from type in assmbly.GetTypes() where !type.IsGenericTypeDefinition select type))
            {
                if (getHotfixType(type) != -1)
                {
                    types.Add(type);
                }
                else
                {
                    var flags = BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly;
                    foreach (var field in type.GetFields(flags))
                    {
                        mergeConfig(field, field.FieldType, () => field.GetValue(null) as IEnumerable<Type>, on_cfg);
                    }
                    foreach (var prop in type.GetProperties(flags))
                    {
                        mergeConfig(prop, prop.PropertyType, () => prop.GetValue(null, null) as IEnumerable<Type>, on_cfg);
                    }
                }
            }
            return types.Select(t => t.Assembly).Distinct()
                .Where(a => a.ManifestModule.FullyQualifiedName.IndexOf(projectPath) == 0)
                .ToList();
        }
 
        public static List<string> GetHotfixAssemblyPaths()
        {
            return GetHotfixAssembly().Select(a => a.ManifestModule.FullyQualifiedName).Distinct().ToList();
        }
    }
}
#if XLUA_GENERAL
 
namespace XLua
{
    [Flags]
    enum HotfixFlagInTool
    {
        Stateless = 0,
        Stateful = 1,
        ValueTypeBoxing = 2,
        IgnoreProperty = 4,
        IgnoreNotPublic = 8,
        Inline = 16,
        IntKey = 32
    }
 
    static class ExtentionMethods
    {
        public static bool HasFlag(this HotfixFlagInTool toCheck, HotfixFlagInTool flag)
        {
            return (toCheck != HotfixFlagInTool.Stateless) && ((toCheck & flag) == flag);
        }
 
        public static MethodReference MakeGenericMethod(this MethodReference self, params TypeReference[] arguments)
        {
            if (self.GenericParameters.Count != arguments.Length)
                throw new ArgumentException();
 
            var instance = new GenericInstanceMethod(self);
            foreach (var argument in arguments)
                instance.GenericArguments.Add(argument);
 
            return instance;
        }
 
        public static FieldReference GetGeneric(this FieldDefinition definition)
        {
            if (definition.DeclaringType.HasGenericParameters)
            {
                var declaringType = new GenericInstanceType(definition.DeclaringType);
                foreach (var parameter in definition.DeclaringType.GenericParameters)
                {
                    declaringType.GenericArguments.Add(parameter);
                }
                return new FieldReference(definition.Name, definition.FieldType, declaringType);
            }
 
            return definition;
        }
 
        public static TypeReference GetGeneric(this TypeDefinition definition)
        {
            if (definition.HasGenericParameters)
            {
                var genericInstanceType = new GenericInstanceType(definition);
                foreach (var parameter in definition.GenericParameters)
                {
                    genericInstanceType.GenericArguments.Add(parameter);
                }
                return genericInstanceType;
            }
 
            return definition;
        }
 
        public static TypeReference TryImport(this ModuleDefinition module, TypeReference type)
        {
            if (module.Assembly.FullName == type.Module.Assembly.FullName
                && module.FullyQualifiedName == type.Module.FullyQualifiedName)
            {
                return type;
            }
            else
            {
#if XLUA_GENERAL
                return module.ImportReference(type);
#else
                return module.Import(type);
#endif
            }
        }
 
        public static MethodReference TryImport(this ModuleDefinition module, MethodReference method)
        {
            if (module.Assembly.FullName == method.Module.Assembly.FullName
                && module.FullyQualifiedName == method.Module.FullyQualifiedName)
            {
                return method;
            }
            else
            {
#if XLUA_GENERAL
                return module.ImportReference(method);
#else
                return module.Import(method);
#endif
            }
        }
    }
 
    public class Hotfix
    {
        private TypeReference objType = null;
        private TypeReference delegateBridgeType = null;
        private AssemblyDefinition injectAssembly = null;
 
        private MethodReference delegateBridgeGetter = null;
        private MethodReference hotfixFlagGetter = null;
        private MethodReference invokeSessionStart = null;
        private MethodReference functionInvoke = null;
        private MethodReference invokeSessionEnd = null;
        private MethodReference invokeSessionEndWithResult = null;
        private MethodReference inParam = null;
        private MethodReference inParams = null;
        private MethodReference outParam = null;
 
        private Dictionary<string, int> hotfixCfg = null;
        private List<MethodDefinition> hotfixBridgesDef = null;
        private Dictionary<MethodDefinition, MethodDefinition> hotfixBridgeToDelegate = null;
 
        private List<MethodDefinition> bridgeIndexByKey = null;
 
        private bool isTheSameAssembly = false;
 
        private int delegateId = 0;
 
        public void Init(AssemblyDefinition injectAssembly, AssemblyDefinition xluaAssembly, IEnumerable<string> searchDirectorys, Dictionary<string, int> hotfixCfg)
        {
            isTheSameAssembly = injectAssembly == xluaAssembly;
            this.injectAssembly = injectAssembly;
            this.hotfixCfg = hotfixCfg;
            var injectModule = injectAssembly.MainModule;
            objType = injectModule.TypeSystem.Object;
 
            var delegateBridgeTypeDef = xluaAssembly.MainModule.Types.Single(t => t.FullName == "XLua.DelegateBridge");
            delegateBridgeType = injectModule.TryImport(delegateBridgeTypeDef);
            delegateBridgeGetter = injectModule.TryImport(xluaAssembly.MainModule.Types.Single(t => t.FullName == "XLua.HotfixDelegateBridge")
                .Methods.Single(m => m.Name == "Get"));
            hotfixFlagGetter = injectModule.TryImport(xluaAssembly.MainModule.Types.Single(t => t.FullName == "XLua.HotfixDelegateBridge")
                .Methods.Single(m => m.Name == "xlua_get_hotfix_flag"));
 
            //luaFunctionType = assembly.MainModule.Types.Single(t => t.FullName == "XLua.LuaFunction");
            invokeSessionStart = injectModule.TryImport(delegateBridgeTypeDef.Methods.Single(m => m.Name == "InvokeSessionStart"));
            functionInvoke = injectModule.TryImport(delegateBridgeTypeDef.Methods.Single(m => m.Name == "Invoke"));
            invokeSessionEnd = injectModule.TryImport(delegateBridgeTypeDef.Methods.Single(m => m.Name == "InvokeSessionEnd"));
            invokeSessionEndWithResult = injectModule.TryImport(delegateBridgeTypeDef.Methods.Single(m => m.Name == "InvokeSessionEndWithResult"));
            inParam = injectModule.TryImport(delegateBridgeTypeDef.Methods.Single(m => m.Name == "InParam"));
            inParams = injectModule.TryImport(delegateBridgeTypeDef.Methods.Single(m => m.Name == "InParams"));
            outParam = injectModule.TryImport(delegateBridgeTypeDef.Methods.Single(m => m.Name == "OutParam"));
 
            hotfixBridgesDef = (from method in delegateBridgeTypeDef.Methods
                              where method.Name.StartsWith("__Gen_Delegate_Imp")
                              select method).ToList();
            hotfixBridgeToDelegate = new Dictionary<MethodDefinition, MethodDefinition>();
            delegateId = 0;
 
            //hotfixBridges = hotfixBridgesDef.Select(m => injectModule.TryImport(m)).ToList();
 
            bridgeIndexByKey = new List<MethodDefinition>();
 
            var resolverOfInjectAssembly = injectAssembly.MainModule.AssemblyResolver as BaseAssemblyResolver;
            var resolverOfXluaAssembly = xluaAssembly.MainModule.AssemblyResolver as BaseAssemblyResolver;
            if (!isTheSameAssembly)
            {
                resolverOfXluaAssembly.AddSearchDirectory(Path.GetDirectoryName(injectAssembly.MainModule.FullyQualifiedName));
            }
            Action<string> addSearchDirectory = (string dir) =>
            {
                resolverOfInjectAssembly.AddSearchDirectory(dir);
                if (!isTheSameAssembly)
                {
                    resolverOfXluaAssembly.AddSearchDirectory(dir);
                }
            };
            addSearchDirectory("./Library/ScriptAssemblies/");
            foreach (var path in
                (from asm in AppDomain.CurrentDomain.GetAssemblies() select asm.ManifestModule.FullyQualifiedName)
                 .Distinct())
            {
                try
                {
                    addSearchDirectory(Path.GetDirectoryName(path));
                }
                catch(Exception)
                {
 
                }
            }
 
            if (searchDirectorys != null)
            {
                foreach(var directory in searchDirectorys.Distinct())
                {
                    addSearchDirectory(directory);
                }
            }
 
            var nameToOpcodes = typeof(OpCodes).GetFields(BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly)
                .ToDictionary(f => f.Name, f => ((OpCode)f.GetValue(null)));
            foreach(var kv in nameToOpcodes)
            {
                if (kv.Key.EndsWith("_S"))
                {
                    shortToLong[kv.Value] = nameToOpcodes[kv.Key.Substring(0, kv.Key.Length - 2)];
                }
            }
        }
 
        static string getAssemblyFullName(IMetadataScope scope)
        {
            if (scope == null) return null;
            switch(scope.MetadataScopeType)
            {
                case MetadataScopeType.ModuleDefinition:
                    {
                        ModuleDefinition md = scope as ModuleDefinition;
                        return md.Assembly.FullName;
                    }
                case MetadataScopeType.AssemblyNameReference:
                    {
                        AssemblyNameReference anr = scope as AssemblyNameReference;
                        return anr.FullName;
                    }
            }
            return null;
        }
 
        static bool isSameType(TypeReference left, TypeReference right)
        {
            if (left.FullName != right.FullName)
            {
                return false;
            }
 
            //TypeReference.Module.FullyQualifiedName不验证
            if (left.Module.Assembly.FullName == right.Module.Assembly.FullName)
            {
                return true;
            }
            else
            {
                var lafn = getAssemblyFullName(left.Scope);
                var rafn = getAssemblyFullName(right.Scope);
                if (lafn != null && lafn == rafn)
                {
                    return true;
                }
                var lr = left.Resolve();
                var rr = right.Resolve();
                if (lr == null || rr == null) return false;
                return lr.Module.Assembly.FullName == rr.Module.Assembly.FullName;
            }
        }
 
        MethodDefinition createDelegateFor(MethodDefinition method, AssemblyDefinition assembly, string delegateName, bool ignoreValueType)
        {
            var voidType = assembly.MainModule.TypeSystem.Void;
            var objectType = assembly.MainModule.TypeSystem.Object;
            var nativeIntType = assembly.MainModule.TypeSystem.IntPtr;
            var asyncResultType = assembly.MainModule.Import(typeof(IAsyncResult));
            var asyncCallbackType = assembly.MainModule.Import(typeof(AsyncCallback));
 
            Mono.Cecil.MethodAttributes delegateMethodAttributes = Mono.Cecil.MethodAttributes.Public | Mono.Cecil.MethodAttributes.HideBySig | Mono.Cecil.MethodAttributes.Virtual | Mono.Cecil.MethodAttributes.VtableLayoutMask;
 
            var delegateDef = new TypeDefinition("XLua", delegateName, Mono.Cecil.TypeAttributes.Sealed | Mono.Cecil.TypeAttributes.Public,
                    assembly.MainModule.Import(typeof(MulticastDelegate)));
            List<TypeReference> argTypes = new List<TypeReference>();
            TypeReference self = null;
            if (!method.IsStatic)
            {
                self = (!ignoreValueType && method.DeclaringType.IsValueType) ? method.DeclaringType : objType;
            }
            foreach(var parameter in method.Parameters)
            {
                bool isparam = parameter.CustomAttributes.FirstOrDefault(ca => ca.AttributeType.Name == "ParamArrayAttribute") != null;
                argTypes.Add((isparam || parameter.ParameterType.IsByReference || (!ignoreValueType && parameter.ParameterType.IsValueType)) ? parameter.ParameterType : objType);
            }
 
            var constructor = new MethodDefinition(".ctor", Mono.Cecil.MethodAttributes.Public | Mono.Cecil.MethodAttributes.HideBySig | Mono.Cecil.MethodAttributes.SpecialName | Mono.Cecil.MethodAttributes.RTSpecialName, voidType);
            constructor.Parameters.Add(new ParameterDefinition("objectInstance", Mono.Cecil.ParameterAttributes.None, objectType));
            constructor.Parameters.Add(new ParameterDefinition("functionPtr", Mono.Cecil.ParameterAttributes.None, nativeIntType));
            constructor.ImplAttributes = Mono.Cecil.MethodImplAttributes.Runtime;
            delegateDef.Methods.Add(constructor);
 
            var beginInvoke = new MethodDefinition("BeginInvoke", delegateMethodAttributes, asyncResultType);
            if (self != null)
            {
                beginInvoke.Parameters.Add(new ParameterDefinition(self));
            }
            for (int i = 0; i < argTypes.Count; i++)
            {
                beginInvoke.Parameters.Add(new ParameterDefinition(method.Parameters[i].Name, (method.Parameters[i].IsOut ? Mono.Cecil.ParameterAttributes.Out : Mono.Cecil.ParameterAttributes.None), argTypes[i]));
            }
            beginInvoke.Parameters.Add(new ParameterDefinition("callback", Mono.Cecil.ParameterAttributes.None, asyncCallbackType));
            beginInvoke.Parameters.Add(new ParameterDefinition("object", Mono.Cecil.ParameterAttributes.None, objectType));
            beginInvoke.ImplAttributes = Mono.Cecil.MethodImplAttributes.Runtime;
            delegateDef.Methods.Add(beginInvoke);
 
            var endInvoke = new MethodDefinition("EndInvoke", delegateMethodAttributes, method.ReturnType);
            for (int i = 0; i < argTypes.Count; i++)
            {
                if (argTypes[i].IsByReference)
                {
                    endInvoke.Parameters.Add(new ParameterDefinition(method.Parameters[i].Name, (method.Parameters[i].IsOut ? Mono.Cecil.ParameterAttributes.Out : Mono.Cecil.ParameterAttributes.None), argTypes[i]));
                }
            }
            endInvoke.Parameters.Add(new ParameterDefinition("result", Mono.Cecil.ParameterAttributes.None, asyncResultType));
            endInvoke.ImplAttributes = Mono.Cecil.MethodImplAttributes.Runtime;
            delegateDef.Methods.Add(endInvoke);
 
            var invoke = new MethodDefinition("Invoke", delegateMethodAttributes, method.ReturnType);
            if (self != null)
            {
                invoke.Parameters.Add(new ParameterDefinition(self));
            }
            foreach (var argType in argTypes)
            {
                invoke.Parameters.Add(new ParameterDefinition(argType));
            }
            invoke.ImplAttributes = Mono.Cecil.MethodImplAttributes.Runtime;
            delegateDef.Methods.Add(invoke);
 
            assembly.MainModule.Types.Add(delegateDef);
 
            return invoke;
        }
 
        MethodDefinition getDelegateInvokeFor(MethodDefinition method, MethodDefinition bridgeDef, bool ignoreValueType)
        {
            MethodDefinition ret;
            if (!hotfixBridgeToDelegate.TryGetValue(bridgeDef, out ret))
            {
                ret = createDelegateFor(method, injectAssembly, ("__XLua_Gen_Delegate" + (delegateId++)), ignoreValueType);
                hotfixBridgeToDelegate.Add(bridgeDef, ret);
            }
 
            return ret;
        }
 
        bool findHotfixDelegate(MethodDefinition method, out MethodReference invoke, HotfixFlagInTool hotfixType)
        {
            bool ignoreValueType = hotfixType.HasFlag(HotfixFlagInTool.ValueTypeBoxing);
 
            for (int i = 0; i < hotfixBridgesDef.Count; i++)
            {
                MethodDefinition hotfixBridgeDef = hotfixBridgesDef[i];
                var returnType = method.ReturnType;
                if (isSameType(returnType, hotfixBridgeDef.ReturnType))
                {
                    var parametersOfDelegate = hotfixBridgeDef.Parameters;
                    int compareOffset = 0;
                    if (!method.IsStatic)
                    {
                        var typeOfSelf = (!ignoreValueType && method.DeclaringType.IsValueType) ? method.DeclaringType : objType;
                        if ((parametersOfDelegate.Count == 0) || parametersOfDelegate[0].ParameterType.IsByReference || !isSameType(typeOfSelf, parametersOfDelegate[0].ParameterType))
                        {
                            continue;
                        }
                        compareOffset++;
                    }
                    if (method.Parameters.Count != (parametersOfDelegate.Count - compareOffset))
                    {
                        continue;
                    }
                    bool paramMatch = true;
                    for (int j = 0; j < method.Parameters.Count; j++)
                    {
                        var param_left = method.Parameters[j];
                        var param_right = parametersOfDelegate[compareOffset++];
                        if (param_left.IsOut != param_right.IsOut
                            || param_left.ParameterType.IsByReference != param_right.ParameterType.IsByReference)
                        {
                            paramMatch = false;
                            break;
                        }
                        if (!ignoreValueType && param_left.ParameterType.IsValueType != param_right.ParameterType.IsValueType)
                        {
                            paramMatch = false;
                            break;
                        }
                        bool isparam = param_left.CustomAttributes.FirstOrDefault(ca => ca.AttributeType.Name == "ParamArrayAttribute") != null;
                        var type_left = (isparam || param_left.ParameterType.IsByReference || (!ignoreValueType && param_left.ParameterType.IsValueType)) ? param_left.ParameterType : objType;
                        if (!isSameType(type_left, param_right.ParameterType))
                        {
                            paramMatch = false;
                            break;
                        }
                    }
 
                    if (!paramMatch)
                    {
                        continue;
                    }
                    invoke = isTheSameAssembly ? hotfixBridgeDef : getDelegateInvokeFor(method, hotfixBridgeDef, ignoreValueType);
                    return true;
                }
            }
            invoke = null;
            return false;
        }
 
        static bool hasGenericParameter(TypeReference type)
        {
            if (type.HasGenericParameters)
            {
                return true;
            }
            if (type.IsByReference)
            {
                return hasGenericParameter(((ByReferenceType)type).ElementType);
            }
            if (type.IsArray)
            {
                return hasGenericParameter(((ArrayType)type).ElementType);
            }
            if (type.IsGenericInstance)
            {
                foreach (var typeArg in ((GenericInstanceType)type).GenericArguments)
                {
                    if (hasGenericParameter(typeArg))
                    {
                        return true;
                    }
                }
                return false;
            }
            return type.IsGenericParameter;
        }
 
        static bool hasGenericParameter(MethodDefinition method)
        {
            if (method.HasGenericParameters) return true;
            if (!method.IsStatic && hasGenericParameter(method.DeclaringType)) return true;
            if (hasGenericParameter(method.ReturnType)) return true;
            foreach(var paramInfo in method.Parameters)
            {
                if (hasGenericParameter(paramInfo.ParameterType)) return true;
            }
            return false;
        }
 
        static bool isNoPublic(TypeReference type)
        {
            if (type.IsByReference)
            {
                return isNoPublic(((ByReferenceType)type).ElementType);
            }
            if (type.IsArray)
            {
                return isNoPublic(((ArrayType)type).ElementType);
            }
            else
            {
                if (type.IsGenericInstance)
                {
                    foreach (var typeArg in ((GenericInstanceType)type).GenericArguments)
                    {
                        if (isNoPublic(typeArg))
                        {
                            return true;
                        }
                    }
                }
 
                var resolveType = type.Resolve();
                if ((!type.IsNested && !resolveType.IsPublic) || (type.IsNested && !resolveType.IsNestedPublic))
                {
                    return true;
                }
                if (type.IsNested)
                {
                    var parent = type.DeclaringType;
                    while (parent != null)
                    {
                        var resolveParent = parent.Resolve();
                        if ((!parent.IsNested && !resolveParent.IsPublic) || (parent.IsNested && !resolveParent.IsNestedPublic))
                        {
                            return true;
                        }
                        if (parent.IsNested)
                        {
                            parent = parent.DeclaringType;
                        }
                        else
                        {
                            break;
                        }
                    }
                }
                return false;
            }
 
        }
 
        static bool genericInOut(MethodDefinition method, HotfixFlagInTool hotfixType)
        {
            bool ignoreValueType = hotfixType.HasFlag(HotfixFlagInTool.ValueTypeBoxing);
 
            if (hasGenericParameter(method.ReturnType) || isNoPublic(method.ReturnType))
            {
                return true;
            }
            var parameters = method.Parameters;
 
            if (!method.IsStatic 
                && (hasGenericParameter(method.DeclaringType) || ((!ignoreValueType && method.DeclaringType.IsValueType) && isNoPublic(method.DeclaringType))))
            {
                    return true;
            }
            for (int i = 0; i < parameters.Count; i++)
            {
                if ( hasGenericParameter(parameters[i].ParameterType) || (((!ignoreValueType && parameters[i].ParameterType.IsValueType) || parameters[i].ParameterType.IsByReference || parameters[i].CustomAttributes.Any(ca => ca.AttributeType.FullName == "System.ParamArrayAttribute")) && isNoPublic(parameters[i].ParameterType)))
                {
                    return true;
                }
            }
            return false;
        }
 
        public bool InjectType(TypeReference hotfixAttributeType, TypeDefinition type)
        {
            foreach(var nestedTypes in type.NestedTypes)
            {
                if (!InjectType(hotfixAttributeType, nestedTypes))
                {
                    return false;
                }
            }
            if (type.Name.Contains("<") || type.IsInterface || type.Methods.Count == 0) // skip anonymous type and interface
            {
                return true;
            }
            CustomAttribute hotfixAttr = type.CustomAttributes.FirstOrDefault(ca => ca.AttributeType == hotfixAttributeType);
            HotfixFlagInTool hotfixType;
            if (hotfixAttr != null)
            {
                hotfixType = (HotfixFlagInTool)(int)hotfixAttr.ConstructorArguments[0].Value;
            }
            else
            {
                if (!hotfixCfg.ContainsKey(type.FullName))
                {
                    return true;
                }
                hotfixType = (HotfixFlagInTool)hotfixCfg[type.FullName];
            }
 
            bool ignoreProperty = hotfixType.HasFlag(HotfixFlagInTool.IgnoreProperty);
            bool ignoreNotPublic = hotfixType.HasFlag(HotfixFlagInTool.IgnoreNotPublic);
            bool isInline = hotfixType.HasFlag(HotfixFlagInTool.Inline);
            bool isIntKey = hotfixType.HasFlag(HotfixFlagInTool.IntKey);
            if (isIntKey && type.HasGenericParameters)
            {
                throw new InvalidOperationException(type.FullName + " is generic definition, can not be mark as IntKey!");
            }
            //isIntKey = !type.HasGenericParameters;
 
            foreach (var method in type.Methods)
            {
                if (ignoreNotPublic && !method.IsPublic)
                {
                    continue;
                }
                if (ignoreProperty && method.IsSpecialName && (method.Name.StartsWith("get_") || method.Name.StartsWith("set_")))
                {
                    continue;
                }
                if (method.Name != ".cctor" && !method.IsAbstract && !method.IsPInvokeImpl && method.Body != null && !method.Name.Contains("<"))
                {
                    //Debug.Log(method);
                    if ((isInline || method.HasGenericParameters || genericInOut(method, hotfixType)) 
                        ? !injectGenericMethod(method, hotfixType) :
                        !injectMethod(method, hotfixType))
                    {
                        return false;
                    }
                }
            }
 
            List<MethodDefinition> toAdd = new List<MethodDefinition>();
            foreach (var method in type.Methods)
            {
                if (ignoreNotPublic && !method.IsPublic)
                {
                    continue;
                }
                if (ignoreProperty && method.IsSpecialName && (method.Name.StartsWith("get_") || method.Name.StartsWith("set_")))
                {
                    continue;
                }
                if (method.Name != ".cctor" && !method.IsAbstract && !method.IsPInvokeImpl && method.Body != null && !method.Name.Contains("<"))
                {
                    var proxyMethod = tryAddBaseProxy(type, method);
                    if (proxyMethod != null) toAdd.Add(proxyMethod);
                }
            }
 
            foreach(var md in toAdd)
            {
                type.Methods.Add(md);
            }
 
            return true;
        }
 
#if !XLUA_GENERAL
        [PostProcessScene]
        [MenuItem("XLua/Hotfix Inject In Editor", false, 3)]
        public static void HotfixInject()
        {
            if (EditorApplication.isCompiling || Application.isPlaying)
            {
                return;
            }
            var hotfixCfg = new Dictionary<string, int>();
            HotfixConfig.GetConfig(hotfixCfg, Utils.GetAllTypes());
            var xluaAssemblyPath = typeof(LuaEnv).Module.FullyQualifiedName;
            var idMapFileName = CSObjectWrapEditor.GeneratorConfig.common_path + "Resources/hotfix_id_map.lua.txt";
            var injectAssemblyPaths = HotfixConfig.GetHotfixAssemblyPaths();
 
            foreach (var injectAssemblyPath in injectAssemblyPaths)
            {
                Info("injecting " + injectAssemblyPath);
                if (injectAssemblyPaths.Count > 1)
                {
                    var injectAssemblyFileName = Path.GetFileName(injectAssemblyPath);
                    idMapFileName = CSObjectWrapEditor.GeneratorConfig.common_path + "Resources/hotfix_id_map_" + injectAssemblyFileName.Substring(0, injectAssemblyFileName.Length - 4) + ".lua.txt";
                }
                HotfixInject(injectAssemblyPath, xluaAssemblyPath, null, idMapFileName, hotfixCfg);
            }
            AssetDatabase.Refresh();
        }
#endif
 
        static AssemblyDefinition readAssembly(string assemblyPath)
        {
#if HOTFIX_SYMBOLS_DISABLE
            return AssemblyDefinition.ReadAssembly(assemblyPath);
#else
            if (File.Exists(assemblyPath + ".mdb"))
            {
                var readerParameters = new ReaderParameters { ReadSymbols = true };
                return AssemblyDefinition.ReadAssembly(assemblyPath, readerParameters);
            }
            else
            {
                return AssemblyDefinition.ReadAssembly(assemblyPath);
            }
#endif
        }
 
        static void writeAssembly(AssemblyDefinition assembly, string assemblyPath)
        {
#if HOTFIX_SYMBOLS_DISABLE
            assembly.Write(assemblyPath);
#else
            if (File.Exists(assemblyPath + ".mdb"))
            {
                var writerParameters = new WriterParameters { WriteSymbols = true };
                assembly.Write(assemblyPath, writerParameters);
            }
            else
            {
                assembly.Write(assemblyPath);
            }
#endif
        }
 
        public static void HotfixInject(string injectAssemblyPath, string xluaAssemblyPath, IEnumerable<string> searchDirectorys, string idMapFilePath, Dictionary<string, int> hotfixConfig)
        {
            AssemblyDefinition injectAssembly = null;
            AssemblyDefinition xluaAssembly = null;
            try
            {
                injectAssembly = readAssembly(injectAssemblyPath);
                
                // injected flag check
                if (injectAssembly.MainModule.Types.Any(t => t.Name == "__XLUA_GEN_FLAG"))
                {
                    Info(injectAssemblyPath + " had injected!");
                    return;
                }
                injectAssembly.MainModule.Types.Add(new TypeDefinition("__XLUA_GEN", "__XLUA_GEN_FLAG", Mono.Cecil.TypeAttributes.Class,
                    injectAssembly.MainModule.TypeSystem.Object));
 
                xluaAssembly = (injectAssemblyPath == xluaAssemblyPath || injectAssembly.MainModule.FullyQualifiedName == xluaAssemblyPath) ? 
                    injectAssembly : readAssembly(xluaAssemblyPath);
 
                Hotfix hotfix = new Hotfix();
                hotfix.Init(injectAssembly, xluaAssembly, searchDirectorys, hotfixConfig);
 
                //var hotfixDelegateAttributeType = assembly.MainModule.Types.Single(t => t.FullName == "XLua.HotfixDelegateAttribute");
                var hotfixAttributeType = xluaAssembly.MainModule.Types.Single(t => t.FullName == "XLua.HotfixAttribute");
                var toInject = (from module in injectAssembly.Modules from type in module.Types select type).ToList();
                foreach (var type in toInject)
                {
                    if (!hotfix.InjectType(hotfixAttributeType, type))
                    {
                        return;
                    }
                }
                Directory.CreateDirectory(Path.GetDirectoryName(idMapFilePath));
                hotfix.OutputIntKeyMapper(new FileStream(idMapFilePath, FileMode.Create, FileAccess.Write));
                File.Copy(idMapFilePath, idMapFilePath + "." + DateTime.Now.ToString("yyyyMMddHHmmssfff"));
 
                writeAssembly(injectAssembly, injectAssemblyPath);
                Info(injectAssemblyPath + " inject finish!");
            }
            catch(Exception e)
            {
                Error(injectAssemblyPath + " inject Exception! " + e);
            }
            finally
            {
                if (injectAssembly != null)
                {
                    Clean(injectAssembly);
                }
                if (xluaAssembly != null)
                {
                    Clean(xluaAssembly);
                }
            }
        }
 
        static void Info(string info)
        {
#if XLUA_GENERAL
            System.Console.WriteLine(info);
#else
            UnityEngine.Debug.Log(info);
#endif
        }
 
        static void Error(string info)
        {
#if XLUA_GENERAL
            System.Console.WriteLine("Error:" + info);
#else
            UnityEngine.Debug.LogError(info);
#endif
        }
 
        static void Clean(AssemblyDefinition assembly)
        {
            if (assembly.MainModule.SymbolReader != null)
            {
                assembly.MainModule.SymbolReader.Dispose();
            }
        }
 
        static OpCode[] ldargs = new OpCode[] { OpCodes.Ldarg_0, OpCodes.Ldarg_1, OpCodes.Ldarg_2, OpCodes.Ldarg_3 };
 
        static readonly int MAX_OVERLOAD = 100;
 
        static string getDelegateName(MethodDefinition method)
        {
            string fieldName = method.Name;
            if (fieldName.StartsWith("."))
            {
                fieldName = fieldName.Substring(1);
            }
            string ccFlag = method.IsConstructor ? "_c" : "";
            string luaDelegateName = null;
            var type = method.DeclaringType;
            for (int i = 0; i < MAX_OVERLOAD; i++)
            {
                string tmp = ccFlag + "__Hotfix" + i + "_" + fieldName;
                if (!type.Fields.Any(f => f.Name == tmp)) // injected
                {
                    luaDelegateName = tmp;
                    break;
                }
            }
            return luaDelegateName;
        }
 
        static Instruction findNextRet(Mono.Collections.Generic.Collection<Instruction> instructions, Instruction pos)
        {
            bool posFound = false;
            for(int i = 0; i < instructions.Count; i++)
            {
                if (posFound && instructions[i].OpCode == OpCodes.Ret)
                {
                    return instructions[i];
                }
                else if (instructions[i] == pos)
                {
                    posFound = true;
                }
            }
            return null;
        }
 
        Dictionary<OpCode, OpCode> shortToLong = new Dictionary<OpCode, OpCode>();
 
        void fixBranch(ILProcessor processor, Mono.Collections.Generic.Collection<Instruction> instructions, Dictionary<Instruction, Instruction> originToNewTarget, HashSet<Instruction> noCheck)
        {
            foreach(var instruction in instructions)
            {
                Instruction target = instruction.Operand as Instruction;
                if (target != null && !noCheck.Contains(instruction))
                {
                    if (originToNewTarget.ContainsKey(target))
                    {
                        instruction.Operand = originToNewTarget[target];
                    }
                }
            }
            for (int i = 0; i < instructions.Count; i++)
            {
                var instruction = instructions[i];
                Instruction target = instruction.Operand as Instruction;
                
                if (target != null)
                {
                    int diff = target.Offset - instruction.Offset;
                    if ((diff > sbyte.MaxValue || diff < sbyte.MinValue) && shortToLong.ContainsKey(instruction.OpCode))
                    {
                        instructions[i] = processor.Create(shortToLong[instruction.OpCode], target);
                    }
                }
            }
        }
 
        static MethodDefinition findOverride(TypeDefinition type, MethodReference vmethod)
        {
            foreach (var method in type.Methods)
            {
                if (method.Name == vmethod.Name && method.IsVirtual && !method.IsAbstract && (method.ReturnType.FullName == vmethod.ReturnType.FullName) && method.Parameters.Count == vmethod.Parameters.Count)
                {
                    bool isParamsMatch = true;
                    for (int i = 0; i < method.Parameters.Count; i++)
                    {
                        if (method.Parameters[i].Attributes != vmethod.Parameters[i].Attributes
                            || (method.Parameters[i].ParameterType.FullName != vmethod.Parameters[i].ParameterType.FullName))
                        {
                            isParamsMatch = false;
                            break;
                        }
                    }
                    if (isParamsMatch) return method;
                }
            }
            return null;
        }
 
        static MethodReference _findBase(TypeReference type, MethodDefinition method)
        {
            TypeDefinition td = type.Resolve();
            if (td == null)
            {
                return null;
            }
            //if (type.IsGenericInstance && 
            //    (method.Module.Assembly.FullName != type.Module.Assembly.FullName || method.Module.Assembly.FullName != td.Module.Assembly.FullName
            //    || method.Module.FullyQualifiedName != type.Module.FullyQualifiedName || method.Module.FullyQualifiedName != td.Module.FullyQualifiedName))
            //{
            //    return _findBase(td.BaseType, method);
            //}
            var m = findOverride(td, method);
            if (m != null)
            {
                if (type.IsGenericInstance)
                {
                    var reference = new MethodReference(m.Name, tryImport(method.DeclaringType, m.ReturnType), tryImport(method.DeclaringType, type))
                    {
                        HasThis = m.HasThis,
                        ExplicitThis = m.ExplicitThis,
                        CallingConvention = m.CallingConvention
                    };
                    foreach (var parameter in m.Parameters)
                        reference.Parameters.Add(new ParameterDefinition(tryImport(method.DeclaringType, parameter.ParameterType)));
                    foreach (var generic_parameter in m.GenericParameters)
                        reference.GenericParameters.Add(new GenericParameter(generic_parameter.Name, reference));
                    return reference;
                }
                else
                {
                    return m;
                }
            }
            return _findBase(td.BaseType, method);
        }
 
        static MethodReference findBase(TypeDefinition type, MethodDefinition method)
        {
            if (method.IsVirtual && !method.IsNewSlot) //表明override
            {
                try
                {
                    if (hasGenericParameter(method)) return null;
                    var b = _findBase(type.BaseType, method);
                    try
                    {
                        if (hasGenericParameter(b.Resolve())) return null;
                    }catch { }
                    return b;
                }
                catch { }
            }
            return null;
        }
 
        const string BASE_RPOXY_PERFIX = "<>xLuaBaseProxy_";
 
        static TypeReference tryImport(TypeReference type, TypeReference toImport)
        {
            if (type.Module.Assembly.FullName == toImport.Module.Assembly.FullName
                && type.Module.FullyQualifiedName == toImport.Module.FullyQualifiedName)
            {
                return toImport;
            }
            else
            {
#if XLUA_GENERAL
                return type.Module.ImportReference(toImport);
#else
                return type.Module.Import(toImport);
#endif
            }
        }
 
        static MethodReference tryImport(TypeReference type, MethodReference toImport)
        {
            if (type.Module.Assembly.FullName == toImport.Module.Assembly.FullName
                && type.Module.FullyQualifiedName == toImport.Module.FullyQualifiedName)
            {
                return toImport;
            }
            else
            {
#if XLUA_GENERAL
                return type.Module.ImportReference(toImport);
#else
                return type.Module.Import(toImport);
#endif
            }
        }
 
        static MethodDefinition tryAddBaseProxy(TypeDefinition type, MethodDefinition method)
        {
            var mbase = findBase(type, method);
            if (mbase != null)
            {
                var proxyMethod = new MethodDefinition(BASE_RPOXY_PERFIX + method.Name, Mono.Cecil.MethodAttributes.Private, tryImport(type, method.ReturnType));
                for (int i = 0; i < method.Parameters.Count; i++)
                {
                    proxyMethod.Parameters.Add(new ParameterDefinition("P" + i, method.Parameters[i].IsOut ? Mono.Cecil.ParameterAttributes.Out : Mono.Cecil.ParameterAttributes.None, tryImport(type, method.Parameters[i].ParameterType)));
                }
                var instructions = proxyMethod.Body.Instructions;
                var processor = proxyMethod.Body.GetILProcessor();
                int paramCount = method.Parameters.Count + 1;
                for (int i = 0; i < paramCount; i++)
                {
                    if (i < ldargs.Length)
                    {
                        instructions.Add(processor.Create(ldargs[i]));
                    }
                    else if (i < 256)
                    {
                        instructions.Add(processor.Create(OpCodes.Ldarg_S, (byte)i));
                    }
                    else
                    {
                        instructions.Add(processor.Create(OpCodes.Ldarg, (short)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, tryImport(type, mbase)));
                instructions.Add(Instruction.Create(OpCodes.Ret));
                return proxyMethod;
            }
            return null;
        }
 
        bool injectMethod(MethodDefinition method, HotfixFlagInTool hotfixType)
        {
            var type = method.DeclaringType;
            
            bool isFinalize = (method.Name == "Finalize" && method.IsSpecialName);
 
            MethodReference invoke = null;
 
            int param_count = method.Parameters.Count + (method.IsStatic ? 0 : 1);
 
            if (!findHotfixDelegate(method, out invoke, hotfixType))
            {
                Error("can not find delegate for " + method.DeclaringType + "." + method.Name + "! try re-genertate code.");
                return false;
            }
 
            if (invoke == null)
            {
                throw new Exception("unknow exception!");
            }
 
#if XLUA_GENERAL
            invoke = injectAssembly.MainModule.ImportReference(invoke);
#else
            invoke = injectAssembly.MainModule.Import(invoke);
#endif
 
            FieldReference fieldReference = null;
            VariableDefinition injection = null;
            bool isIntKey = hotfixType.HasFlag(HotfixFlagInTool.IntKey) && !type.HasGenericParameters && isTheSameAssembly;
            //isIntKey = !type.HasGenericParameters;
 
            if (!isIntKey)
            {
                injection = new VariableDefinition(invoke.DeclaringType);
                method.Body.Variables.Add(injection);
 
                var luaDelegateName = getDelegateName(method);
                if (luaDelegateName == null)
                {
                    Error("too many overload!");
                    return false;
                }
 
                FieldDefinition fieldDefinition = new FieldDefinition(luaDelegateName, Mono.Cecil.FieldAttributes.Static | Mono.Cecil.FieldAttributes.Private,
                    invoke.DeclaringType);
                type.Fields.Add(fieldDefinition);
                fieldReference = fieldDefinition.GetGeneric();
            }
 
            bool ignoreValueType = hotfixType.HasFlag(HotfixFlagInTool.ValueTypeBoxing);
 
            var insertPoint = method.Body.Instructions[0];
            var processor = method.Body.GetILProcessor();
 
            if (method.IsConstructor)
            {
                insertPoint = findNextRet(method.Body.Instructions, insertPoint);
            }
 
            Dictionary<Instruction, Instruction> originToNewTarget = new Dictionary<Instruction, Instruction>();
            HashSet<Instruction> noCheck = new HashSet<Instruction>();
 
            while (insertPoint != null)
            {
                Instruction firstInstruction;
                if (isIntKey)
                {
                    firstInstruction = processor.Create(OpCodes.Ldc_I4, bridgeIndexByKey.Count);
                    processor.InsertBefore(insertPoint, firstInstruction);
                    processor.InsertBefore(insertPoint, processor.Create(OpCodes.Call, hotfixFlagGetter));
                }
                else
                {
                    firstInstruction = processor.Create(OpCodes.Ldsfld, fieldReference);
                    processor.InsertBefore(insertPoint, firstInstruction);
                    processor.InsertBefore(insertPoint, processor.Create(OpCodes.Stloc, injection));
                    processor.InsertBefore(insertPoint, processor.Create(OpCodes.Ldloc, injection));
                }
 
                var jmpInstruction = processor.Create(OpCodes.Brfalse, insertPoint);
                processor.InsertBefore(insertPoint, jmpInstruction);
 
                if (isIntKey)
                {
                    processor.InsertBefore(insertPoint, processor.Create(OpCodes.Ldc_I4, bridgeIndexByKey.Count));
                    processor.InsertBefore(insertPoint, processor.Create(OpCodes.Call, delegateBridgeGetter));
                }
                else
                {
                    processor.InsertBefore(insertPoint, processor.Create(OpCodes.Ldloc, injection));
                }
 
                for (int i = 0; i < param_count; i++)
                {
                    if (i < ldargs.Length)
                    {
                        processor.InsertBefore(insertPoint, processor.Create(ldargs[i]));
                    }
                    else if (i < 256)
                    {
                        processor.InsertBefore(insertPoint, processor.Create(OpCodes.Ldarg_S, (byte)i));
                    }
                    else
                    {
                        processor.InsertBefore(insertPoint, processor.Create(OpCodes.Ldarg, (short)i));
                    }
                    if (i == 0 && !method.IsStatic && type.IsValueType)
                    {
                        processor.InsertBefore(insertPoint, processor.Create(OpCodes.Ldobj, type));
                        
                    }
                    if (ignoreValueType)
                    {
                        TypeReference paramType;
                        if (method.IsStatic)
                        {
                            paramType = method.Parameters[i].ParameterType;
                        }
                        else
                        {
                            paramType = (i == 0) ? type : method.Parameters[i - 1].ParameterType;
                        }
                        if (paramType.IsValueType)
                        {
                            processor.InsertBefore(insertPoint, processor.Create(OpCodes.Box, paramType));
                        }
                    }
                }
 
                processor.InsertBefore(insertPoint, processor.Create(OpCodes.Call, invoke));
 
                if (!method.IsConstructor && !isFinalize)
                {
                    processor.InsertBefore(insertPoint, processor.Create(OpCodes.Ret));
                }
 
                if (!method.IsConstructor)
                {
                    break;
                }
                else
                {
                    originToNewTarget[insertPoint] = firstInstruction;
                    noCheck.Add(jmpInstruction);
                }
                insertPoint = findNextRet(method.Body.Instructions, insertPoint);
            }
 
            if (method.IsConstructor)
            {
                fixBranch(processor, method.Body.Instructions, originToNewTarget, noCheck);
            }
 
            if (isFinalize)
            {
                if (method.Body.ExceptionHandlers.Count == 0)
                {
                    throw new InvalidProgramException("Finalize has not try-catch? Type :" + method.DeclaringType);
                }
                method.Body.ExceptionHandlers[0].TryStart = method.Body.Instructions[0];
            }
            if (isIntKey)
            {
                bridgeIndexByKey.Add(method);
            }
            return true;
        }
 
        bool injectGenericMethod(MethodDefinition method, HotfixFlagInTool hotfixType)
        {
            var type = method.DeclaringType;
            
            bool isFinalize = (method.Name == "Finalize" && method.IsSpecialName);
            bool isIntKey = hotfixType.HasFlag(HotfixFlagInTool.IntKey) && !type.HasGenericParameters;
            //isIntKey = !type.HasGenericParameters;
 
            FieldReference fieldReference = null;
            VariableDefinition injection = null;
            if (!isIntKey)
            {
                var luaDelegateName = getDelegateName(method);
                if (luaDelegateName == null)
                {
                    Error("too many overload!");
                    return false;
                }
 
                FieldDefinition fieldDefinition = new FieldDefinition(luaDelegateName, Mono.Cecil.FieldAttributes.Static | Mono.Cecil.FieldAttributes.Private,
                    delegateBridgeType);
                type.Fields.Add(fieldDefinition);
 
                fieldReference = fieldDefinition.GetGeneric();
            }
 
            injection = new VariableDefinition(delegateBridgeType);
            method.Body.Variables.Add(injection);
 
            int param_start = method.IsStatic ? 0 : 1;
            int param_count = method.Parameters.Count + param_start;
            var insertPoint = method.Body.Instructions[0];
            var processor = method.Body.GetILProcessor();
 
            if (method.IsConstructor)
            {
                insertPoint = findNextRet(method.Body.Instructions, insertPoint);
            }
 
            Dictionary<Instruction, Instruction> originToNewTarget = new Dictionary<Instruction, Instruction>();
            HashSet<Instruction> noCheck = new HashSet<Instruction>();
 
            while (insertPoint != null)
            {
                Instruction firstInstruction;
                Instruction jmpInstruction;
                if (isIntKey)
                {
                    firstInstruction = processor.Create(OpCodes.Ldc_I4, bridgeIndexByKey.Count);
                    processor.InsertBefore(insertPoint, firstInstruction);
                    processor.InsertBefore(insertPoint, processor.Create(OpCodes.Call, hotfixFlagGetter));
                    jmpInstruction = processor.Create(OpCodes.Brfalse, insertPoint);
                    processor.InsertBefore(insertPoint, jmpInstruction);
                    processor.InsertBefore(insertPoint, processor.Create(OpCodes.Ldc_I4, bridgeIndexByKey.Count));
                    processor.InsertBefore(insertPoint, processor.Create(OpCodes.Call, delegateBridgeGetter));
                    processor.InsertBefore(insertPoint, processor.Create(OpCodes.Stloc, injection));
                }
                else
                {
                    firstInstruction = processor.Create(OpCodes.Ldsfld, fieldReference);
                    processor.InsertBefore(insertPoint, firstInstruction);
                    processor.InsertBefore(insertPoint, processor.Create(OpCodes.Stloc, injection));
                    processor.InsertBefore(insertPoint, processor.Create(OpCodes.Ldloc, injection));
                    jmpInstruction = processor.Create(OpCodes.Brfalse, insertPoint);
                    processor.InsertBefore(insertPoint, jmpInstruction);
                }
 
                processor.InsertBefore(insertPoint, processor.Create(OpCodes.Ldloc, injection));
 
                processor.InsertBefore(insertPoint, processor.Create(OpCodes.Callvirt, invokeSessionStart));
 
                TypeReference returnType = method.ReturnType;
 
                bool isVoid = returnType.FullName == "System.Void";
 
                int outCout = 0;
 
                for (int i = 0; i < param_count; i++)
                {
                    if (i == 0 && !method.IsStatic)
                    {
                        processor.InsertBefore(insertPoint, processor.Create(OpCodes.Ldloc, injection));
                        processor.InsertBefore(insertPoint, processor.Create(OpCodes.Ldarg_0));
                        if (type.IsValueType)
                        {
                            processor.InsertBefore(insertPoint, processor.Create(OpCodes.Ldobj, method.DeclaringType.GetGeneric()));
                        }
                        processor.InsertBefore(insertPoint, processor.Create(OpCodes.Callvirt, inParam.MakeGenericMethod(method.DeclaringType.GetGeneric())));
                    }
                    else
                    {
                        var param = method.Parameters[i - param_start];
                        if (param.ParameterType.IsByReference)
                        {
                            outCout++;
                        }
                        if (!param.IsOut)
                        {
                            processor.InsertBefore(insertPoint, processor.Create(OpCodes.Ldloc, injection));
 
                            if (i < ldargs.Length)
                            {
                                processor.InsertBefore(insertPoint, processor.Create(ldargs[i]));
                            }
                            else if (i < 256)
                            {
                                processor.InsertBefore(insertPoint, processor.Create(OpCodes.Ldarg_S, (byte)i));
                            }
                            else
                            {
                                processor.InsertBefore(insertPoint, processor.Create(OpCodes.Ldarg, (short)i));
                            }
 
                            var paramType = param.ParameterType;
 
                            if (param.ParameterType.IsByReference)
                            {
                                paramType = ((ByReferenceType)paramType).ElementType;
                                if (paramType.IsValueType || paramType.IsGenericParameter)
                                {
                                    processor.InsertBefore(insertPoint, processor.Create(OpCodes.Ldobj, paramType));
                                }
                                else
                                {
                                    processor.InsertBefore(insertPoint, processor.Create(OpCodes.Ldind_Ref));
                                }
                            }
                            if (i == param_count - 1 && param.CustomAttributes.Any(ca => ca.AttributeType.FullName == "System.ParamArrayAttribute"))
                            {
                                processor.InsertBefore(insertPoint, processor.Create(OpCodes.Callvirt, inParams.MakeGenericMethod(((ArrayType)paramType).ElementType)));
                            }
                            else
                            {
                                processor.InsertBefore(insertPoint, processor.Create(OpCodes.Callvirt, inParam.MakeGenericMethod(paramType)));
                            }
                        }
                    }
                }
 
                int outStart = (isVoid ? 0 : 1);
 
                processor.InsertBefore(insertPoint, processor.Create(OpCodes.Ldloc, injection));
                processor.InsertBefore(insertPoint, processor.Create(OpCodes.Ldc_I4, outCout + outStart));
                processor.InsertBefore(insertPoint, processor.Create(OpCodes.Callvirt, functionInvoke));
 
                int outPos = outStart;
                for (int i = 0; i < method.Parameters.Count; i++)
                {
                    if (method.Parameters[i].ParameterType.IsByReference)
                    {
                        processor.InsertBefore(insertPoint, processor.Create(OpCodes.Ldloc, injection));
                        processor.InsertBefore(insertPoint, processor.Create(OpCodes.Ldc_I4, outPos));
                        int arg_pos = param_start + i;
                        if (arg_pos < ldargs.Length)
                        {
                            processor.InsertBefore(insertPoint, processor.Create(ldargs[arg_pos]));
                        }
                        else if (arg_pos < 256)
                        {
                            processor.InsertBefore(insertPoint, processor.Create(OpCodes.Ldarg_S, (byte)arg_pos));
                        }
                        else
                        {
                            processor.InsertBefore(insertPoint, processor.Create(OpCodes.Ldarg, (short)arg_pos));
                        }
                        processor.InsertBefore(insertPoint, processor.Create(OpCodes.Callvirt, outParam.MakeGenericMethod(
                            ((ByReferenceType)method.Parameters[i].ParameterType).ElementType)));
                        outPos++;
                    }
                }
 
                processor.InsertBefore(insertPoint, processor.Create(OpCodes.Ldloc, injection));
                if (isVoid)
                {
                    processor.InsertBefore(insertPoint, processor.Create(OpCodes.Callvirt, invokeSessionEnd));
                }
                else
                {
                    processor.InsertBefore(insertPoint, processor.Create(OpCodes.Callvirt, invokeSessionEndWithResult.MakeGenericMethod(returnType)));
                }
 
                if (!method.IsConstructor && !isFinalize)
                {
                    processor.InsertBefore(insertPoint, processor.Create(OpCodes.Ret));
                }
 
                if (!method.IsConstructor)
                {
                    break;
                }
                else
                {
                    originToNewTarget[insertPoint] = firstInstruction;
                    noCheck.Add(jmpInstruction);
                }
 
                insertPoint = findNextRet(method.Body.Instructions, insertPoint);
            }
 
            if (method.IsConstructor)
            {
                fixBranch(processor, method.Body.Instructions, originToNewTarget, noCheck);
            }
 
            if (isFinalize)
            {
                method.Body.ExceptionHandlers[0].TryStart = method.Body.Instructions[0];
            }
 
            if (isIntKey)
            {
                bridgeIndexByKey.Add(method);
            }
 
            return true;
        }
 
        public void OutputIntKeyMapper(Stream output)
        {
            using (StreamWriter writer = new StreamWriter(output))
            {
                writer.WriteLine("return {");
                var data = bridgeIndexByKey
                    .Select((md, idx) => new { Method = md, Index = idx})
                    .GroupBy(info => info.Method.DeclaringType)
                    .ToDictionary(group => group.Key, group =>
                    {
                        return group.GroupBy(info => info.Method.Name).ToDictionary(group_by_name => group_by_name.Key, group_by_name => group_by_name.Select(info => info.Index.ToString()).ToArray());
                    });
                foreach(var kv in data)
                {
                    writer.WriteLine("    [\"" + kv.Key.FullName.Replace('/', '+') + "\"] = {");
                    foreach(var kv2 in kv.Value)
                    {
                        writer.WriteLine("        [\"" + kv2.Key + "\"] = {");
                        writer.WriteLine("            " + string.Join(",", kv2.Value));
                        writer.WriteLine("        },");
                    }
                    writer.WriteLine("    },");
                }
                writer.WriteLine("}");
            }
        }
    }
}
#else
 
namespace XLua
{
    public static class Hotfix
    {
        [PostProcessScene]
        [MenuItem("XLua/Hotfix Inject In Editor", false, 3)]
        public static void HotfixInject()
        {
            if (EditorApplication.isCompiling || Application.isPlaying)
            {
                return;
            }
 
#if UNITY_EDITOR_OSX
            var mono_path = Path.Combine(Path.GetDirectoryName(typeof(UnityEngine.Debug).Module.FullyQualifiedName),
                "../MonoBleedingEdge/bin/mono");
            if(!File.Exists(mono_path))
            {
                mono_path = Path.Combine(Path.GetDirectoryName(typeof(UnityEngine.Debug).Module.FullyQualifiedName),
                    "../../MonoBleedingEdge/bin/mono");
            }
            if(!File.Exists(mono_path))
            {
                UnityEngine.Debug.LogError("can not find mono!");
            }
#elif UNITY_EDITOR_WIN
            var mono_path = Path.Combine(Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName),
                "Data/MonoBleedingEdge/bin/mono.exe");
#endif
            var inject_tool_path = "./Tools/XLuaHotfixInject.exe";
            if (!File.Exists(inject_tool_path))
            {
                UnityEngine.Debug.LogError("please install the Tools");
                return;
            }
 
            var assembly_csharp_path = "./Library/ScriptAssemblies/Assembly-CSharp.dll";
            var id_map_file_path = CSObjectWrapEditor.GeneratorConfig.common_path + "Resources/hotfix_id_map.lua.txt";
            var hotfix_cfg_in_editor = CSObjectWrapEditor.GeneratorConfig.common_path + "hotfix_cfg_in_editor.data";
 
            Dictionary<string, int> editor_cfg = new Dictionary<string, int>();
            Assembly editor_assembly = typeof(Hotfix).Assembly;
            HotfixConfig.GetConfig(editor_cfg, Utils.GetAllTypes().Where(t => t.Assembly == editor_assembly));
 
            if (!Directory.Exists(CSObjectWrapEditor.GeneratorConfig.common_path))
            {
                Directory.CreateDirectory(CSObjectWrapEditor.GeneratorConfig.common_path);
            }
            
            using (BinaryWriter writer = new BinaryWriter(new FileStream(hotfix_cfg_in_editor, FileMode.Create, FileAccess.Write)))
            {
                writer.Write(editor_cfg.Count);
                foreach(var kv in editor_cfg)
                {
                    writer.Write(kv.Key);
                    writer.Write(kv.Value);
                }
            }
 
            List<string> args = new List<string>() { inject_tool_path, assembly_csharp_path, typeof(LuaEnv).Module.FullyQualifiedName, id_map_file_path, hotfix_cfg_in_editor};
 
            foreach (var path in
                (from asm in AppDomain.CurrentDomain.GetAssemblies() select asm.ManifestModule.FullyQualifiedName)
                 .Distinct())
            {
                try
                {
                    args.Add(System.IO.Path.GetDirectoryName(path));
                }
                catch (Exception)
                {
 
                }
            }
            var injectAssemblyPaths = HotfixConfig.GetHotfixAssemblyPaths();
            var idMapFileNames = new List<string>();
            foreach (var injectAssemblyPath in injectAssemblyPaths)
            {
                args[1] = injectAssemblyPath.Replace('\\', '/');
                if (injectAssemblyPaths.Count > 1)
                {
                    var injectAssemblyFileName = Path.GetFileName(injectAssemblyPath);
                    args[3] = CSObjectWrapEditor.GeneratorConfig.common_path + "Resources/hotfix_id_map_" + injectAssemblyFileName.Substring(0, injectAssemblyFileName.Length - 4) + ".lua.txt";
                    idMapFileNames.Add(args[3]);
                }
                Process hotfix_injection = new Process();
                hotfix_injection.StartInfo.FileName = mono_path;
                hotfix_injection.StartInfo.Arguments = "\"" + String.Join("\" \"", args.ToArray()) + "\"";
                hotfix_injection.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
                hotfix_injection.StartInfo.RedirectStandardOutput = true;
                hotfix_injection.StartInfo.UseShellExecute = false;
                hotfix_injection.StartInfo.CreateNoWindow = true;
                hotfix_injection.Start();
                UnityEngine.Debug.Log(hotfix_injection.StandardOutput.ReadToEnd());
                hotfix_injection.WaitForExit();
            }
 
            File.Delete(hotfix_cfg_in_editor);
            AssetDatabase.Refresh();
        }
    }
}
#endif
#endif