A
download ceemain.cpp
Language: C++
Copyright: (c) 2006 Microsoft Corporation. All rights reserved.
LOC: 1851
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
// ==++==
//
//   
//    Copyright (c) 2006 Microsoft Corporation.  All rights reserved.
//   
//    The use and distribution terms for this software are contained in the file
//    named license.txt, which can be found in the root of this distribution.
//    By using this software in any fashion, you are agreeing to be bound by the
//    terms of this license.
//   
//    You must not remove this notice, or any other, from this software.
//   
//
// ==--==
// ===========================================================================
// File: CEEMAIN.CPP
//
// ===========================================================================

#include "common.h"

// Declare global variables
#define DECLARE_DATA
#include "vars.hpp"
#include "veropcodes.hpp"
#undef DECLARE_DATA

#include "dbgalloc.h"
#include "log.h"
#include "ceemain.h"
#include "clsload.hpp"
#include "object.h"
#include "hash.h"
#include "ecall.h"
#include "ceemain.h"
#include "dllimport.h"
#include "syncblk.h"
#include "comstring.h"
#include "comsystem.h"
#include "eeconfig.h"
#include "stublink.h"
#include "handletable.h"
#include "method.hpp"
#include "codeman.h"
#include "gcscan.h"
#include "frames.h"
#include "threads.h"
#include "stackwalk.h"
#include "gc.h"
#include "interoputil.h"
#include "security.h"
#include "fieldmarshaler.h"
#include "dbginterface.h"
#include "eedbginterfaceimpl.h"
#include "debugdebugger.h"
#include "cordbpriv.h"
#include "remoting.h"
#include "comdelegate.h"
#include "appdomain.hpp"
#include "perfcounters.h"
#include "rwlock.h"
#include "ipcmanagerinterface.h"
#include "eventtrace.h"
#include "timeline.h"
#include "internaldebug.h"
#include "corhost.h"
#include "binder.h"
#include "olevariant.h"
#include "comcallablewrapper.h"
#include "apithreadstress.h"
#include "ipcfunccall.h"
#include "perflog.h"
#include "../dlls/mscorrc/resource.h"
#include "comnlsinfo.h"
#include "util.hpp"
#include "shimload.h"
#include "comthreadpool.h"
#include "stackprobe.h"
#include "posterror.h"
#include "timeline.h"
#include "memoryreport.h"
#include "virtualcallstub.h"
#include "strongname.h"
#include "syncclean.hpp"
#include "typeparse.h"
#include "debuginfostore.h"
#include "mdaassistants.h"
#include "eemessagebox.h"




#ifdef PROFILING_SUPPORTED
#include "proftoeeinterfaceimpl.h"
#endif // PROFILING_SUPPORTED

#include "mdaassistants.h"

HRESULT RunDllMain(MethodDesc *pMD, HINSTANCE hInst, DWORD dwReason, LPVOID lpReserved);

static HRESULT InitializeIPCManager(void);
static void TerminateIPCManager(void);

static int GetThreadUICultureId();

static HRESULT GetThreadUICultureNames(__out_ecount(cchCultureName) LPWSTR wszCultureName, SIZE_T cchCultureName,
                                   __out_ecount(cchParentCultureName) LPWSTR wszParentCultureName, SIZE_T cchParentCultureName);

HRESULT EEStartup(COINITIEE fFlags);
extern "C" HRESULT STDMETHODCALLTYPE InitializeFusion();

HRESULT PrepareExecuteDLLForThunk(HINSTANCE hInst,
                                  DWORD dwReason,
                                  LPVOID lpReserved);
BOOL STDMETHODCALLTYPE ExecuteDLL(HINSTANCE hInst,
                                  DWORD dwReason,
                                  LPVOID lpReserved,
                                  BOOL fFromThunk);
BOOL STDMETHODCALLTYPE ExecuteEXE(HMODULE hMod);
BOOL STDMETHODCALLTYPE ExecuteEXE(__in LPWSTR pImageNameIn);

static void InitializeEventTracing();

static HRESULT InitializeGarbageCollector();

void InitFastInterlockOps(); // cgenxxx.cpp

#ifdef DEBUGGING_SUPPORTED
static void InitializeDebugger(void);
static void TerminateDebugger(void);
extern "C" HRESULT __cdecl CorDBGetInterface(DebugInterface** rcInterface);
static void GetDbgProfControlFlag();
#endif // DEBUGGING_SUPPORTED

HRESULT InitializeDebugStore();
void TerminateDebugStore();

#ifdef PROFILING_SUPPORTED
static HRESULT InitializeProfiling();
static void TerminateProfiling(BOOL fProcessDetach);
#endif // PROFILING_SUPPORTED

// Remember how the last startup of EE went.
HRESULT g_EEStartupStatus = S_OK;

// Flag indicating if the EE has been started.
BOOL    g_fEEStarted = FALSE;

// Flag indicating if the EE should be suspended on shutdown.
BOOL    g_fSuspendOnShutdown = FALSE;

// Event to synchronize EE shutdown.
static CLREvent * g_pEEShutDownEvent;

// ---------------------------------------------------------------------------
// %%Function: EnsureEEStarted()
//
// Description: Ensure the CLR is started.
// ---------------------------------------------------------------------------
HRESULT EnsureEEStarted(COINITIEE flags)
{
    CONTRACTL
    {
        NOTHROW;
        GC_TRIGGERS;
        MODE_PREEMPTIVE;
        ENTRY_POINT;
    }
    CONTRACTL_END;

    if (g_fEEShutDown)
        return E_FAIL;

    HRESULT hr = E_FAIL;

    // On non x86 platforms, when we load mscorlib.dll during EEStartup, we will
    // re-enter _CorDllMain with a DLL_PROCESS_ATTACH for mscorlib.dll. We are
    // far enough in startup that this is allowed, however we don't want to
    // re-start the startup code so we need to check to see if startup has
    // been initiated or completed before we call EEStartup. We do however want to
    // make sure other threads block until the EE is started.
    if (!g_fEEStarted)
    {
	BEGIN_ENTRYPOINT_NOTHROW;


        IHostTaskManager *pHostTaskManager = CorHost2::GetHostTaskManager();
        if (pHostTaskManager)
        {
            BEGIN_SO_TOLERANT_CODE_CALLING_HOST(GetThread());
            pHostTaskManager->BeginThreadAffinity();
            END_SO_TOLERANT_CODE_CALLING_HOST;
        }

        volatile static LONG fOnlyOne = 0;

        BOOL bStarted=FALSE;

        while (FastInterlockExchange(&fOnlyOne, 1) == 1)
        {
            __SwitchToThread(0);
        }

        // Now that we've acquired the lock, check again to make sure we aren't in
        // the process of starting the CLR or that it hasn't already been fully started.
        // At this point, if startup has been inited we don't have anything more to do.
        // And if EEStartup already failed before, we don't do it again.
        if (!g_fEEStarted && !g_fEEInit && SUCCEEDED (g_EEStartupStatus))
        {
            EEStartup(flags);
            bStarted=g_fEEStarted;
            hr = g_EEStartupStatus;
        }
        else
        {
            hr = g_EEStartupStatus;
            if (SUCCEEDED(g_EEStartupStatus))
            {
                hr = S_FALSE;
            }
        }

        fOnlyOne = 0;

        if (pHostTaskManager)
        {
            BEGIN_SO_TOLERANT_CODE_CALLING_HOST(GetThread());
            pHostTaskManager->EndThreadAffinity();
            END_SO_TOLERANT_CODE_CALLING_HOST;
        }
        END_ENTRYPOINT_NOTHROW;
    }
    else
    {
        hr = g_EEStartupStatus;
        if (SUCCEEDED(g_EEStartupStatus))
        {
            hr = S_FALSE;
        }
    }

    return hr;
}

// ---------------------------------------------------------------------------
// %%Function: ForceEEShutdown()
//
// Description: Force the EE to shutdown now.
// ---------------------------------------------------------------------------
void ForceEEShutdown()
{
    WRAPPER_CONTRACT;

    // Don't bother to take the lock for this case.

    STRESS_LOG0(LF_STARTUP, INFO3, "EEShutdown invoked from ForceEEShutdown");
    EEPolicy::HandleExitProcess();
}

// This is our Ctrl-C, Ctrl-Break, etc. handler.
static BOOL WINAPI DbgCtrlCHandler(DWORD dwCtrlType)
{
    WRAPPER_CONTRACT;
    STATIC_CONTRACT_SO_TOLERANT;

#ifdef DEBUGGING_SUPPORTED
    if (CORDebuggerAttached() &&
        (dwCtrlType == CTRL_C_EVENT || dwCtrlType == CTRL_BREAK_EVENT))
    {
        return g_pDebugInterface->SendCtrlCToDebugger(dwCtrlType);
    }
    else
#endif // DEBUGGING_SUPPORTED
    {
        g_fInControlC = true;     // only for weakening assertions in checked build.
        return FALSE;               // keep looking for a real handler.
    }
}

// A host can specify that it only wants one version of hosting interface to be used.
BOOL g_singleVersionHosting;

// ---------------------------------------------------------------------------
// %%Function: GetStartupInformation
//
// Get Configuration Information
// ---------------------------------------------------------------------------
typedef HRESULT (STDMETHODCALLTYPE* pGetHostConfigurationFile)(LPCWSTR, SIZE_T*);
HRESULT GetStartupInformation()
{
    CONTRACTL {
        NOTHROW;
        GC_TRIGGERS;
        MODE_ANY;
        INJECT_FAULT(return E_OUTOFMEMORY);
    } CONTRACTL_END;
     GCHeap::InitializeHeapType(false);
    return S_OK;
}


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


void InitGSCookie()
{
    GSCookie * pGSCookiePtr = GetProcessGSCookiePtr();

    DWORD oldProtection;
    ClrVirtualProtect((LPVOID)pGSCookiePtr, sizeof(GSCookie), PAGE_EXECUTE_READWRITE, &oldProtection);

    GSCookie val = (GSCookie)GetTickCount();

#ifdef _DEBUG
    // In _DEBUG, always use the same value to make it easier to search for the cookie
    val = (GSCookie) WIN64_ONLY(0x9ABCDEF012345678) NOT_WIN64(0x12345678);
#endif

    // To test if it is initialized. Also for ICorMethodInfo::getGSCookie()
    if (val == 0)
        val ++;
    *pGSCookiePtr = val;

    ClrVirtualProtect((LPVOID)pGSCookiePtr, sizeof(GSCookie), oldProtection, &oldProtection);
}


// ---------------------------------------------------------------------------
// %%Function: EEStartupHelper
//
// Parameters:
//  fFlags                  - Initialization flags for the engine.  See the
//                              EEStartupFlags enumerator for valid values.
//
// Returns:
//  S_OK                    - On success
//
// Description:
//  Reserved to initialize the EE runtime engine explicitly.
// ---------------------------------------------------------------------------

#ifndef IfFailGotoLog
#define IfFailGotoLog(EXPR, LABEL) \
do { \
    hr = (EXPR);\
    if(FAILED(hr)) { \
        STRESS_LOG2(LF_STARTUP, LL_ALWAYS, "%s failed with code %x", #EXPR, hr);\
        goto LABEL; \
    } \
    else \
       STRESS_LOG1(LF_STARTUP, LL_ALWAYS, "%s completed", #EXPR);\
} while (0)
#endif

#ifndef IfFailGoLog
#define IfFailGoLog(EXPR) IfFailGotoLog(EXPR, ErrExit)
#endif

void EEStartupHelper(COINITIEE fFlags)
{
    CONTRACTL
    {
        THROWS;
        GC_TRIGGERS;
        MODE_ANY;
    } CONTRACTL_END;

    HRESULT hr = S_OK;
    static ConfigDWORD breakOnEELoad;
    BOOL    initEEConfig = FALSE;
    EX_TRY
    {
#ifdef _DEBUG
    DisableGlobalAllocStore();
#endif //_DEBUG
    g_fEEInit = true;

    ::SetConsoleCtrlHandler(DbgCtrlCHandler, TRUE/*add*/);

    // Initialize event tracing early so we can trace CLR startup time events.
    InitializeEventTracing();

    ETWTraceStartup trace(ETW_TYPE_STARTUP_EESTARTUP);
    TIMELINE_AUTO(STARTUP, "EEStartup");

    // Give PerfMon a chance to hook up to us
    // Do this both *before* and *after* ipcman init so corperfmonext.dll
    // has a chance to release stale private blocks that IPCMan could collide with.
    // do this early to maximize window between perfmon refresh and ipc block creation.
    IPCFuncCallSource::DoThreadSafeCall();

    InitGSCookie();
    Frame::Init();


    // Initialize EEConfig
    if (!g_pConfig)
    {
        IfFailGo(EEConfig::Setup());
        initEEConfig = TRUE;
    }
    // Go get configuration information this is necessary
    // before the EE has started. This will also get any host-supplied
    // configuration file, which EEConfig can then use.
    GetStartupInformation();

    // get any configuration information from the registry
    if (initEEConfig)
        IfFailGo(g_pConfig->SetupConfiguration());


#ifdef STRESS_LOG
    if (REGUTIL::GetConfigDWORD(L"StressLog", g_pConfig->StressLog ()) != 0) {
        unsigned facilities = REGUTIL::GetConfigDWORD(L"LogFacility", LF_ALL);
        unsigned level = REGUTIL::GetConfigDWORD(L"LogLevel", LL_INFO1000);
        unsigned bytesPerThread = REGUTIL::GetConfigDWORD(L"StressLogSize", STRESSLOG_CHUNK_SIZE * 4);
        unsigned totalBytes = REGUTIL::GetConfigDWORD(L"TotalStressLogSize", STRESSLOG_CHUNK_SIZE * 1024);
        StressLog::Initialize(facilities, level, bytesPerThread, totalBytes, GetModuleInst());
        g_pStressLog = &StressLog::theLog;
    }
#endif

#ifdef LOGGING
    InitializeLogging();
#endif

#ifdef ENABLE_PERF_LOG
    PerfLog::PerfLogInitialize();
#endif //ENABLE_PERF_LOG

    STRESS_LOG0(LF_STARTUP, LL_ALWAYS, "===================EEStartup Starting===================");



    // SString
    SString::Startup();

    // Fusion
    {
        ETWTraceStartup traceFusion(ETW_TYPE_STARTUP_FUSIONINIT);
        IfFailGoLog(InitializeFusion());
    }


#if ENABLE_TIMELINE
    Timeline::Startup();
#endif

    InitEventStore();

    if (g_pConfig != NULL)
    {
        IfFailGoLog(g_pConfig->sync());        
    }

    if (breakOnEELoad.val(L"BreakOnEELoad", 0) == 1)
    {
#ifdef _DEBUG
        _ASSERTE(!"Start loading EE!");
#else
                DebugBreak();
#endif
        }




    // Initialize all our InterProcess Communications with COM+
    IfFailGoLog(InitializeIPCManager());

#ifdef ENABLE_PERF_COUNTERS
    hr = PerfCounters::Init();
    _ASSERTE(SUCCEEDED(hr));
    IfFailGo(hr);
#endif


    StubManager::InitializeStubManagers();

    IfFailGoLog(InitializeDebugStore());

    // Set up the cor handle map. This map is used to load assemblies in
    // memory instead of using the normal system load
    PEImage::Startup();


    EECodeInfo::Init();
    HardCodedMetaSig::Init();
    Stub::Init();
    StubLinkerCPU::Init();

  // weak_short, weak_long, strong; no pin
    Ref_Initialize();

    // Initialize remoting
    CRemotingServices::Initialize();

    // Initialize contexts
    Context::Initialize();

    InitThreadManager();
    STRESS_LOG0(LF_STARTUP, LL_ALWAYS, "Returned successfully from InitThreadManager");


    g_pEEShutDownEvent = new CLREvent();
    g_pEEShutDownEvent->CreateManualEvent(FALSE);

    // Initialize RWLocks
    CRWLock::ProcessInit();

    // Initialize debugger manager
    CCLRDebugManager::ProcessInit();


#ifdef DEBUGGING_SUPPORTED
    // Check the debugger/profiling control environment variable to
    // see if there's any work to be done.
    GetDbgProfControlFlag();
#endif // DEBUGGING_SUPPORTED

    if (!VirtualCallStubManager::InitStatic())
        IfFailGoLog(E_FAIL);

    GCInterface::m_MemoryPressureLock.Init("MemoryPressure", CrstGCMemoryPressure);

    // Setup the domains. Threads are started in a default domain.
    SystemDomain::Attach();

#ifdef DEBUGGING_SUPPORTED
    // Initialize the debugging services. This must be done before any
    // EE thread objects are created, and before any classes or
    // modules are loaded.
    InitializeDebugger(); // throws on error
#endif // DEBUGGING_SUPPORTED


#ifdef PROFILING_SUPPORTED
    // Initialize the profiling services.
    hr = InitializeProfiling();

    _ASSERTE(SUCCEEDED(hr));
    IfFailGo(hr);
#endif // PROFILING_SUPPORTED

    InitializeExceptionHandling();
    //
    // Install our global exception filter
    //
    InstallUnhandledExceptionFilter();

    // throws on error
    SetupThread();

    // Give PerfMon a chance to hook up to us
    // Do this both *before* and *after* ipcman init so corperfmonext.dll
    // has a chance to release stale private blocks that IPCMan could collide with.
    IPCFuncCallSource::DoThreadSafeCall();
    STRESS_LOG0(LF_STARTUP, LL_ALWAYS, "Returned successfully from second call to  IPCFuncCallSource::DoThreadSafeCall");

    InitPreStubManager();


    NDirect::Init();

    // Before setting up the execution manager initialize the first part
    // of the JIT helpers.
    InitJITHelpers1();
    InitJITHelpers2();

    SyncBlockCache::Attach();

    // Start up the EE intializing all the global variables
    ECall::Init();

    UMThunkInit();

    COMDelegate::Init();

    // Set up the sync block
    SyncBlockCache::Start();

    StackwalkCache::Init();

    ExecutionManager::Init();
    HostCodeHeap::Init();

    if (!COMNlsInfo::InitializeNLS())
        IfFailGo(E_FAIL);

    // Start up security
    Security::Start();

    AppDomain::CreateADUnloadStartEvent();

    CpuStoreBufferControl::Init();
    
    IfFailGoLog(InitializeGarbageCollector());

    InitializePinHandleTable();


    SystemDomain::System()->Init();

#ifdef PROFILING_SUPPORTED

    SystemDomain::NotifyProfilerStartup();
#endif // PROFILING_SUPPORTED

    if (CLRHosted()
#ifdef _DEBUG
        || ((fFlags & COINITEE_DLL) == 0 &&
            g_pConfig->GetHostTestADUnload())
#endif
        ) {
        // If we are hosted, a host may specify unloading AD when a managed allocation in
        // critical region fails.  We need to precreate a thread to unload AD.
        AppDomain::CreateADUnloadWorker();
    }

    g_fEEInit = false;

    SystemDomain::System()->DefaultDomain()->LoadSystemAssemblies();

    SystemDomain::System()->DefaultDomain()->SetupSharedStatics();

#ifdef DEBUGGING_SUPPORTED

    LOG((LF_CORDB | LF_SYNC | LF_STARTUP, LL_INFO1000, "EEStartup: adding default domain 0x%x\n",
        SystemDomain::System()->DefaultDomain()));

    // Make a call to publish the DefaultDomain for the debugger, etc
        SystemDomain::System()->PublishAppDomainAndInformDebugger(SystemDomain::System()->DefaultDomain());
#endif // DEBUGGING_SUPPORTED

#ifdef _DEBUG
    APIThreadStress::SetThreadStressCount(g_pConfig->GetAPIThreadStressCount());
#endif

    // Perform any once-only SafeHandle initialization.
    SafeHandle::Init();

    // Load mscorsn.dll if the app requested the legacy mode in its configuration file.
    if (g_pConfig->LegacyLoadMscorsnOnStartup())
        IfFailGo(LoadMscorsn());

    g_fEEStarted = TRUE;
    g_EEStartupStatus = S_OK;
    hr = S_OK;
    STRESS_LOG0(LF_STARTUP, LL_ALWAYS, "===================EEStartup Completed===================");

#ifdef _DEBUG
    // Perform mscorlib consistency check if requested
    Binder::CheckMscorlibExtended();
#endif

#if defined(STACK_GUARDS_DEBUG)
    // now we can start stack probing.
    InitStackProbes();
#elif defined(STACK_GUARDS_RELEASE)
    InitStackProbesRetail();
#endif

ErrExit: ;
    }
    EX_CATCH
    {
    }
    EX_END_CATCH(SwallowAllExceptions)

    if (!g_fEEStarted) {
        if (g_fEEInit)
            g_fEEInit = false;

        if (!FAILED(hr))
            hr = E_FAIL;

        g_EEStartupStatus = hr;
    }

    if (breakOnEELoad.val(L"BreakOnEELoad", 0) == 2)
    {
#ifdef _DEBUG
        _ASSERTE(!"Done loading EE!");
#else
        DebugBreak();
#endif
    }

}

LONG FilterStartupException(PEXCEPTION_POINTERS p, PVOID pv)
{
    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
        MODE_ANY;
        PRECONDITION(CheckPointer(p));
        PRECONDITION(CheckPointer(pv));
    } CONTRACTL_END;

    g_EEStartupStatus = (HRESULT)p->ExceptionRecord->ExceptionInformation[0];

    // Make sure we got a failure code in this case
    if (!FAILED(g_EEStartupStatus))
        g_EEStartupStatus = E_FAIL;

    // Initializations has failed so reset the g_fEEInit flag.
    g_fEEInit = false;

    if (p->ExceptionRecord->ExceptionCode == BOOTUP_EXCEPTION_COMPLUS)
    {
        // Don't ever handle the exception in a checked build
#ifndef _DEBUG
        return EXCEPTION_EXECUTE_HANDLER;
#endif
    }

    return EXCEPTION_CONTINUE_SEARCH;
}

HRESULT EEStartup(COINITIEE fFlags)
{
    // Cannot use normal contracts here because of the PAL_TRY.
    STATIC_CONTRACT_NOTHROW;

    _ASSERTE(!g_fEEStarted && !g_fEEInit && SUCCEEDED (g_EEStartupStatus));

    PAL_TRY
    {
        EEStartupHelper(fFlags);
    }
    PAL_EXCEPT_FILTER (FilterStartupException, NULL)
    {
        // The filter should have set g_EEStartupStatus to a failure HRESULT.
        _ASSERTE(FAILED(g_EEStartupStatus));
    }
    PAL_ENDTRY

    if(SUCCEEDED(g_EEStartupStatus) && (fFlags & COINITEE_MAIN) == 0)
        g_EEStartupStatus = SystemDomain::SetupDefaultDomainNoThrow();

    return g_EEStartupStatus;
}





STDAPI ClrCreateManagedInstance(LPCWSTR typeName,
                                REFIID riid,
                                LPVOID FAR *ppv)
{

    CONTRACTL
    {
        NOTHROW;
        GC_TRIGGERS;
        MODE_PREEMPTIVE;
        ENTRY_POINT;
        PRECONDITION(CheckPointer(ppv, NULL_OK));
        PRECONDITION(CheckPointer(typeName, NULL_OK));
    } CONTRACTL_END;

    HRESULT hr = S_OK;
   
    if (ppv == NULL)
        return E_POINTER;

    if (typeName == NULL)
        return E_INVALIDARG;

    MAKE_UTF8PTR_FROMWIDE(pName, typeName);

    IfFailRet(CoInitializeEE(0));


    BOOL fCtorAlreadyCalled = FALSE;
    OBJECTREF       newobj = NULL;
    MethodTable *pMT = NULL;


    // Retrieve the current thread.
    BEGIN_EXTERNAL_ENTRYPOINT(&hr)

    pMT = TypeName::GetTypeUsingCASearchRules(pName, FALSE).GetMethodTable();

    if (!pMT)
        hr = CLASS_E_CLASSNOTAVAILABLE;
    else
    {
        pMT->EnsureInstanceActive();
        if (!pMT->HasPublicDefaultConstructor())
        {
            hr = COR_E_MEMBERACCESS;
        }
        else
        {
            // Call class init if necessary
            pMT->CheckRunClassInitThrowing();
        }
    }

    // If we failed return
    IfFailGo(hr);

    if (CRemotingServices::RequiresManagedActivation(TypeHandle(pMT)) != NoManagedActivation)
    {
        fCtorAlreadyCalled = TRUE;
        newobj = CRemotingServices::CreateProxyOrObject(pMT, TRUE);
    }
    else
    {
        newobj = pMT->Allocate();
    }

    GCPROTECT_BEGIN(newobj);

    // don't call any constructors if we already have called them
    if (!fCtorAlreadyCalled)
        CallDefaultConstructor(newobj);

    // return the tear-off
    SafeComHolder<IUnknown> punk(GetComIPFromObjectRef(&newobj));
    hr = punk->QueryInterface(riid, ppv);

    GCPROTECT_END();

    // If we failed return
    IfFailGo(hr);


ErrExit: ;
    END_EXTERNAL_ENTRYPOINT;

    return hr;
}



//---------------------------------------------------------------------------
// %%Function: void STDMETHODCALLTYPE CorExitProcess(int exitCode)
//
// Parameters:
//  int exitCode :: process exit code
//
// Returns:
//  Nothing
//
// Description:
//  COM Objects shutdown stuff should be done here
// ---------------------------------------------------------------------------
extern "C" void STDMETHODCALLTYPE CorExitProcess(int exitCode)
{

    CONTRACT_VIOLATION(GCViolation | ModeViolation);
    CONTRACTL {
        NOTHROW;
        GC_TRIGGERS;
        MODE_PREEMPTIVE;
        ENTRY_POINT;
    } CONTRACTL_END;

    if (g_fEEShutDown || !g_fEEStarted)
        return;

    HRESULT hr;
    BEGIN_EXTERNAL_ENTRYPOINT(&hr)

    // The exit code for the process is communicated in one of two ways.  If the
    // entrypoint returns an 'int' we take that.  Otherwise we take a latched
    // process exit code.  This can be modified by the app via System.SetExitCode().
    SetLatchedExitCode(exitCode);

    // Bump up the ref-count on the module
    for (int i =0; i<6; i++)
        CLRLoadLibrary(MSCOREE_SHIM_W);

    END_EXTERNAL_ENTRYPOINT;

    ForceEEShutdown();


}

#include "../ildasm/dynamicarray.h"
struct RVAFSE // RVA Field Start & End
{
    BYTE* pbStart;
    BYTE* pbEnd;
};
extern DynamicArray<RVAFSE> *g_drRVAField;

static bool WaitForEndOfShutdown_OneIteration()
{
    CONTRACTL{
        NOTHROW;
        GC_NOTRIGGER;
        MODE_PREEMPTIVE;
    } CONTRACTL_END;

    // We are shutting down.  GC triggers does not have any effect now.
    CONTRACT_VIOLATION(GCViolation);

    // If someone calls EEShutDown while holding OS loader lock, the thread we created for shutdown
    // won't start running.  This is a deadlock we can not fix.  Instead, we timeout and continue the 
    // current thread.
    DWORD timeout = GetEEPolicy()->GetTimeout(OPR_ProcessExit);
    timeout *= 2;
    ULONGLONG endTime = CLRGetTickCount64() + timeout;
    bool done = false;
    EX_TRY
    {
        ULONGLONG curTime = CLRGetTickCount64();
        if (curTime > endTime)
        {
            done = true;
        }
        else
        {
            timeout = endTime - curTime;
            DWORD status = g_pEEShutDownEvent->Wait(timeout,TRUE);
            if (status == WAIT_OBJECT_0 || status == WAIT_TIMEOUT)
            {
                done = true;
            }
            else
            {
                done = false;
            }
        }
    }
    EX_CATCH
    {
    }
    EX_END_CATCH(SwallowAllExceptions);
    return done;
}

void WaitForEndOfShutdown()
{
    CONTRACTL{
        NOTHROW;
        GC_NOTRIGGER;
        MODE_PREEMPTIVE;
    } CONTRACTL_END;

    // We are shutting down.  GC triggers does not have any effect now.
    CONTRACT_VIOLATION(GCViolation);

    while (!WaitForEndOfShutdown_OneIteration());
}

void STDMETHODCALLTYPE EEShutDownHelper(BOOL fIsDllUnloading)
{
    CONTRACTL
    {
        NOTHROW;
        GC_TRIGGERS;
        MODE_ANY;
    } CONTRACTL_END;

    // Get the current thread.
    Thread * pThisThread = GetThread();

    // If the process is detaching then set the global state.
    // This is used to get around FreeLibrary problems.
    if(fIsDllUnloading)
        g_fProcessDetach = true;

    if (IsDbgHelperSpecialThread())
    {
        // Our debugger helper thread does not allow Thread object to be set up.
        // We should not run shutdown code on debugger helper thread.
        _ASSERTE(fIsDllUnloading);
        return;
    }

#ifdef _DEBUG
    // stop API thread stress
    APIThreadStress::SetThreadStressCount(0);
#endif

    STRESS_LOG1(LF_STARTUP, LL_INFO10, "EEShutDown entered unloading = %d", fIsDllUnloading);

#ifdef _DEBUG
    if (_DbgBreakCount)
        _ASSERTE(!"An assert was hit before EE Shutting down");

    if (g_pConfig->GetConfigDWORD(L"BreakOnEEShutdown", 0))
        _ASSERTE(!"Shutting down EE!");
#endif

#ifdef DEBUGGING_SUPPORTED
    // This is a nasty, terrible, horrible thing. If we're being
    // called from our DLL main, then the odds are good that our DLL
    // main has been called as the result of some person calling
    // ExitProcess. That rips the debugger helper thread away very
    // ungracefully. This check is an attempt to recognize that case
    // and avoid the impending hang when attempting to get the helper
    // thread to do things for us.
    if ((g_pDebugInterface != NULL) && g_fProcessDetach)
        g_pDebugInterface->EarlyHelperThreadDeath();
#endif // DEBUGGING_SUPPORTED

    BOOL fFinalizeOK = FALSE;

    EX_TRY
    {
        ClrFlsSetThreadType(ThreadType_Shutdown);

        if (!fIsDllUnloading)
        {
            ProcessEventForHost(Event_ClrDisabled, NULL);
        }
        else if (g_fEEShutDown)
        {
            // I'm in the final shutdown and the first part has already been run.
            goto part2;
        }
        // Indicate the EE is the shut down phase.
        g_fEEShutDown |= ShutDown_Start;

        fFinalizeOK = TRUE;




        // We perform the final GC only if the user has requested it through the GC class.
        // We should never do the final GC for a process detach
        if (!g_fProcessDetach && !g_fFastExitProcess)
        {
            g_fEEShutDown |= ShutDown_Finalize1;
            GCHeap::GetGCHeap()->EnableFinalization();
            fFinalizeOK = GCHeap::GetGCHeap()->FinalizerThreadWatchDog();
        }


        // Ok.  Let's stop the EE.
        if (!g_fProcessDetach)
        {
            if (g_IBCLogger.InstrEnabled())
            {
                // acquire the SystemDomain lock on the second call to shutdown,
                // because after this call to FinalizerThreadWatchDog
                // every thread can be blocked inside Thread::RareDisablePreemptiveGC with this lock acquired
                // making the main shutdown thread to deadlock at the call to WriteAllModuleProfileData below
                SystemDomain::LockHolder systemDomainLock;
                systemDomainLock.SuppressRelease();
            }

            // Convert key locks into "shutdown" mode. A lock in shutdown mode means:
            // - Only the finalizer/helper/shutdown threads will be able to take the the lock.
            // - Any other thread that tries takes it will just get redirected to an endless WaitForEndOfShutdown().
            //
            // The only managed code that should run after this point is the finalizers for shutdown.
            // We convert locks needed for running + debugging such finalizers. Since such locks may need to be
            // juggled between multiple threads (finalizer/helper/shutdown), no single thread can take the
            // lock and not give it up.
            //
            // Each lock needs its own shutdown flag (they can't all be converted at once).
            // To avoid deadlocks, we need to convert locks in order of crst level (biggest first).

            // Notify the debugger that we're going into shutdown to convert debugger-lock to shutdown.
            if (g_pDebugInterface != NULL)
            {
                g_pDebugInterface->LockDebuggerForShutdown();
            }

            // This call will convert the ThreadStoreLock into "shutdown" mode, just like the debugger lock above.
            g_fEEShutDown |= ShutDown_Finalize2;
            if (fFinalizeOK)
            {
                fFinalizeOK = GCHeap::GetGCHeap()->FinalizerThreadWatchDog();
            }
        }

        FastInterlockOr ((DWORD*)&g_fForbidEnterEE, 1);

        if (g_fProcessDetach || !fFinalizeOK)
        {
            ThreadStore::TrapReturningThreads(TRUE);
        }

        if (!g_fProcessDetach && !fFinalizeOK)
        {
            goto lDone;
        }

#ifdef PROFILING_SUPPORTED
        // If profiling is enabled, then notify of shutdown first so that the
        // profiler can make any last calls it needs to.  Do this only if we
        // are not detaching

        if (IsProfilerPresent())
        {
            // If EEShutdown is not being called due to a ProcessDetach event, so
            // the profiler should still be present
            if (!g_fProcessDetach)
            {
                LOG((LF_CORPROF, LL_INFO10, "**PROF: EEShutDown entered.\n"));
                PROFILER_CALL;
                g_profControlBlock.pProfInterface->Shutdown((ThreadID) pThisThread);
            }

            g_fEEShutDown |= ShutDown_Profiler;

            // Free the interface objects.
            TerminateProfiling(g_fProcessDetach);

            // EEShutdown is being called due to a ProcessDetach event, so the
            // profiler has already been unloaded and we must set the profiler
            // status to profNone so we don't attempt to send any more events to
            // the profiler
            if (g_fProcessDetach)
                g_profStatus = profNone;
        }
#endif // PROFILING_SUPPORTED

        // CoEEShutDownCOM moved to
        // the Finalizer thread. See bug 87809
        if (!g_fProcessDetach && !g_fFastExitProcess)
        {
            g_fEEShutDown |= ShutDown_COM;
            if (fFinalizeOK)
                GCHeap::GetGCHeap()->FinalizerThreadWatchDog();
        }

#ifdef _DEBUG
        else
            g_fEEShutDown |= ShutDown_COM;
#endif

#ifdef _DEBUG
        g_fEEShutDown |= ShutDown_SyncBlock;

        // This releases any metadata interfaces that may be held by leaked
        // ISymUnmanagedReaders or Writers. We do this in phase two now that
        // we know any such readers or writers can no longer be in use.
        //
        // Note: we only do this in a debug build to support our wacky leak
        // detection.
        if (g_fProcessDetach)
            Module::ReleaseMemoryForTracking();
#endif

        // Save the security policy cache as necessary.
        Security::SaveCache();



        // This is the end of Part 1.
part2:


        // On the new plan, we only do the tear-down under the protection of the loader
        // lock -- after the OS has stopped all other threads.
        if (fIsDllUnloading && (g_fEEShutDown & ShutDown_Phase2) == 0)
        {
            g_fEEShutDown |= ShutDown_Phase2;


            // Shutdown finalizer before we suspend all background threads. Otherwise we
            // never get to finalize anything. Obviously.

#ifdef _DEBUG
            if (_DbgBreakCount)
                _ASSERTE(!"An assert was hit After Finalizer run");
#endif

            // No longer process exceptions
            g_fNoExceptions = true;

            //
            // Remove our global exception filter. If it was NULL before, we want it to be null now.
            //
            UninstallUnhandledExceptionFilter();

            //
            if (!g_fFastExitProcess)
            {
                SystemDomain::DetachBegin();
            }


#ifdef DEBUGGING_SUPPORTED
            // Terminate the debugging services.
            TerminateDebugger();
#endif // DEBUGGING_SUPPORTED

            TerminateDebugStore();

            StubManager::TerminateStubManagers();


#ifdef ENABLE_PERF_COUNTERS
            // Terminate Perf Counters as late as we can (to get the most data)
            PerfCounters::Terminate();
#endif // ENABLE_PERF_COUNTERS

            VirtualCallStubManager::UninitStatic();

            // Terminate the InterProcess Communications with COM+
            TerminateIPCManager();

#ifdef ENABLE_PERF_LOG
            PerfLog::PerfLogDone();
#endif //ENABLE_PERF_LOG

            // Give PerfMon a chance to hook up to us
            // Have perfmon resync list *after* we close IPC so that it will remove
            // this process
            IPCFuncCallSource::DoThreadSafeCall();

            if (!g_fFastExitProcess)
            {
                SystemDomain::DetachEnd();
            }

            TerminateStackProbes();

#ifdef ENABLE_TIMELINE
            Timeline::Shutdown();
#endif
#ifdef _DEBUG
            if (_DbgBreakCount)
                _ASSERTE(!"EE Shutting down after an assert");
#endif


#ifdef LOGGING
            extern unsigned FcallTimeHist[];
#endif
            LOG((LF_STUBS, LL_INFO10, "FcallHist %3d %3d %3d %3d %3d %3d %3d %3d %3d %3d %3d\n",
                FcallTimeHist[0], FcallTimeHist[1], FcallTimeHist[2], FcallTimeHist[3],
                FcallTimeHist[4], FcallTimeHist[5], FcallTimeHist[6], FcallTimeHist[7],
                FcallTimeHist[8], FcallTimeHist[9], FcallTimeHist[10]));

            WriteJitHelperCountToSTRESSLOG();

            STRESS_LOG0(LF_STARTUP, LL_INFO10, "EEShutdown shutting down logging");


        if (g_pConfig != NULL)
            g_pConfig->Cleanup();

#ifdef LOGGING
            ShutdownLogging();
#endif
        }

    lDone: ;
    }
    EX_CATCH
    {
    }
    EX_END_CATCH(SwallowAllExceptions);

    ClrFlsClearThreadType(ThreadType_Shutdown);
    if (!g_fProcessDetach)
    {
        g_pEEShutDownEvent->Set();
    }
}


BOOL g_fWeOwnProcess = FALSE;

static LONG s_ActiveShutdownThreadCount = 0;

DWORD WINAPI EEShutDownProcForSTAThread(LPVOID lpParameter)
{
    STATIC_CONTRACT_SO_INTOLERANT;;


    ClrFlsSetThreadType(ThreadType_ShutdownHelper);

    EEShutDownHelper(FALSE);
    for (int i = 0; i < 10; i ++)
    {
        if (s_ActiveShutdownThreadCount)
        {
            return 0;
        }
        __SwitchToThread(20);
    }

    EPolicyAction action = GetEEPolicy()->GetDefaultAction(OPR_ProcessExit, NULL);
    if (action < eRudeExitProcess)
    {
        action = eRudeExitProcess;
    }
    UINT exitCode;
    if (g_fWeOwnProcess)
    {
        exitCode = GetLatchedExitCode();
    }
    else
    {
        exitCode = HOST_E_EXITPROCESS_TIMEOUT;
    }
    EEPolicy::HandleExitProcessFromEscalation(action, exitCode);

    return 0;
}

// ---------------------------------------------------------------------------
// %%Function: EEShutDown(BOOL fIsDllUnloading)
//
// Parameters:
//  BOOL fIsDllUnloading :: is it safe point for full cleanup
//
// Returns:
//  Nothing
//
// Description:
//  All ee shutdown stuff should be done here
// ---------------------------------------------------------------------------
void STDMETHODCALLTYPE EEShutDown(BOOL fIsDllUnloading)
{
    CONTRACTL {
        NOTHROW;
        GC_TRIGGERS;
        MODE_ANY;
        SO_TOLERANT; // we don't need to cleanup 'cus we're shutting down
        PRECONDITION(g_fEEStarted);
    } CONTRACTL_END;

    // If we have not started runtime successfully, it is not safe to call EEShutDown.
    if (!g_fEEStarted || g_fFastExitProcess == 2)
    {
        return;
    }

    // Stop stack probing and asserts right away.  Once we're shutting down, we can do no more.
    // And we don't want to SO-protect anything at this point anyway. This really only has impact
    // on a debug build.
    TerminateStackProbes();

    // We only do the first part of the shutdown once.
    static LONG OnlyOne = -1;

    if (!fIsDllUnloading)
    {
        if (FastInterlockIncrement(&OnlyOne) != 0)
        {
            // I'm in a regular shutdown -- but another thread got here first.
            // It's a race if I return from here -- I'll call ExitProcess next, and
            // rip things down while the first thread is half-way through a
            // nice cleanup.  Rather than do that, I should just wait until the
            // first thread calls ExitProcess().  I'll die a nice death when that
            // happens.
            Thread *pThisThread = GetThread();
            if (pThisThread && pThisThread->PreemptiveGCDisabled())
            {
                pThisThread->EnablePreemptiveGC();
            }
            WaitForEndOfShutdown();
            return;
        }
    }

    if (GetThread())
    {
        GCX_COOP();
        EEShutDownHelper(fIsDllUnloading);
        if (!fIsDllUnloading)
        {
            FastInterlockIncrement(&s_ActiveShutdownThreadCount);
        }
    }
    else
    {
        EEShutDownHelper(fIsDllUnloading);
        if (!fIsDllUnloading)
        {
            FastInterlockIncrement(&s_ActiveShutdownThreadCount);
        }
    }
}

// ---------------------------------------------------------------------------
// %%Function: CanRunManagedCode()
//
// Parameters:
//  none
//
// Returns:
//  true or false
//
// Description: Indicates if one is currently allowed to run managed code.
// ---------------------------------------------------------------------------

BOOL CanRunManagedCode(HINSTANCE hInst)
{
    return CanRunManagedCode(TRUE, hInst);
}

BOOL CanRunManagedCode(BOOL fCannotRunIsUserError, HINSTANCE hInst)
{
    CONTRACTL {
        NOTHROW;
        GC_TRIGGERS;        // because of the CustomerDebugProbe
        MODE_ANY;
        SO_TOLERANT;
    } CONTRACTL_END;

    // If we are shutting down the runtime, then we cannot run code.
    if (g_fForbidEnterEE == TRUE)
        return FALSE;

    // If we are finaling live objects or processing ExitProcess event,
    // we can not allow managed method to run unless the current thread
    // is the finalizer thread
    if ((g_fEEShutDown & ShutDown_Finalize2) && !GCHeap::GetGCHeap()->IsCurrentThreadFinalizer())
        return FALSE;

    // If pre-loaded objects are not present, then no way.
    if (g_pPreallocatedOutOfMemoryException == NULL)
        return FALSE;


    return TRUE;
}

// ---------------------------------------------------------------------------
// %%Function: CoInitializeEE(DWORD fFlags)
//
// Parameters:
//  fFlags                  - Initialization flags for the engine.  See the
//                              COINITIEE enumerator for valid values.
//
// Returns:
//  Nothing
//
// Description:
//  Initializes the EE if it hasn't already been initialized. This function
//  no longer maintains a ref count since the EE doesn't support being
//  unloaded and re-loaded. It simply ensures the EE has been started.
// ---------------------------------------------------------------------------
HRESULT STDMETHODCALLTYPE CoInitializeEE(DWORD fFlags)
{
    WRAPPER_CONTRACT;
    HRESULT hr = S_OK;
    BEGIN_ENTRYPOINT_NOTHROW;

    hr = EnsureEEStarted((COINITIEE)fFlags);
    END_ENTRYPOINT_NOTHROW;

    return hr;
}

// ---------------------------------------------------------------------------
// %%Function: CoUninitializeEE
//
// Parameters:
//  BOOL fIsDllUnloading :: is it safe point for full cleanup
//
// Returns:
//  Nothing
//
// Description:
//  Must be called by client on shut down in order to free up the system.
// ---------------------------------------------------------------------------
void STDMETHODCALLTYPE CoUninitializeEE(BOOL fIsDllUnloading)
{
    LEAF_CONTRACT;


}

// ---------------------------------------------------------------------------
//// Win9x: During PROCESS_DETACH as a result of process termination,
//// anything on the stack allocated before PROCESS_DETACH notification
//// is not reliable.
//// Any global and thread variables that track information
//// on the stack should be reset here.


//*****************************************************************************
// This entry point is called from the native DllMain of the loaded image.
// This gives the COM+ loader the chance to dispatch the loader event.  The
// first call will cause the loader to look for the entry point in the user
// image.  Subsequent calls will dispatch to either the user's DllMain or
// their Module derived class.
//*****************************************************************************
BOOL STDMETHODCALLTYPE _CorDllMain(     // TRUE on success, FALSE on error.
    HINSTANCE   hInst,                  // Instance handle of the loaded module.
    DWORD       dwReason,               // Reason for loading.
    LPVOID      lpReserved              // Unused.
    )
{
    STATIC_CONTRACT_NOTHROW;
    //STATIC_CONTRACT_GC_TRIGGERS;
    STATIC_CONTRACT_ENTRY_POINT;
    BOOL retval = FALSE;

    //BEGIN_ENTRYPOINT_NOTHROW;

    // Can't use PAL_TRY/EX_TRY here as they access the ClrDebugState which gets blown away as part of the
    // PROCESS_DETACH path. Must use special PAL_TRY_FOR_DLLMAIN, passing the reason were in the DllMain.
    PAL_TRY_FOR_DLLMAIN(dwReason)
    {
#ifdef _DEBUG
    if (CLRTaskHosted() &&
        ((dwReason == DLL_PROCESS_ATTACH && lpReserved == NULL) ||  // LoadLibrary of a managed dll
         (dwReason == DLL_PROCESS_DETACH && lpReserved == NULL)     // FreeLibrary of a managed dll
         )) {
        // OS loader lock is being held by the current thread.  We can not allow the fiber
        // to be rescheduled here while processing DllMain for managed dll.
        IHostTask *pTask = GetCurrentHostTask();
        if (pTask) {
            Thread *pThread = GetThread();
            _ASSERTE (pThread);
            _ASSERTE (pThread->HasThreadAffinity());
        }
    }
#endif

        // Since we're in _CorDllMain, we know that we were not called because of a
        // bootstrap thunk, since they will call CorDllMainForThunk. Because of this,
        // we can pass FALSE for the fFromThunk parameter.
        retval = ExecuteDLL(hInst,dwReason,lpReserved, FALSE);
    }
    PAL_EXCEPT(EXCEPTION_EXECUTE_HANDLER)
    {
    }
    PAL_ENDTRY;

    //END_ENTRYPOINT_NOTHROW;

    return retval;
}

//*****************************************************************************
void STDMETHODCALLTYPE CorDllMainForThunk(HINSTANCE hInst, HINSTANCE hInstShim)
{

    STATIC_CONTRACT_THROWS;
    STATIC_CONTRACT_GC_TRIGGERS;


    CONSISTENCY_CHECK(g_hInstShim == NULL || hInstShim == g_hInstShim);
    g_hInstShim = hInstShim;

    {
        // If no managed thread exists, then we need to call the prepare method
        // to try and startup the runtime and/or create a managed thread object
        // so that installing an unwind and continue handler below is possible.
        // If we fail to startup or create a thread, we'll raise the basic
        // EXCEPTION_COMPLUS exception.
        if (GetThread() == NULL)
        {
            HRESULT hr;
            // Since this method is only called if a bootstrap thunk is invoked, we
            // know that passing TRUE for fFromThunk is the correct value.
            if (FAILED(hr = PrepareExecuteDLLForThunk(hInst, 0, NULL)))
            {
                // We failed to start the runtime or to create a runtime thread.
                RaiseException(EXCEPTION_COMPLUS, 0, 0, NULL);
            }
        }

    }

    INSTALL_UNWIND_AND_CONTINUE_HANDLER(GetThread());

    // We're actually going to run some managed code and we're inside the loader lock.
    // There may be a customer debug probe enabled that prevents this.
    CanRunManagedCode(hInst);

    // Since this method is only called if a bootstrap thunk is invoked, we
    // know that passing TRUE for fFromThunk is the correct value.
    ExecuteDLL(hInst, 0, NULL, TRUE);

    UNINSTALL_UNWIND_AND_CONTINUE_HANDLER;

}


static BOOL CacheCommandLine(__in LPWSTR pCmdLine, __in_opt LPWSTR* ArgvW)
{
    CONTRACTL {
        THROWS;
        GC_NOTRIGGER;
        MODE_ANY;
        PRECONDITION(CheckPointer(pCmdLine));
        PRECONDITION(CheckPointer(ArgvW));
    } CONTRACTL_END;

    if (pCmdLine) {
        size_t len = wcslen(pCmdLine);

        _ASSERT(g_pCachedCommandLine== NULL);
        g_pCachedCommandLine = new WCHAR[len+1];
        wcscpy_s(g_pCachedCommandLine, len+1, pCmdLine);
    }

    if (ArgvW != NULL && ArgvW[0] != NULL) {
        WCHAR wszModuleName[MAX_PATH];
        WCHAR wszCurDir[MAX_PATH];
        if (!WszGetCurrentDirectory(MAX_PATH, wszCurDir))
            return FALSE;
        if (PathCombine(wszModuleName, wszCurDir, ArgvW[0]) == NULL)
            return FALSE;

        size_t len = wcslen(wszModuleName);
        _ASSERT(g_pCachedModuleFileName== NULL);
        g_pCachedModuleFileName = new WCHAR[len+1];
        wcscpy_s(g_pCachedModuleFileName, len+1, wszModuleName);
    }

    return TRUE;
}

//*****************************************************************************
// This entry point is called from the native entry piont of the loaded
// executable image.  The command line arguments and other entry point data
// will be gathered here.  The entry point for the user image will be found
// and handled accordingly.
//*****************************************************************************
__int32 STDMETHODCALLTYPE _CorExeMain2( // Executable exit code.
    PBYTE   pUnmappedPE,                // -> memory mapped code
    DWORD   cUnmappedPE,                // Size of memory mapped code
    __in LPWSTR  pImageNameIn,          // -> Executable Name
    __in LPWSTR  pLoadersFileName,      // -> Loaders Name
    __in LPWSTR  pCmdLine)              // -> Command Line
{

    // This entry point is used by clix
    BOOL bRetVal = 0;

    //BEGIN_ENTRYPOINT_VOIDRET;

    // Before we initialize the EE, make sure we've snooped for all EE-specific
    // command line arguments that might guide our startup.
    HRESULT result = CorCommandLine::SetArgvW(pCmdLine);

    if (!CacheCommandLine(pCmdLine, CorCommandLine::GetArgvW(NULL))) {
        LOG((LF_STARTUP, LL_INFO10, "Program exiting - CacheCommandLine failed\n"));
        bRetVal = -1;
        goto exit;
    }

    if (SUCCEEDED(result))
        result = CoInitializeEE(COINITEE_DEFAULT | COINITEE_MAIN);

    if (FAILED(result)) {
        VMDumpCOMErrors(result);
        SetLatchedExitCode (-1);
        goto exit;
    }

    // This is here to get the ZAPMONITOR working correctly
    INSTALL_UNWIND_AND_CONTINUE_HANDLER;


    // Load the executable
    bRetVal = ExecuteEXE(pImageNameIn);

    if (!bRetVal) {
        // The only reason I've seen this type of error in the wild is bad
        // metadata file format versions and inadequate error handling for
        // partially signed assemblies.  While this may happen during
        // development, our customers should not get here.  This is a back-stop
        // to catch CLR bugs. If you see this, please try to find a better way
        // to handle your error, like throwing an unhandled exception.
        EEMessageBoxCatastrophic(IDS_EE_COREXEMAIN2_FAILED_TEXT, IDS_EE_COREXEMAIN2_FAILED_TITLE);
        SetLatchedExitCode (-1);
    }

    UNINSTALL_UNWIND_AND_CONTINUE_HANDLER;

exit:
    STRESS_LOG1(LF_STARTUP, LL_ALWAYS, "Program exiting: return code = %d", GetLatchedExitCode());

    STRESS_LOG0(LF_STARTUP, LL_INFO10, "EEShutDown invoked from _CorExeMain2");

    EEPolicy::HandleExitProcess();
    
    //END_ENTRYPOINT_VOIDRET;

    return bRetVal;
}

//*****************************************************************************
// This is the call point to wire up an EXE.  In this case we have the HMODULE
// and just need to make sure we do to correct self referantial things.
//*****************************************************************************

BOOL STDMETHODCALLTYPE ExecuteEXE(HMODULE hMod)
{
    STATIC_CONTRACT_GC_TRIGGERS;

    _ASSERTE(hMod);
    if (!hMod)
        return FALSE;

    ETWTraceStartup::TraceEvent(ETW_TYPE_STARTUP_EXEC_EXE);
    TIMELINE_START(STARTUP, ("ExecuteExe"));

    EX_TRY_NOCATCH
    {
        // Executables are part of the system domain
        SystemDomain::ExecuteMainMethod(hMod);
    }
    EX_END_NOCATCH;

    ETWTraceStartup::TraceEvent(ETW_TYPE_STARTUP_EXEC_EXE+1);
    TIMELINE_END(STARTUP, ("ExecuteExe"));

    return TRUE;
}

BOOL STDMETHODCALLTYPE ExecuteEXE(__in LPWSTR pImageNameIn)
{
    STATIC_CONTRACT_GC_TRIGGERS;

    WCHAR               wzPath[MAX_PATH];
    DWORD               dwPathLength = 0;

    EX_TRY_NOCATCH
    {
        // get the path of executable
        dwPathLength = WszGetFullPathName(pImageNameIn, MAX_PATH, wzPath, NULL);

        if (!dwPathLength || dwPathLength > MAX_PATH)
        {
            ThrowWin32( !dwPathLength ? GetLastError() : ERROR_FILENAME_EXCED_RANGE);
        }

        SystemDomain::ExecuteMainMethod( NULL, (WCHAR *)wzPath );
    }
    EX_END_NOCATCH;

    return TRUE;
}

//*****************************************************************************
// fFromThunk indicates that a dependency is calling through the Import Export table,
// and calling indirect through the IJW vtfixup slot.
//
// fFromThunk=FALSE means that we are running DllMain during LoadLibrary while
// holding the loader lock.
//



//*****************************************************************************
BOOL ExecuteDLL_ReturnOrThrow(HRESULT hr, BOOL fFromThunk)
{
    CONTRACTL {
        if (fFromThunk) THROWS; else NOTHROW;
        WRAPPER(GC_TRIGGERS);
        MODE_ANY;
    SO_TOLERANT;
    } CONTRACTL_END;

    // If we have a failure result, and we're called from a thunk,
    // then we need to throw an exception to communicate the error.
    if (FAILED(hr) && fFromThunk)
    {
        COMPlusThrowHR(hr);
    }
    return SUCCEEDED(hr);
}

#ifdef _DEBUG
//*****************************************************************************
// Factor some common debug code.
//*****************************************************************************
static void EnsureManagedThreadExistsForHostedThread()
{
    CONTRACTL {
        NOTHROW;
        GC_NOTRIGGER;
        MODE_ANY;
    } CONTRACTL_END;

    if (CLRTaskHosted()) {
        // If CLR is hosted, and this is on a thread that a host controls,
        // we must have created Thread object.
        IHostTask *pHostTask = GetCurrentHostTask();
        if (pHostTask)
        {
            CONSISTENCY_CHECK(CheckPointer(GetThread()));
        }
    }
}
#endif

//*****************************************************************************
// This ensure that the runtime is started and an EEThread object is created
// for the current thread. This functionality is duplicated in ExecuteDLL,
// except that this code will not throw.
//*****************************************************************************
HRESULT PrepareExecuteDLLForThunk(HINSTANCE hInst,
                                                 DWORD dwReason,
                                                 LPVOID lpReserved)
{
    CONTRACTL {
        NOTHROW;
        WRAPPER(GC_TRIGGERS);
        MODE_ANY;
        PRECONDITION(CheckPointer(lpReserved, NULL_OK));
        PRECONDITION(CheckPointer(hInst));
    } CONTRACTL_END;


    HRESULT hr = S_OK;
    Thread *pThread = GetThread();

    INDEBUG(EnsureManagedThreadExistsForHostedThread();)

    if (pThread == NULL)
    {
        // If necessary, start the runtime and create a managed thread object.
        hr = EnsureEEStarted(COINITEE_DLL);
        if (FAILED(hr))
        {
            return hr;
        }
        if ((pThread = SetupThreadNoThrow(&hr)) == NULL)
        {
            return hr;
        }
    }

    CONSISTENCY_CHECK(CheckPointer(pThread));

    return S_OK;
}

//*****************************************************************************
// This is the call point to make a DLL that is already loaded into our address
// space run. There will be other code to actually have us load a DLL due to a
// class referance.
//*****************************************************************************
BOOL STDMETHODCALLTYPE ExecuteDLL(HINSTANCE hInst,
                                  DWORD dwReason,
                                  LPVOID lpReserved,
                                  BOOL fFromThunk)
{

    CONTRACTL{
        THROWS;
        WRAPPER(GC_TRIGGERS);
        MODE_ANY;
        ENTRY_POINT;
        PRECONDITION(CheckPointer(lpReserved, NULL_OK));
        PRECONDITION(CheckPointer(hInst));
        PRECONDITION(GetThread() != NULL || !fFromThunk);
    } CONTRACTL_END;

    HRESULT hr = S_OK;
    BOOL fRetValue = FALSE;
    BEGIN_ENTRYPOINT_THROWS;

    Thread *pThread = GetThread();

    if (!hInst)
    {
        fRetValue = ExecuteDLL_ReturnOrThrow(E_FAIL, fFromThunk);
        goto Exit;
    }

    // Note that we always check fFromThunk before checking the dwReason value.
    // This is because the dwReason value is undefined in the case that we're
    // being invoked due to a bootstrap (because that is by definition outside
    // of the loader lock and there is no appropriate dwReason value).
    if (fFromThunk ||
        dwReason == DLL_PROCESS_ATTACH ||
        dwReason == DLL_THREAD_ATTACH)
    {
        INDEBUG(EnsureManagedThreadExistsForHostedThread();)


        // If necessary, start the runtime and create a managed thread object.
        if (fFromThunk || dwReason == DLL_PROCESS_ATTACH)
        {
            hr = EnsureEEStarted(COINITEE_DLL);

            if (SUCCEEDED(hr) && pThread == NULL)
            {
                pThread = SetupThreadNoThrow(&hr);
            }

            if(FAILED(hr))
            {
                fRetValue = ExecuteDLL_ReturnOrThrow(hr, fFromThunk);
                goto Exit;
            }
        }

        // IJW assemblies cause the thread doing the process attach to
        // re-enter ExecuteDLL and do a thread attach. This happens when
        // CoInitializeEE() above executed
        else if (!(pThread &&
                   pThread->GetDomain() &&
                   CanRunManagedCode(FALSE/*=fCannotRunIsUserError*/)))
        {
            fRetValue = ExecuteDLL_ReturnOrThrow(S_OK, fFromThunk);
            goto Exit;
        }

        // we now have a thread setup - either the 1st if set it up, or
        // the else if ran if we didn't have a thread setup.

    }
    else
    {
        PEDecoder pe(hInst);
        if (pe.HasManagedEntryPoint())
        {
            // If the EE is still intact, then run user entry points.  Otherwise
            // detach was handled when the app domain was stopped.
            //
            // Checks for the loader lock will occur within RunDllMain, if that's
            FAULT_NOT_FATAL();
            if (CanRunManagedCode(FALSE/*=fCannotRunIsUserError*/))
            {
                hr = SystemDomain::RunDllMain(hInst, dwReason, lpReserved);
            }
        }
        // This does need to match the attach. We will only unload dll's
        // at the end and CoUninitialize will just bounce at 0. WHEN and IF we
        // get around to unloading IL DLL's during execution prior to
        // shutdown we will need to bump the reference one to compensate
        // for this call.
        if (dwReason == DLL_PROCESS_DETACH && !g_fForbidEnterEE)
        {
        }
    }

    fRetValue = ExecuteDLL_ReturnOrThrow(hr, fFromThunk);

Exit:
    
    END_ENTRYPOINT_THROWS;
    return fRetValue;
}


//
// Initialize the Garbage Collector
//

HRESULT InitializeGarbageCollector()
{
    CONTRACTL{
        NOTHROW;
        GC_TRIGGERS;
        MODE_ANY;
        INJECT_FAULT(return E_OUTOFMEMORY);
    } CONTRACTL_END;

    HRESULT hr;

    // Build the special Free Object used by the Generational GC
    _ASSERT(g_pFreeObjectMethodTable == NULL);
    g_pFreeObjectMethodTable = (MethodTable *) new (nothrow) BYTE[sizeof(MethodTable)];
    if (g_pFreeObjectMethodTable == NULL)
        return (E_OUTOFMEMORY);
    ZeroMemory(g_pFreeObjectMethodTable, sizeof(MethodTable));

    // As the flags in the method table indicate there are no pointers
    // in the object, there is no gc descriptor, and thus no need to adjust
    // the pointer to skip the gc descriptor.

    g_pFreeObjectMethodTable->SetBaseSize(ObjSizeOf (ArrayBase));
    g_pFreeObjectMethodTable->SetClass (NULL);
    g_pFreeObjectMethodTable->InitializeFlags(MethodTable::enum_flag_Array | 1 /* ComponentSize */);

   {
        GCHeap *pGCHeap = GCHeap::CreateGCHeap();
        GCHeap::SetGCHeap(pGCHeap);

        if (!pGCHeap)
            return (E_OUTOFMEMORY);

        {
            CONTRACT_VIOLATION(ThrowsViolation);
            hr = pGCHeap->Initialize();
        }
    }

    return(hr);
}

/*****************************************************************************/
/* This is here only so that if we get an exception we stop before we catch it */
LONG DllMainFilter(PEXCEPTION_POINTERS p, PVOID pv)
{
        _ASSERTE(!"Exception happened in mscorwks!DllMain!");
        return EXCEPTION_EXECUTE_HANDLER;
}

//*****************************************************************************
// This is the part of the old-style DllMain that initializes the
// stuff that the EE team works on. It's called from the real DllMain
// up in MSCOREE land. Separating the DllMain tasks is simply for
// convenience due to the dual build trees.
//*****************************************************************************
BOOL STDMETHODCALLTYPE EEDllMain( // TRUE on success, FALSE on error.
    HINSTANCE   hInst,             // Instance handle of the loaded module.
    DWORD       dwReason,          // Reason for loading.
    LPVOID      lpReserved)        // Unused.
{
    STATIC_CONTRACT_NOTHROW;
    STATIC_CONTRACT_GC_TRIGGERS;

    // this runs at the top of a thread, SO is not a concern here...
    ENTER_SO_NOT_MAINLINE_CODE;

    // HRESULT hr;
    // BEGIN_EXTERNAL_ENTRYPOINT(&hr);
    // EE isn't spun up enough to use this macro

    // Can't use PAL_TRY/EX_TRY here as they access the ClrDebugState which gets blown away as part of the
    // PROCESS_DETACH path. Must use special PAL_TRY_FOR_DLLMAIN, passing the reason were in the DllMain.
    PAL_TRY_FOR_DLLMAIN(dwReason)
    {

    switch (dwReason)
    {
        case DLL_PROCESS_ATTACH:
        {
            // We cache the SystemInfo for anyone to use throughout the
            // life of the DLL.
            GetSystemInfo(&g_SystemInfo);

            // init sync operations
            InitFastInterlockOps();
            // Remember module instance
            g_pMSCorEE = hInst;


            // Set callbacks so that LoadStringRC knows which language our
            // threads are in so that it can return the proper localized string.
            SetResourceCultureCallbacks(GetThreadUICultureNames,
                                        GetThreadUICultureId);

            InitEEPolicy();
            InitHostProtectionManager();

            break;
        }

        case DLL_PROCESS_DETACH:
        {
            // lpReserved is NULL if we're here because someone called FreeLibrary
            // and non-null if we're here because the process is exiting.
            // Since nobody should ever be calling FreeLibrary on mscorwks.dll, lpReserved
            // should always be non NULL.
            _ASSERTE(lpReserved || !g_fEEStarted);
                g_fProcessDetach = TRUE;

            if (g_fEEStarted)
            {
                // GetThread() may be set to NULL for Win9x during shutdown.
                Thread *pThread = GetThread();
                if (GCHeap::IsGCInProgress() &&
                    ( (pThread && (pThread != GCHeap::GetGCHeap()->GetGCThread() ))
                        || !g_fSuspendOnShutdown))
                {
                    g_fEEShutDown |= ShutDown_Phase2;
                    break;
                }

                LOG((LF_STARTUP, INFO3, "EEShutDown invoked from EEDllMain"));
                EEShutDown(TRUE); // shut down EE if it was started up
                }
            break;
        }

        case DLL_THREAD_DETACH:
        {
            // Don't destroy threads here if we're in shutdown (shutdown will
            // clean up for us instead).

            // Don't use GetThread because perhaps we didn't initialize yet, or we
            // have already shutdown the EE.  Note that there is a race here.  We
            // might ask for TLS from a slot we just released.  We are assuming that
            // nobody re-allocates that same slot while we are doing this.  It just
            // isn't worth locking for such an obscure case.
            DWORD   tlsVal = GetThreadTLSIndex();

            if (tlsVal != (DWORD)-1)
            {
                Thread  *thread = (Thread *) UnsafeTlsGetValue(tlsVal);

                if (thread)
                {
                    // For case where thread calls ExitThread directly, we need to reset the
                    // frame pointer. Otherwise stackwalk would AV. We need to do it in cooperative mode.
                    // We need to set m_GCOnTransitionsOK so this thread won't trigger GC when toggle GC mode
                    if (thread->m_pFrame != FRAME_TOP)
                    {
#ifdef _DEBUG
                        thread->m_GCOnTransitionsOK = FALSE;
#endif
                        thread->DisablePreemptiveGC ();
                        thread->m_pFrame = FRAME_TOP;
                        thread->EnablePreemptiveGC ();
                    }
                    thread->DetachThread(TRUE);
                }
            }
        }
    }

    }
    PAL_EXCEPT_FILTER(DllMainFilter, NULL)
    {
    }
    PAL_ENDTRY;

    LEAVE_SO_NOT_MAINLINE_CODE;

    if (dwReason == DLL_THREAD_DETACH)
    {
        if (CLRMemoryHosted())
        {
            // A host may not support memory operation inside OS loader lock.
            // We will free these memory on finalizer thread.
            CExecutionEngine::DetachTlsInfo(CExecutionEngine::CheckThreadStateNoCreate(0));
        }
        else
        {
            CExecutionEngine::ThreadDetaching(CExecutionEngine::CheckThreadStateNoCreate(0));
        }
    }
    return TRUE;
}


#ifdef DEBUGGING_SUPPORTED
//*****************************************************************************
// This gets the environment var control flag for Debugging and Profiling
//*****************************************************************************


static void GetDbgProfControlFlag()
{
    CONTRACTL{
        NOTHROW;
        GC_NOTRIGGER;
        MODE_ANY;
    } CONTRACTL_END;

    // Check the debugger/profiling control environment variable to
    // see if there's any work to be done.
    g_CORDebuggerControlFlags = DBCF_NORMAL_OPERATION;

    char buf[32];
    DWORD len = GetEnvironmentVariableA(CorDB_CONTROL_ENV_VAR_NAME,
                                        buf, sizeof(buf));
    _ASSERTE(len < sizeof(buf));

    char *szBad;
    int  iBase;
    if (len > 0 && len < sizeof(buf))
    {
        iBase = (*buf == '0' && (*(buf + 1) == 'x' || *(buf + 1) == 'X')) ? 16 : 10;
        ULONG dbg = strtoul(buf, &szBad, iBase) & DBCF_USER_MASK;

        if (dbg == 1)
            g_CORDebuggerControlFlags |= DBCF_GENERATE_DEBUG_CODE;
    }
}
#endif // DEBUGGING_SUPPORTED

#ifdef PROFILING_SUPPORTED

//*****************************************************************************
// This is used to get the proc address by name of a proc in MSCORDBC.DLL
// It will perform a LoadLibrary if necessary.
//*****************************************************************************
static HRESULT GetDBCProc(__in const char *szProcName, FARPROC *pProcAddr)
{
    CONTRACTL{
        NOTHROW;
        GC_TRIGGERS;
        MODE_PREEMPTIVE;
        PRECONDITION(CheckPointer(szProcName));
        PRECONDITION(CheckPointer(pProcAddr));
    } CONTRACTL_END;

    HRESULT  hr = S_OK;

    GCX_PREEMP();

    // If the library hasn't already been loaded, do so
    if (g_pDebuggerDll == NULL)
    {
        DWORD lgth = _MAX_PATH + 1;
        WCHAR wszFile[_MAX_PATH + 1];
        hr = GetInternalSystemDirectory(wszFile, &lgth);
        if(FAILED(hr)) goto leav;

        wcscat_s(wszFile, COUNTOF(wszFile), MAKEDLLNAME_W(L"mscordbc"));
        g_pDebuggerDll = CLRLoadLibrary(wszFile);

        if (g_pDebuggerDll == NULL)
        {
            LOG((LF_CORPROF | LF_CORDB, LL_INFO10,
                 "MSCORDBC.DLL not found.\n"));
            hr = HRESULT_FROM_GetLastError();
            goto leav;
        }
    }
    _ASSERTE(g_pDebuggerDll != NULL);

    // Get the pointer to the requested function
    *pProcAddr = GetProcAddress(g_pDebuggerDll, szProcName);

    // If the proc address was not found, return error
    if (*pProcAddr == NULL)
    {
        LOG((LF_CORPROF | LF_CORDB, LL_INFO10,
             "'%s' not found in MSCORDBC.DLL\n"));
        hr = HRESULT_FROM_GetLastError();
        goto leav;
    }

leav:

    return hr;
}

void LogProfFailure(PCSTR szMsg)
{
    CONTRACTL{
        THROWS;
        GC_TRIGGERS;
        MODE_ANY;
        PRECONDITION(CheckPointer(szMsg));
    } CONTRACTL_END;

    SString msg(SString::Ascii, szMsg);

    EEMessageBox(IDS_EE_ERRORMESSAGETEXTTEMPLATE, IDS_EE_PROFILING_FAILURE, MB_OK | MB_ICONEXCLAMATION, msg.GetUnicode());
}

#define LOGPROFFAILURE(msg) LogProfFailure(msg)

/*
 * This will initialize the profiling services, if profiling is enabled.
 */

#define ENV_PROFILER L"COR_PROFILER"
#define ENV_PROFILER_A "COR_PROFILER"
#define ENV_PROFILER_DLL L"COR_PROFILER_DLL"
#define ENV_PROFILER_DLL_A "COR_PROFILER_DLL"
static HRESULT InitializeProfiling()
{
    CONTRACTL{
        THROWS;
        GC_TRIGGERS;
        MODE_ANY;
        INJECT_FAULT(return E_OUTOFMEMORY);
    } CONTRACTL_END;

    HRESULT hr;

    // This has to be called to initialize the WinWrap stuff so that WszXXX
    // may be called.
    OnUnicodeSystem();

    {
        PROFILER_CALL;
        g_profControlBlock.Init();
    }
    // Find out if profiling is enabled
    DWORD fProfEnabled = 0;
     
    //
    // Profiling is only enabled on non-Win9x platforms, so only check the registry on these OSes.
    //
    if (!RunningOnWin95()) 
    {
        fProfEnabled = g_pConfig->GetConfigDWORD(CorDB_CONTROL_ProfilingL, 0, REGUTIL::COR_CONFIG_ALL, FALSE);
    }

    // If profiling is not enabled, return.
    if (fProfEnabled == 0)
    {
        LOG((LF_CORPROF, LL_INFO10, "**PROF: Profiling not enabled.\n"));
        return (S_OK);
    }

    LOG((LF_CORPROF, LL_INFO10, "**PROF: Initializing Profiling Services.\n"));

    // Get the CLSID of the profiler to CoCreate
    NewArrayHolder<WCHAR> wszCLSID(NULL);
    NewArrayHolder<WCHAR> wszProfilerDLL(NULL);

    IfFailRet(g_pConfig->GetConfigString(ENV_PROFILER, &wszCLSID, FALSE));
    IfFailRet(g_pConfig->GetConfigString(ENV_PROFILER_DLL, &wszProfilerDLL, FALSE));

    // If the environment variable doesn't exist, profiling is not enabled.
    if (wszCLSID == NULL)
    {
        LOG((LF_CORPROF, LL_INFO10, "**PROF: Profiling flag set, but required "
             "environment variable does not exist.\n"));

        LOGPROFFAILURE("Profiling flag set, but required environment ("
                       ENV_PROFILER_A ") was not set.");

        return (S_FALSE);
    }
    // If the environment variable doesn't exist, profiling is not enabled.
    if (wszProfilerDLL == NULL)
    {
        LOG((LF_CORPROF, LL_INFO10, "**PROF: Profiling flag set, but required "
             "environment variable does not exist.\n"));

        LOGPROFFAILURE("Profiling flag set, but required environment ("
                       ENV_PROFILER_DLL_A ") was not set.");

        return (S_FALSE);
    }

    //*************************************************************************
    // Create the EE interface to provide to the profiling services
    NewHolder<ProfToEEInterface> pProfEE(
        (ProfToEEInterface *) new ProfToEEInterfaceImpl());

    // Initialize the interface
    hr = pProfEE->Init();

    if (FAILED(hr))
    {
        LOG((LF_CORPROF, LL_INFO10, "**PROF: ProfToEEInterface::Init failed.\n"));

        LOGPROFFAILURE("Internal profiling services initialization failure.");
        return (S_FALSE);
    }

    //*************************************************************************
    // Provide the EE interface to the Profiling services
    SETPROFTOEEINTERFACE *pSetProfToEEInterface = NULL;
    hr = GetDBCProc("SetProfToEEInterface", (FARPROC *)&pSetProfToEEInterface);

    if (FAILED(hr))
    {
        LOGPROFFAILURE("Internal profiling services initialization failure.");
        return (S_FALSE);
    }

    _ASSERTE(pSetProfToEEInterface != NULL);

    // Provide the newly created and inited interface
    pSetProfToEEInterface(pProfEE);

    //*************************************************************************
    // Get the Profiling services interface
    GETEETOPROFINTERFACE *pGetEEToProfInterface;
    hr = GetDBCProc("GetEEToProfInterface", (FARPROC *)&pGetEEToProfInterface);
    _ASSERTE(pGetEEToProfInterface != NULL);

    pGetEEToProfInterface(&g_profControlBlock.pProfInterface);
    _ASSERTE(g_profControlBlock.pProfInterface != NULL);

    // Check if we successfully got an interface to
    if (g_profControlBlock.pProfInterface == NULL)
    {
        LOG((LF_CORPROF, LL_INFO10, "**PROF: GetEEToProfInterface failed.\n"));

        LOGPROFFAILURE("Internal profiling services initialization failure.");

        pSetProfToEEInterface(NULL);
        return (S_FALSE);
    }

    pProfEE.SuppressRelease();


    //*************************************************************************
    // Now ask the profiling services to CoCreate the profiler

    // Indicate that the profiler is in initialization phase
    g_profStatus = profInInit;

    // This will CoCreate the profiler
    {
        PROFILER_CALL;
        hr = g_profControlBlock.pProfInterface->CreateProfiler(wszCLSID, wszProfilerDLL);
    }
    
    if (FAILED(hr))
    {
        LOG((LF_CORPROF, LL_INFO10, "**PROF: No profiler registered, or "
             "CoCreate failed.  Shutting down profiling.\n"));

        if (hr == E_NOINTERFACE)
        {
            LOGPROFFAILURE("CLR 2.0 does not support profilers written for CLR 1.x");
        }
        else
        {
            LOGPROFFAILURE("Failed to CoCreate profiler.");
        }

        // Notify the profiling services that the EE is shutting down
        {
            PROFILER_CALL;
            g_profControlBlock.pProfInterface->Terminate(FALSE);
        }
        g_profControlBlock.pProfInterface = NULL;
        g_profStatus = profNone;

        return (S_FALSE);
    }

    g_profControlBlock.pReservedMem = (BYTE*)ClrVirtualAlloc((BYTE *)TOP_MEMORY - 4*1024*1024, 4*1024*1024,
                                                        MEM_RESERVE, PAGE_READWRITE);

    LOG((LF_CORPROF, LL_INFO10, "**PROF: Profiler created and enabled.\n"));


    // If the profiler is interested in tracking GC events, then we must
    // disable concurrent GC since concurrent GC can allocate and kill
    // objects without relocating and thus not doing a heap walk.
    if (CORProfilerTrackGC())
        g_pConfig->SetGCconcurrent(0);

    // Indicate that profiling is properly initialized.
    g_profStatus = profInit;
    return (hr);
}

/*
 * This will terminate the profiling services, if profiling is enabled.
 */
static void TerminateProfiling(BOOL fProcessDetach)
{
    WRAPPER_CONTRACT;

    _ASSERTE(g_profStatus != profNone);

    // If we have a profiler interface active, then terminate it.
    if (g_profControlBlock.pProfInterface)
    {
        // Notify the profiling services that the EE is shutting down
        PROFILER_CALL;
        g_profControlBlock.pProfInterface->Terminate(fProcessDetach);

        g_profControlBlock.pProfInterface = NULL;
    }

    g_profStatus = profNone;
}
#endif // PROFILING_SUPPORTED



HRESULT InitializeDebugStore()
{
    _ASSERTE(g_pDebugInfoStore == NULL);

    // This will throw on OOM.
    g_pDebugInfoStore = new DebugInfoManager();

    return S_OK;
}

void TerminateDebugStore()
{
    if (g_pDebugInfoStore != NULL)
    {
        delete g_pDebugInfoStore;
        g_pDebugInfoStore = NULL;
    }
}

#ifdef DEBUGGING_SUPPORTED
//
// InitializeDebugger initialized the Runtime-side COM+ Debugging Services
//
static void InitializeDebugger(void)
{
    CONTRACTL
    {
        THROWS;
        GC_TRIGGERS;
        MODE_ANY;
    }
    CONTRACTL_END;

    // Ensure that if we throw, we'll call TerminateDebugger to cleanup.
    // This makes our Init more atomic by avoiding partially-init states.
    class EnsureCleanup {
        BOOL    fNeedCleanup;
    public:
        EnsureCleanup()
        {
            fNeedCleanup = TRUE;
        }

        void SuppressCleanup()
        {
            fNeedCleanup  = FALSE;
        }

        ~EnsureCleanup()
        {
             STATIC_CONTRACT_NOTHROW;
             STATIC_CONTRACT_GC_NOTRIGGER;
             STATIC_CONTRACT_MODE_ANY;
            if (fNeedCleanup) { TerminateDebugger(); };
        }
    } hCleanup;

    HRESULT hr = S_OK;

    LOG((LF_CORDB, LL_INFO10, "Initializing left-side debugging services.\n"));

    FARPROC gi = (FARPROC) &CorDBGetInterface;

    // Init the interface the EE provides to the debugger,
    // ask the debugger for its interface, and if all goes
    // well call Startup on the debugger.
    EEDbgInterfaceImpl::Init();
    _ASSERTE(g_pEEDbgInterfaceImpl != NULL); // throws on OOM

    // This allocates the Debugger object.
    typedef HRESULT __cdecl CORDBGETINTERFACE(DebugInterface**);
    hr = ((CORDBGETINTERFACE*)gi)(&g_pDebugInterface);
    IfFailThrow(hr);

    g_pDebugInterface->SetEEInterface(g_pEEDbgInterfaceImpl);

    {
        hr = g_pDebugInterface->Startup(); // throw on error
        _ASSERTE(SUCCEEDED(hr));
    }

    // If there's a DebuggerThreadControl interface, then we
    // need to update the DebuggerSpecialThread list.
    if (CorHost::GetDebuggerThreadControl())
    {
        hr = CorHost::RefreshDebuggerSpecialThreadList();
        _ASSERTE((SUCCEEDED(hr)) && (hr != S_FALSE));

        // So we don't think this will ever fail, but just in case...
        IfFailThrow(hr);
    }

    LOG((LF_CORDB, LL_INFO10, "Left-side debugging services setup.\n"));


    // If there is a DebuggerThreadControl interface, then it was set before the debugger
    // was initialized and we need to provide this interface now.  If debugging is already
    // initialized then the IDTC pointer is passed in when it is set through CorHost
    IDebuggerThreadControl *pDTC = CorHost::GetDebuggerThreadControl();

    if (pDTC != NULL)
    {
        g_pDebugInterface->SetIDbgThreadControl(pDTC);
    }

    hCleanup.SuppressCleanup();
    return;
}


//
// TerminateDebugger shuts down the Runtime-side COM+ Debugging Services
// InitializeDebugger will call this if it fails.
// This may be called even if the debugger is partially initialized.
// This can be called multiple times.
//
static void TerminateDebugger(void)
{
    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
        MODE_ANY;
    }
    CONTRACTL_END;

    LOG((LF_CORDB, LL_INFO10, "Shutting down left-side debugger services.\n"));

    // If initialized failed really early, then we didn't even get the Debugger object.
    if (g_pDebugInterface != NULL)
    {
        // Notify the out-of-process debugger that shutdown of the in-process debugging support has begun. This is only
        // really used in interop debugging scenarios.
        g_pDebugInterface->ShutdownBegun();

        // This will kill the helper thread, delete the Debugger object, and free all resources.
        g_pDebugInterface->StopDebugger();
        g_pDebugInterface = NULL;
    }

    // Delete this after Debugger, since Debugger may use this.
    EEDbgInterfaceImpl::Terminate();
    _ASSERTE(g_pEEDbgInterfaceImpl == NULL); // Terminate nulls this out for us.

    g_CORDebuggerControlFlags = DBCF_NORMAL_OPERATION;

    CorHost::CleanupDebuggerThreadControl();
}


// ---------------------------------------------------------------------------
// Initialize InterProcess Communications for COM+
// 1. Allocate an IPCManager Implementation and hook it up to our interface *
// 2. Call proper init functions to activate relevant portions of IPC block
// ---------------------------------------------------------------------------
static HRESULT InitializeIPCManager(void)
{
    CONTRACTL{
        NOTHROW;
        GC_TRIGGERS;
        MODE_ANY;
    } CONTRACTL_END;

    MEMORY_REPORT_CONTEXT_SCOPE("InitializeIPCManager");

    HRESULT hr = S_OK;
    HINSTANCE hInstIPCBlockOwner = 0;

    DWORD pid = 0;
    // Allocate the Implementation. Everyone else will work through the interface
    g_pIPCManagerInterface = new (nothrow) IPCWriterInterface();

    if (g_pIPCManagerInterface == NULL)
    {
        hr = E_OUTOFMEMORY;
        goto errExit;
    }

    pid = GetCurrentProcessId();


    // Do general init
    hr = g_pIPCManagerInterface->Init();

    if (!SUCCEEDED(hr))
    {
        goto errExit;
    }

    // Generate private IPCBlock for our PID. Note that for the other side of the debugger,
    // they'll hook up to the debuggee's pid (and not their own). So we still
    // have to pass the PID in.
    EX_TRY
    {
        hr = g_pIPCManagerInterface->CreatePrivateBlockOnPid(pid, FALSE, &hInstIPCBlockOwner);
    }
    EX_CATCH_HRESULT(hr);


    // Generate public IPCBlock for our PID.
    EX_TRY
    {
        hr = g_pIPCManagerInterface->CreatePublicBlockOnPid(pid);
    }
    EX_CATCH_HRESULT(hr);


errExit:
    // If any failure, shut everything down.
    if (!SUCCEEDED(hr))
        TerminateIPCManager();

    return hr;
}

#endif // DEBUGGING_SUPPORTED

// ---------------------------------------------------------------------------
// Terminate all InterProcess operations
// ---------------------------------------------------------------------------
static void TerminateIPCManager(void)
{
    CONTRACTL{
        NOTHROW;
        GC_NOTRIGGER;
        MODE_ANY;
    } CONTRACTL_END;

    if (g_pIPCManagerInterface != NULL)
    {
        g_pIPCManagerInterface->Terminate();

        delete g_pIPCManagerInterface;
        g_pIPCManagerInterface = NULL;
    }
}

void InitializeEventTracing()
{
    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
    }
    CONTRACTL_END;

#define ENABLE_ETW
#ifdef ENABLE_ETW
    if (g_pEtwTracer == NULL)
    {
        NewHolder <CEtwTracer> tempEtwTracer (new (nothrow) CEtwTracer());
        if (tempEtwTracer != NULL && tempEtwTracer->Register () == ERROR_SUCCESS)
            g_pEtwTracer = tempEtwTracer.Extract ();
    }
#endif  //ENABLE_ETW
}


// For ConvertLangIDToCultureName, found in culture.dll
typedef BOOL (STDMETHODCALLTYPE *PConvertLangIDToCultureName)(LANGID langID, LPWSTR pwzCultureName, SIZE_T* pcchCultureName, LPWSTR pwzParentName, SIZE_T *pcchParentName);

static BOOL callConvertLangIDToCultureName(LANGID langID, __out_opt LPWSTR pwzCultureName, SIZE_T* pcchCultureName, __out_opt LPWSTR pwzParentName, SIZE_T *pcchParentName)
{
    BOOL res = FALSE;

    HModuleHolder hCulture(NULL);
    if (SUCCEEDED(LoadLibraryShim(MAKEDLLNAME_W(L"culture"), NULL, 0, &hCulture)))
    {
        PConvertLangIDToCultureName pfnConvertLangIDToCultureName = NULL;

        pfnConvertLangIDToCultureName = (PConvertLangIDToCultureName) GetProcAddress(hCulture, "ConvertLangIdToCultureName");
        _ASSERTE(pfnConvertLangIDToCultureName != NULL);

        if (pfnConvertLangIDToCultureName != NULL)
        {
            res = pfnConvertLangIDToCultureName(langID, pwzCultureName, pcchCultureName, pwzParentName, pcchParentName);
        }
    }

    return res;
}// callConvertLangIDToCultureName

// ---------------------------------------------------------------------------
// Impl for UtilLoadStringRC Callback: In VM, we let the thread decide culture
// copy culture name into szBuffer and return length
// ---------------------------------------------------------------------------
static HRESULT GetThreadUICultureNames(__out_ecount(cchCultureName) LPWSTR wszCultureName, SIZE_T cchCultureName,
                                   __out_ecount(cchParentCultureName) LPWSTR wszParentCultureName, SIZE_T cchParentCultureName)
{
    CONTRACTL{
        NOTHROW;
        GC_NOTRIGGER;
        MODE_ANY;
        PRECONDITION(CheckPointer(wszCultureName));
        PRECONDITION(CheckPointer(wszParentCultureName));
        SO_INTOLERANT;
    } CONTRACTL_END;

    HRESULT hr = S_OK;
    SIZE_T cchCultureNameResult = 0;
    SIZE_T cchParentCultureNameResult = 0;

    _ASSERT(cchCultureName > 0);
    _ASSERT(cchParentCultureName > 0);
    
    wszCultureName[0] = 0;
    wszParentCultureName[0] = 0;

    Thread * pThread = GetThread();

    if (pThread != NULL) {

        // Switch to cooperative mode, since we'll be looking at managed objects
        // and we don't want them moving on us.
        GCX_COOP();

        THREADBASEREF pThreadBase = (THREADBASEREF)pThread->GetExposedObjectRaw();

        if (pThreadBase != NULL)
        {
            CULTUREINFOBASEREF pCurrentCulture = pThreadBase->GetCurrentUICulture();

            if (pCurrentCulture != NULL)
            {
                STRINGREF cultureName = pCurrentCulture->GetName();

                if (cultureName != NULL)
                {
                    cchCultureNameResult = cultureName->GetStringLength();
                    if (cchCultureNameResult < cchCultureName)
                    {
                        memcpy(wszCultureName, cultureName->GetBuffer(), cchCultureNameResult*sizeof(WCHAR));
                        wszCultureName[cchCultureNameResult]='\0';
                    }
                }

                CULTUREINFOBASEREF pParentCulture = pCurrentCulture->GetParent();

                if (pParentCulture != NULL)
                {
                    STRINGREF parentCultureName = pParentCulture->GetName();

                    if (parentCultureName != NULL)
                    {
                        cchParentCultureNameResult = parentCultureName->GetStringLength();
                        if (cchParentCultureNameResult < cchParentCultureName)
                        {
                            memcpy(wszParentCultureName, parentCultureName->GetBuffer(), cchParentCultureNameResult*sizeof(WCHAR));
                            wszParentCultureName[cchParentCultureNameResult]='\0';
                        }
                    }

                }
            }
        }
    }

    // If the lazily-initialized cultureinfo structures aren't initialized yet, we'll
    // need to do the lookup the hard way.
    if (cchCultureNameResult == 0 || cchParentCultureNameResult==0)
    {
        INT32 id = GetThreadUICultureId();
        _ASSERTE(id !=0 && id != (int)UICULTUREID_DONTCARE);

        if (!callConvertLangIDToCultureName(id, wszCultureName, &cchCultureName, wszParentCultureName, &cchParentCultureName))    
        {
            hr = E_FAIL;
        }                
    }

    return hr;
}

// ---------------------------------------------------------------------------
// Impl for UtilLoadStringRC Callback: In VM, we let the thread decide culture
// Return an int uniquely describing which language this thread is using for ui.
// ---------------------------------------------------------------------------
static int GetThreadUICultureId()
{
    CONTRACTL{
        NOTHROW;
        GC_NOTRIGGER;
        MODE_ANY;
        SO_INTOLERANT;;
    } CONTRACTL_END;


    int Result = UICULTUREID_DONTCARE;

    Thread * pThread = GetThread();

    if (pThread != NULL) {

        // Switch to cooperative mode, since we'll be looking at managed objects
        // and we don't want them moving on us.
        GCX_COOP();

        THREADBASEREF pThreadBase = (THREADBASEREF)pThread->GetExposedObjectRaw();

        if (pThreadBase != NULL)
        {
            CULTUREINFOBASEREF pCurrentCulture = pThreadBase->GetCurrentUICulture();

            if (pCurrentCulture != NULL)
                Result = pCurrentCulture->GetCultureID();
        }
    }

    if (Result == (int)UICULTUREID_DONTCARE)
    {
        // This thread isn't set up to use a non-default culture. Let's grab the default
        // one and return that.


        if (Result == 0 || Result == (int)UICULTUREID_DONTCARE)
            Result = GetUserDefaultLangID();

        _ASSERTE(Result != 0);
        if (Result == 0)
        {
            Result = (int)UICULTUREID_DONTCARE;
        }
    }

    return Result;
}

// ---------------------------------------------------------------------------
// Export shared logging code for JIT, et.al.
// ---------------------------------------------------------------------------
#ifdef _DEBUG

extern VOID LogAssert( LPCSTR szFile, int iLine, LPCSTR expr);
extern "C"
//__declspec(dllexport)
VOID STDMETHODCALLTYPE LogHelp_LogAssert( LPCSTR szFile, int iLine, LPCSTR expr)
{
    CONTRACTL {
        NOTHROW;
        GC_NOTRIGGER;
        MODE_ANY;
        ENTRY_POINT;            
        PRECONDITION(CheckPointer(szFile));
        PRECONDITION(CheckPointer(expr));
    }  CONTRACTL_END;

    BEGIN_ENTRYPOINT_VOIDRET;
    LogAssert(szFile, iLine, expr);
    END_ENTRYPOINT_VOIDRET;

}

extern BOOL NoGuiOnAssert();
extern "C"
//__declspec(dllexport)
BOOL STDMETHODCALLTYPE LogHelp_NoGuiOnAssert()
{
    WRAPPER_CONTRACT;
    BOOL fRet = FALSE;
    BEGIN_ENTRYPOINT_VOIDRET;
    fRet = NoGuiOnAssert();
    END_ENTRYPOINT_VOIDRET;
    return fRet;
}

extern VOID TerminateOnAssert();
extern "C"
//__declspec(dllexport)
VOID STDMETHODCALLTYPE LogHelp_TerminateOnAssert()
{
    WRAPPER_CONTRACT;
    BEGIN_ENTRYPOINT_VOIDRET;
//  __asm int 3;
    TerminateOnAssert();
    END_ENTRYPOINT_VOIDRET;

}

#else // !_DEBUG

extern "C"
//__declspec(dllexport)
VOID STDMETHODCALLTYPE LogHelp_LogAssert( LPCSTR szFile, int iLine, LPCSTR expr) {
    LEAF_CONTRACT;

    //BEGIN_ENTRYPOINT_VOIDRET;
    //END_ENTRYPOINT_VOIDRET;
}

extern "C"
//__declspec(dllexport)
BOOL STDMETHODCALLTYPE LogHelp_NoGuiOnAssert() {
    LEAF_CONTRACT;

    //BEGIN_ENTRYPOINT_VOIDRET;
    //END_ENTRYPOINT_VOIDRET;

    return FALSE;
}

extern "C"
//__declspec(dllexport)
VOID STDMETHODCALLTYPE LogHelp_TerminateOnAssert() {
    LEAF_CONTRACT;

    //BEGIN_ENTRYPOINT_VOIDRET;
    //END_ENTRYPOINT_VOIDRET;

}

#endif // _DEBUG


#ifndef ENABLE_PERF_COUNTERS
//
// perf counter stubs for builds which don't have perf counter support
// These are needed because we export these functions in our DLL


Perf_Contexts* STDMETHODCALLTYPE GetPrivateContextsPerfCounters()
{
    LEAF_CONTRACT;

    //BEGIN_ENTRYPOINT_VOIDRET;
    //END_ENTRYPOINT_VOIDRET;

    return NULL;
}


#endif

#ifdef PLATFORM_UNIX
//
// This routine is not directly called from within the CLR.  It is called
// by the developer debugging the CLR, from within GDB.  It's best to put
// this in your .gdbinit file:
//  define sos
//  call (void)SOS("$arg0")
//  echo \n
//  end
//
// Then you can use SOS from the (gdb) prompt like this:
//  sos Help
//  sos DumpStack\ -EE
//               ^
//               | note that space characters must be escaped!
//
extern "C" void __cdecl SOS(__in char *Command)
{
    CONTRACTL {
        NOTHROW;
        GC_NOTRIGGER;
        MODE_PREEMPTIVE;
        PRECONDITION(CheckPointer(Command));
    } CONTRACTL_END;

    static HMODULE hSOS;

    if (!Command) {
        fprintf(stderr, "SOS:  you must specify a command to run\n");
        return;
    }

    if (!hSOS) {
        hSOS = CLRLoadLibrary(MAKEDLLNAME_W(L"sos"));
        if (!hSOS) {
            fprintf(stderr, "SOS:  Failed to load " MAKEDLLNAME_A("sos") ".  LastErr=%d\n",
               GetLastError());
       return;
    }
    }

    typedef void (*SOSAPI)(HMODULE, char *);
    static SOSAPI pfnSOSAPI;

    if (!pfnSOSAPI) {
    pfnSOSAPI = (SOSAPI)GetProcAddress(hSOS, "GDBSOS");
    if (!pfnSOSAPI) {
        fprintf(stderr, "SOS:  Couldn't find GDBSOS() in libsos.so");
            return;
        }
    }

        (*pfnSOSAPI)(hSOS, Command);

    // It is a bad idea to load and free libsos back and forth since it is
    //  just increasing the chance of crashing in the debugged process
    // FreeLibrary(hSOS);
}
#endif //PLATFORM_UNIX

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