summaryrefslogtreecommitdiff
path: root/src/vm/ceemain.cpp
blob: 8f2c46fbc558449d8bfc2fdbf57b653c31fcbc51 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
// ===========================================================================
// File: CEEMAIN.CPP
// ===========================================================================
//

// 
//
// The CLR code base uses a hyperlink feature of the HyperAddin plugin for Visual Studio. If you don't see
// 'HyperAddin' in your Visual Studio menu bar you don't have this support. To get it type 
// 
//     \\clrmain\tools\installCLRAddins
//     
//  After installing HyperAddin, your first run of VS should be as an administrator so HyperAddin can update 
//  some registry information.
//     
//  At this point the code: prefixes become hyperlinks in Visual Studio and life is good. See
//  http://mswikis/clr/dev/Pages/CLR%20Team%20Commenting.aspx for more information
//  
//  There is a bug associated with Visual Studio where it does not recognise the hyperlink if there is a ::
//  preceeding it on the same line. Since C++ uses :: as a namespace separator, this can often mean that the
//  second hyperlink on a line does not work. To work around this it is better to use '.' instead of :: as
//  the namespace separators in code: hyperlinks.
// 
// #StartHere
// #TableOfContents The .NET Runtime Table of contents
// 
// This comment is mean to be a nexus that allows you to jump quickly to various interesting parts of the
// runtime.
// 
// You can refer to product studio bugs using urls like the following
//     * http://bugcheck/bugs/DevDivBugs/2320.asp
//     * http://bugcheck/bugs/VSWhidbey/601210.asp
//     
//  Dev10 Bugs can be added with URLs like the following (for Dev10 bug 671409)
//     * http://tkbgitvstfat01:8090/wi.aspx?id=671409
// 
//*************************************************************************************************
//
// * Introduction to the runtime file:../../Documentation/botr/botr-faq.md
//
// #MajorDataStructures. The major data structures associated with the runtime are
//     * code:Thread (see file:threads.h#ThreadClass) - the additional thread state the runtime needs.
//     * code:AppDomain - The managed version of a process
//     * code:Assembly - The unit of deployment and versioning (may be several DLLs but often is only one).
//     * code:Module - represents a Module (DLL or EXE).
//     * code:MethodTable - represents the 'hot' part of a type (needed during normal execution)
//     * code:EEClass - represents the 'cold' part of a type (used during compilation, interop, ...)
//     * code:MethodDesc - represents a Method
//     * code:FieldDesc - represents a Field.
//     * code:Object - represents a object on the GC heap allocated with code:Alloc 
// 
// * ECMA specifications
//     * Partition I Concepts
//         http://download.microsoft.com/download/D/C/1/DC1B219F-3B11-4A05-9DA3-2D0F98B20917/Partition%20I%20Architecture.doc
//     * Partition II Meta Data
//         http://download.microsoft.com/download/D/C/1/DC1B219F-3B11-4A05-9DA3-2D0F98B20917/Partition%20II%20Metadata.doc
//     * Partition III IL
//         http://download.microsoft.com/download/D/C/1/DC1B219F-3B11-4A05-9DA3-2D0F98B20917/Partition%20III%20CIL.doc
//  
//  * Serge Liden (worked on the CLR and owned ILASM / ILDASM for a long time wrote a good book on IL
//     * Expert .NET 2.0 IL Assembler  http://www.amazon.com/Expert-NET-2-0-IL-Assembler/dp/1590596463
// 
// * This is also a pretty nice overview of what the CLR is at
//     http://msdn2.microsoft.com/en-us/netframework/aa497266.aspx
// 
// * code:EEStartup - This routine must be called before any interesting runtime services are used. It is
//     invoked as part of mscorwks's DllMain logic.
// * code:#EEShutDown - Code called before we shut down the EE.
//     
// * file:..\inc\corhdr.h#ManagedHeader - From a data structure point of view, this is the entry point into
//     the runtime. This is how all other data in the EXE are found.
//  
// * code:ICorJitCompiler#EEToJitInterface - This is the interface from the the EE to the Just in time (JIT)
//     compiler. The interface to the JIT is relatively simple (compileMethod), however the EE provides a
//     rich set of callbacks so the JIT can get all the information it needs. See also
//     file:../../Documentation/botr/ryujit-overview.md for general information on the JIT.
// 
// * code:VirtualCallStubManager - This is the main class that implements interface dispatch
// 
// * Precode - Every method needs entry point for other code to call even if that native code does not
//     actually exist yet. To support this methods can have code:Precode that is an entry point that exists
//     and will call the JIT compiler if the code does not yet exist.
//     
//  * NGEN - NGen stands for Native code GENeration and it is the runtime way of precompiling IL and IL
//      Meta-data into native code and runtime data structures. At compilation time the most
//      fundamental data structures is the code:ZapNode which represents something that needs to go into the
//      NGEN image.
//      
//   * What is cooperative / preemtive mode ? file:threads.h#CooperativeMode and
//       file:threads.h#SuspendingTheRuntime and file:../../Documentation/botr/threading.md
//   * Garbage collection - file:gc.cpp#Overview and file:../../Documentation/botr/garbage-collection.md
//   * code:AppDomain - The managed version of a process.
//   * Calling Into the runtime (FCALLs QCalls) file:../../Documentation/botr/mscorlib.md
//   * Exceptions - file:../../Documentation/botr/exceptions.md. The most important routine to start
//       with is code:COMPlusFrameHandler which is the routine that we hook up to get called when an unmanaged
//       exception happens.
//   * Assembly Loading file:../../Documentation/botr/type-loader.md
//   * Profiling file:../../Documentation/botr/profiling.md and file:../../Documentation/botr/profilability.md
//   * FCALLS QCALLS (calling into the runtime from managed code)
//       file:../../Documentation/botr/mscorlib.md
//   * Event Tracing for Windows
//     * file:../inc/eventtrace.h#EventTracing -
//     * This is the main file dealing with event tracing in CLR
//     * The implementation of this class is available in file:eventtrace.cpp
//     * file:../inc/eventtrace.h#CEtwTracer - This is the main class dealing with event tracing in CLR.
//         Follow the link for more information on how this feature has been implemented
//     * http://mswikis/clr/dev/Pages/CLR%20ETW%20Events%20Wiki.aspx - Follow the link for more information on how to
//         use this instrumentation feature.

// ----------------------------------------------------------------------------------------------------
// Features in the runtime that have been given hyperlinks
// 
// * code:Nullable#NullableFeature - the Nullable<T> type has special runtime semantics associated with
//     boxing this describes this feature.

#include "common.h"

#include "vars.hpp"
#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 "eeconfig.h"
#include "stublink.h"
#include "method.hpp"
#include "codeman.h"
#include "frames.h"
#include "threads.h"
#include "stackwalk.h"
#include "gcheaputilities.h"
#include "interoputil.h"
#include "fieldmarshaler.h"
#include "dbginterface.h"
#include "eedbginterfaceimpl.h"
#include "debugdebugger.h"
#include "cordbpriv.h"
#include "comdelegate.h"
#include "appdomain.hpp"
#include "eventtrace.h"
#include "corhost.h"
#include "binder.h"
#include "olevariant.h"
#include "comcallablewrapper.h"
#include "apithreadstress.h"
#include "perflog.h"
#include "../dlls/mscorrc/resource.h"
#include "util.hpp"
#include "shimload.h"
#include "comthreadpool.h"
#include "posterror.h"
#include "virtualcallstub.h"
#include "strongnameinternal.h"
#include "syncclean.hpp"
#include "typeparse.h"
#include "debuginfostore.h"
#include "eemessagebox.h"
#include "finalizerthread.h"
#include "threadsuspend.h"
#include "disassembler.h"
#include "jithost.h"

#ifndef FEATURE_PAL
#include "dwreport.h"
#endif // !FEATURE_PAL

#include "stringarraylist.h"
#include "stubhelpers.h"

#ifdef FEATURE_STACK_SAMPLING
#include "stacksampler.h"
#endif

#include <shlwapi.h>

#include "bbsweep.h"


#ifdef FEATURE_COMINTEROP
#include "runtimecallablewrapper.h"
#include "notifyexternals.h"
#include "mngstdinterfaces.h"
#include "rcwwalker.h"
#endif // FEATURE_COMINTEROP

#ifdef FEATURE_COMINTEROP_APARTMENT_SUPPORT
#include "olecontexthelpers.h"
#endif // FEATURE_COMINTEROP_APARTMENT_SUPPORT

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

#ifdef FEATURE_COMINTEROP
#include "synchronizationcontextnative.h"       // For SynchronizationContextNative::Cleanup
#endif

#ifdef FEATURE_INTERPRETER
#include "interpreter.h"
#endif // FEATURE_INTERPRETER

#include "../binder/inc/coreclrbindercommon.h"


#ifdef FEATURE_PERFMAP
#include "perfmap.h"
#endif

#include "diagnosticserver.h"
#include "eventpipe.h"

#ifndef FEATURE_PAL
// Included for referencing __security_cookie
#include "process.h"
#endif // !FEATURE_PAL

#ifdef FEATURE_GDBJIT
#include "gdbjit.h"
#endif // FEATURE_GDBJIT

#ifndef CROSSGEN_COMPILE
static int GetThreadUICultureId(__out LocaleIDValue* pLocale);  // TODO: This shouldn't use the LCID.  We should rely on name instead

static HRESULT GetThreadUICultureNames(__inout StringArrayList* pCultureNames);
#endif // !CROSSGEN_COMPILE

HRESULT EEStartup(COINITIEE fFlags);


#ifndef CROSSGEN_COMPILE
static void InitializeGarbageCollector();

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




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

// Flag indicating if the EE has been started.  This is set prior to initializing the default AppDomain, and so does not indicate that
// the EE is fully able to execute arbitrary managed code.  To ensure the EE is fully started, call EnsureEEStarted rather than just
// checking this flag.
Volatile<BOOL> g_fEEStarted = FALSE;

// Flag indicating if the EE was started up by COM.
extern BOOL g_fEEComActivatedStartup;

// flag indicating that EE was not started up by IJW, Hosted, COM or my managed exe. 
extern BOOL g_fEEOtherStartup;

// The OS thread ID of the thread currently performing EE startup, or 0 if there is no such thread.
DWORD   g_dwStartupThreadId = 0;

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

static DangerousNonHostedSpinLock g_EEStartupLock;

HRESULT InitializeEE(COINITIEE flags)
{
    WRAPPER_NO_CONTRACT;
#ifdef FEATURE_EVENT_TRACE
    if(!g_fEEComActivatedStartup)
        g_fEEOtherStartup = TRUE;
#endif // FEATURE_EVENT_TRACE
    return EnsureEEStarted(flags);
}

// ---------------------------------------------------------------------------
// %%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,
    // which we will do further down.
    if (!g_fEEStarted)
    {
        BEGIN_ENTRYPOINT_NOTHROW;

#if defined(FEATURE_APPX) && !defined(CROSSGEN_COMPILE)
        STARTUP_FLAGS startupFlags = CorHost2::GetStartupFlags();
        // On CoreCLR, the host is in charge of determining whether the process is AppX or not.
        AppX::SetIsAppXProcess(!!(startupFlags & STARTUP_APPX_APP_MODEL));
#endif

#ifndef FEATURE_PAL
        // The sooner we do this, the sooner we avoid probing registry entries.
        // (Perf Optimization for VSWhidbey:113373.)
        REGUTIL::InitOptionalConfigCache();
#endif


        BOOL bStarted=FALSE;

        {
            DangerousNonHostedSpinLockHolder lockHolder(&g_EEStartupLock);

            // 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))
            {
                g_dwStartupThreadId = GetCurrentThreadId();

                EEStartup(flags);
                bStarted=g_fEEStarted;
                hr = g_EEStartupStatus;

                g_dwStartupThreadId = 0;
            }
            else
            {
                hr = g_EEStartupStatus;
                if (SUCCEEDED(g_EEStartupStatus))
                {
                    hr = S_FALSE;
                }
            }
        }

        END_ENTRYPOINT_NOTHROW;
    }
    else
    {
        //
        // g_fEEStarted is TRUE, but startup may not be complete since we initialize the default AppDomain
        // *after* setting that flag.  g_fEEStarted is set inside of g_EEStartupLock, and that lock is
        // not released until the EE is really started - so we can quickly check whether the EE is definitely
        // started by checking if that lock is currently held.  If it is not, then we know the other thread
        // (that is actually doing the startup) has finished startup.  If it is currently held, then we
        // need to wait for the other thread to release it, which we do by simply acquiring the lock ourselves.
        //
        // We do not want to do this blocking if we are the thread currently performing EE startup.  So we check
        // that first.
        //
        // Note that the call to IsHeld here is an "acquire" barrier, as is acquiring the lock.  And the release of 
        // the lock by the other thread is a "release" barrier, due to the volatile semantics in the lock's 
        // implementation.  This assures us that once we observe the lock having been released, we are guaranteed 
        // to observe a fully-initialized EE.
        //
        // A note about thread affinity here: we're using the OS thread ID of the current thread without
        // asking the host to pin us to this thread, as we did above.  We can get away with this, because we are
        // only interested in a particular thread ID (that of the "startup" thread) and *that* particular thread
        // is already affinitized by the code above.  So if we get that particular OS thread ID, we know for sure
        // we are really the startup thread.
        //
        if (g_EEStartupLock.IsHeld() && g_dwStartupThreadId != GetCurrentThreadId())
        {
            DangerousNonHostedSpinLockHolder lockHolder(&g_EEStartupLock);
        }

        hr = g_EEStartupStatus;
        if (SUCCEEDED(g_EEStartupStatus))
        {
            hr = S_FALSE;
        }
    }

    return hr;
}


#ifndef CROSSGEN_COMPILE

#ifndef FEATURE_PAL
// This is our Ctrl-C, Ctrl-Break, etc. handler.
static BOOL WINAPI DbgCtrlCHandler(DWORD dwCtrlType)
{
    WRAPPER_NO_CONTRACT;

#if defined(DEBUGGING_SUPPORTED)
    // Note that if a managed-debugger is attached, it's actually attached with the native
    // debugging pipeline and it will get a control-c notifications via native debug events.
    // However, if we let the native debugging pipeline handle the event and send the notification
    // to the debugger, then we break pre-V4 behaviour because we intercept handlers registered
    // in-process.  See Dev10 Bug 846455 for more information. 
    if (CORDebuggerAttached() &&
        (dwCtrlType == CTRL_C_EVENT || dwCtrlType == CTRL_BREAK_EVENT))
    {
        return g_pDebugInterface->SendCtrlCToDebugger(dwCtrlType);
    }
    else
#endif // DEBUGGING_SUPPORTED
    {
        if (dwCtrlType == CTRL_CLOSE_EVENT)
        {
            // Initiate shutdown so the ProcessExit handlers run
            ForceEEShutdown(SCA_ReturnWhenShutdownComplete);
        }

        g_fInControlC = true;     // only for weakening assertions in checked build.
        return FALSE;             // keep looking for a real handler.
    }
}
#endif

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



void InitializeStartupFlags()
{
    CONTRACTL {
        NOTHROW;
        GC_TRIGGERS;
        MODE_ANY;
    } CONTRACTL_END;

    STARTUP_FLAGS flags = CorHost2::GetStartupFlags();


    if (flags & STARTUP_CONCURRENT_GC)
        g_IGCconcurrent = 1;
    else
        g_IGCconcurrent = 0;


    g_heap_type = ((flags & STARTUP_SERVER_GC) && GetCurrentProcessCpuCount() > 1) ? GC_HEAP_SVR : GC_HEAP_WKS;
    g_IGCHoardVM = (flags & STARTUP_HOARD_GC_VM) == 0 ? 0 : 1;
}
#endif // CROSSGEN_COMPILE


// BBSweepStartFunction is the first function to execute in the BBT sweeper thread.
// It calls WatchForSweepEvent where we wait until a sweep occurs.
DWORD __stdcall BBSweepStartFunction(LPVOID lpArgs)
{
    CONTRACTL
    {
        THROWS;
        GC_TRIGGERS;
        MODE_PREEMPTIVE;
    }
    CONTRACTL_END;

    class CLRBBSweepCallback : public ICLRBBSweepCallback
    {
        virtual HRESULT WriteProfileData()
        {
            BEGIN_ENTRYPOINT_NOTHROW
            WRAPPER_NO_CONTRACT;
            Module::WriteAllModuleProfileData(false);
            END_ENTRYPOINT_NOTHROW;
            return S_OK;
        }
    } clrCallback;

    EX_TRY
    {
        g_BBSweep.WatchForSweepEvents(&clrCallback);
    }
    EX_CATCH
    {
    }
    EX_END_CATCH(RethrowTerminalExceptions)

    return 0;
}


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

void InitGSCookie()
{
    CONTRACTL
    {
        THROWS;
        GC_NOTRIGGER;
        MODE_ANY;
    }
    CONTRACTL_END;

    GSCookie * pGSCookiePtr = GetProcessGSCookiePtr();

    DWORD oldProtection;
    if(!ClrVirtualProtect((LPVOID)pGSCookiePtr, sizeof(GSCookie), PAGE_EXECUTE_READWRITE, &oldProtection))
    {
        ThrowLastError();
    }

#ifndef FEATURE_PAL
    // The GSCookie cannot be in a writeable page
    assert(((oldProtection & (PAGE_READWRITE|PAGE_WRITECOPY|PAGE_EXECUTE_READWRITE|
                              PAGE_EXECUTE_WRITECOPY|PAGE_WRITECOMBINE)) == 0));

    // Forces VC cookie to be initialized.
    void * pf = &__security_check_cookie;
    pf = NULL;

    GSCookie val = (GSCookie)(__security_cookie ^ GetTickCount());
#else // !FEATURE_PAL
    // REVIEW: Need something better for PAL...
    GSCookie val = (GSCookie)GetTickCount();
#endif // !FEATURE_PAL

#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;

    if(!ClrVirtualProtect((LPVOID)pGSCookiePtr, sizeof(GSCookie), oldProtection, &oldProtection))
    {
        ThrowLastError();
    }
}

Volatile<BOOL> g_bIsGarbageCollectorFullyInitialized = FALSE;

void SetGarbageCollectorFullyInitialized()
{
    LIMITED_METHOD_CONTRACT;

    g_bIsGarbageCollectorFullyInitialized = TRUE;
}

// Tells whether the garbage collector is fully initialized
// Stronger than IsGCHeapInitialized
BOOL IsGarbageCollectorFullyInitialized()
{
    LIMITED_METHOD_CONTRACT;

    return g_bIsGarbageCollectorFullyInitialized;
}

// ---------------------------------------------------------------------------
// %%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


#ifndef CROSSGEN_COMPILE
#ifdef FEATURE_PAL
void EESocketCleanupHelper()
{
    CONTRACTL
    {
        GC_NOTRIGGER;
        MODE_ANY;
    } CONTRACTL_END;

    // Close the debugger transport socket first
    if (g_pDebugInterface != NULL)
    {
        g_pDebugInterface->CleanupTransportSocket();
    }

    // Close the diagnostic server socket.
#ifdef FEATURE_PERFTRACING
    DiagnosticServer::Shutdown();
#endif // FEATURE_PERFTRACING
}
#endif // FEATURE_PAL
#endif // CROSSGEN_COMPILE

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

#ifdef ENABLE_CONTRACTS_IMPL
    {
        extern void ContractRegressionCheck();
        ContractRegressionCheck();
    }
#endif

    HRESULT hr = S_OK;
    static ConfigDWORD breakOnEELoad;
    EX_TRY
    {
        g_fEEInit = true;

#ifndef CROSSGEN_COMPILE

#ifndef FEATURE_PAL
        ::SetConsoleCtrlHandler(DbgCtrlCHandler, TRUE/*add*/);
#endif

#endif // CROSSGEN_COMPILE

        // SString initialization
        // This needs to be done before config because config uses SString::Empty()
        SString::Startup();

        IfFailGo(EEConfig::Setup());

#ifndef CROSSGEN_COMPILE
        // Initialize Numa and CPU group information
        // Need to do this as early as possible. Used by creating object handle
        // table inside Ref_Initialization() before GC is initialized.
        NumaNodeInfo::InitNumaNodeInfo();
#ifndef FEATURE_PAL
        CPUGroupInfo::EnsureInitialized();
#endif // !FEATURE_PAL

        // Initialize global configuration settings based on startup flags
        // This needs to be done before the EE has started
        InitializeStartupFlags();

        MethodDescBackpatchInfoTracker::StaticInitialize();

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

#ifdef FEATURE_PERFTRACING
        // Initialize the event pipe.
        EventPipe::Initialize();

#endif // FEATURE_PERFTRACING

#ifdef FEATURE_PAL
        PAL_SetShutdownCallback(EESocketCleanupHelper);
#endif // FEATURE_PAL

#ifdef FEATURE_GDBJIT
        // Initialize gdbjit
        NotifyGdb::Initialize();
#endif // FEATURE_GDBJIT

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

        // Fire the EE startup ETW event
        ETWFireEvent(EEStartupStart_V1);
#endif // FEATURE_EVENT_TRACE

        InitGSCookie();

        Frame::Init();

#endif // CROSSGEN_COMPILE


#ifdef STRESS_LOG
        if (REGUTIL::GetConfigDWORD_DontUse_(CLRConfig::UNSUPPORTED_StressLog, g_pConfig->StressLog ()) != 0) {
            unsigned facilities = REGUTIL::GetConfigDWORD_DontUse_(CLRConfig::INTERNAL_LogFacility, LF_ALL);
            unsigned level = REGUTIL::GetConfigDWORD_DontUse_(CLRConfig::EXTERNAL_LogLevel, LL_INFO1000);
            unsigned bytesPerThread = REGUTIL::GetConfigDWORD_DontUse_(CLRConfig::UNSUPPORTED_StressLogSize, STRESSLOG_CHUNK_SIZE * 4);
            unsigned totalBytes = REGUTIL::GetConfigDWORD_DontUse_(CLRConfig::UNSUPPORTED_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

#ifdef FEATURE_PERFMAP
        PerfMap::Initialize();
#endif

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

#ifndef CROSSGEN_COMPILE
#ifndef FEATURE_PAL
        IfFailGoLog(EnsureRtlFunctions());
#endif // !FEATURE_PAL
        InitEventStore();
#endif

        // Fusion
        // Initialize the general Assembly Binder infrastructure
        IfFailGoLog(CCoreCLRBinderHelper::Init());

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

        // Fire the runtime information ETW event
        ETW::InfoLog::RuntimeInformation(ETW::InfoLog::InfoStructs::Normal);

        if (breakOnEELoad.val(CLRConfig::UNSUPPORTED_BreakOnEELoad) == 1)
        {
#ifdef _DEBUG
            _ASSERTE(!"Start loading EE!");
#else
            DebugBreak();
#endif
        }

#ifdef ENABLE_STARTUP_DELAY
        PREFIX_ASSUME(NULL != g_pConfig);
        if (g_pConfig->StartupDelayMS())
        {
            ClrSleepEx(g_pConfig->StartupDelayMS(), FALSE);
        }
#endif
        
#if USE_DISASSEMBLER
        if ((g_pConfig->GetGCStressLevel() & (EEConfig::GCSTRESS_INSTR_JIT | EEConfig::GCSTRESS_INSTR_NGEN)) != 0)
        {
            Disassembler::StaticInitialize();
            if (!Disassembler::IsAvailable())
            {
                fprintf(stderr, "External disassembler is not available.\n");
                IfFailGo(E_FAIL);
            }
        }
#endif // USE_DISASSEMBLER

        // Monitors, Crsts, and SimpleRWLocks all use the same spin heuristics
        // Cache the (potentially user-overridden) values now so they are accessible from asm routines
        InitializeSpinConstants();

#ifndef CROSSGEN_COMPILE

        // Cross-process named objects are not supported in PAL
        // (see CorUnix::InternalCreateEvent - src/pal/src/synchobj/event.cpp.272)
#if !defined(FEATURE_PAL)
        // Initialize the sweeper thread.
        if (g_pConfig->GetZapBBInstr() != NULL)
        {
            DWORD threadID;
            HANDLE hBBSweepThread = ::CreateThread(NULL,
                                                   0,
                                                   (LPTHREAD_START_ROUTINE) BBSweepStartFunction,
                                                   NULL,
                                                   0,
                                                   &threadID);
            _ASSERTE(hBBSweepThread);
            g_BBSweep.SetBBSweepThreadHandle(hBBSweepThread);
        }
#endif // FEATURE_PAL

#ifdef FEATURE_INTERPRETER
        Interpreter::Initialize();
#endif // FEATURE_INTERPRETER

        StubManager::InitializeStubManagers();

#ifndef FEATURE_PAL
        {
            // Record mscorwks geometry
            PEDecoder pe(g_pMSCorEE);

            g_runtimeLoadedBaseAddress = (SIZE_T)pe.GetBase();
            g_runtimeVirtualSize = (SIZE_T)pe.GetVirtualSize();
            InitCodeAllocHint(g_runtimeLoadedBaseAddress, g_runtimeVirtualSize, GetRandomInt(64));
        }
#endif // !FEATURE_PAL

#endif // CROSSGEN_COMPILE

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

        AccessCheckOptions::Startup();

        MscorlibBinder::Startup();

        Stub::Init();
        StubLinkerCPU::Init();

#ifndef CROSSGEN_COMPILE

        InitializeGarbageCollector();

        // Initialize remoting

        if (!GCHandleUtilities::GetGCHandleManager()->Initialize())
        {
            IfFailGo(E_OUTOFMEMORY);
        }

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

        VirtualCallStubManager::InitStatic();

        GCInterface::m_MemoryPressureLock.Init(CrstGCMemoryPressure);

#endif // CROSSGEN_COMPILE

        // Setup the domains. Threads are started in a default domain.

        // Static initialization
        PEAssembly::Attach();
        BaseDomain::Attach();
        SystemDomain::Attach();

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

        COMDelegate::Init();

        ExecutionManager::Init();

        JitHost::Init();

#ifndef CROSSGEN_COMPILE

#ifndef FEATURE_PAL      
        if (!RegisterOutOfProcessWatsonCallbacks())
        {
            IfFailGo(E_FAIL);
        }
#endif // !FEATURE_PAL

#ifdef DEBUGGING_SUPPORTED
        if(!NingenEnabled())
        {
            // 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 = ProfilingAPIUtility::InitializeProfiling();

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

        InitializeExceptionHandling();

        //
        // Install our global exception filter
        //
        if (!InstallUnhandledExceptionFilter())
        {
            IfFailGo(E_FAIL);
        }

        // throws on error
        SetupThread();

#ifdef DEBUGGING_SUPPORTED
        // Notify debugger once the first thread is created to finish initialization.
        if (g_pDebugInterface != NULL)
        {
            g_pDebugInterface->StartupPhase2(GetThread());
        }
#endif

        InitPreStubManager();

#ifdef FEATURE_COMINTEROP
        InitializeComInterop();
#endif // FEATURE_COMINTEROP

        StubHelpers::Init();

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

        SyncBlockCache::Attach();

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

        StackwalkCache::Init();

        // This isn't done as part of InitializeGarbageCollector() above because it
        // requires write barriers to have been set up on x86, which happens as part
        // of InitJITHelpers1.
        hr = g_pGCHeap->Initialize();
        IfFailGo(hr);

        // This isn't done as part of InitializeGarbageCollector() above because thread
        // creation requires AppDomains to have been set up.
        FinalizerThread::FinalizerThreadCreate();

        // Now we really have fully initialized the garbage collector
        SetGarbageCollectorFullyInitialized();

#ifdef DEBUGGING_SUPPORTED
        // Make a call to publish the DefaultDomain for the debugger
        // This should be done before assemblies/modules are loaded into it (i.e. SystemDomain::Init)
        // and after its OK to switch GC modes and syncronize for sending events to the debugger.
        // @dbgtodo  synchronization: this can probably be simplified in V3
        LOG((LF_CORDB | LF_SYNC | LF_STARTUP, LL_INFO1000, "EEStartup: adding default domain 0x%x\n",
             SystemDomain::System()->DefaultDomain()));
        SystemDomain::System()->PublishAppDomainAndInformDebugger(SystemDomain::System()->DefaultDomain());
#endif

#endif // CROSSGEN_COMPILE

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

#ifdef PROFILING_SUPPORTED
        // <TODO>This is to compensate for the DefaultDomain workaround contained in
        // SystemDomain::Attach in which the first user domain is created before profiling
        // services can be initialized.  Profiling services cannot be moved to before the
        // workaround because it needs SetupThread to be called.</TODO>

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

        g_fEEInit = false;

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

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

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

#ifndef CROSSGEN_COMPILE
        if (!NingenEnabled())
        {
            // Perform any once-only SafeHandle initialization.
            SafeHandle::Init();
        }

#ifdef FEATURE_MINIMETADATA_IN_TRIAGEDUMPS
        // retrieve configured max size for the mini-metadata buffer (defaults to 64KB)
        g_MiniMetaDataBuffMaxSize = CLRConfig::GetConfigValue(CLRConfig::INTERNAL_MiniMdBufferCapacity);
        // align up to GetOsPageSize(), with a maximum of 1 MB
        g_MiniMetaDataBuffMaxSize = (DWORD) min(ALIGN_UP(g_MiniMetaDataBuffMaxSize, GetOsPageSize()), 1024 * 1024);
        // allocate the buffer. this is never touched while the process is running, so it doesn't 
        // contribute to the process' working set. it is needed only as a "shadow" for a mini-metadata
        // buffer that will be set up and reported / updated in the Watson process (the 
        // DacStreamsManager class coordinates this)
        g_MiniMetaDataBuffAddress = (TADDR) ClrVirtualAlloc(NULL, 
                                                g_MiniMetaDataBuffMaxSize, MEM_COMMIT, PAGE_READWRITE);
#endif // FEATURE_MINIMETADATA_IN_TRIAGEDUMPS

#endif // CROSSGEN_COMPILE

        g_fEEStarted = TRUE;
#ifndef CROSSGEN_COMPILE
#ifdef FEATURE_PERFTRACING
        DiagnosticServer::Initialize();
#endif
#endif
        g_EEStartupStatus = S_OK;
        hr = S_OK;
        STRESS_LOG0(LF_STARTUP, LL_ALWAYS, "===================EEStartup Completed===================");

#ifndef CROSSGEN_COMPILE

#ifdef _DEBUG

        //if g_fEEStarted was false when we loaded the System Module, we did not run ExpandAll on it.  In
        //this case, make sure we run ExpandAll here.  The rationale is that if we Jit before g_fEEStarted
        //is true, we can't initialize Com, so we can't jit anything that uses Com types.  Also, it's
        //probably not safe to Jit while g_fEEStarted is false.
        //
        //Also, if you run this it's possible we'll call CoInitialize, which defaults to MTA.  This might
        //mess up an application that uses STA.  However, this mode is only supported for certain limited
        //jit testing scenarios, so it can live with the limitation.
        if (g_pConfig->ExpandModulesOnLoad())
        {
            SystemDomain::SystemModule()->ExpandAll();
        }

        // Perform mscorlib consistency check if requested
        g_Mscorlib.CheckExtended();

#endif // _DEBUG

#ifdef HAVE_GCCOVER
        MethodDesc::Init();
#endif

#endif // !CROSSGEN_COMPILE

ErrExit: ;
    }
    EX_CATCH
    {
#ifdef CROSSGEN_COMPILE
        // for minimal impact we won't update hr for regular builds
        hr = GET_EXCEPTION()->GetHR();
        _ASSERTE(FAILED(hr));
        StackSString exceptionMessage;
        GET_EXCEPTION()->GetMessage(exceptionMessage);
        fprintf(stderr, "%S\n", exceptionMessage.GetUnicode());
#endif // CROSSGEN_COMPILE
    }
    EX_END_CATCH(RethrowTerminalExceptionsWithInitCheck)

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

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

        g_EEStartupStatus = hr;
    }

    if (breakOnEELoad.val(CLRConfig::UNSUPPORTED_BreakOnEELoad) == 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;
}

// EEStartup is responsible for all the one time intialization of the runtime.  Some of the highlights of
// what it does include
//     * Creates the default and shared, appdomains. 
//     * Loads mscorlib.dll and loads up the fundamental types (System.Object ...)
// 
// see code:EEStartup#TableOfContents for more on the runtime in general. 
// see code:#EEShutdown for a analagous routine run during shutdown. 
// 
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(COINITIEE *, pfFlags, &fFlags)
    {
#ifndef CROSSGEN_COMPILE
        InitializeClrNotifications();
#ifdef FEATURE_PAL
        InitializeJITNotificationTable();
        DacGlobals::Initialize();
#endif
#endif // CROSSGEN_COMPILE

        EEStartupHelper(*pfFlags);
    }
    PAL_EXCEPT_FILTER (FilterStartupException)
    {
        // The filter should have set g_EEStartupStatus to a failure HRESULT.
        _ASSERTE(FAILED(g_EEStartupStatus));
    }
    PAL_ENDTRY

    return g_EEStartupStatus;
}


#ifndef CROSSGEN_COMPILE

#ifdef FEATURE_COMINTEROP

void InnerCoEEShutDownCOM()
{
    CONTRACTL
    {
        THROWS;
        GC_TRIGGERS;
        MODE_ANY;
    } CONTRACTL_END;

    static LONG AlreadyDone = -1;

    if (g_fEEStarted != TRUE)
        return;

    if (FastInterlockIncrement(&AlreadyDone) != 0)
        return;

    g_fShutDownCOM = true;

    // Release IJupiterGCMgr *
    RCWWalker::OnEEShutdown();

    // Release all of the RCWs in all contexts in all caches.
    ReleaseRCWsInCaches(NULL);

#ifdef FEATURE_APPX    
    // Cleanup cached factory pointer in SynchronizationContextNative
    SynchronizationContextNative::Cleanup();
#endif    
}

#endif // FEATURE_COMINTEROP

// ---------------------------------------------------------------------------
// %%Function: ForceEEShutdown()
//
// Description: Force the EE to shutdown now.
// 
// Note: returns when sca is SCA_ReturnWhenShutdownComplete.
// ---------------------------------------------------------------------------
void ForceEEShutdown(ShutdownCompleteAction sca)
{
    WRAPPER_NO_CONTRACT;

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

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

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
        {
#ifdef PROFILING_SUPPORTED
            if (CORProfilerPresent())
            {
                // A profiler is loaded, so just wait without timeout. This allows
                // profilers to complete potentially lengthy post processing, without the
                // CLR killing them off first. The Office team's server memory profiler,
                // for example, does a lot of post-processing that can exceed the 80
                // second imit we normally impose here. The risk of waiting without
                // timeout is that, if there really is a deadlock, shutdown will hang.
                // Since that will only happen if a profiler is loaded, that is a
                // reasonable compromise
                timeout = INFINITE;
            }
            else
#endif //PROFILING_SUPPORTED
            {
                timeout = static_cast<DWORD>(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);

    Thread *pThread = GetThread();
    // After a thread is blocked in WaitForEndOfShutdown, the thread should not enter runtime again,
    // and block at WaitForEndOfShutdown again.
    if (pThread)
    {
        _ASSERTE(!pThread->HasThreadStateNC(Thread::TSNC_BlockedForShutdown));
        pThread->SetThreadStateNC(Thread::TSNC_BlockedForShutdown);
    }

    while (!WaitForEndOfShutdown_OneIteration());
}

// ---------------------------------------------------------------------------
// Function: EEShutDownHelper(BOOL fIsDllUnloading)
//
// The real meat of shut down happens here.  See code:#EEShutDown for details, including
// what fIsDllUnloading means.
//
void STDMETHODCALLTYPE EEShutDownHelper(BOOL fIsDllUnloading)
{
    CONTRACTL
    {
        NOTHROW;
        GC_TRIGGERS;
        MODE_ANY;
    } CONTRACTL_END;

    // Used later for a callback.
    CEEInfo ceeInf;

    if (fIsDllUnloading)
    {
        ETW::EnumerationLog::ProcessShutdown();
    }

#ifdef FEATURE_PERFTRACING
    if (!fIsDllUnloading)
    {
        EventPipe::Shutdown();
        DiagnosticServer::Shutdown();
    }
#endif // FEATURE_PERFTRACING

#if defined(FEATURE_COMINTEROP)
    // Get the current thread.
    Thread * pThisThread = GetThread();
#endif

    // 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 (CLRConfig::GetConfigValue(CLRConfig::INTERNAL_BreakOnEEShutdown))
        _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

    EX_TRY
    {
        ClrFlsSetThreadType(ThreadType_Shutdown);

        if (fIsDllUnloading && 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;

        // Terminate the BBSweep thread
        g_BBSweep.ShutdownBBSweepThread();

        if (!g_fProcessDetach && !g_fFastExitProcess)
        {
            g_fEEShutDown |= ShutDown_Finalize1;

            // Wait for the finalizer thread to deliver process exit event
            GCX_PREEMP();
            FinalizerThread::RaiseShutdownEvents();
        }

        // Ok.  Let's stop the EE.
        if (!g_fProcessDetach)
        {
            // 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;
        }

#ifdef FEATURE_EVENT_TRACE
        // Flush managed object allocation logging data.
        // We do this after finalization is complete and returning threads have been trapped, so that
        // no there will be no more managed allocations and no more GCs which will manipulate the
        // allocation sampling data structures.
        ETW::TypeSystemLog::FlushObjectAllocationEvents();
#endif // FEATURE_EVENT_TRACE

#ifdef FEATURE_PERFMAP
        // Flush and close the perf map file.
        PerfMap::Destroy();
#endif

        {
            // If we're doing basic block profiling, we need to write the log files to disk.
            static BOOL fIBCLoggingDone = FALSE;
            if (!fIBCLoggingDone)
            {
                if (g_IBCLogger.InstrEnabled())
                {
                    Thread * pThread = GetThread();
                    ThreadLocalIBCInfo* pInfo = pThread->GetIBCInfo();

                    // Acquire the Crst lock before creating the IBCLoggingDisabler object.
                    // Only one thread at a time can be processing an IBC logging event.
                    CrstHolder lock(IBCLogger::GetSync());
                    {
                        IBCLoggingDisabler disableLogging( pInfo );  // runs IBCLoggingDisabler::DisableLogging
                        
                        CONTRACT_VIOLATION(GCViolation);
                        Module::WriteAllModuleProfileData(true);
                    }
                }
                fIBCLoggingDone = TRUE;
            }
        }

        ceeInf.JitProcessShutdownWork();  // Do anything JIT-related that needs to happen at shutdown.

#ifdef FEATURE_INTERPRETER
        // This will check a flag and do nothing if not enabled.
        Interpreter::PrintPostMortemData();
#endif // FEATURE_INTERPRETER
        
#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

        // NOTE: We haven't stopped other threads at this point and nothing is stopping
        // callbacks from coming into the profiler even after Shutdown() has been called.
        // See https://github.com/dotnet/coreclr/issues/22176 for an example of how that
        // happens.
        //
        // To prevent issues when profilers are attached we intentionally skip freeing the
        // profiler here. Since there is no guarantee that the profiler won't be accessed after
        // we free it (e.g. through callbacks or ELT hooks), we can't safely free the profiler.
        if (CORProfilerPresent())
        {
            // Don't call back in to the profiler if we are being torn down, it might be unloaded
            if (!fIsDllUnloading)
            {
                BEGIN_PIN_PROFILER(CORProfilerPresent());
                GCX_PREEMP();
                g_profControlBlock.pProfInterface->Shutdown();
                END_PIN_PROFILER();
            }

            g_fEEShutDown |= ShutDown_Profiler;
        }
#endif // PROFILING_SUPPORTED


#ifdef _DEBUG
        g_fEEShutDown |= ShutDown_SyncBlock;
#endif
        {
            // From here on out we might call stuff that violates mode requirements, but we ignore these
            // because we are shutting down.
            CONTRACT_VIOLATION(ModeViolation);

#ifdef FEATURE_COMINTEROP
            // We need to call CoUninitialize in part one to ensure orderly shutdown of COM dlls.
            if (!g_fFastExitProcess)
            {
                if (pThisThread!= NULL)
                {
                    pThisThread->CoUninitialize();
                }
            }
#endif // FEATURE_COMINTEROP
        }

        // This is the end of Part 1.

part2:
        // If process shutdown is in progress and Crst locks to be used in shutdown phase 2
        // are already in use, then skip phase 2. This will happen only when those locks
        // are orphaned. In Vista, the penalty for attempting to enter such locks is 
        // instant process termination.
        if (g_fProcessDetach)
        {
            // The assert below is a bit too aggresive and has generally brought cases that have been race conditions
            // and not easily reproed to validate a bug. A typical race scenario is when there are two threads,
            // T1 and T2, with T2 having taken a lock (e.g. SystemDomain lock), the OS terminates
            // T2 for some reason. Later, when we enter the shutdown thread, we would assert on such
            // a lock leak, but there is not much we can do since the OS wont notify us prior to thread 
            // termination. And this is not even a user bug.
            //
            // Converting it to a STRESS LOG to reduce noise, yet keep things in radar if they need
            // to be investigated.
            //_ASSERTE_MSG(g_ShutdownCrstUsageCount == 0, "Some locks to be taken during shutdown may already be orphaned!");
            if (g_ShutdownCrstUsageCount > 0)
            {
                STRESS_LOG0(LF_STARTUP, LL_INFO10, "Some locks to be taken during shutdown may already be orphaned!");
                goto lDone;
            }
        }

        {
            CONTRACT_VIOLATION(ModeViolation);

            // 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();

                // <TODO>@TODO: This does things which shouldn't occur in part 2.  Namely,
                // calling managed dll main callbacks (AppDomain::SignalProcessDetach), and
                // RemoveAppDomainFromIPC.
                //
                // (If we move those things to earlier, this can be called only if fShouldWeCleanup.)</TODO>
                if (!g_fFastExitProcess)
                {
                    SystemDomain::DetachBegin();
                }


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

                StubManager::TerminateStubManagers();

#ifdef FEATURE_INTERPRETER
                Interpreter::Terminate();
#endif // FEATURE_INTERPRETER

                //@TODO: find the right place for this
                VirtualCallStubManager::UninitStatic();

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

                // Unregister our vectored exception and continue handlers from the OS.
                // This will ensure that if any other DLL unload (after ours) has an exception,
                // we wont attempt to process that exception (which could lead to various
                // issues including AV in the runtime).
                //
                // This should be done:
                //
                // 1) As the last action during the shutdown so that any unexpected AVs
                //    in the runtime during shutdown do result in FailFast in VEH.
                //
                // 2) Only when the runtime is processing DLL_PROCESS_DETACH. 
                CLRRemoveVectoredHandlers();

#if USE_DISASSEMBLER
                Disassembler::StaticClose();
#endif // USE_DISASSEMBLER

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


#ifdef LOGGING
                extern unsigned FcallTimeHist[11];
#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 0       // Dont clean up the stress log, so that even at process exit we have a log (after all the process is going away
                if (!g_fFastExitProcess)
                    StressLog::Terminate(TRUE);
#endif

#ifdef LOGGING
                ShutdownLogging();
#endif
            }
        }    

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

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


#ifdef FEATURE_COMINTEROP

BOOL IsThreadInSTA()
{
    CONTRACTL
    {
        NOTHROW;
        GC_TRIGGERS;
        MODE_ANY;
    }
    CONTRACTL_END;

    // If ole32.dll is not loaded
    if (WszGetModuleHandle(W("ole32.dll")) == NULL)
    {
        return FALSE;
    }

    BOOL fInSTA = TRUE;
    // To be conservative, check if finalizer thread is around
    EX_TRY
    {
        Thread *pFinalizerThread = FinalizerThread::GetFinalizerThread();
        if (!pFinalizerThread || pFinalizerThread->Join(0, FALSE) != WAIT_TIMEOUT)
        {
            fInSTA = FALSE;
        }
    }
    EX_CATCH
    {
    }
    EX_END_CATCH(SwallowAllExceptions);

    if (!fInSTA)
    {
        return FALSE;
    }

    THDTYPE type;
    HRESULT hr = S_OK;

    hr = GetCurrentThreadTypeNT5(&type);
    if (hr == S_OK)
    {
        fInSTA = (type == THDTYPE_PROCESSMESSAGES) ? TRUE : FALSE;

        // If we get back THDTYPE_PROCESSMESSAGES, we are guaranteed to
        // be an STA thread. If not, we are an MTA thread, however
        // we can't know if the thread has been explicitly set to MTA
        // (via a call to CoInitializeEx) or if it has been implicitly
        // made MTA (if it hasn't been CoInitializeEx'd but CoInitialize
        // has already been called on some other thread in the process.
    }
    else
    {
        // CoInitialize hasn't been called in the process yet so assume the current thread
        // is MTA. 
        fInSTA = FALSE;
    }

    return fInSTA;
}
#endif

// #EEShutDown
// 
// Function: EEShutDown(BOOL fIsDllUnloading)
//
// Parameters:
//    BOOL fIsDllUnloading:
//         * TRUE => Called from CLR's DllMain (DLL_PROCESS_DETACH). Not safe point for
//             full cleanup
//         * FALSE => Called some other way (e.g., end of the CLR's main). Safe to do
//             full cleanup.
//
// Description:
// 
//     All ee shutdown stuff should be done here. EEShutDown is generally called in one
//     of two ways:
//     * 1. From code:EEPolicy::HandleExitProcess (via HandleExitProcessHelper), with
//         fIsDllUnloading == FALSE. This code path is typically invoked by the CLR's
//         main just falling through to the end. Full cleanup can be performed when
//         EEShutDown is called this way.
//     * 2. From CLR's DllMain (DLL_PROCESS_DETACH), with fIsDllUnloading == TRUE. When
//         called this way, much cleanup code is unsafe to run, and is thus skipped.
// 
// Actual shut down logic is factored out to EEShutDownHelper which may be called
// directly by EEShutDown, or indirectly on another thread (see code:#STAShutDown).
//
// In order that callees may also know the value of fIsDllUnloading, EEShutDownHelper
// sets g_fProcessDetach = fIsDllUnloading, and g_fProcessDetach may then be retrieved
// via code:IsAtProcessExit.
//
// NOTE 1: Actually, g_fProcessDetach is set to TRUE if fIsDllUnloading is TRUE. But
// g_fProcessDetach doesn't appear to be explicitly set to FALSE. (Apparently
// g_fProcessDetach is implicitly initialized to FALSE as clr.dll is loaded.)
// 
// NOTE 2: EEDllMain(DLL_PROCESS_DETACH) already sets g_fProcessDetach to TRUE, so it
// appears EEShutDownHelper doesn't have to.
// 
void STDMETHODCALLTYPE EEShutDown(BOOL fIsDllUnloading)
{
    CONTRACTL {
        NOTHROW;
        GC_TRIGGERS;
        MODE_ANY;
        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;
    }

    // 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.
            GCX_PREEMP_NO_DTOR();
            WaitForEndOfShutdown();
            return;
        }

#ifdef FEATURE_MULTICOREJIT
        if (!AppX::IsAppXProcess()) // When running as Appx, make the delayed timer driven writing be the only option
        {
            MulticoreJitManager::StopProfileAll();
        }
#endif
    }

    if (GetThread())
    {
        GCX_COOP();
        EEShutDownHelper(fIsDllUnloading);
    }
    else
    {
        EEShutDownHelper(fIsDllUnloading);
    }
}

// ---------------------------------------------------------------------------
// %%Function: IsRuntimeActive()
//
// Parameters:
//  none
//
// Returns:
//  TRUE or FALSE
//
// Description: Indicates if the runtime is active or not. "Active" implies
//              that the runtime has started and is in a position to run
//              managed code.
// ---------------------------------------------------------------------------
BOOL IsRuntimeActive()
{
    return (g_fEEStarted);
}

//*****************************************************************************
BOOL ExecuteDLL_ReturnOrThrow(HRESULT hr, BOOL fFromThunk)
{
    CONTRACTL {
        if (fFromThunk) THROWS; else NOTHROW;
        WRAPPER(GC_TRIGGERS);
        MODE_ANY;
    } 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);
}

//
// Initialize the Garbage Collector
//

void InitializeGarbageCollector()
{
    CONTRACTL{
        THROWS;
        GC_TRIGGERS;
        MODE_ANY;
    } CONTRACTL_END;

    HRESULT hr;

    // Build the special Free Object used by the Generational GC
    _ASSERT(g_pFreeObjectMethodTable == NULL);
    g_pFreeObjectMethodTable = (MethodTable *) new BYTE[sizeof(MethodTable)];
    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(ARRAYBASE_BASESIZE);
    g_pFreeObjectMethodTable->SetComponentSize(1);

    hr = GCHeapUtilities::LoadAndInitialize();
    if (hr != S_OK)
    {
        ThrowHR(hr);
    }

    // Apparently the Windows linker removes global variables if they are never
    // read from, which is a problem for g_gcDacGlobals since it's expected that
    // only the DAC will read from it. This forces the linker to include
    // g_gcDacGlobals.
    volatile void* _dummy = g_gcDacGlobals;
}

/*****************************************************************************/
/* This is here only so that if we get an exception we stop before we catch it */
LONG DllMainFilter(PEXCEPTION_POINTERS p, PVOID pv)
{
    LIMITED_METHOD_CONTRACT;
    _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;

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

    struct Param
    {
        HINSTANCE hInst;
        DWORD dwReason;
        LPVOID lpReserved;
        void **pTlsData;
    } param;
    param.hInst = hInst;
    param.dwReason = dwReason;
    param.lpReserved = lpReserved;
    param.pTlsData = NULL;

    // 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(Param *, pParam, &param, pParam->dwReason)
    {

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

                // Remember module instance
                g_pMSCorEE = pParam->hInst;


                // Set callbacks so that LoadStringRC knows which language our
                // threads are in so that it can return the proper localized string.
            // TODO: This shouldn't rely on the LCID (id), but only the name
                SetResourceCultureCallbacks(GetThreadUICultureNames,
                                            GetThreadUICultureId);

                InitEEPolicy();

                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(pParam->lpReserved || !g_fEEStarted);
                g_fProcessDetach = TRUE;

                if (g_fEEStarted)
                {
                    if (GCHeapUtilities::IsGCInProgress())
                    {
                        g_fEEShutDown |= ShutDown_Phase2;
                        break;
                    }

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

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

                // Store the TLS data; we'll need it later and we might NULL the slot in DetachThread.
                // This would be problematic because we can't depend on the FLS still existing.
                pParam->pTlsData = CExecutionEngine::CheckThreadStateNoCreate(0
#ifdef _DEBUG
                 // When we get here, OS has destroyed FLS, so FlsGetValue returns NULL now.
                 // We have validation code in CExecutionEngine::CheckThreadStateNoCreate to ensure that
                 // our TLS and FLS data are consistent, but since FLS has been destroyed, we need
                 // to silent the check there.  The extra arg for check build is for this purpose.
                                                                                         , TRUE
#endif
                                                                                         );
                Thread* thread = GetThread();
                if (thread)
                {
#ifdef FEATURE_COMINTEROP
                    // reset the CoInitialize state
                    // so we don't call CoUninitialize during thread detach
                    thread->ResetCoInitialized();
#endif // FEATURE_COMINTEROP
                    // 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
                        GCX_COOP_NO_DTOR();
                        thread->m_pFrame = FRAME_TOP;
                        GCX_COOP_NO_DTOR_END();
                    }
                    thread->DetachThread(TRUE);
                }
            }
        }

    }
    PAL_EXCEPT_FILTER(DllMainFilter)
    {
    }
    PAL_ENDTRY;

    if (dwReason == DLL_THREAD_DETACH || dwReason == DLL_PROCESS_DETACH)
    {
        CExecutionEngine::ThreadDetaching(param.pTlsData);
    }
    return TRUE;
}

#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 the debug pack is not installed, Startup will return S_FALSE
        // and we should cleanup and proceed without debugging support.
        //
        if (hr != S_OK)
        {
            return;
        }
    }


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

    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_CORDebuggerControlFlags = DBCF_NORMAL_OPERATION;

}

#endif // DEBUGGING_SUPPORTED

#ifndef LOCALE_SPARENT
#define LOCALE_SPARENT 0x0000006d
#endif

// ---------------------------------------------------------------------------
// Impl for UtilLoadStringRC Callback: In VM, we let the thread decide culture
// copy culture name into szBuffer and return length
// ---------------------------------------------------------------------------
extern BOOL g_fFatalErrorOccuredOnGCThread;
static HRESULT GetThreadUICultureNames(__inout StringArrayList* pCultureNames)
{
    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
        MODE_ANY;
        PRECONDITION(CheckPointer(pCultureNames));
    } 
    CONTRACTL_END;

    HRESULT hr = S_OK;

    EX_TRY
    {
        InlineSString<LOCALE_NAME_MAX_LENGTH> sCulture;
        InlineSString<LOCALE_NAME_MAX_LENGTH> sParentCulture;

#if 0 // Enable and test if/once the unmanaged runtime is localized
        Thread * pThread = GetThread();

        // When fatal errors have occured our invariants around GC modes may be broken and attempting to transition to co-op may hang
        // indefinately. We want to ensure a clean exit so rather than take the risk of hang we take a risk of the error resource not
        // getting localized with a non-default thread-specific culture.
        // A canonical stack trace that gets here is a fatal error in the GC that comes through:
        // coreclr.dll!GetThreadUICultureNames
        // coreclr.dll!CCompRC::LoadLibraryHelper
        // coreclr.dll!CCompRC::LoadLibrary
        // coreclr.dll!CCompRC::GetLibrary
        // coreclr.dll!CCompRC::LoadString
        // coreclr.dll!CCompRC::LoadString
        // coreclr.dll!SString::LoadResourceAndReturnHR
        // coreclr.dll!SString::LoadResourceAndReturnHR
        // coreclr.dll!SString::LoadResource
        // coreclr.dll!EventReporter::EventReporter
        // coreclr.dll!EEPolicy::LogFatalError
        // coreclr.dll!EEPolicy::HandleFatalError
        if (pThread != NULL && !g_fFatalErrorOccuredOnGCThread) {

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

            CULTUREINFOBASEREF pCurrentCulture = (CULTUREINFOBASEREF)Thread::GetCulture(TRUE);

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

                if (cultureName != NULL)
                {
                    sCulture.Set(cultureName->GetBuffer(),cultureName->GetStringLength());
                }

                CULTUREINFOBASEREF pParentCulture = pCurrentCulture->GetParent();

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

                    if (parentCultureName != NULL)
                    {
                        sParentCulture.Set(parentCultureName->GetBuffer(),parentCultureName->GetStringLength());
                    }

                }
            }
        }
#endif

        // If the lazily-initialized cultureinfo structures aren't initialized yet, we'll
        // need to do the lookup the hard way.
        if (sCulture.IsEmpty() || sParentCulture.IsEmpty())
        {
            LocaleIDValue id ;
            int tmp; tmp = GetThreadUICultureId(&id);   // TODO: We should use the name instead
            _ASSERTE(tmp!=0 && id != UICULTUREID_DONTCARE);
            SIZE_T cchParentCultureName=LOCALE_NAME_MAX_LENGTH;
            sCulture.Set(id);

#ifndef FEATURE_PAL
            if (!::GetLocaleInfoEx((LPCWSTR)sCulture, LOCALE_SPARENT, sParentCulture.OpenUnicodeBuffer(static_cast<COUNT_T>(cchParentCultureName)),static_cast<int>(cchParentCultureName)))
            {
                hr = HRESULT_FROM_GetLastError();
            }
            sParentCulture.CloseBuffer();
#else // !FEATURE_PAL            
            sParentCulture = sCulture;
#endif // !FEATURE_PAL            
        }
        // (LPCWSTR) to restrict the size to null terminated size 
        pCultureNames->AppendIfNotThere((LPCWSTR)sCulture);
        // Disabling for Dev10 for consistency with managed resource lookup (see AppCompat bug notes in ResourceFallbackManager.cs)
        // Also, this is in the wrong order - put after the parent culture chain.
        //AddThreadPreferredUILanguages(pCultureNames);
        pCultureNames->AppendIfNotThere((LPCWSTR)sParentCulture);
        pCultureNames->Append(SString::Empty());
    }
    EX_CATCH
    {
        hr=E_OUTOFMEMORY;
    }
    EX_END_CATCH(SwallowAllExceptions);

    return 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().
static INT32 LatchedExitCode;
    
void SetLatchedExitCode (INT32 code)
{
    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
        MODE_ANY;
    }
    CONTRACTL_END;

    STRESS_LOG1(LF_SYNC, LL_INFO10, "SetLatchedExitCode = %d\n", code);
    LatchedExitCode = code;
}

INT32 GetLatchedExitCode (void)
{
    LIMITED_METHOD_CONTRACT;
    return LatchedExitCode;
}

// ---------------------------------------------------------------------------
// 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(__out LocaleIDValue* pLocale)
{
    CONTRACTL{
        NOTHROW;
        GC_NOTRIGGER;
        MODE_ANY;
    } CONTRACTL_END;

    _ASSERTE(sizeof(LocaleIDValue)/sizeof(WCHAR) >= LOCALE_NAME_MAX_LENGTH);

    int Result = 0;

    Thread * pThread = GetThread();

#if 0 // Enable and test if/once the unmanaged runtime is localized
    // When fatal errors have occured our invariants around GC modes may be broken and attempting to transition to co-op may hang
    // indefinately. We want to ensure a clean exit so rather than take the risk of hang we take a risk of the error resource not
    // getting localized with a non-default thread-specific culture.
    // A canonical stack trace that gets here is a fatal error in the GC that comes through:
    // coreclr.dll!GetThreadUICultureNames
    // coreclr.dll!CCompRC::LoadLibraryHelper
    // coreclr.dll!CCompRC::LoadLibrary
    // coreclr.dll!CCompRC::GetLibrary
    // coreclr.dll!CCompRC::LoadString
    // coreclr.dll!CCompRC::LoadString
    // coreclr.dll!SString::LoadResourceAndReturnHR
    // coreclr.dll!SString::LoadResourceAndReturnHR
    // coreclr.dll!SString::LoadResource
    // coreclr.dll!EventReporter::EventReporter
    // coreclr.dll!EEPolicy::LogFatalError
    // coreclr.dll!EEPolicy::HandleFatalError
    if (pThread != NULL && !g_fFatalErrorOccuredOnGCThread)
    {

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

        CULTUREINFOBASEREF pCurrentCulture = (CULTUREINFOBASEREF)Thread::GetCulture(TRUE);

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

            if (currentCultureName != NULL)
            {
                int cchCurrentCultureNameResult = currentCultureName->GetStringLength();
                if (cchCurrentCultureNameResult < LOCALE_NAME_MAX_LENGTH)
                {
                    memcpy(*pLocale, currentCultureName->GetBuffer(), cchCurrentCultureNameResult*sizeof(WCHAR));
                    (*pLocale)[cchCurrentCultureNameResult]='\0';
                    Result=cchCurrentCultureNameResult;
                }
            }
        }
    }
#endif
    if (Result == 0)
    {
#ifndef FEATURE_PAL
        // This thread isn't set up to use a non-default culture. Let's grab the default
        // one and return that.

        Result = ::GetUserDefaultLocaleName(*pLocale, LOCALE_NAME_MAX_LENGTH);

        _ASSERTE(Result != 0);
#else // !FEATURE_PAL
        static const WCHAR enUS[] = W("en-US");
        memcpy(*pLocale, enUS, sizeof(enUS));
        Result = sizeof(enUS);
#endif // !FEATURE_PAL
    }
    return Result;
}

#ifdef ENABLE_CONTRACTS_IMPL

// Returns TRUE if any contract violation suppressions are in effect.
BOOL AreAnyViolationBitsOn()
{
    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
        MODE_ANY;
    }
    CONTRACTL_END;
    UINT_PTR violationMask = GetClrDebugState()->ViolationMask();
    violationMask &= ~((UINT_PTR)CanFreeMe);  //CanFreeMe is a borrowed bit and has nothing to do with violations
    if (violationMask & ((UINT_PTR)BadDebugState))
    {
        return FALSE;
    }

    return violationMask != 0;
}


// This function is intentionally invoked inside a big CONTRACT_VIOLATION that turns on every violation
// bit on the map. The dynamic contract at the beginning *should* turn off those violation bits. 
// The body of this function tests to see that it did exactly that. This is to prevent the VSWhidbey B#564831 fiasco
// from ever recurring.
void ContractRegressionCheckInner()
{
    // DO NOT TURN THIS CONTRACT INTO A STATIC CONTRACT!!! The very purpose of this function
    // is to ensure that dynamic contracts disable outstanding contract violation bits.
    // This code only runs once at process startup so it's not going pooch the checked build perf.
    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
        FORBID_FAULT;
        LOADS_TYPE(CLASS_LOAD_BEGIN);
        CANNOT_TAKE_LOCK;
    }
    CONTRACTL_END

    if (AreAnyViolationBitsOn())
    {
        // If we got here, the contract above FAILED to turn off one or more violation bits. This is a 
        // huge diagnostics hole and must be fixed immediately.
        _ASSERTE(!("WARNING: mscorwks has detected an internal error that may indicate contracts are"
                   " being silently disabled across the runtime. Do not ignore this assert!"));
    }
}

// This function executes once per process to ensure our CONTRACT_VIOLATION() mechanism 
// is properly scope-limited by nested contracts.
void ContractRegressionCheck()
{
    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
        MODE_ANY;
    }
    CONTRACTL_END;
 
    {
        // DO NOT "FIX" THIS CONTRACT_VIOLATION!!!
        // The existence of this CONTRACT_VIOLATION is not a bug. This is debug-only code specifically written
        // to test the CONTRACT_VIOLATION mechanism itself. This is needed to prevent a regression of 
        // B#564831 (which left a huge swath of contracts silently disabled for over six months)
        PERMANENT_CONTRACT_VIOLATION(ThrowsViolation
                                   | GCViolation
                                   | FaultViolation
                                   | LoadsTypeViolation
                                   | TakesLockViolation
                                   , ReasonContractInfrastructure
                                    );
        {
            FAULT_NOT_FATAL();
            ContractRegressionCheckInner();
        }
    }

    if (AreAnyViolationBitsOn())
    {
        // If we got here, the CONTRACT_VIOLATION() holder left one or more violation bits turned ON
        // after we left its scope. This is a huge diagnostic hole and must be fixed immediately.
        _ASSERTE(!("WARNING: mscorwks has detected an internal error that may indicate contracts are"
                   " being silently disabled across the runtime. Do not ignore this assert!"));
    }

}

#endif // ENABLE_CONTRACTS_IMPL

#endif // CROSSGEN_COMPILE