A
download codeman.cpp
Language: C++
Copyright: (c) 2006 Microsoft Corporation. All rights reserved.
LOC: 2441
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
// ==++==
//
//   
//    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.
//   
//
// ==--==
// codeman.cpp - a managment class for handling multiple code managers
//
#include "common.h"
#include "jitinterface.h"
#include "corjit.h"
#include "eetwain.h"
#include "eeconfig.h"
#include "excep.h"
#include "appdomain.hpp"
#include "codeman.h"
#include "codeman.inl"
#include "nibblemapmacros.h"
#include "generics.h"
#include "dynamicmethod.h"
#include "eemessagebox.h"


#include "fjit_eetwain.h"
#include "jitperf.h"
#include "shimload.h"
#include "memoryreport.h"
#include "debuginfostore.h"


#define MAX_M_ALLOCATED         (16 * 1024)

SPTR_IMPL(RangeSection, ExecutionManager, m_CodeRangeList);
SPTR_IMPL(RangeSection, ExecutionManager, m_DataRangeList);
SPTR_IMPL(IJitManager,  ExecutionManager, m_pJitList);
#ifndef FJITONLY
SPTR_IMPL(EECodeManager, ExecutionManager, m_pDefaultCodeMan);
#endif

#ifdef DACCESS_COMPILE
SVAL_IMPL(LONG, ExecutionManager, m_dwReaderCount);
SVAL_IMPL(LONG, ExecutionManager, m_dwWriterLock);
#endif

#ifndef DACCESS_COMPILE

CrstStatic ExecutionManager::m_ExecutionManagerCrst;
CrstStatic ExecutionManager::m_JumpStubCrst;
CrstStatic ExecutionManager::m_RangeCrst;
BYTE ExecutionManager::m_fFailedToLoad = 0x00;
volatile LONG ExecutionManager::m_dwReaderCount = 0;
volatile LONG ExecutionManager::m_dwWriterLock = 0;
JumpStubBlockHeader *  ExecutionManager::m_jumpStubBlock;
ExecutionManager::JumpStubTable*    ExecutionManager::m_jumpStubTable;


/*-----------------------------------------------------------------------------
 This is a listing of which methods uses which synchronization mechanism
 in the EEJitManager.
//-----------------------------------------------------------------------------

Setters of EEJitManager::m_CodeHeapCritSec
-----------------------------------------------
allocCode
allocEntryChunk
allocGCInfo
allocEHInfo
allocJumpStubBlock
ResolveEHClause
RemoveJitData
Unload
ReleaseReferenceToHeap
JitCodeToMethodInfo


Need EEJitManager::m_CodeHeapCritSec to be set
-----------------------------------------------
NewCodeHeap
allocCodeRaw
GetCodeHeapList
GetCodeHeap
RemoveCodeHeapFromDomainList
DeleteCodeHeap
AddRangeToJitHeapCache
DeleteJitHeapCache


HeapList::changeStart/changeEnd
-----------------------------------------------
allocCode
allocEntryChunk
allocJumpStubBlock
RemoveJitData
JitCodeToMethodInfo (read-only)

*/

void EEJitManager::IncrementReader(EEJitManager *pMgr)
{
    CONTRACTL {
        NOTHROW;
        GC_NOTRIGGER;
        SO_TOLERANT;
    } CONTRACTL_END;

    _ASSERTE(pMgr != NULL);
    CounterHolder h(&pMgr->m_dwReaderCount);
    while (pMgr->m_dwWriterLock)
        __SwitchToThread(0);
    h.SuppressRelease();
}

void EEJitManager::DecrementReader(EEJitManager *pMgr)
{
    LEAF_CONTRACT;

    FastInterlockDecrement(&pMgr->m_dwReaderCount);
}

void EEJitManager::TakeWriter(EEJitManager *pMgr)
{
    CONTRACTL {
        NOTHROW;
        GC_NOTRIGGER;
        SO_TOLERANT;
    } CONTRACTL_END;

    _ASSERTE(pMgr != NULL);
    _ASSERTE(pMgr->m_dwWriterLock == 0);

    // Signal to a debugger or hijacking profiler that it's not safe to do a stackwalk now
    IncCantStopCount(StateHolderParamValue);
    
    while (TRUE)
    {
        Thread::IncForbidSuspendThread(StateHolderParamValue);
        FastInterlockIncrement(&pMgr->m_dwWriterLock);
        if (pMgr->m_dwReaderCount == 0)
            break;
        FastInterlockDecrement(&pMgr->m_dwWriterLock);
        Thread::DecForbidSuspendThread(StateHolderParamValue);
        __SwitchToThread(0);
    }
}

void EEJitManager::ReleaseWriter(EEJitManager *pMgr)
{
    LEAF_CONTRACT;

    FastInterlockDecrement(&pMgr->m_dwWriterLock);
    
    // Signal to a debugger or hijacking profiler that it's again safe to do a stackwalk now    
    Thread::DecForbidSuspendThread(StateHolderParamValue);
    DecCantStopCount(StateHolderParamValue);
}

/*-----------------------------------------------------------------------------
 This is a listing of which methods uses which synchronization mechanism
 in the EEJitManager
//-----------------------------------------------------------------------------

==============================================================================
ExecutionManger::ReaderLockHolder and ExecutionManger::WriterLockHolder
Protects the callers of ExecutionManager::GetRangeSection from heap deletions
while walking RangeSections.  You need to take a reader lock before reading the
values: m_CodeRangeList or m_DataRangeList and hold it while walking the lists
The two xxxWrapper functions allows us to avoid taking a ReaderLock in some cases

Uses ReaderLockHolder (allows multiple reeaders with no writers)
-----------------------------------------
ExecutionManager::FindJitManNonZeroWrapper
ExecutionManager::GetMethodHeaderForAddressWrapper
ExecutionManager::GetRangeSectionForAddress
ExecutionManager::FindZapModule
ExecutionManager::FindZapModuleForNativeCode
ExecutionManager::AddRangeHelper
ExecutionManager::EnumMemoryRegions

Uses WriterLockHolder (allows single writer and no readers)
-----------------------------------------
ExecutionManager::DeleteRangeHelper


==============================================================================
EEJitManger::ReaderLockHolder and EEJitManager::WriterLockHolder
Protects the callers of EEJitManager::JitCodeToMethodInfo from heap deletions
while walking HeapLists.  You need to take a reader lock before reading the
value of pCodeHeap (using GetVolatile_pCodeHeap() and hold it while walking
the HeapList usinging GetVolatile_hpNext

Uses ReaderLockHolder (allows multiple reeaders with no writers)
-----------------------------------------
EEJitManager::JitCodeToMethodDescWrapper

Uses WriterLockHolder (allows single writer and no readers)
-----------------------------------------
EEJitManager::DeleteCodeHeap

ExecutionManager::m_ExecutionManagerCrst
-----------------------------------------
GetJitForType

*/

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

/* static */
void ExecutionManager::IncrementReader(ExecutionManager *)
{
    CONTRACTL {
        NOTHROW;
        GC_NOTRIGGER;
        SO_TOLERANT;
    } CONTRACTL_END;

    FastInterlockIncrement(&m_dwReaderCount);
    while (m_dwWriterLock)
        __SwitchToThread(0);
    IncCantAllocCount();    
}

/* static */
void ExecutionManager::DecrementReader(ExecutionManager *)
{
    LEAF_CONTRACT;

    DecCantAllocCount();
    FastInterlockDecrement(&m_dwReaderCount);    
}

/* static */
void ExecutionManager::TakeWriter(ExecutionManager *)
{
    CONTRACTL {
        NOTHROW;
        GC_NOTRIGGER;
    } CONTRACTL_END;

    _ASSERTE(m_dwWriterLock == 0);
    while (TRUE)
    {
        FastInterlockIncrement(&m_dwWriterLock);
        if (m_dwReaderCount == 0)
            break;
        FastInterlockDecrement(&m_dwWriterLock);
        __SwitchToThread(0);
    }
    IncCantAllocCount();    
}

/* static */
void ExecutionManager::ReleaseWriter(ExecutionManager *)
{
    LEAF_CONTRACT;
    
    DecCantAllocCount();
    FastInterlockDecrement(&m_dwWriterLock);
}


//**********************************************************************************
//  IJitManager
//**********************************************************************************
IJitManager::IJitManager()
{
    LEAF_CONTRACT;

    m_IsDefaultCodeMan = FALSE;
    m_runtimeSupport   = NULL;
    m_JITCompiler      = NULL;
}

IJitManager::~IJitManager()
{
    CONTRACTL {
        NOTHROW;
        GC_TRIGGERS;
    } CONTRACTL_END;

   // Unload the JIT DLL
   if ((m_runtimeSupport) && (!m_IsDefaultCodeMan))
        delete m_runtimeSupport;

   m_runtimeSupport = NULL;

   if (m_JITCompiler) {
        if(!g_fProcessDetach || !RunningOnWin95())
        {
            CLRFreeLibrary(m_JITCompiler);
        }
    }
    // Null all pointers to make sure checks fail!
    m_JITCompiler = NULL;
}

void  SetCpuInfo()
{
    //
    // NOTE: This function needs to be kept in sync with Zapper::CompileAssembly()
    //

#ifdef _X86_

    // NOTE: if you're adding any flags here, you probably should also be doing it
    // for ngen (zapper.cpp)
    CORINFO_CPU cpuInfo;
    GetSpecificCpuInfo(&cpuInfo);

    switch (CPU_X86_FAMILY(cpuInfo.dwCPUType))
    {
    case CPU_X86_PENTIUM:
        g_pConfig->SetCpuFlag(CORJIT_FLG_TARGET_PENTIUM);
        break;
    case CPU_X86_PENTIUM_PRO:
        // check for the mobile class
        if(CPU_X86_MODEL(cpuInfo.dwCPUType) == CPU_X86_MODEL_PENTIUM_PRO_BANIAS)
            g_pConfig->SetCpuFlag(CORJIT_FLG_TARGET_BANIAS);
        else
            g_pConfig->SetCpuFlag(CORJIT_FLG_TARGET_PPRO);
        break;
    case CPU_X86_PENTIUM_4:
        g_pConfig->SetCpuFlag(CORJIT_FLG_TARGET_P4);
        break;
    default:
        g_pConfig->SetCpuFlag(0);
        break;
    }

    if (CPU_X86_USE_CMOV(cpuInfo.dwFeatures))
    {
        g_pConfig->SetCpuCapabilities(g_pConfig->GetCpuCapabilities() |
                                      CORJIT_FLG_USE_CMOV |
                                      CORJIT_FLG_USE_FCOMI);
    }

#ifdef PLATFORM_UNIX
#else
    if (CPU_X86_USE_SSE2(cpuInfo.dwFeatures))
    {
        g_pConfig->SetCpuCapabilities(g_pConfig->GetCpuCapabilities() |
                                      CORJIT_FLG_USE_SSE2);
    }
#endif
    
#endif // _X86_
}

BOOL IJitManager::LoadJIT(LPCWSTR szJITdll)
{
    Thread  *thread = GetThread();
    BOOL     toggleGC = (thread && thread->PreemptiveGCDisabled());
    BOOL     res = TRUE;

    CONTRACTL {
        NOTHROW;
        if (toggleGC) GC_TRIGGERS; else GC_NOTRIGGER;
    } CONTRACTL_END;

    if (toggleGC)
        thread->EnablePreemptiveGC();

    m_JITCompiler = CLRLoadSystemLibrary(szJITdll);

    if (!m_JITCompiler)
    {
        res = FALSE;
        goto leav;
    }

    {
        typedef ICorJitCompiler* (__stdcall* pGetJitFn)();
        pGetJitFn getJitFn = (pGetJitFn) GetProcAddress(m_JITCompiler, "getJit");

        SetCpuInfo();

        EX_TRY
        {
            if (getJitFn)
                m_jit = (*getJitFn)();
        }
        EX_CATCH
        {
        }
        EX_END_CATCH(SwallowAllExceptions)

        if (!m_jit)
        {
            res = FALSE;
            goto leav;
        }
    }

leav:
    if (toggleGC)
        thread->DisablePreemptiveGC();

    return res;
}


#endif // #ifndef DACCESS_COMPILE

// When we unload an appdomain, we need to make sure that any threads that are crawling through
// our heap or rangelist are out. For cooperative-mode threads, we know that they will have
// been stopped when we suspend the EE so they won't be touching an element that is about to be deleted.
// However for pre-emptive mode threads, they could be stalled right on top of the element we want
// to delete, so we need to apply the reader lock to them and wait for them to drain.
IJitManager::ScanFlag IJitManager::GetScanFlags()
{
    CONTRACTL {
        NOTHROW;
        GC_NOTRIGGER;
        SO_TOLERANT;
    } CONTRACTL_END;

#ifndef DACCESS_COMPILE
    Thread *pThread = GetThread();

    if (!pThread)
        return ScanNoReaderLock;

    // If this thread is hijacked by a profiler and crawling its own stack,
    // we do need to take the lock
    if (pThread->GetProfilerFilterContext() != NULL)
        return ScanReaderLock;
    
    if (pThread->PreemptiveGCDisabled() || pThread == GCHeap::GetGCHeap()->GetGCThread())
        return ScanNoReaderLock;

    return ScanReaderLock;
#else
    return ScanNoReaderLock;
#endif
}

#ifdef DACCESS_COMPILE

void IJitManager::EnumMemoryRegions(CLRDataEnumMemoryFlags flags)
{
    DAC_ENUM_VTHIS();
    if (m_runtimeSupport.IsValid())
    {
        m_runtimeSupport->EnumMemoryRegions(flags);
    }
}

#endif // #ifdef DACCESS_COMPILE


#ifndef DACCESS_COMPILE

//**********************************************************************************
//  EEJitManager
//**********************************************************************************

EEJitManager::EEJitManager()
{
    CONTRACTL {
        THROWS;
        GC_NOTRIGGER;
        SO_TOLERANT;
    } CONTRACTL_END;

    m_next = NULL;
    m_pCodeHeap = NULL;
    m_jit = NULL;
    m_dwReaderCount = 0;
    m_dwWriterLock = 0;

    for (unsigned int i=0; i<HASH_BUCKETS; i++)
        m_JitCodeHashTable[i] = NULL;
    m_pJitHeapCacheUnlinkedList = NULL;

    // There is a situation that we have seen in the debugger (currently only on IA64) where we are doing
    // a right-side requested stackwalk of the threads and there is a thread that isn't in coop mode so
    // doesn't get suspended, when we get around to doing the stackwalk it is Jitting and we run into 
    // conflicts trying to read the nibble map using EEJitManager::JitCodeToMethodInfo which tries to
    // take this lock if it can't get a clean copy of the nibble map on its first time through.
    //
    // As a workaround we're adding the CRST_DEBUGGER_THREAD attribute to this Crst's init.
    m_CodeHeapCritSec.Init("JitMetaHeapCrst", 
                        CrstSingleUseLock, 
                        (CrstFlags)(CRST_UNSAFE_ANYMODE|CRST_DEBUGGER_THREAD));


}

HeapList* LoaderCodeHeap::CreateCodeHeap(CodeHeapRequestInfo *pInfo, LoaderHeap *pJitMetaHeap)
{
    CONTRACT(HeapList *) {
        THROWS;
        GC_NOTRIGGER;
        POSTCONDITION(CheckPointer(RETVAL));
    } CONTRACT_END;

    size_t * pPrivatePCLBytes   = NULL;
    size_t   reserveSize        = pInfo->getReserveSize();
#ifdef _DEBUG
    size_t   initialRequestSize = pInfo->getRequestSize();
#endif
    size_t   cacheSize          = pInfo->getCacheSize();
    const BYTE *   loAddr       = pInfo->m_loAddr;
    const BYTE *   hiAddr       = pInfo->m_hiAddr;

    // Make sure that what we are reserving will fix inside a DWORD
    if (reserveSize != (DWORD) reserveSize)
    {
        _ASSERTE(!"reserveSize does not fit in a DWORD");
        EEPOLICY_HANDLE_FATAL_ERROR(COR_E_EXECUTIONENGINE);
    }

#ifdef PROFILING_SUPPORTED
    pPrivatePCLBytes   = &(GetPrivatePerfCounters().m_Loading.cbLoaderHeapSize);
#endif

    LOG((LF_JIT, LL_INFO100,
         "Request new LoaderCodeHeap::CreateCodeHeap(%08x, %08x, for domain" FMT_ADDR "in" FMT_ADDR ".." FMT_ADDR ")\n",
         (DWORD) reserveSize, (DWORD) initialRequestSize, DBG_ADDR(pInfo->m_pDomain), DBG_ADDR(loAddr), DBG_ADDR(hiAddr)
                                ));

    NewHolder<ExplicitControlLoaderHeap> pHeap(
                    new ExplicitControlLoaderHeap((DWORD) reserveSize,
                                                  (DWORD) PAGE_SIZE,
                                                  pPrivatePCLBytes,
                                                  0,                          // RangeList *pRangeList
                                                  TRUE,                       // BOOL fMakeExecutable
                                                  loAddr,
                                                  hiAddr));

    // this first allocation is critical as it sets up correctly the loader heap info
    HeapList *pHp = (HeapList*)pHeap->AllocMem(sizeof(HeapList));

    NewHolder<LoaderCodeHeap> pCodeHeap(new LoaderCodeHeap(pHeap));
    pHeap.SuppressRelease();
    pHp->pHeap = pCodeHeap;

    pHp->pCacheSpacePtr  = (PBYTE)pHeap->AllocMem(cacheSize);
    pHp->bCacheSpaceSize = (pHp->pCacheSpacePtr == NULL) ? 0 : cacheSize;

    size_t heapSize = pHeap->GetReservedBytesFree();
    size_t nibbleMapSize = HEAP2MAPSIZE(ROUND_UP_TO_PAGE(heapSize));

    pHp->startAddress    = (TADDR)pHp + sizeof(HeapList);

    pHp->startAddress   += pHp->bCacheSpaceSize;

    pHp->endAddress      = pHp->startAddress;
    pHp->maxCodeHeapSize = heapSize;

    _ASSERTE(heapSize >= initialRequestSize);

    // We do not need to memset this memory, since ClrVirtualAlloc() guarantees that the memory is zero.
    // Furthermore, if we avoid writing to it, these pages don't come into our working set

    pHp->changeStart     = NULL;
    pHp->changeEnd       = NULL;
    pHp->bFull           = FALSE;
    pHp->cBlocks         = 0;

    pHp->mapBase         = ROUND_DOWN_TO_PAGE(pHp->startAddress);  // round down to next lower page align
    pHp->pHdrMap         = (DWORD*)(void*)pJitMetaHeap->AllocMem(nibbleMapSize);

    LOG((LF_JIT, LL_INFO100,
         "Created new CodeHeap(" FMT_ADDR ".." FMT_ADDR ")\n",
         DBG_ADDR(pHp->startAddress), DBG_ADDR(pHp->startAddress+pHp->maxCodeHeapSize)
         ));


    pCodeHeap.SuppressRelease();
    RETURN pHp;
}

void CodeHeapRequestInfo::Init()
{ 
    CONTRACTL {
        NOTHROW;
        GC_NOTRIGGER;
        PRECONDITION((m_hiAddr == 0) ||
                     ((m_loAddr < m_hiAddr) &&
                      ((m_loAddr + m_requestSize) < m_hiAddr)));
    } CONTRACTL_END;

    if (m_pDomain == NULL)
        m_pDomain = m_pMD->GetDomain();
    m_isDynamicDomain = m_pMD->IsLCGMethod();
}

HeapList* EEJitManager::NewCodeHeap(CodeHeapRequestInfo *pInfo, DomainCodeHeapList *pADHeapList)
{
    CONTRACT(HeapList *) {
        THROWS;
        GC_NOTRIGGER;
        PRECONDITION(m_CodeHeapCritSec.OwnedByCurrentThread());
        POSTCONDITION(CheckPointer(RETVAL));
    } CONTRACT_END;

    MEMORY_REPORT_CONTEXT_SCOPE("CodeHeap");

    size_t initialRequestSize = pInfo->getRequestSize();
    size_t reserveSize;
    size_t cacheSize = 0;
    size_t minReserveSize = VIRTUAL_ALLOC_RESERVE_GRANULARITY; //     ( 64 KB)           


    // SETUP_NEW_BLOCK reserves the first sizeof(LoaderHeapBlock) bytes for LoaderHeapBlock.
    // In other word, the first m_pAllocPtr starts at sizeof(LoaderHeapBlock) bytes 
    // after the allocated memory. Therefore, we need to take it into account.
    size_t requestAndHeadersSize = sizeof(LoaderHeapBlock) + sizeof(HeapList) + initialRequestSize;

    // This loop will typically execute only once, it will execute twice when 
    // we have an initialRequestSize that is close to a V_A_R_GRANULARITY
    do {
        reserveSize = requestAndHeadersSize + cacheSize;
        if (reserveSize < minReserveSize)
            reserveSize = minReserveSize;
        reserveSize = ALIGN_UP(reserveSize, VIRTUAL_ALLOC_RESERVE_GRANULARITY);

        cacheSize = GetCodeHeapCacheSize(reserveSize);

    } while (reserveSize - cacheSize < requestAndHeadersSize);

    pInfo->setReserveSize(reserveSize);
    pInfo->setCacheSize(cacheSize);

    HeapList *pHp = NULL;

    if (pInfo->IsDynamicDomain())
    {
        //
        // Initialize m_loAddr and m_hiAddr appropriately to the 
        // memory range that should be used for executable code
        //
        if ((pInfo->m_loAddr == 0) && (pInfo->m_hiAddr == 0))
        {
            InitArgsForAllocInExecutableRange(pInfo->m_loAddr,
                                              pInfo->m_hiAddr);
        }
        
        pHp = HostCodeHeap::CreateCodeHeap(pInfo, this);
    }
    else
    {
        LoaderHeap *pJitMetaHeap = pADHeapList->m_pDomain->GetLowFrequencyHeap();
        pHp = LoaderCodeHeap::CreateCodeHeap(pInfo, pJitMetaHeap);
    }

    _ASSERTE (pHp != NULL);
    _ASSERTE (pHp->maxCodeHeapSize >= initialRequestSize);

    pHp->SetVolatile_hpNext(GetVolatile_pCodeHeap());

    EX_TRY
    {        
        ExecutionManager::AddCodeRange((TADDR) pHp, (TADDR)&((BYTE*)pHp->startAddress)[pHp->maxCodeHeapSize],this, NULL);
    }
    EX_CATCH
    {
        // If we failed to alloc memory in ExecutionManager::AddCodeRange()
        // then we will delete the LoaderHeap that we allocated

        // pHp is allocated in pHeap, so only need to delete the LoaderHeap itself
        delete pHp->pHeap;

        pHp = NULL;
    }
    EX_END_CATCH(SwallowAllExceptions)

    if (pHp == NULL)
    {
        ThrowOutOfMemory();
    }

    // Since the virtualalloc'ed memory is MEM_RESERVED in the LoaderHeap at a page boundary the
    // following assertion shold be true. If you added some structs between the start of the LoaderHeap and the startAddress
    // then update this ASSERTEand the following if condition appropriately.
    _ASSERTE(((size_t)(pHp->startAddress -  (pHp->pHeap->GetReservedPrivateData() + pHp->bCacheSpaceSize)) & PAGE_MASK) == 0);

    // Insure that the LoaderHeap's start address is 64 KB aligned.
    // The MDTOKEN_CACHE only works if this is true.
    _ASSERTE(pHp->pHeap->GetHeapStartAddress() != NULL);
    _ASSERTE(((size_t)pHp->pHeap->GetHeapStartAddress() & CACHE_BLOCK_MASK) == 0);

    AddRangeToJitHeapCache (pHp->startAddress, pHp->startAddress+pHp->maxCodeHeapSize, pHp);

    SetVolatile_pCodeHeap(pHp);

#ifdef _DEBUG
    DebugCheckJitHeapCacheValidity ();
#endif // _DEBUG

    HeapList **ppHeapList = pADHeapList->m_CodeHeapList.AppendThrowing();
    *ppHeapList = pHp;

    RETURN(pHp);
}

void* EEJitManager::allocCodeRaw(CodeHeapRequestInfo *pInfo,
                                 size_t blockSize, unsigned align, 
                                 HeapList ** ppCodeHeap /* Writeback, Can be null */ )
{
    CONTRACT(void *) {
        THROWS;
        GC_NOTRIGGER;
        PRECONDITION(m_CodeHeapCritSec.OwnedByCurrentThread());
        POSTCONDITION(CheckPointer(RETVAL));
    } CONTRACT_END;

    // Initialize the writeback value to NULL if a non-NULL pointer was provided
    if (ppCodeHeap)
        *ppCodeHeap = NULL;

    void *      mem       = NULL;
    HeapList *  pCodeHeap = GetCodeHeap(pInfo);

    if (pCodeHeap != NULL)
    {
        mem = (pCodeHeap->pHeap)->AllocMemory_NoThrow(blockSize, align);
    }

    if (mem == NULL)
    {
        // The current heap couldn't handle our request.
        if (pCodeHeap != NULL)
        {
            pCodeHeap->SetHeapFull();  // Mark it as full
        }

        // Let us create a new heap.

        DomainCodeHeapList *pList = GetCodeHeapList(pInfo->m_pMD, pInfo->m_pDomain);
        _ASSERTE(pList);

        pInfo->setRequestSize(blockSize+align);
        pCodeHeap = NewCodeHeap(pInfo, pList);
        _ASSERTE(pCodeHeap);

        mem = (void *)(pCodeHeap->pHeap)->AllocMemory(blockSize, align);
        _ASSERTE(mem);
    }

    // Record the pCodeHeap value into ppCodeHeap, if a non-NULL pointer was provided
    if (ppCodeHeap)
        *ppCodeHeap = pCodeHeap;

    _ASSERTE((TADDR)mem >= pCodeHeap->startAddress);

    if (((TADDR) mem)+blockSize > (TADDR)pCodeHeap->endAddress)
    {
        // Update the CodeHeap endAddress
        pCodeHeap->endAddress = (TADDR)mem+blockSize;
    }

    RETURN(mem);
}

CodeHeader* EEJitManager::allocCode(MethodDesc* pMD, size_t blockSize, CorJitAllocMemFlag flag)
{
    CONTRACT(CodeHeader *) {
        THROWS;
        GC_NOTRIGGER;
        POSTCONDITION(CheckPointer(RETVAL));
    } CONTRACT_END;

    unsigned alignment = CODE_SIZE_ALIGN;
    unsigned alignmentFudge = sizeof(CodeHeader) % alignment;
    
    if ((flag & CORJIT_ALLOCMEM_FLG_16BYTE_ALIGN) != 0) alignment = max(alignment, 16);
    
     // when not optimizing for code size, 8-byte align the method entry point, so that the JIT
     // can in turn 8-byte align the loop entry headers.
    if (g_pConfig->GenOptimizeType() != OPT_SIZE) alignment = max(alignment, 8);

    // CodeHeader immediately proceeds the code, so it must be aligned for the 
    // code to be aligned properly.
    _ASSERTE(IS_ALIGNED(sizeof(CodeHeader) + alignmentFudge, alignment));

    CodeHeader * pCodeHdr = NULL;

    // Immediately before the native code we place a CodeHeader struct
    blockSize += sizeof(CodeHeader) + alignmentFudge;   // 8 is needed for 16 byte code alignment on win64

    // Ensure minimal size
    if (blockSize < BYTES_PER_BUCKET)
        blockSize = BYTES_PER_BUCKET;

    CodeHeapRequestInfo requestInfo(pMD);

    // Scope the lock
    {
        // This crst has the CRST_DEBUGGER_THREAD flag, which prevents
        // debuggers from halting this thread after if has incremented changeStart,
        // but before it has incremented changeEnd; otherwise it would loop forever
        // when it does a stack walk and tries to access the nibble map.
        // Hijacking profilers have a similar problem, which is fixed by the forbid
        // suspend thread holder below.  Profilers will refuse a stackwalk in
        // a forbid suspend thread region.
        CrstHolder ch(&m_CodeHeapCritSec);

        HeapList *pCodeHeap = NULL;

#ifdef USE_INDIRECT_CODEHEADER
        // if this is a LCG method then we will be allocating the RealCodeHeader
        // alongside the code (immediately preceeding the CodeHeader) so that the
        // code block can be removed easily by the LCG code heap.
        if (pMD->IsLCGMethod())
        {
            blockSize -= alignmentFudge;
            blockSize += sizeof(RealCodeHeader);
            alignmentFudge = (sizeof(RealCodeHeader)+sizeof(CodeHeader)) % alignment;
            blockSize += alignmentFudge;
        }
#endif  // USE_INDIRECT_CODEHEADER

        size_t mem = (size_t) allocCodeRaw(&requestInfo, blockSize, alignment, &pCodeHeap);

        _ASSERTE(pCodeHeap);

        // bump us up to get proper alignment
        mem += alignmentFudge;

        TADDR pCode;

        if (pMD->IsLCGMethod())
        {
#ifdef USE_INDIRECT_CODEHEADER
            mem += sizeof(RealCodeHeader);
#endif  // USE_INDIRECT_CODEHEADER

            pCode = mem + sizeof(CodeHeader);

            ((DynamicMethodDesc*)pMD)->GetLCGMethodResolver()->m_recordCodePointer = (void*) pCode;
        }
        else
        {
            pCode = mem + sizeof(CodeHeader);
        }

        _ASSERTE(IS_ALIGNED(pCode, alignment));

        JIT_PERF_UPDATE_X86_CODE_SIZE(blockSize);

        BEGIN_HOST_NOCALL_CODE;
        {
            // Prevents a thread suspension AND prevents a hijacking profiler from doing
            // a stackwalk.
            ForbidSuspendThreadHolder suspend;

            CantAllocHolder caHolder;
        

            pCodeHeap->changeStart++;   // mark that we are about to make changes

            _ASSERTE(pCode >= pCodeHeap->mapBase);

            size_t delta = pCode - pCodeHeap->mapBase;
            NibbleMapSet(pCodeHeap->pHdrMap, delta);

            pCodeHeap->cBlocks++;
            pCodeHeap->changeEnd++;

        }
        END_HOST_NOCALL_CODE;

        pCodeHdr = (CodeHeader *)(mem);    

#ifdef USE_INDIRECT_CODEHEADER
        if (pMD->IsLCGMethod())
        {
            pCodeHdr->SetRealCodeHeader((BYTE*)pCodeHdr - sizeof(RealCodeHeader));
        }
        else
        {
            //
            size_t cbExtra;
            BYTE* pRealHeader = (BYTE*)(void*)pMD->GetDomain()->GetLowFrequencyHeap()->AllocAlignedMem(sizeof(RealCodeHeader), sizeof(void*), &cbExtra);
            pCodeHdr->SetRealCodeHeader(pRealHeader);
        }
#endif
    }

    pCodeHdr->SetDebugInfo(NULL);
    pCodeHdr->SetEHInfo(NULL);
    pCodeHdr->SetGCInfo(NULL);
    pCodeHdr->SetMethodDesc(pMD);

    RETURN(pCodeHdr);
}

#endif // #ifndef DACCESS_COMPILE


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

#ifndef DACCESS_COMPILE
EEJitManager::DomainCodeHeapList *EEJitManager::GetCodeHeapList(MethodDesc *pMD, BaseDomain *pDomain)
{
    CONTRACTL {
        NOTHROW;
        GC_NOTRIGGER;
        PRECONDITION(m_CodeHeapCritSec.OwnedByCurrentThread());
    } CONTRACTL_END;

    DomainCodeHeapList *pList = NULL;
    DomainCodeHeapList **ppList = NULL;
    int count = 0;

    // get the appropriate list of heaps
    if (pMD == NULL || pMD->IsLCGMethod())
    {
        ppList = m_DynamicDomainCodeHeaps.Table();
        count = m_DynamicDomainCodeHeaps.Count();
    }
    else
    {
        ppList = m_DomainCodeHeaps.Table();
        count = m_DomainCodeHeaps.Count();
    }

    // look for a DomainCodeHeapList
    for (int i=0; i < count; i++)
    {
        if (ppList[i]->m_pDomain == pDomain ||
            ! ppList[i]->m_pDomain->CanUnload() && ! pDomain->CanUnload())
        {
            pList = ppList[i];
        }
    }
    return pList;
}

HeapList* EEJitManager::GetCodeHeap(CodeHeapRequestInfo *pInfo)
{
    CONTRACT(HeapList *) {
        THROWS;
        GC_NOTRIGGER;
        PRECONDITION(m_CodeHeapCritSec.OwnedByCurrentThread());
    } CONTRACT_END;

    HeapList *pResult = NULL;

    _ASSERTE(pInfo->m_pDomain != NULL);

    // loop through the m_DomainCodeHeaps to find the AppDomain
    // if not found, then create it
    DomainCodeHeapList *pList = GetCodeHeapList(pInfo->m_pMD, pInfo->m_pDomain);
    if (pList)
    {
        _ASSERTE(pList->m_CodeHeapList.Count() > 0);

        // Set pResult to the largest non-full HeapList
        // that also satisfies the [loAddr..hiAddr] constraint
        for (int i=0; i < pList->m_CodeHeapList.Count(); i++)
        {
            HeapList *pCandidate = NULL;
            HeapList *pCurrent   = pList->m_CodeHeapList[i];
            
            if ((pInfo->m_loAddr == 0) && (pInfo->m_hiAddr == 0))
            {
                if (!pCurrent->IsHeapFull())
                {
                    // We have no constraint so this non empty heap will be able to satistfy our request
                    pCandidate = pCurrent;
                }
            }
            else
            {
                if (!pCurrent->IsHeapFull())
                {
                    // We also check to see if an allocation in this heap would satistfy
                    // the [loAddr..hiAddr] requirement
                    
                    // Calculate the byte range that can ever be returned by
                    // an allocation in this HeapList element
                    //
                    BYTE * firstAddr      = (BYTE *) pCurrent->startAddress;
                    BYTE * lastAddr       = (BYTE *) pCurrent->startAddress + pCurrent->maxCodeHeapSize;

                    _ASSERTE(pCurrent->startAddress <= pCurrent->endAddress);
                    _ASSERTE(firstAddr <= lastAddr);
                    
                    if (pInfo->IsDynamicDomain())
                    {
                        // We check to see if every allocation in this heap
                        // will satistfy the [loAddr..hiAddr] requirement.
                        //
                        // Dynmaic domains use a free list allocator, 
                        // thus we can recieve any address in the range
                        // when calling AllocMemory with a DynamicDomain
                    
                        // [firstaddr .. lastAddr] must be entirely within
                        // [pInfo->m_loAddr .. pInfo->m_hiAddr]
                        //
                        if ((pInfo->m_loAddr <= firstAddr)   &&
                            (lastAddr        <= pInfo->m_hiAddr))
                        {
                            // This heap will always satistfy our constraint
                            pCandidate = pCurrent;
                        }
                    }
                    else // non-DynamicDoman
                    {
                        // Calculate the byte range that would be allocated for the
                        // next allocation request into [loRequestAddr..hiRequestAddr]
                        //
                        BYTE * loRequestAddr  = (BYTE *) pCurrent->endAddress;
                        BYTE * hiRequestAddr  = loRequestAddr + pInfo->getRequestSize();
                        _ASSERTE(loRequestAddr <= hiRequestAddr);

                        // loRequestAddr and hiRequestAddr must be entirely within
                        // [pInfo->m_loAddr .. pInfo->m_hiAddr]
                        // additionally hiRequestAddr must also be less than
                        // or equal to lastAddr
                        //
                        if ((pInfo->m_loAddr <= loRequestAddr)   &&
                            (hiRequestAddr   <= pInfo->m_hiAddr) &&
                            (hiRequestAddr   <= lastAddr))
                        {
                            // This heap will be able to satistfy our constraint
                            pCandidate = pCurrent;
                        }
                    }
                }
            }

            if (pCandidate != NULL)
            {
                if (pResult == NULL)
                {
                    // pCandidate is the first (and possibly only) heap that would satistfy
                    pResult = pCandidate;
                }
                // We use the initial creation size as a discriminator (i.e largest heap)
                else if (pResult->maxCodeHeapSize < pCandidate->maxCodeHeapSize)
                {
                    pResult = pCandidate;
                }
            }
        }
    }
    else
    {
        // not found so need to create the first one
    NewHolder<DomainCodeHeapList> pNewList(new DomainCodeHeapList());
        pNewList->m_pDomain = pInfo->m_pDomain;

        pResult = NewCodeHeap(pInfo, pNewList);

    DomainCodeHeapList **ppList = NULL;
        if (pInfo->IsDynamicDomain())
        ppList = m_DynamicDomainCodeHeaps.AppendThrowing();
    else
        ppList = m_DomainCodeHeaps.AppendThrowing();
    *ppList = pNewList;

    pNewList.SuppressRelease();
}

    RETURN (pResult);
}

LoaderHeap *EEJitManager::GetJitMetaHeap(MethodDesc *pMD)
{
    CONTRACTL {
        NOTHROW;
        GC_NOTRIGGER;
    } CONTRACTL_END;

    BaseDomain *pDomain = pMD->GetDomain();
    _ASSERTE(pDomain);

    return pDomain->GetLowFrequencyHeap();
}

BYTE* EEJitManager::allocGCInfo(CodeHeader* pCodeHeader, DWORD blockSize, size_t * pAllocationSize)
{
    CONTRACTL {
        THROWS;
        GC_NOTRIGGER;
    } CONTRACTL_END;

    MethodDesc* pMD = pCodeHeader->GetMethodDesc();
    // sadly for light code gen I need the check in here. We should change GetJitMetaHeap
    if (pMD->IsLCGMethod()) 
    {
        CrstHolder ch(&m_CodeHeapCritSec);
        pCodeHeader->SetGCInfo((BYTE*)(void*)pMD->GetDynamicMethodDesc()->GetResolver()->GetJitMetaHeap()->New(blockSize));
    }
    else
    {
        pCodeHeader->SetGCInfo((BYTE*) (void*)GetJitMetaHeap(pMD)->AllocMem(blockSize));
    }
    _ASSERTE(pCodeHeader->GetGCInfo()); // AllocMem throws if there's not enough memory
    JIT_PERF_UPDATE_X86_CODE_SIZE(blockSize);

    * pAllocationSize = blockSize;  // Store the allocation size so we can backout later.
    
    return(pCodeHeader->GetGCInfo());
}

void* EEJitManager::allocEHInfoRaw(CodeHeader* pCodeHeader, DWORD blockSize, size_t * pAllocationSize)
{
    CONTRACTL {
        THROWS;
        GC_NOTRIGGER;
    } CONTRACTL_END;

    MethodDesc* pMD = pCodeHeader->GetMethodDesc();
    void * mem = NULL;

    // sadly for light code gen I need the check in here. We should change GetJitMetaHeap
    if (pMD->IsLCGMethod()) 
    {
        CrstHolder ch(&m_CodeHeapCritSec);
        mem = (void*)pMD->GetDynamicMethodDesc()->GetResolver()->GetJitMetaHeap()->New(blockSize);
    }
    else 
    {
        mem = (void*)GetJitMetaHeap(pMD)->AllocMem(blockSize);
    }
    _ASSERTE(mem);   // AllocMem throws if there's not enough memory

    JIT_PERF_UPDATE_X86_CODE_SIZE(blockSize);

    * pAllocationSize = blockSize; // Store the allocation size so we can backout later.
    
    return(mem);
}


EE_ILEXCEPTION* EEJitManager::allocEHInfo(CodeHeader* pCodeHeader, unsigned numClauses, size_t * pAllocationSize)
{
    CONTRACTL {
        THROWS;
        GC_NOTRIGGER;
    } CONTRACTL_END;

    // Note - pCodeHeader->phdrJitEHInfo - sizeof(size_t) contains the number of EH clauses
    DWORD blockSize = EE_ILEXCEPTION::Size(numClauses) + sizeof(size_t);
    BYTE *EHInfo = (BYTE*)allocEHInfoRaw(pCodeHeader, blockSize, pAllocationSize);

    pCodeHeader->SetEHInfo((EE_ILEXCEPTION*) (EHInfo + sizeof(size_t)));
    pCodeHeader->GetEHInfo()->Init(numClauses);
    *((size_t *)EHInfo) = numClauses;
    return(pCodeHeader->GetEHInfo());
}

JumpStubBlockHeader *  EEJitManager::allocJumpStubBlock(MethodDesc* pMD, DWORD numJumps, 
                                                        BYTE * loAddr, BYTE * hiAddr,
                                                        BaseDomain *pDomain)
{
    CONTRACT(JumpStubBlockHeader *) {
        THROWS;
        GC_NOTRIGGER;
        PRECONDITION(loAddr < hiAddr);
        POSTCONDITION(CheckPointer(RETVAL));
    } CONTRACT_END;

    if (numJumps < 32)
        numJumps = 32;

    _ASSERTE((sizeof(JumpStubBlockHeader) % CODE_SIZE_ALIGN) == 0);
    _ASSERTE(numJumps < MAX_M_ALLOCATED);

    size_t blockSize = sizeof(JumpStubBlockHeader) + (size_t) numJumps * BACK_TO_BACK_JUMP_ALLOCATE_SIZE;

    size_t alignmentFudge = sizeof(CodeHeader) % CODE_SIZE_ALIGN;

    // Immediately before the native code we place a CodeHeader struct
    size_t extraSize = sizeof(CodeHeader) + alignmentFudge;
#ifdef USE_INDIRECT_CODEHEADER
    // alignmentFudge might change with CH+RCH
    extraSize -= alignmentFudge;
    extraSize += sizeof(RealCodeHeader);
    alignmentFudge = (sizeof(RealCodeHeader) + sizeof(CodeHeader)) % CODE_SIZE_ALIGN;
    extraSize += alignmentFudge;
#endif

    blockSize += extraSize;

    // Ensure minimal size
    if (blockSize < BYTES_PER_BUCKET)
        blockSize = BYTES_PER_BUCKET;

    if (pDomain == NULL)
        pDomain = pMD->GetDomain();

    HeapList *pCodeHeap = NULL;

   CodeHeapRequestInfo    requestInfo(pMD, pDomain, blockSize, loAddr, hiAddr);

    CodeHeader *           pCodeHdr;
    BYTE *                 mem;
    JumpStubBlockHeader *  pBlock;

    // Scope the lock
    {
        // This crst has the CRST_DEBUGGER_THREAD flag, which prevents
        // debuggers from halting this thread after if has incremented changeStart,
        // but before it has incremented changeEnd; otherwise it would loop forever
        // when it does a stack walk and tries to access the nibble map.
        // Hijacking profilers have a similar problem, which is fixed by the forbid
        // suspend thread holder below.  Profilers will refuse a stackwalk in
        // a forbid suspend thread region.
        CrstHolder ch(&m_CodeHeapCritSec);

        mem       = (BYTE *) allocCodeRaw(&requestInfo, blockSize, CODE_SIZE_ALIGN, &pCodeHeap);
#ifdef USE_INDIRECT_CODEHEADER
        // RealCodeHeader comes immediately before the CodeHeader
        pCodeHdr  = (CodeHeader *) (mem + sizeof(RealCodeHeader) + alignmentFudge);
        pCodeHdr->SetRealCodeHeader(mem);
#else   // USE_INDIRECT_CODEHEADER
        pCodeHdr  = (CodeHeader *) (mem + alignmentFudge);
#endif  // USE_INDIRECT_CODEHEADER
        // CodeHeader comes immediately before the code;
        pBlock    = (JumpStubBlockHeader *)(pCodeHdr + 1);

        _ASSERTE(IS_ALIGNED(pBlock, CODE_SIZE_ALIGN));
    
        JIT_PERF_UPDATE_X86_CODE_SIZE(blockSize);
    
        {
            // Prevents a thread suspension AND prevents a hijacking profiler from doing
            // a stackwalk.
            ForbidSuspendThreadHolder suspend;
            BEGIN_HOST_NOCALL_CODE;
            {
            CantAllocHolder caHolder;

            pCodeHeap->changeStart++;   // mark that we are about to make changes
        
            _ASSERTE((TADDR)pCodeHdr >= pCodeHeap->mapBase);
            size_t delta = (TADDR)pCodeHdr + sizeof(CodeHeader) - pCodeHeap->mapBase;
            NibbleMapSet(pCodeHeap->pHdrMap, delta);
    
            pCodeHeap->cBlocks++;
            pCodeHeap->changeEnd++;
            }
            END_HOST_NOCALL_CODE;
        }
    }

    pBlock->m_next      = NULL;
    pBlock->m_used      = 0;
    pBlock->m_allocated = numJumps;
    pBlock->m_domain    = pDomain;
    pBlock->m_zero      = 0;

    BYTE *  start = mem;
    BYTE *  end   = start + blockSize;

    JumpStubStubManager::g_pManager->GetRangeList()->AddRange(start, end, this);

    LOG((LF_JIT, LL_INFO1000, "Allocated new JumpStubBlockHeader for %d stubs at" FMT_ADDR " in domain" FMT_ADDR "\n",
         numJumps, DBG_ADDR(pBlock) , DBG_ADDR(pDomain) ));

    RETURN(pBlock);
}

#endif //!DACCESS_COMPILE

// creates an enumeration and returns the number of EH clauses
unsigned EEJitManager::InitializeEHEnumeration(METHODTOKEN MethodToken, EH_CLAUSE_ENUMERATOR* pEnumState)
{
    LEAF_CONTRACT;
    *pEnumState = 1;     // since the EH info is not compressed, the clause number is used to do the enumeration
    EE_ILEXCEPTION *EHInfo = PTR_CodeHeader((CodeHeader*)MethodToken)->GetEHInfo();
    if (!EHInfo)
        return 0;
    return *(PTR_unsigned(PTR_HOST_TO_TADDR(EHInfo) - sizeof(size_t)));
}

EE_ILEXCEPTION_CLAUSE*  EEJitManager::GetNextEHClause(METHODTOKEN MethodToken,
                              //unsigned clauseNumber,
                              EH_CLAUSE_ENUMERATOR* pEnumState,
                              EE_ILEXCEPTION_CLAUSE* pEHClauseOut)
{
    CONTRACTL {
        NOTHROW;
        GC_NOTRIGGER;
    } CONTRACTL_END;

    CodeHeader *pHeader = PTR_CodeHeader((CodeHeader*)MethodToken);

    EE_ILEXCEPTION *pExceptions = pHeader->GetEHInfo();

    (*pEnumState)++;

    return pExceptions->EHClause((unsigned) *pEnumState - 2);
}

#ifndef DACCESS_COMPILE
TypeHandle EEJitManager::ResolveEHClause(METHODTOKEN MethodToken,
                                         //unsigned clauseNumber,
                                         EH_CLAUSE_ENUMERATOR* pEnumState,
                                         EE_ILEXCEPTION_CLAUSE* pEHClauseOut,
                                         CrawlFrame *pCf)
{
    // We don't want to use a runtime contract here since this codepath is used during
    // the processing of a hard SO. Contracts use a significant amount of stack
    // which we can't afford for those cases.
    STATIC_CONTRACT_THROWS;
    STATIC_CONTRACT_GC_TRIGGERS;

    EE_ILEXCEPTION* pExceptions;
    TypeHandle      typeHnd = TypeHandle();
    CodeHeader *    pCHdr   = (CodeHeader*) MethodToken;
    MethodDesc *    pMD     = JitTokenToMethodDesc(MethodToken);
    Module     *    pModule = pMD->GetModule();

    PREFIX_ASSUME(pModule != NULL);

    pExceptions = pCHdr->GetEHInfo();
    // use -2 because need to go back to previous one, as enum will have already been updated
    _ASSERTE(*pEnumState >= 2);
    EE_ILEXCEPTION_CLAUSE *pClause = pExceptions->EHClause((unsigned) *pEnumState - 2);
    _ASSERTE(IsTypedHandler(pClause));

    {
        mdToken typeTok = mdTokenNil;

        {
            CrstHolder chRead(&m_CodeHeapCritSec);
            if (HasCachedTypeHandle(pClause))
            {
                typeHnd = TypeHandle::FromPtr(pClause->TypeHandle);
            }
            else
            {
                typeTok = pClause->ClassToken;
            }
        }

        if (!typeHnd.IsNull())
        {
            return typeHnd;
        }

        SigTypeContext typeContext(pMD);
        VarKind k = hasNoVars;
        if (TypeFromToken(typeTok) == mdtTypeSpec)
        {
            PCCOR_SIGNATURE pSig;
            ULONG cSig;
            pModule->GetMDImport()->GetTypeSpecFromToken(typeTok, &pSig, &cSig);
            SigPointer psig(pSig);
            k = psig.IsPolyType(&typeContext);
            //
            // Grab the active class and method instantiation.  This exact instantiation is only
            // needed in the corner case of "generic" exception catching in shared
            // generic code.  We don't need the exact instantiation if the token
            // doesn't contain E_T_VAR or E_T_MVAR.
            if ((k & hasSharableVarsMask) != 0)
            {
                TypeHandle *classInst = NULL;
                TypeHandle *methodInst = NULL;
                pCf->GetExactGenericInstantiations(&classInst, &methodInst);
                SigTypeContext::InitTypeContext(pMD,classInst, methodInst,&typeContext);
            }
        }

        typeHnd = ClassLoader::LoadTypeDefOrRefOrSpecThrowing(pModule, typeTok, &typeContext, 
                                                              ClassLoader::ReturnNullIfNotFound);

        // If the type (pModule,typeTok) was not loaded or not
        // restored then the exception object won't have this type, because an
        // object of this type has been allocated.
        if (typeHnd.IsNull())
            return typeHnd;

        CrstHolder chWrite(&m_CodeHeapCritSec);

        // check first as if has already been resolved then token will have been replaced with TypeHandle
        if (!HasCachedTypeHandle(pClause))
        {
            //
            // We can cache any exception specification except:
            //   - If the type contains type variables in generic code,
            //     e.g. catch E<T> where T is a type variable.
            //   - If the type handle load returned NULL
            // We CANNOT cache E<T> in non-shared instantiations of generic code because
            // there is only one EHClause cache for the IL, shared across all instantiations.
            if (((k & hasAnyVarsMask) == 0) && !typeHnd.IsNull())
            {
                pClause->TypeHandle = typeHnd.AsPtr();
                SetHasCachedTypeHandle(pClause);
            }
        }
        else
        {
            // If we raced in here with aother thread and got held up on the lock, then we just need to return the
            // type handle that the other thread put into the clause.
            typeHnd = TypeHandle::FromPtr(pClause->TypeHandle);
        }
    }
    return typeHnd;
}

void EEJitManager::RemoveJitData (METHODTOKEN token, size_t GCinfo_len, size_t EHinfo_len)
{
    CONTRACTL {
        NOTHROW;
        GC_NOTRIGGER;
    } CONTRACTL_END;

    CodeHeader* pCHdr = (CodeHeader*) token;

    HeapList *pHp = GetVolatile_pCodeHeap();

    {
        // This crst has the CRST_DEBUGGER_THREAD flag, which prevents
        // debuggers from halting this thread after if has incremented changeStart,
        // but before it has incremented changeEnd; otherwise it would loop forever
        // when it does a stack walk and tries to access the nibble map.
        // Hijacking profilers have a similar problem, which is fixed by the forbid
        // suspend thread holder below.  Profilers will refuse a stackwalk in
        // a forbid suspend thread region.
        CrstHolder ch(&m_CodeHeapCritSec);

        while (pHp && ((pHp->startAddress > (TADDR)pCHdr) ||
                        (pHp->endAddress < (TADDR)pCHdr + sizeof(CodeHeader))))
        {
            pHp = pHp->GetVolatile_hpNext();
        }

        _ASSERTE(pHp && pHp->pHdrMap);
        _ASSERTE(pHp && pHp->cBlocks);

        // Better to just return than AV?
        if (pHp ==  NULL)
            return;

        // After we suspend a thread for GC or abort, we may call EEJitManager::JitCodeToMethodInfo which
        // will loop until changeStart == changeEnd.  If a thread is supended in between, we hang.
        // Also prevents a stackwalk by a hijacking profiler which would see a similar hang when it
        // accesses the EEJitManager.
        ForbidSuspendThreadHolder suspend;
        BEGIN_HOST_NOCALL_CODE;
        {
        CantAllocHolder caHolder;
        
        pHp->changeStart++;

        size_t delta = (TADDR)pCHdr + sizeof(CodeHeader) - pHp->mapBase;
        NibbleMapSet(pHp->pHdrMap, delta, FALSE);

        pHp->cBlocks--;

        pHp->changeEnd++;
        }
        END_HOST_NOCALL_CODE;
        // leave lock
    }

    MethodDesc* pMD = pCHdr->GetMethodDesc();

    // Backout the GCInfo  
    if (GCinfo_len > 0) {
        if (pMD->IsDynamicMethod()) {

             // !!DO NOTHING!!, See comment above.            
        }
        else {
            GetJitMetaHeap(pMD)->BackoutMem(pCHdr->GetGCInfo(), GCinfo_len);
        }
    }
    
    // Backout the EHInfo  
    BYTE *EHInfo = (BYTE *)pCHdr->GetEHInfo();
    if (EHInfo) {
        EHInfo -= sizeof(size_t);

        _ASSERTE(EHinfo_len>0);

        if (pMD->IsDynamicMethod()) {

            // !!DO NOTHING!!, See comment above. 
        }
        else {
            GetJitMetaHeap(pMD)->BackoutMem(EHInfo, EHinfo_len);
        }
    }  

    // 
    //
    //
    return;
}

// appdomain is being unloaded, so delete any data associated with it. We have to do this in two stages.
// On the first stage, we remove the elements from the list. On the second stage, which occurs after a GC
// we know that only threads who were in preemptive mode prior to the GC could possibly still be looking
// at an element that is about to be deleted. All such threads are guarded with a reader count, so if the
// count is 0, we can safely delete, otherwise we must add to the cleanup list to be deleted later. We know
// there can only be one unload at a time, so we can use a single var to hold the unlinked, but not deleted,
// elements.
void EEJitManager::Unload(AppDomain *pDomain)
{
    CONTRACTL {
        NOTHROW;
        GC_NOTRIGGER;
     } CONTRACTL_END;

    CrstHolder ch(&m_CodeHeapCritSec);

    DomainCodeHeapList **ppList = m_DomainCodeHeaps.Table();
    int count = m_DomainCodeHeaps.Count();
    for (int i=0; i < count; i++) {
        if (ppList[i]->m_pDomain == pDomain) {
            DomainCodeHeapList *pList = ppList[i];
            m_DomainCodeHeaps.DeleteByIndex(i);

            // pHeapList is allocated in pHeap, so only need to delete the LoaderHeap itself
            count = pList->m_CodeHeapList.Count();
            for (i=0; i < count; i++) {
                HeapList *pHeapList = pList->m_CodeHeapList[i];
                DeleteCodeHeap(pHeapList);
            }

            // this is ok to do delete as anyone accessing the DomainCodeHeapList structure holds the critical section.
            delete pList;

            break;
        }
    }

    ppList = m_DynamicDomainCodeHeaps.Table();
    count = m_DynamicDomainCodeHeaps.Count();
    for (int i=0; i < count; i++) {
        if (ppList[i]->m_pDomain == pDomain) {
            DomainCodeHeapList *pList = ppList[i];
            m_DynamicDomainCodeHeaps.DeleteByIndex(i);

            // pHeapList is allocated in pHeap, so only need to delete the CodeHeap itself
            count = pList->m_CodeHeapList.Count();
            for (i=0; i < count; i++) {
                HeapList *pHeapList = pList->m_CodeHeapList[i];
                DeleteCodeHeap(pHeapList);
            }

            // this is ok to do delete as anyone accessing the DomainCodeHeapList structure holds the critical section.
            delete pList;

            break;
        }
    }

    ResetNextCodeStartAllocHint();
}

EEJitManager::DomainCodeHeapList::DomainCodeHeapList()
{
    LEAF_CONTRACT;
    m_pDomain = NULL;
}

EEJitManager::DomainCodeHeapList::~DomainCodeHeapList()
{
    LEAF_CONTRACT;
}

//static BOOL bJitHeapShutdown = FALSE;

void EEJitManager::RemoveCodeHeapFromDomainList(CodeHeap *pHeap, BaseDomain *pDomain)
{
    CONTRACTL {
        NOTHROW;
        GC_NOTRIGGER;
        PRECONDITION(m_CodeHeapCritSec.OwnedByCurrentThread());
    } CONTRACTL_END;

    // get the proper AppDomain list of heaps
    DomainCodeHeapList *pList = GetCodeHeapList(NULL, pDomain);
    // go through the heaps and find and remove pHeap
    int count = pList->m_CodeHeapList.Count();
    for (int i = 0; i < count; i++) {
        HeapList *pHeapList = pList->m_CodeHeapList[i];
        if (pHeapList->pHeap == pHeap) {
            // found the heap to remove. If thsi is the only heap we remove the whole DomainCodeHeapList
            // otherwise we just remove this heap
            if (count == 1) {
                m_DynamicDomainCodeHeaps.Delete(pList);
                delete pList;
            }
            else
                pList->m_CodeHeapList.Delete(i);
        }
    }

}

void ExecutionManager::ReleaseReferenceToHeap(EEJitManager *pJitManager, CodeHeap *pCodeHeap, MethodDesc *pMethod)
{
    WRAPPER_CONTRACT;
    CrstHolder ch(&m_JumpStubCrst);
    pJitManager->ReleaseReferenceToHeap(pCodeHeap, pMethod);
}

void EEJitManager::ReleaseReferenceToHeap(CodeHeap *pCodeHeap, MethodDesc *pMD)
{
    WRAPPER_CONTRACT;
    CrstHolder ch(&m_CodeHeapCritSec);
    pCodeHeap->ReleaseReferenceToHeap(pMD);
}

void ExecutionManager::ReleaseHeap(EEJitManager *pJitManager, CodeHeap *pCodeHeap)
{
    WRAPPER_CONTRACT;
    CrstHolder ch(&m_JumpStubCrst);
    pJitManager->ReleaseHeap(pCodeHeap);
}

void EEJitManager::ReleaseHeap(CodeHeap *pCodeHeap)
{
    WRAPPER_CONTRACT;
    CrstHolder ch(&m_CodeHeapCritSec);
    pCodeHeap->DestroyHeap();
}

void EEJitManager::DeleteCodeHeap(HeapList *pHeapList)
{
    CONTRACTL {
        NOTHROW;
        GC_NOTRIGGER;
        PRECONDITION(m_CodeHeapCritSec.OwnedByCurrentThread());
    } CONTRACTL_END;

#ifdef _DEBUG
    DebugCheckJitHeapCacheValidity ();
#endif // _DEBUG

    HeapList *pHp = GetVolatile_pCodeHeap();
    if (pHp == pHeapList)
        SetVolatile_pCodeHeap(pHp->GetVolatile_hpNext());
    else
    {
        HeapList *pHpNext = pHp->GetVolatile_hpNext();
        
        while (pHpNext != pHeapList)
        {
            pHp = pHpNext;
            _ASSERTE(pHp != NULL);  // should always find the HeapList
            pHpNext = pHp->GetVolatile_hpNext();
        }
        pHp->SetVolatile_hpNext(pHeapList->GetVolatile_hpNext());
    }

    ExecutionManager::DeleteCodeRange((TADDR)pHeapList);

    DeleteJitHeapCache (pHeapList);
    m_pJitHeapCacheUnlinkedList = 0; // automatically deleted when the LoaderHeap is deleted.
#ifdef _DEBUG
    DebugCheckJitHeapCacheValidity ();
#endif // _DEBUG

    LOG((LF_JIT, LL_INFO100, "DeleteCodeHeap start" FMT_ADDR "end" FMT_ADDR "\n",
                              (const BYTE*)pHeapList->startAddress, 
                              (const BYTE*)pHeapList->endAddress     ));





    // Take the writer lock to ensure all readers have finished with the pHp pointer,
    // then release it so we delete the memory outside the lock to avoid deadlocks
    // with the heap lock.
    
    WriterLockHolder wlh(this);
    wlh.Release();
    
    // pHeapList is allocated in pHeap, so only need to delete the CodeHeap itself
    delete pHeapList->pHeap;
}

#endif // #ifndef DACCESS_COMPILE

MethodDesc* EEJitManager::JitCodeToMethodDescWrapper(SLOT currentPC, METHODTOKEN* pMethodToken, DWORD* pPCOffset)
{
    CONTRACTL {
        NOTHROW;
        GC_NOTRIGGER;
    } CONTRACTL_END;

    ReaderLockHolder rlh(this);
    MethodDesc* pMethodDesc = NULL;
    JitCodeToMethodInfo(currentPC, 
                        &pMethodDesc, 
                        pMethodToken, 
                        pPCOffset, 
                        ScanNoReaderLock);
    return pMethodDesc;
}


// Given an CodeHeader for an EEJitManager, get the Debugging Information associated with it.
JitDebugInfo * GetDebugInfoSlotForHeader(CodeHeader * pHdr)
{
    LEAF_CONTRACT;
    
    JitDebugInfo *  p = pHdr->GetDebugInfo();
    return p;
}

CodeHeader * EEJitDebugInfoStore::GetCodeHeaderFromJitRequest(const DebugInfoRequest & request)
{
    CONTRACTL {
        NOTHROW;
        GC_NOTRIGGER;
    } CONTRACTL_END;
    
    TADDR address = (TADDR) request.GetStartAddress();
    _ASSERTE(address != NULL);
    
    CodeHeader * pHeader = EEJitManager::GetCodeHeaderFromAddr(address);
    _ASSERTE(pHeader != NULL);    

    _ASSERTE(!pHeader->GetMethodDesc()->IsPreImplemented());
    
    return pHeader;
}

//-----------------------------------------------------------------------------
// Get vars from Jit Store
//-----------------------------------------------------------------------------
HRESULT EEJitDebugInfoStore::GetVars(
        const DebugInfoRequest & request,
        IN FP_IDS_NEW fpNew, IN void * pNewData,
        OUT ULONG32 * pcVars, 
        OUT ICorDebugInfo::NativeVarInfo **  ppVars)
{
    CONTRACTL {
        THROWS;       // on OOM.
        GC_NOTRIGGER; // getting vars shouldn't trigger
    } CONTRACTL_END;
    
    _ASSERTE(ppVars != NULL);
    _ASSERTE(pcVars != NULL);
    _ASSERTE(fpNew != NULL);
    
    *pcVars = 0;
    *ppVars = NULL;

    CodeHeader * pHdr = GetCodeHeaderFromJitRequest(request);
    _ASSERTE(pHdr != NULL);

    JitDebugInfo * pSlot = GetDebugInfoSlotForHeader(pHdr);
    
    // No header created, which means no jit information is available.
    if (pSlot == NULL)
    {
        return E_FAIL;
    }
    
    
    CompressDebugInfo::Vars info;    
    info = pSlot->m_vars;

    // Uncompress. This allocates memory and may throw.
    CompressDebugInfo::RestoreVars(
        fpNew, pNewData, // allocators
        &info,           // input
        pcVars, ppVars); // output

    return S_OK;
}

//-----------------------------------------------------------------------------
// Get boundaries from JIT store.
//-----------------------------------------------------------------------------
HRESULT EEJitDebugInfoStore::GetBoundaries(
        const DebugInfoRequest & request,
        IN FP_IDS_NEW fpNew, IN void * pNewData,
        OUT ULONG32 * pcMap, 
        OUT ICorDebugInfo::OffsetMapping ** ppMap)
{
    CONTRACTL {
        THROWS;       // on OOM.
        GC_NOTRIGGER; // getting vars shouldn't trigger
    } CONTRACTL_END;
    
    _ASSERTE(ppMap != NULL);
    _ASSERTE(pcMap != NULL);
    _ASSERTE(fpNew != NULL);

    *pcMap = 0;
    *ppMap = NULL;
    
    //MethodDesc * md = request.GetMD();
    CodeHeader * pHdr = GetCodeHeaderFromJitRequest(request);
    _ASSERTE(pHdr != NULL);

    JitDebugInfo * pSlot = GetDebugInfoSlotForHeader(pHdr);    
    
    // No header created, which means no jit information is available.
    if (pSlot == NULL)
    {
        return E_FAIL;
    }
    
    CompressDebugInfo::Boundaries info;    

    info = pSlot->m_bounds;


    // Uncompress. This allocates memory and may throw.
    CompressDebugInfo::RestoreBoundaries(
        fpNew, pNewData, // allocators
        &info,           // input
        pcMap, ppMap);   // output

    return S_OK;
}

//-----------------------------------------------------------------------------
// Get a IDebugInfoStore which can read the debugging information.
//-----------------------------------------------------------------------------
void EEJitManager::GetDebugInfoStore(IDebugInfoStore ** ppStore)
{
    CONTRACT_VOID {
        NOTHROW;
        GC_NOTRIGGER;
    } CONTRACT_END;
    
    _ASSERTE(ppStore != NULL);

    TADDR addrStore = PTR_HOST_MEMBER_TADDR(EEJitManager, this, m_DebugInfoStore);
    IDebugInfoStore * pStore = PTR_IDebugInfoStore(addrStore);
    *ppStore = pStore;
    
    RETURN;
}

#ifndef DACCESS_COMPILE   
// Allocators for Jit's implementation of IDebugInfoStore
BYTE * LoaderHeapNewMD(MethodDesc * pMD, size_t cBytes)
{
    CONTRACTL {
        THROWS;
        WRAPPER(GC_TRIGGERS);
    } CONTRACTL_END;
    
    LoaderHeap * pHeap = pMD->GetDomain()->GetLowFrequencyHeap();
    // Note that void*() casting operator is overloaded and very special here.
    TaggedMemAllocPtr p = pHeap->AllocMem(cBytes);
    void* mem = (void*) p;
    
    return (BYTE*) mem;
}

// Read-write operation which will get the JitDebugInfo from the header,
// and create it lazily if needed.
JitDebugInfo * GetOrCreateInfoSlotForHeader(CodeHeader* pHeader)
{
    CONTRACTL {
        THROWS;
        WRAPPER(GC_TRIGGERS);
    } CONTRACTL_END;
   
    _ASSERTE(pHeader != NULL);
    
    JitDebugInfo * pInfo = pHeader->GetDebugInfo();    
    if (pInfo == NULL)
    {
        // DAC is read-only here and will return NULL if not initialized.
        pInfo = reinterpret_cast<JitDebugInfo*> (LoaderHeapNewMD(pHeader->GetMethodDesc(), sizeof(JitDebugInfo)));
        pHeader->SetDebugInfo(pInfo);
        pInfo->Init();
    }
    return pInfo;    
}

// Used to populate the info store.
void EEJitManager::setVars(CodeHeader * pHeader, CORINFO_METHOD_HANDLE ftn, ULONG32 cVars, ICorDebugInfo::NativeVarInfo *vars)
{
    CONTRACTL {
        NOTHROW;
        WRAPPER(GC_TRIGGERS);
    } CONTRACTL_END;

    _ASSERTE(pHeader != NULL);
    
    if (!ShouldTrackJitInfo(pHeader))
    {
        return;
    }

    if (cVars > 0)
    {
        EX_TRY
        {        
            _ASSERTE((cVars == 0) == (vars == NULL));
            
            StackSBuffer bufferTemp;
            CompressDebugInfo::CompressVars(cVars, vars, &bufferTemp);
            ULONG32 cbSize = bufferTemp.GetSize();

            BYTE* pBuffer = LoaderHeapNewMD(pHeader->GetMethodDesc(), cbSize); // throws
            memcpy(pBuffer, (const void*) bufferTemp, cbSize);

            JitDebugInfo * pSlot = GetOrCreateInfoSlotForHeader(pHeader);        

            CompressDebugInfo::Vars info;

            info.Deserialize((TADDR) pBuffer, cbSize);
            pSlot->m_vars = info;
        }
        EX_CATCH
        {
            // Just ignore exceptions here. The debugger's structures will still be in a consistent state.
        }
        EX_END_CATCH(SwallowAllExceptions)
    }        
}

void EEJitManager::setBoundaries(CodeHeader * pHeader, CORINFO_METHOD_HANDLE ftn, ULONG32 cMap, ICorDebugInfo::OffsetMapping *pMap)
{
    CONTRACTL {
        NOTHROW;
        WRAPPER(GC_TRIGGERS);
    } CONTRACTL_END;

    _ASSERTE(pHeader != NULL);
    
    if (!ShouldTrackJitInfo(pHeader))
    {
        return;
    }

    if (cMap > 0)
    {
        EX_TRY
        {        
            StackSBuffer bufferTemp;
            CompressDebugInfo::CompressBoundaries(cMap, pMap, &bufferTemp);
            ULONG32 cbSize = bufferTemp.GetSize();
            

            BYTE* pBuffer = LoaderHeapNewMD(pHeader->GetMethodDesc(), cbSize); // throws
            memcpy(pBuffer, (const void *) bufferTemp, cbSize);


            CompressDebugInfo::Boundaries info;

            JitDebugInfo * pSlot = GetOrCreateInfoSlotForHeader(pHeader);
            info.Deserialize((TADDR) pBuffer, cbSize);
            pSlot->m_bounds = info;           
        }
        EX_CATCH
        {
            // Just ignore exceptions here. The debugger's structures will still be in a consistent state.
        }
        EX_END_CATCH(SwallowAllExceptions)
    }        
}
#endif

#ifdef DACCESS_COMPILE
void JitDebugInfo::EnumMemoryRegions(CLRDataEnumMemoryFlags flags)
{
    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
    }
    CONTRACTL_END;    

    DAC_ENUM_DTHIS();

    DacEnumMemoryRegion(PTR_HOST_TO_TADDR(this), sizeof(JitDebugInfo));

    this->m_bounds.EnumMemoryRegions(flags);
    this->m_vars.EnumMemoryRegions(flags);
}


void CodeHeader::EnumMemoryRegions(CLRDataEnumMemoryFlags flags, IJitManager* pJitMan)
{
    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
    }
    CONTRACTL_END;    

    DAC_ENUM_DTHIS();
    
#ifdef USE_INDIRECT_CODEHEADER
    DacEnumMemoryRegion(PTR_HOST_TO_TADDR(this), sizeof(CodeHeader));
    DacEnumMemoryRegion(PTR_HOST_TO_TADDR(this->pRealCodeHeader), sizeof(RealCodeHeader));
#else // USE_INDIRECT_CODEHEADER
    DacEnumMemoryRegion(PTR_HOST_TO_TADDR(this), sizeof(CodeHeader));
#endif // USE_INDIRECT_CODEHEADER

    if (this->GetDebugInfo() != NULL)
    {
        this->GetDebugInfo()->EnumMemoryRegions(flags);
    }

}

//-----------------------------------------------------------------------------
// Enumerate for minidumps.
//-----------------------------------------------------------------------------
void EEJitDebugInfoStore::EnumMemoryRegionsForMethodDebugInfo(CLRDataEnumMemoryFlags flags, MethodDesc * pMD)
{
    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
    }
    CONTRACTL_END;    

    DebugInfoRequest request;
    TADDR addrCode = (TADDR) pMD->GetFunctionAddress();
    request.InitFromStartingAddr(pMD, addrCode);

    CodeHeader* pHeader = EEJitDebugInfoStore::GetCodeHeaderFromJitRequest(request);

    pHeader->EnumMemoryRegions(flags, NULL);
}
#endif

void EEJitManager::JitCodeToMethodInfo(
        SLOT currentPC,
        MethodDesc** ppMethodDesc,
        METHODTOKEN* pMethodToken,
        DWORD* pPCOffset,
        ScanFlag scanFlag)
{
    CONTRACT_VOID {
        NOTHROW;
        GC_NOTRIGGER;
        SO_TOLERANT;
        POSTCONDITION(( ppMethodDesc == NULL) || 
                      (*ppMethodDesc == NULL) ||
                      (*ppMethodDesc != (MethodDesc*)POISONC && (*ppMethodDesc)->SanityCheck()));
        POSTCONDITION(pMethodToken == NULL || *pMethodToken != (METHODTOKEN)POISONC);
    } CONTRACT_END;

#ifdef _DEBUG
    if (ppMethodDesc)
    {
        *ppMethodDesc = (MethodDesc*)POISONC;
    }
    if (pMethodToken)
    {
        *pMethodToken = (METHODTOKEN)POISONC;
    }
#endif // _DEBUG

    if (scanFlag != IJitManager::ScanNoReaderLock && IJitManager::GetScanFlags() != IJitManager::ScanNoReaderLock)
    {
        MethodDesc * pMethodDesc = JitCodeToMethodDescWrapper(currentPC, 
                                                              pMethodToken, 
                                                              pPCOffset
                                                              );
        if (ppMethodDesc)
        {
            *ppMethodDesc = pMethodDesc;
        }
        RETURN;        
    }

    HeapList *pHp = NULL;
    CodeHeader *pCHdr;
    PBYTE tick;

#ifdef _DEBUG_IMPL
    HeapList *pDebugHp = GetVolatile_pCodeHeap();
    while (pDebugHp != NULL)
    {
        if ( (pDebugHp->startAddress < (TADDR)currentPC) &&
             (pDebugHp->endAddress >= (TADDR)currentPC) )
        {
            break;
        }
        pDebugHp = pDebugHp->GetVolatile_hpNext();
    }
#endif // _DEBUG_IMPL


    //-------------------------------------------------------------------------
    // Search the cache for the HeapList containing "currentPC"

    HashEntry* hashEntry = NULL;

    size_t currHashKey = COMPUTE_HASH_KEY((size_t)currentPC);
    DWORD  index       = GET_CACHE_INDEX(currHashKey);

    LOG((LF_SYNC, LL_INFO10000, "JitCodeToMethodDesc_CacheCompare: %0x\t%0x\n", index, currHashKey));

    hashEntry = m_JitCodeHashTable[index];
    while (hashEntry != NULL)
    {
        if (hashEntry->hashKey == currHashKey)
        {
            pHp = hashEntry->pHp;

            // The first page of the heap has header. The header can contain executable code 
            // that is not jitted code (e.g. exception handling rebounder jump). We need to check 
            // actual boundaries to confirm the cache hit.
            if ( (pHp->startAddress < (TADDR)currentPC) &&
                (pHp->endAddress >= (TADDR)currentPC) )
            {
                LOG((LF_SYNC, LL_INFO1000, "JitCodeToMethodDesc_CacheHit: %0x\t%0x\n", COMPUTE_HASH_KEY((size_t)currentPC), pHp));
                goto foundHeader;
            }
        }
        hashEntry = hashEntry->pNext;
    }
    

    // Reached here imples that we didn't find the range in the cache or the cache is off
    pHp = GetVolatile_pCodeHeap();
    while (pHp != NULL)
    {
        if ( (pHp->startAddress < (TADDR)currentPC) &&
             (pHp->endAddress >= (TADDR)currentPC) )
        {
            break;
        }
        pHp = pHp->GetVolatile_hpNext();
    }

foundHeader:

    // Whatever method we use to get to the heap node, the following should be true
#ifdef _DEBUG_IMPL
    _ASSERTE ((pHp == pDebugHp) && "JitCodeToMethodDesc cache incorrect");
#endif

    if ((pHp == NULL) || ((TADDR)currentPC < pHp->startAddress) ||
        ((TADDR)currentPC > pHp->endAddress))
    {
        if (pMethodToken)
        {
            *pMethodToken = NULL;
        }
        if (ppMethodDesc)
        {
            *ppMethodDesc = NULL;
        }
        RETURN;
    }

    // we now access the nibble-map and are prone to race conditions.
    // Since we are strictly a "reader", we just use a simple counter
    // scheme to detect if something changed while we were accessing
    // the map. In that case we simply try it again.
    while (1)
    {

        tick = pHp->changeEnd;

        size_t codeOffset = FindMethodCode(pHp->pHdrMap, (TADDR)currentPC - pHp->mapBase);
        if (codeOffset == UINT_MAX)
        {
            if (pMethodToken)
            {
                *pMethodToken = NULL;
            }
            if (ppMethodDesc)
            {
                *ppMethodDesc = NULL;
            }
            RETURN;
        }
        pCHdr = PTR_CodeHeader(pHp->mapBase + (codeOffset - sizeof(CodeHeader)));

        // now check if something has changed while we were accessing
        // the map
        if (tick == pHp->changeStart)
        {
            // no changes, we are done
            _ASSERTE((TADDR)currentPC > PTR_HOST_TO_TADDR(pCHdr));
            if (pMethodToken)
            {
                *pMethodToken = (METHODTOKEN) pCHdr;
            }

            if (pPCOffset)
            {
                *pPCOffset = (DWORD)(currentPC - pCHdr->GetCodeStartAddress());
            }

            if (ppMethodDesc)
            {
                *ppMethodDesc = pCHdr->GetMethodDesc();
            }
            RETURN;
        }
        else
        {
            // A writer modified heap while we were reading it.
            // Give the writer a chance to finish what it's doing and
            // then retry. This is potentially bad as we could keep on
            // looping if writers keep on making changes, but since we
            // typically will not have many writers it should be fine.
            //
            // <WARNING!!!>
            // DO NOT replace this __SwitchToThread() with grabbing
            // the m_CodeHeapCritSec to get in sync with the writers.
            // On 64bit platforms we can frequently end up in JitCodeToMethodInfo
            // under the Loader lock and have numerous potential
            // deadlocks with that implementation.
            // </WARNING!!!>
#ifndef DACCESS_COMPILE
            {
            // When hosted, call SwitchToThread through the OS instead of the host
                __DangerousSwitchToThread(0, TRUE);
            }
#else
            // Nothing should be updating the nibble map under DAC!
            UNREACHABLE();
#endif
        }
    }

    _ASSERTE(!"Unreachable");
    RETURN ;
}

#if !defined(DACCESS_COMPILE)


void  EEJitManager::ResumeAtJitEH(CrawlFrame* pCf, EE_ILEXCEPTION_CLAUSE *EHClausePtr, DWORD nestingLevel, Thread *pThread, BOOL unwindStack)
{
    // no explicit contract here because this function doesn't return and destructors wouldn't be executed

    WRAPPER_CONTRACT;

    BYTE* startAddress = JitTokenToStartAddress(pCf->GetMethodToken());
    ::ResumeAtJitEH(pCf,startAddress,EHClausePtr,nestingLevel,pThread, unwindStack);
}

int  EEJitManager::CallJitEHFilter(CrawlFrame* pCf, EE_ILEXCEPTION_CLAUSE *EHClausePtr, DWORD nestingLevel, OBJECTREF thrownObj)
{
    // Exact contract depends on called code, assume the worst.

    // Note: you can't have a dynamic contract in here. We've pushed a nested exception handler before calling
    // this, and that handler has to be the top FS:0 handler when calling managed code, which is what's going to
    // happen very shortly.
    STATIC_CONTRACT_THROWS;
    STATIC_CONTRACT_GC_TRIGGERS;

    BYTE* startAddress = JitTokenToStartAddress(pCf->GetMethodToken());
    return ::CallJitEHFilter(pCf,startAddress,EHClausePtr,nestingLevel,thrownObj);
}

void   EEJitManager::CallJitEHFinally(CrawlFrame* pCf, EE_ILEXCEPTION_CLAUSE *EHClausePtr, DWORD nestingLevel)
{
    // Exact contract depends on called code, assume the worst.

    // Note: you can't have a dynamic contract in here. We've pushed a nested exception handler before calling
    // this, and that handler has to be the top FS:0 handler when calling managed code, which is what's going to
    // happen very shortly.
    STATIC_CONTRACT_THROWS;
    STATIC_CONTRACT_GC_TRIGGERS;

    BYTE* startAddress = JitTokenToStartAddress(pCf->GetMethodToken());
    ::CallJitEHFinally(pCf,startAddress,EHClausePtr,nestingLevel);
}

void EEJitManager::NibbleMapSet(DWORD * pMap, size_t delta, BOOL bSet /* = TRUE */) 
{
    CONTRACTL {
        NOTHROW;
        GC_NOTRIGGER;
        HOST_NOCALLS;
    } CONTRACTL_END;

    size_t pos  = ADDR2POS(delta); 
    DWORD value = bSet?ADDR2OFFS(delta):0;

    DWORD index = (DWORD) (pos >> LOG2_NIBBLES_PER_DWORD);
    DWORD mask  = ~((DWORD) HIGHEST_NIBBLE_MASK >> ((pos & NIBBLES_PER_DWORD_MASK) << LOG2_NIBBLE_SIZE));

//  printf("[Set: pos=%5x, val=%d]\n", pos, value);

    value = value << POS2SHIFTCOUNT(pos);

    // assert that we don't overwrite an existing offset
    // (it's a reset or it is empty)
    _ASSERTE(!value || !((*(pMap+index))& ~mask));

    *(pMap+index) = ((*(pMap+index))&mask)|value;
}

#endif // !DACCESS_COMPILE



// Finds the header corresponding to the code at offset "delta".
// Note that there are different types of headers like CodeHeader, CORCOMPILE_METHOD_HEADER, etc.
// Returns UINT_MAX if there is no header for the given "delta"

size_t EEJitManager::FindMethodCode(PTR_DWORD pMap, TADDR delta)
{
    LEAF_CONTRACT;

    PTR_DWORD pMapStart = pMap;

    DWORD tmp;

    size_t startPos = ADDR2POS(delta);  // align to 32byte buckets
                                        // ( == index into the array of nibbles)
    DWORD  offset   = ADDR2OFFS(delta); // this is the offset inside the bucket + 1

    _ASSERTE(offset == (offset & NIBBLE_MASK));

    pMap += (startPos >> LOG2_NIBBLES_PER_DWORD); // points to the proper DWORD of the map

    // get DWORD and shift down our nibble

    PREFIX_ASSUME(pMap != NULL);
    tmp = (*pMap) >> POS2SHIFTCOUNT(startPos);

    if ((tmp & NIBBLE_MASK) && ((tmp & NIBBLE_MASK) <= offset) )
    {
        return POSOFF2ADDR(startPos, tmp & NIBBLE_MASK);
    }

    // Is there a header in the remainder of the DWORD ?
    tmp = tmp >> NIBBLE_SIZE;

    if (tmp)
    {
        startPos--;
        while (!(tmp & NIBBLE_MASK))
        {
            tmp = tmp >> NIBBLE_SIZE;
            startPos--;
        }
        return POSOFF2ADDR(startPos, tmp & NIBBLE_MASK);
    }

    // We skipped the remainder of the DWORD,
    // so we must set startPos to the highest position of
    // previous DWORD, unless we are already on the first DWORD

    if (startPos < NIBBLES_PER_DWORD)
        return UINT_MAX;

    startPos = ((startPos >> LOG2_NIBBLES_PER_DWORD) << LOG2_NIBBLES_PER_DWORD) - 1;

    // Skip "headerless" DWORDS

    while (pMapStart < pMap && 0 == (tmp = *(--pMap)))
    {
        startPos -= NIBBLES_PER_DWORD;
    }

    // This helps to catch degenerate error cases. This relies on the fact that
    // startPos cannot ever be bigger than MAX_UINT
    if (((INT_PTR)startPos) < 0)
        return UINT_MAX;

    // Find the nibble with the header in the DWORD

    while (startPos && !(tmp & NIBBLE_MASK))
    {
        tmp = tmp >> NIBBLE_SIZE;
        startPos--;
    }

    if (startPos == 0 && tmp == 0)
        return UINT_MAX;

    return POSOFF2ADDR(startPos, tmp & NIBBLE_MASK);
}

#ifdef DACCESS_COMPILE

void EEJitManager::EnumMemoryRegions(CLRDataEnumMemoryFlags flags)
{
    IJitManager::EnumMemoryRegions(flags);

    //
    // Save all of the code heaps.
    //

    HeapList* heap;

    for (heap = GetVolatile_pCodeHeap(); heap; heap = heap->GetVolatile_hpNext())
    {
        DacEnumHostDPtrMem(heap);

        if (heap->pHeap.IsValid())
        {
            heap->pHeap->EnumMemoryRegions(flags);
        }

        DacEnumMemoryRegion(heap->startAddress, (ULONG32)
                            (heap->endAddress - heap->startAddress));

        if (heap->pHdrMap.IsValid())
        {
            ULONG32 nibbleMapSize = (ULONG32)
                HEAP2MAPSIZE(ROUND_UP_TO_PAGE(heap->maxCodeHeapSize));
            DacEnumMemoryRegion(PTR_TO_TADDR(heap->pHdrMap), nibbleMapSize);
        }
    }


    //
    // Save the hash table entries.
    //
    for (ULONG i = 0; i < NumItems(m_JitCodeHashTable); i++)
    {
        HashEntry* hashEntry;

        for (hashEntry = m_JitCodeHashTable[i];
             hashEntry;
             hashEntry = hashEntry->pNext)
        {
            DacEnumHostDPtrMem(hashEntry);
        }
    }

}

#endif // #ifdef DACCESS_COMPILE

#ifndef DACCESS_COMPILE

//*******************************************************
// Execution Manager
//*******************************************************

// Init statics
void ExecutionManager::Init()
{
    CONTRACTL {
        THROWS;
        GC_NOTRIGGER;
    } CONTRACTL_END;


    m_ExecutionManagerCrst.Init("ExecuteManCrst", CrstExecuteManLock);

    m_JumpStubCrst.Init("JumpStubCrst", CrstJumpStubCache, CRST_UNSAFE_ANYMODE);

    m_RangeCrst.Init("ExecuteManRangeCrst", CrstExecuteManRangeLock, CRST_UNSAFE_ANYMODE);


#ifndef FJITONLY
    m_pDefaultCodeMan = new EECodeManager();
#endif

}

#endif // #ifndef DACCESS_COMPILE

IJitManager* ExecutionManager::FindJitManNonZeroWrapper(SLOT currentPC)
{
    WRAPPER_CONTRACT;

    ReaderLockHolder rlh;    

    return FindJitManNonZero(currentPC, IJitManager::ScanNoReaderLock);
}

//**************************************************************************
// Find a jit manager from the current locations of the IP
//
IJitManager*
ExecutionManager::FindJitManNonZero(SLOT currentPC,
                                    IJitManager::ScanFlag scanFlag)
{
    CONTRACTL {
        NOTHROW;
        GC_NOTRIGGER;
        SO_TOLERANT;
    } CONTRACTL_END;

    if (scanFlag != IJitManager::ScanNoReaderLock && IJitManager::GetScanFlags() != IJitManager::ScanNoReaderLock)
        return FindJitManNonZeroWrapper(currentPC);

    RangeSection *pRS = GetRangeSection(m_CodeRangeList, (TADDR) currentPC);

    if (pRS == NULL)
    {
        return NULL;
    }
    else
    {

        return pRS->pjit;
    }
}

#ifndef DACCESS_COMPILE

//**************************************************************************
// Find a code manager for a particular type of code
// ie. IL, Managed Native or OPT_IL
//
IJitManager* ExecutionManager::FindJitForType(DWORD Flags)
{
    CONTRACTL {
        NOTHROW;
        GC_NOTRIGGER;
    } CONTRACTL_END;

    if (!m_pJitList)
        return NULL;

    IJitManager *walker = m_pJitList;

    while (walker)
    {
        if (walker->IsJitForType(Flags))
            return walker;
        else
            walker = walker->m_next;
    }
    return walker;
}

//**************************************************************************
// Clear the caches for all JITs loaded.
//
void ExecutionManager::ClearCaches( void )
{
    CONTRACTL {
        NOTHROW;
        GC_NOTRIGGER;
    } CONTRACTL_END;

    if (!m_pJitList)
        return;

    IJitManager *walker = m_pJitList;

    while (walker)
    {
        walker->ClearCache();
        walker = walker->m_next;
    }
    
    return;
}

//**************************************************************************
// Check if caches for any JITs loaded need to be cleaned
//
BOOL ExecutionManager::IsCacheCleanupRequired( void )
{
    CONTRACTL {
        NOTHROW;
        GC_NOTRIGGER;
    } CONTRACTL_END;

    if (!m_pJitList)
        return FALSE;

    IJitManager *walker = m_pJitList;

    while (walker)
    {
        if( walker->IsCacheCleanupRequired() )
        {
            return TRUE;
        }
        
        walker = walker->m_next;
    }
    
    return FALSE;
}

/*********************************************************************/
// This static method returns the name of the jit dll
//
LPWSTR ExecutionManager::GetJitName()
{
    CONTRACTL {
        THROWS;
        GC_TRIGGERS;
        SO_INTOLERANT;
    } CONTRACTL_END;

    LPWSTR  pwzJitName;

    // Try to obtain a name for the jit library from the env. variable
    IfFailThrow(g_pConfig->GetConfigString(L"JitName", &pwzJitName));
    
    if (NULL == pwzJitName)
    {
        pwzJitName = MAKEDLLNAME_W(L"mscorjit");
    }
    return pwzJitName;
}

/*********************************************************************/
// This static method on ExecutionManager returns the IJitManager for
//  the appropriate code type based on the Flags parameter
//
// When creating the method entry points we don't need to force the jit dll to be loaded
// But typically asking for a managaed IL IJitCodeManager forces the jit dll to be loaded
// So w have added a bool argument to GetJitForType to tell it that it doesn't need to
// force load the jit dll
// If we call GetJitForType later on a different codepath where we need to load the JIT
// it will load the jit dll at that later time
//
IJitManager* ExecutionManager::GetJitForType(DWORD Flags, bool dontLoadJit /*= false*/)
{
    CONTRACTL {
        THROWS;
        GC_TRIGGERS;
        SO_INTOLERANT;  // allocates memory
    } CONTRACTL_END;

    // If we have instantiated jit managers then we need to walk the and see if one of them handles this codetype.
    IJitManager* jitMgr = FindJitForType(Flags);
    if (!jitMgr)
    {
        // Take the code manager lock
        CrstPreempHolder ch(&m_ExecutionManagerCrst);

        jitMgr = FindJitForType(Flags);
        if (!jitMgr)
        {
            NewHolder<ICodeManager> codeMgrHolder;
            ICodeManager* codeMgr = NULL;
            BOOL bIsDefault = FALSE;

            switch (Flags)
            {
            case (miManaged | miIL):
                break;


#ifdef FJIT
            // This is the type that is set if we have used the Econo-Jit!!!
            case miManaged_IL_EJIT:
                codeMgrHolder = new Fjit_EETwain();
                codeMgr = codeMgrHolder;
                break;
#endif

            default:
                _ASSERTE(false);
                break;
            }

            // Use the default JIT manager if we do not have one by this point
            if (jitMgr == NULL)
                jitMgr = new EEJitManager();
            jitMgr->SetCodeType(Flags);

#ifndef FJITONLY
            // Use the default code manager if we do not have one by this point
            if (codeMgr == NULL)
            {
                codeMgr = m_pDefaultCodeMan;
                bIsDefault = TRUE;
            }
#endif
            jitMgr->SetCodeManager(codeMgr, bIsDefault);
            codeMgrHolder.SuppressRelease();

            AddJitManager(jitMgr);
        }
    }


    if (!dontLoadJit && !jitMgr->IsJitLoaded())
    {
        // Take the code manager lock
        CrstPreempHolder ch(&m_ExecutionManagerCrst);

        if (!jitMgr->IsJitLoaded())
        {
            LPWSTR  pwzJitName;
            
            switch (Flags)
            {

#ifndef FJITONLY
            case (miManaged | miIL):
                pwzJitName = ExecutionManager::GetJitName();

                if (!jitMgr->LoadJIT(pwzJitName))
                {
                    if (!(m_fFailedToLoad & FAILED_JIT))
                    {
                        EEMessageBoxCatastrophic(IDS_EE_CANNOT_LOAD_JIT, IDS_FATAL_ERROR, pwzJitName);
                        m_fFailedToLoad = m_fFailedToLoad | FAILED_JIT;
                    }
                }
                break;
#endif // FJITONLY

#ifdef FJIT
            // This is the type that is set if we have used the Econo-Jit!!!
            case miManaged_IL_EJIT:
                // Try to obtain a name for the jit library from the env. variable
                IfFailThrow(g_pConfig->GetConfigString(L"JitName", &pwzJitName));

                if (NULL == pwzJitName)
                {
                    pwzJitName = MAKEDLLNAME_W(L"mscorejt");
                }

                if (!(jitMgr->LoadJIT(pwzJitName)))
                {
                    if (!(m_fFailedToLoad & FAILED_EJIT))
                    {
                        m_fFailedToLoad = m_fFailedToLoad | FAILED_EJIT;
                    }
                }
                break;
#endif  // FJIT

            default :
                // If we got here then something odd happened
                // and we need to free the codeMgr and exit
                _ASSERTE(0 && "Unknown impl type");
                break;
            }

        }
    }

    _ASSERTE(jitMgr != NULL);

    return jitMgr;
}

void ExecutionManager::Unload(AppDomain *pDomain)
{
    CONTRACTL {
        NOTHROW;
        GC_NOTRIGGER;
    } CONTRACTL_END;

    // a size of 0 is a signal to Nirvana to flush the entire cache 
    FlushInstructionCache(GetCurrentProcess(),0,0);
    CrstHolder ch(&m_JumpStubCrst);

    /* StackwalkCacheEntry::EIP is an address into code. Since we are
    unloading the code, we need to invalidate the cache. Otherwise,
    its possible that another appdomain might generate code at the very
    same address, and we might incorrectly think that the old
    StackwalkCacheEntry corresponds to it. So flush the cache.
    */
    StackwalkCache::Invalidate(pDomain);
    
    IJitManager *pMan = m_pJitList;
    while (pMan)
    {
        pMan->Unload(pDomain);
        pMan = pMan->m_next;
    }
}

BOOL ExecutionManager::PatchEntryPoint(BYTE* pBuffer, BYTE epSize, BYTE* target, MethodDesc * methodDesc)
{
    CONTRACTL {
        THROWS;
        GC_NOTRIGGER;
    } CONTRACTL_END;

    UNREACHABLE();
}

void ExecutionManager::AddJitManager(IJitManager * newjitmgr)
{
    LEAF_CONTRACT;

    // This is the first code manager added.
    if (!m_pJitList)
        m_pJitList = newjitmgr;
    // else walk the list.
    else
    {
        IJitManager *walker = m_pJitList;
        while (walker->m_next)
            walker = walker->m_next;
        walker->m_next = newjitmgr;
    }
}

#endif // #ifndef DACCESS_COMPILE


RangeSection* ExecutionManager::GetRangeSection(RangeSection *pHead, TADDR addr)
{
    WRAPPER_CONTRACT;
    STATIC_CONTRACT_SO_TOLERANT;

    RangeSection *pCurr = pHead;

#ifndef DACCESS_COMPILE
    RangeSection *pLastUsedRS = (pCurr != NULL) ? pCurr->pLastUsed : NULL;

    if ((pLastUsedRS != NULL)              &&
        (addr >= pLastUsedRS->LowAddress)  &&
        (addr <  pLastUsedRS->HighAddress)   )
    {
        return pLastUsedRS;
    }
#endif

    while (pCurr != NULL)
    {
        // See if addr is in [pCurr->LowAddress .. pCurr->HighAddress)
        if (pCurr->LowAddress <= addr)
        {
            // Since we are sorted, once pCurr->HighAddress is less than addr
            // then all subsequence ones will also be lower, so we are done.
            if (addr >= pCurr->HighAddress)
                break;
        
            // addr must be in [pCurr->LowAddress .. pCurr->HighAddress)
            _ASSERTE((pCurr->LowAddress <= addr) && (addr < pCurr->HighAddress));
        
            // Found the matching RangeSection
            
#ifndef DACCESS_COMPILE
            // Cache pCurr as pLastUsed in the head node
            // Unless we are on an MP system with many cpus
            // where this sort of caching actually diminishes scaling during server GC
            // due to many processors writing to a common location
            if (g_SystemInfo.dwNumberOfProcessors < 4 || !GCHeap::IsServerHeap() || !GCHeap::IsGCInProgress())
                pHead->pLastUsed = pCurr;
#endif
            
            return pCurr;
        }
        pCurr = pCurr->pnext;
    }

    return NULL;
}

RangeSection* ExecutionManager::GetRangeSectionAndPrev(RangeSection *pHead, TADDR addr, RangeSection** ppPrev)
{
    WRAPPER_CONTRACT;

    RangeSection *pCurr;
    RangeSection *pPrev;
    RangeSection *result = NULL;

    for (pPrev = NULL,  pCurr = pHead; 
         pCurr != NULL; 
         pPrev = pCurr, pCurr = pCurr->pnext)
    {
        // See if addr is in [pCurr->LowAddress .. pCurr->HighAddress)
        if (pCurr->LowAddress > addr)
            continue;

        if (addr >= pCurr->HighAddress)
            break;
        
        // addr must be in [pCurr->LowAddress .. pCurr->HighAddress)
        _ASSERTE((pCurr->LowAddress <= addr) && (addr < pCurr->HighAddress));
    
        // Found the matching RangeSection
        result = pCurr;

        // Write back pPrev to ppPrev if it is non-null
        if (ppPrev != NULL)
            *ppPrev = pPrev;

        break;
    }
    
    // If we failed to find a match write NULL to ppPrev if it is non-null
    if ((ppPrev != NULL) && (result == NULL))
    {
        *ppPrev = NULL;
    }

    return result;
}

RangeSection* ExecutionManager::GetRangeSectionForAddress(TADDR startAddress)
{
    WRAPPER_CONTRACT;

    ReaderLockHolder rlh;

    return GetRangeSection(m_CodeRangeList, startAddress);
}

/* static */
Module* ExecutionManager::FindZapModule(TADDR currentData)
{
    WRAPPER_CONTRACT;
    STATIC_CONTRACT_SO_TOLERANT;

    ReaderLockHolder rlh;

    RangeSection *pRS = GetRangeSection(m_DataRangeList, currentData);
    
    return (pRS == NULL) ? (Module*) NULL : pRS->pModule;
}

/* static */
Module* ExecutionManager::FindZapModuleForNativeCode(TADDR currentCode)
{
    WRAPPER_CONTRACT;

    ReaderLockHolder rlh;

    RangeSection *pRS = GetRangeSection(m_CodeRangeList, currentCode);

    return (pRS == NULL) ? (Module*) NULL : pRS->pModule;
}

#ifndef DACCESS_COMPILE

RangeSection * ExecutionManager::AddCodeRange(TADDR          pStartRange,
                                              TADDR          pEndRange,
                                              IJitManager *  pJit,
                                              TADDR          pTable,
                                              DWORD          flags,
                                              RangeSection * pColdRangeSection,
                                              Module*        pModule)
{
    CONTRACT(RangeSection *) {
        THROWS;
        GC_NOTRIGGER;
        PRECONDITION(CheckPointer((LPVOID)pStartRange));
        PRECONDITION(CheckPointer((LPVOID)pEndRange));
        PRECONDITION(CheckPointer(pJit));
        POSTCONDITION(CheckPointer(RETVAL));
    } CONTRACT_END;

    if (!(pStartRange && pEndRange && pJit))
        COMPlusThrowArgumentNull(L"AddCodeRange argument");

    RangeSection * result = AddRangeHelper(&m_CodeRangeList,
                                           pStartRange,
                                           pEndRange,
                                           pJit,
                                           pTable,
                                           flags,
                                           pColdRangeSection,
                                           pModule);


    RETURN (result);
}


RangeSection * ExecutionManager::AddDataRange(TADDR          pStartRange,
                                              TADDR          pEndRange,
                                              Module*        pModule)
{
    CONTRACT(RangeSection *) {
        THROWS;
        GC_NOTRIGGER;
        PRECONDITION(CheckPointer((LPVOID)pStartRange));
        PRECONDITION(CheckPointer((LPVOID)pEndRange));
        POSTCONDITION(CheckPointer(RETVAL));
    } CONTRACT_END;

    if (!(pStartRange && pEndRange))
       COMPlusThrowArgumentNull(L"AddDataRange argument");

    RETURN(AddRangeHelper(&m_DataRangeList,
                          pStartRange,
                          pEndRange,
                          NULL,
                          NULL,
                          NULL,
                          NULL,
                          pModule));
}

RangeSection * ExecutionManager::AddRangeHelper(RangeSection** ppRangeList,
                                                TADDR          pStartRange,
                                                TADDR          pEndRange,
                                                IJitManager *  pJit,
                                                TADDR          pTable,
                                                DWORD          flags,
                                                RangeSection * pColdRangeSection,
                                                Module*        pModule)
{
    CONTRACT(RangeSection *) {
        THROWS;
        GC_NOTRIGGER;
        PRECONDITION(CheckPointer(ppRangeList));
        PRECONDITION(CheckPointer((LPVOID)pStartRange));
        PRECONDITION(CheckPointer((LPVOID)pEndRange));
        POSTCONDITION(CheckPointer(RETVAL));
    } CONTRACT_END;

    ReaderLockHolder rlh;

    RangeSection *pnewrange = new RangeSection;

    _ASSERTE(pEndRange > pStartRange);

    pnewrange->LowAddress  = pStartRange;
    pnewrange->HighAddress = pEndRange;
    pnewrange->pjit        = pJit;
    pnewrange->ptable      = pTable;
    pnewrange->pnext       = NULL;
    pnewrange->flags       = flags;
    pnewrange->pcold       = pColdRangeSection;
    pnewrange->pModule     = pModule;
    pnewrange->pLastUsed   = NULL;

    {
        CrstHolder ch(&m_RangeCrst); // Acquire the Crst before linking in a new RangeList

        if (*ppRangeList != NULL)
        {
            RangeSection * current  = *ppRangeList;
            RangeSection * previous = NULL;
            
            while (true)
            {
                // Sort addresses top down so that more recently created ranges
                // will populate the top of the list
                if (pnewrange->LowAddress > current->LowAddress)
                {
                    if (previous == NULL) // insert new head
                    {
                        pnewrange->pnext = *ppRangeList;
                        *ppRangeList = pnewrange;
                    }
                    else // insert in the middle
                    {
                        pnewrange->pnext = current;
                        previous->pnext  = pnewrange;
                    }
                    // Asserts if ranges are overlapping
                    _ASSERTE(pnewrange->LowAddress > pnewrange->pnext->HighAddress);
                    break;
                }
                else if (current->pnext == NULL) // insert at end of list
                {
                    current->pnext = pnewrange;
                    break;
                }
                else  // Continue walking the RangeSection list
                {
                    previous = current;
                    current  = current->pnext;
                }
            }
        }
        else
        {
            *ppRangeList = pnewrange;
        }
    }

    RETURN(pnewrange);
}


// Deletes a single range starting at pStartRange
void ExecutionManager::DeleteCodeRange(TADDR pStartRange)
{
    WRAPPER_CONTRACT;
    DeleteRangeHelper(&m_CodeRangeList, pStartRange);
}

// Deletes a single range starting at pStartRange
void ExecutionManager::DeleteDataRange(TADDR pStartRange)
{
    WRAPPER_CONTRACT;
    DeleteRangeHelper(&m_DataRangeList, pStartRange);
}

// Deletes a single range starting at pStartRange
void ExecutionManager::DeleteRangeHelper(RangeSection** ppRangeList,
                                         TADDR pStartRange)
{
    CONTRACTL {
        NOTHROW;
        GC_NOTRIGGER;
    } CONTRACTL_END;

    WriterLockHolder wlh;        // Acquire the WriteLock and prevent any readers from walking the RangeList
    CrstHolder ch(&m_RangeCrst); // Acquire the Crst before unlinking a RangeList
    
    RangeSection *pCurr = NULL;
    RangeSection *pPrev = NULL;

    pCurr = GetRangeSectionAndPrev(*ppRangeList, pStartRange, &pPrev);
    
    // pCurr points at the Range that needs to be unlinked from the RangeList
    if (pCurr != NULL)
    {

        // If pPrev is NULL the the head of this list is to be deleted
        if (pPrev == NULL)
        {
            *ppRangeList = pCurr->pnext;          
        }
        else
        {
            _ASSERT(pPrev->pnext == pCurr);
        
            pPrev->pnext = pCurr->pnext;
        }

        // Clear the cache pLastUsed in the head node (if any)
        if (*ppRangeList)
        {
            (*ppRangeList)->pLastUsed = NULL;
        }

        delete pCurr;
    }
}

#endif // #ifndef DACCESS_COMPILE

#ifdef DACCESS_COMPILE

void ExecutionManager::EnumRangeList(RangeSection* list,
                                     CLRDataEnumMemoryFlags flags)
{
    while (list != NULL) 
    {
        DacEnumMemoryRegion(PTR_HOST_TO_TADDR(list), sizeof(*list));

        if (list->pjit.IsValid())
        {
            list->pjit->EnumMemoryRegions(flags);
        }
        if (list->pModule.IsValid())
        {
            list->pModule->EnumMemoryRegions(flags, true);
        }

        list = list->pnext;
    }
}

void ExecutionManager::EnumMemoryRegions(CLRDataEnumMemoryFlags flags)
{
    ReaderLockHolder rlh;

    //
    // Report the global data portions.
    //

    m_CodeRangeList.EnumMem();
    m_DataRangeList.EnumMem();
#ifndef FJITONLY
    m_pDefaultCodeMan.EnumMem();
#endif

    //
    // Walk structures and report.
    //

    if (m_CodeRangeList.IsValid())
    {
        EnumRangeList(m_CodeRangeList, flags);
    }
    if (m_DataRangeList.IsValid())
    {
        EnumRangeList(m_DataRangeList, flags);
    }
}
#endif // #ifdef DACCESS_COMPILE

#ifndef DACCESS_COMPILE
void ExecutionManager::preallocatedJumpStubBlock(BYTE * mem, DWORD blockSize, BaseDomain *pDomain)
{
    CONTRACTL {
        NOTHROW;
        GC_NOTRIGGER;
    } CONTRACTL_END;

    _ASSERTE(((size_t) mem % CODE_SIZE_ALIGN) == 0);
    _ASSERTE((sizeof(JumpStubBlockHeader) % CODE_SIZE_ALIGN) == 0);

    DWORD                  numJumps = (blockSize - sizeof(JumpStubBlockHeader)) / BACK_TO_BACK_JUMP_ALLOCATE_SIZE;
    JumpStubBlockHeader *  pBlock   = (JumpStubBlockHeader *)(mem);

    _ASSERTE(numJumps < MAX_M_ALLOCATED);

    {
        CrstHolder ch(&m_JumpStubCrst);

        pBlock->m_next      = m_jumpStubBlock;
        pBlock->m_used      = 0;
        pBlock->m_allocated = numJumps;
        pBlock->m_domain    = pDomain;
        pBlock->m_zero      = 0;

        m_jumpStubBlock     = pBlock;
        
        // We don't really use the ID field of the range list, so just give it anything that's not NULL.
        // (In the other case we give it a pointer to the EEJitManager.)
        JumpStubStubManager::g_pManager->GetRangeList()->AddRange(mem, mem + blockSize, (LPVOID)mem);
    }

    LOG((LF_ZAP, LL_INFO100, "preallocated JumpStubBlockHeader for %d stubs at" FMT_ADDR "\n",
         numJumps, DBG_ADDR(pBlock) ));
}

void ExecutionManager::unlinkPreallocatedJumpStubBlock(BYTE * mem, DWORD blockSize, BaseDomain *pDomain)
{
    CONTRACTL {
        NOTHROW;
        GC_NOTRIGGER;
    } CONTRACTL_END;

    _ASSERTE(((size_t) mem % CODE_SIZE_ALIGN) == 0);
    _ASSERTE((sizeof(JumpStubBlockHeader) % CODE_SIZE_ALIGN) == 0);

    JumpStubBlockHeader *  pBlockToUnlink;
    pBlockToUnlink = (JumpStubBlockHeader *)(mem);
    _ASSERTE(pBlockToUnlink->m_domain == pDomain);

    {
        CrstHolder ch(&m_JumpStubCrst);

        TADDR startAddr = (TADDR) mem;
        TADDR endAddr   = (TADDR) (mem + blockSize);

        deleteJumpStubBlockHelper(startAddr, endAddr);
    }

    LOG((LF_ZAP, LL_INFO100, "unlink the preallocated JumpStubBlockHeader at" FMT_ADDR "\n",
         DBG_ADDR(pBlockToUnlink) ));
}

void ExecutionManager::deleteJumpStubBlock (HeapList *pHp)
{
    CONTRACTL {
        NOTHROW;
        GC_NOTRIGGER;
        PRECONDITION(m_JumpStubCrst.OwnedByCurrentThread());
    } CONTRACTL_END;

    TADDR startAddr = pHp->startAddress;
    TADDR endAddr   = pHp->endAddress;

    ExecutionManager::deleteJumpStubBlockHelper(startAddr, endAddr);
}

void ExecutionManager::deleteJumpStubBlockHelper(TADDR startAddr, TADDR endAddr)
{
    CONTRACTL {
        NOTHROW;
        GC_NOTRIGGER;
        PRECONDITION(m_JumpStubCrst.OwnedByCurrentThread());
    } CONTRACTL_END;

    JumpStubBlockHeader *prevHeader = NULL;
    JumpStubBlockHeader *currHeader = m_jumpStubBlock;

    while (currHeader != NULL)
    {
        if (((TADDR)currHeader >= startAddr) && ((TADDR)currHeader < endAddr))
        {
            if (prevHeader == NULL)
            {
                // Remove currHeader from the head of this list
                m_jumpStubBlock = currHeader->m_next;
            }
            else
            {
                // Make preHeader skip over the currHeader
                prevHeader->m_next = currHeader->m_next;
            }

            //
            // Now we need to remove the matching entries
            //  in the JumpStubTable hashtable
            //
            for (unsigned i=0; i < currHeader->m_used; i++)
            {
                BYTE *  jumpStub  = (BYTE *) currHeader + sizeof(JumpStubBlockHeader) + ((size_t) i * BACK_TO_BACK_JUMP_ALLOCATE_SIZE);
                BYTE *  target    = decodeBackToBackJump(jumpStub);

                for (JumpStubTable::KeyIterator j = m_jumpStubTable->Begin(target), 
                    end = m_jumpStubTable->End(target); j != end; j++)
                {
                    if (j->m_jumpStub == jumpStub)
                    {
                        m_jumpStubTable->Remove(j);
                        break;
                    }
                }
            }
        }
        else
        {
            // update prevHeader
            prevHeader = currHeader;
        }
        currHeader = currHeader->m_next;
    }

    JumpStubStubManager::g_pManager->GetRangeList()->RemoveRanges(NULL,
                                                              (const BYTE*)startAddr, 
                                                              (const BYTE*)endAddr);
}

JumpStubBlockHeader * ExecutionManager::recoverJumpStubBlockHeader(BYTE * jumpStub)
{
    JumpStubBlockHeader * result = NULL;
    _ASSERTE(!"Unsupported target");

    // Sanity Check the fields of the JumpStubBlockHeader
    _ASSERTE(result->m_zero   == 0);
    _ASSERTE(result->m_domain != NULL);
    _ASSERTE(result->m_allocated < MAX_M_ALLOCATED);
    _ASSERTE(result->m_used <= result->m_allocated);

    return result;
}

BYTE * ExecutionManager::jumpStub(MethodDesc* pMD, BYTE * target,
                                  BYTE * loAddr,   BYTE * hiAddr,
                                  BaseDomain *pDomain)
{
    CONTRACT(BYTE *) {
        THROWS;
        GC_TRIGGERS;
        PRECONDITION(pDomain || NULL != pMD->GetDomain());
        PRECONDITION(loAddr < hiAddr);
        // This can't be checked - if a domain is provided, pMD may not be fully functional.
        //PRECONDITION(!pDomain || pDomain == pMD->GetDomain());
        POSTCONDITION(CheckPointer(RETVAL));
    } CONTRACT_END;

    BYTE *         jumpStub = NULL;
    IJitManager *  pJitMan  = ExecutionManager::GetJitForType(miManaged|miIL);

    if (pDomain == NULL)
        pDomain = pMD->GetDomain();

    {
        CrstHolder ch(&m_JumpStubCrst);

        for (JumpStubTable::KeyIterator i = m_jumpStubTable->Begin(target), 
            end = m_jumpStubTable->End(target); i != end; i++)
        {
            jumpStub = i->m_jumpStub;

                // Is the matching entry with the requested range?
                if ((jumpStub != NULL) && (loAddr <= jumpStub) && (jumpStub <= hiAddr))
                {
                    JumpStubBlockHeader * header = recoverJumpStubBlockHeader(jumpStub);

                    PREFIX_ASSUME(header != NULL);
                    
                    if (header->m_domain == pDomain)
                        goto DONE_RELEASE_LOCK;
                }
        }

        // If we get here we need to create a new jump stub
        // add or change the jump stub table to point at the new one
        jumpStub = getNextJumpStub(pMD, pJitMan, target, loAddr, hiAddr, pDomain);    // this statement can throw

        _ASSERTE((loAddr <= jumpStub) && (jumpStub <= hiAddr));

        JumpStubEntry entry;

        entry.m_target = target;
        entry.m_jumpStub = jumpStub;

        m_jumpStubTable->Add(entry);

        LOG((LF_JIT, LL_INFO10000, "Add JumpStub to" FMT_ADDR "at" FMT_ADDR "\n",
             DBG_ADDR(target), DBG_ADDR(jumpStub) ));

DONE_RELEASE_LOCK:;
    }
    RETURN(jumpStub);
}

BYTE * ExecutionManager::getNextJumpStub(MethodDesc* pMD, IJitManager* pJitMan, BYTE * target,
                                         BYTE * loAddr, BYTE * hiAddr, BaseDomain *pDomain)
{
    CONTRACT(BYTE *) {
        THROWS;
        GC_NOTRIGGER;
        PRECONDITION(m_JumpStubCrst.OwnedByCurrentThread());
        PRECONDITION(CheckPointer(pJitMan));
        POSTCONDITION(CheckPointer(RETVAL));
    } CONTRACT_END;

    BYTE *                 jumpStub = NULL;
    JumpStubBlockHeader *  curBlock = m_jumpStubBlock;

    if (pDomain == NULL)
        pDomain = pMD->GetDomain();

    while (curBlock)
    {
        if ((curBlock->m_used < curBlock->m_allocated) && (pDomain == curBlock->m_domain))
        {
            jumpStub = (BYTE *) curBlock + sizeof(JumpStubBlockHeader) + ((size_t) curBlock->m_used * BACK_TO_BACK_JUMP_ALLOCATE_SIZE);

            if ((loAddr <= jumpStub) && (jumpStub <= hiAddr))
            {
                goto DONE;
            }
        }

        curBlock = curBlock->m_next;
    }

    // If we get here then we need to allocate a new JumpStubBlock

    // this can throw an OM exception
    curBlock = pJitMan->allocJumpStubBlock(pMD, 32, loAddr, hiAddr, pDomain);

    jumpStub = (BYTE *) curBlock + sizeof(JumpStubBlockHeader) + ((size_t) curBlock->m_used * BACK_TO_BACK_JUMP_ALLOCATE_SIZE);

    if ((loAddr > jumpStub) || (jumpStub > hiAddr))
    {
        _ASSERTE(!"allocJumpStubBlock block was not in expected range");        
        EEPOLICY_HANDLE_FATAL_ERROR(COR_E_EXECUTIONENGINE);
    }

    curBlock->m_next = m_jumpStubBlock;
    m_jumpStubBlock = curBlock;

DONE:

    _ASSERTE((curBlock->m_used < curBlock->m_allocated));

    curBlock->m_used++;

    emitBackToBackJump(jumpStub, (void*) target);

    RETURN(jumpStub);
}
#endif // #ifndef DACCESS_COMPILE


#ifndef DACCESS_COMPILE

//**************************************************
// Helpers
//**************************************************

inline DWORD MIN (DWORD a, DWORD b)
{
    LEAF_CONTRACT;

    if (a < b)
        return a;
    else
        return b;
}


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

size_t EEJitManager::GetCodeHeapCacheSize (size_t bAllocationRequest)
{
    LEAF_CONTRACT;

    return ((bAllocationRequest/CACHE_BLOCK_SIZE)+1) * sizeof (HashEntry);
}

void EEJitManager::AddRangeToJitHeapCache (TADDR startAddr, TADDR endAddr, HeapList *pHp)
{
    CONTRACTL {
        NOTHROW;
        GC_NOTRIGGER;
        PRECONDITION(m_CodeHeapCritSec.OwnedByCurrentThread());
        PRECONDITION (((size_t)(pHp->startAddress -  (pHp->pHeap->GetReservedPrivateData() + pHp->bCacheSpaceSize)) & CACHE_BLOCK_MASK) == 0);
        PRECONDITION (pHp->pHeap->GetHeapStartAddress() && (((size_t)pHp->pHeap->GetHeapStartAddress() & CACHE_BLOCK_MASK) == 0));
    } CONTRACTL_END;

    HashEntry* hashEntry = NULL;

    size_t currHashKey = COMPUTE_HASH_KEY((size_t)startAddr);
    size_t cacheSpaceSizeLeft = pHp->bCacheSpaceSize;
    PBYTE cacheSpacePtr = pHp->pCacheSpacePtr;
    while ((currHashKey < (size_t)endAddr) && (cacheSpaceSizeLeft > 0))
    {
        _ASSERTE ((cacheSpaceSizeLeft % sizeof (HashEntry)) == 0);
        _ASSERTE (cacheSpacePtr && "Cache ptr and size out of sync");

        DWORD index = GET_CACHE_INDEX(currHashKey);

        hashEntry = new (cacheSpacePtr) HashEntry;
        hashEntry->hashKey = currHashKey;
        hashEntry->pHp = pHp;
        hashEntry->pNext = m_JitCodeHashTable[index];
        m_JitCodeHashTable[index] = hashEntry;
        currHashKey += CACHE_BLOCK_SIZE;
        LOG((LF_SYNC, LL_INFO1000, "AddRangeToJitHeapCache: %0x\t%0x\t%0x\n", index, currHashKey, pHp));

        cacheSpacePtr += sizeof (HashEntry);
        cacheSpaceSizeLeft -= sizeof (HashEntry);
    }

    pHp->bCacheSpaceSize = cacheSpaceSizeLeft;
    pHp->pCacheSpacePtr  = cacheSpacePtr;

}

void EEJitManager::DeleteJitHeapCache (HeapList *pHp)
{
    CONTRACTL {
        NOTHROW;
        GC_NOTRIGGER;
        PRECONDITION(m_CodeHeapCritSec.OwnedByCurrentThread());
    } CONTRACTL_END;

    // If the following condition is not true then this heap node was not inserted in the cache
    _ASSERTE (pHp->pHeap->GetHeapStartAddress());
    if (((size_t)pHp->pHeap->GetHeapStartAddress() & CACHE_BLOCK_MASK) != 0)
        return;

    TADDR startAddr = pHp->startAddress;
    TADDR endAddr = pHp->startAddress+pHp->maxCodeHeapSize;

    size_t currHashKey = COMPUTE_HASH_KEY((size_t)startAddr);
    while (currHashKey < (size_t)endAddr)
    {
        DWORD index = GET_CACHE_INDEX(currHashKey);

        HashEntry *hashEntry = m_JitCodeHashTable[index];
        _ASSERTE (hashEntry && "JitHeapCache entry not found");
        if (hashEntry && (hashEntry->hashKey == currHashKey))
        {
            m_JitCodeHashTable[index] = hashEntry->pNext;
            hashEntry->pNext = m_pJitHeapCacheUnlinkedList;
            m_pJitHeapCacheUnlinkedList = hashEntry;
        }
        else
        {
            // We are guaranteed to find all the sub heaps in the collision lists.
            _ASSERTE (hashEntry && hashEntry->pNext && "JitHeapCache entry not found");
            while (hashEntry && hashEntry->pNext && (hashEntry->pNext->hashKey != currHashKey))
            {
                hashEntry = hashEntry->pNext;
                _ASSERTE (hashEntry && hashEntry->pNext && "JitHeapCache entry not found");
            }
            if (hashEntry && hashEntry->pNext && (hashEntry->pNext->hashKey == currHashKey))
            {
                HashEntry *ptmpEntry = hashEntry->pNext;
                hashEntry->pNext = hashEntry->pNext->pNext;
                ptmpEntry->pNext = m_pJitHeapCacheUnlinkedList;
                m_pJitHeapCacheUnlinkedList = ptmpEntry;
            }
        }
        currHashKey += CACHE_BLOCK_SIZE;
        LOG((LF_SYNC, LL_INFO1000, "UnlinkJitHeapCache: %0x\t%0x\t%0x\n", index, currHashKey, hashEntry));
    }
}

#ifdef _DEBUG

BOOL EEJitManager::DebugContainedInHeapList (HeapList *pHashEntryHp)
{
    LEAF_CONTRACT;
    HeapList *pHp = GetVolatile_pCodeHeap();
    while (pHp)
    {
        if (pHp == pHashEntryHp)
            return TRUE;
        pHp = pHp->GetVolatile_hpNext();
    }
    return FALSE;
}

void EEJitManager::DebugCheckJitHeapCacheValidity ()
{
    CONTRACTL {
        NOTHROW;
        GC_NOTRIGGER;
    } CONTRACTL_END;

    HeapList *pHp = GetVolatile_pCodeHeap();
    while (pHp)
    {

        TADDR startAddr = pHp->startAddress;
        TADDR endAddr = pHp->startAddress+pHp->maxCodeHeapSize;

        size_t currHashKey = COMPUTE_HASH_KEY((size_t)startAddr);
        while (currHashKey < (size_t)endAddr)
        {
            DWORD index = GET_CACHE_INDEX(currHashKey);

            HashEntry *hashEntry = m_JitCodeHashTable[index];
            _ASSERTE (hashEntry && "JitHeapCache entry not found");
            if (hashEntry && (hashEntry->hashKey == currHashKey))
            {
                // found the entry
            }
            else
            {
                // We are guaranteed to find all the sub heaps in the collision lists.
                _ASSERTE (hashEntry && hashEntry->pNext && "JitHeapCache entry not found");
                while (hashEntry && (hashEntry->hashKey != currHashKey))
                {
                    hashEntry = hashEntry->pNext;
                }
                _ASSERTE (hashEntry && "JitHeapCache entry not found");
            }
            currHashKey += CACHE_BLOCK_SIZE;
        }
        pHp = pHp->GetVolatile_hpNext();
    }

    for (unsigned int i=0; i<HASH_BUCKETS; i++)
    {
        HashEntry *hashEntry = m_JitCodeHashTable[i];
        while (hashEntry)
        {
            if (!DebugContainedInHeapList (hashEntry->pHp))
            {
                _ASSERTE (!"Inconsistent JitHeapCache found");
            }
            hashEntry = hashEntry->pNext;
        }
    }

}
#endif // _DEBUG

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

#endif // #ifndef DACCESS_COMPILE

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