download ceeload.cpp
Language: C++
Copyright: (c) 2006 Microsoft Corporation. All rights reserved.
LOC: 3648
Project Info
Shared Source Common Language Infrastructure(sscli20)
Server: Shared Source Common Language Infrastructure
Type: filesystem
...sscli20\sscli20\clr\src\vm\
   appdomain.cpp
   appdomain.hpp
   appdomain.inl
   appdomainhelper.cpp
   appdomainhelper.h
   appdomainnative.cpp
   appdomainnative.hpp
   appdomainstack.cpp
   appdomainstack.h
   appdomainstack.inl
   argslot.h
   array.cpp
   array.h
   assembly.cpp
   assembly.hpp
   assemblyname.cpp
   assemblyname.hpp
   assemblynative.cpp
   assemblynative.hpp
   assemblysink.cpp
   assemblysink.h
   assemblyspec.cpp
   assemblyspec.hpp
   binder.cpp
   binder.h
   cachelinealloc.cpp
   cachelinealloc.h
   ceeload.cpp
   ceeload.h
   ceeload.inl
   ceemain.cpp
   ceemain.h
   certificatecache.cpp
   certificatecache.h
   cgensys.h
   class.cpp
   class.h
   class.inl
   classloadlevel.h
   classnames.h
   clrex.cpp
   clrex.h
   clsload.cpp
   clsload.hpp
   clsload.inl
   codeman.cpp
   codeman.h
   codeman.inl
   comarrayhelpers.cpp
   comarrayhelpers.h
   comarrayinfo.cpp
   comarrayinfo.h
   comcallablewrapper.cpp
   comcallablewrapper.h
   comcurrency.cpp
   comcurrency.h
   comdatetime.cpp
   comdatetime.h
   comdecimal.cpp
   comdecimal.h
   comdelegate.cpp
   comdelegate.h
   comdynamic.cpp
   comdynamic.h
   comisolatedstorage.cpp
   comisolatedstorage.h
   commemoryfailpoint.cpp
   commemoryfailpoint.h
   commethodrental.cpp
   commethodrental.h
   commodule.cpp
   commodule.h
   common.cpp
   common.h
   comnumber.cpp
   comnumber.h
   comobject.cpp
   comobject.h
   comreflectioncache.hpp
   comreflectioncommon.cpp
   comreflectioncommon.h
   comstreams.cpp
   comstreams.h
   comstring.cpp
   comstring.h
   comstringbuffer.cpp
   comstringbuffer.h
   comstringcommon.h
   comsynchronizable.cpp
   comsynchronizable.h
   comsystem.cpp
   comsystem.h
   comthreadpool.cpp
   comthreadpool.h
   comutilnative.cpp
   comutilnative.h
   comvarargs.cpp
   comvarargs.h
   comvariant.cpp
   comvariant.h
   comwaithandle.cpp
   comwaithandle.h
   confighelper.cpp
   confighelper.h
   ...inedexecutionregion.cpp
   ...rainedexecutionregion.h
   context.h
   contexts.cpp
   contractimpl.cpp
   contractimpl.h
   corhost.cpp
   crossdomaincalls.cpp
   crossdomaincalls.h
   crst.cpp
   crst.h
   cryptapis.h
   ctxtcall.h
   customattribute.cpp
   customattribute.h
   custommarshalerinfo.cpp
   custommarshalerinfo.h
   dbginterface.h
   debugdebugger.cpp
   debugdebugger.h
   debughelp.cpp
   debuginfostore.cpp
   debuginfostore.h
   decodemd.cpp
   decodemd.h
   delegateinfo.h
   dllimport.cpp
   dllimport.h
   dllimportcallback.cpp
   dllimportcallback.h
   domainfile.cpp
   domainfile.h
   domainfile.inl
   dynamicmethod.cpp
   dynamicmethod.h
   ecall.cpp
   ecall.h
   ecmakey.h
   eecallconv.h
   eeconfig.cpp
   eeconfig.h
   eeconfigfactory.cpp
   eeconfigfactory.h
   eecontract.cpp
   eecontract.h
   eecontract.inl
   eedbginterface.h
   eedbginterfaceimpl.cpp
   eedbginterfaceimpl.h
   eedbginterfaceimpl.inl
   eehash.cpp
   eehash.h
   eemessagebox.cpp
   eemessagebox.h
   eepolicy.cpp
   eepolicy.h
   eeprofinterfaces.h
   eeprofinterfaces.inl
   ...rofinterfacewrapper.inl
   eetwain.cpp
   encee.h
   eventstore.cpp
   eventstore.hpp
   excep.cpp
   excep.h
   exceptmacros.h
   exinfo.cpp
   exinfo.h
   exstate.cpp
   exstate.h
   exstatecommon.h
   fcall.cpp
   fcall.h
   field.cpp
   field.h
   fieldmarshaler.cpp
   fieldmarshaler.h
   fjit_eetwain.cpp
   fjit_eetwain.h
   fptrstubs.cpp
   fptrstubs.h
   frames.cpp
   frames.h
   fusionbind.cpp
   fusioninit.cpp
   fusionsink.cpp
   fusionwrap.cpp
   fusionwrap.h
   gc.h
   gccommon.cpp
   gcdecode.cpp
   gcdesc.h
   gcee.cpp
   gceesvr.cpp
   gceewks.cpp
   gchost.cpp
   gcimpl.h
   gcscan.cpp
   gcscan.h
   gcsmp.cpp
   gcsmppriv.h
   gcsvr.cpp
   gcwks.cpp
   genericdict.cpp
   genericdict.h
   generics.cpp
   generics.h
   genmeth.cpp
   gmheap.cpp
   gmheap.hpp
   gms.h
   h2inc.pl
   handletable.cpp
   handletable.h
   handletable.inl
   handletablecache.cpp
   handletablecore.cpp
   handletablepriv.h
   handletablescan.cpp
   hash.cpp
   hash.h
   hostexecutioncontext.cpp
   hostexecutioncontext.h
   hosting.cpp
   hosting.h
   ibclogger.h
   ildump.h
   ilmarshalers.cpp
   ilmarshalers.h
   ilstubcache.cpp
   ilstubcache.h
   ilstubresolver.cpp
   ilstubresolver.h
   instmethhash.cpp
   instmethhash.h
   interopconverter.cpp
   interopconverter.h
   interoputil.cpp
   interoputil.h
   ...lidoverlappedwrappers.h
   invokeutil.cpp
   invokeutil.h
   jithelpers.cpp
   jitinterface.cpp
   jitinterface.h
   jitinterfacegen.cpp
   list.cpp
   list.h
   listlock.cpp
   listlock.h
   listlock.inl
   makefile.inc
   managedmdimport.cpp
   managedmdimport.hpp
   marshaler.h
   marshalnative.cpp
   marshalnative.h
   mdaassistants.h
   mdaassistantsptr.h
   memberload.cpp
   memberload.h
   message.cpp
   message.h
   metasig.h
   method.cpp
   method.hpp
   method.inl
   methodimpl.cpp
   methodimpl.h
   methoditer.cpp
   methoditer.h
   methodtable.cpp
   methodtable.h
   methodtable.inl
   ml.cpp
   ml.h
   mlcache.cpp
   mlcache.h
   mlgen.cpp
   mlgen.h
   mlinfo.cpp
   mlinfo.h
   mlopdef.h
   mscorlib.h
   mtypes.h
   namespace.h
   nativeoverlapped.cpp
   nativeoverlapped.h
   newcompressedstack.cpp
   newcompressedstack.h
   nsenums.h
   object.cpp
   object.h
   object.inl
   objectclone.cpp
   objectclone.h
   objecthandle.cpp
   objecthandle.h
   objectlist.cpp
   objectlist.h
   olevariant.cpp
   olevariant.h
   pefile.cpp
   pefile.h
   pefile.inl
   peimage.cpp
   peimage.h
   peimage.inl
   peimagelayout.cpp
   peimagelayout.h
   peimagelayout.inl
   pendingload.cpp
   pendingload.h
   precode.cpp
   precode.h
   prestub.cpp
   proftoeeinterfaceimpl.cpp
   proftoeeinterfaceimpl.h
   reflectclasswriter.cpp
   reflectclasswriter.h
   reflectioninvocation.cpp
   reflectioninvocation.h
   remoting.cpp
   remoting.h
   rexcep.h
   runtimeexceptionkind.h
   runtimehandles.cpp
   runtimehandles.h
   rwlock.cpp
   rwlock.h
   safehandle.cpp
   security.h
   security.inl
   securityattributes.cpp
   securityattributes.h
   securityconfig.cpp
   securityconfig.h
   securitydeclarative.cpp
   securitydeclarative.h
   securitydescriptor.cpp
   securitydescriptor.h
   ...descriptorappdomain.cpp
   ...tydescriptorappdomain.h
   ...ydescriptorassembly.cpp
   ...itydescriptorassembly.h
   securityhostprotection.cpp
   securityhostprotection.h
   securityimperative.cpp
   securityimperative.h
   securitymeta.cpp
   securitymeta.h
   securitypolicy.cpp
   securitypolicy.h
   securitystackwalk.cpp
   securitystackwalk.h
   ...transparentassembly.cpp
   ...tytransparentassembly.h
   sigformat.cpp
   sigformat.h
   siginfo.cpp
   siginfo.hpp
   simplerwlock.cpp
   simplerwlock.hpp
   sourceline.cpp
   sourceline.h
   sources.dac
   sources.inc
   specialstatics.h
   spinlock.cpp
   spinlock.h
   stackbuildersink.cpp
   stackbuildersink.h
   stackcompressor.cpp
   stackcompressor.h
   stackingallocator.cpp
   stackingallocator.h
   stackprobe.h
   stackprobe.inl
   stackwalk.cpp
   stackwalk.h
   stackwalktypes.h
   stringliteralmap.cpp
   stringliteralmap.h
   strongname.cpp
   stubgen.h
   stublink.cpp
   stublink.h
   stublink.inl
   stubmgr.cpp
   stubmgr.h
   syncblk.cpp
   syncblk.h
   syncblk.inl
   syncclean.cpp
   syncclean.hpp
   synch.cpp
   synch.h
   ...zationcontextnative.cpp
   ...nizationcontextnative.h
   testhookmgr.cpp
   testhookmgr.h
   thekey.h
   threads.cpp
   threads.h
   threads.inl
   tokeniter.cpp
   tokeniter.hpp
   typectxt.cpp
   typectxt.h
   typedesc.cpp
   typedesc.h
   typedesc.inl
   typehandle.cpp
   typehandle.h
   typehandle.inl
   typehash.cpp
   typehash.h
   typekey.h
   typeparse.cpp
   typeparse.h
   typestring.cpp
   typestring.h
   umthunkhash.cpp
   umthunkhash.h
   util.cpp
   util.hpp
   validator.cpp
   vars.cpp
   vars.hpp
   verifier.cpp
   verifier.hpp
   veropcodes.hpp
   vertable.h
   virtualcallstub.cpp
   virtualcallstub.h
   vmholder.h
   win32threadpool.cpp
   win32threadpool.h
   wrappers.h

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
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
// ==++==
//
//   
//    Copyright (c) 2006 Microsoft Corporation.  All rights reserved.
//   
//    The use and distribution terms for this software are contained in the file
//    named license.txt, which can be found in the root of this distribution.
//    By using this software in any fashion, you are agreeing to be bound by the
//    terms of this license.
//   
//    You must not remove this notice, or any other, from this software.
//   
//
// ==--==
// ===========================================================================
// File: CEELOAD.CPP
//

// CEELOAD reads in the PE file format using LoadLibrary
// ===========================================================================

#include "common.h"

#include "array.h"
#include "ceeload.h"
#include "hash.h"
#include "vars.hpp"
#include "reflectclasswriter.h"
#include "method.hpp"
#include "stublink.h"
#include "security.h"
#include "cgensys.h"
#include "excep.h"
#include "dbginterface.h"
#include "dllimport.h"
#include "eeprofinterfaces.h"
#include "perfcounters.h"
#include "encee.h"
#include "jitinterface.h"
#include "eeconfig.h"
#include "dllimportcallback.h"
#include "contractimpl.h"
#include "typehash.h"
#include "instmethhash.h"
#include "virtualcallstub.h"
#include "typestring.h"
#include "stringliteralmap.h"
#include "eventtrace.h"
#include "securitytransparentassembly.h"
#include "prettyprintsig.h"



#include "perflog.h"
#include "timeline.h"
#include "memoryreport.h"
#include "ecall.h"
#include "objectclone.h"
#include "constrainedexecutionregion.h"
#include "typekey.h"
#include "peimagelayout.inl"

#define COR_VTABLE_PTRSIZED     COR_VTABLE_32BIT
#define COR_VTABLE_NOT_PTRSIZED COR_VTABLE_64BIT

// Hash table parameter of available classes (name -> module/class) hash
#define AVAILABLE_CLASSES_HASH_BUCKETS 1024
#define PARAMTYPES_HASH_BUCKETS 23
#define PARAMMETHODS_HASH_BUCKETS 11

#define NGEN_STATICS_ALLCLASSES_WERE_LOADED -1

#ifdef _X86_ 
extern "C" VOID __stdcall IJWNOADThunkJumpTarget(void);
#endif




#ifndef DACCESS_COMPILE 

HRESULT STDMETHODCALLTYPE CreateICeeGen(REFIID riid, void **pCeeGen);


// {F5398690-98FE-11d2-9C56-00A0C9B7CC45}
const GUID IID_ICorReflectionModule =
{ 0xf5398690, 0x98fe, 0x11d2, { 0x9c, 0x56, 0x0, 0xa0, 0xc9, 0xb7, 0xcc, 0x45 } };





// ===========================================================================
// Module
// ===========================================================================

#ifdef _X86_
#define FixupVTableSlot FixupVTableSlotX86
#endif

void __cdecl FixupVTableSlot();

//---------------------------------------------------------------------------------------------------
// This wrapper just invokes the real initialization inside a try/hook.
//---------------------------------------------------------------------------------------------------
void Module::DoInit(AllocMemTracker *pamTracker)
{
    CONTRACTL
    {
        INSTANCE_CHECK;
        THROWS;
        GC_TRIGGERS;
        MODE_ANY;
        INJECT_FAULT(COMPlusThrowOM());
    }
    CONTRACTL_END;

    MEMORY_REPORT_CONTEXT_SCOPE("Module");

    if (CORProfilerTrackModuleLoads())
    {
        PROFILER_CALL;
        g_profControlBlock.pProfInterface->ModuleLoadStarted((ThreadID) GetThread(), (ModuleID) this);
    }
    // Need TRY/HOOK instead of holder so we can get HR of exception thrown for profiler callback
    EX_TRY
    {
        Initialize(pamTracker);
    }
    EX_HOOK
    {
        if (CORProfilerTrackModuleLoads())
        {
            PROFILER_CALL;
            g_profControlBlock.pProfInterface->ModuleLoadFinished((ThreadID) GetThread(),
                                                                 (ModuleID) this, GET_EXCEPTION()->GetHR());
        }
    }
    EX_END_HOOK;
}

#if PROFILING_SUPPORTED 
void Module::NotifyProfilerLoadFinished(HRESULT hr)
{
    CONTRACTL
    {
        INSTANCE_CHECK;
        THROWS;
        GC_TRIGGERS;
        INJECT_FAULT(COMPlusThrowOM());
        MODE_ANY;
    }
    CONTRACTL_END;

    // Note that in general we wil reuse shared modules.  So we need to make sure we only notify
    // the profiler once.

    if (FastInterlockCompareExchange(&m_profilerNotified, 1, 0) == 0)
    {
    
        if (CORProfilerTrackModuleLoads())
        {
            PROFILER_CALL;
            g_profControlBlock.pProfInterface->ModuleLoadFinished((ThreadID) GetThread(), (ModuleID) this, hr);

            if (SUCCEEDED(hr))
            {
                GetISymUnmanagedReader();
                g_profControlBlock.pProfInterface->ModuleAttachedToAssembly((ThreadID) GetThread(), (ModuleID) this,
                                                                            (AssemblyID) m_pAssembly);
            }
        }

        if (CORProfilerTrackAssemblyLoads() && IsManifest())
        {
            PROFILER_CALL;
            g_profControlBlock.pProfInterface->AssemblyLoadFinished((ThreadID) GetThread(), (AssemblyID) m_pAssembly, hr);
        }
    }
}
#endif // PROFILING_SUPPORTED


// Module initialization occurs in two phases: the constructor phase and the Initialize phase.
//
// The constructor phase initializes just enough so that Destruct() can be safely called.
// It cannot throw or fail.
//
Module::Module(Assembly *pAssembly, mdFile moduleRef, PEFile *file)
{
    CONTRACTL
    {
        NOTHROW;
        GC_TRIGGERS;
        FORBID_FAULT;
    }
    CONTRACTL_END

    PREFIX_ASSUME(pAssembly != NULL);

    m_pAssembly = pAssembly;
    m_moduleRef = moduleRef;
    m_file      = file;
    m_dwTransientFlags = CLASSES_FREED;


    m_pISymUnmanagedReaderLock = NULL;
    m_dwDebuggerJMCProbeCount  = 0;


#ifdef PROFILING_SUPPORTED_DATA 
    m_profilerNotified         = 0;
#endif

    m_pCerPrepInfo              = NULL;
    m_pCerCrst                  = NULL;

    m_pRVAOverrides             = NULL;
    m_pRVAOverridesCrst         = NULL;

    m_pRemotingInterfaceThunks  = NULL;
    m_pRemotingInterfaceThunksCrst = NULL;
    if (!m_file->HasNativeImage())
    {
        // Init fields which are persisted in the native image
        m_dwCompilationRelaxationFlags = 0;
        m_cDynamicEntries           = 0;
        m_pStaticOffsets            = 0;
        m_maxDynamicEntries         = 0;
        m_dwMaxGCStaticHandles      = 0;
        m_dwStaticsBlockSize        = 0;
        m_dwPersistedFlags          = 0;
        m_pDllMain                  = NULL;
        m_pVASigCookieBlock         = NULL;
        m_pISymUnmanagedReader      = NULL;

        m_pIStreamSym               = NULL;

        // Set up tables
        ZeroMemory(&m_TypeDefToMethodTableMap, sizeof(LookupMap));
        m_dwTypeDefMapBlockSize = 0;
        ZeroMemory(&m_TypeRefToMethodTableMap, sizeof(LookupMap));
        m_dwTypeRefMapBlockSize = 0;
        ZeroMemory(&m_MethodDefToDescMap, sizeof(LookupMap));
        m_dwMethodDefMapBlockSize = 0;
        ZeroMemory(&m_FieldDefToDescMap, sizeof(LookupMap));
        m_dwFieldDefMapBlockSize = 0;
        ZeroMemory(&m_MemberRefToDescMap, sizeof(LookupMap));
        m_dwMemberRefMapBlockSize = 0;
        ZeroMemory(&m_FileReferencesMap, sizeof(LookupMap));
        m_dwFileReferencesMapBlockSize = 0;
        ZeroMemory(&m_ManifestModuleReferencesMap, sizeof(LookupMap));
        m_dwManifestModuleReferencesMapBlockSize = 0;

        m_pAvailableClasses         = NULL;
        m_pAvailableClassesCaseIns  = NULL;
        m_pAvailableParamTypes      = NULL;
        m_pInstMethodHashTable      = NULL;
        m_pDynamicStaticsInfo       = NULL;

        ZeroMemory(&m_ModuleCtorInfo, sizeof(m_ModuleCtorInfo));

        m_pBinder                   = NULL;





#ifdef _DEBUG 
        m_dwDebugArrayClassSize   = 0;
#endif

        // If we are being created fresh, the compilation type will match the loading type.
        // If we were ngenned, we will retain the compilation type across the load operation.

        if (pAssembly->IsDomainNeutral())
            m_dwPersistedFlags |= COMPILED_DOMAIN_NEUTRAL;

        m_pModuleSecurityDescriptor = NULL;
    }

    file->AddRef();
}



// Module initialization occurs in two phases: the constructor phase and the Initialize phase.
//
// The Initialize() phase completes the initialization after the constructor has run.
// It can throw exceptions but whether it throws or succeeds, it must leave the Module
// in a state where Destruct() can be safely called.
//
void Module::Initialize(AllocMemTracker *pamTracker)
{
    CONTRACTL
    {
        INSTANCE_CHECK;
        THROWS;
        GC_TRIGGERS;
        MODE_ANY;
    }
    CONTRACTL_END;
    m_dwNumberOfActivations=0;
    m_Crst.Init("ModuleCrst", CrstModule, CRST_DEFAULT);
    m_LookupTableCrst.Init("ModuleLookupTableCrst", CrstModuleLookupTable, CrstFlags(CRST_UNSAFE_ANYMODE | CRST_DEBUGGER_THREAD));
    m_FixupCrst.Init("StringFixupCrst", CrstModuleFixup, (CrstFlags)(CRST_DEFAULT|CRST_HOST_BREAKABLE|CRST_REENTRANCY));
    m_InstMethodHashTableCrst.Init("InstMethodHashTableCrst", CrstInstMethodHashTable, CRST_REENTRANCY);

    if (!m_file->HasNativeImage())
    {
        m_rgDispatchTypeTable = NULL;
        AllocateMaps();

        _ASSERT(m_pModuleSecurityDescriptor == NULL);
        m_pModuleSecurityDescriptor = new ModuleSecurityDescriptor(this);

    }

    m_dwTransientFlags &= ~((DWORD)CLASSES_FREED);  // Set flag indicating LookupMaps are now in a consistent and destructable state
    
#ifdef PROFILING_SUPPORTED 
    // Profiler enabled, and re-jits requested?
    // if (CORProfilerAllowRejit())
    // {
    //    not supported in V2
    // }
#endif // PROFILING_SUPPORTED

#ifdef _DEBUG 
    m_fForceVerify = FALSE;
#endif

    if (m_pAvailableClasses == NULL && !IsResource())
    {
        m_pAvailableClasses = EEClassHashTable::Create(this,
                                                       AVAILABLE_CLASSES_HASH_BUCKETS,
                                                       FALSE /* bCaseInsensitive */, pamTracker);
    }

    if (m_pAvailableParamTypes == NULL && !IsResource())
    {
        m_pAvailableParamTypes = EETypeHashTable::Create(GetDomain(), this, PARAMTYPES_HASH_BUCKETS, pamTracker);
    }

    if (m_pInstMethodHashTable == NULL && !IsResource())
    {
        m_pInstMethodHashTable = InstMethodHashTable::Create(GetDomain(), this, PARAMMETHODS_HASH_BUCKETS, pamTracker);
    }

    if (GetAssembly()->IsDomainNeutral())
    {
        // Allocate the slots, record their values and get our shared module index
        // Note that we shift over one and tag it with the low bit
        m_pDomainLocalModule = (DomainLocalModule *) DomainLocalBlock::AllocateModuleID();
    }
    else
    {
        // this will be initialized a bit later.
        m_pDomainLocalModule = NULL;
    }

    // Prepare statics that are known at module load time
    AllocateStatics(pamTracker);


    LOG((LF_CLASSLOADER, LL_INFO10, "Loaded pModule: \"%ws\".\n", GetDebugName()));

}


#ifdef DEBUGGING_SUPPORTED 
void Module::SetDebuggerInfoBits(DebuggerAssemblyControlFlags newBits)
{
    LEAF_CONTRACT;

    _ASSERTE(((newBits << DEBUGGER_INFO_SHIFT_PRIV) &
              ~DEBUGGER_INFO_MASK_PRIV) == 0);

    m_dwTransientFlags &= ~DEBUGGER_INFO_MASK_PRIV;
    m_dwTransientFlags |= (newBits << DEBUGGER_INFO_SHIFT_PRIV);

    BOOL setEnC = ((newBits & DACF_ENC_ENABLED) != 0) && IsEditAndContinueCapable() && !GetAssembly()->IsDomainNeutral();

    // The only way can change Enc is through debugger override.
    if (setEnC)
    {
        EnableEditAndContinue();
    }
    else
    {
        DisableEditAndContinue();
    }
}
#endif // DEBUGGING_SUPPORTED

/* static */
Module *Module::Create(Assembly *pAssembly, mdFile moduleRef, PEFile *file, AllocMemTracker *pamTracker)
{
    CONTRACT(Module *)
    {
        THROWS;
        GC_TRIGGERS;
        MODE_ANY;
        PRECONDITION(CheckPointer(pAssembly));
        PRECONDITION(CheckPointer(file));
        PRECONDITION(!IsNilToken(moduleRef) || file->IsAssembly());
        POSTCONDITION(CheckPointer(RETVAL));
        POSTCONDITION(RETVAL->GetFile() == file);
    }
    CONTRACT_END;

    // Hoist CONTRACT into separate routine because of EX incompatibility

    Module *pModule = NULL;

    // Create the module


    if (pModule == NULL)
    {
        {
            void* pMemory = pamTracker->Track(pAssembly->GetHighFrequencyHeap()->AllocMem(sizeof(Module)));
            pModule = new (pMemory) Module(pAssembly, moduleRef, file);
        }
    }

    PREFIX_ASSUME(pModule != NULL);
    ModuleHolder pModuleSafe(pModule);
    pModuleSafe->DoInit(pamTracker);

    pModuleSafe.SuppressRelease();

    RETURN pModuleSafe;
}



//
// Destructor for Module
//

void Module::Destruct()
{
    CONTRACTL
    {
        INSTANCE_CHECK;
        NOTHROW;
        GC_TRIGGERS;
        MODE_ANY;
    }
    CONTRACTL_END;

    LOG((LF_EEMEM, INFO3, "Deleting module %x\n", this));
#ifdef PROFILING_SUPPORTED 
    if (!IsBeingUnloaded() && CORProfilerTrackModuleLoads())
    {
        // Profiler is causing some peripheral class loads. Probably this just needs
        // to be turned into a Fault_not_fatal and moved to a specific place inside the profiler.
        BEGIN_EXCEPTION_GLUE(/*hr=*/NULL, NULL)
        {
            PROFILER_CALL;
            g_profControlBlock.pProfInterface->ModuleUnloadStarted((ThreadID) GetThread(), (ModuleID) this);
        }
        END_EXCEPTION_GLUE
    }
#endif // PROFILING_SUPPORTED


    DACNotify::DoModuleUnloadNotification(this);

    // Free classes in the class table
    FreeClassTables();

#ifdef DEBUGGING_SUPPORTED 
    {
        GCX_PREEMP();
        g_pDebugInterface->DestructModule(this);
    }
#endif // DEBUGGING_SUPPORTED

    ReleaseISymUnmanagedReader();

    if (m_pISymUnmanagedReaderLock)
    {
        delete m_pISymUnmanagedReaderLock;
        m_pISymUnmanagedReaderLock = NULL;
    }

   // Clean up sig cookies
    VASigCookieBlock    *pVASigCookieBlock = m_pVASigCookieBlock;
    while (pVASigCookieBlock)
    {
        VASigCookieBlock    *pNext = pVASigCookieBlock->m_Next;

        for (UINT i = 0; i < pVASigCookieBlock->m_numcookies; i++)
            pVASigCookieBlock->m_cookies[i].Destruct();

        delete pVASigCookieBlock;

        pVASigCookieBlock = pNext;
    }




#ifdef PROFILING_SUPPORTED 
    if (CORProfilerTrackModuleLoads())
    {
        // Profiler is causing some peripheral class loads. Probably this just needs
        // to be turned into a Fault_not_fatal and moved to a specific place inside the profiler.
        BEGIN_EXCEPTION_GLUE(/*hr=*/NULL, NULL)
        {
            PROFILER_CALL;
            g_profControlBlock.pProfInterface->ModuleUnloadFinished((ThreadID) GetThread(),
                                                                    (ModuleID) this, S_OK);
        }
        END_EXCEPTION_GLUE
    }
#endif // PROFILING_SUPPORTED


    //
    // Warning - deleting the zap file will cause the module to be unmapped
    //
    IStream *pStream = GetInMemorySymbolStream();
    if(pStream != NULL)
    {
        pStream->Release();
        SetInMemorySymbolStream(NULL);
    }

    m_Crst.Destroy();
    m_FixupCrst.Destroy();
    m_LookupTableCrst.Destroy();
    m_InstMethodHashTableCrst.Destroy();

    if (m_pCerPrepInfo)
    {
        GCX_COOP();

        _ASSERTE(m_pCerCrst != NULL);
        CrstHolder sCrstHolder(m_pCerCrst);

        EEHashTableIteration sIter;
        m_pCerPrepInfo->IterateStart(&sIter);
        while (m_pCerPrepInfo->IterateNext(&sIter)) {
            CerPrepInfo *pPrepInfo = (CerPrepInfo*)m_pCerPrepInfo->IterateGetValue(&sIter);
            delete pPrepInfo;
        }

        delete m_pCerPrepInfo;
    }
    if (m_pCerCrst)
        delete m_pCerCrst;

    if (m_pRVAOverrides)
        delete m_pRVAOverrides;

    if (m_pRVAOverridesCrst)
        delete m_pRVAOverridesCrst;

    if (m_pRemotingInterfaceThunksCrst)
        delete m_pRemotingInterfaceThunksCrst;

    if (m_pRemotingInterfaceThunks)
        delete m_pRemotingInterfaceThunks;

    {
        m_file->Release();

        if (m_pModuleSecurityDescriptor)
            delete m_pModuleSecurityDescriptor;

    }
}


bool Module::NeedsGlobalMethodTable()
{
    CONTRACTL
    {
        INSTANCE_CHECK;
        THROWS;
        GC_TRIGGERS;
        MODE_ANY;
    }
    CONTRACTL_END;

    if (!IsResource() && GetMDImport()->IsValidToken(COR_GLOBAL_PARENT_TOKEN))
    {
        HENUMInternalHolder funcEnum(GetMDImport());
        funcEnum.EnumGlobalFunctionsInit();

        HENUMInternalHolder fieldEnum(GetMDImport());
        fieldEnum.EnumGlobalFieldsInit();

        if (GetMDImport()->EnumGetCount(&funcEnum) != 0
            || GetMDImport()->EnumGetCount(&fieldEnum) != 0)
        {
            return true;
        }
    }

    // resource module or no global statics nor global functions
    return false;
}


MethodTable *Module::GetGlobalMethodTable()
{
    CONTRACT (MethodTable *)
    {
        INSTANCE_CHECK;
        THROWS;
        GC_TRIGGERS;
        MODE_ANY;
        INJECT_FAULT(CONTRACT_RETURN NULL;);
        POSTCONDITION(CheckPointer(RETVAL, NULL_OK));
    }
    CONTRACT_END;


    if ((m_dwPersistedFlags & COMPUTED_GLOBAL_CLASS) == 0)
    {
        MethodTable *pMT = NULL;

        if (NeedsGlobalMethodTable())
        {
            pMT = ClassLoader::LoadTypeDefThrowing(this, COR_GLOBAL_PARENT_TOKEN,
                                                   ClassLoader::ThrowIfNotFound,
                                                   ClassLoader::FailIfUninstDefOrRef).AsMethodTable();
        }

        FastInterlockOr(&m_dwPersistedFlags, COMPUTED_GLOBAL_CLASS);
        RETURN pMT;
    }
    else
    {
        RETURN LookupTypeDef(COR_GLOBAL_PARENT_TOKEN).AsMethodTable();
    }
}


#endif // !DACCESS_COMPILE




BOOL Module::IsManifest()
{
    WRAPPER_CONTRACT;
    return PTR_HOST_TO_TADDR(GetAssembly()->GetManifestModule()) ==
        PTR_HOST_TO_TADDR(this);
}

DomainAssembly* Module::GetDomainAssembly(AppDomain *pDomain)
{
    CONTRACT(DomainAssembly *)
    {
        INSTANCE_CHECK;
        PRECONDITION(CheckPointer(pDomain, NULL_OK));
        POSTCONDITION(CheckPointer(RETVAL));
        THROWS;
        GC_TRIGGERS;
        MODE_ANY;
    }
    CONTRACT_END;

    if (IsManifest())
        RETURN (DomainAssembly *) GetDomainFile(pDomain);
    else
        RETURN (DomainAssembly *) m_pAssembly->GetDomainAssembly(pDomain);
}

DomainFile *Module::GetDomainFile(AppDomain *pDomain)
{
    CONTRACT(DomainFile *)
    {
        INSTANCE_CHECK;
        PRECONDITION(CheckPointer(pDomain, NULL_OK));
        POSTCONDITION(CheckPointer(RETVAL));
        GC_TRIGGERS;
        THROWS;
        MODE_ANY;
    }
    CONTRACT_END;

    // Null means current domain
    if (pDomain == NULL)
        pDomain = GetAppDomain();

    if (m_pAssembly->IsDomainNeutral())
    {
        DomainLocalBlock *pLocalBlock = pDomain->GetDomainLocalBlock();
        DomainFile *pDomainFile =  pLocalBlock->TryGetDomainFile(GetModuleID());

#ifndef DACCESS_COMPILE 
        if (pDomainFile == NULL)
            pDomainFile = pDomain->LoadDomainNeutralModuleDependency(this, FILE_LOADED);
#endif // !DACCESS_COMPILE

        RETURN (PTR_DomainFile) pDomainFile;
    }
    else
    {

        CONSISTENCY_CHECK(PTR_HOST_TO_TADDR(pDomain) == PTR_HOST_TO_TADDR(GetDomain()));
        RETURN PTR_DomainFile(m_pDomainLocalModule->GetDomainFile());
    }
}

DomainAssembly* Module::FindDomainAssembly(AppDomain *pDomain)
{
    CONTRACT(DomainAssembly *)
    {
        INSTANCE_CHECK;
        PRECONDITION(CheckPointer(pDomain));
        POSTCONDITION(CheckPointer(RETVAL, NULL_OK));
        NOTHROW;
        GC_NOTRIGGER;
        MODE_ANY;
    }
    CONTRACT_END;

    if (IsManifest())
        RETURN (DomainAssembly *) FindDomainFile(pDomain);
    else
        RETURN (DomainAssembly *) m_pAssembly->FindDomainAssembly(pDomain);
}

DomainModule *Module::GetDomainModule(AppDomain *pDomain)
{
    CONTRACT(DomainModule *)
    {
        INSTANCE_CHECK;
        PRECONDITION(CheckPointer(pDomain, NULL_OK));
        PRECONDITION(!IsManifest());
        POSTCONDITION(CheckPointer(RETVAL));

        THROWS;
        GC_TRIGGERS;
        MODE_ANY;
    }
    CONTRACT_END;

    RETURN (DomainModule *) GetDomainFile(pDomain);
}

DomainFile *Module::FindDomainFile(AppDomain *pDomain)
{
    CONTRACT(DomainFile *)
    {
        INSTANCE_CHECK;
        PRECONDITION(CheckPointer(pDomain));
        POSTCONDITION(CheckPointer(RETVAL, NULL_OK));
        NOTHROW;
        GC_NOTRIGGER;
        MODE_ANY;
        SO_TOLERANT;
    }
    CONTRACT_END;

    if (m_pAssembly->IsDomainNeutral())
    {
        DomainLocalBlock *pLocalBlock = pDomain->GetDomainLocalBlock();
        RETURN pLocalBlock->TryGetDomainFile(GetModuleID());
    }
    else
    {
        if (PTR_HOST_TO_TADDR(pDomain) == PTR_HOST_TO_TADDR(GetDomain()))
            RETURN PTR_DomainFile(m_pDomainLocalModule->GetDomainFile());
        else
            RETURN NULL;
    }
}

DomainModule *Module::FindDomainModule(AppDomain *pDomain)
{
    CONTRACT(DomainModule *)
    {
        INSTANCE_CHECK;
        PRECONDITION(CheckPointer(pDomain));
        PRECONDITION(!IsManifest());
        POSTCONDITION(CheckPointer(RETVAL, NULL_OK));
        GC_NOTRIGGER;
        NOTHROW;
        MODE_ANY;
    }
    CONTRACT_END;

    RETURN (DomainModule *) FindDomainFile(pDomain);
    }

#ifndef DACCESS_COMPILE 


CorElementType  Module::ParseMetadataForStaticsIsTypeDefEnum(mdToken tk, const SigTypeContext* pContext)
{
    CONTRACTL
    {
        THROWS;
        GC_TRIGGERS;
        INJECT_FAULT(COMPlusThrowOM(););
    }
    CONTRACTL_END;

    IMDInternalImport *pImport = GetMDImport();

    // The only condition we will be checking is that the parent of the type is System.Enum
    // Rest of the checks will be handed by class loader, which will fail to load if it's malformed
    // hence, no need to do all the checks here.
    mdToken tkParent = 0;
    DWORD dwParentAttr = 0;

    pImport->GetTypeDefProps(tk, &dwParentAttr, &tkParent);

    if(RidFromToken(tkParent)==0)
    {
        return ELEMENT_TYPE_END;
    }

    LPCSTR szName = NULL, szNamespace = NULL;
    switch(TypeFromToken(tkParent))
    {
        case mdtTypeDef:
            pImport->GetNameOfTypeDef(tkParent, &szName, &szNamespace);
            break;

        case mdtTypeRef:
            pImport->GetNameOfTypeRef(tkParent, &szNamespace, &szName);
            break;

        default:
            return ELEMENT_TYPE_END;
    }

    if (szName == NULL || szNamespace == NULL)
    {
        return ELEMENT_TYPE_END;
    }    
    
    // If it doesn't inherit from System.Enum, then it must be a value type
    // Note that loader will not load malformed types so this check is enough
    if(strcmp(szName,"Enum") != 0 || strcmp(szNamespace,"System") != 0)
    {
        return ELEMENT_TYPE_VALUETYPE;
    }

    // OK, it's an enum; find its instance field and get its type
    HENUMInternalHolderNoRef   hEnum(pImport);
    mdToken tkField;
    pImport->EnumInit(mdtFieldDef,tk,&hEnum);
    while(pImport->EnumNext(&hEnum,&tkField))
    {
        PCCOR_SIGNATURE pMemberSignature;
        DWORD           cMemberSignature;

        // Get the type of the static field.
        DWORD dwMemberAttribs = pImport->GetFieldDefProps(tkField);

        if(!IsFdStatic(dwMemberAttribs))
        {
            pMemberSignature = pImport->GetSigOfFieldDef(tkField, &cMemberSignature);
            HRESULT hr = validateTokenSig(tkField,pMemberSignature,cMemberSignature,dwMemberAttribs,pImport);

            if (FAILED(hr))
            {
                COMPlusThrowHR(hr);
            }

            SigTypeContext typeContext;
            MetaSig fsig(pMemberSignature, cMemberSignature, this, &typeContext, FALSE, MetaSig::sigField);
            CorElementType ElementType = fsig.NextArg();
            return ElementType;
        }
    }

    // no instance field found -- error!
    return ELEMENT_TYPE_END;
}

CorElementType  Module::ParseMetadataForStaticsIsValueTypeEnum(mdToken tk, const SigTypeContext* pContext)
{
    CONTRACTL
    {
        THROWS;
        GC_TRIGGERS;
        INJECT_FAULT(COMPlusThrowOM(););
    }
    CONTRACTL_END;

    if(TypeFromToken(tk) == mdtTypeDef)
    {
        return ParseMetadataForStaticsIsTypeDefEnum(tk, pContext);
    }
    else
    {
        // At this point, we would have to load other assemblies. The only one we have guaranteed
        // to be there is mscorlib. Would have to investigate if its worth it.
        return ELEMENT_TYPE_END;
    }
}


// Parses metadata and returns size needed for the different static blocks.
// Also allocates the offsets needed for each class
void Module::ParseMetadataForStatics(DWORD* pdwNumTypes, DWORD* pdwNonGCStaticBytes, DWORD* pdwGCStaticHandles)
{
    CONTRACTL
    {
        THROWS;
        GC_TRIGGERS;
        INJECT_FAULT(COMPlusThrowOM(););
    }
    CONTRACTL_END;

    // Trade off here. We want a slot for each type. That way we can get to 2 bits per class and
    // index directly and not need a mapping from ClassID to MethodTable (we will use the RID
    // as the mapping)
    IMDInternalImport *pImport = GetMDImport();
    DWORD dwTypes   = pImport->GetCountWithTokenKind(mdtTypeDef) + 1; // +1 for module type

    // Allocate table for offsets. We need offsets for GC and non GC areas. We add +1 to use as
    // a sentinel (we don't care about not needing it release because we dont have this table
    // in correctly ngened images
    m_pStaticOffsets =
    (PTR_DWORD)(void*)
       GetDomain()->GetHighFrequencyHeap()->AllocMem((sizeof(DWORD)*(dwTypes+1))*2);

    HENUMInternal hTypeEnum;
    IfFailThrow(pImport->EnumAllInit(mdtTypeDef, &hTypeEnum));

    DWORD      dwGCHandles = 0;
    DWORD      dwNonGCBytes = 0;

    mdTypeDef type;
    // Parse each type of the class
    while (pImport->EnumNext(&hTypeEnum, &type))
    {
        HENUMInternal hFieldEnum;
        mdFieldDef field;

        // Set offset for this type
        DWORD dwIndex = RidFromToken(type) - 1;
        DWORD dwAlignment =  DATA_ALIGNMENT;
        DWORD dwClassNonGCBytes = 0;
        DWORD dwClassGCHandles  = 0;

        IfFailThrow(pImport->EnumInit(mdtFieldDef, type, &hFieldEnum));

        // need to check if the type is generic and if so exclude it from iteration as we don't know the size
        HENUMInternal hGenericEnum;
        IfFailThrow(pImport->EnumInit(mdtGenericParam, type, &hGenericEnum));
        ULONG cGenericParams = pImport->EnumGetCount(&hGenericEnum);
        pImport->EnumClose(&hGenericEnum);

        if (cGenericParams > 0)
        {
        }
        else
        {
            // Parse each field of the type
            while (pImport->EnumNext(&hFieldEnum, &field))
            {
                if (!GetMDImport()->IsValidToken(field))
                {
                    ThrowHR(COR_E_BADIMAGEFORMAT, BFA_METADATA_CORRUPT);
                }

                DWORD dwFieldAttrs = GetMDImport()->GetFieldDefProps(field);
                if (!IsFdLiteral(dwFieldAttrs) && IsFdStatic(dwFieldAttrs))
                {
                    PCCOR_SIGNATURE pMemberSignature;
                    DWORD       cMemberSignature;
                    DWORD       dwMemberAttribs;

                    // Get the type of the static field.
                    dwMemberAttribs = pImport->GetFieldDefProps(field);
                    pMemberSignature = pImport->GetSigOfFieldDef(field, &cMemberSignature);
                    HRESULT hr = validateTokenSig(field,pMemberSignature,cMemberSignature,dwMemberAttribs,pImport);
                    if (FAILED(hr))
                    {
                        COMPlusThrowHR(hr);
                    }
                    SigTypeContext typeContext;
                    MetaSig fsig(pMemberSignature, cMemberSignature, this, &typeContext, FALSE, MetaSig::sigField);
                    CorElementType ElementType = fsig.NextArg();

                ADD_SPACE:
                    switch (ElementType)
                    {
                        case ELEMENT_TYPE_I1:
                        case ELEMENT_TYPE_U1:
                        case ELEMENT_TYPE_BOOLEAN:
                            dwClassNonGCBytes += 4;  // We don't pack statics
                            break;
                        case ELEMENT_TYPE_I2:
                        case ELEMENT_TYPE_U2:
                        case ELEMENT_TYPE_CHAR:
                            dwClassNonGCBytes += 4; // We don't pack statics
                            break;
                        case ELEMENT_TYPE_I4:
                        case ELEMENT_TYPE_U4:
                        case ELEMENT_TYPE_R4:
                            dwClassNonGCBytes += 4;
                            break;
                        case ELEMENT_TYPE_FNPTR:
                        case ELEMENT_TYPE_PTR:
                        case ELEMENT_TYPE_I:
                        case ELEMENT_TYPE_U:
#if defined(ALIGN_ACCESS) 
                            dwClassNonGCBytes = ALIGN_UP(dwClassNonGCBytes, (1 << LOG2_PTRSIZE));
#endif
                            dwClassNonGCBytes += (1 << LOG2_PTRSIZE);
                            break;

                        case ELEMENT_TYPE_I8:
                        case ELEMENT_TYPE_U8:
                        case ELEMENT_TYPE_R8:
                            dwAlignment =  max(8, DATA_ALIGNMENT);
#if defined(ALIGN_ACCESS) 
                            dwClassNonGCBytes = ALIGN_UP(dwClassNonGCBytes, 8);
#endif
                            dwClassNonGCBytes += 8;
                            break;
                        case ELEMENT_TYPE_VAR:
                        case ELEMENT_TYPE_MVAR:
                        case ELEMENT_TYPE_STRING:
                        case ELEMENT_TYPE_SZARRAY:
                        case ELEMENT_TYPE_ARRAY:
                        case ELEMENT_TYPE_CLASS:
                        case ELEMENT_TYPE_OBJECT:
                            dwClassGCHandles  += 1;
                            break;
                        case ELEMENT_TYPE_VALUETYPE:
                        {
                            // See if we can figure out what the value type is
                            mdToken tk = fsig.GetArgProps().PeekValueTypeTokenClosed(&typeContext);
                            ElementType = ParseMetadataForStaticsIsValueTypeEnum(tk, &typeContext);

                            switch (ElementType)
                            {
                                case ELEMENT_TYPE_I1:
                                case ELEMENT_TYPE_U1:
                                case ELEMENT_TYPE_BOOLEAN:
                                case ELEMENT_TYPE_I2:
                                case ELEMENT_TYPE_U2:
                                case ELEMENT_TYPE_CHAR:
                                case ELEMENT_TYPE_I4:
                                case ELEMENT_TYPE_U4:
                                case ELEMENT_TYPE_R4:
                                case ELEMENT_TYPE_I:
                                case ELEMENT_TYPE_U:
                                case ELEMENT_TYPE_I8:
                                case ELEMENT_TYPE_U8:
                                case ELEMENT_TYPE_R8:
                                    goto ADD_SPACE;
                                case ELEMENT_TYPE_VALUETYPE:
                                {
                                    dwClassGCHandles  += 1;
                                    break;
                                }
                                case ELEMENT_TYPE_END:
                                default:
                                {
                                    // We'll have to be pessimistic here
#if defined(ALIGN_ACCESS) 
                                    dwClassNonGCBytes = ALIGN_UP(dwClassNonGCBytes, (1 << MAX_LOG2_PRIMITIVE_FIELD_SIZE));
#endif
                                    dwClassNonGCBytes += (1 << MAX_LOG2_PRIMITIVE_FIELD_SIZE);
                                    dwClassGCHandles  += 1;
                                    break;
                                }
                            }

                            break;
                        }

                        default:
                            // field has an unexpected type
                            ThrowHR(VER_E_FIELD_SIG);
                            break;
                    }
                }
            }
        }

        // We will require alignment if the type has non gc statics
        if (dwClassNonGCBytes)
        {
            dwNonGCBytes = (DWORD) ALIGN_UP(dwNonGCBytes, dwAlignment);
        }

        // Save current offsets
        m_pStaticOffsets[dwIndex*2]     = dwGCHandles*sizeof(sizeof(OBJECTREF*));
        m_pStaticOffsets[dwIndex*2 + 1] = dwNonGCBytes;

        // Increment for next class
        dwGCHandles  += dwClassGCHandles;
        dwNonGCBytes += dwClassNonGCBytes;


    }

    m_pStaticOffsets[dwTypes*2]     = dwGCHandles*sizeof(sizeof(OBJECTREF*));
    m_pStaticOffsets[dwTypes*2 + 1] = dwNonGCBytes;

    if (pdwNonGCStaticBytes) { *pdwNonGCStaticBytes = dwNonGCBytes; }
    if (pdwGCStaticHandles)  { *pdwGCStaticHandles  = dwGCHandles; }
    if (pdwNumTypes)         { *pdwNumTypes = dwTypes; }
}


void  Module::GetOffsetsForStaticData(
                    mdToken cl,
                    BOOL bDynamic, DWORD dwGCStaticHandles,
                    DWORD dwNonGCStaticBytes,
                    DWORD * pOutStaticHandleOffset,
                    DWORD * pOutNonGCStaticOffset)
{
    CONTRACTL
    {
        THROWS;
        GC_TRIGGERS;
        INJECT_FAULT(COMPlusThrowOM());
    }
    CONTRACTL_END

    *pOutStaticHandleOffset = 0;
    *pOutNonGCStaticOffset  = 0;

    if (!dwGCStaticHandles && !dwNonGCStaticBytes)
    {
        return;
    }

    // Statics for instantiated types are allocated dynamically per-instantiation
    if (bDynamic)
    {
        // Non GC statics are embedded in the Dynamic Entry.
        *pOutNonGCStaticOffset  = DomainLocalModule::DynamicEntry::GetOffsetOfDataBlob();
        return;
    }

    {
        // We allocate in the big blob.

        _ASSERTE(m_pStaticOffsets);
        DWORD index = RidFromToken(cl) - 1;

        *pOutStaticHandleOffset = m_pStaticOffsets[index*2];

        *pOutNonGCStaticOffset  = m_pStaticOffsets[index*2 + 1];

        // Check we didnt go out of what we predicted we would need for the class
        if (*pOutStaticHandleOffset + sizeof(OBJECTREF*)*dwGCStaticHandles >
                    m_pStaticOffsets[(index+1)*2] ||
            *pOutNonGCStaticOffset + dwNonGCStaticBytes >
                    m_pStaticOffsets[(index+1)*2 + 1])
        {
            // If there is a corner case bug - mismatch between the loader code and code that estimates
            // the statics size for the module, we fail instead of opening a security hole.
            _ASSERTE(false);
            COMPlusThrowNonLocalized(kExecutionEngineException, L"Incorrect estimate of the statics size");
        }
    }
}

#endif // !DACCESS_COMPILE

#define IS_ENCODED_TYPEID(id) (id & 0x2)
#define ENCODE_TYPEID(id) ((id << 2) | 0x2)
#define DECODE_TYPEID(id) (id >> 2)

UINT32 Module::MapZapTypeID(UINT32 typeID)
{
    CONTRACTL {
        INSTANCE_CHECK;
        MODE_ANY;
        THROWS;
        GC_TRIGGERS;
        PRECONDITION(CheckPointer(m_rgDispatchTypeTable));
        PRECONDITION(typeID != TYPE_ID_THIS_CLASS);
    } CONTRACTL_END;

    if (typeID == TYPE_ID_THIS_CLASS) {
        return typeID;
    }

    SIZE_T typeTableValue = *((volatile SIZE_T *)(m_rgDispatchTypeTable + typeID));

#ifndef DACCESS_COMPILE 
    if (CORCOMPILE_IS_TOKEN_TAGGED(typeTableValue)) {
    }
#else // DACCESS_COMPILE
    DacError(E_FAIL);
#endif // DACCESS_COMPILE

    if (!IS_ENCODED_TYPEID(typeTableValue)) {
#ifndef DACCESS_COMPILE 
        // This is a MethodTable that was hard bound or restored just above
        MethodTable *pMT = (MethodTable *)typeTableValue;

        // Normally, an interface is restored by the time there is a call to
        // an interface method. However, SZArrays implicitly implement IList<T>,
        // and the IList<T> is not guaranteed to be restored in such cases.
        INDEBUG(BOOL wasAlreadyRestored = pMT->IsRestored());
        pMT->CheckRestore();
        _ASSERTE(wasAlreadyRestored || IsImplicitInterfaceOfSZArray(pMT));

        UINT32 newTypeID = pMT->GetTypeID();
        typeTableValue = ENCODE_TYPEID(newTypeID);
#else // DACCESS_COMPILE
        DacError(E_FAIL);
#endif // DACCESS_COMPILE
    }

    // Write the final result back into the array.
    m_rgDispatchTypeTable[typeID] = typeTableValue;

    CONSISTENCY_CHECK(!CORCOMPILE_IS_TOKEN_TAGGED(m_rgDispatchTypeTable[typeID]));
    CONSISTENCY_CHECK(IS_ENCODED_TYPEID(m_rgDispatchTypeTable[typeID]));
    INDEBUG(MethodTable *pActualMT = NULL; pActualMT = GetDomain()->LookupType(DECODE_TYPEID(m_rgDispatchTypeTable[typeID]));)
    return DECODE_TYPEID(m_rgDispatchTypeTable[typeID]);
}

#undef DECODE_TYPEID
#undef ENCODE_TYPEID
#undef IS_ENCODED_TYPEID



#ifndef DACCESS_COMPILE 


BOOL Module::IsNoStringInterning()
{
    CONTRACTL
    {
        THROWS;
        GC_TRIGGERS;
    }
    CONTRACTL_END

    if (!HasNativeImage())
    {
        return GetAssembly()->IsNoStringInterning();
    }

#ifdef _DEBUG 
    static ConfigDWORD g_NoStringInterning;
    DWORD dwOverride = g_NoStringInterning.val(L"NoStringInterning", 1);

    if (dwOverride == 0)
    {
        // Disabled
        return FALSE;
    }
    else if (dwOverride == 2)
    {
        // Always true (testing)
        return TRUE;
    }
#endif // _DEBUG

    return (m_dwCompilationRelaxationFlags & CompilationRelaxations_NoStringInterning)?TRUE:FALSE;
}

// Makes sure all flags are set
void Module::GenerateAllCompilationRelaxationFlags()
{
    CONTRACTL
    {
        THROWS;
        GC_TRIGGERS;
    }
    CONTRACTL_END

    if (GetAssembly()->IsNoStringInterning())
    {
        m_dwCompilationRelaxationFlags |=  CompilationRelaxations_NoStringInterning;
    }
}

MethodTable ** ModuleCtorInfo::GetGCStaticMTs(DWORD index)
{
    LEAF_CONTRACT;

    if (index < numHotGCStaticsMTs)
    {
        _ASSERTE(ppHotGCStaticsMTs != NULL);

        return ppHotGCStaticsMTs + index;
    }
    else
    {
        _ASSERTE(ppColdGCStaticsMTs != NULL);

        // shift the start of the cold table because all cold offsets are also shifted
        return ppColdGCStaticsMTs + (index - numHotGCStaticsMTs);
    }
}

DWORD Module::AllocateDynamicEntry(MethodTable *pMT)
{
    CONTRACTL
    {
        THROWS;
        GC_TRIGGERS;
        PRECONDITION(pMT->GetModuleForStatics() == this);
        PRECONDITION(pMT->IsDynamicStatics());
        PRECONDITION(!pMT->ContainsGenericVariables());
    }
    CONTRACTL_END;

    DWORD newId = FastInterlockExchangeAdd((LONG*)&m_cDynamicEntries, 1);

    if (newId >= m_maxDynamicEntries)
    {
        CrstHolder ch(&m_Crst);

        if (newId >= m_maxDynamicEntries)
        {
            SIZE_T maxDynamicEntries = max(16, m_maxDynamicEntries);
            while (maxDynamicEntries <= newId)
            {
                maxDynamicEntries *= 2;
            }

            DynamicStaticsInfo* pNewDynamicStaticsInfo = (DynamicStaticsInfo*)
                (void*)GetDomain()->GetHighFrequencyHeap()->AllocMem(sizeof(DynamicStaticsInfo) * maxDynamicEntries);

            if (m_pDynamicStaticsInfo)
                memcpy(pNewDynamicStaticsInfo, m_pDynamicStaticsInfo, sizeof(DynamicStaticsInfo) * m_maxDynamicEntries);

            m_pDynamicStaticsInfo = pNewDynamicStaticsInfo;
            m_maxDynamicEntries = maxDynamicEntries;
        }
    }

    m_pDynamicStaticsInfo[newId].pEnclosingMT = pMT;

    LOG((LF_CLASSLOADER, LL_INFO10000, "STATICS: Assigned dynamic ID %d to %s\n", newId, pMT->GetDebugClassName()));

    return newId;
}

void Module::BuildStaticsOffsets()
{
    CONTRACTL
    {
        THROWS;
        GC_TRIGGERS;
        INJECT_FAULT(COMPlusThrowOM());
    }
    CONTRACTL_END

    LOG((LF_CLASSLOADER, LL_INFO10000, "STATICS: Building statics offsets for %s\n", GetSimpleName()));

    // Parse metadata to obtain a good guess of how many bytes we need
    DWORD dwNumTypes, dwNonGCStaticBytes;

    ParseMetadataForStatics(&dwNumTypes, &dwNonGCStaticBytes, &m_dwMaxGCStaticHandles);


    // Calculate offsets of each section.

    // Organization in memory of the static block
    //
    //
    //                                       |  GC Statics             |
    //                                                  |
    //                                                  |
    //    | Class Data (one byte per class)  |   pointer to gc statics | primitive type statics |
    //
    //
    DWORD dwOffsetClassSlots;
    DWORD dwOffsetNonGCStaticBytes;

    dwOffsetClassSlots        = (DWORD) DomainLocalModule::OffsetOfDataBlob();

    dwOffsetNonGCStaticBytes  = (DWORD) ALIGN_UP((size_t)(dwOffsetClassSlots + sizeof(BYTE)*dwNumTypes), (1 << MAX_LOG2_PRIMITIVE_FIELD_SIZE));

    // Calculate final size of the precomputed statics block
    m_dwStaticsBlockSize = (dwOffsetNonGCStaticBytes + dwNonGCStaticBytes - dwOffsetClassSlots);

    DWORD i;
    for (i = 0 ; i <= dwNumTypes ; i++) // <= for sentinel
    {
        m_pStaticOffsets[i*2]     += 0;
        m_pStaticOffsets[i*2 + 1] += dwOffsetNonGCStaticBytes;
    }

    // Check we're sane
    _ASSERTE(m_pStaticOffsets[0               ] == 0);
    _ASSERTE(m_pStaticOffsets[dwNumTypes*2    ] == m_dwMaxGCStaticHandles*sizeof(OBJECTREF*));

    _ASSERTE(m_pStaticOffsets[1               ] == dwOffsetNonGCStaticBytes);
    _ASSERTE(m_pStaticOffsets[dwNumTypes*2 + 1] == dwOffsetClassSlots + m_dwStaticsBlockSize);
}



void Module::AllocateStaticHandles(AppDomain* pDomain)
{
    CONTRACT_VOID
    {
        THROWS;
        GC_TRIGGERS;
    }
    CONTRACT_END;

    // Allocate the handles we will need. Note that AllocateStaticFieldObjRefPtrs will only
    // allocate if pModuleData->GetGCStaticsBasePointerAddress(pMT) != 0, avoiding creating
    // handles more than once for a given MT or module

    DomainLocalModule *pModuleData = GetDomainLocalModule(pDomain);

    _ASSERTE(pModuleData->GetPrecomputedGCStaticsBasePointerAddress() != NULL);
    if (this->m_dwMaxGCStaticHandles > 0)
    {
        pDomain->AllocateStaticFieldObjRefPtrs(this->m_dwMaxGCStaticHandles,
                                               pModuleData->GetPrecomputedGCStaticsBasePointerAddress());

        // We should throw if we fail to allocate and never hit this assert
        _ASSERTE(pModuleData->GetPrecomputedGCStaticsBasePointer() != NULL);
    }

    RETURN;
}

void Module::AllocateStatics(AllocMemTracker *pamTracker)
{
    CONTRACT_VOID
    {
        THROWS;
        GC_TRIGGERS;
    }
    CONTRACT_END;

    if (IsResource())
    {
        // If it has no code, we don't have to allocate anything
        LOG((LF_CLASSLOADER, LL_INFO10000, "STATICS: Resource module %s. No statics neeeded\n", GetSimpleName()));
        RETURN;
    }

    if (m_pStaticOffsets == (PTR_DWORD) NGEN_STATICS_ALLCLASSES_WERE_LOADED)
    {
        _ASSERTE(HasNativeImage());

        // This is an ngen image and all the classes were loaded at ngen time, so we're done.
        LOG((LF_CLASSLOADER, LL_INFO10000, "STATICS: 'Complete' Native image found, no statics parsing needed for module %s.\n", GetSimpleName()));
        RETURN;
    }

    LOG((LF_CLASSLOADER, LL_INFO10000, "STATICS: Allocating statics for module %s\n", GetSimpleName()));

    // Build the offset table, which will tell us what the offsets for the statics of each class are (one offset for gc handles, one offset
    // for non gc types)
    BuildStaticsOffsets();

    RETURN;
}

// This method will report GC static refs of the module. It doesn't have to be complete (ie, it's 
// currently used to opportunistically get more concurrency in the marking of statics), so it currently
// ignores any statics that are not preallocated (ie: won't report statics from IsDynamicStatics() MT)
// The reason this function is in Module and not in DomainFile (together with DomainLocalModule is because
// for shared modules we need a very fast way of getting to the DomainLocalModule. For that we use
// a table in DomainLocalBlock that's indexed with a module ID
void Module::EnumStaticGCRefs(AppDomain* pAppDomain, GCEnumCallback  pCallback, LPVOID hCallBack)
{
    CONTRACT_VOID
    {
        NOTHROW;
        GC_NOTRIGGER;
    }
    CONTRACT_END;

    _ASSERTE(GCHeap::IsGCInProgress() &&    
         GCHeap::IsServerHeap()   &&      
         IsGCSpecialThread());              


    DomainLocalModule *pModuleData = GetDomainLocalModule(pAppDomain);
    DWORD dwHandles                = m_dwMaxGCStaticHandles;

    if (IsResource())
    {
        RETURN;
    }

    LOG((LF_GC, LL_INFO100, "Scanning statics for module %s\n", GetSimpleName()));

    OBJECTREF* ppObjectRefs       = pModuleData->GetPrecomputedGCStaticsBasePointer();
    for (DWORD i = 0 ; i < dwHandles ; i++)
    {
        // Handles are allocated in SetDomainFile (except for bootstrapped mscorlib). In any
        // case, we shouldnt get called if the module hasn't had it's handles allocated (as we
        // only get here if IsActive() is true, which only happens after SetDomainFile(), which
        // is were we allocate handles.
        _ASSERTE(ppObjectRefs);
        pCallback(hCallBack, ppObjectRefs+i, 0);
    }        

    LOG((LF_GC, LL_INFO100, "Done scanning statics for module %s\n", GetSimpleName()));

    RETURN;
}

void Module::SetDomainFile(DomainFile *pDomainFile)
{
    CONTRACTL
    {
        INSTANCE_CHECK;
        PRECONDITION(CheckPointer(pDomainFile));
        PRECONDITION(IsManifest() == pDomainFile->IsAssembly());
        THROWS;
        GC_TRIGGERS;
        MODE_ANY;
    }
    CONTRACTL_END;

    DomainLocalModule* pModuleData = 0;

    // Do we need to allocate memory for the non GC statics?
    if (GetAssembly()->IsDomainNeutral() || m_pDomainLocalModule == NULL)
    {
        LOG((LF_CLASSLOADER, LL_INFO10, "STATICS: Allocating %i bytes for precomputed statics in module %s in Appdomain %08x\n",
        this->GetStaticsAndClassInitBlockSize(), this->GetDebugName(), pDomainFile->GetAppDomain()));

        MEMORY_REPORT_CONTEXT_SCOPE("ModuleStatics");

        // Allocate memory for the module statics. For ngened non shared case, we dont
        // need to do so, as we have the data in the image
        pModuleData =    (DomainLocalModule*)(void*)
                         pDomainFile->GetAppDomain()->GetHighFrequencyHeap()->AllocMem(sizeof(DomainLocalModule) +
                         this->GetStaticsAndClassInitBlockSize());

        // Note: Memory allocated on loader heap is zero filled
        // memset(pModuleData->GetPrecomputedStaticsAndClassInitBlock(), 0, this->GetStaticsAndClassInitBlockSize());

        // Init members
        pModuleData->Init();
    }
    else
    {
        pModuleData = this->m_pDomainLocalModule;
        LOG((LF_CLASSLOADER, LL_INFO10, "STATICS: Allocation not needed for ngened non shared module %s in Appdomain %08x\n"));
    }

    if (GetAssembly()->IsDomainNeutral())
    {
        DomainLocalBlock *pLocalBlock;
        {
            pLocalBlock = pDomainFile->GetAppDomain()->GetDomainLocalBlock();
            pLocalBlock->SetModuleSlot(GetModuleID(), pModuleData);
        }

        pLocalBlock->SetDomainFile(GetModuleID(), pDomainFile);
    }
    else
    {
        // Non shared case, module points directly to the statics. In ngen case
        // m_pDomainModule is already set for the non shared case
        if (m_pDomainLocalModule == NULL)
        {
            m_pDomainLocalModule = pModuleData;
        }

        m_pDomainLocalModule->SetDomainFile(pDomainFile);
    }

    // Allocate static handles now.
    // NOTE: Bootstrapping issue with mscorlib - we will manually allocate later
    if (g_pPredefinedArrayTypes[ELEMENT_TYPE_OBJECT] != NULL)
        AllocateStaticHandles(pDomainFile->GetAppDomain());

}

OBJECTREF Module::GetExposedObject()
{
    CONTRACT(OBJECTREF)
    {
        INSTANCE_CHECK;
        POSTCONDITION(RETVAL != NULL);
        THROWS;
        GC_TRIGGERS;
        MODE_COOPERATIVE;
    }
    CONTRACT_END;

    RETURN GetDomainFile()->GetExposedModuleObject();
}

//
// AllocateMap allocates the RID maps based on the size of the current
// metadata (if any)
//

void Module::AllocateMaps()
{
    CONTRACTL
    {
        INSTANCE_CHECK;
        THROWS;
        GC_NOTRIGGER;
        MODE_ANY;
    }
    CONTRACTL_END;

    enum
    {
        TYPEDEF_MAP_INITIAL_SIZE = 5,
        TYPEREF_MAP_INITIAL_SIZE = 5,
        MEMBERREF_MAP_INITIAL_SIZE = 10,
        MEMBERDEF_MAP_INITIAL_SIZE = 10,
        FILEREFERENCES_MAP_INITIAL_SIZE = 5,
        ASSEMBLYREFERENCES_MAP_INITIAL_SIZE = 5,

        TYPEDEF_MAP_BLOCK_SIZE = 50,
        TYPEREF_MAP_BLOCK_SIZE = 50,
        MEMBERREF_MAP_BLOCK_SIZE = 50,
        MEMBERDEF_MAP_BLOCK_SIZE = 50,
        FILEREFERENCES_MAP_BLOCK_SIZE = 50,
        ASSEMBLYREFERENCES_MAP_BLOCK_SIZE = 50,
    };

    DWORD           dwTableAllocElements;
    DWORD           dwReserveSize;
    TADDR           *pTable = NULL;

    if (IsResource())
        return;

    MEMORY_REPORT_CONTEXT_SCOPE("RidMap");

    if (IsReflection())
    {
        m_TypeDefToMethodTableMap.dwMaxIndex = TYPEDEF_MAP_INITIAL_SIZE;

        // The above is essential.  The following ones are precautionary.
        m_TypeRefToMethodTableMap.dwMaxIndex = TYPEREF_MAP_INITIAL_SIZE;
        m_MethodDefToDescMap.dwMaxIndex = MEMBERDEF_MAP_INITIAL_SIZE;
        m_FieldDefToDescMap.dwMaxIndex = MEMBERDEF_MAP_INITIAL_SIZE;
        m_MemberRefToDescMap.dwMaxIndex = MEMBERREF_MAP_BLOCK_SIZE;
        m_FileReferencesMap.dwMaxIndex = FILEREFERENCES_MAP_INITIAL_SIZE;
        m_ManifestModuleReferencesMap.dwMaxIndex = ASSEMBLYREFERENCES_MAP_INITIAL_SIZE;
    }
    else
    {
        HENUMInternal   hTypeDefEnum;

        IfFailThrow(GetMDImport()->EnumTypeDefInit(&hTypeDefEnum));
        m_TypeDefToMethodTableMap.dwMaxIndex = GetMDImport()->EnumTypeDefGetCount(&hTypeDefEnum);
        GetMDImport()->EnumTypeDefClose(&hTypeDefEnum);

        if (m_TypeDefToMethodTableMap.dwMaxIndex >= MAX_CLASSES_PER_MODULE)
            ThrowHR(COR_E_TYPELOAD);

        // Metadata count is inclusive
        m_TypeDefToMethodTableMap.dwMaxIndex++;

        // Get # TypeRefs
        m_TypeRefToMethodTableMap.dwMaxIndex = GetMDImport()->GetCountWithTokenKind(mdtTypeRef)+1;

        // Get # MethodDefs
        m_MethodDefToDescMap.dwMaxIndex = GetMDImport()->GetCountWithTokenKind(mdtMethodDef)+1;

        // Get # FieldDefs
        m_FieldDefToDescMap.dwMaxIndex = GetMDImport()->GetCountWithTokenKind(mdtFieldDef)+1;

        // Get # MemberRefs
        m_MemberRefToDescMap.dwMaxIndex = GetMDImport()->GetCountWithTokenKind(mdtMemberRef)+1;

        // Get the number of AssemblyReferences and FileReferences in the map
        m_FileReferencesMap.dwMaxIndex = GetMDImport()->GetCountWithTokenKind(mdtFile)+1;
        m_ManifestModuleReferencesMap.dwMaxIndex = GetMDImport()->GetCountWithTokenKind(mdtAssemblyRef)+1;
    }

    ClrSafeInt<DWORD> acc;
    acc += m_TypeDefToMethodTableMap.dwMaxIndex;
    acc += m_TypeRefToMethodTableMap.dwMaxIndex;
    acc += m_MemberRefToDescMap.dwMaxIndex;
    acc += m_MethodDefToDescMap.dwMaxIndex;
    acc += m_FieldDefToDescMap.dwMaxIndex;
    acc += m_ManifestModuleReferencesMap.dwMaxIndex;
    acc += m_FileReferencesMap.dwMaxIndex;
    if (acc.IsOverflow())
        COMPlusThrowOM();
    dwTableAllocElements = acc.Value();

    acc *= (sizeof(void*));
    if (acc.IsOverflow())
        COMPlusThrowOM();
    dwReserveSize = acc.Value();


    if (dwTableAllocElements > 0)
    {
        _ASSERTE (m_pAssembly && m_pAssembly->GetLowFrequencyHeap());
        pTable = (TADDR *)(void*) m_pAssembly->GetLowFrequencyHeap()->AllocMem(dwTableAllocElements * sizeof(void*));

        // Note: Memory allocated on loader heap is zero filled
        // memset(pTable, 0, dwTableAllocElements * sizeof(void*));
    }

    m_dwTypeDefMapBlockSize = TYPEDEF_MAP_BLOCK_SIZE;
    m_TypeDefToMethodTableMap.pdwBlockSize = &m_dwTypeDefMapBlockSize;
    m_TypeDefToMethodTableMap.pNext  = NULL;
    m_TypeDefToMethodTableMap.pTable = pTable;

    m_dwTypeRefMapBlockSize = TYPEREF_MAP_BLOCK_SIZE;
    m_TypeRefToMethodTableMap.pdwBlockSize = &m_dwTypeRefMapBlockSize;
    m_TypeRefToMethodTableMap.pNext  = NULL;
    m_TypeRefToMethodTableMap.pTable = &pTable[m_TypeDefToMethodTableMap.dwMaxIndex];

    m_dwMethodDefMapBlockSize = MEMBERDEF_MAP_BLOCK_SIZE;
    m_MethodDefToDescMap.pdwBlockSize = &m_dwMethodDefMapBlockSize;
    m_MethodDefToDescMap.pNext  = NULL;
    m_MethodDefToDescMap.pTable = &m_TypeRefToMethodTableMap.pTable[m_TypeRefToMethodTableMap.dwMaxIndex];

    m_dwFieldDefMapBlockSize = MEMBERDEF_MAP_BLOCK_SIZE;
    m_FieldDefToDescMap.pdwBlockSize = &m_dwFieldDefMapBlockSize;
    m_FieldDefToDescMap.pNext  = NULL;
    m_FieldDefToDescMap.pTable = &m_MethodDefToDescMap.pTable[m_MethodDefToDescMap.dwMaxIndex];

    m_dwMemberRefMapBlockSize = MEMBERREF_MAP_BLOCK_SIZE;
    m_MemberRefToDescMap.pdwBlockSize = &m_dwMemberRefMapBlockSize;
    m_MemberRefToDescMap.pNext  = NULL;
    m_MemberRefToDescMap.pTable = &m_FieldDefToDescMap.pTable[m_FieldDefToDescMap.dwMaxIndex];

    m_dwFileReferencesMapBlockSize = FILEREFERENCES_MAP_BLOCK_SIZE;
    m_FileReferencesMap.pdwBlockSize = &m_dwFileReferencesMapBlockSize;
    m_FileReferencesMap.pNext  = NULL;
    m_FileReferencesMap.pTable = &m_MemberRefToDescMap.pTable[m_MemberRefToDescMap.dwMaxIndex];

    m_dwManifestModuleReferencesMapBlockSize = ASSEMBLYREFERENCES_MAP_BLOCK_SIZE;
    m_ManifestModuleReferencesMap.pdwBlockSize = &m_dwManifestModuleReferencesMapBlockSize;
    m_ManifestModuleReferencesMap.pNext  = NULL;
    m_ManifestModuleReferencesMap.pTable = &m_FileReferencesMap.pTable[m_FileReferencesMap.dwMaxIndex];
}

//
// FreeClassTables frees the classes in the module
//

void Module::FreeClassTables()
{
    CONTRACTL
    {
        INSTANCE_CHECK;
        NOTHROW;
        GC_TRIGGERS;
        MODE_ANY;
    }
    CONTRACTL_END;

    if (m_dwTransientFlags & CLASSES_FREED)
        return;

    FastInterlockOr(&m_dwTransientFlags, CLASSES_FREED);

    // disable ibc here because it can cause errors during the destruction of classes
    IBCLoggingDisabler disableIbc;
            
#if _DEBUG 
    DebugLogRidMapOccupancy();
#endif

    // Free the types filled out in the TypeDefToEEClass map
    LookupMap *pMap;
    DWORD       dwMinIndex = 0;
    MethodTable *pMT;

    // Go through each linked block
    for (pMap = &m_TypeDefToMethodTableMap; pMap != NULL && pMap->pTable; pMap = pMap->pNext)
    {
        DWORD i;
        DWORD dwIterCount = pMap->dwMaxIndex - dwMinIndex;
        TADDR *pRealTableStart = &pMap->pTable[dwMinIndex];

        for (i = 0; i < dwIterCount; i++)
        {
            TADDR result = pRealTableStart[i];
            if (result != NULL && (result & (TADDR)LookupMap::IS_MODULE_BACKPOINTER) == 0)
            {
                pMT = (MethodTable *) result;

                if (pMT != NULL)
                {
                    pMT->GetClass()->Destruct();
                    pRealTableStart[i] = NULL;
                }
            }
        }

        dwMinIndex = pMap->dwMaxIndex;
    }

    // Now do the same for constructed types (arrays and instantiated generic types)
    if (IsTenured())  // If we're destructing because of an error during the module's creation, we'll play it safe and not touch this table as its memory is freed by a
    {                 // separate AllocMemTracker. Though you're supposed to destruct everything else before destructing the AllocMemTracker, this is an easy invariant to break so
                      // we'll play extra safe on this end.
        if (m_pAvailableParamTypes != NULL)
        {
            EETypeHashTable::Iterator it(m_pAvailableParamTypes);
            EETypeHashEntry *pEntry;
            while (m_pAvailableParamTypes->FindNext(&it, &pEntry))
            {
                // We need to call destruct on instances of EEClass whose "canonical" dependent lives in this table
                if (pEntry->data.IsRestored() && pEntry->data.OwnsEEClass())
                {
                    EEClass *pClass = pEntry->data.GetClass();
                    CONSISTENCY_CHECK(pClass != NULL);
                    if (!pClass->IsDestroyed())
                    {
                        pClass->Destruct();
                    }
                    pEntry->data = TypeHandle();
                }
            }
        }
    }
}




#endif // !DACCESS_COMPILE

ClassLoader *Module::GetClassLoader()
{
    WRAPPER_CONTRACT;
    _ASSERTE(m_pAssembly != NULL);
    return m_pAssembly->GetLoader();
}

BaseDomain *Module::GetDomain()
{
    WRAPPER_CONTRACT;
    _ASSERTE(m_pAssembly != NULL);
    return m_pAssembly->GetDomain();
}

#ifndef DACCESS_COMPILE 

AssemblySecurityDescriptor *Module::GetSecurityDescriptor()
{
    WRAPPER_CONTRACT;
    _ASSERTE(m_pAssembly != NULL);
    return m_pAssembly->GetSecurityDescriptor();
}

//
// We'll use this struct and global to keep a list of all
// ISymUnmanagedReaders and ISymUnmanagedWriters (or any IUnknown) so
// we can relelease them at the end.
//
struct IUnknownList
{
    IUnknownList   *next;
    HelpForInterfaceCleanup *cleanup;
    IUnknown       *pUnk;
};

static IUnknownList *g_IUnknownList = NULL;

/* static */
HRESULT Module::TrackIUnknownForDelete(IUnknown *pUnk,
                                 IUnknown ***pppUnk,
                                 HelpForInterfaceCleanup *pCleanHelp)
{
    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
        MODE_ANY;
        INJECT_FAULT(return E_OUTOFMEMORY;);
    }
    CONTRACTL_END

    IUnknownList *pNew = new (nothrow) IUnknownList;
    if (!pNew)
        return E_OUTOFMEMORY;

    pNew->pUnk = pUnk; // Ref count is 1
    pNew->cleanup = pCleanHelp;
    pNew->next = g_IUnknownList;
    g_IUnknownList = pNew;

    // Return the address of where we're keeping the IUnknown*, if
    // needed.
    if (pppUnk)
        *pppUnk = &(pNew->pUnk);

    return S_OK;
}

/* static */
void Module::ReleaseAllIUnknowns(void)
{
    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
        MODE_ANY;
        FORBID_FAULT;
    }
    CONTRACTL_END;

    IUnknownList **ppElement = &g_IUnknownList;

    while (*ppElement)
    {
        IUnknownList *pTmp = *ppElement;

        // Release the IUnknown
        if (pTmp->pUnk != NULL)
            pTmp->pUnk->Release();

        if (pTmp->cleanup != NULL)
            delete pTmp->cleanup;

        *ppElement = pTmp->next;
        delete pTmp;
    }
}

/* static */
void Module::ReleaseIUnknown(IUnknown *pUnk)
{
    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
        MODE_ANY;
        FORBID_FAULT;
    }
    CONTRACTL_END;

    IUnknownList **ppElement = &g_IUnknownList;

    while (*ppElement)
    {
        IUnknownList *pTmp = *ppElement;

        // Release the IUnknown
        if (pTmp->pUnk == pUnk)
        {

            //
            FAULT_NOT_FATAL();
            pTmp->pUnk->Release();
            if (pTmp->cleanup != NULL)
                delete pTmp->cleanup;
            *ppElement = pTmp->next;
            delete pTmp;
            break;
        }
        ppElement = &pTmp->next;
    }
    _ASSERTE(ppElement);    // if have a reader, should have found it in list
}

/* static */
void Module::ReleaseIUnknown(IUnknown **ppUnk)
{
    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
        MODE_ANY;
        FORBID_FAULT;
    }
    CONTRACTL_END;

    IUnknownList **ppElement = &g_IUnknownList;

    while (*ppElement)
    {
        IUnknownList *pTmp = *ppElement;

        // Release the IUnknown
        if (&(pTmp->pUnk) == ppUnk)
        {
            //
            FAULT_NOT_FATAL();
            if (pTmp->pUnk)
                pTmp->pUnk->Release();
            if (pTmp->cleanup != NULL)
                delete pTmp->cleanup;
            *ppElement = pTmp->next;
            delete pTmp;
            break;
        }
        ppElement = &pTmp->next;
    }
    _ASSERTE(ppElement);    // if have a reader, should have found it in list
}

void Module::ReleaseISymUnmanagedReader(void)
{
    WRAPPER_CONTRACT;
    // This doesn't have to take the m_pISymUnmanagedReaderLock since
    // a module is destroyed only by one thread.
    if (m_pISymUnmanagedReader == NULL)
        return;
    Module::ReleaseIUnknown(m_pISymUnmanagedReader);
    m_pISymUnmanagedReader = NULL;
}

void Module::StartUnload()
{
    WRAPPER_CONTRACT;
#ifdef PROFILING_SUPPORTED 
    if (!IsBeingUnloaded() && CORProfilerTrackModuleLoads())
    {
        // Profiler is causing some peripheral class loads. Probably this just needs
        // to be turned into a Fault_not_fatal and moved to a specific place inside the profiler.
        BEGIN_EXCEPTION_GLUE(/*hr=*/NULL, NULL)
        {
            PROFILER_CALL;
            g_profControlBlock.pProfInterface->ModuleUnloadStarted((ThreadID) GetThread(), (ModuleID) this);

        }
        END_EXCEPTION_GLUE
    }
#endif // PROFILING_SUPPORTED
    SetBeingUnloaded();
}

void Module::ReleaseILData(void)
{
    WRAPPER_CONTRACT;

    ReleaseISymUnmanagedReader();
}


/* static */
void Module::ReleaseMemoryForTracking()
{
    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
        MODE_ANY;
        FORBID_FAULT;
    }
    CONTRACTL_END;

    IUnknownList **ppElement = &g_IUnknownList;

    while (*ppElement)
    {
        IUnknownList *pTmp = *ppElement;

        *ppElement = pTmp->next;

        if (pTmp->cleanup != NULL)
        {
            (*(pTmp->cleanup->pFunction))(pTmp->cleanup->pData);

            delete pTmp->cleanup;
        }

        delete pTmp;
    }
}// ReleaseMemoryForTracking


//
// Module::FusionCopyPDBs asks Fusion to copy PDBs for a given
// assembly if they need to be copied. This is for the case where a PE
// file is shadow copied to the Fusion cache. Fusion needs to be told
// to take the time to copy the PDB, too.
//

STDAPI CopyPDBs(IAssembly *pAsm); // private fusion API

void Module::FusionCopyPDBs(LPCWSTR moduleName)
{
    CONTRACTL
    {
        INSTANCE_CHECK;
        NOTHROW;
        GC_NOTRIGGER;
        MODE_ANY;
    }
    CONTRACTL_END;

    Assembly *pAssembly = GetAssembly();

    // Just return if we've already done this for this Module's
    // Assembly.
    if ((pAssembly->GetDebuggerInfoBits() & DACF_PDBS_COPIED) ||
        (pAssembly->GetFusionAssembly() == NULL))
    {
        LOG((LF_CORDB, LL_INFO10,
             "Don't need to copy PDB's for module %S\n",
             moduleName));

        return;
    }

    LOG((LF_CORDB, LL_INFO10,
         "Attempting to copy PDB's for module %S\n", moduleName));

    HRESULT hr;
    hr = CopyPDBs(pAssembly->GetFusionAssembly());
    LOG((LF_CORDB, LL_INFO10,
            "Fusion.dll!CopyPDBs returned hr=0x%08x for module 0x%08x\n",
            hr, this));

    // Remember that we've copied the PDBs for this assembly.
    pAssembly->SetCopiedPDBs();
}

// This function will free the metadata interface if we are not
// able to free the ISymUnmanagedReader
static void ReleaseImporterFromISymUnmanagedReader(void * pData)
{
    WRAPPER_CONTRACT;
    IMetaDataImport *md = (IMetaDataImport*)pData;

    // We need to release it twice
    md->Release();
    md->Release();

}// ReleaseImporterFromISymUnmanagedReader

// This function will return PDB stream if exist.
// It is the caller responsibility to call release on *ppStream after a successful
// result.
// We will first check to see if we have a cached pdb stream available. If not,
// we will ask fusion which in terms to ask host vis HostProvideAssembly. Host may
// decide to provide one or not.
//
HRESULT Module::GetHostPdbStream(IStream **ppStream)
{
    CONTRACTL
    {
        NOTHROW;
        if(GetThread()) {GC_TRIGGERS;} else {GC_NOTRIGGER;}
    }
    CONTRACTL_END

    HRESULT hr = NOERROR;

    _ASSERTE(ppStream);

    *ppStream = NULL;

    if (m_file->IsIStream() == false)
    {
        // not a host stream
        return E_FAIL;
    }
    *ppStream = m_file->GetPdbStream();

    if (*ppStream != NULL)
    {
        // We are done!
        // This is the case where host specified the pdb in the IStream format
        // in LoadPdb host API call. This is the case where module was loaded
        // without pdb before attach.
        //
        return S_OK;
    }

    // Maybe fusion can ask our host. This will give us back a PDB stream if
    // host decides to provide one.
    //
    if (m_file->IsAssembly())
    {
        GCX_PREEMP();
        hr = ((PEAssembly*)m_file)->GetIHostAssembly()->GetAssemblyDebugStream(ppStream);
    }
    else
    {
        _ASSERTE(m_file->IsModule());
        IHostAssemblyModuleImport *pIHAMI;
        MAKE_WIDEPTR_FROMUTF8_NOTHROW(pName, m_file->GetSimpleName());
        if (pName == NULL)
            return E_OUTOFMEMORY;
        IfFailRet(m_file->GetAssembly()->GetIHostAssembly()->GetModuleByName(pName, &pIHAMI));
        hr = pIHAMI->GetModuleDebugStream(ppStream);
    }
    return hr;
}

// Clear the cached PDB stream associated with this module if we have one.
// Note that SQL will provide PDB stream in HostProvideAssembly call. However, only
// when Loader triggers this call, we will cache it. If it is debugger who triggers this call,
// we will not cache it.
//
HRESULT Module::ClearHostPdbStream()
{
    // clear our cache if we have one!
    m_file->ClearPdbStream();

    return S_OK;
}



ISymUnmanagedReader *Module::GetISymUnmanagedReaderNoThrow(void)
{
    CONTRACT(ISymUnmanagedReader *)
    {
        INSTANCE_CHECK;
        POSTCONDITION(CheckPointer(RETVAL, NULL_OK));
        NOTHROW;
        WRAPPER(GC_TRIGGERS);
        MODE_ANY;
    }
    CONTRACT_END;

    ISymUnmanagedReader *ret = NULL;

    EX_TRY
    {
        ret = GetISymUnmanagedReader();
    }
    EX_CATCH
    {
        // We swallow any exception and say that we simply couldn't get a reader by returning NULL.
        ret = NULL;
    }
    EX_END_CATCH(SwallowAllExceptions);

    RETURN (ret);
}

ISymUnmanagedReader *Module::GetISymUnmanagedReader(void)
{
    CONTRACT(ISymUnmanagedReader *)
    {
        INSTANCE_CHECK;
        POSTCONDITION(CheckPointer(RETVAL, NULL_OK));
        THROWS;
        WRAPPER(GC_TRIGGERS);
        MODE_ANY;
    }
    CONTRACT_END;

    // No symbols for resource modules
    if (IsResource())
        RETURN NULL;

    // ReleaseAllIUnknowns() called during EEShutDown() will destroy
    // m_pISymUnmanagedReader. We cannot use it for stack-traces or anything
    if (g_fEEShutDown)
        RETURN NULL;

    // Verify that symbol reading is permitted for this module.
    // If we know we've already created a symbol reader, don't bother checking.  There is
    // no advantage to allowing symbol reading to be turned off if we've already created the reader.
    // Note that we can't just put this code in the creation block below because we might have to
    // call managed code to resolve security policy, and we can't do that while holding a lock.
    // There is no disadvantage other than a minor perf cost to calling this unnecessarily, so the
    // race on m_pISymUnmanagedReader here is OK.  The perf cost is minor because the only real
    // work is done by the security system which caches the result.
    if( m_pISymUnmanagedReader == NULL && !IsSymbolReadingEnabled() )
        RETURN NULL;
    
    // If we haven't created the lock yet, do so lazily here
    if (m_pISymUnmanagedReaderLock == NULL)
    {

        Crst* pCritSec = new Crst("ISymUnmangedReader",
                                            (CrstLevel) CrstISymUnmanagedReader, CRST_DEBUGGER_THREAD);

        // Swap the pointers in a thread safe manner.
        if (InterlockedCompareExchangePointer((PVOID *)&m_pISymUnmanagedReaderLock,
                                              (PVOID)pCritSec, NULL) != NULL)
            delete pCritSec;
    }

    // Take the lock for the m_pISymUnmanagedReader
    CrstPreempHolder holder(m_pISymUnmanagedReaderLock);

    UINT lastErrorMode = 0;

    // Check to see if this variable has already been set
    if (m_pISymUnmanagedReader == NULL)
    {
        // There are 4 main cases here:
        //  1. Assembly is on disk and we'll get the symbols from a file next to the assembly
        //  2. Assembly is provided by the host and we'll get the symbols from the host
        //  3. Assembly was loaded in-memory (by byte array or ref-emit), and symbols were
        //      provided along with it.
        //  4. Assembly was loaded in-memory but no symbols were provided.

        // Determine whether we should be looking in memory for the symbols (cases 2 & 3)        
        bool fInMemorySymbols = ( m_file->IsIStream() || GetInMemorySymbolStream() );
        if( !fInMemorySymbols && m_file->GetPath().IsEmpty() )
        {
            // Case 4.  We don't have a module path, an IStream or an in memory symbol stream, 
            // so there is no-where to try and get symbols from.
            RETURN (NULL);
        }

        // Create a binder to find the reader.
        //
        HRESULT hr = S_OK;

        SafeComHolder<ISymUnmanagedBinder> pBinder;

        IfFailThrow(FakeCoCreateInstance(CLSID_CorSymBinder_SxS,
                                  IID_ISymUnmanagedBinder,
                                  (void**)&pBinder));

        LOG((LF_CORDB, LL_INFO10, "M::GISUR: Created binder\n"));

        // Note: we change the error mode here so we don't get any popups as the PDB symbol reader attempts to search the
        // hard disk for files.
        lastErrorMode = SetErrorMode(SEM_NOOPENFILEERRORBOX|SEM_FAILCRITICALERRORS);

        SafeComHolder<ISymUnmanagedReader> pReader;

        if (fInMemorySymbols) 
        {
            SafeComHolder<IStream> pIStream( NULL );

            // If debug stream is already specified, don't bother to go through fusion
            if (GetInMemorySymbolStream() )
            {
                // Case 3 - byte-array or ref-emit.

                // If this is reflection-emit, we need to flush the writer
                if( IsReflection() )
                {
                    ISymUnmanagedWriter* pWriter = GetReflectionModule()->GetISymUnmanagedWriter();
                    if( pWriter != NULL )
                    {
                        SafeComHolder<ISymUnmanagedWriter3> pWriter3;
                        HRESULT thr = pWriter->QueryInterface(IID_ISymUnmanagedWriter3, (void**)&pWriter3);
                        _ASSERTE( SUCCEEDED(thr) );
                        if( SUCCEEDED(thr) )
                        {
                            thr = pWriter3->Commit();
                            _ASSERTE( SUCCEEDED(thr) || thr == E_OUTOFMEMORY );
                        }
                    }
                }

                pIStream = GetInMemorySymbolStream();
                pIStream->AddRef();
            }
            else
            {
                if (CLRHosted())
                {
                    pIStream = m_file->GetPdbStream();
                }

                if (pIStream == NULL)
                {
                    // For hosting scenario where pdb is loaded alone with module,
                    // it will be stored at fusion. The following code will retrieve
                    // the pdb stream from fusion.
                    //
                    if (m_file->IsAssembly())
                    {
                        GCX_PREEMP();
                        hr = ((PEAssembly*)m_file)->GetIHostAssembly()->GetAssemblyDebugStream(&pIStream);
                    }
                    else {
                        _ASSERTE(m_file->IsModule());
                        IHostAssemblyModuleImport *pIHAMI;
                        MAKE_WIDEPTR_FROMUTF8(pName, m_file->GetSimpleName());
                        IfFailThrow(m_file->GetAssembly()->GetIHostAssembly()->GetModuleByName(pName, &pIHAMI));
                        hr = pIHAMI->GetModuleDebugStream(&pIStream);
                    }
                }
            }

            if (SUCCEEDED(hr))
            {
                hr = pBinder->GetReaderFromStream(GetRWImporter(), pIStream, &pReader);
            }
        }
        else
        {
            // The assembly is on disk, so try and load symbols based on the path to the assembly (case 1)
            const SString &path = m_file->GetPath();

            // Call Fusion to ensure that any PDB's are shadow copied before
            // trying to get a symbol reader. This has to be done once per
            // Assembly.
            FusionCopyPDBs(path);

            hr = pBinder->GetReaderForFile(GetRWImporter(), path, NULL, &pReader);
        }

        SetErrorMode(lastErrorMode);

        if (SUCCEEDED(hr))
        {
            NewHolder<HelpForInterfaceCleanup> hlp(new HelpForInterfaceCleanup);

            hlp->pData = GetRWImporter();
            hlp->pFunction = ReleaseImporterFromISymUnmanagedReader;

            IfFailThrow(Module::TrackIUnknownForDelete((IUnknown*)pReader,
                                            NULL,
                                            hlp));

            hlp.SuppressRelease();
            m_pISymUnmanagedReader = pReader.Extract();

            LOG((LF_CORDB, LL_INFO10, "M::GISUR: Loaded symbols for module %S\n", GetDebugName()));
        }
    }

    if (m_pISymUnmanagedReader == NULL)
    {
        LOG((LF_CORDB, LL_INFO10, "M::GISUR: Failed to load symbols for module %S\n", GetDebugName()));
        m_pISymUnmanagedReader = (ISymUnmanagedReader*)0x01; // Failed to load.
    }

    // Make checks that don't have to be done under lock
    if (m_pISymUnmanagedReader == (ISymUnmanagedReader *)0x01)
        RETURN (NULL);
    else
        RETURN (m_pISymUnmanagedReader);
}


BOOL Module::IsSymbolReadingEnabled()
{
    CONTRACTL
    {
        INSTANCE_CHECK;
        THROWS;
        GC_TRIGGERS;
        MODE_ANY;
    }
    CONTRACTL_END;

    // This can be set by the SymbolReadingPolicy config switch or by a host via
    // ICLRDebugManager.AllowFileLineInfo.
    
    ESymbolReadingPolicy policy = CCLRDebugManager::GetSymbolReadingPolicy();
    if( policy == eSymbolReadingFullTrustOnly )
    {
        // We're only supposed to read symbols corresponding to full-trust assemblies.
        // Note that there is no strong (cryptographic) connection between a symbol file and it's assembly.
        // The intent here is just to ensure that the common high-risk scenarios (IEExec, AppLaunch, etc)
        // will never be able to load untrusted PDB files.
        if( Security::CanCallUnmanagedCode( this ) )
        {
            return TRUE;
        }
    } 
    else if( policy == eSymbolReadingAlways )
    {
        return TRUE;
    }
    else
    {        
        _ASSERTE( policy == eSymbolReadingNever );
    }

    return FALSE;
}

// At this point, this is only called when we're creating an appdomain
// out of an array of bytes, so we'll keep the IStream that we create
// around in case the debugger attaches later (including detach & re-attach!)
HRESULT Module::SetSymbolBytes(BYTE *pbSyms, DWORD cbSyms)
{
    CONTRACTL
    {
        INSTANCE_CHECK;
        NOTHROW;
        GC_TRIGGERS;
        MODE_ANY;
        INJECT_FAULT(return E_OUTOFMEMORY;);
    }
    CONTRACTL_END


    HRESULT hr = S_OK;

    // Create a IStream from the memory for the syms.
    CGrowableStream *pStream = new (nothrow) CGrowableStream();
    if (pStream == NULL)
        return E_OUTOFMEMORY;

    // Do not need to AddRef the CGrowableStream because the constructor set it to 1
    // ref count already. The Module will keep a copy for its own use.

    // Make sure to set the symbol stream on the module before
    // attempting to send UpdateModuleSyms messages up for it.
    SetInMemorySymbolStream(pStream);

#ifdef LOGGING 
    LPCWSTR pName = NULL;
    pName = GetDebugName();
#endif // LOGGING

    ULONG cbWritten;
    IfFailRet(HRESULT_FROM_WIN32(pStream->Write((const void *)pbSyms,
                                                (ULONG)cbSyms,
                                                &cbWritten)));

    // clear the old one if exist
    if (m_pISymUnmanagedReader)
    {
        m_pISymUnmanagedReader->Release();
        m_pISymUnmanagedReader = NULL; // We'll try again next time.
    }

    // Don't eager load the diasymreader
    BEGIN_EXCEPTION_GLUE(&hr, NULL)
    {

#ifdef DEBUGGING_SUPPORTED 
        // Tell the debugger that symbols have been loaded for this
        // module.  We iterate through all domains which contain this
        // module's assembly, and send a debugger notify for each one.
        if (CORDebuggerAttached())
        {
            AppDomainIterator i(FALSE);

            while (i.Next())
            {
                AppDomain *pDomain = i.GetDomain();

                if (pDomain->IsDebuggerAttached() && (GetDomain() == SystemDomain::System() ||
                                                      pDomain->ContainsAssembly(m_pAssembly)))
                    g_pDebugInterface->UpdateModuleSyms(this, pDomain, FALSE);
            }
        }
#endif // DEBUGGING_SUPPORTED
    }
    END_EXCEPTION_GLUE
    return hr;
}


// Distinguish between the fake class associated with the module (global fields &
// functions) from normal classes.
void Module::AddClass(mdTypeDef classdef)
{
    CONTRACTL
    {
        INSTANCE_CHECK;
        THROWS;
        GC_TRIGGERS;
        MODE_ANY;
        PRECONDITION(!IsResource());
    }
    CONTRACTL_END;

    if (RidFromToken(classdef) == 0)
    {
        BuildClassForModule();
    }
    else
    {
        AllocMemTracker amTracker;
        GetClassLoader()->AddAvailableClassDontHaveLock(this,
                                                        classdef,
                                                        &amTracker);
        amTracker.SuppressRelease();
    }
}

//---------------------------------------------------------------------------
// For the global class this builds the table of MethodDescs an adds the rids
// to the MethodDef map.
//---------------------------------------------------------------------------
void Module::BuildClassForModule()
{
    CONTRACTL
    {
        INSTANCE_CHECK;
        THROWS;
        GC_TRIGGERS;
        MODE_ANY;
    }
    CONTRACTL_END;

    HENUMInternal   hEnum;
    DWORD           cFunctions, cFields;

    // Obtain count of global functions
    IfFailThrow(GetMDImport()->EnumGlobalFunctionsInit(&hEnum));
    cFunctions = GetMDImport()->EnumGetCount(&hEnum);
    GetMDImport()->EnumClose(&hEnum);

    // Obtain count of global fields
    IfFailThrow(GetMDImport()->EnumGlobalFieldsInit(&hEnum));
    cFields = GetMDImport()->EnumGetCount(&hEnum);
    GetMDImport()->EnumClose(&hEnum);

    // If we have any work to do...
    if (cFunctions > 0 || cFields > 0)
    {
        COUNTER_ONLY(size_t _HeapSize = 0);

        TypeKey typeKey(this, COR_GLOBAL_PARENT_TOKEN);
        GCX_PREEMP();
        TypeHandle typeHnd = GetClassLoader()->LoadTypeHandleForTypeKeyNoLock(&typeKey);

#ifdef ENABLE_PERF_COUNTERS 

        _HeapSize = typeHnd.GetDomain()->GetHighFrequencyHeap()->GetSize();

        GetPrivatePerfCounters().m_Loading.cbLoaderHeapSize = _HeapSize;
#endif // ENABLE_PERF_COUNTERS

    }
}

#endif // !DACCESS_COMPILE

const void *Module::GetIL(DWORD target)
{
    WRAPPER_CONTRACT;

    return m_file->GetIL(target);
}

#ifndef DACCESS_COMPILE 

CHECK Module::CheckIL(RVA il, COUNT_T size)
{
    WRAPPER_CONTRACT;
    // Don't check if we're a reflection module or
    // if we have methods with phony rvas.
    if (!IsReflection()
        && ((m_dwTransientFlags & HAS_PHONY_IL_RVAS) == 0))
        CHECK(m_file->CheckIL(il, size));
    CHECK_OK;
}

CHECK Module::CheckIL(RVA il)
{
    WRAPPER_CONTRACT;
    // Don't check if we're a reflection module or
    // if we have methods with phony rvas.
    if (!IsReflection()
        && ((m_dwTransientFlags & HAS_PHONY_IL_RVAS) == 0))
        CHECK(m_file->CheckIL(il));
    CHECK_OK;
}

BYTE *Module::GetPhonyILBase()
{
    WRAPPER_CONTRACT;

    return m_file->GetPhonyILBase();
}

RVA Module::GetPhonyILRva(BYTE *il)
{
    WRAPPER_CONTRACT;

    // Set a flag on the module that we should be on the lookout
    // for bogus RVAs.  These are only used in full trust scenarios
    // (EnC & profiling) so disabling checks is OK. (If we wanted
    // to be really fancy we could remember the specific phony RVAs
    // but it's probably not worth it.)
    FastInterlockOr(&m_dwTransientFlags, HAS_PHONY_IL_RVAS);

    return m_file->GetPhonyILRva(il);
}

#endif // !DACCESS_COMPILE

void *Module::GetRvaField(DWORD rva)
{
    WRAPPER_CONTRACT;


    return m_file->GetRvaField(rva);
}

#ifndef DACCESS_COMPILE 

CHECK Module::CheckRvaField(RVA field)
{
    WRAPPER_CONTRACT;
    if (!IsReflection())
        CHECK(m_file->CheckRvaField(field));
    CHECK_OK;
}

CHECK Module::CheckRvaField(RVA field, COUNT_T size)
{
    WRAPPER_CONTRACT;
    if (!IsReflection())
        CHECK(m_file->CheckRvaField(field, size));
    CHECK_OK;
}

#endif // !DACCESS_COMPILE

BOOL Module::HasTls()
{
    WRAPPER_CONTRACT;

    return m_file->HasTls();
}

BOOL Module::IsRvaFieldTls(DWORD rva)
{
    WRAPPER_CONTRACT;

    return m_file->IsRvaFieldTls(rva);
}

UINT32 Module::GetFieldTlsOffset(DWORD rva)
{
    WRAPPER_CONTRACT;

    return m_file->GetFieldTlsOffset(rva);
}

UINT32 Module::GetTlsIndex()
{
    WRAPPER_CONTRACT;

    return m_file->GetTlsIndex();
}

PCCOR_SIGNATURE Module::GetSignature(RVA signature)
{
    WRAPPER_CONTRACT;

    return m_file->GetSignature(signature);
}

RVA Module::GetSignatureRva(PCCOR_SIGNATURE signature)
{
    WRAPPER_CONTRACT;

    return m_file->GetSignatureRva(signature);
}

#ifndef DACCESS_COMPILE 

CHECK Module::CheckSignatureRva(RVA signature)
{
    WRAPPER_CONTRACT;
    CHECK(m_file->CheckSignatureRva(signature));
    CHECK_OK;
}

CHECK Module::CheckSignature(PCCOR_SIGNATURE signature)
{
    WRAPPER_CONTRACT;
    CHECK(m_file->CheckSignature(signature));
    CHECK_OK;
}

void Module::InitializeStringData(DWORD token, EEStringData *pstrData, CQuickBytes *pqb)
{
    CONTRACTL
    {
        INSTANCE_CHECK;
        THROWS;
        GC_TRIGGERS;
        MODE_ANY;
        INJECT_FAULT(COMPlusThrowOM());
        PRECONDITION(TypeFromToken(token) == mdtString);
    }
    CONTRACTL_END;

    if(!GetMDImport()->IsValidToken(token))
    {
        THROW_BAD_FORMAT(BFA_BAD_STRING_TOKEN, this);
    }

    BOOL fIs80Plus;
    DWORD dwCharCount;
    LPCWSTR pString = GetMDImport()->GetUserString(token, &dwCharCount, &fIs80Plus);

    if (!pString)
    {
        THROW_BAD_FORMAT(BFA_BAD_STRING_TOKEN_RANGE, this);
    }

#if !BIGENDIAN 
    pstrData->SetStringBuffer(pString);
#else // !!BIGENDIAN
    _ASSERTE(pqb != NULL);

    LPWSTR pSwapped;

    pSwapped = (LPWSTR) pqb->AllocThrows(dwCharCount * sizeof(WCHAR));
    memcpy((void*)pSwapped, (void*)pString, dwCharCount*sizeof(WCHAR));
    SwapStringLength(pSwapped, dwCharCount);

    pstrData->SetStringBuffer(pSwapped);
#endif // !!BIGENDIAN

        // MD and String look at this bit in opposite ways.  Here's where we'll do the conversion.
        // MD sets the bit to true if the string contains characters greater than 80.
        // String sets the bit to true if the string doesn't contain characters greater than 80.

    pstrData->SetCharCount(dwCharCount);
    pstrData->SetIsOnlyLowChars(!fIs80Plus);
}


OBJECTHANDLE Module::ResolveStringRef(DWORD token, BaseDomain *pDomain, bool bNeedToSyncWithFixups)
{
    CONTRACTL
    {
        INSTANCE_CHECK;
        THROWS;
        GC_TRIGGERS;
        MODE_ANY;
        INJECT_FAULT(COMPlusThrowOM());
        PRECONDITION(TypeFromToken(token) == mdtString);
    }
    CONTRACTL_END;

    EEStringData strData;
    OBJECTHANDLE string = NULL;

#if !BIGENDIAN 
    InitializeStringData(token, &strData, NULL);
#else // !!BIGENDIAN
    CQuickBytes qb;
    InitializeStringData(token, &strData, &qb);
#endif // !!BIGENDIAN

    GCX_COOP();

    if (HasNativeImage() && IsNoStringInterning())
    {
        /* Unfortunately, this assert won't work in some cases of generics, consider the following scenario:

            1) Generic type in mscorlib.
            2) Instantiation of generic (1) (via valuetype) in another module
            3) other module now holds a copy of the code of the generic for that particular instantiation
               however, it is resolving the string literals against mscorlib, which breaks the invariant
               this assert was based on (no string fixups against other modules). In fact, with NoStringInterning,
               our behavior is not very intuitive.
        */
        /*
        _ASSERTE(pDomain == GetAssembly()->GetDomain() && "If your are doing ldstr for a string"
        "in another module, either the JIT is very smart or you have a bug, check INLINE_NO_CALLEE_LDSTR");

        */

        // The caller is going to update an ngen fixup entry. The fixup entry
        // is used to reference the string and to ensure that the string is
        // allocated only once. Hence, this operation needs to be done under a lock.
        _ASSERTE(GetFixupCrst()->OwnedByCurrentThread());

        // Allocate handle
        OBJECTREF* pRef = pDomain->AllocateObjRefPtrsInLargeTable(1);

        STRINGREF str = AllocateStringObject(&strData);
        SetObjectReference(pRef, str, NULL);

        #ifdef LOGGING 
        int length = strData.GetCharCount();
        length = min(length, 100);
        WCHAR *szString = (WCHAR *)_alloca((length + 1) * sizeof(WCHAR));
        memcpyNoGCRefs((void*)szString, (void*)strData.GetStringBuffer(), length * sizeof(WCHAR));
        szString[length] = '\0';
        LOG((LF_APPDOMAIN, LL_INFO10000, "String literal \"%S\" won't be interned due to NoInterningAttribute\n", szString));
        #endif // LOGGING

        return (OBJECTHANDLE) pRef;
    }

    // Retrieve the string from the AppDomain.
    string = (OBJECTHANDLE)pDomain->GetStringObjRefPtrFromUnicodeString(&strData);

    return string;
}

//
// Used by the verifier.  Returns whether this stringref is valid.
//
CHECK Module::CheckStringRef(DWORD token)
{
    WRAPPER_CONTRACT;
    CHECK(TypeFromToken(token)==mdtString);
    CHECK(!IsNilToken(token));
    CHECK(GetMDImport()->IsValidToken(token));
    CHECK_OK;
}

mdToken Module::GetEntryPointToken()
{
    WRAPPER_CONTRACT;

    return m_file->GetEntryPointToken();
}

BYTE *Module::GetProfilerBase()
{
    CONTRACT(BYTE*)
    {
        NOTHROW;
        GC_NOTRIGGER;
    }
    CONTRACT_END;

    if (m_file == NULL)  // I'd rather assert this is not the case...
    {
        RETURN NULL;
    }
    else if (HasNativeImage())
    {
        RETURN (BYTE*)(GetNativeImage()->GetBase());
    }
    else if (m_file->IsLoaded())
    {
        RETURN  (BYTE*)(m_file->GetLoadedIL()->GetBase());
    }
    else
    {
        RETURN NULL;
    }
}

BOOL Module::AddActiveDependency(Module *pModule, BOOL unconditional)
{
    CONTRACT(BOOL)
    {
        THROWS;
        GC_TRIGGERS;
        PRECONDITION(CheckPointer(pModule));
        PRECONDITION(pModule != this);
        PRECONDITION(!IsSystem());
        PRECONDITION(!GetAssembly()->IsDomainNeutral() || pModule->GetAssembly()->IsDomainNeutral());
        POSTCONDITION(HasActiveDependency(pModule));
        POSTCONDITION(!unconditional || HasUnconditionalActiveDependency(pModule));
        // Postcondition about activation
    }
    CONTRACT_END;

    CONSISTENCY_CHECK_MSG(!GetAssembly()->IsDomainNeutral() || pModule->GetAssembly()->IsDomainNeutral(),
                          "Active dependency from domain neutral to domain bound is illegal");

    // We must track this dependency for multiple domains' use
    STRESS_LOG2(LF_CLASSLOADER, LL_INFO100," %08x -> %08x",this,pModule);
    _ASSERTE(!unconditional || pModule->HasNativeImage()); 
    _ASSERTE(!unconditional || HasNativeImage()); 
    
    COUNT_T index;

    // this function can run in parallel with DomainFile::Activate and sychronizes via GetNumberOfActivations()
    // because we expose dependency only in the end Domain::Activate might miss it, but it will increment a counter module
    // so we can realize we have to additionally propagate a dependency into that appdomain.
    // currently we do it just by rescanning al appdomains.
    // needless to say, updating the counter and checking counter+adding dependency to the list should be atomic


    BOOL propagate = FALSE;
    ULONG startCounter=0;
    ULONG endCounter=0;    
    do
    {
        // First, add the dependency to the physical dependency list
        {
            CrstPreempHolder lock(&m_Crst);
            startCounter=GetNumberOfActivations();

            index = m_activeDependencies.FindElement(0, pModule);
            if (index == (COUNT_T) ArrayList::NOT_FOUND)
            {
                propagate = TRUE;
                STRESS_LOG3(LF_CLASSLOADER, LL_INFO100,"Adding new module dependency %08x -> %08x, unconditional=%i",this,pModule,unconditional);
            }

            if (unconditional)
            {
#ifdef _DEBUG 
                lock.Release();
                CHECK check=DomainFile::CheckUnactivatedInAllDomains(this);
                lock.Acquire();

                if (propagate)
                CONSISTENCY_CHECK_MSG(check,
                                      "Unconditional dependency cannot be added after module has already been activated");
#endif // _DEBUG
                index = m_activeDependencies.GetCount();
                m_activeDependencies.Append(pModule);
                m_unconditionalDependencies.SetBit(index);
                STRESS_LOG2(LF_CLASSLOADER, LL_INFO100," Unconditional module dependency propagated %08x -> %08x",this,pModule);
                // Now other threads can skip this dependency without propagating.
                RETURN propagate;
            }

        }

        // Now we have to propagate any module activations in the loader

        if (propagate)
        {

            _ASSERTE(!unconditional);
            DomainFile::PropagateNewActivation(this, pModule);

            CrstPreempHolder lock(&m_Crst);
            STRESS_LOG2(LF_CLASSLOADER, LL_INFO100," Conditional module dependency propagated %08x -> %08x",this,pModule);
            // Now other threads can skip this dependency without propagating.
            endCounter=GetNumberOfActivations();
            if(startCounter==endCounter)
                m_activeDependencies.Append(pModule);
        }
        
    }while(propagate && startCounter!=endCounter); //need to retry if someone was activated in parallel
    RETURN propagate;
}

BOOL Module::HasActiveDependency(Module *pModule)
{
    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
        MODE_ANY;
        PRECONDITION(CheckPointer(pModule));
    }
    CONTRACTL_END;

    if (pModule == this)
        return TRUE;

    DependencyIterator i = IterateActiveDependencies();
    while (i.Next())
    {
        if (i.GetDependency() == pModule)
            return TRUE;
    }

    return FALSE;
}

BOOL Module::HasUnconditionalActiveDependency(Module *pModule)
{
    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
        MODE_ANY;
        PRECONDITION(CheckPointer(pModule));
    }
    CONTRACTL_END;

    if (pModule == this)
        return TRUE;

    DependencyIterator i = IterateActiveDependencies();
    while (i.Next())
    {
        if (i.GetDependency() == pModule
            && i.IsUnconditional())
            return TRUE;
    }

    return FALSE;
}

BOOL Module::AddClassDependency(Module *pModule, BitMask *mask)
{
    CONTRACT(BOOL)
    {
        THROWS;
        GC_TRIGGERS;
        PRECONDITION(CheckPointer(pModule));
        PRECONDITION(pModule != this);
    }
    CONTRACT_END;

    if (pModule->IsSystem() ||
        HasUnconditionalActiveDependency(pModule))
        RETURN FALSE;

    COUNT_T index;

    // Add the dependency to the physical dependency list

    {
        CrstPreempHolder lock(&m_Crst);

        //

        index = m_classDependencies.FindElement(0, pModule);
        if (index == (COUNT_T) ArrayList::NOT_FOUND)
        {
            index = m_classDependencies.GetCount();
            m_classDependencies.Append(pModule);
        }
    }

    mask->SetBit(index);

    RETURN TRUE;
}


void Module::EnableModuleFailureTriggers(Module *pModuleTo, AppDomain *pDomain)
{
    // At this point we need to enable failure triggers we have placed in the code for this module.  However,
    // the failure trigger codegen logic is NYI.  To keep correctness, we just allow the exception to propagate
    // here.  Note that in general this will enforce the failure invariants, but will also result in some rude
    // behavior as these failures will be propagated too widely rather than constrained to the appropriate
    // assemblies/app domains.
    //
    // This should throw.
    DomainFile *pDomainFileTo = pModuleTo->GetDomainFile(pDomain);
    pDomainFileTo->EnsureActive();

    UNREACHABLE_MSG("Module failure triggers NYI");
}

#endif // !DACCESS_COMPILE

Assembly *Module::GetAssemblyIfLoaded(mdAssemblyRef kAssemblyRef)
{
    CONTRACT(Assembly *)
    {
        INSTANCE_CHECK;
        NOTHROW;
        GC_NOTRIGGER;
        MODE_ANY;
        POSTCONDITION(CheckPointer(RETVAL, NULL_OK));
    }
    CONTRACT_END;

    Assembly *pAssembly = LookupAssemblyRef(kAssemblyRef);
    if (!pAssembly) {

#ifndef DACCESS_COMPILE 

        AssemblySpec spec;
        if (!spec.InitializeSpec(kAssemblyRef, GetMDImport(), GetAssembly()->GetManifestFile(),
                                 IsIntrospectionOnly(), FALSE /*fThrow*/))
            RETURN NULL;

        DomainAssembly *pDomainAssembly = GetAppDomain()->FindCachedAssembly(&spec, FALSE /*fThrow*/);
        if (pDomainAssembly && pDomainAssembly->IsLoaded())
            pAssembly = pDomainAssembly->GetCurrentAssembly();

        if (pAssembly)
            StoreAssemblyRef(kAssemblyRef, pAssembly);

#else // DACCESS_COMPILE
        DacNotImpl();
#endif // DACCESS_COMPILE
    }

    RETURN pAssembly;
}

#ifndef DACCESS_COMPILE 




DomainAssembly *Module::LoadAssembly(AppDomain *pDomain, mdAssemblyRef kAssemblyRef)
{
    CONTRACT(DomainAssembly *)
    {
        INSTANCE_CHECK;
        THROWS;
        GC_TRIGGERS;
        MODE_ANY;
        PRECONDITION(CheckPointer(pDomain));
        POSTCONDITION(CheckPointer(RETVAL, NULL_NOT_OK));
    }
    CONTRACT_END;

    ETWTraceStartup trace(ETW_TYPE_STARTUP_LOADERCATCHALL);

    Assembly *pAssembly = LookupAssemblyRef(kAssemblyRef);

    DomainAssembly *pDomainAssembly;
    if (pAssembly != NULL)
    {
        pDomainAssembly = pAssembly->FindDomainAssembly(pDomain);

        if (pDomainAssembly == NULL)
            pDomainAssembly=pAssembly->GetDomainAssembly(pDomain);
        pDomain->LoadDomainFile(pDomainAssembly, FILE_LOADED);
    }
    else if (IsIntrospectionOnly())
    {
        AssemblySpec spec;
        spec.InitializeSpec(kAssemblyRef, GetMDImport(), GetDomainFile(GetAppDomain())->GetFile()->GetAssembly(), IsIntrospectionOnly());
        pDomainAssembly = GetAppDomain()->BindAssemblySpecForIntrospectionDependencies(&spec);
    }
    else
    {
        PEAssemblyHolder pFile(GetDomainFile(GetAppDomain())->GetFile()->LoadAssembly(kAssemblyRef));
        AssemblySpec spec;
        spec.InitializeSpec(kAssemblyRef, GetMDImport(), GetDomainFile(GetAppDomain())->GetFile()->GetAssembly(), IsIntrospectionOnly());
        pDomainAssembly = GetAppDomain()->LoadDomainAssembly(&spec, pFile, FILE_LOADED, NULL, NULL);
    }

    if (pDomainAssembly != NULL)
    {
        if (pAssembly == NULL)
        {
            if (pDomainAssembly->GetCurrentAssembly() != NULL)
                StoreAssemblyRef(kAssemblyRef, pDomainAssembly->GetCurrentAssembly());
        }
        else
        {
            CONSISTENCY_CHECK(pAssembly == pDomainAssembly->GetAssembly());
        }
    }

    RETURN pDomainAssembly;
}

Module *Module::GetModuleIfLoaded(mdFile kFile, BOOL permitResources/*=TRUE*/)
{
    CONTRACT(Module *)
    {
        INSTANCE_CHECK;
        NOTHROW;
        GC_NOTRIGGER;
        MODE_ANY;
        PRECONDITION(TypeFromToken(kFile) == mdtFile
                     || TypeFromToken(kFile) == mdtModuleRef);
        POSTCONDITION(CheckPointer(RETVAL, NULL_OK));
        FORBID_FAULT;
    }
    CONTRACT_END;

    ENABLE_FORBID_GC_LOADER_USE_IN_THIS_SCOPE();

    // Handle the module ref case
    if (TypeFromToken(kFile) == mdtModuleRef)
    {
        LPCSTR moduleName;
        GetMDImport()->GetModuleRefProps(kFile, &moduleName);

        // This is required only because of some lower casing on the name
        kFile = GetAssembly()->GetManifestFileToken(moduleName);
        if (kFile == mdTokenNil)
            RETURN NULL;

        RETURN GetAssembly()->GetManifestModule()->GetModuleIfLoaded(kFile, permitResources);
    }

    Module *pModule = LookupFile(kFile);
    if (pModule == NULL)
    {
        if (IsManifest())
        {
            if (kFile == mdFileNil)
                pModule = GetAssembly()->GetManifestModule();
        }
        else
        {
            // If we didn't find it there, look at the "master rid map" in the manifest file
            Assembly *pAssembly = GetAssembly();
            mdFile kMatch;

            // This is required only because of some lower casing on the name
            kMatch = pAssembly->GetManifestFileToken(GetMDImport(), kFile);
            if (IsNilToken(kMatch)) {
                if (kMatch == mdFileNil)
                    pModule = pAssembly->GetManifestModule();
                else
                    RETURN NULL;
            }
            else
            pModule = pAssembly->GetManifestModule()->LookupFile(kMatch);
        }

        if (pModule)
            StoreFileNoThrow(kFile, pModule);
    }

    // We may not want to return a resource module
    if (!permitResources && pModule && pModule->IsResource())
        pModule = NULL;

    RETURN pModule;
}

DomainFile *Module::LoadModule(AppDomain *pDomain, mdFile kFile,
                               BOOL permitResources/*=TRUE*/, BOOL bindOnly/*=FALSE*/)
{
    CONTRACT(DomainFile *)
    {
        INSTANCE_CHECK;
        THROWS;
        GC_TRIGGERS;
        MODE_ANY;
        PRECONDITION(TypeFromToken(kFile) == mdtFile
                     || TypeFromToken(kFile) == mdtModuleRef);
        POSTCONDITION(CheckPointer(RETVAL, !permitResources || bindOnly ? NULL_OK : NULL_NOT_OK));
    }
    CONTRACT_END;


    // Handle the module ref case
    if (TypeFromToken(kFile) == mdtModuleRef)
    {
        LPCSTR moduleName;
        GetMDImport()->GetModuleRefProps(kFile, &moduleName);
        mdFile kFileLocal = GetAssembly()->GetManifestFileToken(moduleName);

        if (kFileLocal == mdTokenNil)
            COMPlusThrowHR(COR_E_BADIMAGEFORMAT);

        RETURN GetAssembly()->GetManifestModule()->LoadModule(pDomain, kFileLocal, permitResources, bindOnly);
    }

    // First, make sure the assembly is loaded in our domain

    DomainAssembly *pDomainAssembly = GetAssembly()->FindDomainAssembly(pDomain);
    if (!bindOnly)
    {
        if (pDomainAssembly == NULL)
            pDomainAssembly = GetAssembly()->GetDomainAssembly(pDomain);
        pDomain->LoadDomainFile(pDomainAssembly, FILE_LOADED);
    }

    if (kFile == mdFileNil)
        RETURN pDomainAssembly;

    if (pDomainAssembly == NULL)
        RETURN NULL;

    // Now look for the module in the rid maps

    Module *pModule = LookupFile(kFile);
    if (pModule == NULL && !IsManifest())
    {
        // If we didn't find it there, look at the "master rid map" in the manifest file
        Assembly *pAssembly = GetAssembly();
        mdFile kMatch = pAssembly->GetManifestFileToken(GetMDImport(), kFile);
        if (IsNilToken(kMatch)) {
            if (kMatch == mdFileNil)
                pModule = pAssembly->GetManifestModule();
            else
                COMPlusThrowHR(COR_E_BADIMAGEFORMAT);
        }
        else
            pModule = pAssembly->GetManifestModule()->LookupFile(kMatch);
    }

    // Get a DomainModule for our domain

    DomainModule *pDomainModule = NULL;
    if (pModule)
    {
        pDomainModule = pModule->FindDomainModule(pDomain);

        if (!bindOnly && (permitResources || !pModule->IsResource()))
        {
            if (pDomainModule == NULL)
                pDomainModule = pDomain->LoadDomainModule(pDomainAssembly, (PEModule*) pModule->GetFile(), FILE_LOADED);
            else
                pDomain->LoadDomainFile(pDomainModule, FILE_LOADED);
        }
    }
    else if (!bindOnly)
    {
        PEModuleHolder pFile(GetAssembly()->LoadModule(kFile, permitResources));
        if (pFile)
            pDomainModule = pDomain->LoadDomainModule(pDomainAssembly, pFile, FILE_LOADED);
    }

    // Cache the result in the rid map
    if (pDomainModule != NULL && pDomainModule->GetCurrentModule() != NULL)
        StoreFileThrowing(kFile, pDomainModule->GetCurrentModule());

    // Make sure we didn't load a different module than what was in the rid map
    CONSISTENCY_CHECK(pDomainModule == NULL || pModule == NULL || pDomainModule->GetModule() == pModule);

    // We may not want to return a resource module
    if (!permitResources && pDomainModule != NULL && pDomainModule->GetFile()->IsResource())
        pDomainModule = NULL;

    RETURN pDomainModule;
}


Module* Module::LookupModule(mdToken kFile,BOOL permitResources/*=TRUE*/)
{
    CONTRACT(Module *)
    {
        INSTANCE_CHECK;
        if (FORBIDGC_LOADER_USE_ENABLED()) NOTHROW; else THROWS;
        if (FORBIDGC_LOADER_USE_ENABLED()) GC_NOTRIGGER; else GC_TRIGGERS;
        if (FORBIDGC_LOADER_USE_ENABLED()) FORBID_FAULT; else { INJECT_FAULT(COMPlusThrowOM();); }
        MODE_ANY;
        PRECONDITION(TypeFromToken(kFile) == mdtFile
                     || TypeFromToken(kFile) == mdtModuleRef);
        POSTCONDITION(CheckPointer(RETVAL, NULL_OK));
    }
    CONTRACT_END;
    
    if (TypeFromToken(kFile) == mdtModuleRef)
    {
        LPCSTR moduleName;
        IfFailThrow(GetMDImport()->GetModuleRefProps(kFile, &moduleName));
        mdFile kFileLocal = GetAssembly()->GetManifestFileToken(moduleName);

        if (kFileLocal == mdTokenNil)
            COMPlusThrowHR(COR_E_BADIMAGEFORMAT);

        RETURN GetAssembly()->GetManifestModule()->LookupModule(kFileLocal, permitResources);
    }

    Module *pModule = LookupFile(kFile);
    if (pModule == NULL && !IsManifest())
    {
        // If we didn't find it there, look at the "master rid map" in the manifest file
        Assembly *pAssembly = GetAssembly();
        mdFile kMatch = pAssembly->GetManifestFileToken(GetMDImport(), kFile);
        if (IsNilToken(kMatch)) {
            if (kMatch == mdFileNil)
                pModule = pAssembly->GetManifestModule();
            else
                COMPlusThrowHR(COR_E_BADIMAGEFORMAT);
        }
        else
            pModule = pAssembly->GetManifestModule()->LookupFile(kMatch);
    }
    RETURN pModule;
}
#endif // !DACCESS_COMPILE


TypeHandle Module::LookupTypeRef(mdTypeRef token, ClassLoadLevel level)
{
    STATIC_CONTRACT_NOTHROW;
    STATIC_CONTRACT_GC_NOTRIGGER;
    STATIC_CONTRACT_FORBID_FAULT;

    _ASSERTE(TypeFromToken(token) == mdtTypeRef);

    g_IBCLogger.LogRidMapAccess( MakePair( this, token ) );

    TypeHandle entry = TypeHandle::FromData(GetFromRidMap(&m_TypeRefToMethodTableMap,
                                                  RidFromToken(token)));

    if (entry.IsNull() || entry.GetLoadLevel() < level)
        return TypeHandle();

    // Cannot do this in a NOTHROW function.
    // Note that this could be called while doing GC from the prestub of
    // a method to resolve typerefs in a signature. We cannot THROW
    // during GC.

    // @PERF: Enable this so that we do not need to touch metadata
    // to resolve typerefs


    return entry;
}




#ifndef DACCESS_COMPILE 

// Increase the size of one of the maps, such that it can handle a RID of at least "rid".
//
// This function must also check that another thread didn't already add a LookupMap capable
// of containing the same RID.
//
LookupMap *Module::IncMapSize(LookupMap *pMap, DWORD rid)
{
    CONTRACT(LookupMap *)
    {
        INSTANCE_CHECK;
        THROWS;
        GC_NOTRIGGER;
        MODE_ANY;
        INJECT_FAULT(ThrowOutOfMemory(););
        POSTCONDITION(CheckPointer(RETVAL));
    }
    CONTRACT_END;

    LookupMap  *pPrev = NULL;
    DWORD       dwPrevMaxIndex = 0;
    LookupMap  *pNewMap;

    {
        CrstHolder ch(&m_LookupTableCrst);
        // Check whether we can already handle this RID index
        do
        {
            if (rid < pMap->dwMaxIndex)
            {
                // Already there - some other thread must have added it
                RETURN pMap;
            }

            dwPrevMaxIndex = pMap->dwMaxIndex;
            pPrev = pMap;
            pMap = pMap->pNext;
        } while (pMap != NULL);

        _ASSERTE(pPrev != NULL); // should never happen, because there's always at least one map

        DWORD dwMinNeeded = rid - dwPrevMaxIndex + 1; // Min # elements required for this chunk
        DWORD dwBlockSize = *pPrev->pdwBlockSize;   // Min # elements required by block size
        DWORD dwSizeToAllocate;                     // Actual number of elements we will allocate

        if (dwMinNeeded > dwBlockSize)
        {
            dwSizeToAllocate = dwMinNeeded;
        }
        else
        {
            dwSizeToAllocate = dwBlockSize;
            dwBlockSize <<= 1;                      // Increase block size
            *pPrev->pdwBlockSize = dwBlockSize;
        }

        MEMORY_REPORT_CONTEXT_SCOPE("RidMap");

        _ASSERTE (m_pAssembly && m_pAssembly->GetLowFrequencyHeap());

        pNewMap = (LookupMap *) (void*)m_pAssembly->GetLowFrequencyHeap()->AllocMem(sizeof(LookupMap) + dwSizeToAllocate*sizeof(void*));

        // Note: Memory allocated on loader heap is zero filled
        // memset(pNewMap, 0, sizeof(LookupMap) + dwSizeToAllocate*sizeof(void*));

        pNewMap->pNext          = NULL;
        pNewMap->dwMaxIndex     = dwPrevMaxIndex + dwSizeToAllocate;
        pNewMap->pdwBlockSize   = pPrev->pdwBlockSize;

        // pTable is not a pointer to the beginning of the table.  Rather, anyone who uses Table can
        // simply index off their RID (as long as their RID is < dwMaxIndex, and they are not serviced
        // by a previous table for lower RIDs).
        pNewMap->pTable         = ((TADDR *) (pNewMap + 1)) - dwPrevMaxIndex;

        // Link ourselves in

        pPrev->pNext            = pNewMap;
    }

    RETURN pNewMap;
}


// Stores an association in a ridmap that has been previously grown to
// the required size. Will never throw or fail.
void Module::SetInRidMap(LookupMap *pMap, DWORD rid, SIZE_T pDatum)
{
    WRAPPER_CONTRACT;

    for(;;)
    {
        _ASSERTE(pMap != NULL && "The onus is on my caller to make sure the ridmap was already grown to the right size");

        if (rid < pMap->dwMaxIndex)
        {
            pMap->pTable[rid] = pDatum;
            return;
        }

        pMap = pMap->pNext;
    }
}

BOOL Module::TryAddToRidMap(LookupMap *pMap, DWORD rid, TADDR pDatum)
{
    CONTRACTL
    {
        INSTANCE_CHECK;
        PRECONDITION(CheckPointer(pMap));
        NOTHROW;
        GC_NOTRIGGER;
        MODE_ANY;
    }
    CONTRACTL_END;

    do
    {
        if (rid < pMap->dwMaxIndex)
        {
            pMap->pTable[rid] = pDatum;
            return TRUE;
        }

        pMap = pMap->pNext;
    } while (pMap != NULL);

    return FALSE;
}

void Module::AddToRidMap(LookupMap *pMap, DWORD rid, TADDR pDatum)
{
    CONTRACTL
    {
        INSTANCE_CHECK;
        PRECONDITION(CheckPointer(pMap));
        THROWS;
        GC_NOTRIGGER;
        MODE_ANY;
        INJECT_FAULT(ThrowOutOfMemory(););
    }
    CONTRACTL_END;


    LookupMap *pMapStart = pMap;

    do
    {
        if (rid < pMap->dwMaxIndex)
        {
            pMap->pTable[rid] = pDatum;
            return;
        }

        pMap = pMap->pNext;
    } while (pMap != NULL);

    pMap = IncMapSize(pMapStart, rid);
    pMap->pTable[rid] = pDatum;
}

#endif // !DACCESS_COMPILE

TADDR* Module::RidToDefHandle(LookupMap *pMap, DWORD rid)
{
    CONTRACT(TADDR*)
    {
        INSTANCE_CHECK;
        NOTHROW;
        GC_NOTRIGGER;
        MODE_ANY;
        PRECONDITION(CheckPointer(pMap));
        POSTCONDITION(CheckPointer(RETVAL, NULL_OK));
    }
    CONTRACT_END

    do
    {
        if (rid < pMap->dwMaxIndex)
        {
            TADDR* result = &(pMap->pTable[rid]);
            if (*result == NULL && !HasNativeImage())
            {
                *result = (TADDR)this | (TADDR)LookupMap::IS_MODULE_BACKPOINTER;
            }
            RETURN result;
        }

        pMap = pMap->pNext;
    } while (pMap != NULL);

    RETURN(NULL);
}

TypeDefHandle Module::TypeDefToTypeDefHandle(mdTypeDef typeDef)
{
    CONTRACT(TypeDefHandle)
    {
        NOTHROW;
        GC_NOTRIGGER;
        MODE_ANY;
        INSTANCE_CHECK;
        PRECONDITION(TypeFromToken(typeDef) == mdtTypeDef);
        PRECONDITION(GetMDImport()->IsValidToken(typeDef));
        POSTCONDITION(CheckPointer(RETVAL));
    }
    CONTRACT_END

    RETURN (TypeDefHandle) RidToDefHandle(&m_TypeDefToMethodTableMap, RidFromToken(typeDef));
}

MethodDefHandle Module::MethodDefToMethodDefHandle(mdMethodDef methodDef)
{
    CONTRACT(MethodDefHandle)
    {
        NOTHROW;
        GC_NOTRIGGER;
        MODE_ANY;
        INSTANCE_CHECK;
        PRECONDITION(TypeFromToken(methodDef) == mdtMethodDef);
        PRECONDITION(GetMDImport()->IsValidToken(methodDef));
        POSTCONDITION(CheckPointer(RETVAL));
    }
    CONTRACT_END

    RETURN (MethodDefHandle) RidToDefHandle(&m_MethodDefToDescMap, RidFromToken(methodDef));
}

/*static*/
Module* Module::GetModuleForTypeDefHandle(TypeDefHandle handle)
{
    CONTRACT(Module*)
    {
        NOTHROW;
        GC_NOTRIGGER;
        MODE_ANY;
        PRECONDITION(CheckPointer(handle));
        POSTCONDITION(CheckPointer(RETVAL));
    }
    CONTRACT_END

    TADDR entry = *((TADDR*) handle);
    if (entry == NULL)
    {
        RETURN (ExecutionManager::FindZapModule((TADDR) handle));
    }
    else if (entry & LookupMap::IS_MODULE_BACKPOINTER)
    {
        RETURN ((Module*) (entry & ~(TADDR)LookupMap::IS_MODULE_BACKPOINTER));
    }
    else
    {
        MethodTable* pMT = (MethodTable*) entry;
        RETURN pMT->GetModule();
    }
}


/*static*/
Module* Module::GetModuleForMethodDefHandle(MethodDefHandle handle)
{
    CONTRACT(Module*)
    {
        NOTHROW;
        GC_NOTRIGGER;
        MODE_ANY;
        PRECONDITION(CheckPointer(handle));
        POSTCONDITION(CheckPointer(RETVAL));
    }
    CONTRACT_END

    TADDR entry = *((TADDR*) handle);
    if (entry == NULL)
    {
        RETURN (ExecutionManager::FindZapModule((TADDR) handle));
    }
    else if (entry & LookupMap::IS_MODULE_BACKPOINTER)
    {
        RETURN ((Module*) (entry & ~(TADDR)LookupMap::IS_MODULE_BACKPOINTER));
    }
    else
    {
        MethodDesc* pMD = (MethodDesc*) entry;
        RETURN pMD->GetModule();
    }
}


mdTypeDef Module::GetTypeDefForTypeDefHandle(TypeDefHandle handle)
{
    CONTRACT(mdTypeDef)
    {
        NOTHROW;
        GC_NOTRIGGER;
        MODE_ANY;
        INSTANCE_CHECK;
        PRECONDITION(CheckPointer(handle));
        POSTCONDITION(!IsNilToken(RETVAL));
        POSTCONDITION(TypeFromToken(RETVAL) == mdtTypeDef);
        POSTCONDITION(GetMDImport()->IsValidToken(RETVAL));
    }
    CONTRACT_END

    TADDR entry = *((TADDR*) handle);
    if (entry == NULL || (entry & LookupMap::IS_MODULE_BACKPOINTER) != 0)
    {
        DWORD rid = GetRidFromMapAddress(&m_TypeDefToMethodTableMap, (TADDR*) handle);
        RETURN (TokenFromRid(rid, mdtTypeDef));
    }
    else
    {
        MethodTable* pMT = (MethodTable*) entry;
        mdTypeDef typeDef = pMT->GetCl();
        _ASSERTE(GetRidFromMapAddress(&m_TypeDefToMethodTableMap, (TADDR*) handle) == RidFromToken(typeDef));
        RETURN typeDef;
    }
}

mdMethodDef Module::GetMethodDefForMethodDefHandle(MethodDefHandle handle)
{
    CONTRACT(mdMethodDef)
    {
        NOTHROW;
        GC_NOTRIGGER;
        MODE_ANY;
        INSTANCE_CHECK;
        PRECONDITION(CheckPointer(handle));
        POSTCONDITION(!IsNilToken(RETVAL));
        POSTCONDITION(TypeFromToken(RETVAL) == mdtMethodDef);
        POSTCONDITION(GetMDImport()->IsValidToken(RETVAL));
    }
    CONTRACT_END

    TADDR entry = *((TADDR*) handle);
    if (entry == NULL || (entry & LookupMap::IS_MODULE_BACKPOINTER) != 0)
    {
        DWORD rid = GetRidFromMapAddress(&m_MethodDefToDescMap, (TADDR*) handle);
        RETURN TokenFromRid(rid, mdtMethodDef);
    }
    else
    {
        MethodDesc* pMD = (MethodDesc*) entry;
        mdMethodDef methodDef = pMD->GetMemberDef();
        _ASSERTE(GetRidFromMapAddress(&m_MethodDefToDescMap, (TADDR*) handle) == RidFromToken(methodDef));
        RETURN methodDef;
    }
}


DWORD Module::GetRidFromMapAddress(LookupMap *pMap, TADDR* addr)
{
    CONTRACTL
    {
        INSTANCE_CHECK;
        NOTHROW;
        GC_NOTRIGGER;
        MODE_ANY;
        PRECONDITION(CheckPointer(pMap));
    }
    CONTRACTL_END

    DWORD index = 0;
    do
    {
        DWORD rid = addr - pMap->pTable;
        if (rid >= index && rid < pMap->dwMaxIndex)
        {
            return rid;
        }
        index = pMap->dwMaxIndex;
        pMap = pMap->pNext;
    } while (pMap != NULL);

    return 0;
}



TADDR Module::GetFromRidMap(LookupMap *pMap, DWORD rid)
{
    CONTRACT(TADDR)
    {
        INSTANCE_CHECK;
        NOTHROW;
        GC_NOTRIGGER;
        MODE_ANY;
        SO_TOLERANT;
        PRECONDITION(CheckPointer(pMap));
        POSTCONDITION(CheckPointer((void*)RETVAL, NULL_OK));
    }
    CONTRACT_END


    TADDR result = NULL;
    do
    {
        if (rid < pMap->dwMaxIndex)
        {
            result = pMap->pTable[rid];
            break;
        }

        pMap = pMap->pNext;
    } while (pMap != NULL);

    if (result & (TADDR)LookupMap::IS_MODULE_BACKPOINTER)
        result = NULL;


    RETURN(result);
}

#ifndef DACCESS_COMPILE 

#ifdef _DEBUG 
void Module::DebugGetRidMapOccupancy(LookupMap *pMap, DWORD *pdwOccupied, DWORD *pdwSize)
{
    LEAF_CONTRACT;

    DWORD       dwMinIndex = 0;

    *pdwOccupied = 0;
    *pdwSize     = 0;

    if(pMap == NULL) return;

    // Go through each linked block
    for (; pMap != NULL; pMap = pMap->pNext)
    {
        DWORD i;
        DWORD dwIterCount = pMap->dwMaxIndex - dwMinIndex;
        TADDR *pRealTableStart = &pMap->pTable[dwMinIndex];

        for (i = 0; i < dwIterCount; i++)
        {
            if (pRealTableStart[i] != NULL && (pRealTableStart[i] & (TADDR)LookupMap::IS_MODULE_BACKPOINTER) == 0)
                (*pdwOccupied)++;
        }

        (*pdwSize) += dwIterCount;

        dwMinIndex = pMap->dwMaxIndex;
    }
}

void Module::DebugLogRidMapOccupancy()
{
    WRAPPER_CONTRACT;

    DWORD dwOccupied1, dwSize1, dwPercent1;
    DWORD dwOccupied2, dwSize2, dwPercent2;
    DWORD dwOccupied3, dwSize3, dwPercent3;
    DWORD dwOccupied4, dwSize4, dwPercent4;
    DWORD dwOccupied5, dwSize5, dwPercent5;
    DWORD dwOccupied6, dwSize6, dwPercent6;
    DWORD dwOccupied7, dwSize7, dwPercent7;

    DebugGetRidMapOccupancy(&m_TypeDefToMethodTableMap, &dwOccupied1, &dwSize1);
    DebugGetRidMapOccupancy(&m_TypeRefToMethodTableMap, &dwOccupied2, &dwSize2);
    DebugGetRidMapOccupancy(&m_MethodDefToDescMap, &dwOccupied3, &dwSize3);
    DebugGetRidMapOccupancy(&m_FieldDefToDescMap, &dwOccupied4, &dwSize4);
    DebugGetRidMapOccupancy(&m_MemberRefToDescMap, &dwOccupied5, &dwSize5);
    DebugGetRidMapOccupancy(&m_FileReferencesMap, &dwOccupied6, &dwSize6);
    DebugGetRidMapOccupancy(&m_ManifestModuleReferencesMap, &dwOccupied7, &dwSize7);

    dwPercent1 = dwOccupied1 ? ((dwOccupied1 * 100) / dwSize1) : 0;
    dwPercent2 = dwOccupied2 ? ((dwOccupied2 * 100) / dwSize2) : 0;
    dwPercent3 = dwOccupied3 ? ((dwOccupied3 * 100) / dwSize3) : 0;
    dwPercent4 = dwOccupied4 ? ((dwOccupied4 * 100) / dwSize4) : 0;
    dwPercent5 = dwOccupied5 ? ((dwOccupied5 * 100) / dwSize5) : 0;
    dwPercent6 = dwOccupied6 ? ((dwOccupied6 * 100) / dwSize6) : 0;
    dwPercent7 = dwOccupied7 ? ((dwOccupied7 * 100) / dwSize7) : 0;

    LOG((
        LF_EEMEM,
        INFO3,
        "   Map occupancy:\n"
        "      TypeDefToEEClass map: %4d/%4d (%2d %%)\n"
        "      TypeRefToEEClass map: %4d/%4d (%2d %%)\n"
        "      MethodDefToDesc map:  %4d/%4d (%2d %%)\n"
        "      FieldDefToDesc map:  %4d/%4d (%2d %%)\n"
        "      MemberRefToDesc map:  %4d/%4d (%2d %%)\n"
        "      FileReferences map:  %4d/%4d (%2d %%)\n"
        "      AssemblyReferences map:  %4d/%4d (%2d %%)\n"
        ,
        dwOccupied1, dwSize1, dwPercent1,
        dwOccupied2, dwSize2, dwPercent2,
        dwOccupied3, dwSize3, dwPercent3,
        dwOccupied4, dwSize4, dwPercent4,
        dwOccupied5, dwSize5, dwPercent5,
        dwOccupied6, dwSize6, dwPercent6,
        dwOccupied7, dwSize7, dwPercent7

    ));
}
#endif // _DEBUG

BOOL Module::CanExecuteCode()
{
    WRAPPER_CONTRACT;

    // In a passive domain, we lock down which assemblies can run code
    if (!GetAppDomain()->IsPassiveDomain())
        return TRUE;

    Assembly * pAssembly = GetAssembly();
    PEAssembly * pPEAssembly = pAssembly->GetManifestFile();

    // ExecuteDLLForAttach does not run the managed entry point in 
    // a passive domain to avoid loader-lock deadlocks.
    // Hence, it is not safe to execute any code from this assembly.
    if (pPEAssembly->GetEntryPointToken(INDEBUG(TRUE)) != mdTokenNil)
        return FALSE;

    // EXEs loaded using LoadAssembly() may not be loaded at their
    // preferred base address. If they have any relocs, these may
    // not have been fixed up.
    if (!pPEAssembly->IsDll() && !pPEAssembly->IsILOnly())
        return FALSE;

    // If the assembly does not have FullTrust, we should not execute its code.
    if (!Security::IsFullyTrusted(pAssembly->GetSecurityDescriptor()))
        return FALSE;

    return TRUE;
}



//
// FindMethod finds a MethodDesc for a global function methoddef or ref
//

MethodDesc *Module::FindMethodThrowing(mdToken pMethod)
{
    CONTRACT (MethodDesc *)
    {
        INSTANCE_CHECK;
        THROWS;
        GC_TRIGGERS;
        MODE_ANY;
        POSTCONDITION(CheckPointer(RETVAL));
    }
    CONTRACT_END

    SigTypeContext typeContext;  /* empty type context: methods will not be generic */
    RETURN MemberLoader::GetMethodDescFromMemberDefOrRefOrSpecThrowing(this, pMethod,
                                                                       &typeContext,
                                                                       TRUE, /* strictMetadataChecks */
                                                                       FALSE /* dont get code shared between generic instantiations */);
}

//
// FindMethod finds a MethodDesc for a global function methoddef or ref
//

MethodDesc *Module::FindMethod(mdToken pMethod)
{
    CONTRACT (MethodDesc *) {
        INSTANCE_CHECK;
        NOTHROW;
        GC_TRIGGERS;
        MODE_ANY;
        POSTCONDITION(CheckPointer(RETVAL, NULL_OK));
    } CONTRACT_END;

    MethodDesc *pMDRet = NULL;

    EX_TRY
    {
        pMDRet = FindMethodThrowing(pMethod);
    }
    EX_CATCH
    {
#ifdef _DEBUG 
        GCX_COOP();
        OBJECTREF throwable = NULL;
        GCPROTECT_BEGIN(throwable);
        throwable = GETTHROWABLE();
        CONTRACT_VIOLATION(ThrowsViolation);
        char szMethodName [MAX_CLASSNAME_LENGTH];
        CEEInfo::findNameOfToken(this, pMethod, szMethodName, COUNTOF (szMethodName));
        LOG((LF_IJW, LL_INFO10, "Failed to find Method: %s for Vtable Fixup\n", szMethodName));
        GCPROTECT_END();
#endif // _DEBUG
    }
    EX_END_CATCH(SwallowAllExceptions)

    RETURN pMDRet;
}

#ifdef DEBUGGING_SUPPORTED 

BOOL Module::NotifyDebuggerLoad(AppDomain *pDomain, int flags, BOOL attaching)
{
    WRAPPER_CONTRACT;

    if (IsIntrospectionOnly())
        return FALSE;

    if (!attaching && !pDomain->IsDebuggerAttached())
        return FALSE;

    // We don't notify the debugger about modules that don't contain any code.
    if (IsResource())
        return FALSE;

    BOOL result = FALSE;

    if (flags & ATTACH_MODULE_LOAD)
    {
        g_pDebugInterface->LoadModule(this,
                                      m_file->GetPath(),
                                      m_file->GetPath().GetCount(),
                                      GetAssembly(), pDomain,
                                      attaching);

        result = TRUE;
    }

    if (flags & ATTACH_CLASS_LOAD)
    {
        LookupMap *pMap;
        DWORD       dwMinIndex = 0;

        // Go through each linked block
        for (pMap = &m_TypeDefToMethodTableMap; pMap != NULL; pMap = pMap->pNext)
        {
            DWORD i;
            DWORD dwIterCount = pMap->dwMaxIndex - dwMinIndex;
            TADDR *pRealTableStart = &pMap->pTable[dwMinIndex];

            for (i = 0; i < dwIterCount; i++)
            {
                TADDR addr = pRealTableStart[i];
                if (addr != NULL && (addr & (TADDR)LookupMap::IS_MODULE_BACKPOINTER) == 0)
                {
                    MethodTable *pMT = (MethodTable *) addr;

                    if (pMT != NULL && pMT->IsRestored())
                    {
                        result = TypeHandle(pMT).NotifyDebuggerLoad(pDomain, attaching) || result;
                    }
                }
            }

            dwMinIndex = pMap->dwMaxIndex;
        }
    }

    return result;
}

void Module::NotifyDebuggerUnload(AppDomain *pDomain)
{
    WRAPPER_CONTRACT;

    if (IsIntrospectionOnly())
        return;

    if (!pDomain->IsDebuggerAttached())
        return;

    // We don't notify the debugger about modules that don't contain any code.
    if (IsResource())
        return;

    LookupMap  *pMap;
    DWORD       dwMinIndex = 0;

    // Go through each linked block
    for (pMap = &m_TypeDefToMethodTableMap; pMap != NULL;
         pMap = pMap->pNext)
    {
        DWORD i;
        DWORD dwIterCount = pMap->dwMaxIndex - dwMinIndex;
        TADDR *pRealTableStart = &pMap->pTable[dwMinIndex];

        for (i = 0; i < dwIterCount; i++)
        {
            TADDR result = pRealTableStart[i];
            if (result != NULL && (result & (TADDR)LookupMap::IS_MODULE_BACKPOINTER) == 0)
            {
                MethodTable *pMT = (MethodTable *) result;

                if (pMT != NULL && pMT->IsRestored())
                {
                    TypeHandle(pMT).NotifyDebuggerUnload(pDomain);
                }
            }
        }

        dwMinIndex = pMap->dwMaxIndex;
    }

    g_pDebugInterface->UnloadModule(this, pDomain);
}
#endif // DEBUGGING_SUPPORTED

#endif // !DACCESS_COMPILE


BOOL Module::IsPersistedObject(void *address)
{
    LEAF_CONTRACT;
    return FALSE;
}



#ifndef DACCESS_COMPILE 


#endif // !DACCESS_COMPILE

#ifndef DACCESS_COMPILE
void Module::SetBeingUnloaded()
{
    LEAF_CONTRACT;
    FastInterlockOr((ULONG*)&m_dwTransientFlags, IS_BEING_UNLOADED);
}
#endif



void Module::LogInstantiatedType(TypeHandle typeHnd, ULONG flagNum)
{
#ifndef DACCESS_COMPILE 

    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
        MODE_ANY;
        PRECONDITION(g_IBCLogger.InstrEnabled());
        PRECONDITION(!typeHnd.HasUnrestoredTypeKey());
        // We want to report the type only in its own loader module as a type's
        // MethodTable can only live in its own loader module.
        // We can relax this if we allow a (duplicate) MethodTable to live
        // in any module (which might be needed for ngen of generics)
        PRECONDITION(this == GetPreferredZapModuleForTypeHandle(typeHnd));
    }
    CONTRACTL_END;

    FAULT_NOT_FATAL();

    EX_TRY
    {
    }

    EX_CATCH
    {
        _ASSERTE(!"Exception in LogInstantiatedType");
    }
    EX_END_CATCH(SwallowAllExceptions);

#endif // !DACCESS_COMPILE

}


void Module::LogInstantiatedMethod( MethodDesc * md )
{
    CONTRACT_VOID
    {
        NOTHROW;
        GC_NOTRIGGER;
        MODE_ANY;
        PRECONDITION( md != NULL );
    }
    CONTRACT_END;

}


#ifndef DACCESS_COMPILE

// ===========================================================================
// ReflectionModule
// ===========================================================================

/* static */
ReflectionModule *ReflectionModule::Create(Assembly *pAssembly, PEFile *pFile, AllocMemTracker *pamTracker)
{
    CONTRACT(ReflectionModule *)
    {
        THROWS;
        GC_TRIGGERS;
        MODE_ANY;
        PRECONDITION(CheckPointer(pAssembly));
        PRECONDITION(CheckPointer(pFile));
        PRECONDITION(pFile->IsDynamic());
        POSTCONDITION(CheckPointer(RETVAL));
    }
    CONTRACT_END;

    // Hoist CONTRACT into separate routine because of EX incompatibility

    mdFile token;
    if (pFile->IsAssembly())
        token = mdFileNil;
    else
        token = ((PEModule *)pFile)->GetToken();

    // Initial memory block for Modules must be zero-initialized (to make it harder
    // to introduce Destruct crashes arising from OOM's during initialization.)

    void* pMemory = pamTracker->Track(pAssembly->GetHighFrequencyHeap()->AllocMem(sizeof(ReflectionModule)));
    ReflectionModuleHolder pModule(new (pMemory) ReflectionModule(pAssembly, token, pFile));

    pModule->DoInit(pamTracker);

    pModule.SuppressRelease();
    
    RETURN pModule;
}


// Module initialization occurs in two phases: the constructor phase and the Initialize phase.
//
// The constructor phase initializes just enough so that Destruct() can be safely called.
// It cannot throw or fail.
//
ReflectionModule::ReflectionModule(Assembly *pAssembly, mdFile token, PEFile *pFile)
  : Module(pAssembly, token, pFile)
{
    CONTRACTL
    {
        NOTHROW;
        GC_TRIGGERS;
        FORBID_FAULT;
    }
    CONTRACTL_END

    m_pInMemoryWriter = NULL;
    m_sdataSection = NULL;
    m_ppISymUnmanagedWriter = NULL;
    m_pCreatingAssembly = NULL;
    m_pCeeFileGen = NULL;

}



// Module initialization occurs in two phases: the constructor phase and the Initialize phase.
//
// The Initialize() phase completes the initialization after the constructor has run.
// It can throw exceptions but whether it throws or succeeds, it must leave the Module
// in a state where Destruct() can be safely called.
//
void ReflectionModule::Initialize(AllocMemTracker *pamTracker)
{
    CONTRACTL
    {
        INSTANCE_CHECK;
        THROWS;
        GC_TRIGGERS;
        INJECT_FAULT(COMPlusThrowOM());
        MODE_ANY;
    }
    CONTRACTL_END;

    Module::Initialize(pamTracker);

    IfFailThrow(CreateICeeGen(IID_ICeeGen, (void **)&m_pCeeFileGen));

    m_pInMemoryWriter = new RefClassWriter();

    IfFailThrow(m_pInMemoryWriter->Init(GetCeeGen(), GetEmitter()));

}

void ReflectionModule::Destruct()
{
    WRAPPER_CONTRACT;

    delete m_pInMemoryWriter;

    if (m_ppISymUnmanagedWriter)
    {
        Module::ReleaseIUnknown((IUnknown**)m_ppISymUnmanagedWriter);
        m_ppISymUnmanagedWriter = NULL;
    }

    if (m_pCeeFileGen)
        m_pCeeFileGen->Release();

    Module::Destruct();
}

void ReflectionModule::ReleaseILData()
{
    WRAPPER_CONTRACT;

    if (m_ppISymUnmanagedWriter)
    {
        Module::ReleaseIUnknown((IUnknown**)m_ppISymUnmanagedWriter);
        m_ppISymUnmanagedWriter = NULL;
    }

    Module::ReleaseILData();
}


#endif // !DACCESS_COMPILE

const void *ReflectionModule::GetIL(RVA il) // virtual
{
#ifndef DACCESS_COMPILE 
    WRAPPER_CONTRACT;
    BYTE* pByte = NULL;
    m_pCeeFileGen->GetMethodBuffer(il, &pByte);
    return pByte;
#else // DACCESS_COMPILE
    DacNotImpl();
    return NULL;
#endif // DACCESS_COMPILE
}

void *ReflectionModule::GetRvaField(RVA field) // virtual
{
#ifndef DACCESS_COMPILE 
    WRAPPER_CONTRACT;
    // This function should be call only if the target is a field or a field with RVA.
    BYTE* pByte = NULL;
    m_pCeeFileGen->ComputePointer(m_sdataSection, field, &pByte);
    return pByte;
#else // DACCESS_COMPILE
    DacNotImpl();
    return NULL;
#endif // DACCESS_COMPILE
}

#ifndef DACCESS_COMPILE 


VASigCookie *Module::GetVASigCookie(PCCOR_SIGNATURE pVASig)
{
    CONTRACT(VASigCookie*)
    {
        INSTANCE_CHECK;
        THROWS;
        GC_TRIGGERS;
        MODE_ANY;
        POSTCONDITION(CheckPointer(RETVAL));
        INJECT_FAULT(COMPlusThrowOM());
    }
    CONTRACT_END;

    VASigCookieBlock *pBlock;
    VASigCookie      *pCookie;

    pCookie = NULL;

    // First, see if we already enregistered this sig.
    // Note that we're outside the lock here, so be a bit careful with our logic
    for (pBlock = m_pVASigCookieBlock; pBlock != NULL; pBlock = pBlock->m_Next)
    {
        for (UINT i = 0; i < pBlock->m_numcookies; i++)
        {
            if (pVASig == pBlock->m_cookies[i].mdVASig)
            {
                pCookie = &(pBlock->m_cookies[i]);
                break;
            }
        }
    }

    if (!pCookie)
    {
        // If not, time to make a new one.

        // Compute the size of args first, outside of the lock.

        DWORD sizeOfArgs;

        SigTypeContext typeContext;

        sizeOfArgs = MetaSig::SizeOfActualFixedArgStack(this, 
                                                        pVASig,
                                                        SigParser::LengthOfSig(pVASig),
                                                        (*pVASig & IMAGE_CEE_CS_CALLCONV_HASTHIS)==0, 
                                                        &typeContext);

        // enable gc before taking lock
        {
            CrstPreempHolder ch(&m_Crst);

            // Note that we were possibly racing to create the cookie, and another thread
            // may have already created it.  We could put another check
            // here, but it's probably not worth the effort, so we'll just take an
            // occasional duplicate cookie instead.

            // Is the first block in the list full?
            if (m_pVASigCookieBlock && m_pVASigCookieBlock->m_numcookies
                < VASigCookieBlock::kVASigCookieBlockSize)
            {
                // Nope, reserve a new slot in the existing block.
                pCookie = &(m_pVASigCookieBlock->m_cookies[m_pVASigCookieBlock->m_numcookies]);
            }
            else
            {
                // Yes, create a new block.
                VASigCookieBlock *pNewBlock = new VASigCookieBlock();
                if (pNewBlock)
                {
                    pNewBlock->m_Next = m_pVASigCookieBlock;
                    pNewBlock->m_numcookies = 0;
                    m_pVASigCookieBlock = pNewBlock;
                    pCookie = &(pNewBlock->m_cookies[0]);
                }
            }

            // Now, fill in the new cookie (assuming we had enough memory to create one.)
            if (pCookie)
            {
                pCookie->mdVASig = pVASig;
                pCookie->pModule = this;
                pCookie->pNDirectMLStub = NULL;
                pCookie->sizeOfArgs = sizeOfArgs;
            }

            // Finally, now that it's safe for ansynchronous readers to see it,
            // update the count.
            m_pVASigCookieBlock->m_numcookies++;
        }
    }

    RETURN pCookie;
}


VOID VASigCookie::Destruct()
{
    WRAPPER_CONTRACT;
    if (pNDirectMLStub)
        pNDirectMLStub->DecRef();
}

// ===========================================================================
// LookupMap
// ===========================================================================

DWORD LookupMap::Find(TADDR pointer)
{
    LEAF_CONTRACT;

    LookupMap *map = this;
    DWORD index = 0;
    while (map != NULL)
    {
#ifndef DACCESS_COMPILE 
        TADDR *p = map->pTable + index;
        TADDR *pEnd = map->pTable + map->dwMaxIndex;
        while (p < pEnd)
        {
            if (*p == pointer)
                return (DWORD)(p - map->pTable);
            p++;
        }
#else // DACCESS_COMPILE
        while (index < map->dwMaxIndex)
        {
            if (map->pTable[index] == pointer)
                return index;
            index++;
        }
#endif // DACCESS_COMPILE
        index = map->dwMaxIndex;
        map = map->pNext;
    }

    return 0;
}

#endif // !DACCESS_COMPILE

#ifdef DACCESS_COMPILE 

void
LookupMap::EnumMemoryRegions(CLRDataEnumMemoryFlags flags,
                             DWORD minIndex,
                             bool enumThis)
{
    CONTRACTL
    {
        INSTANCE_CHECK;
        NOTHROW;
        GC_NOTRIGGER;
        MODE_ANY;
        FORBID_FAULT;
    }
    CONTRACTL_END;

    if (enumThis)
    {
        DacEnumHostDPtrMem(this);
    }
    if ((minIndex < dwMaxIndex) && pTable.IsValid())
    {
        DacEnumMemoryRegion(PTR_TO_TADDR(pTable),
                            (dwMaxIndex - minIndex) * sizeof(TADDR));
    }
}


/* static */
void
LookupMap::ListEnumMemoryRegions(CLRDataEnumMemoryFlags flags,
                                 LookupMap* headMap,
                                 bool enumHead)
{
    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
        MODE_ANY;
        FORBID_FAULT;
    }
    CONTRACTL_END;

    DWORD minIndex = 0;
    while (headMap)
    {
        headMap->EnumMemoryRegions(flags, minIndex, enumHead);

        if (!headMap->pNext.IsValid())
        {
            break;
        }

        minIndex = headMap->dwMaxIndex;
        headMap = headMap->pNext;
        enumHead = false;
    }
}

#endif // DACCESS_COMPILE

// -------------------------------------------------------
// Stub manager for thunks.
//
// Note, the only reason we have this stub manager is so that we can recgonize UMEntryThunks for IsTransitionStub. If it
// turns out that having a full-blown stub manager for these things causes problems else where, then we can just attach
// a range list to the thunk heap and have IsTransitionStub check that after checking with the main stub manager.
// -------------------------------------------------------

SPTR_IMPL(ThunkHeapStubManager, ThunkHeapStubManager, g_pManager);

#ifndef DACCESS_COMPILE 

/* static */
void ThunkHeapStubManager::Init()
{
    CONTRACTL
    {
        THROWS;
        GC_NOTRIGGER;
        MODE_ANY;
        INJECT_FAULT(COMPlusThrowOM());
    }
    CONTRACTL_END;

    g_pManager = new ThunkHeapStubManager();
    StubManager::AddStubManager(g_pManager);
}

#endif // !DACCESS_COMPILE

BOOL ThunkHeapStubManager::CheckIsStub_Internal(TADDR stubStartAddress)
{
    WRAPPER_CONTRACT;
    // Its a stub if its in our heaps range.
    return GetRangeList()->IsInRange((const BYTE *) stubStartAddress);
}

BOOL ThunkHeapStubManager::DoTraceStub(const BYTE *stubStartAddress,
                                       TraceDestination *trace)
{
    LEAF_CONTRACT;
    // We never trace through these stubs when stepping through managed code. The only reason we have this stub manager
    // is so that IsTransitionStub can recgonize UMEntryThunks.
    return FALSE;
}



#ifdef _MSC_VER 
#ifndef _DEBUG 
// Optimization intended for Module::IsIntrospectionOnly and Module::EnsureActive only
#pragma optimize("t", on)
#endif
#endif

BOOL Module::IsIntrospectionOnly()
{
    WRAPPER_CONTRACT;
    return GetAssembly()->IsIntrospectionOnly();
}

VOID Module::EnsureActive()
{
    WRAPPER_CONTRACT;

    GetDomainFile()->EnsureActive();
}

#ifdef _MSC_VER 
#ifndef _DEBUG 
#pragma optimize("", on)
#endif
#endif

VOID Module::EnsureAllocated()
{
    WRAPPER_CONTRACT;

    GetDomainFile()->EnsureAllocated();
}

VOID Module::EnsureLibraryLoaded()
{
    WRAPPER_CONTRACT;

    GetDomainFile()->EnsureLibraryLoaded();
}



CHECK Module::CheckActivated()
{
    WRAPPER_CONTRACT;
    DomainFile *pDomainFile = FindDomainFile(GetAppDomain());
    CHECK(pDomainFile != NULL);
#ifndef DACCESS_COMPILE 
    PREFIX_ASSUME(pDomainFile != NULL);
    CHECK(pDomainFile->CheckActivated());
#endif
    CHECK_OK;
}

#ifdef DACCESS_COMPILE 

void
ModuleCtorInfo::EnumMemoryRegions(CLRDataEnumMemoryFlags flags)
{
    // This class is contained so do not enumerate 'this'.
    DacEnumMemoryRegion(PTR_TO_TADDR(ppMT), numElements *
                        sizeof(TADDR));
    DacEnumMemoryRegion(PTR_TO_TADDR(cctorInfoHot), numElementsHot *
                        sizeof(ClassCtorInfoEntry));
    DacEnumMemoryRegion(PTR_TO_TADDR(cctorInfoCold),
                        (numElements - numElementsHot) *
                        sizeof(ClassCtorInfoEntry));
    DacEnumMemoryRegion(PTR_TO_TADDR(hotHashOffsets), numHotHashes *
                        sizeof(DWORD));
    DacEnumMemoryRegion(PTR_TO_TADDR(coldHashOffsets), numColdHashes *
                        sizeof(DWORD));
}

void Module::EnumMemoryRegions(CLRDataEnumMemoryFlags flags,
                               bool enumThis)
{
    CONTRACTL
    {
        INSTANCE_CHECK;
        NOTHROW;
        GC_NOTRIGGER;
        MODE_ANY;
        FORBID_FAULT;
    }
    CONTRACTL_END;

    if (enumThis)
    {
        DAC_ENUM_VTHIS();
        EMEM_OUT(("MEM: %p Module\n", PTR_HOST_TO_TADDR(this)));
    }

    if (m_file.IsValid())
    {
        m_file->EnumMemoryRegions(flags);
    }
    if (m_pAssembly.IsValid())
    {
        m_pAssembly->EnumMemoryRegions(flags);
    }
    if (m_pAvailableClasses.IsValid())
    {
        m_pAvailableClasses->EnumMemoryRegions(flags);
    }
    if (m_pAvailableParamTypes.IsValid())
    {
        m_pAvailableParamTypes->EnumMemoryRegions(flags);
    }
    if (m_pInstMethodHashTable.IsValid())
    {
        m_pInstMethodHashTable->EnumMemoryRegions(flags);
    }
    if (m_pAvailableClassesCaseIns.IsValid())
    {
        m_pAvailableClassesCaseIns->EnumMemoryRegions(flags);
    }
    if (m_pBinder.IsValid())
    {
        m_pBinder->EnumMemoryRegions(flags);
    }
    m_ModuleCtorInfo.EnumMemoryRegions(flags);

    // Save the LookupMap structures.
    LookupMap::ListEnumMemoryRegions(flags, &m_TypeDefToMethodTableMap, false);
    LookupMap::ListEnumMemoryRegions(flags, &m_TypeRefToMethodTableMap, false);
    LookupMap::ListEnumMemoryRegions(flags, &m_MethodDefToDescMap, false);
    LookupMap::ListEnumMemoryRegions(flags, &m_FieldDefToDescMap, false);
    LookupMap::ListEnumMemoryRegions(flags, &m_MemberRefToDescMap, false);
    LookupMap::ListEnumMemoryRegions(flags, &m_FileReferencesMap, false);
    LookupMap::ListEnumMemoryRegions(flags, &m_ManifestModuleReferencesMap, false);

    LookupMap::Iterator typeDefIter(&m_TypeDefToMethodTableMap);
    while (typeDefIter.Next())
    {
        if (typeDefIter.GetElement())
        {
            (PTR_MethodTable(typeDefIter.GetElement()))->
                EnumMemoryRegions(flags);
        }
    }

    LookupMap::Iterator typeRefIter(&m_TypeRefToMethodTableMap);
    while (typeRefIter.Next())
    {
        if (typeRefIter.GetElement())
        {
            (PTR_MethodTable(typeRefIter.GetElement()))->
                EnumMemoryRegions(flags);
        }
    }

    LookupMap::Iterator methodDefIter(&m_MethodDefToDescMap);
    while (methodDefIter.Next())
    {
        if (methodDefIter.GetElement())
        {
            (PTR_MethodDesc(methodDefIter.GetElement()))->
                EnumMemoryRegions(flags);
        }
    }

    LookupMap::Iterator fieldDefIter(&m_FieldDefToDescMap);
    while (fieldDefIter.Next())
    {
        if (fieldDefIter.GetElement())
        {
            (PTR_FieldDesc(fieldDefIter.GetElement()))->
                EnumMemoryRegions(flags);
        }
    }

    LookupMap::Iterator memberRefIter(&m_MemberRefToDescMap);
    while (memberRefIter.Next())
    {
        if (memberRefIter.GetElement())
        {
            TADDR memb = memberRefIter.GetElement();
            if (memb & IS_FIELD_MEMBER_REF)
            {
                (PTR_FieldDesc(memb & ~(TADDR)IS_FIELD_MEMBER_REF))->
                    EnumMemoryRegions(flags);
            }
            else
            {
                // Extra casts are to satisfy prefast.
                (PTR_MethodDesc((TADDR)(void*)memb))->
                    EnumMemoryRegions(flags);
            }
        }
    }

    LookupMap::Iterator fileRefIter(&m_FileReferencesMap);
    while (fileRefIter.Next())
    {
        if (fileRefIter.GetElement())
        {
            (PTR_Module(fileRefIter.GetElement()))->
                EnumMemoryRegions(flags, true);
        }
    }

    LookupMap::Iterator asmRefIter(&m_ManifestModuleReferencesMap);
    while (asmRefIter.Next())
    {
        if (asmRefIter.GetElement())
        {
            (PTR_Module(asmRefIter.GetElement())->GetAssembly())->
                EnumMemoryRegions(flags);
        }
    }

}

FieldDesc *Module::LookupFieldDef(mdFieldDef token)
{
    WRAPPER_CONTRACT;
    _ASSERTE(TypeFromToken(token) == mdtFieldDef);
    g_IBCLogger.LogRidMapAccess( MakePair( this, token ) );
    return PTR_FieldDesc(GetFromRidMap(&m_FieldDefToDescMap,
                                       RidFromToken(token)));
}

#endif // DACCESS_COMPILE


#ifndef DACCESS_COMPILE 

// Access to CerPrepInfo, the structure used to track CERs prepared at runtime (as opposed to ngen time). GetCerPrepInfo will
// return the structure associated with the given method desc if it exists or NULL otherwise. CreateCerPrepInfo will get the
// structure if it exists or allocate and return a new struct otherwise. Creation of CerPrepInfo structures is automatically
// synchronized by the CerCrst (lazily allocated as needed).
CerPrepInfo *Module::GetCerPrepInfo(MethodDesc *pMD)
{
    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
        MODE_ANY;
        PRECONDITION(CheckPointer(pMD));
    }
    CONTRACTL_END;

    if (m_pCerPrepInfo == NULL)
        return NULL;

    // Don't need a crst for read only access to the hash table.
    HashDatum sDatum;
    if (m_pCerPrepInfo->GetValue(pMD, &sDatum))
        return (CerPrepInfo*)sDatum;
    else
        return NULL;
}

CerPrepInfo *Module::CreateCerPrepInfo(MethodDesc *pMD)
{
    CONTRACTL
    {
        THROWS;
        GC_TRIGGERS;
        MODE_COOPERATIVE;
        PRECONDITION(CheckPointer(pMD));
    }
    CONTRACTL_END;

    // Lazily allocate a Crst to serialize update access to the info structure.
    // Carefully synchronize to ensure we don't leak a Crst in race conditions.
    if (m_pCerCrst == NULL)
    {
        Crst *pCrst = new Crst("ConstrainedExecutionRegionHashTable", CrstCer, CRST_UNSAFE_COOPGC);
        if (InterlockedCompareExchangePointer((void**)&m_pCerCrst, pCrst, NULL) != NULL)
            delete pCrst;
    }

    CrstHolder sCrstHolder(m_pCerCrst);

    // Lazily allocate the info structure.
    if (m_pCerPrepInfo == NULL)
    {
        LockOwner sLock = {m_pCerCrst, IsOwnerOfCrst};
        NewHolder <EEPtrHashTable> tempCerPrepInfo (new EEPtrHashTable());
        if (!tempCerPrepInfo->Init(CER_DEFAULT_HASH_SIZE, &sLock))
            COMPlusThrowOM();
        m_pCerPrepInfo = tempCerPrepInfo.Extract ();
    }
    else
    {
        // Try getting an existing value first.
        HashDatum sDatum;
        if (m_pCerPrepInfo->GetValue(pMD, &sDatum))
            return (CerPrepInfo*)sDatum;
    }

    // We get here if there was no info structure or no existing method desc entry. Either way we now have an info structure and
    // need to create a new method desc entry.
    NewHolder<CerPrepInfo> pInfo(new CerPrepInfo());
    m_pCerPrepInfo->InsertValue(pMD, (HashDatum)pInfo);

    return pInfo.Extract();
}


BOOL Module::GetRVAOverrideForMethod(MethodDesc* pMD, DWORD* pdwOverride)
{
    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
        MODE_ANY;
    }
    CONTRACTL_END

    if (!m_pRVAOverrides)
        return FALSE;

    // Don't need a crst for read only access to the hash table.
    HashDatum sDatum;
    if (!m_pRVAOverrides->GetValue(pMD, &sDatum))
        return FALSE;
    
    *pdwOverride = (DWORD)(SIZE_T)sDatum;
    return TRUE;
}

void  Module::SetRVAOverrideForMethod(MethodDesc* pMD, DWORD dwOverride)
{
    CONTRACTL
    {
        THROWS;
        GC_NOTRIGGER;
        MODE_ANY;
    }
    CONTRACTL_END

    // Lazily allocate a Crst to serialize update access to the info structure.
    // Carefully synchronize to ensure we don't leak a Crst in race conditions.
    if (m_pRVAOverridesCrst == NULL)
    {
        Crst *pCrst = new Crst("RVAOverridesHashTable", CrstRVAOverrides, CrstFlags(CRST_UNSAFE_ANYMODE | CRST_DEBUGGER_THREAD));
        if (InterlockedCompareExchangePointer((void**)&m_pRVAOverridesCrst, pCrst, NULL) != NULL)
            delete pCrst;
    }

    CrstHolder sCrstHolder(m_pRVAOverridesCrst);

    // Lazily allocate the info structure.
    if (m_pRVAOverrides == NULL)
    {
        LockOwner sLock = {m_pRVAOverridesCrst, IsOwnerOfCrst};
        NewHolder <EEPtrHashTable> tempRVAOverrides(new EEPtrHashTable());
        if (!tempRVAOverrides->Init(59, &sLock))
            COMPlusThrowOM();
        MemoryBarrier();
        m_pRVAOverrides = tempRVAOverrides.Extract ();
    }
    else
    {
        if (m_pRVAOverrides->ReplaceValue(pMD, (HashDatum)(SIZE_T)dwOverride))
            return;
    }

    m_pRVAOverrides->InsertValue(pMD, (HashDatum)(SIZE_T)dwOverride);
}

#endif // !DACCESS_COMPILE



//-------------------------------------------------------------------------------
// Make best-case effort to obtain an image name for use in an error message.
//
// This routine must expect to be called before the this object is fully loaded.
// It can return an empty if the name isn't available or the object isn't initialized
// enough to get a name, but it mustn't crash.
//-------------------------------------------------------------------------------
void Module::GetPathForErrorMessages(SString & result)
{
    CONTRACTL
    {
        THROWS;
        GC_TRIGGERS;
        if (FORBIDGC_LOADER_USE_ENABLED()) FORBID_FAULT; else { INJECT_FAULT(COMPlusThrowOM()); }
    }
    CONTRACTL_END

    PEFile *pFile = GetFile();
    if (pFile)
    {
        pFile->GetPathForErrorMessages(result);
    }
    else
    {
        result = L"";
    }
}

//-------------------------------------------------------------------------------

// Verify consistency of asmconstants.h

// Wrap all C_ASSERT's in asmconstants.h with a class definition.  Many of the
// fields referenced below are private, and this class is a friend of the
// enclosing type.  (A C_ASSERT isn't a compiler intrinsic, just a magic
// typedef that produces a compiler error when the condition is false.)

class CheckAsmOffsets
{
#define ASMCONSTANTS_C_ASSERT(cond) \
        typedef char UNIQUE_LABEL(__C_ASSERT__)[(cond) ? 1 : -1];
#include "asmconstants.h"
};

//-------------------------------------------------------------------------------

About Koders | Resources | Downloads | Support | Black Duck | Submit Project | Terms of Service | DMCA | Privacy Policy | Site Map| Contact Us