summaryrefslogtreecommitdiff
path: root/src/mscorlib/src/System/Reflection/Emit/ModuleBuilder.cs
blob: 30e638255073b19f19031ba3c9d8d6dcfec42972 (plain)
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
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

// 

namespace System.Reflection.Emit 
{
    using System.Runtime.InteropServices;
    using System;
    using System.Collections.Generic;
    using System.Diagnostics.SymbolStore;
    using System.Globalization;
    using System.Reflection;
    using System.IO;
    using System.Resources;
    using System.Security;
    using System.Runtime.Serialization;
    using System.Text;
    using System.Threading;
    using System.Runtime.Versioning;
    using System.Runtime.CompilerServices;
    using System.Diagnostics;
    using System.Diagnostics.Contracts;

    internal sealed class InternalModuleBuilder : RuntimeModule
    {
        #region Private Data Members
        // WARNING!! WARNING!!
        // InternalModuleBuilder should not contain any data members as its reflectbase is the same as Module.
        #endregion

        private InternalModuleBuilder() { }

        #region object overrides
        public override bool Equals(object obj)
        {
            if (obj == null)
                return false;

            if (obj is InternalModuleBuilder)
                return ((object)this == obj);

            return obj.Equals(this);
        }
        // Need a dummy GetHashCode to pair with Equals
        public override int GetHashCode() { return base.GetHashCode(); }
        #endregion
    }

    // deliberately not [serializable]
    public class ModuleBuilder : Module
    {
        #region FCalls

        [MethodImplAttribute(MethodImplOptions.InternalCall)]
        internal static extern IntPtr nCreateISymWriterForDynamicModule(Module module, String filename);

        #endregion

        #region Internal Static Members
        static internal String UnmangleTypeName(String typeName)
        {
            // Gets the original type name, without '+' name mangling.

            int i = typeName.Length - 1;
            while (true)
            {
                i = typeName.LastIndexOf('+', i);
                if (i == -1)
                    break;

                bool evenSlashes = true;
                int iSlash = i;
                while (typeName[--iSlash] == '\\')
                    evenSlashes = !evenSlashes;

                // Even number of slashes means this '+' is a name separator
                if (evenSlashes)
                    break;

                i = iSlash;
            }

            return typeName.Substring(i + 1);
        }

        #endregion

        #region Intenral Data Members
        // m_TypeBuilder contains both TypeBuilder and EnumBuilder objects
        private Dictionary<string, Type> m_TypeBuilderDict;
        private ISymbolWriter m_iSymWriter;
        internal ModuleBuilderData m_moduleData;
        internal InternalModuleBuilder m_internalModuleBuilder;
        // This is the "external" AssemblyBuilder
        // only the "external" ModuleBuilder has this set
        private AssemblyBuilder m_assemblyBuilder;
        internal AssemblyBuilder ContainingAssemblyBuilder { get { return m_assemblyBuilder; } }
        #endregion

        #region Constructor
        internal ModuleBuilder(AssemblyBuilder assemblyBuilder, InternalModuleBuilder internalModuleBuilder)
        {
            m_internalModuleBuilder = internalModuleBuilder;
            m_assemblyBuilder = assemblyBuilder;
        }
        #endregion

        #region Private Members
        internal void AddType(string name, Type type)
        {
            m_TypeBuilderDict.Add(name, type);
        }

        internal void CheckTypeNameConflict(String strTypeName, Type enclosingType)
        {
            Type foundType = null;
            if (m_TypeBuilderDict.TryGetValue(strTypeName, out foundType) &&
                object.ReferenceEquals(foundType.DeclaringType, enclosingType))
            {
                // Cannot have two types with the same name
                throw new ArgumentException(Environment.GetResourceString("Argument_DuplicateTypeName"));
            }
        }

        private Type GetType(String strFormat, Type baseType)
        {
            // This function takes a string to describe the compound type, such as "[,][]", and a baseType.

            if (strFormat == null || strFormat.Equals(String.Empty))
            {
                return baseType;
            }

            // convert the format string to byte array and then call FormCompoundType
            return SymbolType.FormCompoundType(strFormat, baseType, 0);

        }
        
        
        internal void CheckContext(params Type[][] typess)
        {
            ContainingAssemblyBuilder.CheckContext(typess);
        }
        internal void CheckContext(params Type[] types)
        {
            ContainingAssemblyBuilder.CheckContext(types);
        }


        [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
        [SuppressUnmanagedCodeSecurity]
        private extern static int GetTypeRef(RuntimeModule module, String strFullName, RuntimeModule refedModule, String strRefedModuleFileName, int tkResolution);

        [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
        [SuppressUnmanagedCodeSecurity]
        private extern static int GetMemberRef(RuntimeModule module, RuntimeModule refedModule, int tr, int defToken);

        private int GetMemberRef(Module refedModule, int tr, int defToken)
        {
            return GetMemberRef(GetNativeHandle(), GetRuntimeModuleFromModule(refedModule).GetNativeHandle(), tr, defToken);
        }

        [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
        [SuppressUnmanagedCodeSecurity]
        private extern static int GetMemberRefFromSignature(RuntimeModule module, int tr, String methodName, byte[] signature, int length);

        private int GetMemberRefFromSignature(int tr, String methodName, byte[] signature, int length)
        {
            return GetMemberRefFromSignature(GetNativeHandle(), tr, methodName, signature, length);
        }

        [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
        [SuppressUnmanagedCodeSecurity]
        private extern static int GetMemberRefOfMethodInfo(RuntimeModule module, int tr, IRuntimeMethodInfo method);

        private int GetMemberRefOfMethodInfo(int tr, RuntimeMethodInfo method)
        {
            Debug.Assert(method != null);

#if FEATURE_APPX
            if (ContainingAssemblyBuilder.ProfileAPICheck)
            {
                if ((method.InvocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0)
                    throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_APIInvalidForCurrentContext", method.FullName));
            }
#endif

            return GetMemberRefOfMethodInfo(GetNativeHandle(), tr, method);
        }

        private int GetMemberRefOfMethodInfo(int tr, RuntimeConstructorInfo method)
        {
            Debug.Assert(method != null);

#if FEATURE_APPX
            if (ContainingAssemblyBuilder.ProfileAPICheck)
            {
                if ((method.InvocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0)
                    throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_APIInvalidForCurrentContext", method.FullName));
            }
#endif

            return GetMemberRefOfMethodInfo(GetNativeHandle(), tr, method);
        }

        [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
        [SuppressUnmanagedCodeSecurity]
        private extern static int GetMemberRefOfFieldInfo(RuntimeModule module, int tkType, RuntimeTypeHandle declaringType, int tkField);

        private int GetMemberRefOfFieldInfo(int tkType, RuntimeTypeHandle declaringType, RuntimeFieldInfo runtimeField)
        {
            Debug.Assert(runtimeField != null);

#if FEATURE_APPX
            if (ContainingAssemblyBuilder.ProfileAPICheck)
            {
                RtFieldInfo rtField = runtimeField as RtFieldInfo;
                if (rtField != null && (rtField.InvocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0)
                throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_APIInvalidForCurrentContext", rtField.FullName));
            }
#endif

            return GetMemberRefOfFieldInfo(GetNativeHandle(), tkType, declaringType, runtimeField.MetadataToken);
        }

        [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
        [SuppressUnmanagedCodeSecurity]
        private extern static int GetTokenFromTypeSpec(RuntimeModule pModule, byte[] signature, int length);

        private int GetTokenFromTypeSpec(byte[] signature, int length)
        {
            return GetTokenFromTypeSpec(GetNativeHandle(), signature, length);
        }

        [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
        [SuppressUnmanagedCodeSecurity]
        private extern static int GetArrayMethodToken(RuntimeModule module, int tkTypeSpec, String methodName, byte[] signature, int sigLength);

        [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
        [SuppressUnmanagedCodeSecurity]
        private extern static int GetStringConstant(RuntimeModule module, String str, int length);

        [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
        [SuppressUnmanagedCodeSecurity]
        internal extern static void SetFieldRVAContent(RuntimeModule module, int fdToken, byte[] data, int length);

        #endregion

        #region Internal Members
        internal virtual Type FindTypeBuilderWithName(String strTypeName, bool ignoreCase)
        {
            if (ignoreCase)
            {
                foreach (string name in m_TypeBuilderDict.Keys)
                {
                    if (String.Compare(name, strTypeName, (StringComparison.OrdinalIgnoreCase)) == 0)
                        return m_TypeBuilderDict[name];
                }
            }
            else
            {
                Type foundType;
                if (m_TypeBuilderDict.TryGetValue(strTypeName, out foundType))
                    return foundType;
            }

            return null;
        }

        private int GetTypeRefNested(Type type, Module refedModule, String strRefedModuleFileName)
        {
            // This function will generate correct TypeRef token for top level type and nested type.

            Type enclosingType = type.DeclaringType;
            int tkResolution = 0;
            String typeName = type.FullName;

            if (enclosingType != null)
            {
                tkResolution = GetTypeRefNested(enclosingType, refedModule, strRefedModuleFileName);
                typeName = UnmangleTypeName(typeName);
            }

            Debug.Assert(!type.IsByRef, "Must not be ByRef.");
            Debug.Assert(!type.IsGenericType || type.IsGenericTypeDefinition, "Must not have generic arguments.");

#if FEATURE_APPX
            if (ContainingAssemblyBuilder.ProfileAPICheck)
            {
                RuntimeType rtType = type as RuntimeType;
                if (rtType != null && (rtType.InvocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0)
                {
                    throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_APIInvalidForCurrentContext", rtType.FullName));
                }
            }
#endif

            return GetTypeRef(GetNativeHandle(), typeName, GetRuntimeModuleFromModule(refedModule).GetNativeHandle(), strRefedModuleFileName, tkResolution);
        }

        internal MethodToken InternalGetConstructorToken(ConstructorInfo con, bool usingRef)
        {
            // Helper to get constructor token. If usingRef is true, we will never use the def token

            if (con == null)
                throw new ArgumentNullException(nameof(con));
            Contract.EndContractBlock();

            int tr;
            int mr = 0;

            ConstructorBuilder conBuilder = null;
            ConstructorOnTypeBuilderInstantiation conOnTypeBuilderInst = null;
            RuntimeConstructorInfo rtCon = null;

            if ( (conBuilder = con as ConstructorBuilder) != null )
            {
                if (usingRef == false && conBuilder.Module.Equals(this))
                    return conBuilder.GetToken();

                // constructor is defined in a different module
                tr = GetTypeTokenInternal(con.ReflectedType).Token;
                mr = GetMemberRef(con.ReflectedType.Module, tr, conBuilder.GetToken().Token);
            }
            else if ( (conOnTypeBuilderInst = con as ConstructorOnTypeBuilderInstantiation) != null )
            {
                if (usingRef == true) throw new InvalidOperationException();

                tr = GetTypeTokenInternal(con.DeclaringType).Token;
                mr = GetMemberRef(con.DeclaringType.Module, tr, conOnTypeBuilderInst.MetadataTokenInternal);
            }
            else if ( (rtCon = con as RuntimeConstructorInfo) != null && con.ReflectedType.IsArray == false)
            {
                // constructor is not a dynamic field
                // We need to get the TypeRef tokens

                tr = GetTypeTokenInternal(con.ReflectedType).Token;
                mr = GetMemberRefOfMethodInfo(tr, rtCon);
            }
            else
            {
                // some user derived ConstructorInfo
                // go through the slower code path, i.e. retrieve parameters and form signature helper.
                ParameterInfo[] parameters = con.GetParameters();
                if (parameters == null)
                    throw new ArgumentException(Environment.GetResourceString("Argument_InvalidConstructorInfo"));

                Type[] parameterTypes = new Type[parameters.Length];
                Type[][] requiredCustomModifiers = new Type[parameters.Length][];
                Type[][] optionalCustomModifiers = new Type[parameters.Length][];

                for (int i = 0; i < parameters.Length; i++)
                {
                    if (parameters[i] == null)
                        throw new ArgumentException(Environment.GetResourceString("Argument_InvalidConstructorInfo"));

                    parameterTypes[i] = parameters[i].ParameterType;
                    requiredCustomModifiers[i] = parameters[i].GetRequiredCustomModifiers();
                    optionalCustomModifiers[i] = parameters[i].GetOptionalCustomModifiers();
                }

                tr = GetTypeTokenInternal(con.ReflectedType).Token;

                SignatureHelper sigHelp = SignatureHelper.GetMethodSigHelper(this, con.CallingConvention, null, null, null, parameterTypes, requiredCustomModifiers, optionalCustomModifiers);
                int length;
                byte[] sigBytes = sigHelp.InternalGetSignature(out length);

                mr = GetMemberRefFromSignature(tr, con.Name, sigBytes, length);
            }
            
            return new MethodToken( mr );
        }

        internal void Init(String strModuleName, String strFileName, int tkFile)
        {
            m_moduleData = new ModuleBuilderData(this, strModuleName, strFileName, tkFile);
            m_TypeBuilderDict = new Dictionary<string, Type>();
        }

        internal void SetSymWriter(ISymbolWriter writer)
        {
            m_iSymWriter = writer;
        }

        internal object SyncRoot
        {
            get
            {
                return ContainingAssemblyBuilder.SyncRoot;
            }
        }

        #endregion

        #region Module Overrides
            
        // m_internalModuleBuilder is null iff this is a "internal" ModuleBuilder
        internal InternalModuleBuilder InternalModule
        {
            get
            {
                return m_internalModuleBuilder;
            }
        }

        internal override ModuleHandle GetModuleHandle()
        {
            return new ModuleHandle(GetNativeHandle());
        }

        internal RuntimeModule GetNativeHandle()
        {
            return InternalModule.GetNativeHandle();
        }

        private static RuntimeModule GetRuntimeModuleFromModule(Module m)
        {
            ModuleBuilder mb = m as ModuleBuilder;
            if (mb != null)
            {
                return mb.InternalModule;
            }

            return m as RuntimeModule;
        }

        private int GetMemberRefToken(MethodBase method, IEnumerable<Type> optionalParameterTypes)
        {
            Type[] parameterTypes;
            Type returnType;
            int tkParent;
            int cGenericParameters = 0;

            if (method.IsGenericMethod)
            {
                if (!method.IsGenericMethodDefinition)
                    throw new InvalidOperationException();

                cGenericParameters = method.GetGenericArguments().Length;
            }

            if (optionalParameterTypes != null)
            {
                if ((method.CallingConvention & CallingConventions.VarArgs) == 0)
                {
                    // Client should not supply optional parameter in default calling convention
                    throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NotAVarArgCallingConvention"));
                }
            }

            MethodInfo masmi = method as MethodInfo;

            if (method.DeclaringType.IsGenericType)
            {
                MethodBase methDef = null; // methodInfo = G<Foo>.M<Bar> ==> methDef = G<T>.M<S>

                MethodOnTypeBuilderInstantiation motbi;
                ConstructorOnTypeBuilderInstantiation cotbi;

                if ((motbi = method as MethodOnTypeBuilderInstantiation) != null)
                {
                    methDef = motbi.m_method;
                }
                else if ((cotbi = method as ConstructorOnTypeBuilderInstantiation) != null)
                {
                    methDef = cotbi.m_ctor;
                }
                else if (method is MethodBuilder || method is ConstructorBuilder)
                {
                    // methodInfo must be GenericMethodDefinition; trying to emit G<?>.M<S>
                    methDef = method;
                }
                else
                {
                    Debug.Assert(method is RuntimeMethodInfo || method is RuntimeConstructorInfo);

                    if (method.IsGenericMethod)
                    {
                        Debug.Assert(masmi != null);

                        methDef = masmi.GetGenericMethodDefinition();
                        methDef = methDef.Module.ResolveMethod(
                            method.MetadataToken,
                            methDef.DeclaringType != null ? methDef.DeclaringType.GetGenericArguments() : null,
                            methDef.GetGenericArguments());
                    }
                    else
                    {
                        methDef = method.Module.ResolveMethod(
                            method.MetadataToken,
                            method.DeclaringType != null ? method.DeclaringType.GetGenericArguments() : null,
                            null);
                    }
                }

                parameterTypes = methDef.GetParameterTypes();
                returnType = MethodBuilder.GetMethodBaseReturnType(methDef);
            }
            else
            {
                parameterTypes = method.GetParameterTypes();
                returnType = MethodBuilder.GetMethodBaseReturnType(method);
            }

            int sigLength;
            byte[] sigBytes = GetMemberRefSignature(method.CallingConvention, returnType, parameterTypes,
                optionalParameterTypes, cGenericParameters).InternalGetSignature(out sigLength);

            if (method.DeclaringType.IsGenericType)
            {
                int length;
                byte[] sig = SignatureHelper.GetTypeSigToken(this, method.DeclaringType).InternalGetSignature(out length);
                tkParent = GetTokenFromTypeSpec(sig, length);
            }
            else if (!method.Module.Equals(this))
            {
                // Use typeRef as parent because the method's declaringType lives in a different assembly                
                tkParent = GetTypeToken(method.DeclaringType).Token;
            }
            else
            {
                // Use methodDef as parent because the method lives in this assembly and its declaringType has no generic arguments
                if (masmi != null)
                    tkParent = GetMethodToken(masmi).Token;
                else
                    tkParent = GetConstructorToken(method as ConstructorInfo).Token;
            }

            return GetMemberRefFromSignature(tkParent, method.Name, sigBytes, sigLength);
        }

        internal SignatureHelper GetMemberRefSignature(CallingConventions call, Type returnType,
            Type[] parameterTypes, IEnumerable<Type> optionalParameterTypes, int cGenericParameters) 
        {
            SignatureHelper sig = SignatureHelper.GetMethodSigHelper(this, call, returnType, cGenericParameters);

            if (parameterTypes != null)
            {
                foreach (Type t in parameterTypes)
                {
                    sig.AddArgument(t);
                }
            }

            if (optionalParameterTypes != null) {
                int i = 0;
                foreach (Type type in optionalParameterTypes)
                {
                    // add the sentinel
                    if (i == 0)
                    {
                        sig.AddSentinel();
                    }

                    sig.AddArgument(type);
                    i++;
                }
            }

            return sig;
        }

        #endregion

        #region object overrides
        public override bool Equals(object obj)
        {
            return InternalModule.Equals(obj);
        }
        // Need a dummy GetHashCode to pair with Equals
        public override int GetHashCode() { return InternalModule.GetHashCode(); }
        #endregion

        #region ICustomAttributeProvider Members
        public override Object[] GetCustomAttributes(bool inherit)
        {
            return InternalModule.GetCustomAttributes(inherit);
        }

        public override Object[] GetCustomAttributes(Type attributeType, bool inherit)
        {
            return InternalModule.GetCustomAttributes(attributeType, inherit);
        }

        public override bool IsDefined(Type attributeType, bool inherit)
        {
            return InternalModule.IsDefined(attributeType, inherit);
        }

        public override IList<CustomAttributeData> GetCustomAttributesData()
        {
            return InternalModule.GetCustomAttributesData();
        }
        #endregion

        #region Module Overrides

        public override Type[] GetTypes()
        {
            lock(SyncRoot)
            {
                return GetTypesNoLock();
            }
        }

        internal Type[] GetTypesNoLock()
        {
            int size = m_TypeBuilderDict.Count;
            Type[] typeList = new Type[m_TypeBuilderDict.Count];
            int i = 0;

            foreach (Type builder in m_TypeBuilderDict.Values)
            {
                EnumBuilder enumBldr = builder as EnumBuilder;
                TypeBuilder tmpTypeBldr;

                if (enumBldr != null)
                    tmpTypeBldr = enumBldr.m_typeBuilder;
                else
                    tmpTypeBldr = (TypeBuilder)builder;
                    
                // We should not return TypeBuilders.
                // Otherwise anyone can emit code in it.
                if (tmpTypeBldr.IsCreated())
                    typeList[i++] = tmpTypeBldr.UnderlyingSystemType;
                else
                    typeList[i++] = builder;
            }

            return typeList;
        }

        public override Type GetType(String className)
        {
            return GetType(className, false, false);
        }
        
        public override Type GetType(String className, bool ignoreCase)
        {
            return GetType(className, false, ignoreCase);
        }
        
        public override Type GetType(String className, bool throwOnError, bool ignoreCase)
        {
            lock(SyncRoot)
            {
                return GetTypeNoLock(className, throwOnError, ignoreCase);
            }
        }

        private Type GetTypeNoLock(String className, bool throwOnError, bool ignoreCase)
        {
            // public API to to a type. The reason that we need this function override from module
            // is because clients might need to get foo[] when foo is being built. For example, if 
            // foo class contains a data member of type foo[].
            // This API first delegate to the Module.GetType implementation. If succeeded, great! 
            // If not, we have to look up the current module to find the TypeBuilder to represent the base
            // type and form the Type object for "foo[,]".
                
            // Module.GetType() will verify className.                
            Type baseType = InternalModule.GetType(className, throwOnError, ignoreCase);
            if (baseType != null)
                return baseType;

            // Now try to see if we contain a TypeBuilder for this type or not.
            // Might have a compound type name, indicated via an unescaped
            // '[', '*' or '&'. Split the name at this point.
            String baseName = null;
            String parameters = null;
            int startIndex = 0;

            while (startIndex <= className.Length)
            {
                // Are there any possible special characters left?
                int i = className.IndexOfAny(new char[]{'[', '*', '&'}, startIndex);
                if (i == -1)
                {
                    // No, type name is simple.
                    baseName = className;
                    parameters = null;
                    break;
                }

                // Found a potential special character, but it might be escaped.
                int slashes = 0;
                for (int j = i - 1; j >= 0 && className[j] == '\\'; j--)
                    slashes++;

                // Odd number of slashes indicates escaping.
                if (slashes % 2 == 1)
                {
                    startIndex = i + 1;
                    continue;
                }

                // Found the end of the base type name.
                baseName = className.Substring(0, i);
                parameters = className.Substring(i);
                break;
            }

            // If we didn't find a basename yet, the entire class name is
            // the base name and we don't have a composite type.
            if (baseName == null)
            {
                baseName = className;
                parameters = null;
            }

            baseName = baseName.Replace(@"\\",@"\").Replace(@"\[",@"[").Replace(@"\*",@"*").Replace(@"\&",@"&");

            if (parameters != null)
            {
                // try to see if reflection can find the base type. It can be such that reflection
                // does not support the complex format string yet!

                baseType = InternalModule.GetType(baseName, false, ignoreCase);
            }

            if (baseType == null)
            {
                // try to find it among the unbaked types.
                // starting with the current module first of all.
                baseType = FindTypeBuilderWithName(baseName, ignoreCase);
                if (baseType == null && Assembly is AssemblyBuilder)
                {
                    // now goto Assembly level to find the type.
                    int size;
                    List<ModuleBuilder> modList;

                    modList = ContainingAssemblyBuilder.m_assemblyData.m_moduleBuilderList;
                    size = modList.Count;
                    for (int i = 0; i < size && baseType == null; i++)
                    {
                        ModuleBuilder mBuilder = modList[i];
                        baseType = mBuilder.FindTypeBuilderWithName(baseName, ignoreCase);
                    }
                }
                if (baseType == null)
                    return null;
            }

            if (parameters == null)         
                return baseType;
        
            return GetType(parameters, baseType);
        }

        public override String FullyQualifiedName
        {
            get
            {
                String fullyQualifiedName = m_moduleData.m_strFileName;
                if (fullyQualifiedName == null)
                    return null;
                if (ContainingAssemblyBuilder.m_assemblyData.m_strDir != null)
                {
                    fullyQualifiedName = Path.Combine(ContainingAssemblyBuilder.m_assemblyData.m_strDir, fullyQualifiedName);
                    fullyQualifiedName = Path.GetFullPath(fullyQualifiedName);
                }

                return fullyQualifiedName;
            }
        }

        public override byte[] ResolveSignature(int metadataToken)
        {
            return InternalModule.ResolveSignature(metadataToken);
        }

        public override MethodBase ResolveMethod(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments)
        {
            return InternalModule.ResolveMethod(metadataToken, genericTypeArguments, genericMethodArguments);
        }

        public override FieldInfo ResolveField(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments)
        {
            return InternalModule.ResolveField(metadataToken, genericTypeArguments, genericMethodArguments);
        }

        public override Type ResolveType(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments)
        {
            return InternalModule.ResolveType(metadataToken, genericTypeArguments, genericMethodArguments);
        }

        public override MemberInfo ResolveMember(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments)
        {
            return InternalModule.ResolveMember(metadataToken, genericTypeArguments, genericMethodArguments);
        }

        public override string ResolveString(int metadataToken)
        {
            return InternalModule.ResolveString(metadataToken);
        }

        public override void GetPEKind(out PortableExecutableKinds peKind, out ImageFileMachine machine)
        {
            InternalModule.GetPEKind(out peKind, out machine);
        }

        public override int MDStreamVersion
        {
            get
            {
                return InternalModule.MDStreamVersion;
            }
        }

        public override Guid ModuleVersionId
        {
            get
            {
                return InternalModule.ModuleVersionId;
            }
        }

        public override int MetadataToken
        {
            get
            {
                return InternalModule.MetadataToken;
            }
        }

        public override bool IsResource()
        {
            return InternalModule.IsResource();
        }

        public override FieldInfo[] GetFields(BindingFlags bindingFlags)
        {
            return InternalModule.GetFields(bindingFlags);
        }

        public override FieldInfo GetField(String name, BindingFlags bindingAttr)
        {
            return InternalModule.GetField(name, bindingAttr);
        }

        public override MethodInfo[] GetMethods(BindingFlags bindingFlags)
        {
            return InternalModule.GetMethods(bindingFlags);
        }

        protected override MethodInfo GetMethodImpl(String name, BindingFlags bindingAttr, Binder binder,
            CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers)
        {
            // Cannot call InternalModule.GetMethods because it doesn't allow types to be null
            return InternalModule.GetMethodInternal(name, bindingAttr, binder, callConvention, types, modifiers);
        }

        public override String ScopeName
        {
            get
            {
                return InternalModule.ScopeName;
            }
        }

        public override String Name
        {
            get
            {
                return InternalModule.Name;
            }
        }

        public override Assembly Assembly
        {
            [Pure]
            get
            {
                return m_assemblyBuilder;
            }
        }

        #endregion

        #region Public Members

        #region Define Type
        public TypeBuilder DefineType(String name)
        {
            Contract.Ensures(Contract.Result<TypeBuilder>() != null);

            lock(SyncRoot)
            {
                return DefineTypeNoLock(name, TypeAttributes.NotPublic, null, null, PackingSize.Unspecified, TypeBuilder.UnspecifiedTypeSize);
            }
        }

        public TypeBuilder DefineType(String name, TypeAttributes attr)
        {
            Contract.Ensures(Contract.Result<TypeBuilder>() != null);

            lock(SyncRoot)
            {
                return DefineTypeNoLock(name, attr, null, null, PackingSize.Unspecified, TypeBuilder.UnspecifiedTypeSize);
            }
        }

        public TypeBuilder DefineType(String name, TypeAttributes attr, Type parent)
        {
            Contract.Ensures(Contract.Result<TypeBuilder>() != null);

            lock(SyncRoot)
            {
                // Why do we only call CheckContext here? Why don't we call it in the other overloads?
                CheckContext(parent);

                return DefineTypeNoLock(name, attr, parent, null, PackingSize.Unspecified, TypeBuilder.UnspecifiedTypeSize);
            }
        }

        public TypeBuilder DefineType(String name, TypeAttributes attr, Type parent, int typesize)
        {
            Contract.Ensures(Contract.Result<TypeBuilder>() != null);

            lock(SyncRoot)
            {
                return DefineTypeNoLock(name, attr, parent, null, PackingSize.Unspecified, typesize);
            }
        }

        public TypeBuilder DefineType(String name, TypeAttributes attr, Type parent, PackingSize packingSize, int typesize)
        {
            Contract.Ensures(Contract.Result<TypeBuilder>() != null);

            lock (SyncRoot)
            {
                return DefineTypeNoLock(name, attr, parent, null, packingSize, typesize);
            }
        }

        public TypeBuilder DefineType(String name, TypeAttributes attr, Type parent, Type[] interfaces)
        {
            Contract.Ensures(Contract.Result<TypeBuilder>() != null);

            lock(SyncRoot)
            {
                return DefineTypeNoLock(name, attr, parent, interfaces, PackingSize.Unspecified, TypeBuilder.UnspecifiedTypeSize);
            }
        }

        private TypeBuilder DefineTypeNoLock(String name, TypeAttributes attr, Type parent, Type[] interfaces, PackingSize packingSize, int typesize)
        {
            Contract.Ensures(Contract.Result<TypeBuilder>() != null);

            return new TypeBuilder(name, attr, parent, interfaces, this, packingSize, typesize, null); ;
        }

        public TypeBuilder DefineType(String name, TypeAttributes attr, Type parent, PackingSize packsize)
        {
            Contract.Ensures(Contract.Result<TypeBuilder>() != null);

            lock(SyncRoot)
            {
                return DefineTypeNoLock(name, attr, parent, packsize);
            }
        }

        private TypeBuilder DefineTypeNoLock(String name, TypeAttributes attr, Type parent, PackingSize packsize)
        {
            Contract.Ensures(Contract.Result<TypeBuilder>() != null);

            return new TypeBuilder(name, attr, parent, null, this, packsize, TypeBuilder.UnspecifiedTypeSize, null);
        }

        #endregion

        #region Define Enum

        // This API can only be used to construct a top-level (not nested) enum type.
        // Nested enum types can be defined manually using ModuleBuilder.DefineType.
        public EnumBuilder DefineEnum(String name, TypeAttributes visibility, Type underlyingType)
        {
            Contract.Ensures(Contract.Result<EnumBuilder>() != null);

            CheckContext(underlyingType);
            lock(SyncRoot)
            {
                EnumBuilder enumBuilder = DefineEnumNoLock(name, visibility, underlyingType);

                // This enum is not generic, nested, and cannot have any element type.

                // We ought to be able to make the following assertions:
                //
                //  Debug.Assert(name == enumBuilder.FullName);
                //  Debug.Assert(enumBuilder.m_typeBuilder == m_TypeBuilderDict[name]);
                //
                // but we can't because an embedded null ('\0') in the name will cause it to be truncated
                // incorrectly.  Fixing that would be a breaking change.

                // Replace the TypeBuilder object in m_TypeBuilderDict with this EnumBuilder object.
                m_TypeBuilderDict[name] = enumBuilder;

                return enumBuilder;
            }
        }

        private EnumBuilder DefineEnumNoLock(String name, TypeAttributes visibility, Type underlyingType)
        {
            Contract.Ensures(Contract.Result<EnumBuilder>() != null);

            return new EnumBuilder(name, underlyingType, visibility, this);
        }
    
        #endregion

        #region Define Resource

        #endregion

        #region Define Global Method
        public MethodBuilder DefineGlobalMethod(String name, MethodAttributes attributes, Type returnType, Type[] parameterTypes)
        {
            Contract.Ensures(Contract.Result<MethodBuilder>() != null);

            return DefineGlobalMethod(name, attributes, CallingConventions.Standard, returnType, parameterTypes);
        }

        public MethodBuilder DefineGlobalMethod(String name, MethodAttributes attributes, CallingConventions callingConvention, 
            Type returnType, Type[] parameterTypes)
        {
            Contract.Ensures(Contract.Result<MethodBuilder>() != null);

            return DefineGlobalMethod(name, attributes, callingConvention, returnType, null, null, parameterTypes, null, null);
        }

        public MethodBuilder DefineGlobalMethod(String name, MethodAttributes attributes, CallingConventions callingConvention, 
            Type returnType, Type[] requiredReturnTypeCustomModifiers, Type[] optionalReturnTypeCustomModifiers,
            Type[] parameterTypes, Type[][] requiredParameterTypeCustomModifiers, Type[][] optionalParameterTypeCustomModifiers)
        {
            lock(SyncRoot)
            {
                return DefineGlobalMethodNoLock(name, attributes, callingConvention, returnType, 
                                                requiredReturnTypeCustomModifiers, optionalReturnTypeCustomModifiers,
                                                parameterTypes, requiredParameterTypeCustomModifiers, optionalParameterTypeCustomModifiers);
            }
        }

        private MethodBuilder DefineGlobalMethodNoLock(String name, MethodAttributes attributes, CallingConventions callingConvention, 
            Type returnType, Type[] requiredReturnTypeCustomModifiers, Type[] optionalReturnTypeCustomModifiers,
            Type[] parameterTypes, Type[][] requiredParameterTypeCustomModifiers, Type[][] optionalParameterTypeCustomModifiers)
        {
            if (m_moduleData.m_fGlobalBeenCreated == true)
                throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_GlobalsHaveBeenCreated"));
        
            if (name == null)
                throw new ArgumentNullException(nameof(name));

            if (name.Length == 0)
                throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), nameof(name));
        
            if ((attributes & MethodAttributes.Static) == 0)
                throw new ArgumentException(Environment.GetResourceString("Argument_GlobalFunctionHasToBeStatic"));
            Contract.Ensures(Contract.Result<MethodBuilder>() != null);
            Contract.EndContractBlock();

            CheckContext(returnType);
            CheckContext(requiredReturnTypeCustomModifiers, optionalReturnTypeCustomModifiers, parameterTypes);
            CheckContext(requiredParameterTypeCustomModifiers);
            CheckContext(optionalParameterTypeCustomModifiers);

            m_moduleData.m_fHasGlobal = true;

            return m_moduleData.m_globalTypeBuilder.DefineMethod(name, attributes, callingConvention, 
                returnType, requiredReturnTypeCustomModifiers, optionalReturnTypeCustomModifiers, 
                parameterTypes, requiredParameterTypeCustomModifiers, optionalParameterTypeCustomModifiers);
        }
        
        public void CreateGlobalFunctions()
        {
            lock(SyncRoot)
            {
                CreateGlobalFunctionsNoLock();
            }
        }

        private void CreateGlobalFunctionsNoLock()
        {
            if (m_moduleData.m_fGlobalBeenCreated)
            {
                // cannot create globals twice
                throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NotADebugModule"));
            }
            m_moduleData.m_globalTypeBuilder.CreateType();
            m_moduleData.m_fGlobalBeenCreated = true;
        }
    
        #endregion

        #region Define Data

        public FieldBuilder DefineInitializedData(String name, byte[] data, FieldAttributes attributes)
        {
            // This method will define an initialized Data in .sdata. 
            // We will create a fake TypeDef to represent the data with size. This TypeDef
            // will be the signature for the Field.         
            Contract.Ensures(Contract.Result<FieldBuilder>() != null);

            lock(SyncRoot)
            {
                return DefineInitializedDataNoLock(name, data, attributes);
            }
        }

        private FieldBuilder DefineInitializedDataNoLock(String name, byte[] data, FieldAttributes attributes)
        {
            // This method will define an initialized Data in .sdata. 
            // We will create a fake TypeDef to represent the data with size. This TypeDef
            // will be the signature for the Field.
            if (m_moduleData.m_fGlobalBeenCreated == true)
            {
                throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_GlobalsHaveBeenCreated"));
            }
            Contract.Ensures(Contract.Result<FieldBuilder>() != null);
            Contract.EndContractBlock();
        
            m_moduleData.m_fHasGlobal = true;
            return m_moduleData.m_globalTypeBuilder.DefineInitializedData(name, data, attributes);
        }
        
        public FieldBuilder DefineUninitializedData(String name, int size, FieldAttributes attributes)
        {
            Contract.Ensures(Contract.Result<FieldBuilder>() != null);

            lock(SyncRoot)
            {
                return DefineUninitializedDataNoLock(name, size, attributes);
            }
        }

        private FieldBuilder DefineUninitializedDataNoLock(String name, int size, FieldAttributes attributes)
        {
            // This method will define an uninitialized Data in .sdata. 
            // We will create a fake TypeDef to represent the data with size. This TypeDef
            // will be the signature for the Field. 

            if (m_moduleData.m_fGlobalBeenCreated == true)
            {
                throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_GlobalsHaveBeenCreated"));
            }
            Contract.Ensures(Contract.Result<FieldBuilder>() != null);
            Contract.EndContractBlock();
        
            m_moduleData.m_fHasGlobal = true;
            return m_moduleData.m_globalTypeBuilder.DefineUninitializedData(name, size, attributes);
        }
                
        #endregion

        #region GetToken
        // For a generic type definition, we should return the token for the generic type definition itself in two cases: 
        //   1. GetTypeToken
        //   2. ldtoken (see ILGenerator)
        // For all other occasions we should return the generic type instantiated on its formal parameters.
        internal TypeToken GetTypeTokenInternal(Type type)
        {
            return GetTypeTokenInternal(type, false);
        }

        private TypeToken GetTypeTokenInternal(Type type, bool getGenericDefinition)
        {
            lock(SyncRoot)
            {
                return GetTypeTokenWorkerNoLock(type, getGenericDefinition);
            }
        }

        public TypeToken GetTypeToken(Type type)
        {        
            return GetTypeTokenInternal(type, true);
        }

        private TypeToken GetTypeTokenWorkerNoLock(Type type, bool getGenericDefinition)
        {
            if (type == null)
                throw new ArgumentNullException(nameof(type));
            Contract.EndContractBlock();

            CheckContext(type);
            
            // Return a token for the class relative to the Module.  Tokens
            // are used to indentify objects when the objects are used in IL
            // instructions.  Tokens are always relative to the Module.  For example,
            // the token value for System.String is likely to be different from
            // Module to Module.  Calling GetTypeToken will cause a reference to be
            // added to the Module.  This reference becomes a perminate part of the Module,
            // multiple calles to this method with the same class have no additional side affects.
            // This function is optimized to use the TypeDef token if Type is within the same module.
            // We should also be aware of multiple dynamic modules and multiple implementation of Type!!!

            if (type.IsByRef)
                throw new ArgumentException(Environment.GetResourceString("Argument_CannotGetTypeTokenForByRef"));

            if ((type.IsGenericType && (!type.IsGenericTypeDefinition || !getGenericDefinition)) ||
                type.IsGenericParameter ||
                type.IsArray ||
                type.IsPointer)
            {
                int length;
                byte[] sig = SignatureHelper.GetTypeSigToken(this, type).InternalGetSignature(out length);
                return new TypeToken(GetTokenFromTypeSpec(sig, length));
            }

            Module refedModule = type.Module;

            if (refedModule.Equals(this))
            {
                // no need to do anything additional other than defining the TypeRef Token
                TypeBuilder typeBuilder = null;
                GenericTypeParameterBuilder paramBuilder = null;

                EnumBuilder enumBuilder = type as EnumBuilder;
                if (enumBuilder != null)
                    typeBuilder = enumBuilder.m_typeBuilder;
                else
                    typeBuilder = type as TypeBuilder;

                if (typeBuilder != null)
                {
                    // optimization: if the type is defined in this module,
                    // just return the token
                    //
                    return typeBuilder.TypeToken;
                }
                else if ((paramBuilder = type as GenericTypeParameterBuilder) != null)
                {
                    return new TypeToken(paramBuilder.MetadataTokenInternal);
                }
                
                return new TypeToken(GetTypeRefNested(type, this, String.Empty));
            }
                    
            // After this point, the referenced module is not the same as the referencing
            // module.
            //
            ModuleBuilder refedModuleBuilder = refedModule as ModuleBuilder;

            String strRefedModuleFileName = String.Empty;
            if (refedModule.Assembly.Equals(this.Assembly))
            {
                // if the referenced module is in the same assembly, the resolution
                // scope of the type token will be a module ref, we will need
                // the file name of the referenced module for that.
                // if the refed module is in a different assembly, the resolution
                // scope of the type token will be an assembly ref. We don't need
                // the file name of the referenced module.
                if (refedModuleBuilder == null)
                {
                    refedModuleBuilder = this.ContainingAssemblyBuilder.GetModuleBuilder((InternalModuleBuilder)refedModule);
                }
                strRefedModuleFileName = refedModuleBuilder.m_moduleData.m_strFileName;
            }

            return new TypeToken(GetTypeRefNested(type, refedModule, strRefedModuleFileName));
        }
        
        public TypeToken GetTypeToken(String name)
        {
            // Return a token for the class relative to the Module. 
            // Module.GetType() verifies name
            
            // Unfortunately, we will need to load the Type and then call GetTypeToken in 
            // order to correctly track the assembly reference information.
            
            return GetTypeToken(InternalModule.GetType(name, false, true));
        }

        public MethodToken GetMethodToken(MethodInfo method)
        {
            lock(SyncRoot)
            {
                return GetMethodTokenNoLock(method, true);
            }
        }

        internal MethodToken GetMethodTokenInternal(MethodInfo method)
        {
            lock(SyncRoot)
            {
                return GetMethodTokenNoLock(method, false);
            }
        }

        // For a method on a generic type, we should return the methoddef token on the generic type definition in two cases
        //   1. GetMethodToken
        //   2. ldtoken (see ILGenerator)
        // For all other occasions we should return the method on the generic type instantiated on the formal parameters.
        private MethodToken GetMethodTokenNoLock(MethodInfo method, bool getGenericTypeDefinition)
        {
            // Return a MemberRef token if MethodInfo is not defined in this module. Or 
            // return the MethodDef token. 
            if (method == null)
                throw new ArgumentNullException(nameof(method));
            Contract.EndContractBlock();

            int tr;
            int mr = 0;
            
            SymbolMethod symMethod = null;
            MethodBuilder methBuilder = null;

            if ( (methBuilder = method as MethodBuilder) != null )
            {
                int methodToken = methBuilder.MetadataTokenInternal;
                if (method.Module.Equals(this))
                    return new MethodToken(methodToken);

                if (method.DeclaringType == null)
                    throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_CannotImportGlobalFromDifferentModule"));

                // method is defined in a different module
                tr = getGenericTypeDefinition ? GetTypeToken(method.DeclaringType).Token : GetTypeTokenInternal(method.DeclaringType).Token;
                mr = GetMemberRef(method.DeclaringType.Module, tr, methodToken);
            }
            else if (method is MethodOnTypeBuilderInstantiation)
            {
                return new MethodToken(GetMemberRefToken(method, null));
            }
            else if ((symMethod = method as SymbolMethod) != null)
            {
                if (symMethod.GetModule() == this)
                    return symMethod.GetToken();

                // form the method token
                return symMethod.GetToken(this);
            }
            else
            {
                Type declaringType = method.DeclaringType;

                // We need to get the TypeRef tokens
                if (declaringType == null)
                    throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_CannotImportGlobalFromDifferentModule"));

                RuntimeMethodInfo rtMeth = null;

                if (declaringType.IsArray == true)
                {
                    // use reflection to build signature to work around the E_T_VAR problem in EEClass
                    ParameterInfo[] paramInfo = method.GetParameters();
                    
                    Type[] tt = new Type[paramInfo.Length];
                    
                    for (int i = 0; i < paramInfo.Length; i++)
                        tt[i] = paramInfo[i].ParameterType;

                    return GetArrayMethodToken(declaringType, method.Name, method.CallingConvention, method.ReturnType, tt);
                }
                else if ( (rtMeth = method as RuntimeMethodInfo) != null )
                {
                    tr = getGenericTypeDefinition ? GetTypeToken(method.DeclaringType).Token : GetTypeTokenInternal(method.DeclaringType).Token;
                    mr = GetMemberRefOfMethodInfo(tr, rtMeth);
                }
                else
                {
                    // some user derived ConstructorInfo
                    // go through the slower code path, i.e. retrieve parameters and form signature helper.
                    ParameterInfo[] parameters = method.GetParameters();

                    Type[] parameterTypes = new Type[parameters.Length];
                    Type[][] requiredCustomModifiers = new Type[parameterTypes.Length][];
                    Type[][] optionalCustomModifiers = new Type[parameterTypes.Length][];

                    for (int i = 0; i < parameters.Length; i++)
                    {
                        parameterTypes[i] = parameters[i].ParameterType;
                        requiredCustomModifiers[i] = parameters[i].GetRequiredCustomModifiers();
                        optionalCustomModifiers[i] = parameters[i].GetOptionalCustomModifiers();
                    }
          
                    tr = getGenericTypeDefinition ? GetTypeToken(method.DeclaringType).Token : GetTypeTokenInternal(method.DeclaringType).Token;

                    SignatureHelper sigHelp;

                    try 
                    {
                        sigHelp = SignatureHelper.GetMethodSigHelper(
                        this, method.CallingConvention, method.ReturnType, 
                        method.ReturnParameter.GetRequiredCustomModifiers(), method.ReturnParameter.GetOptionalCustomModifiers(), 
                        parameterTypes, requiredCustomModifiers, optionalCustomModifiers);
                    } 
                    catch(NotImplementedException)
                    {
                        // Legacy code deriving from MethodInfo may not have implemented ReturnParameter.
                        sigHelp = SignatureHelper.GetMethodSigHelper(this, method.ReturnType, parameterTypes);
                    }

                    int length;                                           
                    byte[] sigBytes = sigHelp.InternalGetSignature(out length);
                    mr = GetMemberRefFromSignature(tr, method.Name, sigBytes, length);
                }
            }

            return new MethodToken(mr);
        }

        internal int GetMethodTokenInternal(MethodBase method, IEnumerable<Type> optionalParameterTypes, bool useMethodDef)
        {
            int tk = 0;
            MethodInfo methodInfo = method as MethodInfo;

            if (method.IsGenericMethod)
            {
                // Constructors cannot be generic.
                Debug.Assert(methodInfo != null);

                // Given M<Bar> unbind to M<S>
                MethodInfo methodInfoUnbound = methodInfo;
                bool isGenericMethodDef = methodInfo.IsGenericMethodDefinition;

                if (!isGenericMethodDef)
                {
                    methodInfoUnbound = methodInfo.GetGenericMethodDefinition();
                }

                if (!this.Equals(methodInfoUnbound.Module)
                    || (methodInfoUnbound.DeclaringType != null && methodInfoUnbound.DeclaringType.IsGenericType))
                {
                    tk = GetMemberRefToken(methodInfoUnbound, null);
                }
                else
                {
                    tk = GetMethodTokenInternal(methodInfoUnbound).Token;
                }

                // For Ldtoken, Ldftn, and Ldvirtftn, we should emit the method def/ref token for a generic method definition.
                if (isGenericMethodDef && useMethodDef)
                {
                    return tk;
                }

                // Create signature of method instantiation M<Bar>
                int sigLength;
                byte[] sigBytes = SignatureHelper.GetMethodSpecSigHelper(
                    this, methodInfo.GetGenericArguments()).InternalGetSignature(out sigLength);

                // Create MethodSepc M<Bar> with parent G?.M<S> 
                tk = TypeBuilder.DefineMethodSpec(this.GetNativeHandle(), tk, sigBytes, sigLength);
            }
            else
            {
                if (((method.CallingConvention & CallingConventions.VarArgs) == 0) &&
                    (method.DeclaringType == null || !method.DeclaringType.IsGenericType))
                {
                    if (methodInfo != null)
                    {
                        tk = GetMethodTokenInternal(methodInfo).Token;
                    }
                    else
                    {
                        tk = GetConstructorToken(method as ConstructorInfo).Token;
                    }
                }
                else
                {
                    tk = GetMemberRefToken(method, optionalParameterTypes);
                }
            }

            return tk;
        }
    
        public MethodToken GetArrayMethodToken(Type arrayClass, String methodName, CallingConventions callingConvention, 
            Type returnType, Type[] parameterTypes)
        {
            lock(SyncRoot)
            {
                return GetArrayMethodTokenNoLock(arrayClass, methodName, callingConvention, returnType, parameterTypes);
            }
        }

        private MethodToken GetArrayMethodTokenNoLock(Type arrayClass, String methodName, CallingConventions callingConvention, 
            Type returnType, Type[] parameterTypes)
        {
            if (arrayClass == null)
                throw new ArgumentNullException(nameof(arrayClass));

            if (methodName == null)
                throw new ArgumentNullException(nameof(methodName));

            if (methodName.Length == 0)
                throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), nameof(methodName));

            if (arrayClass.IsArray == false)
                throw new ArgumentException(Environment.GetResourceString("Argument_HasToBeArrayClass")); 
            Contract.EndContractBlock();

            CheckContext(returnType, arrayClass);
            CheckContext(parameterTypes);

            // Return a token for the MethodInfo for a method on an Array.  This is primarily
            // used to get the LoadElementAddress method. 

            int length;

            SignatureHelper sigHelp = SignatureHelper.GetMethodSigHelper(
                this, callingConvention, returnType, null, null, parameterTypes, null, null);

            byte[] sigBytes = sigHelp.InternalGetSignature(out length);

            TypeToken typeSpec = GetTypeTokenInternal(arrayClass);

            return new MethodToken(GetArrayMethodToken(GetNativeHandle(),
                typeSpec.Token, methodName, sigBytes, length));
        }

        public MethodInfo GetArrayMethod(Type arrayClass, String methodName, CallingConventions callingConvention, 
            Type returnType, Type[] parameterTypes)
        {
            CheckContext(returnType, arrayClass);
            CheckContext(parameterTypes);

            // GetArrayMethod is useful when you have an array of a type whose definition has not been completed and 
            // you want to access methods defined on Array. For example, you might define a type and want to define a 
            // method that takes an array of the type as a parameter. In order to access the elements of the array, 
            // you will need to call methods of the Array class.

            MethodToken token = GetArrayMethodToken(arrayClass, methodName, callingConvention, returnType, parameterTypes);

            return new SymbolMethod(this, token, arrayClass, methodName, callingConvention, returnType, parameterTypes);
        }

        public MethodToken GetConstructorToken(ConstructorInfo con)
        {
            // Return a token for the ConstructorInfo relative to the Module. 
            return InternalGetConstructorToken(con, false);
        }

        public FieldToken GetFieldToken(FieldInfo field) 
        {
            lock(SyncRoot)
            {
                return GetFieldTokenNoLock(field);
            }
        }

        private FieldToken GetFieldTokenNoLock(FieldInfo field) 
        {
            if (field == null) {
                throw new ArgumentNullException(nameof(field));
            }
            Contract.EndContractBlock();

            int     tr;
            int     mr = 0;

            FieldBuilder fdBuilder = null;
            RuntimeFieldInfo rtField = null;
            FieldOnTypeBuilderInstantiation fOnTB = null;

            if ((fdBuilder = field as FieldBuilder) != null)
            {
                if (field.DeclaringType != null && field.DeclaringType.IsGenericType)
                {
                    int length;
                    byte[] sig = SignatureHelper.GetTypeSigToken(this, field.DeclaringType).InternalGetSignature(out length);
                    tr = GetTokenFromTypeSpec(sig, length);
                    mr = GetMemberRef(this, tr, fdBuilder.GetToken().Token);
                }
                else if (fdBuilder.Module.Equals(this))
                {
                    // field is defined in the same module
                    return fdBuilder.GetToken();
                }
                else
                {
                    // field is defined in a different module
                    if (field.DeclaringType == null)
                    {
                        throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_CannotImportGlobalFromDifferentModule"));
                    }
                    tr = GetTypeTokenInternal(field.DeclaringType).Token;
                    mr = GetMemberRef(field.ReflectedType.Module, tr, fdBuilder.GetToken().Token);
                }
            }
            else if ( (rtField = field as RuntimeFieldInfo) != null)
            {
                // FieldInfo is not an dynamic field
                
                // We need to get the TypeRef tokens
                if (field.DeclaringType == null)
                {
                    throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_CannotImportGlobalFromDifferentModule"));
                }
                
                if (field.DeclaringType != null && field.DeclaringType.IsGenericType)
                {
                    int length;
                    byte[] sig = SignatureHelper.GetTypeSigToken(this, field.DeclaringType).InternalGetSignature(out length);
                    tr = GetTokenFromTypeSpec(sig, length);
                    mr = GetMemberRefOfFieldInfo(tr, field.DeclaringType.GetTypeHandleInternal(), rtField);
                }
                else
                {
                    tr = GetTypeTokenInternal(field.DeclaringType).Token;       
                    mr = GetMemberRefOfFieldInfo(tr, field.DeclaringType.GetTypeHandleInternal(), rtField);
                }
            }
            else if ( (fOnTB = field as FieldOnTypeBuilderInstantiation) != null)
            {
                FieldInfo fb = fOnTB.FieldInfo;
                int length;
                byte[] sig = SignatureHelper.GetTypeSigToken(this, field.DeclaringType).InternalGetSignature(out length);
                tr = GetTokenFromTypeSpec(sig, length);
                mr = GetMemberRef(fb.ReflectedType.Module, tr, fOnTB.MetadataTokenInternal);
            }
            else
            {
                // user defined FieldInfo
                tr = GetTypeTokenInternal(field.ReflectedType).Token;

                SignatureHelper sigHelp = SignatureHelper.GetFieldSigHelper(this);

                sigHelp.AddArgument(field.FieldType, field.GetRequiredCustomModifiers(), field.GetOptionalCustomModifiers());

                int length;
                byte[] sigBytes = sigHelp.InternalGetSignature(out length);

                mr = GetMemberRefFromSignature(tr, field.Name, sigBytes, length);
            }
            
            return new FieldToken(mr, field.GetType());
        }
        
        public StringToken GetStringConstant(String str) 
        {
            if (str == null)
            {
                throw new ArgumentNullException(nameof(str));
            }
            Contract.EndContractBlock();

            // Returns a token representing a String constant.  If the string 
            // value has already been defined, the existing token will be returned.
            return new StringToken(GetStringConstant(GetNativeHandle(), str, str.Length));
        }
    
        public SignatureToken GetSignatureToken(SignatureHelper sigHelper)
        {
            // Define signature token given a signature helper. This will define a metadata
            // token for the signature described by SignatureHelper.

            if (sigHelper == null)
            {
                throw new ArgumentNullException(nameof(sigHelper));
            }
            Contract.EndContractBlock();

            int sigLength;
            byte[] sigBytes;
    
            // get the signature in byte form
            sigBytes = sigHelper.InternalGetSignature(out sigLength);
            return new SignatureToken(TypeBuilder.GetTokenFromSig(GetNativeHandle(), sigBytes, sigLength), this);
        }           
        public SignatureToken GetSignatureToken(byte[] sigBytes, int sigLength)
        {
            if (sigBytes == null)
                throw new ArgumentNullException(nameof(sigBytes));
            Contract.EndContractBlock();

            byte[] localSigBytes = new byte[sigBytes.Length];
            Buffer.BlockCopy(sigBytes, 0, localSigBytes, 0, sigBytes.Length);

            return new SignatureToken(TypeBuilder.GetTokenFromSig(GetNativeHandle(), localSigBytes, sigLength), this);
        }
    
        #endregion

        #region Other

        public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute)
        {
            if (con == null)
                throw new ArgumentNullException(nameof(con));
            if (binaryAttribute == null)
                throw new ArgumentNullException(nameof(binaryAttribute));
            Contract.EndContractBlock();
            
            TypeBuilder.DefineCustomAttribute(
                this,
                1,                                          // This is hard coding the module token to 1
                this.GetConstructorToken(con).Token,
                binaryAttribute,
                false, false);
        }

        public void SetCustomAttribute(CustomAttributeBuilder customBuilder)
        {
            if (customBuilder == null)
            {
                throw new ArgumentNullException(nameof(customBuilder));
            }
            Contract.EndContractBlock();

            customBuilder.CreateCustomAttribute(this, 1);   // This is hard coding the module token to 1
        }

        // This API returns the symbol writer being used to write debug symbols for this 
        // module (if any).
        // 
        // WARNING: It is unlikely this API can be used correctly by applications in any 
        // reasonable way.  It may be called internally from within TypeBuilder.CreateType.
        // 
        // Specifically:
        // 1. The underlying symbol writer (written in unmanaged code) is not necessarily well
        // hardenned and fuzz-tested against malicious API calls.  The security of partial-trust
        // symbol writing is improved by restricting usage of the writer APIs to the well-structured
        // uses in ModuleBuilder. 
        // 2. TypeBuilder.CreateType emits all the symbols for the type.  This will effectively 
        // overwrite anything someone may have written manually about the type (specifically 
        // ISymbolWriter.OpenMethod is specced to clear anything previously written for the 
        // specified method)
        // 3. Someone could technically update the symbols for a method after CreateType is 
        // called, but the debugger (which uses these symbols) assumes that they are only 
        // updated at TypeBuilder.CreateType time.  The changes wouldn't be visible (committed 
        // to the underlying stream) until another type was baked.
        // 4. Access to the writer is supposed to be synchronized (the underlying COM API is 
        // not thread safe, and these are only thin wrappers on top of them).  Exposing this 
        // directly allows the synchronization to be violated.  We know that concurrent symbol 
        // writer access can cause AVs and other problems.  The writer APIs should not be callable
        // directly by partial-trust code, but if they could this would be a security hole.  
        // Regardless, this is a reliability bug.  
        // 
        // For these reasons, we should consider making this API internal in Arrowhead
        // (as it is in Silverlight), and consider validating that we're within a call
        // to TypeBuilder.CreateType whenever this is used.
        internal ISymbolWriter GetSymWriter()
        {
            return m_iSymWriter;
        }

        public ISymbolDocumentWriter DefineDocument(String url, Guid language, Guid languageVendor, Guid documentType)
        {
            // url cannot be null but can be an empty string 
            if (url == null)
                throw new ArgumentNullException(nameof(url));
            Contract.EndContractBlock();

            lock(SyncRoot)
            {
                return DefineDocumentNoLock(url, language, languageVendor, documentType);
            }
        }

        private ISymbolDocumentWriter DefineDocumentNoLock(String url, Guid language, Guid languageVendor, Guid documentType)
        {
            if (m_iSymWriter == null)
            {
                // Cannot DefineDocument when it is not a debug module
                throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NotADebugModule"));
            }

            return m_iSymWriter.DefineDocument(url, language, languageVendor, documentType);
        }
    
        [Pure]
        public bool IsTransient()
        {
            return InternalModule.IsTransientInternal();
        }

        #endregion

        #endregion    
    }
}