summaryrefslogtreecommitdiff
path: root/src/vm/corhost.cpp
blob: 75adbada94e7c1ab848db2303dde515c32aa1dae (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
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
// 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.
//*****************************************************************************
// CorHost.cpp
//
// Implementation for the meta data dispenser code.
//

//*****************************************************************************

#include "common.h"

#include "mscoree.h"
#include "corhost.h"
#include "excep.h"
#include "threads.h"
#include "jitinterface.h"
#include "eeconfig.h"
#include "dbginterface.h"
#include "ceemain.h"
#include "hosting.h"
#include "eepolicy.h"
#include "clrex.h"
#ifdef FEATURE_IPCMAN
#include "ipcmanagerinterface.h"
#endif // FEATURE_IPCMAN
#include "comcallablewrapper.h"
#include "invokeutil.h"
#include "appdomain.inl"
#include "vars.hpp"
#include "comdelegate.h"
#include "dllimportcallback.h"
#include "eventtrace.h"

#include "win32threadpool.h"
#include "eventtrace.h"
#include "finalizerthread.h"
#include "threadsuspend.h"

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

#include "stringarraylist.h"

#ifdef FEATURE_COMINTEROP
#include "winrttypenameconverter.h"
#endif


GVAL_IMPL_INIT(DWORD, g_fHostConfig, 0);

#ifdef FEATURE_IMPLICIT_TLS
#ifndef __llvm__
EXTERN_C __declspec(thread) ThreadLocalInfo gCurrentThreadInfo;
#else // !__llvm__
EXTERN_C __thread ThreadLocalInfo gCurrentThreadInfo;
#endif // !__llvm__
#ifndef FEATURE_PAL
EXTERN_C UINT32 _tls_index;
#else // FEATURE_PAL
UINT32 _tls_index = 0;
#endif // FEATURE_PAL
SVAL_IMPL_INIT(DWORD, CExecutionEngine, TlsIndex, _tls_index);
#else
SVAL_IMPL_INIT(DWORD, CExecutionEngine, TlsIndex, TLS_OUT_OF_INDEXES);
#endif


#if defined(FEATURE_WINDOWSPHONE)
SVAL_IMPL_INIT(ECustomDumpFlavor, CCLRErrorReportingManager, g_ECustomDumpFlavor, DUMP_FLAVOR_Default);
#endif

#ifndef DACCESS_COMPILE

extern void STDMETHODCALLTYPE EEShutDown(BOOL fIsDllUnloading);
extern HRESULT STDMETHODCALLTYPE CoInitializeEE(DWORD fFlags);
extern void PrintToStdOutA(const char *pszString);
extern void PrintToStdOutW(const WCHAR *pwzString);
extern BOOL g_fEEHostedStartup;

INT64 g_PauseTime;         // Total time in millisecond the CLR has been paused
Volatile<BOOL> g_IsPaused;  // True if the runtime is paused (FAS)
CLREventStatic g_ClrResumeEvent; // Event that is fired at FAS Resuming 

extern BYTE g_rbTestKeyBuffer[];

//***************************************************************************

ULONG CorRuntimeHostBase::m_Version = 0;


#if defined(FEATURE_WINDOWSPHONE)
CCLRErrorReportingManager g_CLRErrorReportingManager;
#endif // defined(FEATURE_WINDOWSPHONE)

#ifdef FEATURE_IPCMAN
static CCLRSecurityAttributeManager s_CLRSecurityAttributeManager;
#endif // FEATURE_IPCMAN

#endif // !DAC

typedef DPTR(CONNID)   PTR_CONNID;



// Keep track connection id and name

#ifndef DACCESS_COMPILE




// *** ICorRuntimeHost methods ***

extern BOOL g_fWeOwnProcess;

CorHost2::CorHost2()
{
    LIMITED_METHOD_CONTRACT;

    m_fStarted = FALSE;
    m_fFirstToLoadCLR = FALSE;
    m_fAppDomainCreated = FALSE;
}

static DangerousNonHostedSpinLock lockOnlyOneToInvokeStart;

STDMETHODIMP CorHost2::Start()
{
    CONTRACTL
    {
        NOTHROW;
        GC_TRIGGERS;
        ENTRY_POINT;
    }CONTRACTL_END;

    HRESULT hr;

    BEGIN_ENTRYPOINT_NOTHROW;

    // Ensure that only one thread at a time gets in here
    DangerousNonHostedSpinLockHolder lockHolder(&lockOnlyOneToInvokeStart);
        
    // To provide the complete semantic of Start/Stop in context of a given host, we check m_fStarted and let
    // them invoke the Start only if they have not already. Likewise, they can invoke the Stop method
    // only if they have invoked Start prior to that.
    //
    // This prevents a host from invoking Stop twice and hitting the refCount to zero, when another
    // host is using the CLR, as CLR instance sharing across hosts is a scenario for CoreCLR.

    if (g_fEEStarted)
    {
        hr = S_OK;
        // CoreCLR is already running - but was Start already invoked by this host?
        if (m_fStarted)
        {
            // This host had already invoked the Start method - return them an error
            hr = HOST_E_INVALIDOPERATION;
        }
        else
        {
            // Increment the global (and dynamic) refCount...
            FastInterlockIncrement(&m_RefCount);

            // And set our flag that this host has invoked the Start...
            m_fStarted = TRUE;
        }
    }
    else
    {
        // Using managed C++ libraries, its possible that when the runtime is already running,
        // MC++ will use CorBindToRuntimeEx to make callbacks into specific appdomain of its
        // choice. Now, CorBindToRuntimeEx results in CorHost2::CreateObject being invoked
        // that will set runtime hosted flag "g_fHostConfig |= CLRHOSTED".
        //
        // For the case when managed code started without CLR hosting and MC++ does a 
        // CorBindToRuntimeEx, setting the CLR hosted flag is incorrect.
        //
        // Thus, before we attempt to start the runtime, we save the status of it being
        // already running or not. Next, if we are able to successfully start the runtime
        // and ONLY if it was not started earlier will we set the hosted flag below.
        if (!g_fEEStarted)
        {
            g_fHostConfig |= CLRHOSTED;
        }

        hr = CorRuntimeHostBase::Start();
        if (SUCCEEDED(hr))
        {
            // Set our flag that this host invoked the Start method.
            m_fStarted = TRUE;

            // And they also loaded the CoreCLR DLL in the memory (for this version).
            // This is a special flag as the host that has got this flag set will be allowed
            // to repeatedly invoke Stop method (without corresponding Start method invocations).
            // This is to support scenarios like that of Office where they need to bring down
            // the CLR at any cost.
            // 
            // So, if you want to do that, just make sure you are the first host to load the
            // specific version of CLR in memory AND start it.
            m_fFirstToLoadCLR = TRUE;
            if (FastInterlockIncrement(&m_RefCount) != 1)
            {
            }
            else
            {
                if (g_fWeOwnProcess)
                {
                    // Runtime is started by a managed exe.  Bump the ref-count, so that
                    // matching Start/Stop does not stop runtime.
                    FastInterlockIncrement(&m_RefCount);
                }
            }
        }
    }

    END_ENTRYPOINT_NOTHROW;
    return hr;
}

// Starts the runtime. This is equivalent to CoInitializeEE();
HRESULT CorRuntimeHostBase::Start()
{
    CONTRACTL
    {
        NOTHROW;
        DISABLED(GC_TRIGGERS);
        ENTRY_POINT;
    }
    CONTRACTL_END;

    HRESULT hr = S_OK;

    BEGIN_ENTRYPOINT_NOTHROW;
    {
        m_Started = TRUE;
#ifdef FEATURE_EVENT_TRACE
        g_fEEHostedStartup = TRUE;
#endif // FEATURE_EVENT_TRACE
        hr = InitializeEE(COINITEE_DEFAULT);
    }
    END_ENTRYPOINT_NOTHROW;

    return hr;
}


HRESULT CorHost2::Stop()
{
    CONTRACTL
    {
        NOTHROW;
        ENTRY_POINT;    // We're bringing the EE down, so no point in probing
        if (GetThread()) {GC_TRIGGERS;} else {DISABLED(GC_NOTRIGGER);}
    }
    CONTRACTL_END;
    if (!g_fEEStarted)
    {
        return E_UNEXPECTED;
    }
    HRESULT hr=S_OK;
    BEGIN_ENTRYPOINT_NOTHROW;

    // Is this host eligible to invoke the Stop method?
    if ((!m_fStarted) && (!m_fFirstToLoadCLR))
    {
        // Well - since this host never invoked Start, it is not eligible to invoke Stop.
        // Semantically, for such a host, CLR is not available in the process. The only
        // exception to this condition is the host that first loaded this version of the
        // CLR and invoked Start method. For details, refer to comments in CorHost2::Start implementation.
        hr = HOST_E_CLRNOTAVAILABLE;
    }
    else
    {
        while (TRUE)
        {
            LONG refCount = m_RefCount;
            if (refCount == 0)
            {
                hr = HOST_E_CLRNOTAVAILABLE;
                break;
            }
            else
            if (FastInterlockCompareExchange(&m_RefCount, refCount - 1, refCount) == refCount)
            {
                // Indicate that we have got a Stop for a corresponding Start call from the
                // Host. Semantically, CoreCLR has stopped for them.
                m_fStarted = FALSE;

                if (refCount > 1)
                {
                    hr=S_FALSE;
                    break;
                }
                else
                {
                    break;
                }
            }
        }
    }
    END_ENTRYPOINT_NOTHROW;


    return hr;
}


HRESULT CorHost2::GetCurrentAppDomainId(DWORD *pdwAppDomainId)
{
    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
        ENTRY_POINT;
    }
    CONTRACTL_END;

    // No point going further if the runtime is not running...
    // We use CanRunManagedCode() instead of IsRuntimeActive() because this allows us
    // to specify test using the form that does not trigger a GC.
    if (!(g_fEEStarted && CanRunManagedCode(LoaderLockCheck::None))
        || !m_fStarted
    )
    {
        return HOST_E_CLRNOTAVAILABLE;
    }   
    
    HRESULT hr = S_OK;

    BEGIN_ENTRYPOINT_NOTHROW;

    if(pdwAppDomainId == NULL)
    {
        hr = E_POINTER;
    }
    else
    {
        Thread *pThread = GetThread();
        if (!pThread)
        {
            hr = E_UNEXPECTED;
        }
        else
        {
            *pdwAppDomainId = SystemDomain::GetCurrentDomain()->GetId().m_dwId;
        }
    }

    END_ENTRYPOINT_NOTHROW;

    return hr;
}

HRESULT CorHost2::ExecuteApplication(LPCWSTR   pwzAppFullName,
                                     DWORD     dwManifestPaths,
                                     LPCWSTR   *ppwzManifestPaths,
                                     DWORD     dwActivationData,
                                     LPCWSTR   *ppwzActivationData,
                                     int       *pReturnValue)
{
    return E_NOTIMPL;
}

/*
 * This method processes the arguments sent to the host which are then used
 * to invoke the main method.
 * Note -
 * [0] - points to the assemblyName that has been sent by the host.
 * The rest are the arguments sent to the assembly.
 * Also note, this might not always return the exact same identity as the cmdLine
 * used to invoke the method.
 *
 * For example :-
 * ActualCmdLine - Foo arg1 arg2.
 * (Host1)       - Full_path_to_Foo arg1 arg2
*/
void SetCommandLineArgs(LPCWSTR pwzAssemblyPath, int argc, LPCWSTR* argv)
{
    CONTRACTL
    {
        THROWS;
        GC_TRIGGERS;
        MODE_COOPERATIVE;
    }
    CONTRACTL_END;

    struct _gc
    {
        PTRARRAYREF cmdLineArgs;
    } gc;

    ZeroMemory(&gc, sizeof(gc));
    GCPROTECT_BEGIN(gc);

    gc.cmdLineArgs = (PTRARRAYREF)AllocateObjectArray(argc + 1 /* arg[0] should be the exe name*/, g_pStringClass);
    OBJECTREF orAssemblyPath = StringObject::NewString(pwzAssemblyPath);
    gc.cmdLineArgs->SetAt(0, orAssemblyPath);

    for (int i = 0; i < argc; ++i)
    {
        OBJECTREF argument = StringObject::NewString(argv[i]);
        gc.cmdLineArgs->SetAt(i + 1, argument);
    }

    MethodDescCallSite setCmdLineArgs(METHOD__ENVIRONMENT__SET_COMMAND_LINE_ARGS);

    ARG_SLOT args[] =
    {
        ObjToArgSlot(gc.cmdLineArgs),
    };
    setCmdLineArgs.Call(args);

    GCPROTECT_END();
}

HRESULT CorHost2::ExecuteAssembly(DWORD dwAppDomainId,
                                      LPCWSTR pwzAssemblyPath,
                                      int argc,
                                      LPCWSTR* argv,
                                      DWORD *pReturnValue)
{
    CONTRACTL
    {
        THROWS; // Throws...as we do not want it to swallow the managed exception
        ENTRY_POINT;
    }
    CONTRACTL_END;

    // This is currently supported in default domain only
    if (dwAppDomainId != DefaultADID)
        return HOST_E_INVALIDOPERATION;

    // No point going further if the runtime is not running...
    if (!IsRuntimeActive() || !m_fStarted)
    {
        return HOST_E_CLRNOTAVAILABLE;
    }   
   
    if(!pwzAssemblyPath)
        return E_POINTER;

    if(argc < 0)
    {
        return E_INVALIDARG;
    }

    if(argc > 0 && argv == NULL)
    {
        return E_INVALIDARG;
    }

    HRESULT hr = S_OK;

    AppDomain *pCurDomain = SystemDomain::GetCurrentDomain();

    Thread *pThread = GetThread();
    if (pThread == NULL)
    {
        pThread = SetupThreadNoThrow(&hr);
        if (pThread == NULL)
        {
            goto ErrExit;
        }
    }

    if(pCurDomain->GetId().m_dwId != DefaultADID)
    {
        return HOST_E_INVALIDOPERATION;
    }

    INSTALL_UNHANDLED_MANAGED_EXCEPTION_TRAP;
    INSTALL_UNWIND_AND_CONTINUE_HANDLER;

    _ASSERTE (!pThread->PreemptiveGCDisabled());

    Assembly *pAssembly = AssemblySpec::LoadAssembly(pwzAssemblyPath);

#if defined(FEATURE_MULTICOREJIT)
    pCurDomain->GetMulticoreJitManager().AutoStartProfile(pCurDomain);
#endif // defined(FEATURE_MULTICOREJIT)

    {
        GCX_COOP();

        // Here we call the managed method that gets the cmdLineArgs array.
        SetCommandLineArgs(pwzAssemblyPath, argc, argv);

        PTRARRAYREF arguments = NULL;
        GCPROTECT_BEGIN(arguments);

        arguments = (PTRARRAYREF)AllocateObjectArray(argc, g_pStringClass);
        for (int i = 0; i < argc; ++i)
        {
            STRINGREF argument = StringObject::NewString(argv[i]);
            arguments->SetAt(i, argument);
        }

        DWORD retval = pAssembly->ExecuteMainMethod(&arguments, TRUE /* waitForOtherThreads */);
        if (pReturnValue)
        {
            *pReturnValue = retval;
        }

        GCPROTECT_END();

    }

    UNINSTALL_UNWIND_AND_CONTINUE_HANDLER;
    UNINSTALL_UNHANDLED_MANAGED_EXCEPTION_TRAP;

ErrExit:

    return hr;
}

HRESULT CorHost2::ExecuteInDefaultAppDomain(LPCWSTR pwzAssemblyPath,
                                            LPCWSTR pwzTypeName,
                                            LPCWSTR pwzMethodName,
                                            LPCWSTR pwzArgument,
                                            DWORD   *pReturnValue)
{
    CONTRACTL
    {
        NOTHROW;
        ENTRY_POINT;
    }
    CONTRACTL_END;

    // No point going further if the runtime is not running...
    if (!IsRuntimeActive()
        || !m_fStarted
    )
    {
        return HOST_E_CLRNOTAVAILABLE;
    }   
   
    
    // Ensure that code is not loaded in the Default AppDomain
    return HOST_E_INVALIDOPERATION;
}

HRESULT ExecuteInAppDomainHelper(FExecuteInAppDomainCallback pCallback,
                                 void * cookie)
{
    STATIC_CONTRACT_THROWS;
    STATIC_CONTRACT_SO_INTOLERANT;

    HRESULT hr = S_OK;

    BEGIN_SO_TOLERANT_CODE(GetThread());
    hr = pCallback(cookie);
    END_SO_TOLERANT_CODE;

    return hr;
}

HRESULT CorHost2::ExecuteInAppDomain(DWORD dwAppDomainId,
                                     FExecuteInAppDomainCallback pCallback,
                                     void * cookie)
{

    // No point going further if the runtime is not running...
    if (!IsRuntimeActive()
        || !m_fStarted
    )
    {
        return HOST_E_CLRNOTAVAILABLE;
    }       

    if(!(m_dwStartupFlags & STARTUP_SINGLE_APPDOMAIN))
    {
        // Ensure that code is not loaded in the Default AppDomain
        if (dwAppDomainId == DefaultADID)
           return HOST_E_INVALIDOPERATION;
    }

    // Moved this here since no point validating the pointer
    // if the basic checks [above] fail
    if( pCallback == NULL)
        return E_POINTER;

    CONTRACTL
    {
        NOTHROW;
        if (GetThread()) {GC_TRIGGERS;} else {DISABLED(GC_NOTRIGGER);}
        ENTRY_POINT;  // This is called by a host.
    }
    CONTRACTL_END;

    HRESULT hr = S_OK;

    BEGIN_ENTRYPOINT_NOTHROW;
    BEGIN_EXTERNAL_ENTRYPOINT(&hr);
    GCX_COOP_THREAD_EXISTS(GET_THREAD());
    ENTER_DOMAIN_ID(ADID(dwAppDomainId))
    {
        // We are calling an unmanaged function pointer, either an unmanaged function, or a marshaled out delegate.
        // The thread should be in preemptive mode, and SO_Tolerant.
        GCX_PREEMP();
        hr=ExecuteInAppDomainHelper (pCallback, cookie);
    }
    END_DOMAIN_TRANSITION;
    END_EXTERNAL_ENTRYPOINT;
    END_ENTRYPOINT_NOTHROW;

    return hr;
}

#define EMPTY_STRING_TO_NULL(s) {if(s && s[0] == 0) {s=NULL;};}

HRESULT CorHost2::_CreateAppDomain(
    LPCWSTR wszFriendlyName,
    DWORD  dwFlags,
    LPCWSTR wszAppDomainManagerAssemblyName, 
    LPCWSTR wszAppDomainManagerTypeName, 
    int nProperties, 
    LPCWSTR* pPropertyNames, 
    LPCWSTR* pPropertyValues,
    DWORD* pAppDomainID)
{
    CONTRACTL
    {
        NOTHROW;
        if (GetThread()) {GC_TRIGGERS;} else {DISABLED(GC_NOTRIGGER);}
        ENTRY_POINT;  // This is called by a host.
    }
    CONTRACTL_END;

    HRESULT hr=S_OK;

    //cannot call the function more than once when single appDomain is allowed
    if (m_fAppDomainCreated && (m_dwStartupFlags & STARTUP_SINGLE_APPDOMAIN))
    {
        return HOST_E_INVALIDOPERATION;
    }

    //normalize empty strings
    EMPTY_STRING_TO_NULL(wszFriendlyName);
    EMPTY_STRING_TO_NULL(wszAppDomainManagerAssemblyName);
    EMPTY_STRING_TO_NULL(wszAppDomainManagerTypeName);

    if(pAppDomainID==NULL)
        return E_POINTER;

    if (!m_fStarted)
        return HOST_E_INVALIDOPERATION;

    if(wszFriendlyName == NULL)
        return E_INVALIDARG;

    if((wszAppDomainManagerAssemblyName == NULL) != (wszAppDomainManagerTypeName == NULL))
        return E_INVALIDARG;

    BEGIN_ENTRYPOINT_NOTHROW;

    BEGIN_EXTERNAL_ENTRYPOINT(&hr);
    GCX_COOP_THREAD_EXISTS(GET_THREAD());

    AppDomainCreationHolder<AppDomain> pDomain;

    // If StartupFlag specifies single appDomain then return the default domain instead of creating new one
    if(m_dwStartupFlags & STARTUP_SINGLE_APPDOMAIN)
    {
        pDomain.Assign(SystemDomain::System()->DefaultDomain());
    }
    else
    {
        AppDomain::CreateUnmanagedObject(pDomain);
    }

    ETW::LoaderLog::DomainLoad(pDomain, (LPWSTR)wszFriendlyName);

    if (dwFlags & APPDOMAIN_IGNORE_UNHANDLED_EXCEPTIONS)
    {
        pDomain->SetIgnoreUnhandledExceptions();
    }

    if (dwFlags & APPDOMAIN_SECURITY_FORBID_CROSSAD_REVERSE_PINVOKE)
        pDomain->SetReversePInvokeCannotEnter();

    if (dwFlags & APPDOMAIN_FORCE_TRIVIAL_WAIT_OPERATIONS)
        pDomain->SetForceTrivialWaitOperations();

        
#ifdef PROFILING_SUPPORTED
    EX_TRY
#endif    
    {
        pDomain->SetAppDomainManagerInfo(wszAppDomainManagerAssemblyName,wszAppDomainManagerTypeName,eInitializeNewDomainFlags_None);

        GCX_COOP();
    
        struct 
        {
            STRINGREF friendlyName;
            PTRARRAYREF propertyNames;
            PTRARRAYREF propertyValues;
            STRINGREF sandboxName;
            OBJECTREF setupInfo;
            OBJECTREF adSetup;
        } _gc;

        ZeroMemory(&_gc,sizeof(_gc));

        GCPROTECT_BEGIN(_gc)
        _gc.friendlyName=StringObject::NewString(wszFriendlyName);
        
        if(nProperties>0)
        {
            _gc.propertyNames = (PTRARRAYREF) AllocateObjectArray(nProperties, g_pStringClass);
            _gc.propertyValues= (PTRARRAYREF) AllocateObjectArray(nProperties, g_pStringClass);
            for (int i=0;i< nProperties;i++)
            {
                STRINGREF obj = StringObject::NewString(pPropertyNames[i]);
                _gc.propertyNames->SetAt(i, obj);
                
                obj = StringObject::NewString(pPropertyValues[i]);
                _gc.propertyValues->SetAt(i, obj);
            }
        }

        if (dwFlags & APPDOMAIN_SECURITY_SANDBOXED)
        {
            _gc.sandboxName = StringObject::NewString(W("Internet"));
        }
        else
        {
            _gc.sandboxName = StringObject::NewString(W("FullTrust"));
        }

        MethodDescCallSite prepareDataForSetup(METHOD__APP_DOMAIN__PREPARE_DATA_FOR_SETUP);

        ARG_SLOT args[8];
        args[0]=ObjToArgSlot(_gc.friendlyName);
        args[1]=ObjToArgSlot(NULL);
        args[2]=ObjToArgSlot(NULL);
        args[3]=ObjToArgSlot(NULL);
        //CoreCLR shouldn't have dependencies on parent app domain.
        args[4]=ObjToArgSlot(NULL);
        args[5]=ObjToArgSlot(_gc.sandboxName);
        args[6]=ObjToArgSlot(_gc.propertyNames);
        args[7]=ObjToArgSlot(_gc.propertyValues);

        _gc.setupInfo=prepareDataForSetup.Call_RetOBJECTREF(args);

        //
        // Get the new flag values and set it to the domain
        //
        PTRARRAYREF handleArrayObj = (PTRARRAYREF) ObjectToOBJECTREF(_gc.setupInfo);
        _gc.adSetup = ObjectToOBJECTREF(handleArrayObj->GetAt(1));


        pDomain->DoSetup(&_gc.setupInfo);

        pDomain->CacheStringsForDAC();
        
        GCPROTECT_END();

        *pAppDomainID=pDomain->GetId().m_dwId;

        // If StartupFlag specifies single appDomain then set the flag that appdomain has already been created
        if(m_dwStartupFlags & STARTUP_SINGLE_APPDOMAIN)
        {
            m_fAppDomainCreated = TRUE;
        }
    }
#ifdef PROFILING_SUPPORTED
    EX_HOOK
    {
        // Need the first assembly loaded in to get any data on an app domain.
        {
            BEGIN_PIN_PROFILER(CORProfilerTrackAppDomainLoads());
            GCX_PREEMP();
            g_profControlBlock.pProfInterface->AppDomainCreationFinished((AppDomainID)(AppDomain*) pDomain, GET_EXCEPTION()->GetHR());
            END_PIN_PROFILER();
        }
    }
    EX_END_HOOK;

    // Need the first assembly loaded in to get any data on an app domain.
    {
        BEGIN_PIN_PROFILER(CORProfilerTrackAppDomainLoads());
        GCX_PREEMP();
        g_profControlBlock.pProfInterface->AppDomainCreationFinished((AppDomainID)(AppDomain*) pDomain, S_OK);
        END_PIN_PROFILER();
    }        
#endif // PROFILING_SUPPORTED

    // DoneCreating releases ownership of AppDomain.  After this call, there should be no access to pDomain.
    pDomain.DoneCreating();

    END_EXTERNAL_ENTRYPOINT;

    END_ENTRYPOINT_NOTHROW;

    return hr;

};

HRESULT CorHost2::_CreateDelegate(
    DWORD appDomainID,
    LPCWSTR wszAssemblyName,     
    LPCWSTR wszClassName,     
    LPCWSTR wszMethodName,
    INT_PTR* fnPtr)
{

    CONTRACTL
    {
        NOTHROW;
        if (GetThread()) {GC_TRIGGERS;} else {DISABLED(GC_NOTRIGGER);}
        ENTRY_POINT;  // This is called by a host.
    }
    CONTRACTL_END;

    HRESULT hr=S_OK;

    EMPTY_STRING_TO_NULL(wszAssemblyName);
    EMPTY_STRING_TO_NULL(wszClassName);
    EMPTY_STRING_TO_NULL(wszMethodName);

    if (fnPtr == NULL)
       return E_POINTER;
    *fnPtr = NULL;

    if(wszAssemblyName == NULL)
        return E_INVALIDARG;
    
    if(wszClassName == NULL)
        return E_INVALIDARG;

    if(wszMethodName == NULL)
        return E_INVALIDARG;
    
    if (!m_fStarted)
        return HOST_E_INVALIDOPERATION;

    if(!(m_dwStartupFlags & STARTUP_SINGLE_APPDOMAIN))
    {
        // Ensure that code is not loaded in the Default AppDomain
        if (appDomainID == DefaultADID)
            return HOST_E_INVALIDOPERATION;
    }

    BEGIN_ENTRYPOINT_NOTHROW;

    BEGIN_EXTERNAL_ENTRYPOINT(&hr);
    GCX_COOP_THREAD_EXISTS(GET_THREAD());

    MAKE_UTF8PTR_FROMWIDE(szAssemblyName, wszAssemblyName);
    MAKE_UTF8PTR_FROMWIDE(szClassName, wszClassName);
    MAKE_UTF8PTR_FROMWIDE(szMethodName, wszMethodName);

    ADID id;
    id.m_dwId=appDomainID;

    ENTER_DOMAIN_ID(id)

    GCX_PREEMP();

    AssemblySpec spec;
    spec.Init(szAssemblyName);
    Assembly* pAsm=spec.LoadAssembly(FILE_ACTIVE);

    // we have no signature to check so allowing calling partially trusted code
    // can result in an exploit
    if (!pAsm->GetSecurityDescriptor()->IsFullyTrusted())    
          ThrowHR(COR_E_SECURITY);

    TypeHandle th=pAsm->GetLoader()->LoadTypeByNameThrowing(pAsm,NULL,szClassName);
    MethodDesc* pMD=NULL;
    
    if (!th.IsTypeDesc()) 
    {
        pMD = MemberLoader::FindMethodByName(th.GetMethodTable(), szMethodName, MemberLoader::FM_Unique);
        if (pMD == NULL)
        {
            // try again without the FM_Unique flag (error path)
            pMD = MemberLoader::FindMethodByName(th.GetMethodTable(), szMethodName, MemberLoader::FM_Default);
            if (pMD != NULL)
            {
                // the method exists but is overloaded
                ThrowHR(COR_E_AMBIGUOUSMATCH);
            }
        }
    }

    if (pMD==NULL || !pMD->IsStatic() || pMD->ContainsGenericVariables()) 
        ThrowHR(COR_E_MISSINGMETHOD);

    // the target method must be decorated with AllowReversePInvokeCallsAttribute
    if (!COMDelegate::IsMethodAllowedToSinkReversePInvoke(pMD))
        ThrowHR(COR_E_SECURITY);

    UMEntryThunk *pUMEntryThunk = GetAppDomain()->GetUMEntryThunkCache()->GetUMEntryThunk(pMD);
    *fnPtr = (INT_PTR)pUMEntryThunk->GetCode();

    END_DOMAIN_TRANSITION;

    END_EXTERNAL_ENTRYPOINT;

    END_ENTRYPOINT_NOTHROW;

    return hr;
}

HRESULT CorHost2::CreateAppDomainWithManager(
    LPCWSTR wszFriendlyName,
    DWORD  dwFlags,
    LPCWSTR wszAppDomainManagerAssemblyName, 
    LPCWSTR wszAppDomainManagerTypeName, 
    int nProperties, 
    LPCWSTR* pPropertyNames, 
    LPCWSTR* pPropertyValues, 
    DWORD* pAppDomainID)
{
    WRAPPER_NO_CONTRACT;

    return _CreateAppDomain(
        wszFriendlyName,
        dwFlags,
        wszAppDomainManagerAssemblyName, 
        wszAppDomainManagerTypeName, 
        nProperties, 
        pPropertyNames, 
        pPropertyValues,
        pAppDomainID);
}

HRESULT CorHost2::CreateDelegate(
    DWORD appDomainID,
    LPCWSTR wszAssemblyName,     
    LPCWSTR wszClassName,     
    LPCWSTR wszMethodName,
    INT_PTR* fnPtr)
{
    WRAPPER_NO_CONTRACT;

    return _CreateDelegate(appDomainID, wszAssemblyName, wszClassName, wszMethodName, fnPtr);
}

HRESULT CorHost2::Authenticate(ULONGLONG authKey)
{
    CONTRACTL
    {
        NOTHROW;
        if (GetThread()) {GC_TRIGGERS;} else {DISABLED(GC_NOTRIGGER);}
        ENTRY_POINT;  // This is called by a host.
    }
    CONTRACTL_END;

    // Host authentication was used by Silverlight. It is no longer relevant for CoreCLR.
    return S_OK;
}

HRESULT CorHost2::RegisterMacEHPort()
{
    CONTRACTL
    {
        NOTHROW;
        if (GetThread()) {GC_TRIGGERS;} else {DISABLED(GC_NOTRIGGER);}
        ENTRY_POINT;  // This is called by a host.
    }
    CONTRACTL_END;

    return S_OK;
}

HRESULT CorHost2::SetStartupFlags(STARTUP_FLAGS flag)
{
    CONTRACTL
    {
        NOTHROW;
        if (GetThread()) {GC_TRIGGERS;} else {DISABLED(GC_NOTRIGGER);}
        ENTRY_POINT;  // This is called by a host.
    }
    CONTRACTL_END;

    if (g_fEEStarted)
    {
        return HOST_E_INVALIDOPERATION;
    }

    m_dwStartupFlags = flag;

    return S_OK;
}



HRESULT SuspendEEForPause()
{
    CONTRACTL
    {
        NOTHROW;
        MODE_PREEMPTIVE;
        GC_TRIGGERS;
    }
    CONTRACTL_END;

    HRESULT hr = S_OK;

    // In CoreCLR, we always resume from the same thread that paused.  So we can simply suspend the EE from this thread,
    // knowing we'll restart from the same thread.
    ThreadSuspend::SuspendEE(ThreadSuspend::SUSPEND_OTHER);

    return hr;
}

HRESULT RestartEEFromPauseAndSetResumeEvent()
{
    CONTRACTL
    {
        NOTHROW;
        MODE_PREEMPTIVE;
        GC_TRIGGERS;
    }
    CONTRACTL_END;

    // see comments in SuspendEEFromPause
    ThreadSuspend::RestartEE(FALSE, TRUE);

    _ASSERTE(g_ClrResumeEvent.IsValid());
    g_ClrResumeEvent.Set();

    return S_OK;
}
    


CorExecutionManager::CorExecutionManager()
    : m_dwFlags(0), m_pauseStartTime(0)
{
    LIMITED_METHOD_CONTRACT;
    g_IsPaused = FALSE;
    g_PauseTime = 0;
}

HRESULT CorExecutionManager::Pause(DWORD dwAppDomainId, DWORD dwFlags)
{
    CONTRACTL
    {
        NOTHROW;
        if (GetThread()) {GC_TRIGGERS;} else {DISABLED(GC_NOTRIGGER);}
        ENTRY_POINT;  // This is called by a host.
    }
    CONTRACTL_END;

    HRESULT hr = S_OK;


    if(g_IsPaused)
        return E_FAIL;

    EX_TRY
    {
        if(!g_ClrResumeEvent.IsValid())
            g_ClrResumeEvent.CreateManualEvent(FALSE);
        else
            g_ClrResumeEvent.Reset();

    }
    EX_CATCH_HRESULT(hr);
    
    if (FAILED(hr))
        return hr;
    
    BEGIN_ENTRYPOINT_NOTHROW;

    m_dwFlags = dwFlags;


    if (SUCCEEDED(hr))
    {
        g_IsPaused = TRUE;

        hr = SuspendEEForPause();

        // Even though this is named with TickCount, it returns milliseconds
        m_pauseStartTime = (INT64)CLRGetTickCount64(); 
    }

    END_ENTRYPOINT_NOTHROW;

    return hr;
}


HRESULT CorExecutionManager::Resume(DWORD dwAppDomainId)
{
    CONTRACTL
    {
        NOTHROW;
        if (GetThread()) {GC_TRIGGERS;} else {DISABLED(GC_NOTRIGGER);}
        ENTRY_POINT;  // This is called by a host.
    }
    CONTRACTL_END;

    HRESULT hr = S_OK;


    if(!g_IsPaused)
        return E_FAIL;

    // GCThread is the thread that did the Pause. Resume should also happen on that same thread
    Thread *pThread = GetThread();
    if(pThread != ThreadSuspend::GetSuspensionThread())
    {
        _ASSERTE(!"HOST BUG: The same thread that did Pause should do the Resume");
        return E_FAIL;
    }

    BEGIN_ENTRYPOINT_NOTHROW;

    // Even though this is named with TickCount, it returns milliseconds
    INT64 currTime = (INT64)CLRGetTickCount64(); 
    _ASSERTE(currTime >= m_pauseStartTime);
    _ASSERTE(m_pauseStartTime != 0);

    g_PauseTime += (currTime - m_pauseStartTime);
    g_IsPaused = FALSE;

    hr = RestartEEFromPauseAndSetResumeEvent();


    END_ENTRYPOINT_NOTHROW;

    return hr;
}


#endif //!DACCESS_COMPILE

#ifndef DACCESS_COMPILE
SVAL_IMPL(STARTUP_FLAGS, CorHost2, m_dwStartupFlags = STARTUP_CONCURRENT_GC);
#else
SVAL_IMPL(STARTUP_FLAGS, CorHost2, m_dwStartupFlags);
#endif

STARTUP_FLAGS CorHost2::GetStartupFlags()
{
    return m_dwStartupFlags;
}

#ifndef DACCESS_COMPILE


#ifdef FEATURE_COMINTEROP

// Enumerate currently existing domains.
HRESULT CorRuntimeHostBase::EnumDomains(HDOMAINENUM *hEnum)
{
    CONTRACTL
    {
        NOTHROW;
        MODE_PREEMPTIVE;
        WRAPPER(GC_TRIGGERS);
        ENTRY_POINT;
    }
    CONTRACTL_END;

    if(hEnum == NULL) return E_POINTER;

    // Thread setup happens in BEGIN_EXTERNAL_ENTRYPOINT below.
    // If the runtime has not started, we have nothing to do.
    if (!g_fEEStarted)
    {
        return HOST_E_CLRNOTAVAILABLE;
    }

    HRESULT hr = E_OUTOFMEMORY;
    *hEnum = NULL;
    BEGIN_ENTRYPOINT_NOTHROW;

    BEGIN_EXTERNAL_ENTRYPOINT(&hr)

    AppDomainIterator *pEnum = new (nothrow) AppDomainIterator(FALSE);
    if(pEnum) {
        *hEnum = (HDOMAINENUM) pEnum;
        hr = S_OK;
    }
    END_EXTERNAL_ENTRYPOINT;
    END_ENTRYPOINT_NOTHROW;

    return hr;
}

#endif // FEATURE_COMINTEROP

extern "C"
HRESULT  GetCLRRuntimeHost(REFIID riid, IUnknown **ppUnk)
{
    WRAPPER_NO_CONTRACT;

    return CorHost2::CreateObject(riid, (void**)ppUnk);
}


STDMETHODIMP CorHost2::UnloadAppDomain(DWORD dwDomainId, BOOL fWaitUntilDone)
{
    WRAPPER_NO_CONTRACT;
    STATIC_CONTRACT_SO_TOLERANT;

    if (!m_fStarted)
        return HOST_E_INVALIDOPERATION;

    if(m_dwStartupFlags & STARTUP_SINGLE_APPDOMAIN)
    {
        if (!g_fEEStarted)
        {
            return HOST_E_CLRNOTAVAILABLE;
        }

        if(!m_fAppDomainCreated)
        {
            return HOST_E_INVALIDOPERATION;
        }

        HRESULT hr=S_OK;
        BEGIN_ENTRYPOINT_NOTHROW;
    
        if (!m_fFirstToLoadCLR)
        {
            _ASSERTE(!"Not reachable");
            hr = HOST_E_CLRNOTAVAILABLE;
        }
        else
        {
            LONG refCount = m_RefCount;
            if (refCount == 0)
            {
                hr = HOST_E_CLRNOTAVAILABLE;
            }
            else
            if (1 == refCount)
            {
                // Stop coreclr on unload.
                m_fStarted = FALSE;
                EEShutDown(FALSE);
            }
            else
            {
                _ASSERTE(!"Not reachable");
                hr = S_FALSE;
            }
        }
        END_ENTRYPOINT_NOTHROW;

        return hr;
    }
    else

    return CorRuntimeHostBase::UnloadAppDomain(dwDomainId, fWaitUntilDone);
}

HRESULT CorRuntimeHostBase::UnloadAppDomain(DWORD dwDomainId, BOOL fSync)
{
    CONTRACTL
    {
        NOTHROW;
        GC_TRIGGERS;
        MODE_ANY;
        FORBID_FAULT; // Unloading domains cannot fail due to OOM
        ENTRY_POINT;
    }
    CONTRACTL_END;

    HRESULT hr = S_OK;

    // No point going further if the runtime is not running...
    {
        // In IsRuntimeActive, we will call CanRunManagedCode that will
        // check if the current thread has taken the loader lock or not,
        // if MDA is supported. To do the check, MdaLoaderLock::ReportViolation
        // will be invoked that will internally end up invoking
        // MdaFactory<MdaXmlElement>::GetNext that will use the "new" operator
        // that has the "FAULT" contract set, resulting in FAULT_VIOLATION since
        // this method has the FORBID_FAULT contract set above.
        //
        // However, for a thread that holds the loader lock, unloading the appDomain is
        // not a supported scenario. Thus, we should not be ending up in this code
        // path for the FAULT violation. 
        //
        // Hence, the CONTRACT_VIOLATION below for overriding the FORBID_FAULT
        // for this scope only.
        CONTRACT_VIOLATION(FaultViolation);
        if (!IsRuntimeActive()
            || !m_fStarted
        )
        {
            return HOST_E_CLRNOTAVAILABLE;
        }   
    }
    
    BEGIN_ENTRYPOINT_NOTHROW;

    // We do not use BEGIN_EXTERNAL_ENTRYPOINT here because
    // we do not want to setup Thread.  Process may be OOM, and we want Unload
    // to work.
    hr =  AppDomain::UnloadById(ADID(dwDomainId), fSync);

    END_ENTRYPOINT_NOTHROW;

    return hr;
}

//*****************************************************************************
// Fiber Methods
//*****************************************************************************

HRESULT CorRuntimeHostBase::LocksHeldByLogicalThread(DWORD *pCount)
{
    if (!pCount)
        return E_POINTER;

    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
        ENTRY_POINT;
    }
    CONTRACTL_END;

    BEGIN_ENTRYPOINT_NOTHROW;

    Thread* pThread = GetThread();
    if (pThread == NULL)
        *pCount = 0;
    else
        *pCount = pThread->m_dwLockCount;

    END_ENTRYPOINT_NOTHROW;

    return S_OK;
}

//*****************************************************************************
// ICorConfiguration
//*****************************************************************************

//*****************************************************************************
// IUnknown
//*****************************************************************************

ULONG CorRuntimeHostBase::AddRef()
{
    CONTRACTL
    {
        WRAPPER(THROWS);
        WRAPPER(GC_TRIGGERS);
        SO_TOLERANT;
    }
    CONTRACTL_END;
    return InterlockedIncrement(&m_cRef);
}


ULONG CorHost2::Release()
{
    LIMITED_METHOD_CONTRACT;

    ULONG cRef = InterlockedDecrement(&m_cRef);
    if (!cRef) {
            delete this;
    }

    return (cRef);
}



HRESULT CorHost2::QueryInterface(REFIID riid, void **ppUnk)
{
    if (!ppUnk)
        return E_POINTER;

    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
        SO_TOLERANT;    // no global state updates that need guarding.
    }
    CONTRACTL_END;

    if (ppUnk == NULL)
    {
        return E_POINTER;
    }

    *ppUnk = 0;

    // Deliberately do NOT hand out ICorConfiguration.  They must explicitly call
    // GetConfiguration to obtain that interface.
    if (riid == IID_IUnknown)
        *ppUnk = static_cast<IUnknown *>(static_cast<ICLRRuntimeHost *>(this));
    else if (riid == IID_ICLRRuntimeHost2)
    {
        ULONG version = 2;
        if (m_Version == 0)
            FastInterlockCompareExchange((LONG*)&m_Version, version, 0);

        *ppUnk = static_cast<ICLRRuntimeHost2 *>(this);
    }
    else if (riid == IID_ICLRExecutionManager)
    {
        ULONG version = 2;
        if (m_Version == 0)
            FastInterlockCompareExchange((LONG*)&m_Version, version, 0);

        *ppUnk = static_cast<ICLRExecutionManager *>(this);
    }
#ifndef FEATURE_PAL
    else if (riid == IID_IPrivateManagedExceptionReporting)
    {
        *ppUnk = static_cast<IPrivateManagedExceptionReporting *>(this);
    }
#endif // !FEATURE_PAL
    else
        return (E_NOINTERFACE);
    AddRef();
    return (S_OK);
}


#ifndef FEATURE_PAL
HRESULT CorHost2::GetBucketParametersForCurrentException(BucketParameters *pParams)
{
    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
        SO_TOLERANT;
    }
    CONTRACTL_END;

    HRESULT hr = S_OK;
    BEGIN_ENTRYPOINT_NOTHROW;

    // To avoid confusion, clear the buckets.
    memset(pParams, 0, sizeof(BucketParameters));

    // Defer to Watson helper.
    hr = ::GetBucketParametersForCurrentException(pParams);

    END_ENTRYPOINT_NOTHROW;

    return hr;
}
#endif // !FEATURE_PAL

HRESULT CorHost2::CreateObject(REFIID riid, void **ppUnk)
{
    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
        SO_TOLERANT;
    }
    CONTRACTL_END;

    HRESULT hr = S_OK;

    BEGIN_SO_INTOLERANT_CODE_NO_THROW_CHECK_THREAD(return COR_E_STACKOVERFLOW; );
    CorHost2 *pCorHost = new (nothrow) CorHost2();
    if (!pCorHost)
    {
        hr = E_OUTOFMEMORY;
    }
    else
    {
        hr = pCorHost->QueryInterface(riid, ppUnk);
    if (FAILED(hr))
        delete pCorHost;
    }
    END_SO_INTOLERANT_CODE;
    return (hr);
}


//-----------------------------------------------------------------------------
// MapFile - Maps a file into the runtime in a non-standard way
//-----------------------------------------------------------------------------

static PEImage *MapFileHelper(HANDLE hFile)
{
    CONTRACTL
    {
        THROWS;
        GC_TRIGGERS;
        MODE_ANY;
    }
    CONTRACTL_END;

    GCX_PREEMP();

    HandleHolder hFileMap(WszCreateFileMapping(hFile, NULL, PAGE_READONLY, 0, 0, NULL));
    if (hFileMap == NULL)
        ThrowLastError();

    CLRMapViewHolder base(CLRMapViewOfFile(hFileMap, FILE_MAP_READ, 0, 0, 0));
    if (base == NULL)
        ThrowLastError();

    DWORD dwSize = SafeGetFileSize(hFile, NULL);
    if (dwSize == 0xffffffff && GetLastError() != NOERROR)
    {
        ThrowLastError();
    }
    PEImageHolder pImage(PEImage::LoadFlat(base, dwSize));
    return pImage.Extract();
}

HRESULT CorRuntimeHostBase::MapFile(HANDLE hFile, HMODULE* phHandle)
{
    CONTRACTL
    {
        NOTHROW;
        GC_TRIGGERS;
        MODE_PREEMPTIVE;
        ENTRY_POINT;
    }
    CONTRACTL_END;

    HRESULT hr;
    BEGIN_ENTRYPOINT_NOTHROW;

    BEGIN_EXTERNAL_ENTRYPOINT(&hr)
    {
        *phHandle = (HMODULE) (MapFileHelper(hFile)->GetLoadedLayout()->GetBase());
    }
    END_EXTERNAL_ENTRYPOINT;
    END_ENTRYPOINT_NOTHROW;


    return hr;
}

///////////////////////////////////////////////////////////////////////////////
// IDebuggerInfo::IsDebuggerAttached

LONG CorHost2::m_RefCount = 0;

IHostControl *CorHost2::m_HostControl = NULL;

LPCWSTR CorHost2::s_wszAppDomainManagerAsm = NULL;
LPCWSTR CorHost2::s_wszAppDomainManagerType = NULL;
EInitializeNewDomainFlags CorHost2::s_dwDomainManagerInitFlags = eInitializeNewDomainFlags_None;


#ifdef _DEBUG
extern void ValidateHostInterface();
#endif

// fusion's global copy of host assembly manager stuff
BOOL g_bFusionHosted = FALSE;

/*static*/ BOOL CorHost2::IsLoadFromBlocked() // LoadFrom, LoadFile and Load(byte[]) are blocked in certain hosting scenarios
{
    LIMITED_METHOD_CONTRACT;
    return FALSE; // as g_pHostAsmList is not defined for CoreCLR; hence above expression will be FALSE.
}

static Volatile<BOOL> fOneOnly = 0;

///////////////////////////////////////////////////////////////////////////////
// ICLRRuntimeHost::SetHostControl
///////////////////////////////////////////////////////////////////////////////
HRESULT CorHost2::SetHostControl(IHostControl* pHostControl)
{
    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
        ENTRY_POINT;
    }
    CONTRACTL_END;
    if (m_Version < 2)
        // CLR is hosted with v1 hosting interface.  Some part of v2 hosting API are disabled.
        return HOST_E_INVALIDOPERATION;

    if (pHostControl == 0)
        return E_INVALIDARG;

    // If Runtime has been started, do not allow setting HostMemoryManager
    if (g_fEEStarted)
        return E_ACCESSDENIED;

    HRESULT hr = S_OK;

    BEGIN_ENTRYPOINT_NOTHROW;
    
    DWORD dwSwitchCount = 0;

    while (FastInterlockExchange((LONG*)&fOneOnly, 1) == 1)
    {
             __SwitchToThread(0, ++dwSwitchCount);
    }
    

    if (m_HostControl == NULL)
    {
        m_HostControl = pHostControl;
        m_HostControl->AddRef();
    }

    goto ErrExit;

ErrExit:
    fOneOnly = 0;

    END_ENTRYPOINT_NOTHROW;

    return hr;
}

class CCLRPolicyManager: public ICLRPolicyManager
{
public:
    virtual HRESULT STDMETHODCALLTYPE SetDefaultAction(EClrOperation operation,
                                                       EPolicyAction action)
    {
        LIMITED_METHOD_CONTRACT;
        return E_NOTIMPL;
    }

    virtual HRESULT STDMETHODCALLTYPE SetTimeout(EClrOperation operation,
                                                 DWORD dwMilliseconds)
    {
        LIMITED_METHOD_CONTRACT;
        return E_NOTIMPL;
    }

    virtual HRESULT STDMETHODCALLTYPE SetActionOnTimeout(EClrOperation operation,
                                                         EPolicyAction action)
    {
        LIMITED_METHOD_CONTRACT;
        return E_NOTIMPL;
    }

    virtual HRESULT STDMETHODCALLTYPE SetTimeoutAndAction(EClrOperation operation, DWORD dwMilliseconds,
                                                          EPolicyAction action)
    {
        LIMITED_METHOD_CONTRACT;
        return E_NOTIMPL;
    }

    virtual HRESULT STDMETHODCALLTYPE SetActionOnFailure(EClrFailure failure,
                                                         EPolicyAction action)
    {
        // This is enabled for CoreCLR since a host can use this to 
        // specify action for handling AV.
        STATIC_CONTRACT_ENTRY_POINT;
        LIMITED_METHOD_CONTRACT;
        HRESULT hr;
        // For CoreCLR, this method just supports FAIL_AccessViolation as a valid
        // failure input arg. The validation of the specified action for the failure
        // will be done in EEPolicy::IsValidActionForFailure.
        if (failure != FAIL_AccessViolation)
        {
            return E_INVALIDARG;
        }
        BEGIN_ENTRYPOINT_NOTHROW;
        hr = GetEEPolicy()->SetActionOnFailure(failure,action);
        END_ENTRYPOINT_NOTHROW;
        return hr;
    }

    virtual HRESULT STDMETHODCALLTYPE SetUnhandledExceptionPolicy(EClrUnhandledException policy)
    {
        LIMITED_METHOD_CONTRACT;
        return E_NOTIMPL;
    }

    virtual ULONG STDMETHODCALLTYPE AddRef(void)
    {
        LIMITED_METHOD_CONTRACT;
        STATIC_CONTRACT_SO_TOLERANT;
        return 1;
    }

    virtual ULONG STDMETHODCALLTYPE Release(void)
    {
        LIMITED_METHOD_CONTRACT;
        STATIC_CONTRACT_SO_TOLERANT;
        return 1;
    }

    BEGIN_INTERFACE HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid,
                                                             void **ppvObject)
    {
        LIMITED_METHOD_CONTRACT;
        STATIC_CONTRACT_SO_TOLERANT;
        if (riid != IID_ICLRPolicyManager && riid != IID_IUnknown)
            return (E_NOINTERFACE);

        // Ensure that the out going pointer is not null
        if (ppvObject == NULL)
            return E_POINTER;

        *ppvObject = this;
        return S_OK;
    }
};

static CCLRPolicyManager s_PolicyManager;



void ProcessEventForHost(EClrEvent event, void *data)
{
}

// We do not call ProcessEventForHost for stack overflow, since we have limit stack
// and we should avoid calling GCX_PREEMPT
void ProcessSOEventForHost(EXCEPTION_POINTERS *pExceptionInfo, BOOL fInSoTolerant)
{
}

BOOL IsHostRegisteredForEvent(EClrEvent event)
{
    WRAPPER_NO_CONTRACT;
    return FALSE;
}

inline size_t SizeInKBytes(size_t cbSize)
{
    LIMITED_METHOD_CONTRACT;
    size_t cb = (cbSize % 1024) ? 1 : 0;
    return ((cbSize / 1024) + cb);
}

SIZE_T Host_SegmentSize = 0;
SIZE_T Host_MaxGen0Size = 0;
BOOL  Host_fSegmentSizeSet = FALSE;
BOOL  Host_fMaxGen0SizeSet = FALSE;

void UpdateGCSettingFromHost ()
{
    WRAPPER_NO_CONTRACT;
    _ASSERTE (g_pConfig);
    if (Host_fSegmentSizeSet)
    {
        g_pConfig->SetSegmentSize(Host_SegmentSize);
    }
    if (Host_fMaxGen0SizeSet)
    {
        g_pConfig->SetGCgen0size(Host_MaxGen0Size);
    }
}

#if defined(FEATURE_WINDOWSPHONE)
class CCLRGCManager: public ICLRGCManager2
{
public:
    virtual HRESULT STDMETHODCALLTYPE Collect(LONG Generation)
    {
        CONTRACTL
        {
            NOTHROW;
            GC_TRIGGERS;
            ENTRY_POINT;
        }
        CONTRACTL_END;

        HRESULT     hr = S_OK;

        if (Generation > (int) GCHeapUtilities::GetGCHeap()->GetMaxGeneration())
            hr = E_INVALIDARG;

        if (SUCCEEDED(hr))
        {
            // Set up a Thread object if this is called on a native thread.
            Thread *pThread;
            pThread = GetThread();
            if (pThread == NULL)
                pThread = SetupThreadNoThrow(&hr);
            if (pThread != NULL)
            {
                BEGIN_ENTRYPOINT_NOTHROW_WITH_THREAD(pThread);
                GCX_COOP();

                EX_TRY
                {
                    STRESS_LOG0(LF_GC, LL_INFO100, "Host triggers GC\n");
                    hr = GCHeapUtilities::GetGCHeap()->GarbageCollect(Generation);
                }
                EX_CATCH
                {
                    hr = GET_EXCEPTION()->GetHR();
                }
                EX_END_CATCH(SwallowAllExceptions);

                END_ENTRYPOINT_NOTHROW_WITH_THREAD;
            }
        }

        return (hr);
    }

    virtual HRESULT STDMETHODCALLTYPE GetStats(COR_GC_STATS *pStats)
    {
        CONTRACTL
        {
            NOTHROW;
            GC_NOTRIGGER;
            ENTRY_POINT;
        }
        CONTRACTL_END;

        HRESULT hr = S_OK;
        BEGIN_ENTRYPOINT_NOTHROW;

    #if defined(ENABLE_PERF_COUNTERS)

        Perf_GC     *pgc = &GetPerfCounters().m_GC;

        if (!pStats)
            IfFailGo(E_INVALIDARG);

        if (pStats->Flags & COR_GC_COUNTS)
        {
            pStats->ExplicitGCCount = pgc->cInducedGCs;

            for (int idx=0; idx<3; idx++)
                pStats->GenCollectionsTaken[idx] = pgc->cGenCollections[idx];
        }

        if (pStats->Flags & COR_GC_MEMORYUSAGE)
        {
            pStats->CommittedKBytes = SizeInKBytes(pgc->cTotalCommittedBytes);
            pStats->ReservedKBytes = SizeInKBytes(pgc->cTotalReservedBytes);
            pStats->Gen0HeapSizeKBytes = SizeInKBytes(pgc->cGenHeapSize[0]);
            pStats->Gen1HeapSizeKBytes = SizeInKBytes(pgc->cGenHeapSize[1]);
            pStats->Gen2HeapSizeKBytes = SizeInKBytes(pgc->cGenHeapSize[2]);
            pStats->LargeObjectHeapSizeKBytes = SizeInKBytes(pgc->cLrgObjSize);
            pStats->KBytesPromotedFromGen0 = SizeInKBytes(pgc->cbPromotedMem[0]);
            pStats->KBytesPromotedFromGen1 = SizeInKBytes(pgc->cbPromotedMem[1]);
        }
        hr = S_OK;
ErrExit:
    #else
        hr = E_NOTIMPL;
    #endif // ENABLE_PERF_COUNTERS

        END_ENTRYPOINT_NOTHROW;
        return hr;
    }
    virtual HRESULT STDMETHODCALLTYPE SetGCStartupLimits(
        DWORD SegmentSize,
        DWORD MaxGen0Size)
    {
        CONTRACTL
        {
            NOTHROW;
            GC_NOTRIGGER;
            ENTRY_POINT;

        }
        CONTRACTL_END;

        HRESULT hr = S_OK;
        BEGIN_ENTRYPOINT_NOTHROW;

        // Set default overrides if specified by caller.
        if (SegmentSize != (DWORD) ~0 && SegmentSize > 0)
        {
            hr = _SetGCSegmentSize(SegmentSize);
        }

        if (SUCCEEDED(hr) && MaxGen0Size != (DWORD) ~0 && MaxGen0Size > 0)
        {
            hr = _SetGCMaxGen0Size(MaxGen0Size);
        }

        END_ENTRYPOINT_NOTHROW;

        return (hr);
    }

    virtual HRESULT STDMETHODCALLTYPE SetGCStartupLimitsEx(
        SIZE_T SegmentSize,
        SIZE_T MaxGen0Size)
    {
        CONTRACTL
        {
            NOTHROW;
            GC_NOTRIGGER;
            ENTRY_POINT;

        }
        CONTRACTL_END;

        HRESULT hr = S_OK;
        BEGIN_ENTRYPOINT_NOTHROW;

        // Set default overrides if specified by caller.
        if (SegmentSize != (SIZE_T) ~0 && SegmentSize > 0)
        {
            hr = _SetGCSegmentSize(SegmentSize);
        }

        if (SUCCEEDED(hr) && MaxGen0Size != (SIZE_T) ~0 && MaxGen0Size > 0)
        {
            hr = _SetGCMaxGen0Size(MaxGen0Size);
        }

        END_ENTRYPOINT_NOTHROW;

        return (hr);
    }

    virtual ULONG STDMETHODCALLTYPE AddRef(void)
    {
        LIMITED_METHOD_CONTRACT;
        return 1;
    }

    virtual HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, OUT PVOID *ppUnk)
    {
        LIMITED_METHOD_CONTRACT;
        if (riid != IID_ICLRGCManager && riid != IID_ICLRGCManager2 && riid != IID_IUnknown)
            return (E_NOINTERFACE);
        *ppUnk = this;
        return S_OK;
    }

    virtual ULONG STDMETHODCALLTYPE Release(void)
    {
        LIMITED_METHOD_CONTRACT;
        return 1;
    }
private:
    HRESULT _SetGCSegmentSize(SIZE_T SegmentSize);
    HRESULT _SetGCMaxGen0Size(SIZE_T MaxGen0Size);
};


HRESULT CCLRGCManager::_SetGCSegmentSize(SIZE_T SegmentSize)
{
    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
        SO_TOLERANT;
    }
    CONTRACTL_END;

    HRESULT hr = S_OK;

    // Sanity check the value, it must be a power of two and big enough.
    if (!GCHeapUtilities::GetGCHeap()->IsValidSegmentSize(SegmentSize))
    {
        hr = E_INVALIDARG;
    }
    else
    {
        Host_SegmentSize = SegmentSize;
        Host_fSegmentSizeSet = TRUE;
    }

    return (hr);
}

HRESULT CCLRGCManager::_SetGCMaxGen0Size(SIZE_T MaxGen0Size)
{
    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
        SO_TOLERANT;
    }
    CONTRACTL_END;

    HRESULT hr = S_OK;

    // Sanity check the value is at least large enough.
    if (!GCHeapUtilities::GetGCHeap()->IsValidGen0MaxSize(MaxGen0Size))
    {
        hr = E_INVALIDARG;
    }
    else
    {
        Host_MaxGen0Size = MaxGen0Size;
        Host_fMaxGen0SizeSet = TRUE;
    }

    return (hr);
}

static CCLRGCManager s_GCManager;
#endif //FEATURE_WINDOWSPHONE

#ifdef FEATURE_APPDOMAIN_RESOURCE_MONITORING
class CCLRAppDomainResourceMonitor : public ICLRAppDomainResourceMonitor
{
public:
    virtual HRESULT STDMETHODCALLTYPE GetCurrentAllocated(DWORD dwAppDomainId, 
                                                          ULONGLONG* pBytesAllocated)
    {
        CONTRACTL
        {
            NOTHROW;
            GC_NOTRIGGER;
            ENTRY_POINT;
        }
        CONTRACTL_END;

        HRESULT     hr = S_OK;

        BEGIN_ENTRYPOINT_NOTHROW;

        SystemDomain::LockHolder lh;
        AppDomainFromIDHolder pAppDomain((ADID)dwAppDomainId, TRUE, AppDomainFromIDHolder::SyncType_ADLock);

        if (!pAppDomain.IsUnloaded())
        {
            if (pBytesAllocated)
            {
                *pBytesAllocated = pAppDomain->GetAllocBytes();
            }
        }
        else
        {
            hr = COR_E_APPDOMAINUNLOADED;
        }

        END_ENTRYPOINT_NOTHROW;

        return (hr);
    }

    virtual HRESULT STDMETHODCALLTYPE GetCurrentSurvived(DWORD dwAppDomainId, 
                                                         ULONGLONG* pAppDomainBytesSurvived, 
                                                         ULONGLONG* pTotalBytesSurvived)
    {
        CONTRACTL
        {
            NOTHROW;
            GC_NOTRIGGER;
            ENTRY_POINT;
        }
        CONTRACTL_END;

        HRESULT     hr = S_OK;
        BEGIN_ENTRYPOINT_NOTHROW;

        SystemDomain::LockHolder lh;
        AppDomainFromIDHolder pAppDomain((ADID)dwAppDomainId, TRUE, AppDomainFromIDHolder::SyncType_ADLock);

        if (pAppDomain.IsUnloaded())
        {
            hr = COR_E_APPDOMAINUNLOADED;
        }
        else
        {
            if (pAppDomainBytesSurvived)
            {
                *pAppDomainBytesSurvived = pAppDomain->GetSurvivedBytes();
            }
            if (pTotalBytesSurvived)
            {
                *pTotalBytesSurvived = SystemDomain::GetTotalSurvivedBytes();
            }
        }

        END_ENTRYPOINT_NOTHROW;

        return (hr);
    }

    virtual HRESULT STDMETHODCALLTYPE GetCurrentCpuTime(DWORD dwAppDomainId, 
                                                        ULONGLONG* pMilliseconds)
    {
        CONTRACTL
        {
            NOTHROW;
            GC_TRIGGERS;
            ENTRY_POINT;
        }
        CONTRACTL_END;

        HRESULT hr = S_OK;

        BEGIN_ENTRYPOINT_NOTHROW;

        {
            SystemDomain::LockHolder lh;
    
            {
                AppDomainFromIDHolder pAppDomain((ADID)dwAppDomainId, TRUE, AppDomainFromIDHolder::SyncType_ADLock);

                if (!pAppDomain.IsUnloaded())
                {
                    if (pMilliseconds)
                    {
                        *pMilliseconds = pAppDomain->QueryProcessorUsage() / 10000;
                    }
                }
                else
                {
                    hr = COR_E_APPDOMAINUNLOADED;
                }
            }
        }

        END_ENTRYPOINT_NOTHROW;

        return hr;
    }

    virtual ULONG STDMETHODCALLTYPE AddRef(void)
    {
        LIMITED_METHOD_CONTRACT;
        return 1;
    }

    virtual HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, OUT PVOID *ppUnk)
    {
        LIMITED_METHOD_CONTRACT;
        *ppUnk = NULL;
        if (riid == IID_IUnknown)
            *ppUnk = (IUnknown*)this;
        else if (riid == IID_ICLRAppDomainResourceMonitor)
            *ppUnk = (ICLRAppDomainResourceMonitor*)this;
        else
            return E_NOINTERFACE;
        return S_OK;
    }

    virtual ULONG STDMETHODCALLTYPE Release(void)
    {
        LIMITED_METHOD_CONTRACT;
        return 1;
    }
};
static CCLRAppDomainResourceMonitor s_Arm;
#endif //FEATURE_APPDOMAIN_RESOURCE_MONITORING


BOOL g_CLRPolicyRequested = FALSE;

class CCorCLRControl: public ICLRControl
{
public:
    virtual HRESULT STDMETHODCALLTYPE GetCLRManager(REFIID riid, void **ppObject)
    {
        CONTRACTL
        {
            NOTHROW;
            GC_NOTRIGGER;
            SO_TOLERANT;    // no global state updates
        }
        CONTRACTL_END;

        // Sanity check.
        if (ppObject == NULL)
            return E_INVALIDARG;

#if defined(FEATURE_WINDOWSPHONE)
        if (riid == IID_ICLRErrorReportingManager2)
        {
            *ppObject = &g_CLRErrorReportingManager;
            return S_OK;
        }
        else
#endif //defined(FEATURE_WINDOWSPHONE)
        if (g_fEEStarted && !m_fFullAccess)
        {
            // If runtime has been started, do not allow user to obtain CLR managers.
            return HOST_E_INVALIDOPERATION;
        }

        // CoreCLR supports ICLRPolicyManager since it allows the host
        // to specify the policy for AccessViolation.  
        else if (riid == IID_ICLRPolicyManager) {
            *ppObject = &s_PolicyManager;
            FastInterlockExchange((LONG*)&g_CLRPolicyRequested, TRUE);
            return S_OK;
        }

#if defined(FEATURE_WINDOWSPHONE)
        else if ((riid == IID_ICLRGCManager) || (riid == IID_ICLRGCManager2))
        {
            *ppObject = &s_GCManager;
            return S_OK;
        }
#endif //FEATURE_WINDOWSPHONE

#ifdef FEATURE_APPDOMAIN_RESOURCE_MONITORING
        else if (riid == IID_ICLRAppDomainResourceMonitor)
        {
            EnableARM();
            *ppObject = &s_Arm;
            return S_OK;
        }
#endif //FEATURE_APPDOMAIN_RESOURCE_MONITORING
        else
            return (E_NOINTERFACE);
    }

    virtual HRESULT STDMETHODCALLTYPE SetAppDomainManagerType(
        LPCWSTR pwzAppDomainManagerAssembly,
        LPCWSTR pwzAppDomainManagerType)
    {
        
        // CoreCLR does not support this method
        return E_NOTIMPL;
    }

    virtual ULONG STDMETHODCALLTYPE AddRef(void)
    {
        LIMITED_METHOD_CONTRACT;
        return 1;
    }

    virtual ULONG STDMETHODCALLTYPE Release(void)
    {
        LIMITED_METHOD_CONTRACT;
        return 1;
    }

    BEGIN_INTERFACE HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid,
                                                             void **ppvObject)
    {
        LIMITED_METHOD_CONTRACT;
        if (riid != IID_ICLRControl && riid != IID_IUnknown)
            return (E_NOINTERFACE);

        // Ensure that the out going pointer is not null
        if (ppvObject == NULL)
            return E_POINTER;

        *ppvObject = this;
        return S_OK;
    }

    // This is to avoid having ctor.  We have static objects, and it is
    // difficult to support ctor on certain platform.
    void SetAccess(BOOL fFullAccess)
    {
        LIMITED_METHOD_CONTRACT;
        m_fFullAccess = fFullAccess;
    }
private:
    BOOL m_fFullAccess;
};

// Before CLR starts, we give out s_CorCLRControl which has full access to all managers.
// After CLR starts, we give out s_CorCLRControlLimited which allows limited access to managers.
static CCorCLRControl s_CorCLRControl;


///////////////////////////////////////////////////////////////////////////////
// ICLRRuntimeHost::GetCLRControl
HRESULT CorHost2::GetCLRControl(ICLRControl** pCLRControl)
{
    LIMITED_METHOD_CONTRACT;
    
    // Ensure that we have a valid pointer
    if (pCLRControl == NULL)
    {
        return E_POINTER;
    }

    HRESULT hr = S_OK;
    
    STATIC_CONTRACT_ENTRY_POINT;
    BEGIN_ENTRYPOINT_NOTHROW;
    if (!g_fEEStarted && m_Version >= 2)
    {
        s_CorCLRControl.SetAccess(TRUE);
        *pCLRControl = &s_CorCLRControl;
    }
    else
    {
        // If :
        // 1) request comes for interface other than ICLRControl*, OR
        // 2) runtime has already started, OR
        // 3) version is not 2
        //
        // we will return failure and set the out pointer to NULL
        *pCLRControl = NULL;
        if (g_fEEStarted)
        {
            // Return HOST_E_INVALIDOPERATION as per MSDN if runtime has already started
            hr = HOST_E_INVALIDOPERATION;
        }
        else
        {
            hr = E_NOTIMPL;
        }
    }
    END_ENTRYPOINT_NOTHROW;

    return hr;
}


LPCWSTR CorHost2::GetAppDomainManagerAsm()
{
    LIMITED_METHOD_CONTRACT;
    return NULL;
}

LPCWSTR CorHost2::GetAppDomainManagerType()
{
    LIMITED_METHOD_CONTRACT;
    return NULL;
}

// static
EInitializeNewDomainFlags CorHost2::GetAppDomainManagerInitializeNewDomainFlags()
{
    LIMITED_METHOD_CONTRACT;
    return eInitializeNewDomainFlags_None;
}


#endif // !DAC


#ifdef DACCESS_COMPILE


#endif //DACCESS_COMPILE

#ifndef DACCESS_COMPILE


#if defined(FEATURE_WINDOWSPHONE)

HRESULT CCLRErrorReportingManager::QueryInterface(REFIID riid, void** ppUnk)
{
    if (!ppUnk)
        return E_POINTER;

    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
        SO_TOLERANT;
    }
    CONTRACTL_END;

    HRESULT hr = S_OK;
    
    if (ppUnk == NULL)
    {
        return E_POINTER;
    }

    *ppUnk = 0;

    // Deliberately do NOT hand out ICorConfiguration.  They must explicitly call
    // GetConfiguration to obtain that interface.
    if (riid == IID_IUnknown)
    {
        *ppUnk = (IUnknown *) this;
    }
    else if (riid == IID_ICLRErrorReportingManager)
    {
        *ppUnk = (ICLRErrorReportingManager *) this;
    }
#ifdef FEATURE_WINDOWSPHONE
    else if (riid == IID_ICLRErrorReportingManager2)
    {
        *ppUnk = (ICLRErrorReportingManager2 *) this;
    }
#endif // FEATURE_WINDOWSPHONE
    else
    {
        hr = E_NOINTERFACE;
    }

    return hr;

} // HRESULT CCLRErrorReportingManager::QueryInterface()

ULONG CCLRErrorReportingManager::AddRef()
{
    LIMITED_METHOD_CONTRACT;
    return 1;
} // HRESULT CCLRErrorReportingManager::AddRef()

ULONG CCLRErrorReportingManager::Release()
{
    LIMITED_METHOD_CONTRACT;
    return 1;
} // HRESULT CCLRErrorReportingManager::Release()

// Get Watson bucket parameters for "current" exception (on calling thread).
HRESULT CCLRErrorReportingManager::GetBucketParametersForCurrentException(
    BucketParameters *pParams)
{
    CONTRACTL
    {
        WRAPPER(THROWS);
        WRAPPER(GC_TRIGGERS);
        ENTRY_POINT;
    }
    CONTRACTL_END;

    HRESULT hr = S_OK;
    BEGIN_ENTRYPOINT_NOTHROW;

    // To avoid confusion, clear the buckets.
    memset(pParams, 0, sizeof(BucketParameters));

#ifndef FEATURE_PAL   
    // Defer to Watson helper.
    hr = ::GetBucketParametersForCurrentException(pParams);
 #else
    // Watson doesn't exist on non-windows platforms
    hr = E_NOTIMPL;
#endif // !FEATURE_PAL

    END_ENTRYPOINT_NOTHROW;

    return hr;

} // HRESULT CCLRErrorReportingManager::GetBucketParametersForCurrentException()

//
// The BeginCustomDump function configures the custom dump support
//
// Parameters -
// dwFlavor     - The flavor of the dump
// dwNumItems   - The number of items in the CustomDumpItem array.
//                  Should always be zero today, since no custom items are defined
// items        - Array of CustomDumpItem structs specifying items to be added to the dump.
//                  Should always be NULL today, since no custom items are defined.
// dwReserved   - reserved for future use. Must be zero today
//
HRESULT CCLRErrorReportingManager::BeginCustomDump( ECustomDumpFlavor dwFlavor,
                                        DWORD dwNumItems,
                                        CustomDumpItem items[],
                                        DWORD dwReserved)
{
    STATIC_CONTRACT_ENTRY_POINT;
    HRESULT hr = S_OK;

    BEGIN_ENTRYPOINT_NOTHROW;

    if (dwNumItems != 0 ||  items != NULL || dwReserved != 0)
    {
        IfFailGo(E_INVALIDARG);
    }
    if (g_ECustomDumpFlavor != DUMP_FLAVOR_Default)
    {
        // BeginCustomDump is called without matching EndCustomDump
        IfFailGo(E_INVALIDARG);
    }
    g_ECustomDumpFlavor = dwFlavor;

ErrExit:
    END_ENTRYPOINT_NOTHROW;

    return hr;
}

//
// EndCustomDump clears the custom dump configuration
//
HRESULT CCLRErrorReportingManager::EndCustomDump()
{
    STATIC_CONTRACT_ENTRY_POINT;
    // NOT IMPLEMENTED YET
    BEGIN_ENTRYPOINT_NOTHROW;
    g_ECustomDumpFlavor = DUMP_FLAVOR_Default;
    END_ENTRYPOINT_NOTHROW;

    return S_OK;
}

#ifdef FEATURE_WINDOWSPHONE
HRESULT CopyStringWorker(_Out_ WCHAR** pTarget, WCHAR const* pSource)
{
    LIMITED_METHOD_CONTRACT;

    if (pTarget == NULL || pSource == NULL)
        return E_INVALIDARG;

    if (*pTarget)
        delete[] (*pTarget);

    // allocate space for the data plus one wchar for NULL
    size_t sourceLen = wcslen(pSource);
    *pTarget = new (nothrow) WCHAR[sourceLen + 1];
    
    if (!(*pTarget))
        return E_OUTOFMEMORY;

    errno_t result = wcsncpy_s(*pTarget, sourceLen + 1, pSource, sourceLen);
    _ASSERTE(result == 0);
    
    if (result != 0)
    {
        delete[] (*pTarget);
        *pTarget = NULL;

        return E_FAIL;
    }

    return S_OK;
}

CCLRErrorReportingManager::BucketParamsCache::BucketParamsCache(DWORD maxNumParams) : m_pParams(NULL), m_cMaxParams(maxNumParams)
{
    LIMITED_METHOD_CONTRACT;
}

CCLRErrorReportingManager::BucketParamsCache::~BucketParamsCache()
{
    LIMITED_METHOD_CONTRACT;

    if (m_pParams)
    {
        for (DWORD i = 0; i < m_cMaxParams; ++i)
            if (m_pParams[i]) delete[] m_pParams[i];
    }
}

WCHAR const* CCLRErrorReportingManager::BucketParamsCache::GetAt(BucketParameterIndex index)
{
    LIMITED_METHOD_CONTRACT;

    if (index >= InvalidBucketParamIndex)
    {
        _ASSERTE(!"bad bucket parameter index");
        return NULL;
    }

    if (!m_pParams)
        return NULL;

    return m_pParams[index];
}

HRESULT CCLRErrorReportingManager::BucketParamsCache::SetAt(BucketParameterIndex index, WCHAR const* val)
{
    LIMITED_METHOD_CONTRACT;

    if (index >= InvalidBucketParamIndex)
    {
        _ASSERTE(!"bad bucket parameter index");
        return E_INVALIDARG;
    }

    if (!val)
        return E_INVALIDARG;

    if (!m_pParams)
    {
        m_pParams = new (nothrow) WCHAR*[m_cMaxParams];
        if (!m_pParams)
            return E_OUTOFMEMORY;

        for (DWORD i = 0; i < m_cMaxParams; ++i)
            m_pParams[i] = NULL;
    }

    return CopyStringWorker(&m_pParams[index], val);
}

HRESULT CCLRErrorReportingManager::CopyToDataCache(_Out_ WCHAR** pTarget, WCHAR const* pSource)
{
    LIMITED_METHOD_CONTRACT;

    return CopyStringWorker(pTarget, pSource);
}

HRESULT CCLRErrorReportingManager::SetApplicationData(ApplicationDataKey key, WCHAR const* pValue)
{
    STATIC_CONTRACT_ENTRY_POINT;

    BEGIN_ENTRYPOINT_NOTHROW;

    if(g_fEEStarted)
        return HOST_E_INVALIDOPERATION;

    if (pValue == NULL || wcslen(pValue) > MAX_LONGPATH)
        return E_INVALIDARG;

    HRESULT hr = S_OK;

    switch (key)
    {
    case ApplicationID:
        hr = CopyToDataCache(&m_pApplicationId, pValue);
        break;

    case InstanceID:
        hr = CopyToDataCache(&m_pInstanceId, pValue);
        break;

    default:
        hr = E_INVALIDARG;
    }
    
    END_ENTRYPOINT_NOTHROW;

    return hr;
}

HRESULT CCLRErrorReportingManager::SetBucketParametersForUnhandledException(BucketParameters const* pBucketParams, DWORD* pCountParams)
{
    STATIC_CONTRACT_ENTRY_POINT;

    BEGIN_ENTRYPOINT_NOTHROW;

    if(g_fEEStarted)
        return HOST_E_INVALIDOPERATION;

    if (pBucketParams == NULL || pCountParams == NULL || pBucketParams->fInited != TRUE)
        return E_INVALIDARG;

    *pCountParams = 0;

    if (!m_pBucketParamsCache)
    {
        m_pBucketParamsCache = new (nothrow) BucketParamsCache(InvalidBucketParamIndex);
        if (!m_pBucketParamsCache)
            return E_OUTOFMEMORY;
    }

    HRESULT hr = S_OK;
    bool hasOverride = false;

    for (DWORD i = 0; i < InvalidBucketParamIndex; ++i)
    {
        if (pBucketParams->pszParams[i][0] != W('\0'))
        {
            hasOverride = true;
            hr = m_pBucketParamsCache->SetAt(static_cast<BucketParameterIndex>(i), pBucketParams->pszParams[i]);
            if (SUCCEEDED(hr))
                *pCountParams += 1;
            else
                break;
        }
    }
    
    if (!hasOverride)
        return E_INVALIDARG;
    
    END_ENTRYPOINT_NOTHROW;

    return hr;
}

WCHAR const* CCLRErrorReportingManager::GetApplicationData(ApplicationDataKey key)
{
    LIMITED_METHOD_CONTRACT;

    WCHAR* pValue = NULL;

    switch (key)
    {
    case ApplicationID:
        pValue = m_pApplicationId;
        break;

    case InstanceID:
        pValue = m_pInstanceId;
        break;

    default:
        _ASSERTE(!"invalid key specified");
    }

    return pValue;
}

WCHAR const* CCLRErrorReportingManager::GetBucketParamOverride(BucketParameterIndex bucketParamId)
{
    LIMITED_METHOD_CONTRACT;

    if (!m_pBucketParamsCache)
        return NULL;

    return m_pBucketParamsCache->GetAt(bucketParamId);
}

#endif // FEATURE_WINDOWSPHONE

CCLRErrorReportingManager::CCLRErrorReportingManager()
{
    LIMITED_METHOD_CONTRACT;
#ifdef FEATURE_WINDOWSPHONE
    m_pApplicationId = NULL;
    m_pInstanceId = NULL;
    m_pBucketParamsCache = NULL;
#endif
}

CCLRErrorReportingManager::~CCLRErrorReportingManager()
{
    LIMITED_METHOD_CONTRACT;
#ifdef FEATURE_WINDOWSPHONE
    if (m_pApplicationId)
        delete[] m_pApplicationId;

    if (m_pInstanceId)
        delete[] m_pInstanceId;

    if (m_pBucketParamsCache)
        delete m_pBucketParamsCache;
#endif
}

#endif // defined(FEATURE_WINDOWSPHONE)

#ifdef FEATURE_IPCMAN

CrstStatic          CCLRSecurityAttributeManager::m_hostSAMutex;
PACL                CCLRSecurityAttributeManager::m_pACL;

SECURITY_ATTRIBUTES CCLRSecurityAttributeManager::m_hostSA;
SECURITY_DESCRIPTOR CCLRSecurityAttributeManager::m_hostSD;

/*
* constructor
*
*/
void CCLRSecurityAttributeManager::ProcessInit()
{
    CONTRACTL
    {
        THROWS;
        GC_NOTRIGGER;
    }
    CONTRACTL_END;

    m_hostSAMutex.Init(CrstReDacl, CRST_UNSAFE_ANYMODE);
    m_pACL = NULL;
}

/*
* destructor
*
*/
void CCLRSecurityAttributeManager::ProcessCleanUp()
{
    CONTRACTL
    {
        GC_NOTRIGGER;
        NOTHROW;
    }
    CONTRACTL_END;

    m_hostSAMutex.Destroy();
    if (m_pACL)
        CoTaskMemFree(m_pACL);
}

// Set private block and events to the new ACL.
HRESULT CCLRSecurityAttributeManager::SetDACL(PACL pacl)
{
    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
        MODE_ANY;
    }
    CONTRACTL_END;

    HRESULT     hr = S_OK;
    DWORD       dwError;
    PACL        pNewACL = NULL;
    HANDLE      hProc = NULL;
    DWORD       pid = 0;

    // @todo: How can we make sure that debugger attach will not attempt to happen during this time???
    //
    CrstHolder ch(&m_hostSAMutex);

    // make sure our host pass our a valid ACL
    if (!IsValidAcl(pacl))
    {
        dwError = GetLastError();
        hr = HRESULT_FROM_WIN32(dwError);
        goto ErrExit;
    }

    // Cannnot set DACL while debugger is attached. Because the events are already all hooked up
    // between LS and RS.
    if (CORDebuggerAttached())
        return CORDBG_E_DEBUGGER_ALREADY_ATTACHED;

    // make a copy of the new ACL
    pNewACL = (PACL) CoTaskMemAlloc(pacl->AclSize);
    if (FAILED( CopyACL(pacl, pNewACL)))
        goto ErrExit;

    _ASSERTE (SECURITY_DESCRIPTOR_MIN_LENGTH == sizeof(SECURITY_DESCRIPTOR));

    if (!InitializeSecurityDescriptor(&m_hostSD, SECURITY_DESCRIPTOR_REVISION))
    {
        hr = HRESULT_FROM_GetLastError();
        goto ErrExit;
    }

    if (!SetSecurityDescriptorDacl(&m_hostSD, TRUE, pNewACL, FALSE))
    {
        hr = HRESULT_FROM_GetLastError();
        goto ErrExit;
    }

    // Now cache the pNewACL to m_pACL and delete m_pACL.
    if (m_pACL)
        CoTaskMemFree(m_pACL);

    m_pACL = pNewACL;
    pNewACL = NULL;

    m_hostSA.nLength = sizeof(SECURITY_ATTRIBUTES);
    m_hostSA.lpSecurityDescriptor = &m_hostSD;
    m_hostSA.bInheritHandle = FALSE;

    // first of all, try to reDacl on the process token
    pid = GetCurrentProcessId();
    hProc = OpenProcess(WRITE_DAC, FALSE, pid);
    if (hProc == NULL)
    {
        hr = HRESULT_FROM_GetLastError();
        goto ErrExit;
    }
    if (SetKernelObjectSecurity(hProc, DACL_SECURITY_INFORMATION, &m_hostSD) == 0)
    {
        // failed!
        hr = HRESULT_FROM_GetLastError();
        goto ErrExit;
    }


    // now reset all of the kernel object token's DACL.
    // This will reDACL the global shared section
    if (FAILED(g_pIPCManagerInterface->ReDaclLegacyPrivateBlock(&m_hostSD)))
        goto ErrExit;

    // This will reDacl on debugger events.
    if (g_pDebugInterface)
    {
        g_pDebugInterface->ReDaclEvents(&m_hostSD);
    }

ErrExit:
    if (pNewACL)
        CoTaskMemFree(pNewACL);
    if (hProc != NULL)
        CloseHandle(hProc);

    return hr;
}

// cLen - specify the size of input buffer ppacl. If cLen is zero or ppacl is null,
// pcLenTotal will return the total size of required pacl buffer.
// pacl - caller allocated space. We will fill acl in this buffer.
// pcLenTotal - the total size of ACL.
//
HRESULT CCLRSecurityAttributeManager::GetDACL(PACL *ppacl)
{
    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
        MODE_ANY;
    }
    CONTRACTL_END;

    HRESULT     hr = S_OK;
    PACL        pNewACL = NULL;
    PACL        pDefaultACL = NULL;
    SECURITY_ATTRIBUTES *pSA = NULL;

    // output parameter cannot be NULL
    if (ppacl == NULL)
        return E_INVALIDARG;

    *ppacl = NULL;

    CrstHolder ch(&m_hostSAMutex);

    // we want to return the ACL of our default policy
    if (m_pACL == NULL)
    {
        hr = g_pIPCManagerInterface->CreateWinNTDescriptor(GetCurrentProcessId(), &pSA, eDescriptor_Private);
        if (FAILED(hr))
        {
            goto ErrExit;
        }
        EX_TRY
        {
            BOOL bDaclPresent;
            BOOL bDaclDefault;

            ::GetSecurityDescriptorDacl(pSA->lpSecurityDescriptor, &bDaclPresent, &pDefaultACL, &bDaclDefault);
        }
        EX_CATCH
        {
            hr = GET_EXCEPTION()->GetHR();
        }
        EX_END_CATCH(SwallowAllExceptions);
        if (FAILED(hr) || pDefaultACL == NULL || pDefaultACL->AclSize == 0)
        {
            goto ErrExit;
        }
    }
    else
    {
        pDefaultACL = m_pACL;
    }

    pNewACL = (PACL) CoTaskMemAlloc(pDefaultACL->AclSize);
    if (pNewACL == NULL)
    {
        hr = E_OUTOFMEMORY;
        goto ErrExit;
    }

    // make a copy of ACL
    hr = CCLRSecurityAttributeManager::CopyACL(pDefaultACL, pNewACL);
    if (SUCCEEDED(hr))
        *ppacl = pNewACL;

ErrExit:
    if (FAILED(hr))
    {
        if (pNewACL)
        {
            CoTaskMemFree(pNewACL);
        }
    }
    if (pSA != NULL)
    {
        g_pIPCManagerInterface->DestroySecurityAttributes(pSA);
    }
    return hr;
}


// This API will duplicate a copy of pAclOrigingal and pass it out on ppAclNew
HRESULT CCLRSecurityAttributeManager::CopyACL(PACL pAclOriginal, PACL pNewACL)
{
    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
        MODE_ANY;
    }
    CONTRACTL_END;

    HRESULT     hr = NO_ERROR;
    DWORD       dwError = GetLastError();
    int         i;
    ACE_HEADER  *pDACLAce;

    _ASSERTE(pNewACL && pAclOriginal);

    // initialize the target ACL buffer
    if (!InitializeAcl(pNewACL, pAclOriginal->AclSize, ACL_REVISION))
    {
        dwError = GetLastError();
        hr = HRESULT_FROM_WIN32(dwError);
        goto ErrExit;
    }

    // loop through each existing ace and copy it over
    for (i = 0; i < pAclOriginal->AceCount; i++)
    {
        if (!GetAce(pAclOriginal, i, (LPVOID *) &pDACLAce))
        {
            dwError = GetLastError();
            hr = HRESULT_FROM_WIN32(dwError);
            goto ErrExit;
        }

        if (!AddAce(pNewACL, ACL_REVISION, i, pDACLAce, pDACLAce->AceSize))
        {
            dwError = GetLastError();
            hr = HRESULT_FROM_WIN32(dwError);
            goto ErrExit;
        }
    }

    // make sure everything went well with the new ACL
    if (!IsValidAcl(pNewACL))
    {
        dwError = GetLastError();
        hr = HRESULT_FROM_WIN32(dwError);
        goto ErrExit;
    }

ErrExit:
    return hr;
}


HRESULT CCLRSecurityAttributeManager::GetHostSecurityAttributes(SECURITY_ATTRIBUTES **ppSA)
{
    WRAPPER_NO_CONTRACT;

    if(!ppSA)
        return E_POINTER;

    HRESULT hr = S_OK;

    *ppSA = NULL;

    // host has specified ACL
    if (m_pACL != NULL)
        *ppSA = &(m_hostSA);

    else
        hr = g_pIPCManagerInterface->CreateWinNTDescriptor(GetCurrentProcessId(), ppSA, eDescriptor_Private);

    return hr;
}

void CCLRSecurityAttributeManager::DestroyHostSecurityAttributes(SECURITY_ATTRIBUTES *pSA)
{
    WRAPPER_NO_CONTRACT;

    // no pSA to cleanup
    if (pSA == NULL)
        return;

    // it is our current host SA.
    if (&(m_hostSA) == pSA)
        return;

    g_pIPCManagerInterface->DestroySecurityAttributes(pSA);
}
#endif // FEATURE_IPCMAN

void GetProcessMemoryLoad(LPMEMORYSTATUSEX pMSEX)
{
    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
    }
    CONTRACTL_END;

    pMSEX->dwLength = sizeof(MEMORYSTATUSEX);
    BOOL fRet = GlobalMemoryStatusEx(pMSEX);
    _ASSERTE (fRet);


    // If the machine has more RAM than virtual address limit, let us cap it.
    // Our GC can never use more than virtual address limit.
    if (pMSEX->ullAvailPhys > pMSEX->ullTotalVirtual)
    {
        pMSEX->ullAvailPhys = pMSEX->ullAvailVirtual;
    }
}

// This is the instance that exposes interfaces out to all the other DLLs of the CLR
// so they can use our services for TLS, synchronization, memory allocation, etc.
static BYTE g_CEEInstance[sizeof(CExecutionEngine)];
static Volatile<IExecutionEngine*> g_pCEE = NULL;

PTLS_CALLBACK_FUNCTION CExecutionEngine::Callbacks[MAX_PREDEFINED_TLS_SLOT];

extern "C" IExecutionEngine * __stdcall IEE()
{
    LIMITED_METHOD_CONTRACT;

    // Unfortunately,we can't probe here. The probing system requires the
    // use of TLS, and in order to initialize TLS we need to call IEE.

    //BEGIN_ENTRYPOINT_VOIDRET;


    // The following code does NOT contain a race condition.  The following code is BY DESIGN.
    // The issue is that we can have two separate threads inside this if statement, both of which are
    // initializing the g_CEEInstance variable (and subsequently updating g_pCEE).  This works fine,
    // and will not cause an inconsistent state due to the fact that CExecutionEngine has no
    // local variables.  If multiple threads make it inside this if statement, it will copy the same
    // bytes over g_CEEInstance and there will not be a time when there is an inconsistent state.
    if ( !g_pCEE )
    {
        // Create a local copy on the stack and then copy it over to the static instance.
        // This avoids race conditions caused by multiple initializations of vtable in the constructor
       CExecutionEngine local;
       memcpy(&g_CEEInstance, (void*)&local, sizeof(CExecutionEngine));

       g_pCEE = (IExecutionEngine*)(CExecutionEngine*)&g_CEEInstance;
    }
    //END_ENTRYPOINT_VOIDRET;

    return g_pCEE;
}


HRESULT STDMETHODCALLTYPE CExecutionEngine::QueryInterface(REFIID id, void **pInterface)
{
    LIMITED_METHOD_CONTRACT;
    STATIC_CONTRACT_SO_TOLERANT;

    if (!pInterface)
        return E_POINTER;

    *pInterface = NULL;

    //CANNOTTHROWCOMPLUSEXCEPTION();
    if (id == IID_IExecutionEngine)
        *pInterface = (IExecutionEngine *)this;
    else if (id == IID_IEEMemoryManager)
        *pInterface = (IEEMemoryManager *)this;
    else if (id == IID_IUnknown)
        *pInterface = (IUnknown *)(IExecutionEngine *)this;
    else
        return E_NOINTERFACE;

    AddRef();
    return S_OK;
} // HRESULT STDMETHODCALLTYPE CExecutionEngine::QueryInterface()


ULONG STDMETHODCALLTYPE CExecutionEngine::AddRef()
{
    LIMITED_METHOD_CONTRACT;
    return 1;
}

ULONG STDMETHODCALLTYPE CExecutionEngine::Release()
{
    LIMITED_METHOD_CONTRACT;
    return 1;
}

struct ClrTlsInfo
{
    void* data[MAX_PREDEFINED_TLS_SLOT];
    // When hosted, we may not be able to delete memory in DLL_THREAD_DETACH.
    // We will chain this into a side list, and free these on Finalizer thread.
    ClrTlsInfo *next;
};

#define DataToClrTlsInfo(a) (a)?(ClrTlsInfo*)((BYTE*)a - offsetof(ClrTlsInfo, data)):NULL


#ifdef HAS_FLS_SUPPORT

static BOOL fHasFlsSupport = FALSE;

typedef DWORD (*Func_FlsAlloc)(PFLS_CALLBACK_FUNCTION lpCallback);
typedef BOOL (*Func_FlsFree)(DWORD dwFlsIndex);
typedef BOOL (*Func_FlsSetValue)(DWORD dwFlsIndex,PVOID lpFlsData);
typedef PVOID (*Func_FlsGetValue)(DWORD dwFlsIndex);

static DWORD FlsIndex = FLS_OUT_OF_INDEXES;
static Func_FlsAlloc pFlsAlloc;
static Func_FlsSetValue pFlsSetValue;
static Func_FlsFree pFlsFree;
static Func_FlsGetValue pFlsGetValue;
static Volatile<BOOL> fFlsSetupDone = FALSE;

VOID WINAPI FlsCallback(
  PVOID lpFlsData
)
{
    LIMITED_METHOD_CONTRACT;

    _ASSERTE (pFlsGetValue);
    if (pFlsGetValue(FlsIndex) != lpFlsData)
    {
        // The current running fiber is being destroyed.  We can not destroy the memory yet,
        // because our DllMain function may still need the memory.
        CExecutionEngine::ThreadDetaching((void **)lpFlsData);        
    }
    else
    {
        // The thread is being wound down.
        // In hosting scenarios the host will have already called ICLRTask::ExitTask, which 
        // ends up calling CExecutionEngine::SwitchOut, which will have reset the TLS at TlsIndex.
        // 
        // Unfortunately different OSes have different ordering of destroying FLS data and sending
        // the DLL_THREAD_DETACH notification (pre-Vista FlsCallback is called after DllMain, while 
        // in Vista and up, FlsCallback is called before DllMain).  Additionally, starting with 
        // Vista SP1 and Win2k8, the OS will set the FLS slot to 0 after the call to FlsCallback, 
        // effectively removing our last reference to this data. Since in EEDllMain we need to be 
        // able to access the FLS data, we save lpFlsData in the TLS slot at TlsIndex, if needed.
        if (CExecutionEngine::GetTlsData() == NULL)
        {
            CExecutionEngine::SetTlsData((void **)lpFlsData);
        }
    }
}

#endif // HAS_FLS_SUPPORT


#ifdef FEATURE_IMPLICIT_TLS
void** CExecutionEngine::GetTlsData()
{
    LIMITED_METHOD_CONTRACT;

   return gCurrentThreadInfo.m_EETlsData;
}

BOOL CExecutionEngine::SetTlsData (void** ppTlsInfo)
{
    LIMITED_METHOD_CONTRACT;

    gCurrentThreadInfo.m_EETlsData = ppTlsInfo;
    return TRUE;
}
#else 
void** CExecutionEngine::GetTlsData()
{
    LIMITED_METHOD_CONTRACT;

    if (TlsIndex == TLS_OUT_OF_INDEXES)
        return NULL;

    void **ppTlsData = (void **)UnsafeTlsGetValue(TlsIndex);
    return ppTlsData;
}
BOOL CExecutionEngine::SetTlsData (void** ppTlsInfo)
{
    LIMITED_METHOD_CONTRACT;

    if (TlsIndex == TLS_OUT_OF_INDEXES)
        return FALSE;

    return UnsafeTlsSetValue(TlsIndex, ppTlsInfo);
}

#endif // FEATURE_IMPLICIT_TLS

//---------------------------------------------------------------------------------------
//
// Returns the current logical thread's data block (ClrTlsInfo::data).
//
// Arguments:
//    slot - Index of the slot that is about to be requested
//    force - If the data block does not exist yet, create it as a side-effect
//
// Return Value:
//    NULL, if the data block did not exist yet for the current thread and force was FALSE.
//    A pointer to the data block, otherwise.
//
// Notes:
//    If the underlying OS does not support fiber mode, the data block is stored in TLS.
//    If the underlying OS does support fiber mode, it is primarily stored in FLS,
//    and cached in TLS so that we can use our generated optimized TLS accessors.
//
// TLS support for the other DLLs of the CLR operates quite differently in hosted
// and unhosted scenarios.

void **CExecutionEngine::CheckThreadState(DWORD slot, BOOL force)
{
    STATIC_CONTRACT_GC_NOTRIGGER;
    STATIC_CONTRACT_THROWS;
    STATIC_CONTRACT_MODE_ANY;
    STATIC_CONTRACT_CANNOT_TAKE_LOCK;
    STATIC_CONTRACT_SO_TOLERANT;

    // !!! This function is called during Thread::SwitchIn and SwitchOut
    // !!! It is extremely important that while executing this function, we will not
    // !!! cause fiber switch.  This means we can not allocate memory, lock, etc...

    //<TODO> @TODO: Decide on an exception strategy for all the DLLs of the CLR, and then
    // enable all the exceptions out of this method.</TODO>

    // Treat as a runtime assertion, since the invariant spans many DLLs.
    _ASSERTE(slot < MAX_PREDEFINED_TLS_SLOT);
//    if (slot >= MAX_PREDEFINED_TLS_SLOT)
//        COMPlusThrow(kArgumentOutOfRangeException);

#ifdef HAS_FLS_SUPPORT
    if (!fFlsSetupDone)
    {
        // Contract depends on Fls support.  Don't use contract here.
        HMODULE hmod = GetModuleHandleA(WINDOWS_KERNEL32_DLLNAME_A);
        if (hmod)
        {
            pFlsSetValue = (Func_FlsSetValue) GetProcAddress(hmod, "FlsSetValue");
            pFlsGetValue = (Func_FlsGetValue) GetProcAddress(hmod, "FlsGetValue");
            pFlsAlloc = (Func_FlsAlloc) GetProcAddress(hmod, "FlsAlloc");
            pFlsFree = (Func_FlsFree) GetProcAddress(hmod, "FlsFree");

            if (pFlsSetValue && pFlsGetValue && pFlsAlloc && pFlsFree )
            {
                fHasFlsSupport = TRUE;
            }
            else
            {
                // Since we didn't find them all, we shouldn't have found any
                _ASSERTE( pFlsSetValue == NULL && pFlsGetValue == NULL && pFlsAlloc == NULL && pFlsFree == NULL);
            }
            fFlsSetupDone = TRUE;
        }
    }

    if (fHasFlsSupport && FlsIndex == FLS_OUT_OF_INDEXES)
    {
        // PREFIX_ASSUME needs TLS.  If we use it here, we will loop forever
#if defined(_PREFAST_) || defined(_PREFIX_) 
        if (pFlsAlloc == NULL) __UNREACHABLE();
#else
        _ASSERTE(pFlsAlloc != NULL);
#endif // _PREFAST_ || _PREFIX_

        DWORD tryFlsIndex = pFlsAlloc(FlsCallback);
        if (tryFlsIndex != FLS_OUT_OF_INDEXES)
        {
            if (FastInterlockCompareExchange((LONG*)&FlsIndex, tryFlsIndex, FLS_OUT_OF_INDEXES) != FLS_OUT_OF_INDEXES)
            {
                pFlsFree(tryFlsIndex);
            }
        }
        if (FlsIndex == FLS_OUT_OF_INDEXES)
        {
            COMPlusThrowOM();
        }
    }
#endif // HAS_FLS_SUPPORT

#ifndef FEATURE_IMPLICIT_TLS
    // Ensure we have a TLS Index
    if (TlsIndex == TLS_OUT_OF_INDEXES)
    {
        DWORD tryTlsIndex = UnsafeTlsAlloc();
        if (tryTlsIndex != TLS_OUT_OF_INDEXES)
        {
            if (FastInterlockCompareExchange((LONG*)&TlsIndex, tryTlsIndex, TLS_OUT_OF_INDEXES) != (LONG)TLS_OUT_OF_INDEXES)
            {
                UnsafeTlsFree(tryTlsIndex);
            }
        }
        if (TlsIndex == TLS_OUT_OF_INDEXES)
        {
            COMPlusThrowOM();
        }
    }
#endif // FEATURE_IMPLICIT_TLS

    void** pTlsData = CExecutionEngine::GetTlsData();
    BOOL fInTls = (pTlsData != NULL);

#ifdef HAS_FLS_SUPPORT
    if (fHasFlsSupport)
    {
        if (pTlsData == NULL)
        {
            pTlsData = (void **)pFlsGetValue(FlsIndex);
        }
    }
#endif

    ClrTlsInfo *pTlsInfo = DataToClrTlsInfo(pTlsData);
    if (pTlsInfo == 0 && force)
    {
#undef HeapAlloc
#undef GetProcessHeap
        // !!! Contract uses our TLS support.  Contract may be used before our host support is set up.
        // !!! To better support contract, we call into OS for memory allocation.
        pTlsInfo = (ClrTlsInfo*) ::HeapAlloc(GetProcessHeap(),0,sizeof(ClrTlsInfo));
#define GetProcessHeap() Dont_Use_GetProcessHeap()
#define HeapAlloc(hHeap, dwFlags, dwBytes) Dont_Use_HeapAlloc(hHeap, dwFlags, dwBytes)
        if (pTlsInfo == NULL)
        {
            goto LError;
        }
        memset (pTlsInfo, 0, sizeof(ClrTlsInfo));
#ifdef HAS_FLS_SUPPORT
        if (fHasFlsSupport && !pFlsSetValue(FlsIndex, pTlsInfo))
        {
            goto LError;
        }
#endif
        // We save the last intolerant marker on stack in this slot.  
        // -1 is the larget unsigned number, and therefore our marker is always smaller than it.
        pTlsInfo->data[TlsIdx_SOIntolerantTransitionHandler] = (void*)(-1);
    }

    if (!fInTls && pTlsInfo)
    {
#ifdef HAS_FLS_SUPPORT
        // If we have a thread object or are on a non-fiber thread, we are safe for fiber switching.
        if (!fHasFlsSupport ||
            GetThread() ||
            (g_fEEStarted || g_fEEInit) ||
            (((size_t)pTlsInfo->data[TlsIdx_ThreadType]) & (ThreadType_GC | ThreadType_Gate | ThreadType_Timer | ThreadType_DbgHelper)))
        {
#ifdef _DEBUG
            Thread *pThread = GetThread();
            if (pThread)
            {
                pThread->AddFiberInfo(Thread::ThreadTrackInfo_Lifetime);
            }
#endif
            if (!CExecutionEngine::SetTlsData(pTlsInfo->data) && !fHasFlsSupport)
            {
                goto LError;
            }
        }
#else
        if (!CExecutionEngine::SetTlsData(pTlsInfo->data))
        {
            goto LError;
        }
#endif
    }

    return pTlsInfo?pTlsInfo->data:NULL;

LError:
    if (pTlsInfo)
    {
#undef HeapFree
#undef GetProcessHeap
        ::HeapFree(GetProcessHeap(), 0, pTlsInfo);
#define GetProcessHeap() Dont_Use_GetProcessHeap()
#define HeapFree(hHeap, dwFlags, lpMem) Dont_Use_HeapFree(hHeap, dwFlags, lpMem)
    }
    // If this is for the stack probe, and we failed to allocate memory for it, we won't
    // put in a guard page.
    if (slot == TlsIdx_ClrDebugState || slot == TlsIdx_StackProbe)
        return NULL;

    ThrowOutOfMemory();
}


void **CExecutionEngine::CheckThreadStateNoCreate(DWORD slot
#ifdef _DEBUG
                                                  , BOOL fForDestruction
#endif // _DEBUG
                                                  )
{
    STATIC_CONTRACT_GC_NOTRIGGER;
    STATIC_CONTRACT_NOTHROW;
    STATIC_CONTRACT_MODE_ANY;
    STATIC_CONTRACT_SO_TOLERANT;

    // !!! This function is called during Thread::SwitchIn and SwitchOut
    // !!! It is extremely important that while executing this function, we will not
    // !!! cause fiber switch.  This means we can not allocate memory, lock, etc...


    // Treat as a runtime assertion, since the invariant spans many DLLs.
    _ASSERTE(slot < MAX_PREDEFINED_TLS_SLOT);

    void **pTlsData = CExecutionEngine::GetTlsData();

#ifdef HAS_FLS_SUPPORT
    if (fHasFlsSupport)
    {
        if (pTlsData == NULL)
        {
            pTlsData = (void **)pFlsGetValue(FlsIndex);
        }
    }
#endif

    ClrTlsInfo *pTlsInfo = DataToClrTlsInfo(pTlsData);

    return pTlsInfo?pTlsInfo->data:NULL;
}

// Note: Sampling profilers also use this function to initialize TLS for a unmanaged 
// sampling thread so that initialization can be done in advance to avoid deadlocks. 
// See ProfToEEInterfaceImpl::InitializeCurrentThread for more details.
void CExecutionEngine::SetupTLSForThread(Thread *pThread)
{
    STATIC_CONTRACT_THROWS;
    STATIC_CONTRACT_GC_NOTRIGGER;
    STATIC_CONTRACT_SO_TOLERANT;
    STATIC_CONTRACT_MODE_ANY;

#ifdef _DEBUG
    if (pThread)
        pThread->AddFiberInfo(Thread::ThreadTrackInfo_Lifetime);
#endif
#ifdef STRESS_LOG
    if (StressLog::StressLogOn(~0u, 0))
    {
        StressLog::CreateThreadStressLog();
    }
#endif
    void **pTlsData;
    pTlsData = CheckThreadState(0);

    PREFIX_ASSUME(pTlsData != NULL);

#ifdef ENABLE_CONTRACTS
    // Profilers need the side effect of GetClrDebugState() to perform initialization
    // in advance to avoid deadlocks. Refer to ProfToEEInterfaceImpl::InitializeCurrentThread
    ClrDebugState *pDebugState = ::GetClrDebugState();

    if (pThread)
        pThread->m_pClrDebugState = pDebugState; 
#endif
}

void CExecutionEngine::SwitchIn()
{
    // No real contracts here.  This function is called by Thread::SwitchIn.
    STATIC_CONTRACT_NOTHROW;
    STATIC_CONTRACT_GC_NOTRIGGER;
    STATIC_CONTRACT_MODE_ANY;
    STATIC_CONTRACT_ENTRY_POINT;

    // @TODO - doesn't look like we can probe here....

#ifdef HAS_FLS_SUPPORT
    if (fHasFlsSupport)
    {
        void **pTlsData = (void **)pFlsGetValue(FlsIndex);

        BOOL fResult = CExecutionEngine::SetTlsData(pTlsData);
        if (fResult)
        {
#ifdef STRESS_LOG
            // We are in task transition period.  We can not call into host to create stress log.
            if (ClrTlsGetValue(TlsIdx_StressLog) != NULL)
            {
                STRESS_LOG1(LF_SYNC, LL_INFO100, ThreadStressLog::TaskSwitchMsg(), ::GetCurrentThreadId());
            }
#endif
        }
        // It is OK for UnsafeTlsSetValue to fail here, since we can always go back to Fls to get value.
    }
#endif
}

void CExecutionEngine::SwitchOut()
{
    // No real contracts here.  This function is called by Thread::SwitchOut
    STATIC_CONTRACT_NOTHROW;
    STATIC_CONTRACT_GC_NOTRIGGER;
    STATIC_CONTRACT_MODE_ANY;
    STATIC_CONTRACT_ENTRY_POINT;

#ifdef HAS_FLS_SUPPORT
    // @TODO - doesn't look like we can probe here.
    if (fHasFlsSupport && pFlsGetValue != NULL  && (void **)pFlsGetValue(FlsIndex) != NULL)
    {
        // Clear out TLS unless we're in the process of ThreadDetach 
        // We establish that we're in ThreadDetach because fHasFlsSupport will
        // be TRUE, but the FLS will not exist.
        CExecutionEngine::SetTlsData(NULL);
    }
#endif // HAS_FLS_SUPPORT
}

static void ThreadDetachingHelper(PTLS_CALLBACK_FUNCTION callback, void* pData)
{
    // Do not use contract.  We are freeing TLS blocks.
    STATIC_CONTRACT_NOTHROW;
    STATIC_CONTRACT_GC_NOTRIGGER;
    STATIC_CONTRACT_MODE_ANY;

        callback(pData);
    }

// Called here from a thread detach or from destruction of a Thread object.  In
// the detach case, we get our info from TLS.  In the destruct case, it comes from
// the object we are destructing.
void CExecutionEngine::ThreadDetaching(void ** pTlsData)
{
    // Can not cause memory allocation during thread detach, so no real contracts.
    STATIC_CONTRACT_NOTHROW;
    STATIC_CONTRACT_GC_NOTRIGGER;
    STATIC_CONTRACT_MODE_ANY;

    // This function may be called twice:
    // 1. When a physical thread dies, our DLL_THREAD_DETACH calls this function with pTlsData = NULL
    // 2. When a fiber is destroyed, or OS calls FlsCallback after DLL_THREAD_DETACH process.
    // We will null the FLS and TLS entry if it matches the deleted one.

    if (pTlsData)
    {
        DeleteTLS (pTlsData);
    }
}

void CExecutionEngine::DeleteTLS(void ** pTlsData)
{
    // Can not cause memory allocation during thread detach, so no real contracts.
    STATIC_CONTRACT_NOTHROW;
    STATIC_CONTRACT_GC_NOTRIGGER;
    STATIC_CONTRACT_MODE_ANY;

    if (CExecutionEngine::GetTlsData() == NULL)
    {
        // We have not allocated TlsData yet.
        return;
    }

    PREFIX_ASSUME(pTlsData != NULL);

    ClrTlsInfo *pTlsInfo = DataToClrTlsInfo(pTlsData);
    BOOL fNeed;
    do
    {
        fNeed = FALSE;
        for (int i=0; i<MAX_PREDEFINED_TLS_SLOT; i++)
        {
            if (i == TlsIdx_ClrDebugState ||
                i == TlsIdx_StressLog)
            {
                // StressLog and DebugState may be needed during callback.
                continue;
            }
            // If we have some data and a callback, issue it.
            if (Callbacks[i] != 0 && pTlsInfo->data[i] != 0)
            {
                void* pData = pTlsInfo->data[i];
                pTlsInfo->data[i] = 0;
                ThreadDetachingHelper(Callbacks[i], pData);
                fNeed = TRUE;
            }
        }
    } while (fNeed);

    if (pTlsInfo->data[TlsIdx_StressLog] != 0)
    {
#ifdef STRESS_LOG
        StressLog::ThreadDetach((ThreadStressLog *)pTlsInfo->data[TlsIdx_StressLog]);
#else
        _ASSERTE (!"should not have StressLog");
#endif
    }

    if (Callbacks[TlsIdx_ClrDebugState] != 0 && pTlsInfo->data[TlsIdx_ClrDebugState] != 0)
    {
        void* pData = pTlsInfo->data[TlsIdx_ClrDebugState];
        pTlsInfo->data[TlsIdx_ClrDebugState] = 0;
        ThreadDetachingHelper(Callbacks[TlsIdx_ClrDebugState], pData);
    }

#ifdef _DEBUG
    Thread *pThread = GetThread();
    if (pThread)
    {
        pThread->AddFiberInfo(Thread::ThreadTrackInfo_Lifetime);
    }
#endif

    // NULL TLS and FLS entry so that we don't double free.
    // We may get two callback here on thread death
    // 1. From EEDllMain
    // 2. From OS callback on FLS destruction
    if (CExecutionEngine::GetTlsData() == pTlsData)
    {
        CExecutionEngine::SetTlsData(0);
    }

#ifdef HAS_FLS_SUPPORT
    if (fHasFlsSupport && pFlsGetValue(FlsIndex) == pTlsData)
    {
        pFlsSetValue(FlsIndex, NULL);
    }
#endif

#undef HeapFree
#undef GetProcessHeap
    ::HeapFree (GetProcessHeap(),0,pTlsInfo);
#define HeapFree(hHeap, dwFlags, lpMem) Dont_Use_HeapFree(hHeap, dwFlags, lpMem)
#define GetProcessHeap() Dont_Use_GetProcessHeap()

}

#ifdef ENABLE_CONTRACTS_IMPL
// Fls callback to deallocate ClrDebugState when our FLS block goes away.
void FreeClrDebugState(LPVOID pTlsData);
#endif

VOID STDMETHODCALLTYPE CExecutionEngine::TLS_AssociateCallback(DWORD slot, PTLS_CALLBACK_FUNCTION callback)
{
    WRAPPER_NO_CONTRACT;
    STATIC_CONTRACT_SO_TOLERANT;

    CheckThreadState(slot);

    // They can toggle between a callback and no callback.  But anything else looks like
    // confusion on their part.
    //
    // (TlsIdx_ClrDebugState associates its callback from utilcode.lib - which can be replicated. But
    // all the callbacks are equally good.)
    _ASSERTE(slot == TlsIdx_ClrDebugState || Callbacks[slot] == 0 || Callbacks[slot] == callback || callback == 0);
    if (slot == TlsIdx_ClrDebugState)
    {
#ifdef ENABLE_CONTRACTS_IMPL
        // ClrDebugState is shared among many dlls.  Some dll, like perfcounter.dll, may be unloaded.
        // We force the callback function to be in mscorwks.dll.
        Callbacks[slot] = FreeClrDebugState;
#else
        _ASSERTE (!"should not get here");
#endif
    }
    else
        Callbacks[slot] = callback;
}

LPVOID* STDMETHODCALLTYPE CExecutionEngine::TLS_GetDataBlock()
{
    STATIC_CONTRACT_GC_NOTRIGGER;
    STATIC_CONTRACT_THROWS;
    STATIC_CONTRACT_MODE_ANY;
    STATIC_CONTRACT_CANNOT_TAKE_LOCK;
    STATIC_CONTRACT_SO_TOLERANT;

    return CExecutionEngine::GetTlsData();
}

LPVOID STDMETHODCALLTYPE CExecutionEngine::TLS_GetValue(DWORD slot)
{
    WRAPPER_NO_CONTRACT;
    STATIC_CONTRACT_SO_TOLERANT;
    return EETlsGetValue(slot);
}

BOOL STDMETHODCALLTYPE CExecutionEngine::TLS_CheckValue(DWORD slot, LPVOID * pValue)
{
    WRAPPER_NO_CONTRACT;
    STATIC_CONTRACT_SO_TOLERANT;
    return EETlsCheckValue(slot, pValue);
}

VOID STDMETHODCALLTYPE CExecutionEngine::TLS_SetValue(DWORD slot, LPVOID pData)
{
    WRAPPER_NO_CONTRACT;
    STATIC_CONTRACT_SO_TOLERANT;
    EETlsSetValue(slot,pData);
}


VOID STDMETHODCALLTYPE CExecutionEngine::TLS_ThreadDetaching()
{
    WRAPPER_NO_CONTRACT;
    STATIC_CONTRACT_SO_TOLERANT;
    CExecutionEngine::ThreadDetaching(NULL);
}


CRITSEC_COOKIE STDMETHODCALLTYPE CExecutionEngine::CreateLock(LPCSTR szTag, LPCSTR level, CrstFlags flags)
{
    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
        MODE_ANY;
        ENTRY_POINT;
    }
    CONTRACTL_END;

    CRITSEC_COOKIE cookie = NULL;
    BEGIN_ENTRYPOINT_VOIDRET;
    cookie = ::EECreateCriticalSection(*(CrstType*)&level, flags);
    END_ENTRYPOINT_VOIDRET;
    return cookie;
}

void STDMETHODCALLTYPE CExecutionEngine::DestroyLock(CRITSEC_COOKIE cookie)
{
    WRAPPER_NO_CONTRACT;
    STATIC_CONTRACT_SO_TOLERANT;
    ::EEDeleteCriticalSection(cookie);
}

void STDMETHODCALLTYPE CExecutionEngine::AcquireLock(CRITSEC_COOKIE cookie)
{
    WRAPPER_NO_CONTRACT;
    STATIC_CONTRACT_SO_TOLERANT;
    BEGIN_SO_INTOLERANT_CODE(GetThread());
    ::EEEnterCriticalSection(cookie);
    END_SO_INTOLERANT_CODE;
}

void STDMETHODCALLTYPE CExecutionEngine::ReleaseLock(CRITSEC_COOKIE cookie)
{
    WRAPPER_NO_CONTRACT;
    STATIC_CONTRACT_SO_TOLERANT;
    BEGIN_SO_INTOLERANT_CODE(GetThread());
    ::EELeaveCriticalSection(cookie);
    END_SO_INTOLERANT_CODE;
}

// Locking routines supplied by the EE to the other DLLs of the CLR.  In a _DEBUG
// build of the EE, we poison the Crst as a poor man's attempt to do some argument
// validation.
#define POISON_BITS 3

static inline EVENT_COOKIE CLREventToCookie(CLREvent * pEvent)
{
    LIMITED_METHOD_CONTRACT;
    _ASSERTE((((uintptr_t) pEvent) & POISON_BITS) == 0);
#ifdef _DEBUG
    pEvent = (CLREvent *) (((uintptr_t) pEvent) | POISON_BITS);
#endif
    return (EVENT_COOKIE) pEvent;
}

static inline CLREvent *CookieToCLREvent(EVENT_COOKIE cookie)
{
    LIMITED_METHOD_CONTRACT;

    _ASSERTE((((uintptr_t) cookie) & POISON_BITS) == POISON_BITS);
#ifdef _DEBUG
    if (cookie)
    {
    cookie = (EVENT_COOKIE) (((uintptr_t) cookie) & ~POISON_BITS);
    }
#endif
    return (CLREvent *) cookie;
}


EVENT_COOKIE STDMETHODCALLTYPE CExecutionEngine::CreateAutoEvent(BOOL bInitialState)
{
    CONTRACTL
    {
        THROWS;
        MODE_ANY;
        GC_NOTRIGGER;
        ENTRY_POINT;
    }
    CONTRACTL_END;

    EVENT_COOKIE event = NULL;
    BEGIN_ENTRYPOINT_THROWS;
    NewHolder<CLREvent> pEvent(new CLREvent());
    pEvent->CreateAutoEvent(bInitialState);
    event = CLREventToCookie(pEvent);
    pEvent.SuppressRelease();
    END_ENTRYPOINT_THROWS;

    return event;
}

EVENT_COOKIE STDMETHODCALLTYPE CExecutionEngine::CreateManualEvent(BOOL bInitialState)
{
    CONTRACTL
    {
        THROWS;
        MODE_ANY;
        GC_NOTRIGGER;
        ENTRY_POINT;
    }
    CONTRACTL_END;

    EVENT_COOKIE event = NULL;
    BEGIN_ENTRYPOINT_THROWS;

    NewHolder<CLREvent> pEvent(new CLREvent());
    pEvent->CreateManualEvent(bInitialState);
    event = CLREventToCookie(pEvent);
    pEvent.SuppressRelease();

    END_ENTRYPOINT_THROWS;

    return event;
}

void STDMETHODCALLTYPE CExecutionEngine::CloseEvent(EVENT_COOKIE event)
{
    WRAPPER_NO_CONTRACT;
    STATIC_CONTRACT_SO_TOLERANT;
    if (event) {
        CLREvent *pEvent = CookieToCLREvent(event);
        pEvent->CloseEvent();
        delete pEvent;
    }
}

BOOL STDMETHODCALLTYPE CExecutionEngine::ClrSetEvent(EVENT_COOKIE event)
{
    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
        SO_TOLERANT;
        MODE_ANY;
    }
    CONTRACTL_END;
    if (event) {
        CLREvent *pEvent = CookieToCLREvent(event);
        return pEvent->Set();
    }
    return FALSE;
}

BOOL STDMETHODCALLTYPE CExecutionEngine::ClrResetEvent(EVENT_COOKIE event)
{
    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
        SO_TOLERANT;
        MODE_ANY;
    }
    CONTRACTL_END;
    if (event) {
        CLREvent *pEvent = CookieToCLREvent(event);
        return pEvent->Reset();
    }
    return FALSE;
}

DWORD STDMETHODCALLTYPE CExecutionEngine::WaitForEvent(EVENT_COOKIE event,
                                                       DWORD dwMilliseconds,
                                                       BOOL bAlertable)
{
    WRAPPER_NO_CONTRACT;
    STATIC_CONTRACT_SO_TOLERANT;
    if (event) {
        CLREvent *pEvent = CookieToCLREvent(event);
        return pEvent->Wait(dwMilliseconds,bAlertable);
    }

    if (GetThread() && bAlertable)
        ThrowHR(E_INVALIDARG);
    return WAIT_FAILED;
}

DWORD STDMETHODCALLTYPE CExecutionEngine::WaitForSingleObject(HANDLE handle,
                                                              DWORD dwMilliseconds)
{
    STATIC_CONTRACT_WRAPPER;
    STATIC_CONTRACT_SO_TOLERANT;
    return ::WaitForSingleObject(handle,dwMilliseconds);
}

static inline SEMAPHORE_COOKIE CLRSemaphoreToCookie(CLRSemaphore * pSemaphore)
{
    LIMITED_METHOD_CONTRACT;
    STATIC_CONTRACT_SO_TOLERANT;

    _ASSERTE((((uintptr_t) pSemaphore) & POISON_BITS) == 0);
#ifdef _DEBUG
    pSemaphore = (CLRSemaphore *) (((uintptr_t) pSemaphore) | POISON_BITS);
#endif
    return (SEMAPHORE_COOKIE) pSemaphore;
}

static inline CLRSemaphore *CookieToCLRSemaphore(SEMAPHORE_COOKIE cookie)
{
    LIMITED_METHOD_CONTRACT;
    _ASSERTE((((uintptr_t) cookie) & POISON_BITS) == POISON_BITS);
#ifdef _DEBUG
    if (cookie)
    {
    cookie = (SEMAPHORE_COOKIE) (((uintptr_t) cookie) & ~POISON_BITS);
    }
#endif
    return (CLRSemaphore *) cookie;
}


SEMAPHORE_COOKIE STDMETHODCALLTYPE CExecutionEngine::ClrCreateSemaphore(DWORD dwInitial,
                                                                        DWORD dwMax)
{
    CONTRACTL
    {
        THROWS;
        MODE_ANY;
        GC_NOTRIGGER;
        SO_TOLERANT;
    }
    CONTRACTL_END;

    NewHolder<CLRSemaphore> pSemaphore(new CLRSemaphore());
    pSemaphore->Create(dwInitial, dwMax);
    SEMAPHORE_COOKIE ret = CLRSemaphoreToCookie(pSemaphore);;
    pSemaphore.SuppressRelease();
    return ret;
}

void STDMETHODCALLTYPE CExecutionEngine::ClrCloseSemaphore(SEMAPHORE_COOKIE semaphore)
{
    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
        SO_TOLERANT;
        MODE_ANY;
    }
    CONTRACTL_END;
    CLRSemaphore *pSemaphore = CookieToCLRSemaphore(semaphore);
    pSemaphore->Close();
    delete pSemaphore;
}

BOOL STDMETHODCALLTYPE CExecutionEngine::ClrReleaseSemaphore(SEMAPHORE_COOKIE semaphore,
                                                             LONG lReleaseCount,
                                                             LONG *lpPreviousCount)
{
    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
        SO_TOLERANT;
        MODE_ANY;
    }
    CONTRACTL_END;
    CLRSemaphore *pSemaphore = CookieToCLRSemaphore(semaphore);
    return pSemaphore->Release(lReleaseCount,lpPreviousCount);
}

DWORD STDMETHODCALLTYPE CExecutionEngine::ClrWaitForSemaphore(SEMAPHORE_COOKIE semaphore,
                                                              DWORD dwMilliseconds,
                                                              BOOL bAlertable)
{
    WRAPPER_NO_CONTRACT;
    STATIC_CONTRACT_SO_TOLERANT;
    CLRSemaphore *pSemaphore = CookieToCLRSemaphore(semaphore);
    return pSemaphore->Wait(dwMilliseconds,bAlertable);
}

static inline MUTEX_COOKIE CLRMutexToCookie(CLRMutex * pMutex)
{
    LIMITED_METHOD_CONTRACT;
    _ASSERTE((((uintptr_t) pMutex) & POISON_BITS) == 0);
#ifdef _DEBUG
    pMutex = (CLRMutex *) (((uintptr_t) pMutex) | POISON_BITS);
#endif
    return (MUTEX_COOKIE) pMutex;
}

static inline CLRMutex *CookieToCLRMutex(MUTEX_COOKIE cookie)
{
    LIMITED_METHOD_CONTRACT;
    _ASSERTE((((uintptr_t) cookie) & POISON_BITS) == POISON_BITS);
#ifdef _DEBUG
    if (cookie)
    {
    cookie = (MUTEX_COOKIE) (((uintptr_t) cookie) & ~POISON_BITS);
    }
#endif
    return (CLRMutex *) cookie;
}


MUTEX_COOKIE STDMETHODCALLTYPE CExecutionEngine::ClrCreateMutex(LPSECURITY_ATTRIBUTES lpMutexAttributes,
                                                                BOOL bInitialOwner,
                                                                LPCTSTR lpName)
{
    CONTRACTL
    {
        NOTHROW;
        MODE_ANY;
        GC_NOTRIGGER;
        SO_TOLERANT;    // we catch any erros and free the allocated memory
    }
    CONTRACTL_END;


    MUTEX_COOKIE mutex = 0;
    CLRMutex *pMutex = new (nothrow) CLRMutex();
    if (pMutex)
    {
        EX_TRY
        {
            pMutex->Create(lpMutexAttributes, bInitialOwner, lpName);
            mutex = CLRMutexToCookie(pMutex);
        }
        EX_CATCH
        {
            delete pMutex;
        }
        EX_END_CATCH(SwallowAllExceptions);
    }
    return mutex;
}

void STDMETHODCALLTYPE CExecutionEngine::ClrCloseMutex(MUTEX_COOKIE mutex)
{
    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
        SO_TOLERANT;
        MODE_ANY;
    }
    CONTRACTL_END;
    CLRMutex *pMutex = CookieToCLRMutex(mutex);
    pMutex->Close();
    delete pMutex;
}

BOOL STDMETHODCALLTYPE CExecutionEngine::ClrReleaseMutex(MUTEX_COOKIE mutex)
{
    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
        SO_TOLERANT;
        MODE_ANY;
    }
    CONTRACTL_END;
    CLRMutex *pMutex = CookieToCLRMutex(mutex);
    return pMutex->Release();
}

DWORD STDMETHODCALLTYPE CExecutionEngine::ClrWaitForMutex(MUTEX_COOKIE mutex,
                                                          DWORD dwMilliseconds,
                                                          BOOL bAlertable)
{
    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
        SO_INTOLERANT;
        MODE_ANY;
    }
    CONTRACTL_END;
    CLRMutex *pMutex = CookieToCLRMutex(mutex);
    return pMutex->Wait(dwMilliseconds,bAlertable);
}

#undef ClrSleepEx
DWORD STDMETHODCALLTYPE CExecutionEngine::ClrSleepEx(DWORD dwMilliseconds, BOOL bAlertable)
{
    WRAPPER_NO_CONTRACT;
    STATIC_CONTRACT_SO_TOLERANT;

    return EESleepEx(dwMilliseconds,bAlertable);
}
#define ClrSleepEx EESleepEx

#undef ClrAllocationDisallowed
BOOL STDMETHODCALLTYPE CExecutionEngine::ClrAllocationDisallowed()
{
    WRAPPER_NO_CONTRACT;
    STATIC_CONTRACT_SO_TOLERANT;
    return EEAllocationDisallowed();
}
#define ClrAllocationDisallowed EEAllocationDisallowed

#undef ClrVirtualAlloc
LPVOID STDMETHODCALLTYPE CExecutionEngine::ClrVirtualAlloc(LPVOID lpAddress,
                                                           SIZE_T dwSize,
                                                           DWORD flAllocationType,
                                                           DWORD flProtect)
{
    WRAPPER_NO_CONTRACT;
    STATIC_CONTRACT_SO_TOLERANT;
    return EEVirtualAlloc(lpAddress, dwSize, flAllocationType, flProtect);
}
#define ClrVirtualAlloc EEVirtualAlloc

#undef ClrVirtualFree
BOOL STDMETHODCALLTYPE CExecutionEngine::ClrVirtualFree(LPVOID lpAddress,
                                                        SIZE_T dwSize,
                                                        DWORD dwFreeType)
{
    WRAPPER_NO_CONTRACT;
    STATIC_CONTRACT_SO_TOLERANT;
    return EEVirtualFree(lpAddress, dwSize, dwFreeType);
}
#define ClrVirtualFree EEVirtualFree

#undef ClrVirtualQuery
SIZE_T STDMETHODCALLTYPE CExecutionEngine::ClrVirtualQuery(LPCVOID lpAddress,
                                                           PMEMORY_BASIC_INFORMATION lpBuffer,
                                                           SIZE_T dwLength)
{
    WRAPPER_NO_CONTRACT;
    STATIC_CONTRACT_SO_TOLERANT;
    return EEVirtualQuery(lpAddress, lpBuffer, dwLength);
}
#define ClrVirtualQuery EEVirtualQuery

#if defined(_DEBUG) && !defined(FEATURE_PAL)
static VolatilePtr<BYTE> s_pStartOfUEFSection = NULL;
static VolatilePtr<BYTE> s_pEndOfUEFSectionBoundary = NULL;
static Volatile<DWORD> s_dwProtection = 0;
#endif // _DEBUG && !FEATURE_PAL

#undef ClrVirtualProtect

BOOL STDMETHODCALLTYPE CExecutionEngine::ClrVirtualProtect(LPVOID lpAddress,
                                                           SIZE_T dwSize,
                                                           DWORD flNewProtect,
                                                           PDWORD lpflOldProtect)
{
    WRAPPER_NO_CONTRACT;
    STATIC_CONTRACT_SO_TOLERANT;

   // Get the UEF installation details - we will use these to validate
   // that the calls to ClrVirtualProtect are not going to affect the UEF.
   // 
   // The OS UEF invocation mechanism was updated. When a UEF is setup,the OS captures 
   // the following details about it:
   //  1) Protection of the pages in which the UEF lives
   //  2) The size of the region in which the UEF lives
   //  3) The region's Allocation Base
   //
   //  The OS verifies details surrounding the UEF before invocation.  For security reasons 
   //  the page protection cannot change between SetUnhandledExceptionFilter and invocation.
   //
   // Prior to this change, the UEF lived in a common section of code_Seg, along with
   // JIT_PatchedCode. Thus, their pages have the same protection, they live
   //  in the same region (and thus, its size is the same).
   //
   // In EEStartupHelper, when we setup the UEF and then invoke InitJitHelpers1 and InitJitHelpers2, 
   // they perform some optimizations that result in the memory page protection being changed. When
   // the UEF is to be invoked, the OS does the check on the UEF's cached details against the current
   // memory pages. This check used to fail when on 64bit retail builds when JIT_PatchedCode was
   // aligned after the UEF with a different memory page protection (post the optimizations by InitJitHelpers). 
   // Thus, the UEF was never invoked.
   //
   // To circumvent this, we put the UEF in its own section in the code segment so that any modifications
   // to memory pages will not affect the UEF details that the OS cached. This is done in Excep.cpp
   // using the "#pragma code_seg" directives.
   //
   // Below, we double check that:
   // 
   // 1) the address being protected does not lie in the region of of the UEF. 
   // 2) the section after UEF is not having the same memory protection as UEF section.
   //
   // We assert if either of the two conditions above are true.

#if defined(_DEBUG) && !defined(FEATURE_PAL)
   // We do this check in debug/checked builds only

    // Do we have the UEF details?
    if (s_pEndOfUEFSectionBoundary.Load() == NULL)
    {
        // Get reference to MSCORWKS image in memory...
        PEDecoder pe(g_pMSCorEE);

        // Find the UEF section from the image
        IMAGE_SECTION_HEADER* pUEFSection = pe.FindSection(CLR_UEF_SECTION_NAME);
        _ASSERTE(pUEFSection != NULL);
        if (pUEFSection)
        {
            // We got our section - get the start of the section
            BYTE* pStartOfUEFSection = static_cast<BYTE*>(pe.GetBase())+pUEFSection->VirtualAddress;
            s_pStartOfUEFSection = pStartOfUEFSection;

            // Now we need the protection attributes for the memory region in which the
            // UEF section is...
            MEMORY_BASIC_INFORMATION uefInfo;
            if (ClrVirtualQuery(pStartOfUEFSection, &uefInfo, sizeof(uefInfo)) != 0)
            {
                // Calculate how many pages does the UEF section take to get to the start of the
                // next section. We dont calculate this as
                //
                // pStartOfUEFSection + uefInfo.RegionSize
                //
                // because the section following UEF will also be included in the region size
                // if it has the same protection as the UEF section.
                DWORD dwUEFSectionPageCount = ((pUEFSection->Misc.VirtualSize + OS_PAGE_SIZE - 1)/OS_PAGE_SIZE);

                BYTE* pAddressOfFollowingSection = pStartOfUEFSection + (OS_PAGE_SIZE * dwUEFSectionPageCount);
                
                // Ensure that the section following us is having different memory protection
                MEMORY_BASIC_INFORMATION nextSectionInfo;
                _ASSERTE(ClrVirtualQuery(pAddressOfFollowingSection, &nextSectionInfo, sizeof(nextSectionInfo)) != 0);
                _ASSERTE(nextSectionInfo.Protect != uefInfo.Protect);
                
                // save the memory protection details
                s_dwProtection = uefInfo.Protect;

                // Get the end of the UEF section
                BYTE* pEndOfUEFSectionBoundary = pAddressOfFollowingSection - 1;
                
                // Set the end of UEF section boundary
                FastInterlockExchangePointer(s_pEndOfUEFSectionBoundary.GetPointer(), pEndOfUEFSectionBoundary);
            }
            else
            {
                _ASSERTE(!"Unable to get UEF Details!");
            }
        }
    }

    if (s_pEndOfUEFSectionBoundary.Load() != NULL)
    {
        // Is the protection being changed?
        if (flNewProtect != s_dwProtection)
        {
            // Is the target address NOT affecting the UEF ? Possible cases:
            // 1) Starts and ends before the UEF start
            // 2) Starts after the UEF start

            void* pEndOfRangeAddr = static_cast<BYTE*>(lpAddress)+dwSize-1;

            _ASSERTE_MSG(((pEndOfRangeAddr < s_pStartOfUEFSection.Load()) || (lpAddress > s_pEndOfUEFSectionBoundary.Load())), 
                "Do not virtual protect the section in which UEF lives!");
        }
    }
#endif // _DEBUG && !FEATURE_PAL

    return EEVirtualProtect(lpAddress, dwSize, flNewProtect, lpflOldProtect);
}
#define ClrVirtualProtect EEVirtualProtect

#undef ClrGetProcessHeap
HANDLE STDMETHODCALLTYPE CExecutionEngine::ClrGetProcessHeap()
{
    WRAPPER_NO_CONTRACT;
    STATIC_CONTRACT_SO_TOLERANT;
    return EEGetProcessHeap();
}
#define ClrGetProcessHeap EEGetProcessHeap

#undef ClrGetProcessExecutableHeap
HANDLE STDMETHODCALLTYPE CExecutionEngine::ClrGetProcessExecutableHeap()
{
    WRAPPER_NO_CONTRACT;
    STATIC_CONTRACT_SO_TOLERANT;
    return EEGetProcessExecutableHeap();
}
#define ClrGetProcessExecutableHeap EEGetProcessExecutableHeap


#undef ClrHeapCreate
HANDLE STDMETHODCALLTYPE CExecutionEngine::ClrHeapCreate(DWORD flOptions,
                                                         SIZE_T dwInitialSize,
                                                         SIZE_T dwMaximumSize)
{
    WRAPPER_NO_CONTRACT;
    STATIC_CONTRACT_SO_TOLERANT;
    return EEHeapCreate(flOptions, dwInitialSize, dwMaximumSize);
}
#define ClrHeapCreate EEHeapCreate

#undef ClrHeapDestroy
BOOL STDMETHODCALLTYPE CExecutionEngine::ClrHeapDestroy(HANDLE hHeap)
{
    WRAPPER_NO_CONTRACT;
    STATIC_CONTRACT_SO_TOLERANT;
    return EEHeapDestroy(hHeap);
}
#define ClrHeapDestroy EEHeapDestroy

#undef ClrHeapAlloc
LPVOID STDMETHODCALLTYPE CExecutionEngine::ClrHeapAlloc(HANDLE hHeap,
                                                        DWORD dwFlags,
                                                        SIZE_T dwBytes)
{
    WRAPPER_NO_CONTRACT;
    STATIC_CONTRACT_SO_TOLERANT;

    // We need to guarentee a very small stack consumption in allocating.  And we can't allow
    // an SO to happen while calling into the host.  This will force a hard SO which is OK because
    // we shouldn't ever get this close inside the EE in SO-intolerant code, so this should
    // only fail if we call directly in from outside the EE, such as the JIT.
    MINIMAL_STACK_PROBE_CHECK_THREAD(GetThread());

    return EEHeapAlloc(hHeap, dwFlags, dwBytes);
}
#define ClrHeapAlloc EEHeapAlloc

#undef ClrHeapFree
BOOL STDMETHODCALLTYPE CExecutionEngine::ClrHeapFree(HANDLE hHeap,
                                                     DWORD dwFlags,
                                                     LPVOID lpMem)
{
    WRAPPER_NO_CONTRACT;
    STATIC_CONTRACT_SO_TOLERANT;
    return EEHeapFree(hHeap, dwFlags, lpMem);
}
#define ClrHeapFree EEHeapFree

#undef ClrHeapValidate
BOOL STDMETHODCALLTYPE CExecutionEngine::ClrHeapValidate(HANDLE hHeap,
                                                         DWORD dwFlags,
                                                         LPCVOID lpMem)
{
    WRAPPER_NO_CONTRACT;
    STATIC_CONTRACT_SO_TOLERANT;
    return EEHeapValidate(hHeap, dwFlags, lpMem);
}
#define ClrHeapValidate EEHeapValidate

//------------------------------------------------------------------------------
// Helper function to get an exception object from outside the exception.  In
//  the CLR, it may be from the Thread object.  Non-CLR users have no thread object,
//  and it will do nothing.

void CExecutionEngine::GetLastThrownObjectExceptionFromThread(void **ppvException)
{
    WRAPPER_NO_CONTRACT;
    STATIC_CONTRACT_SO_TOLERANT;

    // Cast to our real type.
    Exception **ppException = reinterpret_cast<Exception**>(ppvException);

    // Try to get a better message.
    GetLastThrownObjectExceptionFromThread_Internal(ppException);

} // HRESULT CExecutionEngine::GetLastThrownObjectExceptionFromThread()


LocaleID RuntimeGetFileSystemLocale()
{
    return PEImage::GetFileSystemLocale();
};

HRESULT CorHost2::DllGetActivationFactory(DWORD appDomainID, LPCWSTR wszTypeName, IActivationFactory ** factory)
{
#ifdef FEATURE_COMINTEROP_WINRT_MANAGED_ACTIVATION
    // WinRT activation currently supported in default domain only
    if (appDomainID != DefaultADID)
        return HOST_E_INVALIDOPERATION;

    HRESULT hr = S_OK;

    Thread *pThread = GetThread();
    if (pThread == NULL)
    {
        pThread = SetupThreadNoThrow(&hr);
        if (pThread == NULL)
        {
            return hr;
        }
    }

    if(SystemDomain::GetCurrentDomain()->GetId().m_dwId != DefaultADID)
    {
        return HOST_E_INVALIDOPERATION;
    }

    return DllGetActivationFactoryImpl(NULL, wszTypeName, NULL, factory);
#else
    return E_NOTIMPL;
#endif
}


#ifdef FEATURE_COMINTEROP_WINRT_MANAGED_ACTIVATION

HRESULT STDMETHODCALLTYPE DllGetActivationFactoryImpl(LPCWSTR wszAssemblyName, 
                                                      LPCWSTR wszTypeName, 
                                                      LPCWSTR wszCodeBase,
                                                      IActivationFactory ** factory)
{
    CONTRACTL
    {
        DISABLED(NOTHROW);
        GC_TRIGGERS;
        MODE_ANY;
        ENTRY_POINT;
    }
    CONTRACTL_END;

    HRESULT hr = S_OK;

    BEGIN_ENTRYPOINT_NOTHROW;

    AppDomain* pDomain = SystemDomain::System()->DefaultDomain();
    _ASSERTE(pDomain);

    BEGIN_EXTERNAL_ENTRYPOINT(&hr);
    {
        GCX_COOP();

        bool bIsPrimitive;
        TypeHandle typeHandle = WinRTTypeNameConverter::GetManagedTypeFromWinRTTypeName(wszTypeName, &bIsPrimitive);
        if (!bIsPrimitive && !typeHandle.IsNull() && !typeHandle.IsTypeDesc() && typeHandle.AsMethodTable()->IsExportedToWinRT())
        {
            struct _gc {
                OBJECTREF type;
            } gc;
            memset(&gc, 0, sizeof(gc));


            IActivationFactory* activationFactory;
            GCPROTECT_BEGIN(gc);

            gc.type = typeHandle.GetManagedClassObject();

            MethodDescCallSite mdcs(METHOD__WINDOWSRUNTIMEMARSHAL__GET_ACTIVATION_FACTORY_FOR_TYPE);
            ARG_SLOT args[1] = {
                ObjToArgSlot(gc.type)
            };
            activationFactory = (IActivationFactory*)mdcs.Call_RetLPVOID(args);

            *factory = activationFactory;

            GCPROTECT_END();
        }
        else
        {
            hr = COR_E_TYPELOAD;
        }
    }
    END_EXTERNAL_ENTRYPOINT;
    END_ENTRYPOINT_NOTHROW;

    return hr;
}

#endif // !FEATURE_COMINTEROP_MANAGED_ACTIVATION




#endif // !DACCESS_COMPILE