summaryrefslogtreecommitdiff
path: root/src/vm/appdomain.hpp
blob: 898e50f1c24dcda8750b5e4e399eaa50413a99b2 (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
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
// 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.

/*============================================================
**
** Header:  AppDomain.cpp
** 

**
** Purpose: Implements AppDomain (loader domain) architecture
**
**
===========================================================*/
#ifndef _APPDOMAIN_H
#define _APPDOMAIN_H

#include "eventtrace.h"
#include "assembly.hpp"
#include "clsload.hpp"
#include "eehash.h"
#include "arraylist.h"
#include "comreflectioncache.hpp"
#include "comutilnative.h"
#include "domainfile.h"
#include "objectlist.h"
#include "fptrstubs.h"
#include "ilstubcache.h"
#include "testhookmgr.h"
#include "gcheaputilities.h"
#include "gchandletableutilities.h"
#include "../binder/inc/applicationcontext.hpp"
#include "rejit.h"

#ifdef FEATURE_MULTICOREJIT
#include "multicorejit.h"
#endif

#ifdef FEATURE_COMINTEROP
#include "clrprivbinderwinrt.h"
#include "..\md\winmd\inc\adapter.h"
#include "winrttypenameconverter.h"
#endif // FEATURE_COMINTEROP

#include "appxutil.h"

#ifdef FEATURE_TIERED_COMPILATION
#include "tieredcompilation.h"
#include "callcounter.h"
#endif

class BaseDomain;
class SystemDomain;
class SharedDomain;
class AppDomain;
class CompilationDomain;
class AppDomainEnum;
class AssemblySink;
class EEMarshalingData;
class Context;
class GlobalStringLiteralMap;
class StringLiteralMap;
struct SecurityContext;
class MngStdInterfacesInfo;
class DomainModule;
class DomainAssembly;
struct InteropMethodTableData;
class LoadLevelLimiter;
class UMEntryThunkCache;
class TypeEquivalenceHashTable;
class IApplicationSecurityDescriptor;
class StringArrayList;

typedef VPTR(IApplicationSecurityDescriptor) PTR_IApplicationSecurityDescriptor;

extern INT64 g_PauseTime;  // Total time in millisecond the CLR has been paused

#ifdef FEATURE_COMINTEROP
class ComCallWrapperCache;
struct SimpleComCallWrapper;

class RCWRefCache;

// This enum is used to specify whether user want COM or remoting
enum COMorRemotingFlag {
    COMorRemoting_NotInitialized = 0,
    COMorRemoting_COM            = 1, // COM will be used both cross-domain and cross-runtime
    COMorRemoting_Remoting       = 2, // Remoting will be used cross-domain; cross-runtime will use Remoting only if it looks like it's expected (default)
    COMorRemoting_LegacyMode     = 3  // Remoting will be used both cross-domain and cross-runtime
};

#endif // FEATURE_COMINTEROP

#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable : 4200) // Disable zero-sized array warning
#endif


GPTR_DECL(IdDispenser,       g_pModuleIndexDispenser);

// This enum is aligned to System.ExceptionCatcherType. 
enum ExceptionCatcher {
    ExceptionCatcher_ManagedCode = 0,
    ExceptionCatcher_AppDomainTransition = 1,
    ExceptionCatcher_COMInterop = 2,    
};

// We would like *ALLOCATECLASS_FLAG to AV (in order to catch errors), so don't change it
struct ClassInitFlags {
    enum
    {
        INITIALIZED_FLAG_BIT    = 0,
        INITIALIZED_FLAG        = 1<<INITIALIZED_FLAG_BIT,
        ERROR_FLAG_BIT          = 1,
        ERROR_FLAG              = 1<<ERROR_FLAG_BIT,
        ALLOCATECLASS_FLAG_BIT  = 2,                    // Bit to avoid racing for InstantiateStaticHandles
        ALLOCATECLASS_FLAG      = 1<<ALLOCATECLASS_FLAG_BIT,
        COLLECTIBLE_FLAG_BIT    = 3,
        COLLECTIBLE_FLAG        = 1<<COLLECTIBLE_FLAG_BIT
    };
};

struct DomainLocalModule
{
    friend class ClrDataAccess;
    friend class CheckAsmOffsets;
    friend struct ThreadLocalModule;

// After these macros complete, they may have returned an interior pointer into a gc object. This pointer will have been cast to a byte pointer
// It is critically important that no GC is allowed to occur before this pointer is used.
#define GET_DYNAMICENTRY_GCSTATICS_BASEPOINTER(pLoaderAllocator, dynamicClassInfoParam, pGCStatics) \
    {\
        DomainLocalModule::PTR_DynamicClassInfo dynamicClassInfo = dac_cast<DomainLocalModule::PTR_DynamicClassInfo>(dynamicClassInfoParam);\
        DomainLocalModule::PTR_DynamicEntry pDynamicEntry = dac_cast<DomainLocalModule::PTR_DynamicEntry>((DomainLocalModule::DynamicEntry*)dynamicClassInfo->m_pDynamicEntry.Load()); \
        if ((dynamicClassInfo->m_dwFlags) & ClassInitFlags::COLLECTIBLE_FLAG) \
        {\
            PTRARRAYREF objArray;\
            objArray = (PTRARRAYREF)pLoaderAllocator->GetHandleValueFastCannotFailType2( \
                                        (dac_cast<DomainLocalModule::PTR_CollectibleDynamicEntry>(pDynamicEntry))->m_hGCStatics);\
            *(pGCStatics) = dac_cast<PTR_BYTE>(PTR_READ(PTR_TO_TADDR(OBJECTREFToObject( objArray )) + offsetof(PtrArray, m_Array), objArray->GetNumComponents() * sizeof(void*))) ;\
        }\
        else\
        {\
            *(pGCStatics) = (dac_cast<DomainLocalModule::PTR_NormalDynamicEntry>(pDynamicEntry))->GetGCStaticsBasePointer();\
        }\
    }\

#define GET_DYNAMICENTRY_NONGCSTATICS_BASEPOINTER(pLoaderAllocator, dynamicClassInfoParam, pNonGCStatics) \
    {\
        DomainLocalModule::PTR_DynamicClassInfo dynamicClassInfo = dac_cast<DomainLocalModule::PTR_DynamicClassInfo>(dynamicClassInfoParam);\
        DomainLocalModule::PTR_DynamicEntry pDynamicEntry = dac_cast<DomainLocalModule::PTR_DynamicEntry>((DomainLocalModule::DynamicEntry*)(dynamicClassInfo)->m_pDynamicEntry.Load()); \
        if (((dynamicClassInfo)->m_dwFlags) & ClassInitFlags::COLLECTIBLE_FLAG) \
        {\
            if ((dac_cast<DomainLocalModule::PTR_CollectibleDynamicEntry>(pDynamicEntry))->m_hNonGCStatics != 0) \
            { \
                U1ARRAYREF objArray;\
                objArray = (U1ARRAYREF)pLoaderAllocator->GetHandleValueFastCannotFailType2( \
                                            (dac_cast<DomainLocalModule::PTR_CollectibleDynamicEntry>(pDynamicEntry))->m_hNonGCStatics);\
                *(pNonGCStatics) = dac_cast<PTR_BYTE>(PTR_READ( \
                        PTR_TO_TADDR(OBJECTREFToObject( objArray )) + sizeof(ArrayBase) - DomainLocalModule::DynamicEntry::GetOffsetOfDataBlob(), \
                            objArray->GetNumComponents() * (DWORD)objArray->GetComponentSize() + DomainLocalModule::DynamicEntry::GetOffsetOfDataBlob())); \
            } else (*pNonGCStatics) = NULL; \
        }\
        else\
        {\
            *(pNonGCStatics) = dac_cast<DomainLocalModule::PTR_NormalDynamicEntry>(pDynamicEntry)->GetNonGCStaticsBasePointer();\
        }\
    }\

    struct DynamicEntry
    {
        static DWORD GetOffsetOfDataBlob();
    };
    typedef DPTR(DynamicEntry) PTR_DynamicEntry;

    struct CollectibleDynamicEntry : public DynamicEntry
    {
        LOADERHANDLE    m_hGCStatics;
        LOADERHANDLE    m_hNonGCStatics;
    };
    typedef DPTR(CollectibleDynamicEntry) PTR_CollectibleDynamicEntry;

    struct NormalDynamicEntry : public DynamicEntry
    {
        PTR_OBJECTREF   m_pGCStatics;
#ifdef FEATURE_64BIT_ALIGNMENT
        // Padding to make m_pDataBlob aligned at MAX_PRIMITIVE_FIELD_SIZE
        // code:MethodTableBuilder::PlaceRegularStaticFields assumes that the start of the data blob is aligned 
        SIZE_T          m_padding;
#endif
        BYTE            m_pDataBlob[0];

        inline PTR_BYTE GetGCStaticsBasePointer()
        {
            LIMITED_METHOD_CONTRACT;
            SUPPORTS_DAC;
            return dac_cast<PTR_BYTE>(m_pGCStatics);
        }
        inline PTR_BYTE GetNonGCStaticsBasePointer()
        {
            LIMITED_METHOD_CONTRACT
            SUPPORTS_DAC;
            return dac_cast<PTR_BYTE>(this);
        }
    };
    typedef DPTR(NormalDynamicEntry) PTR_NormalDynamicEntry;

    struct DynamicClassInfo
    {
        VolatilePtr<DynamicEntry, PTR_DynamicEntry>  m_pDynamicEntry;
        Volatile<DWORD>             m_dwFlags;
    };
    typedef DPTR(DynamicClassInfo) PTR_DynamicClassInfo;
    
    inline UMEntryThunk * GetADThunkTable()
    {
        LIMITED_METHOD_CONTRACT
        return m_pADThunkTable;
    }

    inline void SetADThunkTable(UMEntryThunk* pADThunkTable)
    {
        LIMITED_METHOD_CONTRACT
        InterlockedCompareExchangeT(m_pADThunkTable.GetPointer(), pADThunkTable, NULL);
    }

    // Note the difference between:
    // 
    //  GetPrecomputedNonGCStaticsBasePointer() and
    //  GetPrecomputedStaticsClassData()
    //
    //  GetPrecomputedNonGCStaticsBasePointer returns the pointer that should be added to field offsets to retrieve statics
    //  GetPrecomputedStaticsClassData returns a pointer to the first byte of the precomputed statics block
    inline TADDR GetPrecomputedNonGCStaticsBasePointer()
    {
        LIMITED_METHOD_CONTRACT
        return dac_cast<TADDR>(this);
    }

    inline PTR_BYTE GetPrecomputedStaticsClassData()
    {
        LIMITED_METHOD_CONTRACT
        return dac_cast<PTR_BYTE>(this) + offsetof(DomainLocalModule, m_pDataBlob);
    }

    static SIZE_T GetOffsetOfDataBlob() { return offsetof(DomainLocalModule, m_pDataBlob); }
    static SIZE_T GetOffsetOfGCStaticPointer() { return offsetof(DomainLocalModule, m_pGCStatics); }

    inline DomainFile* GetDomainFile()
    {
        LIMITED_METHOD_CONTRACT
        SUPPORTS_DAC;
        return m_pDomainFile;
    }

#ifndef DACCESS_COMPILE
    inline void        SetDomainFile(DomainFile* pDomainFile)
    {
        LIMITED_METHOD_CONTRACT
        m_pDomainFile = pDomainFile;
    }
#endif

    inline PTR_OBJECTREF  GetPrecomputedGCStaticsBasePointer()
    {
        LIMITED_METHOD_CONTRACT        
        return m_pGCStatics;
    }

    inline PTR_OBJECTREF * GetPrecomputedGCStaticsBasePointerAddress()
    {
        LIMITED_METHOD_CONTRACT        
        return &m_pGCStatics;
    }

    // Returns bytes so we can add offsets
    inline PTR_BYTE GetGCStaticsBasePointer(MethodTable * pMT)
    {
        WRAPPER_NO_CONTRACT
        SUPPORTS_DAC;

        if (pMT->IsDynamicStatics())
        {
            _ASSERTE(GetDomainFile()->GetModule() == pMT->GetModuleForStatics());
            return GetDynamicEntryGCStaticsBasePointer(pMT->GetModuleDynamicEntryID(), pMT->GetLoaderAllocator());
        }
        else
        {
            return dac_cast<PTR_BYTE>(m_pGCStatics);
        }
    }

    inline PTR_BYTE GetNonGCStaticsBasePointer(MethodTable * pMT)
    {
        WRAPPER_NO_CONTRACT
        SUPPORTS_DAC;

        if (pMT->IsDynamicStatics())
        {
            _ASSERTE(GetDomainFile()->GetModule() == pMT->GetModuleForStatics());
            return GetDynamicEntryNonGCStaticsBasePointer(pMT->GetModuleDynamicEntryID(), pMT->GetLoaderAllocator());
        }
        else
        {
            return dac_cast<PTR_BYTE>(this);
        }
    }

    inline DynamicClassInfo* GetDynamicClassInfo(DWORD n)
    {
        LIMITED_METHOD_CONTRACT
        SUPPORTS_DAC;
        _ASSERTE(m_pDynamicClassTable.Load() && m_aDynamicEntries > n);
        dac_cast<PTR_DynamicEntry>(m_pDynamicClassTable[n].m_pDynamicEntry.Load());

        return &m_pDynamicClassTable[n];
    }

    // These helpers can now return null, as the debugger may do queries on a type
    // before the calls to PopulateClass happen
    inline PTR_BYTE GetDynamicEntryGCStaticsBasePointer(DWORD n, PTR_LoaderAllocator pLoaderAllocator)
    {
        CONTRACTL
        {
            NOTHROW;
            GC_NOTRIGGER;
            SO_TOLERANT;
            MODE_COOPERATIVE;
            SUPPORTS_DAC;
        }
        CONTRACTL_END;


        if (n >= m_aDynamicEntries)
        {
            return NULL;
        }
        
        DynamicClassInfo* pClassInfo = GetDynamicClassInfo(n);
        if (!pClassInfo->m_pDynamicEntry)
        {
            return NULL;
        }

        PTR_BYTE retval = NULL;

        GET_DYNAMICENTRY_GCSTATICS_BASEPOINTER(pLoaderAllocator, pClassInfo, &retval);

        return retval;
    }

    inline PTR_BYTE GetDynamicEntryNonGCStaticsBasePointer(DWORD n, PTR_LoaderAllocator pLoaderAllocator)
    {
        CONTRACTL
        {
            NOTHROW;
            GC_NOTRIGGER;
            SO_TOLERANT;
            MODE_COOPERATIVE;
            SUPPORTS_DAC;
        }
        CONTRACTL_END;

        
        if (n >= m_aDynamicEntries)
        {
            return NULL;
        }
        
        DynamicClassInfo* pClassInfo = GetDynamicClassInfo(n);
        if (!pClassInfo->m_pDynamicEntry)
        {
            return NULL;
        }

        PTR_BYTE retval = NULL;

        GET_DYNAMICENTRY_NONGCSTATICS_BASEPOINTER(pLoaderAllocator, pClassInfo, &retval);

        return retval;
    }

    FORCEINLINE PTR_DynamicClassInfo GetDynamicClassInfoIfInitialized(DWORD n)
    {
        WRAPPER_NO_CONTRACT;

        // m_aDynamicEntries is set last, it needs to be checked first
        if (n >= m_aDynamicEntries)
        {
            return NULL;
        }

        _ASSERTE(m_pDynamicClassTable.Load() != NULL);
        PTR_DynamicClassInfo pDynamicClassInfo = (PTR_DynamicClassInfo)(m_pDynamicClassTable.Load() + n);

        // INITIALIZED_FLAG is set last, it needs to be checked first
        if ((pDynamicClassInfo->m_dwFlags & ClassInitFlags::INITIALIZED_FLAG) == 0)
        {
            return NULL;
        }

        PREFIX_ASSUME(pDynamicClassInfo != NULL);
        return pDynamicClassInfo;
    }

    // iClassIndex is slightly expensive to compute, so if we already know
    // it, we can use this helper
    inline BOOL IsClassInitialized(MethodTable* pMT, DWORD iClassIndex = (DWORD)-1)
    {
        WRAPPER_NO_CONTRACT;
        return (GetClassFlags(pMT, iClassIndex) & ClassInitFlags::INITIALIZED_FLAG) != 0;
    }

    inline BOOL IsPrecomputedClassInitialized(DWORD classID)
    {
        return GetPrecomputedStaticsClassData()[classID] & ClassInitFlags::INITIALIZED_FLAG;
    }
    
    inline BOOL IsClassAllocated(MethodTable* pMT, DWORD iClassIndex = (DWORD)-1)
    {
        WRAPPER_NO_CONTRACT;
        return (GetClassFlags(pMT, iClassIndex) & ClassInitFlags::ALLOCATECLASS_FLAG) != 0;
    }

    BOOL IsClassInitError(MethodTable* pMT, DWORD iClassIndex = (DWORD)-1)
    {
        WRAPPER_NO_CONTRACT;
        return (GetClassFlags(pMT, iClassIndex) & ClassInitFlags::ERROR_FLAG) != 0;
    }

    void    SetClassInitialized(MethodTable* pMT);
    void    SetClassInitError(MethodTable* pMT);

    void    EnsureDynamicClassIndex(DWORD dwID);

    void    AllocateDynamicClass(MethodTable *pMT);

    void    PopulateClass(MethodTable *pMT);

#ifdef DACCESS_COMPILE
    void EnumMemoryRegions(CLRDataEnumMemoryFlags flags);
#endif

    static DWORD OffsetOfDataBlob()
    {
        LIMITED_METHOD_CONTRACT;
        return offsetof(DomainLocalModule, m_pDataBlob);
    }

    FORCEINLINE MethodTable * GetMethodTableFromClassDomainID(DWORD dwClassDomainID)
    {
        DWORD rid = (DWORD)(dwClassDomainID) + 1;
        TypeHandle th = GetDomainFile()->GetModule()->LookupTypeDef(TokenFromRid(rid, mdtTypeDef));
        _ASSERTE(!th.IsNull());
        MethodTable * pMT = th.AsMethodTable();
        PREFIX_ASSUME(pMT != NULL);
        return pMT;
    }

private:
    friend void EmitFastGetSharedStaticBase(CPUSTUBLINKER *psl, CodeLabel *init, bool bCCtorCheck);

    void SetClassFlags(MethodTable* pMT, DWORD dwFlags);
    DWORD GetClassFlags(MethodTable* pMT, DWORD iClassIndex);

    PTR_DomainFile           m_pDomainFile;
    VolatilePtr<DynamicClassInfo, PTR_DynamicClassInfo> m_pDynamicClassTable;   // used for generics and reflection.emit in memory
    Volatile<SIZE_T>         m_aDynamicEntries;      // number of entries in dynamic table
    VolatilePtr<UMEntryThunk> m_pADThunkTable;
    PTR_OBJECTREF            m_pGCStatics;           // Handle to GC statics of the module

    // In addition to storing the ModuleIndex in the Module class, we also
    // keep a copy of the ModuleIndex in the DomainLocalModule class. This
    // allows the thread static JIT helpers to quickly convert a pointer to
    // a DomainLocalModule into a ModuleIndex.
    ModuleIndex             m_ModuleIndex;

    // Note that the static offset calculation in code:Module::BuildStaticsOffsets takes the offset m_pDataBlob
    // into consideration for alignment so we do not need any padding to ensure that the start of the data blob is aligned

    BYTE                     m_pDataBlob[0];         // First byte of the statics blob

    // Layout of m_pDataBlob is:
    //              ClassInit bytes (hold flags for cctor run, cctor error, etc)
    //              Non GC Statics

public:

    // The Module class need to be able to initialized ModuleIndex,
    // so for now I will make it a friend..
    friend class Module;

    FORCEINLINE ModuleIndex GetModuleIndex()
    {
        LIMITED_METHOD_DAC_CONTRACT;
        return m_ModuleIndex;
    }

};  // struct DomainLocalModule


typedef DPTR(class DomainLocalBlock) PTR_DomainLocalBlock;
class DomainLocalBlock
{
    friend class ClrDataAccess;
    friend class CheckAsmOffsets;

private:
    PTR_AppDomain          m_pDomain;
    DPTR(PTR_DomainLocalModule) m_pModuleSlots;
    SIZE_T                 m_aModuleIndices;               // Module entries the shared block has allocated

public: // used by code generators
    static SIZE_T GetOffsetOfModuleSlotsPointer() { return offsetof(DomainLocalBlock, m_pModuleSlots);}

public:

#ifndef DACCESS_COMPILE
    DomainLocalBlock()
      : m_pDomain(NULL),  m_pModuleSlots(NULL), m_aModuleIndices(0) {}

    void    EnsureModuleIndex(ModuleIndex index);

    void Init(AppDomain *pDomain) { LIMITED_METHOD_CONTRACT; m_pDomain = pDomain; }
#endif

    void SetModuleSlot(ModuleIndex index, PTR_DomainLocalModule pLocalModule);

    FORCEINLINE PTR_DomainLocalModule GetModuleSlot(ModuleIndex index)
    {
        WRAPPER_NO_CONTRACT;
        SUPPORTS_DAC;
        _ASSERTE(index.m_dwIndex < m_aModuleIndices);
        return m_pModuleSlots[index.m_dwIndex];
    }

    inline PTR_DomainLocalModule GetModuleSlot(MethodTable* pMT)
    {
        WRAPPER_NO_CONTRACT;
        return GetModuleSlot(pMT->GetModuleForStatics()->GetModuleIndex());
    }

    DomainFile* TryGetDomainFile(ModuleIndex index)
    {
        WRAPPER_NO_CONTRACT;
        SUPPORTS_DAC;

        // the publishing of m_aModuleIndices and m_pModuleSlots is dependent
        // on the order of accesses; we must ensure that we read from m_aModuleIndices
        // before m_pModuleSlots.
        if (index.m_dwIndex < m_aModuleIndices)
        {
            MemoryBarrier();
            if (m_pModuleSlots[index.m_dwIndex])
            {
                return m_pModuleSlots[index.m_dwIndex]->GetDomainFile();
            }
        }

        return NULL;
    }

    DomainFile* GetDomainFile(SIZE_T ModuleID)
    {
        WRAPPER_NO_CONTRACT;
        ModuleIndex index = Module::IDToIndex(ModuleID);
        _ASSERTE(index.m_dwIndex < m_aModuleIndices);
        return m_pModuleSlots[index.m_dwIndex]->GetDomainFile();
    }

#ifndef DACCESS_COMPILE
    void SetDomainFile(ModuleIndex index, DomainFile* pDomainFile)
    {
        WRAPPER_NO_CONTRACT;
        _ASSERTE(index.m_dwIndex < m_aModuleIndices);
        m_pModuleSlots[index.m_dwIndex]->SetDomainFile(pDomainFile);
    }
#endif

#ifdef DACCESS_COMPILE
    void EnumMemoryRegions(CLRDataEnumMemoryFlags flags);
#endif


private:

    //
    // Low level routines to get & set class entries
    //

};

#ifdef _MSC_VER
#pragma warning(pop)
#endif


// The large heap handle bucket class is used to contain handles allocated
// from an array contained in the large heap.
class LargeHeapHandleBucket
{
public:
    // Constructor and desctructor.
    LargeHeapHandleBucket(LargeHeapHandleBucket *pNext, DWORD Size, BaseDomain *pDomain, BOOL bCrossAD = FALSE);
    ~LargeHeapHandleBucket();

    // This returns the next bucket.
    LargeHeapHandleBucket *GetNext()
    {
        LIMITED_METHOD_CONTRACT;

        return m_pNext;
    }

    // This returns the number of remaining handle slots.
    DWORD GetNumRemainingHandles()
    {
        LIMITED_METHOD_CONTRACT;

        return m_ArraySize - m_CurrentPos;
    }

    void ConsumeRemaining()
    {
        LIMITED_METHOD_CONTRACT;
        
        m_CurrentPos = m_ArraySize;
    }

    OBJECTREF *TryAllocateEmbeddedFreeHandle();       

    // Allocate handles from the bucket.
    OBJECTREF* AllocateHandles(DWORD nRequested);
    OBJECTREF* CurrentPos()
    {
        LIMITED_METHOD_CONTRACT;
        return m_pArrayDataPtr + m_CurrentPos;
    }

private:
    LargeHeapHandleBucket *m_pNext;
    int m_ArraySize;
    int m_CurrentPos;
    int m_CurrentEmbeddedFreePos;
    OBJECTHANDLE m_hndHandleArray;
    OBJECTREF *m_pArrayDataPtr;
};



// The large heap handle table is used to allocate handles that are pointers
// to objects stored in an array in the large object heap.
class LargeHeapHandleTable
{
public:
    // Constructor and desctructor.
    LargeHeapHandleTable(BaseDomain *pDomain, DWORD InitialBucketSize);
    ~LargeHeapHandleTable();

    // Allocate handles from the large heap handle table.
    OBJECTREF* AllocateHandles(DWORD nRequested, BOOL bCrossAD = FALSE);

    // Release object handles allocated using AllocateHandles().
    void ReleaseHandles(OBJECTREF *pObjRef, DWORD nReleased);    

private:
    // The buckets of object handles.
    LargeHeapHandleBucket *m_pHead;

    // We need to know the containing domain so we know where to allocate handles
    BaseDomain *m_pDomain;

    // The size of the LargeHeapHandleBuckets.
    DWORD m_NextBucketSize;

    // for finding and re-using embedded free items in the list
    LargeHeapHandleBucket *m_pFreeSearchHint;
    DWORD m_cEmbeddedFree;   

#ifdef _DEBUG

    // these functions are present to enforce that there is a locking mechanism in place
    // for each LargeHeapHandleTable even though the code itself does not do the locking
    // you must tell the table which lock you intend to use and it will verify that it has
    // in fact been taken before performing any operations

public:
    void RegisterCrstDebug(CrstBase *pCrst)
    {
        LIMITED_METHOD_CONTRACT;

        // this function must be called exactly once
        _ASSERTE(pCrst != NULL);
        _ASSERTE(m_pCrstDebug == NULL);
        m_pCrstDebug = pCrst;
    }

private:
    // we will assert that this Crst is held before using the object
    CrstBase *m_pCrstDebug;

#endif
    
};

class LargeHeapHandleBlockHolder;
void LargeHeapHandleBlockHolder__StaticFree(LargeHeapHandleBlockHolder*);


class LargeHeapHandleBlockHolder:public Holder<LargeHeapHandleBlockHolder*,DoNothing,LargeHeapHandleBlockHolder__StaticFree>

{
    LargeHeapHandleTable* m_pTable;
    DWORD m_Count;
    OBJECTREF* m_Data;
public:
    FORCEINLINE LargeHeapHandleBlockHolder(LargeHeapHandleTable* pOwner, DWORD nCount)
    {
        WRAPPER_NO_CONTRACT;
        m_Data = pOwner->AllocateHandles(nCount);
        m_Count=nCount;
        m_pTable=pOwner;
    };

    FORCEINLINE void FreeData()
    {
        WRAPPER_NO_CONTRACT;
        for (DWORD i=0;i< m_Count;i++)
            ClearObjectReference(m_Data+i);
        m_pTable->ReleaseHandles(m_Data, m_Count);
    };
    FORCEINLINE OBJECTREF* operator[] (DWORD idx)
    {
        LIMITED_METHOD_CONTRACT;
        _ASSERTE(idx<m_Count);
        return &(m_Data[idx]);
    }
};

FORCEINLINE  void LargeHeapHandleBlockHolder__StaticFree(LargeHeapHandleBlockHolder* pHolder)
{
    WRAPPER_NO_CONTRACT;
    pHolder->FreeData();
};





// The large heap handle bucket class is used to contain handles allocated
// from an array contained in the large heap.
class ThreadStaticHandleBucket
{
public:
    // Constructor and desctructor.
    ThreadStaticHandleBucket(ThreadStaticHandleBucket *pNext, DWORD Size, BaseDomain *pDomain);
    ~ThreadStaticHandleBucket();

    // This returns the next bucket.
    ThreadStaticHandleBucket *GetNext()
    {
        LIMITED_METHOD_CONTRACT;

        return m_pNext;
    }

    // Allocate handles from the bucket.
    OBJECTHANDLE GetHandles();

private:
    ThreadStaticHandleBucket *m_pNext;
    int m_ArraySize;
    OBJECTHANDLE m_hndHandleArray;
};


// The large heap handle table is used to allocate handles that are pointers
// to objects stored in an array in the large object heap.
class ThreadStaticHandleTable
{
public:
    // Constructor and desctructor.
    ThreadStaticHandleTable(BaseDomain *pDomain);
    ~ThreadStaticHandleTable();

    // Allocate handles from the large heap handle table.
    OBJECTHANDLE AllocateHandles(DWORD nRequested);

private:
    // The buckets of object handles.
    ThreadStaticHandleBucket *m_pHead;

    // We need to know the containing domain so we know where to allocate handles
    BaseDomain *m_pDomain;
};




//--------------------------------------------------------------------------------------
// Base class for domains. It provides an abstract way of finding the first assembly and
// for creating assemblies in the the domain. The system domain only has one assembly, it
// contains the classes that are logically shared between domains. All other domains can
// have multiple assemblies. Iteration is done be getting the first assembly and then
// calling the Next() method on the assembly.
//
// The system domain should be as small as possible, it includes object, exceptions, etc.
// which are the basic classes required to load other assemblies. All other classes
// should be loaded into the domain. Of coarse there is a trade off between loading the
// same classes multiple times, requiring all domains to load certain assemblies (working
// set) and being able to specify specific versions.
//

#define LOW_FREQUENCY_HEAP_RESERVE_SIZE        (3 * PAGE_SIZE)
#define LOW_FREQUENCY_HEAP_COMMIT_SIZE         (1 * PAGE_SIZE)

#define HIGH_FREQUENCY_HEAP_RESERVE_SIZE       (10 * PAGE_SIZE)
#define HIGH_FREQUENCY_HEAP_COMMIT_SIZE        (1 * PAGE_SIZE)

#define STUB_HEAP_RESERVE_SIZE                 (3 * PAGE_SIZE)
#define STUB_HEAP_COMMIT_SIZE                  (1 * PAGE_SIZE)

// --------------------------------------------------------------------------------
// PE File List lock - for creating list locks on PE files
// --------------------------------------------------------------------------------

class PEFileListLock : public ListLock
{
public:
#ifndef DACCESS_COMPILE
    ListLockEntry *FindFileLock(PEFile *pFile)
    {
        STATIC_CONTRACT_NOTHROW;
        STATIC_CONTRACT_GC_NOTRIGGER;
        STATIC_CONTRACT_FORBID_FAULT;

        PRECONDITION(HasLock());

        ListLockEntry *pEntry;

        for (pEntry = m_pHead;
             pEntry != NULL;
             pEntry = pEntry->m_pNext)
        {
            if (((PEFile *)pEntry->m_pData)->Equals(pFile))
            {
                return pEntry;
            }
        }

        return NULL;
    }
#endif // DACCESS_COMPILE

    DEBUG_NOINLINE static void HolderEnter(PEFileListLock *pThis) PUB
    {
        WRAPPER_NO_CONTRACT;
        ANNOTATION_SPECIAL_HOLDER_CALLER_NEEDS_DYNAMIC_CONTRACT;
        
        pThis->Enter();
    }

    DEBUG_NOINLINE static void HolderLeave(PEFileListLock *pThis) PUB
    {
        WRAPPER_NO_CONTRACT;
        ANNOTATION_SPECIAL_HOLDER_CALLER_NEEDS_DYNAMIC_CONTRACT;

        pThis->Leave();
    }

    typedef Wrapper<PEFileListLock*, PEFileListLock::HolderEnter, PEFileListLock::HolderLeave> Holder;
};

typedef PEFileListLock::Holder PEFileListLockHolder;

// Loading infrastructure:
//
// a DomainFile is a file being loaded.  Files are loaded in layers to enable loading in the
// presence of dependency loops.
//
// FileLoadLevel describes the various levels available.  These are implemented slightly
// differently for assemblies and modules, but the basic structure is the same.
//
// LoadLock and FileLoadLock form the ListLock data structures for files. The FileLoadLock
// is specialized in that it allows taking a lock at a particular level.  Basicall any
// thread may obtain the lock at a level at which the file has previously been loaded to, but
// only one thread may obtain the lock at its current level.
//
// The PendingLoadQueue is a per thread data structure which serves two purposes.  First, it
// holds a "load limit" which automatically restricts the level of recursive loads to be
// one less than the current load which is preceding.  This, together with the AppDomain
// LoadLock level behavior, will prevent any deadlocks from occuring due to circular
// dependencies.  (Note that it is important that the loading logic understands this restriction,
// and any given level of loading must deal with the fact that any recursive loads will be partially
// unfulfilled in a specific way.)
//
// The second function is to queue up any unfulfilled load requests for the thread.  These
// are then delivered immediately after the current load request is dealt with.

class FileLoadLock : public ListLockEntry
{
private:
    FileLoadLevel           m_level;
    DomainFile              *m_pDomainFile;
    HRESULT                 m_cachedHR;
    ADID                    m_AppDomainId;

public:
    static FileLoadLock *Create(PEFileListLock *pLock, PEFile *pFile, DomainFile *pDomainFile);

    ~FileLoadLock();
    DomainFile *GetDomainFile();
    ADID GetAppDomainId();
    FileLoadLevel GetLoadLevel();

    // CanAcquire will return FALSE if Acquire will definitely not take the lock due
    // to levels or deadlock.
    // (Note that there is a race exiting from the function, where Acquire may end
    // up not taking the lock anyway if another thread did work in the meantime.)
    BOOL CanAcquire(FileLoadLevel targetLevel);

    // Acquire will return FALSE and not take the lock if the file
    // has already been loaded to the target level.  Otherwise,
    // it will return TRUE and take the lock.
    //
    // Note that the taker must release the lock via IncrementLoadLevel.
    BOOL Acquire(FileLoadLevel targetLevel);

    // CompleteLoadLevel can be called after Acquire returns true
    // returns TRUE if it updated load level, FALSE if the level was set already
    BOOL CompleteLoadLevel(FileLoadLevel level, BOOL success);

    void SetError(Exception *ex);

    void AddRef();
    UINT32 Release() DAC_EMPTY_RET(0);

private:

    FileLoadLock(PEFileListLock *pLock, PEFile *pFile, DomainFile *pDomainFile);

    static void HolderLeave(FileLoadLock *pThis);

public:
    typedef Wrapper<FileLoadLock *, DoNothing, FileLoadLock::HolderLeave> Holder;

};

typedef FileLoadLock::Holder FileLoadLockHolder;

#ifndef DACCESS_COMPILE
    typedef ReleaseHolder<FileLoadLock> FileLoadLockRefHolder;
#endif // DACCESS_COMPILE


#ifdef _MSC_VER
#pragma warning(push)
#pragma warning (disable: 4324) //sometimes 64bit compilers complain about alignment
#endif
class LoadLevelLimiter
{
    FileLoadLevel                   m_currentLevel;
    LoadLevelLimiter* m_previousLimit;
    BOOL m_bActive;

public:

    LoadLevelLimiter()
      : m_currentLevel(FILE_ACTIVE),
      m_previousLimit(NULL),
      m_bActive(FALSE)
    {
        LIMITED_METHOD_CONTRACT;
    }

    void Activate()
    {
        WRAPPER_NO_CONTRACT;
        m_previousLimit=GetThread()->GetLoadLevelLimiter();
        if(m_previousLimit)
            m_currentLevel=m_previousLimit->GetLoadLevel();
        GetThread()->SetLoadLevelLimiter(this);       
        m_bActive=TRUE;
    }

    void Deactivate()
    {
        WRAPPER_NO_CONTRACT;
        if (m_bActive)
        {
            GetThread()->SetLoadLevelLimiter(m_previousLimit);
            m_bActive=FALSE;
        }
    }

    ~LoadLevelLimiter()
    {
        WRAPPER_NO_CONTRACT;

        // PendingLoadQueues are allocated on the stack during a load, and
        // shared with all nested loads on the same thread.

        // Make sure the thread pointer gets reset after the
        // top level queue goes out of scope.
        if(m_bActive)
        {
            Deactivate();
        }
    }

    FileLoadLevel GetLoadLevel()
    {
        LIMITED_METHOD_CONTRACT;
        return m_currentLevel;
    }

    void SetLoadLevel(FileLoadLevel level)
    {
        LIMITED_METHOD_CONTRACT;
        m_currentLevel = level;
    }
};
#ifdef _MSC_VER
#pragma warning (pop) //4324
#endif

#define OVERRIDE_LOAD_LEVEL_LIMIT(newLimit)                    \
    LoadLevelLimiter __newLimit;                                                    \
    __newLimit.Activate();                                                              \
    __newLimit.SetLoadLevel(newLimit);

// A BaseDomain much basic information in a code:AppDomain including
// 
//    * code:#AppdomainHeaps - Heaps for any data structures that will be freed on appdomain unload
//    
class BaseDomain
{
    friend class Assembly;
    friend class AssemblySpec;
    friend class AppDomain;
    friend class AppDomainNative;

    VPTR_BASE_VTABLE_CLASS(BaseDomain)
    VPTR_UNIQUE(VPTR_UNIQUE_BaseDomain)

protected:
    // These 2 variables are only used on the AppDomain, but by placing them here
    // we reduce the cost of keeping the asmconstants file up to date.

    // The creation sequence number of this app domain (starting from 1)
    // This ID is generated by the code:SystemDomain::GetNewAppDomainId routine
    // The ID are recycled. 
    // 
    // see also code:ADID 
    ADID m_dwId;

    DomainLocalBlock    m_sDomainLocalBlock;

public:

    class AssemblyIterator;
    friend class AssemblyIterator;

    // Static initialization.
    static void Attach();

    //****************************************************************************************
    //
    // Initialization/shutdown routines for every instance of an BaseDomain.

    BaseDomain();
    virtual ~BaseDomain() {}
    void Init();
    void Stop();
    void Terminate();

    // ID to uniquely identify this AppDomain - used by the AppDomain publishing
    // service (to publish the list of all appdomains present in the process),
    // which in turn is used by, for eg., the debugger (to decide which App-
    // Domain(s) to attach to).
    // This is also used by Remoting for routing cross-appDomain calls.
    ADID GetId (void)
    {
        LIMITED_METHOD_DAC_CONTRACT;
        STATIC_CONTRACT_SO_TOLERANT;
        return m_dwId;
    }
    
    virtual BOOL IsAppDomain()    { LIMITED_METHOD_DAC_CONTRACT; return FALSE; }
    virtual BOOL IsSharedDomain() { LIMITED_METHOD_DAC_CONTRACT; return FALSE; }

    inline BOOL IsDefaultDomain();  // defined later in this file
    virtual PTR_LoaderAllocator GetLoaderAllocator() = 0;
    virtual PTR_AppDomain AsAppDomain()
    {
        LIMITED_METHOD_CONTRACT;
        STATIC_CONTRACT_SO_TOLERANT;
        _ASSERTE(!"Not an AppDomain");
        return NULL;
    }

    
    // If one domain is the SharedDomain and one is an AppDomain then
    // return the AppDomain, i.e. return the domain with the shorter lifetime
    // of the two given domains.
    static PTR_BaseDomain ComputeBaseDomain(
         BaseDomain *pGenericDefinitionDomain,    // the domain that owns the generic type or method
         Instantiation classInst,                       // the type arguments to the type (if any)
         Instantiation methodInst = Instantiation());   // the type arguments to the method (if any)

    static PTR_BaseDomain ComputeBaseDomain(TypeKey * pTypeKey);

#ifdef FEATURE_COMINTEROP
    //****************************************************************************************
    //
    // This will look up interop data for a method table
    //

#ifndef DACCESS_COMPILE
    // Returns the data pointer if present, NULL otherwise
    InteropMethodTableData *LookupComInteropData(MethodTable *pMT)
    {
        // Take the lock
        CrstHolder holder(&m_InteropDataCrst);

        // Lookup
        InteropMethodTableData *pData = (InteropMethodTableData*) m_interopDataHash.LookupValue((UPTR) pMT, (LPVOID) NULL);

        // Not there...
        if (pData == (InteropMethodTableData*) INVALIDENTRY)
            return NULL;

        // Found it
        return pData;
    }

    // Returns TRUE if successfully inserted, FALSE if this would be a duplicate entry
    BOOL InsertComInteropData(MethodTable* pMT, InteropMethodTableData *pData)
    {
        // We don't keep track of this kind of information for interfaces
        _ASSERTE(!pMT->IsInterface());

        // Take the lock
        CrstHolder holder(&m_InteropDataCrst);

        // Check to see that it's not already in there
        InteropMethodTableData *pDupData = (InteropMethodTableData*) m_interopDataHash.LookupValue((UPTR) pMT, (LPVOID) NULL);
        if (pDupData != (InteropMethodTableData*) INVALIDENTRY)
            return FALSE;

        // Not in there, so insert
        m_interopDataHash.InsertValue((UPTR) pMT, (LPVOID) pData);

        // Success
        return TRUE;
    }
#endif // DACCESS_COMPILE
#endif // FEATURE_COMINTEROP

    void SetDisableInterfaceCache()
    {
        m_fDisableInterfaceCache = TRUE;
    }
    BOOL GetDisableInterfaceCache()
    {
        return m_fDisableInterfaceCache;
    }

#ifdef FEATURE_COMINTEROP
    MngStdInterfacesInfo * GetMngStdInterfacesInfo()
    {
        LIMITED_METHOD_CONTRACT;

        return m_pMngStdInterfacesInfo;
    }
    
    PTR_CLRPrivBinderWinRT GetWinRtBinder()
    {
        return m_pWinRtBinder;
    }
#endif // FEATURE_COMINTEROP

    //****************************************************************************************
    // This method returns marshaling data that the EE uses that is stored on a per app domain
    // basis.
    EEMarshalingData *GetMarshalingData();

    // Deletes marshaling data at shutdown (which contains cached factories that needs to be released)
    void DeleteMarshalingData();
    
#ifdef _DEBUG
    BOOL OwnDomainLocalBlockLock()
    {
        WRAPPER_NO_CONTRACT;

        return m_DomainLocalBlockCrst.OwnedByCurrentThread();
    }
#endif

    //****************************************************************************************
    // Get the class init lock. The method is limited to friends because inappropriate use
    // will cause deadlocks in the system
    ListLock*  GetClassInitLock()
    {
        LIMITED_METHOD_CONTRACT;

        return &m_ClassInitLock;
    }

    ListLock* GetJitLock()
    {
        LIMITED_METHOD_CONTRACT;
        return &m_JITLock;
    }

    ListLock* GetILStubGenLock()
    {
        LIMITED_METHOD_CONTRACT;
        return &m_ILStubGenLock;
    }

    STRINGREF *IsStringInterned(STRINGREF *pString);
    STRINGREF *GetOrInternString(STRINGREF *pString);

    virtual BOOL CanUnload()   { LIMITED_METHOD_CONTRACT; return FALSE; }    // can never unload BaseDomain

    // Returns an array of OBJECTREF* that can be used to store domain specific data.
    // Statics and reflection info (Types, MemberInfo,..) are stored this way
    // If ppLazyAllocate != 0, allocation will only take place if *ppLazyAllocate != 0 (and the allocation
    // will be properly serialized)
    OBJECTREF *AllocateObjRefPtrsInLargeTable(int nRequested, OBJECTREF** ppLazyAllocate = NULL, BOOL bCrossAD = FALSE);

#ifdef FEATURE_PREJIT
    // Ensures that the file for logging profile data is open (we only open it once)
    // return false on failure
    static BOOL EnsureNGenLogFileOpen();
#endif

    //****************************************************************************************
    // Handles

#if !defined(DACCESS_COMPILE) && !defined(CROSSGEN_COMPILE)
    OBJECTHANDLE CreateTypedHandle(OBJECTREF object, int type)
    {
        WRAPPER_NO_CONTRACT;

        IGCHandleTable *pHandleTable = GCHandleTableUtilities::GetGCHandleTable();
        return pHandleTable->CreateHandleOfType(m_handleStore, OBJECTREFToObject(object), type);
    }

    OBJECTHANDLE CreateHandle(OBJECTREF object)
    {
        WRAPPER_NO_CONTRACT;
        CONDITIONAL_CONTRACT_VIOLATION(ModeViolation, object == NULL)
        return ::CreateHandle(m_handleStore, object);
    }

    OBJECTHANDLE CreateWeakHandle(OBJECTREF object)
    {
        WRAPPER_NO_CONTRACT;
        return ::CreateWeakHandle(m_handleStore, object);
    }

    OBJECTHANDLE CreateShortWeakHandle(OBJECTREF object)
    {
        WRAPPER_NO_CONTRACT;
        return ::CreateShortWeakHandle(m_handleStore, object);
    }

    OBJECTHANDLE CreateLongWeakHandle(OBJECTREF object)
    {
        WRAPPER_NO_CONTRACT;
        CONDITIONAL_CONTRACT_VIOLATION(ModeViolation, object == NULL)
        return ::CreateLongWeakHandle(m_handleStore, object);
    }

    OBJECTHANDLE CreateStrongHandle(OBJECTREF object)
    {
        WRAPPER_NO_CONTRACT;
        return ::CreateStrongHandle(m_handleStore, object);
    }

    OBJECTHANDLE CreatePinningHandle(OBJECTREF object)
    {
        WRAPPER_NO_CONTRACT;
#if CHECK_APP_DOMAIN_LEAKS
        if(IsAppDomain())
            object->TryAssignAppDomain((AppDomain*)this,TRUE);
#endif
        return ::CreatePinningHandle(m_handleStore, object);
    }

    OBJECTHANDLE CreateSizedRefHandle(OBJECTREF object)
    {
        WRAPPER_NO_CONTRACT;
        OBJECTHANDLE h;
        if (GCHeapUtilities::IsServerHeap())
        {
            h = ::CreateSizedRefHandle(m_handleStore, object, m_dwSizedRefHandles % m_iNumberOfProcessors);
        }
        else
        {
            h = ::CreateSizedRefHandle(m_handleStore, object);
        }

        InterlockedIncrement((LONG*)&m_dwSizedRefHandles);
        return h;
    }

#ifdef FEATURE_COMINTEROP
    OBJECTHANDLE CreateRefcountedHandle(OBJECTREF object)
    {
        WRAPPER_NO_CONTRACT;
        return ::CreateRefcountedHandle(m_handleStore, object);
    }

    OBJECTHANDLE CreateWinRTWeakHandle(OBJECTREF object, IWeakReference* pWinRTWeakReference)
    {
        CONTRACTL
        {
            THROWS;
            GC_NOTRIGGER;
            MODE_COOPERATIVE;
        }
        CONTRACTL_END;

        return ::CreateWinRTWeakHandle(m_handleStore, object, pWinRTWeakReference);
    }
#endif // FEATURE_COMINTEROP

    OBJECTHANDLE CreateVariableHandle(OBJECTREF object, UINT type)
    {
        WRAPPER_NO_CONTRACT;
        return ::CreateVariableHandle(m_handleStore, object, type);
    }

    OBJECTHANDLE CreateDependentHandle(OBJECTREF primary, OBJECTREF secondary)
    {
        CONTRACTL
        {
            THROWS;
            GC_NOTRIGGER;
            MODE_COOPERATIVE;
        }
        CONTRACTL_END;

        IGCHandleTable *pHandleTable = GCHandleTableUtilities::GetGCHandleTable();
        return pHandleTable->CreateDependentHandle(m_handleStore, OBJECTREFToObject(primary), OBJECTREFToObject(secondary));
    }
#endif // DACCESS_COMPILE && !CROSSGEN_COMPILE

    IUnknown *GetFusionContext() {LIMITED_METHOD_CONTRACT;  return m_pFusionContext; }
    
    CLRPrivBinderCoreCLR *GetTPABinderContext() {LIMITED_METHOD_CONTRACT;  return m_pTPABinderContext; }


    CrstExplicitInit * GetLoaderAllocatorReferencesLock()
    {
        LIMITED_METHOD_CONTRACT;
        return &m_crstLoaderAllocatorReferences;
    }
    
protected:
    
    //****************************************************************************************
    // Helper method to initialize the large heap handle table.
    void InitLargeHeapHandleTable();

    //****************************************************************************************
    // Adds an assembly to the domain.
    void AddAssemblyNoLock(Assembly* assem);

    //****************************************************************************************
    //
    // Hash table that maps a MethodTable to COM Interop compatibility data.
    PtrHashMap          m_interopDataHash;

    // Critical sections & locks
    PEFileListLock   m_FileLoadLock;            // Protects the list of assemblies in the domain
    CrstExplicitInit m_DomainCrst;              // General Protection for the Domain
    CrstExplicitInit m_DomainCacheCrst;         // Protects the Assembly and Unmanaged caches
    CrstExplicitInit m_DomainLocalBlockCrst;
    CrstExplicitInit m_InteropDataCrst;         // Used for COM Interop compatiblilty
    // Used to protect the reference lists in the collectible loader allocators attached to this appdomain
    CrstExplicitInit m_crstLoaderAllocatorReferences;
    CrstExplicitInit m_WinRTFactoryCacheCrst;   // For WinRT factory cache
    
    //#AssemblyListLock
    // Used to protect the assembly list. Taken also by GC or debugger thread, therefore we have to avoid 
    // triggering GC while holding this lock (by switching the thread to GC_NOTRIGGER while it is held).
    CrstExplicitInit m_crstAssemblyList;
    BOOL             m_fDisableInterfaceCache;  // RCW COM interface cache
    ListLock         m_ClassInitLock;
    ListLock         m_JITLock;
    ListLock         m_ILStubGenLock;

    // Fusion context, used for adding assemblies to the is domain. It defines
    // fusion properties for finding assemblyies such as SharedBinPath,
    // PrivateBinPath, Application Directory, etc.
    IUnknown *m_pFusionContext; // Current binding context for the domain

    CLRPrivBinderCoreCLR *m_pTPABinderContext; // Reference to the binding context that holds TPA list details

    void* m_handleStore;

    // The large heap handle table.
    LargeHeapHandleTable        *m_pLargeHeapHandleTable;

    // The large heap handle table critical section.
    CrstExplicitInit             m_LargeHeapHandleTableCrst;

    EEMarshalingData            *m_pMarshalingData;

#ifdef FEATURE_COMINTEROP
    // Information regarding the managed standard interfaces.
    MngStdInterfacesInfo        *m_pMngStdInterfacesInfo;
    
    // WinRT binder
    PTR_CLRPrivBinderWinRT m_pWinRtBinder;
#endif // FEATURE_COMINTEROP

    // Number of allocated slots for context local statics of this domain
    DWORD m_dwContextStatics;

    // Protects allocation of slot IDs for thread and context statics
    static CrstStatic   m_SpecialStaticsCrst;

public:
    // Lazily allocate offset for context static
    DWORD AllocateContextStaticsOffset(DWORD* pOffsetSlot);

public:
    // Only call this routine when you can guarantee there are no
    // loads in progress.
    void ClearFusionContext();

public:

    //****************************************************************************************
    // Synchronization holders.

    class LockHolder : public CrstHolder
    {
    public:
        LockHolder(BaseDomain *pD)
            : CrstHolder(&pD->m_DomainCrst)
        {
            WRAPPER_NO_CONTRACT;
        }
    };
    friend class LockHolder;

    class CacheLockHolder : public CrstHolder
    {
    public:
        CacheLockHolder(BaseDomain *pD)
            : CrstHolder(&pD->m_DomainCacheCrst)
        {
            WRAPPER_NO_CONTRACT;
        }
    };
    friend class CacheLockHolder;

    class DomainLocalBlockLockHolder : public CrstHolder
    {
    public:
        DomainLocalBlockLockHolder(BaseDomain *pD)
            : CrstHolder(&pD->m_DomainLocalBlockCrst)
        {
            WRAPPER_NO_CONTRACT;
        }
    };
    friend class DomainLocalBlockLockHolder;

    class LoadLockHolder :  public PEFileListLockHolder
    {
    public:
        LoadLockHolder(BaseDomain *pD, BOOL Take = TRUE)
          : PEFileListLockHolder(&pD->m_FileLoadLock, Take)
        {
            CONTRACTL
            {
                NOTHROW;
                GC_NOTRIGGER;
                MODE_ANY;
                CAN_TAKE_LOCK;
            }
            CONTRACTL_END;
        }
    };
    friend class LoadLockHolder;
    class WinRTFactoryCacheLockHolder : public CrstHolder
    {
    public:
        WinRTFactoryCacheLockHolder(BaseDomain *pD)
            : CrstHolder(&pD->m_WinRTFactoryCacheCrst)
        {
            WRAPPER_NO_CONTRACT;
        }
    };
    friend class WinRTFactoryCacheLockHolder;

public:
    void InitVSD();
    RangeList *GetCollectibleVSDRanges() { return &m_collVSDRanges; }

private:
    TypeIDMap m_typeIDMap;
    // Range list for collectible types. Maps VSD PCODEs back to the VirtualCallStubManager they belong to
    LockedRangeList m_collVSDRanges;

public:
    UINT32 GetTypeID(PTR_MethodTable pMT);
    UINT32 LookupTypeID(PTR_MethodTable pMT);
    PTR_MethodTable LookupType(UINT32 id);

private:
    // I have yet to figure out an efficent way to get the number of handles 
    // of a particular type that's currently used by the process without 
    // spending more time looking at the handle table code. We know that 
    // our only customer (asp.net) in Dev10 is not going to create many of 
    // these handles so I am taking a shortcut for now and keep the sizedref
    // handle count on the AD itself.
    DWORD m_dwSizedRefHandles;

    static int m_iNumberOfProcessors;

public:
    // Called by DestroySizedRefHandle
    void DecNumSizedRefHandles()
    {
        WRAPPER_NO_CONTRACT;
        LONG result;
        result = InterlockedDecrement((LONG*)&m_dwSizedRefHandles);
        _ASSERTE(result >= 0);
    }

    DWORD GetNumSizedRefHandles()
    {
        return m_dwSizedRefHandles;
    }

    // Profiler rejit
private:
    ReJitManager m_reJitMgr;

public:
    ReJitManager * GetReJitManager() { return &m_reJitMgr; }

#ifdef DACCESS_COMPILE
public:
    virtual void EnumMemoryRegions(CLRDataEnumMemoryFlags flags,
                                   bool enumThis);
#endif

};  // class BaseDomain

enum
{
    ATTACH_ASSEMBLY_LOAD = 0x1,
    ATTACH_MODULE_LOAD = 0x2,
    ATTACH_CLASS_LOAD = 0x4,

    ATTACH_ALL = 0x7
};

class ADUnloadSink
{
    
protected:
    ~ADUnloadSink();
    CLREvent m_UnloadCompleteEvent;
    HRESULT   m_UnloadResult;
    Volatile<LONG> m_cRef;
public:
    ADUnloadSink();
    void ReportUnloadResult (HRESULT hr, OBJECTREF* pException);
    void WaitUnloadCompletion();
    HRESULT GetUnloadResult() {LIMITED_METHOD_CONTRACT; return m_UnloadResult;};
    void Reset();
    ULONG AddRef();
    ULONG Release();
};


FORCEINLINE void ADUnloadSink__Release(ADUnloadSink* pADSink)
{
    WRAPPER_NO_CONTRACT;

    if (pADSink)
        pADSink->Release();
}

typedef Wrapper <ADUnloadSink*,DoNothing,ADUnloadSink__Release,NULL> ADUnloadSinkHolder;

// This filters the output of IterateAssemblies. This ought to be declared more locally
// but it would result in really verbose callsites.
//
// Assemblies can be categorized by their load status (loaded, loading, or loaded just
// enough that they would be made available to profilers)
// Independently, they can also be categorized as execution or introspection.
//
// An assembly will be included in the results of IterateAssemblies only if
// the appropriate bit is set for *both* characterizations.
//
// The flags can be combined so if you want all loaded assemblies, you must specify:
//
///     kIncludeLoaded|kIncludeExecution|kIncludeIntrospection

enum AssemblyIterationFlags
{
    // load status flags
    kIncludeLoaded        = 0x00000001, // include assemblies that are already loaded
                                        // (m_level >= code:FILE_LOAD_DELIVER_EVENTS)
    kIncludeLoading       = 0x00000002, // include assemblies that are still in the process of loading
                                        // (all m_level values)
    kIncludeAvailableToProfilers
                          = 0x00000020, // include assemblies available to profilers
                                        // See comment at code:DomainFile::IsAvailableToProfilers

    // Execution / introspection flags
    kIncludeExecution     = 0x00000004, // include assemblies that are loaded for execution only
    kIncludeIntrospection = 0x00000008, // include assemblies that are loaded for introspection only
    
    kIncludeFailedToLoad  = 0x00000010, // include assemblies that failed to load 

    // Collectible assemblies flags
    kExcludeCollectible   = 0x00000040, // Exclude all collectible assemblies
    kIncludeCollected     = 0x00000080, 
        // Include assemblies which were collected and cannot be referenced anymore. Such assemblies are not 
        // AddRef-ed. Any manipulation with them should be protected by code:GetAssemblyListLock.
        // Should be used only by code:LoaderAllocator::GCLoaderAllocators.

};  // enum AssemblyIterationFlags

//---------------------------------------------------------------------------------------
// 
// Base class for holder code:CollectibleAssemblyHolder (see code:HolderBase).
// Manages AddRef/Release for collectible assemblies. It is no-op for 'normal' non-collectible assemblies.
// 
// Each type of type parameter needs 2 methods implemented:
//  code:CollectibleAssemblyHolderBase::GetLoaderAllocator
//  code:CollectibleAssemblyHolderBase::IsCollectible
// 
template<typename _Type>
class CollectibleAssemblyHolderBase
{
protected:
    _Type m_value;
public:
    CollectibleAssemblyHolderBase(const _Type & value = NULL)
    {
        LIMITED_METHOD_CONTRACT;
        m_value = value;
    }
    void DoAcquire()
    {
        CONTRACTL
        {
            NOTHROW;
            GC_NOTRIGGER;
            MODE_ANY;
        }
        CONTRACTL_END;
        
        // We don't need to keep the assembly alive in DAC - see code:#CAH_DAC
#ifndef DACCESS_COMPILE
        if (this->IsCollectible(m_value))
        {
            LoaderAllocator * pLoaderAllocator = GetLoaderAllocator(m_value);
            pLoaderAllocator->AddReference();
        }
#endif //!DACCESS_COMPILE
    }
    void DoRelease()
    {
        CONTRACTL
        {
            NOTHROW;
            GC_NOTRIGGER;
            MODE_ANY;
        }
        CONTRACTL_END;
        
#ifndef DACCESS_COMPILE
        if (this->IsCollectible(m_value))
        {
            LoaderAllocator * pLoaderAllocator = GetLoaderAllocator(m_value);
            pLoaderAllocator->Release();
        }
#endif //!DACCESS_COMPILE
    }
    
private:
    LoaderAllocator * GetLoaderAllocator(DomainAssembly * pDomainAssembly)
    {
        WRAPPER_NO_CONTRACT;
        return pDomainAssembly->GetLoaderAllocator();
    }
    BOOL IsCollectible(DomainAssembly * pDomainAssembly)
    {
        WRAPPER_NO_CONTRACT;
        return pDomainAssembly->IsCollectible();
    }
    LoaderAllocator * GetLoaderAllocator(Assembly * pAssembly)
    {
        WRAPPER_NO_CONTRACT;
        return pAssembly->GetLoaderAllocator();
    }
    BOOL IsCollectible(Assembly * pAssembly)
    {
        WRAPPER_NO_CONTRACT;
        return pAssembly->IsCollectible();
    }
};  // class CollectibleAssemblyHolderBase<>

//---------------------------------------------------------------------------------------
// 
// Holder of assembly reference which keeps collectible assembly alive while the holder is valid.
// 
// Collectible assembly can be collected at any point when GC happens. Almost instantly all native data 
// structures of the assembly (e.g. code:DomainAssembly, code:Assembly) could be deallocated. 
// Therefore any usage of (collectible) assembly data structures from native world, has to prevent the 
// deallocation by increasing ref-count on the assembly / associated loader allocator.
// 
// #CAH_DAC
// In DAC we don't AddRef/Release as the assembly doesn't have to be kept alive: The process is stopped when 
// DAC is used and therefore the assembly cannot just disappear.
// 
template<typename _Type>
class CollectibleAssemblyHolder : public BaseWrapper<_Type, CollectibleAssemblyHolderBase<_Type> >
{
public:
    FORCEINLINE 
    CollectibleAssemblyHolder(const _Type & value = NULL, BOOL fTake = TRUE)
        : BaseWrapper<_Type, CollectibleAssemblyHolderBase<_Type> >(value, fTake)
    {
        STATIC_CONTRACT_WRAPPER;
    }
    
    FORCEINLINE 
    CollectibleAssemblyHolder & 
    operator=(const _Type & value)
    {
        STATIC_CONTRACT_WRAPPER;
        BaseWrapper<_Type, CollectibleAssemblyHolderBase<_Type> >::operator=(value);
        return *this;
    }
    
    // Operator & is overloaded in parent, therefore we have to get to 'this' pointer explicitly.
    FORCEINLINE 
    CollectibleAssemblyHolder<_Type> * 
    This()
    {
        LIMITED_METHOD_CONTRACT;
        return this;
    }
};  // class CollectibleAssemblyHolder<>

//---------------------------------------------------------------------------------------
// 
#ifdef FEATURE_LOADER_OPTIMIZATION
class SharedAssemblyLocator
{
public:
    enum
    {
        DOMAINASSEMBLY      = 1,
        PEASSEMBLY          = 2,
        PEASSEMBLYEXACT     = 3
    };
    DWORD GetType() {LIMITED_METHOD_CONTRACT; return m_type;};
#ifndef DACCESS_COMPILE
    DomainAssembly* GetDomainAssembly() {LIMITED_METHOD_CONTRACT; _ASSERTE(m_type==DOMAINASSEMBLY); return (DomainAssembly*)m_value;};
    PEAssembly* GetPEAssembly() {LIMITED_METHOD_CONTRACT; _ASSERTE(m_type==PEASSEMBLY||m_type==PEASSEMBLYEXACT); return (PEAssembly*)m_value;};
    SharedAssemblyLocator(DomainAssembly* pAssembly)
    {
        LIMITED_METHOD_CONTRACT;
        m_type=DOMAINASSEMBLY;
        m_value=pAssembly;
    }
    SharedAssemblyLocator(PEAssembly* pFile, DWORD type = PEASSEMBLY)
    {
        LIMITED_METHOD_CONTRACT;
        m_type = type;
        m_value = pFile;
    }
#endif // DACCESS_COMPILE

    DWORD Hash();
protected:
    DWORD m_type;
    LPVOID m_value;
    ULONG   m_uIdentityHash;
};
#endif // FEATURE_LOADER_OPTIMIZATION

//
// Stores binding information about failed assembly loads for DAC
//
struct FailedAssembly {
    SString displayName;
    SString location;
    HRESULT error;

    void Initialize(AssemblySpec *pSpec, Exception *ex)
    {
        CONTRACTL
        {
            THROWS;
            GC_TRIGGERS;
            MODE_ANY;
        }
        CONTRACTL_END;

        displayName.SetASCII(pSpec->GetName());
        location.Set(pSpec->GetCodeBase());
        error = ex->GetHR();

        // 
        // Determine the binding context assembly would have been in.
        // If the parent has been set, use its binding context.
        // If the parent hasn't been set but the code base has, use LoadFrom.
        // Otherwise, use the default.
        //
    }
};

#ifdef FEATURE_COMINTEROP

// Cache used by COM Interop
struct NameToTypeMapEntry
{
    // Host space representation of the key
    struct Key
    {
        LPCWSTR m_wzName;     // The type name or registry string representation of the GUID "{<guid>}"
        SIZE_T  m_cchName;    // wcslen(m_wzName) for faster hashtable lookup
    };
    struct DacKey
    {
        PTR_CWSTR m_wzName;   // The type name or registry string representation of the GUID "{<guid>}"
        SIZE_T    m_cchName;  // wcslen(m_wzName) for faster hashtable lookup
    } m_key;
    TypeHandle m_typeHandle;  // Using TypeHandle instead of MethodTable* to avoid losing information when sharing method tables.
    UINT m_nEpoch;            // tracks creation Epoch. This is incremented each time an external reader enumerate the cache
    BYTE m_bFlags;
};

typedef DPTR(NameToTypeMapEntry) PTR_NameToTypeMapEntry;

class NameToTypeMapTraits : public NoRemoveSHashTraits< DefaultSHashTraits<NameToTypeMapEntry> >
{
public:
    typedef NameToTypeMapEntry::Key key_t;

    static const NameToTypeMapEntry Null() { NameToTypeMapEntry e; e.m_key.m_wzName = NULL; e.m_key.m_cchName = 0; return e; }
    static bool IsNull(const NameToTypeMapEntry &e) { return e.m_key.m_wzName == NULL; }
    static const key_t GetKey(const NameToTypeMapEntry &e) 
    {
        key_t key;
        key.m_wzName = (LPCWSTR)(e.m_key.m_wzName); // this cast brings the string over to the host, in a DAC build
        key.m_cchName = e.m_key.m_cchName;

        return key;
    }
    static count_t Hash(const key_t &key) { WRAPPER_NO_CONTRACT; return HashStringN(key.m_wzName, key.m_cchName); }
    
    static BOOL Equals(const key_t &lhs, const key_t &rhs)
    {
        WRAPPER_NO_CONTRACT;
        return (lhs.m_cchName == rhs.m_cchName) && memcmp(lhs.m_wzName, rhs.m_wzName, lhs.m_cchName * sizeof(WCHAR)) == 0;
    }
    
    void OnDestructPerEntryCleanupAction(const NameToTypeMapEntry& e)
    {
        WRAPPER_NO_CONTRACT;
        _ASSERTE(e.m_key.m_cchName == wcslen(e.m_key.m_wzName));
#ifndef DACCESS_COMPILE
        delete [] e.m_key.m_wzName;
#endif // DACCESS_COMPILE
    }
    static const bool s_DestructPerEntryCleanupAction = true;
};

typedef SHash<NameToTypeMapTraits> NameToTypeMapTable;

typedef DPTR(NameToTypeMapTable) PTR_NameToTypeMapTable;

struct WinRTFactoryCacheEntry
{
    typedef MethodTable *Key;           
    Key          key;                   // Type as KEY
    
    CtxEntry    *m_pCtxEntry;           // Context entry - used to verify whether the cache is a match
    OBJECTHANDLE m_ohFactoryObject;     // Handle to factory object
};

class WinRTFactoryCacheTraits : public DefaultSHashTraits<WinRTFactoryCacheEntry>
{
public:
    typedef WinRTFactoryCacheEntry::Key key_t;
    static const WinRTFactoryCacheEntry Null() { WinRTFactoryCacheEntry e; e.key = NULL; return e; }
    static bool IsNull(const WinRTFactoryCacheEntry &e) { return e.key == NULL; }
    static const WinRTFactoryCacheEntry::Key GetKey(const WinRTFactoryCacheEntry& e) { return e.key; }
    static count_t Hash(WinRTFactoryCacheEntry::Key key) { return (count_t)((size_t)key); }
    static BOOL Equals(WinRTFactoryCacheEntry::Key lhs, WinRTFactoryCacheEntry::Key rhs)
    { return lhs == rhs; }
    static const WinRTFactoryCacheEntry Deleted() { WinRTFactoryCacheEntry e; e.key = (MethodTable *)-1; return e; }
    static bool IsDeleted(const WinRTFactoryCacheEntry &e) { return e.key == (MethodTable *)-1; }

    static void OnDestructPerEntryCleanupAction(const WinRTFactoryCacheEntry& e);
    static const bool s_DestructPerEntryCleanupAction = true;
};

typedef SHash<WinRTFactoryCacheTraits> WinRTFactoryCache;

#endif // FEATURE_COMINTEROP

class AppDomainIterator;

const DWORD DefaultADID = 1;

template <class AppDomainType> class AppDomainCreationHolder;

// An Appdomain is the managed equivalent of a process.  It is an isolation unit (conceptually you don't
// have pointers directly from one appdomain to another, but rather go through remoting proxies).  It is
// also a unit of unloading.
// 
// Threads are always running in the context of a particular AppDomain.  See
// file:threads.h#RuntimeThreadLocals for more details.  
// 
// see code:BaseDomain for much of the meat of a AppDomain (heaps locks, etc)
//     * code:AppDomain.m_Assemblies - is a list of code:Assembly in the appdomain
// 
class AppDomain : public BaseDomain
{
    friend class ADUnloadSink;
    friend class SystemDomain;
    friend class AssemblySink;
    friend class AppDomainNative;
    friend class AssemblyNative;
    friend class AssemblySpec;
    friend class ClassLoader;
    friend class ThreadNative;
    friend class RCWCache;
    friend class ClrDataAccess;
    friend class CheckAsmOffsets;
    friend class AppDomainFromIDHolder;

    VPTR_VTABLE_CLASS(AppDomain, BaseDomain)

public:
#ifndef DACCESS_COMPILE
    AppDomain();
    virtual ~AppDomain();
#endif
    static void DoADUnloadWork();
    DomainAssembly* FindDomainAssembly(Assembly*);
    void EnterContext(Thread* pThread, Context* pCtx,ContextTransitionFrame *pFrame);

#ifndef DACCESS_COMPILE
    //-----------------------------------------------------------------------------------------------------------------
    // Convenience wrapper for ::GetAppDomain to provide better encapsulation.
    static AppDomain * GetCurrentDomain()
    { return ::GetAppDomain(); }
#endif //!DACCESS_COMPILE
    
    //-----------------------------------------------------------------------------------------------------------------
    // Initializes an AppDomain. (this functions is not called from the SystemDomain)
    void Init();

    // creates only unamaged part
    static void CreateUnmanagedObject(AppDomainCreationHolder<AppDomain>& result);
    inline void SetAppDomainManagerInfo(LPCWSTR szAssemblyName, LPCWSTR szTypeName, EInitializeNewDomainFlags dwInitializeDomainFlags);
    inline BOOL HasAppDomainManagerInfo();
    inline LPCWSTR GetAppDomainManagerAsm();
    inline LPCWSTR GetAppDomainManagerType();
    inline EInitializeNewDomainFlags GetAppDomainManagerInitializeNewDomainFlags();


#if defined(FEATURE_COMINTEROP)
    HRESULT SetWinrtApplicationContext(SString &appLocalWinMD);
#endif // FEATURE_COMINTEROP

    BOOL CanReversePInvokeEnter();
    void SetReversePInvokeCannotEnter();
    bool MustForceTrivialWaitOperations();
    void SetForceTrivialWaitOperations();

    //****************************************************************************************
    //
    // Stop deletes all the assemblies but does not remove other resources like
    // the critical sections
    void Stop();

    // Gets rid of resources
    void Terminate();

#ifdef  FEATURE_PREJIT
    //assembly cleanup that requires suspended runtime
    void DeleteNativeCodeRanges();
#endif

    // final assembly cleanup
    void ShutdownAssemblies();
    void ShutdownFreeLoaderAllocators(BOOL bFromManagedCode);
    
    void ReleaseDomainBoundInfo();
    void ReleaseFiles();
    

    // Remove the Appdomain for the system and cleans up. This call should not be
    // called from shut down code.
    void CloseDomain();

    virtual BOOL IsAppDomain() { LIMITED_METHOD_DAC_CONTRACT; return TRUE; }
    virtual PTR_AppDomain AsAppDomain() { LIMITED_METHOD_CONTRACT; return dac_cast<PTR_AppDomain>(this); }


    OBJECTREF DoSetup(OBJECTREF* setupInfo);

    OBJECTREF GetExposedObject();
    OBJECTREF GetRawExposedObject() {
        CONTRACTL
        {
            NOTHROW;
            GC_NOTRIGGER;
            SO_TOLERANT;
            MODE_COOPERATIVE;
        }
        CONTRACTL_END;
        if (m_ExposedObject) {
            return ObjectFromHandle(m_ExposedObject);
        }
        else {
            return NULL;
        }
    }

    OBJECTHANDLE GetRawExposedObjectHandleForDebugger() { LIMITED_METHOD_DAC_CONTRACT; return m_ExposedObject; }

#ifdef FEATURE_COMINTEROP
    HRESULT GetComIPForExposedObject(IUnknown **pComIP);

    MethodTable *GetRedirectedType(WinMDAdapter::RedirectedTypeIndex index);
#endif // FEATURE_COMINTEROP


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

protected:
    // Multi-thread safe access to the list of assemblies
    class DomainAssemblyList
    {
    private:
        ArrayList m_array;
#ifdef _DEBUG
        AppDomain * dbg_m_pAppDomain;
    public:
        void Debug_SetAppDomain(AppDomain * pAppDomain)
        {
            dbg_m_pAppDomain = pAppDomain;
        }
#endif //_DEBUG
    public:
        bool IsEmpty()
        {
            CONTRACTL {
                NOTHROW;
                GC_NOTRIGGER;
                MODE_ANY;
            } CONTRACTL_END;
            
            // This function can be reliably called without taking the lock, because the first assembly
            // added to the arraylist is non-collectible, and the ArrayList itself allows lockless read access
            return (m_array.GetCount() == 0);
        }
        void Clear(AppDomain * pAppDomain)
        {
            CONTRACTL {
                NOTHROW;
                WRAPPER(GC_TRIGGERS); // Triggers only in MODE_COOPERATIVE (by taking the lock)
                MODE_ANY;
            } CONTRACTL_END;
            
            _ASSERTE(dbg_m_pAppDomain == pAppDomain);
            
            CrstHolder ch(pAppDomain->GetAssemblyListLock());
            m_array.Clear();
        }
        
        DWORD GetCount(AppDomain * pAppDomain)
        {
            CONTRACTL {
                NOTHROW;
                WRAPPER(GC_TRIGGERS); // Triggers only in MODE_COOPERATIVE (by taking the lock)
                MODE_ANY;
            } CONTRACTL_END;
            
            _ASSERTE(dbg_m_pAppDomain == pAppDomain);
            
            CrstHolder ch(pAppDomain->GetAssemblyListLock());
            return GetCount_Unlocked();
        }
        DWORD GetCount_Unlocked()
        {
            CONTRACTL {
                NOTHROW;
                GC_NOTRIGGER;
                MODE_ANY;
            } CONTRACTL_END;
            
#ifndef DACCESS_COMPILE
            _ASSERTE(dbg_m_pAppDomain->GetAssemblyListLock()->OwnedByCurrentThread());
#endif
            // code:Append_Unlock guarantees that we do not have more than MAXDWORD items
            return m_array.GetCount();
        }
        
        void Get(AppDomain * pAppDomain, DWORD index, CollectibleAssemblyHolder<DomainAssembly *> * pAssemblyHolder)
        {
            CONTRACTL {
                NOTHROW;
                WRAPPER(GC_TRIGGERS); // Triggers only in MODE_COOPERATIVE (by taking the lock)
                MODE_ANY;
            } CONTRACTL_END;
            
            _ASSERTE(dbg_m_pAppDomain == pAppDomain);
            
            CrstHolder ch(pAppDomain->GetAssemblyListLock());
            Get_Unlocked(index, pAssemblyHolder);
        }
        void Get_Unlocked(DWORD index, CollectibleAssemblyHolder<DomainAssembly *> * pAssemblyHolder)
        {
            CONTRACTL {
                NOTHROW;
                GC_NOTRIGGER;
                MODE_ANY;
            } CONTRACTL_END;
            
            _ASSERTE(dbg_m_pAppDomain->GetAssemblyListLock()->OwnedByCurrentThread());
            *pAssemblyHolder = dac_cast<PTR_DomainAssembly>(m_array.Get(index));
        }
        // Doesn't lock the assembly list (caller has to hold the lock already).
        // Doesn't AddRef the returned assembly (if collectible).
        DomainAssembly * Get_UnlockedNoReference(DWORD index)
        {
            CONTRACTL {
                NOTHROW;
                GC_NOTRIGGER;
                MODE_ANY;
                SUPPORTS_DAC;
            } CONTRACTL_END;
            
#ifndef DACCESS_COMPILE
            _ASSERTE(dbg_m_pAppDomain->GetAssemblyListLock()->OwnedByCurrentThread());
#endif
            return dac_cast<PTR_DomainAssembly>(m_array.Get(index));
        }
        
#ifndef DACCESS_COMPILE
        void Set(AppDomain * pAppDomain, DWORD index, DomainAssembly * pAssembly)
        {
            CONTRACTL {
                NOTHROW;
                WRAPPER(GC_TRIGGERS); // Triggers only in MODE_COOPERATIVE (by taking the lock)
                MODE_ANY;
            } CONTRACTL_END;
            
            _ASSERTE(dbg_m_pAppDomain == pAppDomain);
            
            CrstHolder ch(pAppDomain->GetAssemblyListLock());
            return Set_Unlocked(index, pAssembly);
        }
        void Set_Unlocked(DWORD index, DomainAssembly * pAssembly)
        {
            CONTRACTL {
                NOTHROW;
                GC_NOTRIGGER;
                MODE_ANY;
            } CONTRACTL_END;
            
            _ASSERTE(dbg_m_pAppDomain->GetAssemblyListLock()->OwnedByCurrentThread());
            m_array.Set(index, pAssembly);
        }
        
        HRESULT Append_Unlocked(DomainAssembly * pAssembly)
        {
            CONTRACTL {
                NOTHROW;
                GC_NOTRIGGER;
                MODE_ANY;
            } CONTRACTL_END;
            
            _ASSERTE(dbg_m_pAppDomain->GetAssemblyListLock()->OwnedByCurrentThread());
            return m_array.Append(pAssembly);
        }
#else //DACCESS_COMPILE
        void 
        EnumMemoryRegions(CLRDataEnumMemoryFlags flags)
        {
            SUPPORTS_DAC;
            
            m_array.EnumMemoryRegions(flags);
        }
#endif // DACCESS_COMPILE
        
        // Should be used only by code:AssemblyIterator::Create
        ArrayList::Iterator GetArrayListIterator()
        {
            return m_array.Iterate();
        }
    };  // class DomainAssemblyList
    
    // Conceptually a list of code:Assembly structures, protected by lock code:GetAssemblyListLock
    DomainAssemblyList m_Assemblies;
    
public:
    // Note that this lock switches thread into GC_NOTRIGGER region as GC can take it too.
    CrstExplicitInit * GetAssemblyListLock()
    {
        LIMITED_METHOD_CONTRACT;
        return &m_crstAssemblyList;
    }
    
public:
    class AssemblyIterator
    {
        // AppDomain context with the assembly list
        AppDomain *            m_pAppDomain;
        ArrayList::Iterator    m_Iterator;
        AssemblyIterationFlags m_assemblyIterationFlags;

    public:
        BOOL Next(CollectibleAssemblyHolder<DomainAssembly *> * pDomainAssemblyHolder);
        // Note: Does not lock the assembly list, but AddRefs collectible assemblies.
        BOOL Next_Unlocked(CollectibleAssemblyHolder<DomainAssembly *> * pDomainAssemblyHolder);
#ifndef DACCESS_COMPILE
    private:
        // Can be called only from AppDomain shutdown code:AppDomain::ShutdownAssemblies.
        // Note: Does not lock the assembly list and does not AddRefs collectible assemblies.
        BOOL Next_UnsafeNoAddRef(DomainAssembly ** ppDomainAssembly);
#endif

    private:
        inline DWORD GetIndex()
        {
            LIMITED_METHOD_CONTRACT;
            return m_Iterator.GetIndex();
        }

    private:
        friend class AppDomain;
        // Cannot have constructor so this iterator can be used inside a union
        static AssemblyIterator Create(AppDomain * pAppDomain, AssemblyIterationFlags assemblyIterationFlags)
        {
            LIMITED_METHOD_CONTRACT;
            AssemblyIterator i;

            i.m_pAppDomain = pAppDomain;
            i.m_Iterator = pAppDomain->m_Assemblies.GetArrayListIterator();
            i.m_assemblyIterationFlags = assemblyIterationFlags;
            return i;
        }
    };  // class AssemblyIterator

    AssemblyIterator IterateAssembliesEx(AssemblyIterationFlags assemblyIterationFlags)
    {
        LIMITED_METHOD_CONTRACT;
        return AssemblyIterator::Create(this, assemblyIterationFlags);
    }

private:
    struct NativeImageDependenciesEntry
    {
        BaseAssemblySpec m_AssemblySpec;
        GUID m_guidMVID;
    };

    class NativeImageDependenciesTraits : public NoRemoveSHashTraits<DefaultSHashTraits<NativeImageDependenciesEntry *> >
    {
    public:
        typedef BaseAssemblySpec *key_t;
        static key_t GetKey(NativeImageDependenciesEntry * e) { return &(e->m_AssemblySpec); }

        static count_t Hash(key_t k)
        {
            return k->Hash();
        }

        static BOOL Equals(key_t lhs, key_t rhs)
        {
            return lhs->CompareEx(rhs);
        }
    };

    SHash<NativeImageDependenciesTraits> m_NativeImageDependencies;

public:
    void CheckForMismatchedNativeImages(AssemblySpec * pSpec, const GUID * pGuid);

public:
    class PathIterator
    {
        friend class AppDomain;

        ArrayList::Iterator m_i;

    public:
        BOOL Next()
        {
            WRAPPER_NO_CONTRACT;
            return m_i.Next();
        }

        SString* GetPath()
        {
            WRAPPER_NO_CONTRACT;
            return dac_cast<PTR_SString>(m_i.GetElement());
        }
    };
    BOOL BindingByManifestFile();

    PathIterator IterateNativeDllSearchDirectories();
    void SetNativeDllSearchDirectories(LPCWSTR paths);
    BOOL HasNativeDllSearchDirectories();
    void ShutdownNativeDllSearchDirectories();

public:
    SIZE_T GetAssemblyCount()
    {
        WRAPPER_NO_CONTRACT;
        return m_Assemblies.GetCount(this);
    }

    CHECK CheckCanLoadTypes(Assembly *pAssembly);
    CHECK CheckCanExecuteManagedCode(MethodDesc* pMD);
    CHECK CheckLoading(DomainFile *pFile, FileLoadLevel level);

    FileLoadLevel GetDomainFileLoadLevel(DomainFile *pFile);
    BOOL IsLoading(DomainFile *pFile, FileLoadLevel level);
    static FileLoadLevel GetThreadFileLoadLevel();

    void LoadDomainFile(DomainFile *pFile,
                        FileLoadLevel targetLevel);

    enum FindAssemblyOptions
    {
        FindAssemblyOptions_None                    = 0x0,
        FindAssemblyOptions_IncludeFailedToLoad     = 0x1
    };

    DomainAssembly * FindAssembly(PEAssembly * pFile, FindAssemblyOptions options = FindAssemblyOptions_None) DAC_EMPTY_RET(NULL);


    Assembly *LoadAssembly(AssemblySpec* pIdentity,
                           PEAssembly *pFile,
                           FileLoadLevel targetLevel,
                           AssemblyLoadSecurity *pLoadSecurity = NULL);

    // this function does not provide caching, you must use LoadDomainAssembly
    // unless the call is guaranteed to succeed or you don't need the caching 
    // (e.g. if you will FailFast or tear down the AppDomain anyway)
    // The main point that you should not bypass caching if you might try to load the same file again, 
    // resulting in multiple DomainAssembly objects that share the same PEAssembly for ngen image 
    //which is violating our internal assumptions
    DomainAssembly *LoadDomainAssemblyInternal( AssemblySpec* pIdentity,
                                                PEAssembly *pFile,
                                                FileLoadLevel targetLevel,
                                                AssemblyLoadSecurity *pLoadSecurity = NULL);

    DomainAssembly *LoadDomainAssembly( AssemblySpec* pIdentity,
                                        PEAssembly *pFile,
                                        FileLoadLevel targetLevel,
                                        AssemblyLoadSecurity *pLoadSecurity = NULL);


    CHECK CheckValidModule(Module *pModule);
#ifdef FEATURE_LOADER_OPTIMIZATION    
    DomainFile *LoadDomainNeutralModuleDependency(Module *pModule, FileLoadLevel targetLevel);
#endif

    // private:
    void LoadSystemAssemblies();

    DomainFile *LoadDomainFile(FileLoadLock *pLock,
                               FileLoadLevel targetLevel);

    void TryIncrementalLoad(DomainFile *pFile, FileLoadLevel workLevel, FileLoadLockHolder &lockHolder);

    Assembly *LoadAssemblyHelper(LPCWSTR wszAssembly,
                                 LPCWSTR wszCodeBase);

#ifndef DACCESS_COMPILE // needs AssemblySpec

    void GetCacheAssemblyList(SetSHash<PTR_DomainAssembly>& assemblyList);

    //****************************************************************************************
    // Returns and Inserts assemblies into a lookup cache based on the binding information
    // in the AssemblySpec. There can be many AssemblySpecs to a single assembly.
    DomainAssembly* FindCachedAssembly(AssemblySpec* pSpec, BOOL fThrow=TRUE)
    {
        WRAPPER_NO_CONTRACT;
        return m_AssemblyCache.LookupAssembly(pSpec, fThrow);
    }

    PEAssembly* FindCachedFile(AssemblySpec* pSpec, BOOL fThrow = TRUE);
    BOOL IsCached(AssemblySpec *pSpec);
#endif // DACCESS_COMPILE
    void CacheStringsForDAC();

    BOOL AddFileToCache(AssemblySpec* pSpec, PEAssembly *pFile, BOOL fAllowFailure = FALSE);
    BOOL AddAssemblyToCache(AssemblySpec* pSpec, DomainAssembly *pAssembly);
    BOOL AddExceptionToCache(AssemblySpec* pSpec, Exception *ex);
    void AddUnmanagedImageToCache(LPCWSTR libraryName, HMODULE hMod);
    HMODULE FindUnmanagedImageInCache(LPCWSTR libraryName);
    //****************************************************************************************
    //
    // Adds an assembly to the domain.
    void AddAssembly(DomainAssembly * assem);
    void RemoveAssembly_Unlocked(DomainAssembly * pAsm);

    BOOL ContainsAssembly(Assembly * assem);

#ifdef FEATURE_LOADER_OPTIMIZATION    
    enum SharePolicy
    {
        // Attributes to control when to use domain neutral assemblies
        SHARE_POLICY_UNSPECIFIED,   // Use the current default policy (LoaderOptimization.NotSpecified)
        SHARE_POLICY_NEVER,         // Do not share anything, except the system assembly (LoaderOptimization.SingleDomain)
        SHARE_POLICY_ALWAYS,        // Share everything possible (LoaderOptimization.MultiDomain)
        SHARE_POLICY_GAC,           // Share only GAC-bound assemblies (LoaderOptimization.MultiDomainHost)

        SHARE_POLICY_COUNT,
        SHARE_POLICY_MASK = 0x3,

        // NOTE that previously defined was a bit 0x40 which might be set on this value
        // in custom attributes.
        SHARE_POLICY_DEFAULT = SHARE_POLICY_NEVER,
    };

    void SetSharePolicy(SharePolicy policy);
    SharePolicy GetSharePolicy();
    BOOL ReduceSharePolicyFromAlways();

    //****************************************************************************************
    // Determines if the image is to be loaded into the shared assembly or an individual
    // appdomains.
#endif // FEATURE_LOADER_OPTIMIZATION

    BOOL HasSetSecurityPolicy();

    FORCEINLINE IApplicationSecurityDescriptor* GetSecurityDescriptor()
    {
        LIMITED_METHOD_CONTRACT;
        STATIC_CONTRACT_SO_TOLERANT;
        return static_cast<IApplicationSecurityDescriptor*>(m_pSecDesc);
    }

    void CreateSecurityDescriptor();

    //****************************************************************************************
    //
    // Reference count. When an appdomain is first created the reference is bump
    // to one when it is added to the list of domains (see SystemDomain). An explicit
    // Removal from the list is necessary before it will be deleted.
    ULONG AddRef(void);
    ULONG Release(void) DAC_EMPTY_RET(0);

    //****************************************************************************************
    LPCWSTR GetFriendlyName(BOOL fDebuggerCares = TRUE);
    LPCWSTR GetFriendlyNameForDebugger();
    LPCWSTR GetFriendlyNameForLogging();
#ifdef DACCESS_COMPILE
    PVOID GetFriendlyNameNoSet(bool* isUtf8);
#endif
    void SetFriendlyName(LPCWSTR pwzFriendlyName, BOOL fDebuggerCares = TRUE);
    void ResetFriendlyName(BOOL fDebuggerCares = TRUE);

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

    // This can be used to override the binding behavior of the appdomain.   It
    // is overridden in the compilation domain.  It is important that all
    // static binding goes through this path.
    virtual PEAssembly * BindAssemblySpec(
        AssemblySpec *pSpec,
        BOOL fThrowOnFileNotFound,
        BOOL fRaisePrebindEvents,
        StackCrawlMark *pCallerStackMark = NULL,
        AssemblyLoadSecurity *pLoadSecurity = NULL,
        BOOL fUseHostBinderIfAvailable = TRUE) DAC_EMPTY_RET(NULL);

    HRESULT BindAssemblySpecForHostedBinder(
        AssemblySpec *   pSpec, 
        IAssemblyName *  pAssemblyName, 
        ICLRPrivBinder * pBinder, 
        PEAssembly **    ppAssembly) DAC_EMPTY_RET(E_FAIL);
    
    HRESULT BindHostedPrivAssembly(
        PEAssembly *       pParentPEAssembly,
        ICLRPrivAssembly * pPrivAssembly, 
        IAssemblyName *    pAssemblyName, 
        PEAssembly **      ppAssembly, 
        BOOL               fIsIntrospectionOnly = FALSE) DAC_EMPTY_RET(S_OK);


    PEAssembly *TryResolveAssembly(AssemblySpec *pSpec, BOOL fPreBind);

    // Store a successful binding into the cache.  This will keep the file from
    // being physically unmapped, as well as shortcutting future attempts to bind
    // the same spec throught the Cached entry point.
    //
    // Right now we only cache assembly binds for "probing" type
    // binding situations, basically when loading domain neutral assemblies or
    // zap files.
    //
    // <TODO>@todo: We may want to be more aggressive about this if
    // there are other situations where we are repeatedly binding the
    // same assembly specs, though.</TODO>
    //
    // Returns TRUE if stored
    //         FALSE if it's a duplicate (caller should clean up args)
    BOOL StoreBindAssemblySpecResult(AssemblySpec *pSpec,
                                     PEAssembly *pFile,
                                     BOOL clone = TRUE);

    BOOL StoreBindAssemblySpecError(AssemblySpec *pSpec,
                                    HRESULT hr,
                                    OBJECTREF *pThrowable,
                                    BOOL clone = TRUE);

    //****************************************************************************************
    //
    //****************************************************************************************
    //
    // Uses the first assembly to add an application base to the Context. This is done
    // in a lazy fashion so executables do not take the perf hit unless the load other
    // assemblies
#ifndef DACCESS_COMPILE
    void OnAssemblyLoad(Assembly *assem);
    void OnAssemblyLoadUnlocked(Assembly *assem);
    static BOOL OnUnhandledException(OBJECTREF *pThrowable, BOOL isTerminating = TRUE);
    
#endif

    // True iff a debugger is attached to the process (same as CORDebuggerAttached)
    BOOL IsDebuggerAttached (void);

#ifdef DEBUGGING_SUPPORTED
    // Notify debugger of all assemblies, modules, and possibly classes in this AppDomain
    BOOL NotifyDebuggerLoad(int flags, BOOL attaching);

    // Send unload notifications to the debugger for all assemblies, modules and classes in this AppDomain
    void NotifyDebuggerUnload();
#endif // DEBUGGING_SUPPORTED

    void SetSystemAssemblyLoadEventSent (BOOL fFlag);
    BOOL WasSystemAssemblyLoadEventSent (void);

#ifndef DACCESS_COMPILE
    OBJECTREF* AllocateStaticFieldObjRefPtrs(int nRequested, OBJECTREF** ppLazyAllocate = NULL)
    {
        WRAPPER_NO_CONTRACT;

        return AllocateObjRefPtrsInLargeTable(nRequested, ppLazyAllocate);
    }

    OBJECTREF* AllocateStaticFieldObjRefPtrsCrossDomain(int nRequested, OBJECTREF** ppLazyAllocate = NULL)
    {
        WRAPPER_NO_CONTRACT;

        return AllocateObjRefPtrsInLargeTable(nRequested, ppLazyAllocate, TRUE);
    }
#endif // DACCESS_COMPILE

    void              EnumStaticGCRefs(promote_func* fn, ScanContext* sc);

    DomainLocalBlock *GetDomainLocalBlock()
    {
        LIMITED_METHOD_DAC_CONTRACT;

        return &m_sDomainLocalBlock;
    }

    static SIZE_T GetOffsetOfModuleSlotsPointer()
    {
        WRAPPER_NO_CONTRACT;

        return offsetof(AppDomain,m_sDomainLocalBlock) + DomainLocalBlock::GetOffsetOfModuleSlotsPointer();
    }

    void SetupSharedStatics();

    ADUnloadSink* PrepareForWaitUnloadCompletion();

    //****************************************************************************************
    //
    // Create a quick lookup for classes loaded into this domain based on their GUID.
    //
    void InsertClassForCLSID(MethodTable* pMT, BOOL fForceInsert = FALSE);
    void InsertClassForCLSID(MethodTable* pMT, GUID *pGuid);

#ifdef FEATURE_COMINTEROP
private:
    void CacheTypeByNameWorker(const SString &ssClassName, const UINT vCacheVersion, TypeHandle typeHandle, BYTE flags, BOOL bReplaceExisting = FALSE);
    TypeHandle LookupTypeByNameWorker(const SString &ssClassName, UINT *pvCacheVersion, BYTE *pbFlags);
public:
    // Used by COM Interop for mapping WinRT runtime class names to real types.
    void CacheTypeByName(const SString &ssClassName, const UINT vCacheVersion, TypeHandle typeHandle, BYTE flags, BOOL bReplaceExisting = FALSE);
    TypeHandle LookupTypeByName(const SString &ssClassName, UINT *pvCacheVersion, BYTE *pbFlags);
    PTR_MethodTable LookupTypeByGuid(const GUID & guid);

#ifndef DACCESS_COMPILE
    inline BOOL CanCacheWinRTTypeByGuid(TypeHandle typeHandle)
    { 
        CONTRACTL
        {
            THROWS;
            GC_NOTRIGGER;
            MODE_ANY;
        }
        CONTRACTL_END;
        
        // Only allow caching guid/types maps for types loaded during 
        // "normal" domain operation
        if (IsCompilationDomain() || (m_Stage < STAGE_OPEN))
            return FALSE;

        MethodTable *pMT = typeHandle.GetMethodTable();
        if (pMT != NULL)
        {
            // Don't cache mscorlib-internal declarations of WinRT types.
            if (pMT->GetModule()->IsSystem() && pMT->IsProjectedFromWinRT())
                return FALSE;

            // Don't cache redirected WinRT types.
            if (WinRTTypeNameConverter::IsRedirectedWinRTSourceType(pMT))
                return FALSE;
        }

        return TRUE;
    }
#endif // !DACCESS_COMPILE

    void CacheWinRTTypeByGuid(TypeHandle typeHandle);
    void GetCachedWinRTTypes(SArray<PTR_MethodTable> * pTypes, SArray<GUID> * pGuids, UINT minEpoch, UINT * pCurEpoch);

    // Used by COM Interop for caching WinRT factory objects.
    void CacheWinRTFactoryObject(MethodTable *pClassMT, OBJECTREF *refFactory, LPVOID lpCtxCookie);
    OBJECTREF LookupWinRTFactoryObject(MethodTable *pClassMT, LPVOID lpCtxCookie);
    void RemoveWinRTFactoryObjects(LPVOID pCtxCookie);

    MethodTable *LoadCOMClass(GUID clsid, BOOL bLoadRecord = FALSE, BOOL* pfAssemblyInReg = NULL);
    COMorRemotingFlag GetComOrRemotingFlag();
    BOOL GetPreferComInsteadOfManagedRemoting();
    OBJECTREF GetMissingObject();    // DispatchInfo will call function to retrieve the Missing.Value object.
#endif // FEATURE_COMINTEROP

#ifndef DACCESS_COMPILE
    MethodTable* LookupClass(REFIID iid)
    {
        WRAPPER_NO_CONTRACT;

        MethodTable *pMT = (MethodTable*) m_clsidHash.LookupValue((UPTR) GetKeyFromGUID(&iid), (LPVOID)&iid);
        return (pMT == (MethodTable*) INVALIDENTRY
            ? NULL
            : pMT);
    }
#endif // DACCESS_COMPILE

    //<TODO>@todo get a better key</TODO>
    ULONG GetKeyFromGUID(const GUID *pguid)
    {
        LIMITED_METHOD_CONTRACT;

        return *(ULONG *) pguid;
    }

#ifdef FEATURE_COMINTEROP
    ComCallWrapperCache* GetComCallWrapperCache();
    RCWCache *GetRCWCache()
    {
        WRAPPER_NO_CONTRACT;
        if (m_pRCWCache) 
            return m_pRCWCache;

        // By separating the cache creation from the common lookup, we
        // can keep the (x86) EH prolog/epilog off the path.
        return CreateRCWCache();
    }
private:
    RCWCache *CreateRCWCache();
public:
    RCWCache *GetRCWCacheNoCreate()
    {
        LIMITED_METHOD_CONTRACT;
        return m_pRCWCache;
    }

    RCWRefCache *GetRCWRefCache();

    void ResetComCallWrapperCache()
    {
        LIMITED_METHOD_CONTRACT;
        m_pComCallWrapperCache = NULL;
    }

    MethodTable* GetLicenseInteropHelperMethodTable();
#endif // FEATURE_COMINTEROP

    //****************************************************************************************
    // Get the proxy for this app domain

    ADIndex GetIndex()
    {
        LIMITED_METHOD_CONTRACT;
        SUPPORTS_DAC;

        return m_dwIndex;
    }

    TPIndex GetTPIndex()
    {
        LIMITED_METHOD_CONTRACT;
        return m_tpIndex;
    }

    void InitializeDomainContext(BOOL allowRedirects, LPCWSTR pwszPath, LPCWSTR pwszConfig);

    IUnknown *CreateFusionContext();

    void OverrideDefaultContextBinder(IUnknown *pOverrideBinder)
    {
        LIMITED_METHOD_CONTRACT;
        
        _ASSERTE(pOverrideBinder != NULL);
        pOverrideBinder->AddRef();
        m_pFusionContext->Release();
        m_pFusionContext = pOverrideBinder;
    }
    

#ifdef FEATURE_PREJIT
    CorCompileConfigFlags GetNativeConfigFlags();
#endif // FEATURE_PREJIT

    //****************************************************************************************
    // Create a domain context rooted at the fileName. The directory containing the file name
    // is the application base and the configuration file is the fileName appended with
    // .config. If no name is passed in then no domain is created.
    static AppDomain* CreateDomainContext(LPCWSTR fileName);

    // Sets up the current domain's fusion context based on the given exe file name
    // (app base & config file)
    void SetupExecutableFusionContext(LPCWSTR exePath);

    //****************************************************************************************
    // Manage a pool of asyncrhonous objects used to fetch assemblies.  When a sink is released
    // it places itself back on the pool list.  Only one object is kept in the pool.
    void SetIsUserCreatedDomain()
    {
        LIMITED_METHOD_CONTRACT;

        m_dwFlags |= USER_CREATED_DOMAIN;
    }

    BOOL IsUserCreatedDomain()
    {
        LIMITED_METHOD_CONTRACT;

        return (m_dwFlags & USER_CREATED_DOMAIN);
    }

    void SetIgnoreUnhandledExceptions()
    {
        LIMITED_METHOD_CONTRACT;

        m_dwFlags |= IGNORE_UNHANDLED_EXCEPTIONS;
    }

    BOOL IgnoreUnhandledExceptions()
    {
        LIMITED_METHOD_CONTRACT;

        return (m_dwFlags & IGNORE_UNHANDLED_EXCEPTIONS);
    }

    void SetPassiveDomain()
    {
        LIMITED_METHOD_CONTRACT;

        m_dwFlags |= PASSIVE_DOMAIN;
    }

    BOOL IsPassiveDomain()
    {
        LIMITED_METHOD_CONTRACT;

        return (m_dwFlags & PASSIVE_DOMAIN);
    }

    void SetVerificationDomain()
    {
        LIMITED_METHOD_CONTRACT;

        m_dwFlags |= VERIFICATION_DOMAIN;
    }

    BOOL IsVerificationDomain()
    {
        LIMITED_METHOD_CONTRACT;

        return (m_dwFlags & VERIFICATION_DOMAIN);
    }

    void SetIllegalVerificationDomain()
    {
        LIMITED_METHOD_CONTRACT;

        m_dwFlags |= ILLEGAL_VERIFICATION_DOMAIN;
    }

    BOOL IsIllegalVerificationDomain()
    {
        LIMITED_METHOD_CONTRACT;

        return (m_dwFlags & ILLEGAL_VERIFICATION_DOMAIN);
    }

    void SetCompilationDomain()
    {
        LIMITED_METHOD_CONTRACT;

        m_dwFlags |= (PASSIVE_DOMAIN|COMPILATION_DOMAIN);
    }

    BOOL IsCompilationDomain();

    PTR_CompilationDomain ToCompilationDomain()
    {
        LIMITED_METHOD_CONTRACT;

        _ASSERTE(IsCompilationDomain());
        return dac_cast<PTR_CompilationDomain>(this);
    }

    void SetCanUnload()
    {
        LIMITED_METHOD_CONTRACT;

        m_dwFlags |= APP_DOMAIN_CAN_BE_UNLOADED;
    }

    BOOL CanUnload()
    {
        LIMITED_METHOD_CONTRACT;
        STATIC_CONTRACT_SO_TOLERANT;
        return m_dwFlags & APP_DOMAIN_CAN_BE_UNLOADED;
    }

    void SetRemotingConfigured()
    {
        LIMITED_METHOD_CONTRACT;
        STATIC_CONTRACT_SO_TOLERANT;
        FastInterlockOr((ULONG*)&m_dwFlags, REMOTING_CONFIGURED_FOR_DOMAIN);
    }

    BOOL IsRemotingConfigured()
    {
        LIMITED_METHOD_CONTRACT;
        STATIC_CONTRACT_SO_TOLERANT;
        return m_dwFlags & REMOTING_CONFIGURED_FOR_DOMAIN;
    }

    void SetOrphanedLocks()
    {
        LIMITED_METHOD_CONTRACT;
        STATIC_CONTRACT_SO_TOLERANT;
        FastInterlockOr((ULONG*)&m_dwFlags, ORPHANED_LOCKS);
    }

    BOOL HasOrphanedLocks()
    {
        LIMITED_METHOD_CONTRACT;
        STATIC_CONTRACT_SO_TOLERANT;
        return m_dwFlags & ORPHANED_LOCKS;
    }

    // This function is used to relax asserts in the lock accounting.
    // It returns true if we are fine with hosed lock accounting in this domain.
    BOOL OkToIgnoreOrphanedLocks()
    {
        WRAPPER_NO_CONTRACT;
        return HasOrphanedLocks() && m_Stage >= STAGE_UNLOAD_REQUESTED;
    }

    static void ExceptionUnwind(Frame *pFrame);

#ifdef _DEBUG
    void TrackADThreadEnter(Thread *pThread, Frame *pFrame);
    void TrackADThreadExit(Thread *pThread, Frame *pFrame);
    void DumpADThreadTrack();
#endif

#ifndef DACCESS_COMPILE
    void ThreadEnter(Thread *pThread, Frame *pFrame)
    {
        STATIC_CONTRACT_NOTHROW;
        STATIC_CONTRACT_GC_NOTRIGGER;

#ifdef _DEBUG
        if (LoggingOn(LF_APPDOMAIN, LL_INFO100))
            TrackADThreadEnter(pThread, pFrame);
        else
#endif
        {
            InterlockedIncrement((LONG*)&m_dwThreadEnterCount);
            LOG((LF_APPDOMAIN, LL_INFO1000, "AppDomain::ThreadEnter  %p to [%d] (%8.8x) %S count %d\n", 
                 pThread,GetId().m_dwId, this,
                 GetFriendlyNameForLogging(),GetThreadEnterCount()));
#if _DEBUG_AD_UNLOAD
            printf("AppDomain::ThreadEnter %p to [%d] (%8.8x) %S count %d\n",
                   pThread, GetId().m_dwId, this,
                   GetFriendlyNameForLogging(), GetThreadEnterCount());
#endif
        }
    }

    void ThreadExit(Thread *pThread, Frame *pFrame)
    {
        STATIC_CONTRACT_NOTHROW;
        STATIC_CONTRACT_GC_NOTRIGGER;

#ifdef _DEBUG
        if (LoggingOn(LF_APPDOMAIN, LL_INFO100)) {
            TrackADThreadExit(pThread, pFrame);
        }
        else
#endif
        {
            LONG result;
            result = InterlockedDecrement((LONG*)&m_dwThreadEnterCount);
            _ASSERTE(result >= 0);
            LOG((LF_APPDOMAIN, LL_INFO1000, "AppDomain::ThreadExit from [%d] (%8.8x) %S count %d\n",
                 this, GetId().m_dwId,
                 GetFriendlyNameForLogging(), GetThreadEnterCount()));
#if _DEBUG_ADUNLOAD
            printf("AppDomain::ThreadExit %x from [%d] (%8.8x) %S count %d\n",
                   pThread->GetThreadId(), this, GetId().m_dwId,
                   GetFriendlyNameForLogging(), GetThreadEnterCount());
#endif
        }
    }
#endif // DACCESS_COMPILE

    ULONG GetThreadEnterCount()
    {
        LIMITED_METHOD_CONTRACT;
        return m_dwThreadEnterCount;
    }

    BOOL OnlyOneThreadLeft()
    {
        LIMITED_METHOD_CONTRACT;
        return m_dwThreadEnterCount==1 || m_dwThreadsStillInAppDomain ==1;
    }

    Context *GetDefaultContext()
    {
        LIMITED_METHOD_CONTRACT;
        return m_pDefaultContext;
    }

    BOOL CanLoadCode()
    {
        LIMITED_METHOD_CONTRACT;
        return m_Stage >= STAGE_READYFORMANAGEDCODE && m_Stage < STAGE_CLOSED;        
    }

    void SetAnonymouslyHostedDynamicMethodsAssembly(DomainAssembly * pDomainAssembly)
    {
        LIMITED_METHOD_CONTRACT;
        _ASSERTE(pDomainAssembly != NULL);
        _ASSERTE(m_anonymouslyHostedDynamicMethodsAssembly == NULL);
        m_anonymouslyHostedDynamicMethodsAssembly = pDomainAssembly;
    }

    DomainAssembly * GetAnonymouslyHostedDynamicMethodsAssembly()
    {
        LIMITED_METHOD_CONTRACT;
        return m_anonymouslyHostedDynamicMethodsAssembly;
    }

    BOOL HasUnloadStarted()
    {
        LIMITED_METHOD_CONTRACT;
        return m_Stage>=STAGE_EXITED;
    }
    static void RefTakerAcquire(AppDomain* pDomain)
    {
        WRAPPER_NO_CONTRACT;
        if(!pDomain)
            return;
        pDomain->AddRef();
#ifdef _DEBUG
        FastInterlockIncrement(&pDomain->m_dwRefTakers);
#endif
    }

    static void RefTakerRelease(AppDomain* pDomain)
    {
        WRAPPER_NO_CONTRACT;
        if(!pDomain)
            return;
#ifdef _DEBUG
        _ASSERTE(pDomain->m_dwRefTakers);
        FastInterlockDecrement(&pDomain->m_dwRefTakers);
#endif
        pDomain->Release();
    }

#ifdef _DEBUG 

    BOOL IsHeldByIterator()
    {
        LIMITED_METHOD_CONTRACT;
        return m_dwIterHolders>0;
    }

    BOOL IsHeldByRefTaker()
    {
        LIMITED_METHOD_CONTRACT;
        return m_dwRefTakers>0;
    }

    void IteratorRelease()
    {
        LIMITED_METHOD_CONTRACT;
        _ASSERTE(m_dwIterHolders);
        FastInterlockDecrement(&m_dwIterHolders);
    }

      
    void IteratorAcquire()
    {
        LIMITED_METHOD_CONTRACT;
        FastInterlockIncrement(&m_dwIterHolders);
    }
    
#endif    
    BOOL IsActive()
    {
        LIMITED_METHOD_DAC_CONTRACT;

        return m_Stage >= STAGE_ACTIVE && m_Stage < STAGE_CLOSED;
    }
    // Range for normal execution of code in the appdomain, currently used for
    // appdomain resource monitoring since we don't care to update resource usage
    // unless it's in these stages (as fields of AppDomain may not be valid if it's
    // not within these stages)
    BOOL IsUserActive()
    {
        LIMITED_METHOD_DAC_CONTRACT;

        return m_Stage >= STAGE_ACTIVE && m_Stage <= STAGE_OPEN;
    }
    BOOL IsValid()
    {
        LIMITED_METHOD_DAC_CONTRACT;

#ifdef DACCESS_COMPILE
        // We want to see all appdomains in SOS, even the about to be destructed ones.
        // There is no risk of races under DAC, so we will pretend to be unconditionally valid.
        return TRUE;
#else
        return m_Stage > STAGE_CREATING && m_Stage < STAGE_CLOSED;
#endif
    }

#ifdef _DEBUG
    BOOL IsBeingCreated()
    {
        LIMITED_METHOD_CONTRACT;

        return m_dwCreationHolders > 0;
    }

    void IncCreationCount()
    {
        LIMITED_METHOD_CONTRACT;

        FastInterlockIncrement(&m_dwCreationHolders);
        _ASSERTE(m_dwCreationHolders > 0);
    }

    void DecCreationCount()
    {
        LIMITED_METHOD_CONTRACT;

        FastInterlockDecrement(&m_dwCreationHolders);
        _ASSERTE(m_dwCreationHolders > -1);
    }
#endif
    BOOL IsRunningIn(Thread* pThread);

    BOOL IsUnloading()
    {
        LIMITED_METHOD_CONTRACT;
        SUPPORTS_DAC;

        return m_Stage > STAGE_UNLOAD_REQUESTED;
    }

    BOOL NotReadyForManagedCode()
    {
        LIMITED_METHOD_CONTRACT;

        return m_Stage < STAGE_READYFORMANAGEDCODE;
    }

    void SetFinalized()
    {
        LIMITED_METHOD_CONTRACT;
        SetStage(STAGE_FINALIZED);
    }

    BOOL IsFinalizing()
    {
        LIMITED_METHOD_CONTRACT;

        return m_Stage >= STAGE_FINALIZING;
    }

    BOOL IsFinalized()
    {
        LIMITED_METHOD_CONTRACT;

        return m_Stage >= STAGE_FINALIZED;
    }

    BOOL NoAccessToHandleTable()
    {
        LIMITED_METHOD_CONTRACT;
        SUPPORTS_DAC;

        return m_Stage >= STAGE_HANDLETABLE_NOACCESS;
    }

    // Checks whether the given thread can enter the app domain
    BOOL CanThreadEnter(Thread *pThread);

    // Following two are needed for the Holder
    static void SetUnloadInProgress(AppDomain *pThis) PUB;
    static void SetUnloadComplete(AppDomain *pThis) PUB;
    // Predicates for GC asserts
    BOOL ShouldHaveFinalization()
    {
        LIMITED_METHOD_CONTRACT;

        return ((DWORD) m_Stage) < STAGE_COLLECTED;
    }
    BOOL ShouldHaveCode()
    {
        LIMITED_METHOD_CONTRACT;

        return ((DWORD) m_Stage) < STAGE_COLLECTED;
    }
    BOOL ShouldHaveRoots()
    {
        LIMITED_METHOD_CONTRACT;

        return ((DWORD) m_Stage) < STAGE_CLEARED;
    }
    BOOL ShouldHaveInstances()
    {
        LIMITED_METHOD_CONTRACT;

        return ((DWORD) m_Stage) < STAGE_COLLECTED;
    }


    static void RaiseExitProcessEvent();
    Assembly* RaiseResourceResolveEvent(DomainAssembly* pAssembly, LPCSTR szName);
    DomainAssembly* RaiseTypeResolveEventThrowing(DomainAssembly* pAssembly, LPCSTR szName, ASSEMBLYREF *pResultingAssemblyRef);
    Assembly* RaiseAssemblyResolveEvent(AssemblySpec *pSpec, BOOL fIntrospection, BOOL fPreBind);

private:
    CrstExplicitInit    m_ReflectionCrst;
    CrstExplicitInit    m_RefClassFactCrst;


    EEClassFactoryInfoHashTable *m_pRefClassFactHash;   // Hash table that maps a class factory info to a COM comp.
#ifdef FEATURE_COMINTEROP
    DispIDCache *m_pRefDispIDCache;
    COMorRemotingFlag m_COMorRemotingFlag;
    OBJECTHANDLE  m_hndMissing;     //Handle points to Missing.Value Object which is used for [Optional] arg scenario during IDispatch CCW Call

    MethodTable* m_rpCLRTypes[WinMDAdapter::RedirectedTypeIndex_Count];

    MethodTable* LoadRedirectedType(WinMDAdapter::RedirectedTypeIndex index, WinMDAdapter::FrameworkAssemblyIndex assembly);
#endif // FEATURE_COMINTEROP

public:

    CrstBase *GetRefClassFactCrst()
    {
        LIMITED_METHOD_CONTRACT;

        return &m_RefClassFactCrst;
    }

#ifndef DACCESS_COMPILE
    EEClassFactoryInfoHashTable* GetClassFactHash()
    {
        STATIC_CONTRACT_THROWS;
        STATIC_CONTRACT_GC_TRIGGERS;
        STATIC_CONTRACT_FAULT;

        if (m_pRefClassFactHash != NULL) {
            return m_pRefClassFactHash;
        }

        return SetupClassFactHash();
    }
#endif // DACCESS_COMPILE

#ifdef FEATURE_COMINTEROP
    DispIDCache* GetRefDispIDCache()
    {
        STATIC_CONTRACT_THROWS;
        STATIC_CONTRACT_GC_TRIGGERS;
        STATIC_CONTRACT_FAULT;

        if (m_pRefDispIDCache != NULL) {
            return m_pRefDispIDCache;
        }

        return SetupRefDispIDCache();
    }
#endif // FEATURE_COMINTEROP

    PTR_LoaderHeap GetStubHeap();
    PTR_LoaderHeap GetLowFrequencyHeap();
    PTR_LoaderHeap GetHighFrequencyHeap();
    virtual PTR_LoaderAllocator GetLoaderAllocator();

#ifdef FEATURE_APPDOMAIN_RESOURCE_MONITORING
    #define ARM_ETW_ALLOC_THRESHOLD (4 * 1024 * 1024)
    // cache line size in ULONGLONG - 128 bytes which are 16 ULONGLONG's
    #define ARM_CACHE_LINE_SIZE_ULL 16

    inline ULONGLONG GetAllocBytes()
    {
        LIMITED_METHOD_CONTRACT;
        ULONGLONG ullTotalAllocBytes = 0;

        // Ensure that m_pullAllocBytes is non-null to avoid an AV in a race between GC and AD unload.
        // A race can occur when a new appdomain is created, but an OOM is thrown when allocating for m_pullAllocBytes, causing the AD unload.
        if(NULL != m_pullAllocBytes)
        {
            for (DWORD i = 0; i < m_dwNumHeaps; i++)
            {
                ullTotalAllocBytes += m_pullAllocBytes[i * ARM_CACHE_LINE_SIZE_ULL];
            }
        }
        return ullTotalAllocBytes;
    }

    void RecordAllocBytes(size_t allocatedBytes, DWORD dwHeapNumber)
    {
        LIMITED_METHOD_CONTRACT;
        _ASSERTE(dwHeapNumber < m_dwNumHeaps);
        
        // Ensure that m_pullAllocBytes is non-null to avoid an AV in a race between GC and AD unload.
        // A race can occur when a new appdomain is created, but an OOM is thrown when allocating for m_pullAllocBytes, causing the AD unload.
        if(NULL != m_pullAllocBytes)
        {
            m_pullAllocBytes[dwHeapNumber * ARM_CACHE_LINE_SIZE_ULL] += allocatedBytes;
        }

        ULONGLONG ullTotalAllocBytes = GetAllocBytes();

        if ((ullTotalAllocBytes - m_ullLastEtwAllocBytes) >= ARM_ETW_ALLOC_THRESHOLD)
        {
            m_ullLastEtwAllocBytes = ullTotalAllocBytes;
            FireEtwAppDomainMemAllocated((ULONGLONG)this, ullTotalAllocBytes, GetClrInstanceId());
        }
    }

    inline ULONGLONG GetSurvivedBytes()
    {
        LIMITED_METHOD_CONTRACT;
        ULONGLONG ullTotalSurvivedBytes = 0;

        // Ensure that m_pullSurvivedBytes is non-null to avoid an AV in a race between GC and AD unload.
        // A race can occur when a new appdomain is created, but an OOM is thrown when allocating for m_pullSurvivedBytes, causing the AD unload.
        if(NULL != m_pullSurvivedBytes)
        {
            for (DWORD i = 0; i < m_dwNumHeaps; i++)
            {
                ullTotalSurvivedBytes += m_pullSurvivedBytes[i * ARM_CACHE_LINE_SIZE_ULL];
            }
        }
        return ullTotalSurvivedBytes;
    }

    void RecordSurvivedBytes(size_t promotedBytes, DWORD dwHeapNumber)
    {
        WRAPPER_NO_CONTRACT;
        _ASSERTE(dwHeapNumber < m_dwNumHeaps);
   
        // Ensure that m_pullSurvivedBytes is non-null to avoid an AV in a race between GC and AD unload.
        // A race can occur when a new appdomain is created, but an OOM is thrown when allocating for m_pullSurvivedBytes, causing the AD unload.
        if(NULL != m_pullSurvivedBytes)
        {
            m_pullSurvivedBytes[dwHeapNumber * ARM_CACHE_LINE_SIZE_ULL] += promotedBytes;
        }
    }

    inline void ResetSurvivedBytes()
    {
        LIMITED_METHOD_CONTRACT;
        
        // Ensure that m_pullSurvivedBytes is non-null to avoid an AV in a race between GC and AD unload.
        // A race can occur when a new appdomain is created, but an OOM is thrown when allocating for m_pullSurvivedBytes, causing the AD unload.
        if(NULL != m_pullSurvivedBytes)
        {
            for (DWORD i = 0; i < m_dwNumHeaps; i++)
            {
                m_pullSurvivedBytes[i * ARM_CACHE_LINE_SIZE_ULL] = 0;
            }
        }
    }

    // Return the total processor time (user and kernel) used by threads executing in this AppDomain so far.
    // The result is in 100ns units.
    ULONGLONG QueryProcessorUsage();

    // Add to the current count of processor time used by threads within this AppDomain. This API is called by
    // threads transitioning between AppDomains.
    void UpdateProcessorUsage(ULONGLONG ullAdditionalUsage);
#endif //FEATURE_APPDOMAIN_RESOURCE_MONITORING

private:
    static void RaiseOneExitProcessEvent_Wrapper(AppDomainIterator* pi);
    static void RaiseOneExitProcessEvent();
    size_t EstimateSize();
    EEClassFactoryInfoHashTable* SetupClassFactHash();
#ifdef FEATURE_COMINTEROP
    DispIDCache* SetupRefDispIDCache();
    COMorRemotingFlag GetPreferComInsteadOfManagedRemotingFromConfigFile();
#endif // FEATURE_COMINTEROP

    void InitializeDefaultDomainManager ();


    void InitializeDefaultDomainSecurity();
public:

protected:
    BOOL PostBindResolveAssembly(AssemblySpec  *pPrePolicySpec,
                                 AssemblySpec  *pPostPolicySpec,
                                 HRESULT        hrBindResult,
                                 AssemblySpec **ppFailedSpec);

#ifdef FEATURE_COMINTEROP
public:
    void ReleaseRCWs(LPVOID pCtxCookie);
    void DetachRCWs();

protected:
#endif // FEATURE_COMINTEROP

    LPWSTR m_pwDynamicDir;

private:
    void RaiseLoadingAssemblyEvent(DomainAssembly* pAssembly);

    friend class DomainAssembly;

public:
    static void ProcessUnloadDomainEventOnFinalizeThread();
    static BOOL HasWorkForFinalizerThread()
    {
        LIMITED_METHOD_CONTRACT;
        return s_pAppDomainToRaiseUnloadEvent != NULL;
    }

private:
    static AppDomain* s_pAppDomainToRaiseUnloadEvent;
    static BOOL s_fProcessUnloadDomainEvent;

    void RaiseUnloadDomainEvent();
    static void RaiseUnloadDomainEvent_Wrapper(LPVOID /* AppDomain * */);

    BOOL RaiseUnhandledExceptionEvent(OBJECTREF *pSender, OBJECTREF *pThrowable, BOOL isTerminating);
    BOOL HasUnhandledExceptionEventHandler();
    BOOL RaiseUnhandledExceptionEventNoThrow(OBJECTREF *pSender, OBJECTREF *pThrowable, BOOL isTerminating);
    
    struct RaiseUnhandled_Args
    {
        AppDomain *pExceptionDomain;
        AppDomain *pTargetDomain;
        OBJECTREF *pSender;
        OBJECTREF *pThrowable;
        BOOL isTerminating;
        BOOL *pResult;
    };


    static void AllowThreadEntrance(AppDomain *pApp);
    static void RestrictThreadEntrance(AppDomain *pApp);

    typedef Holder<AppDomain*,DoNothing<AppDomain*>,AppDomain::AllowThreadEntrance,NULL> RestrictEnterHolder;
    
    enum Stage {
        STAGE_CREATING,
        STAGE_READYFORMANAGEDCODE,
        STAGE_ACTIVE,
        STAGE_OPEN,
        STAGE_UNLOAD_REQUESTED,
        STAGE_EXITING,
        STAGE_EXITED,
        STAGE_FINALIZING,
        STAGE_FINALIZED,
        STAGE_HANDLETABLE_NOACCESS,
        STAGE_CLEARED,
        STAGE_COLLECTED,
        STAGE_CLOSED
    };
    void SetStage(Stage stage)
    {
        CONTRACTL
        {
            NOTHROW;
            GC_NOTRIGGER;
            SO_TOLERANT;
            MODE_ANY;
        }
        CONTRACTL_END;
        STRESS_LOG2(LF_APPDOMAIN, LL_INFO100,"Updating AD stage, ADID=%d, stage=%d\n",GetId().m_dwId,stage);
        TESTHOOKCALL(AppDomainStageChanged(GetId().m_dwId,m_Stage,stage));
        Stage lastStage=m_Stage;
        while (lastStage !=stage) 
            lastStage = (Stage)FastInterlockCompareExchange((LONG*)&m_Stage,stage,lastStage);
    };
    void Exit(BOOL fRunFinalizers, BOOL fAsyncExit);
    void Close();
    void ClearGCRoots();
    void ClearGCHandles();
    void HandleAsyncPinHandles();
    void UnwindThreads();
    // Return TRUE if EE is stopped
    // Return FALSE if more work is needed
    BOOL StopEEAndUnwindThreads(unsigned int retryCount, BOOL *pFMarkUnloadRequestThread);

    // Use Rude Abort to unload the domain.
    BOOL m_fRudeUnload;

    Thread *m_pUnloadRequestThread;
    ADUnloadSink*   m_ADUnloadSink;
    BOOL  m_bForceGCOnUnload;
    BOOL  m_bUnloadingFromUnloadEvent;
    AppDomainLoaderAllocator m_LoaderAllocator;

    // List of unloaded LoaderAllocators, protected by code:GetLoaderAllocatorReferencesLock (for now)
    LoaderAllocator * m_pDelayedLoaderAllocatorUnloadList;
    
public:
    
    // Register the loader allocator for deletion in code:ShutdownFreeLoaderAllocators.
    void RegisterLoaderAllocatorForDeletion(LoaderAllocator * pLoaderAllocator);
    
    AppDomain * m_pNextInDelayedUnloadList;
    
    void SetForceGCOnUnload(BOOL bSet)
    {
        m_bForceGCOnUnload=bSet;
    }

    void SetUnloadingFromUnloadEvent()
    {
        m_bUnloadingFromUnloadEvent=TRUE;
    }

    BOOL IsUnloadingFromUnloadEvent()
    {
        return m_bUnloadingFromUnloadEvent;
    }
    
    void SetRudeUnload()
    {
        LIMITED_METHOD_CONTRACT;

        m_fRudeUnload = TRUE;
    }

    BOOL IsRudeUnload()
    {
        LIMITED_METHOD_CONTRACT;

        return m_fRudeUnload;
    }

    ADUnloadSink* GetADUnloadSink();
    ADUnloadSink* GetADUnloadSinkForUnload();
    void SetUnloadRequestThread(Thread *pThread)
    {
        LIMITED_METHOD_CONTRACT;

        m_pUnloadRequestThread = pThread;
    }

    Thread *GetUnloadRequestThread()
    {
        LIMITED_METHOD_CONTRACT;

        return m_pUnloadRequestThread;
    }

public:
    void SetGCRefPoint(int gccounter)
    {
        LIMITED_METHOD_CONTRACT;
        m_LoaderAllocator.SetGCRefPoint(gccounter);
    }
    int  GetGCRefPoint()
    {
        LIMITED_METHOD_CONTRACT;
        return m_LoaderAllocator.GetGCRefPoint();
    }

    static USHORT GetOffsetOfId()
    {
        LIMITED_METHOD_CONTRACT;
        size_t ofs = offsetof(class AppDomain, m_dwId);
        _ASSERTE(FitsInI2(ofs));
        return (USHORT)ofs;
    }

    
    void AddMemoryPressure();
    void RemoveMemoryPressure();
    void Unload(BOOL fForceUnload);
    static HRESULT UnloadById(ADID Id, BOOL fSync, BOOL fExceptionsPassThrough=FALSE);
    static HRESULT UnloadWait(ADID Id, ADUnloadSink* pSink);
#ifdef FEATURE_TESTHOOKS        
    static HRESULT UnloadWaitNoCatch(ADID Id, ADUnloadSink* pSink);
#endif
    static void ResetUnloadRequestThread(ADID Id);

    void UnlinkClass(MethodTable *pMT);

    typedef Holder<AppDomain *, AppDomain::SetUnloadInProgress, AppDomain::SetUnloadComplete> UnloadHolder;
    Assembly *GetRootAssembly()
    {
        LIMITED_METHOD_CONTRACT;
        return m_pRootAssembly;
    }

#ifndef DACCESS_COMPILE
    void SetRootAssembly(Assembly *pAssembly)
    {
        LIMITED_METHOD_CONTRACT;
        m_pRootAssembly = pAssembly;
    }
#endif

private:
    SString         m_friendlyName;
    PTR_Assembly    m_pRootAssembly;

    // General purpose flags.
    DWORD           m_dwFlags;

    // When an application domain is created the ref count is artifically incremented
    // by one. For it to hit zero an explicit close must have happened.
    LONG        m_cRef;                    // Ref count.

    PTR_IApplicationSecurityDescriptor m_pSecDesc;  // Application Security Descriptor

    OBJECTHANDLE    m_ExposedObject;

#ifdef FEATURE_LOADER_OPTIMIZATION
    // Indicates where assemblies will be loaded for
    // this domain. By default all assemblies are loaded into the domain.
    // There are two additional settings, all
    // assemblies can be loaded into the shared domain or assemblies
    // that are strong named are loaded into the shared area.
    SharePolicy m_SharePolicy;
#endif

    IUnknown        *m_pComIPForExposedObject;

    // Hash table that maps a clsid to a type
    PtrHashMap          m_clsidHash;

#ifdef FEATURE_COMINTEROP
    // Hash table that maps WinRT class names to MethodTables.
    PTR_NameToTypeMapTable m_pNameToTypeMap;
    UINT                m_vNameToTypeMapVersion;

    UINT                m_nEpoch; // incremented each time m_pNameToTypeMap is enumerated

    // Hash table that remembers the last cached WinRT factory object per type per appdomain.
    WinRTFactoryCache   *m_pWinRTFactoryCache;

    // The wrapper cache for this domain - it has its own CCacheLineAllocator on a per domain basis
    // to allow the domain to go away and eventually kill the memory when all refs are gone
    ComCallWrapperCache *m_pComCallWrapperCache;
    
    // this cache stores the RCWs in this domain
    RCWCache *m_pRCWCache;

    // this cache stores the RCW -> CCW references in this domain
    RCWRefCache *m_pRCWRefCache;
    
    // The method table used for LicenseInteropHelper
    MethodTable*    m_pLicenseInteropHelperMT;
#endif // FEATURE_COMINTEROP

    AssemblySink*      m_pAsyncPool;  // asynchronous retrival object pool (only one is kept)

    // The index of this app domain among existing app domains (starting from 1)
    ADIndex m_dwIndex;

    // The thread-pool index of this app domain among existing app domains (starting from 1)
    TPIndex m_tpIndex;

#ifdef FEATURE_APPDOMAIN_RESOURCE_MONITORING
    ULONGLONG* m_pullAllocBytes;
    ULONGLONG* m_pullSurvivedBytes;
    DWORD m_dwNumHeaps;
    ULONGLONG m_ullLastEtwAllocBytes;
    // Total processor time (user and kernel) utilized by threads running in this AppDomain so far. May not
    // account for threads currently executing in the AppDomain until a call to QueryProcessorUsage() is
    // made.
    Volatile<ULONGLONG> m_ullTotalProcessorUsage;
#endif //FEATURE_APPDOMAIN_RESOURCE_MONITORING

#ifdef _DEBUG
    struct ThreadTrackInfo;
    typedef CDynArray<ThreadTrackInfo *> ThreadTrackInfoList;
    ThreadTrackInfoList *m_pThreadTrackInfoList;
    DWORD m_TrackSpinLock;
#endif


    // IL stub cache with fabricated MethodTable parented by a random module in this AD.
    ILStubCache         m_ILStubCache;

    // U->M thunks created in this domain and not associated with a delegate.
    // The cache is keyed by MethodDesc pointers.
    UMEntryThunkCache *m_pUMEntryThunkCache;

    // The number of  times we have entered this AD
    ULONG m_dwThreadEnterCount;
    // The number of threads that have entered this AD, for ADU only
    ULONG m_dwThreadsStillInAppDomain;

    Volatile<Stage> m_Stage;

    // The default context for this domain
    Context *m_pDefaultContext;

    SString         m_applicationBase;
    SString         m_privateBinPaths;
    SString         m_configFile;

    ArrayList        m_failedAssemblies;

    DomainAssembly * m_anonymouslyHostedDynamicMethodsAssembly;

#ifdef _DEBUG
    Volatile<LONG> m_dwIterHolders;
    Volatile<LONG> m_dwRefTakers;
    Volatile<LONG> m_dwCreationHolders;
#endif

    //
    // DAC iterator for failed assembly loads
    //
    class FailedAssemblyIterator
    {
        ArrayList::Iterator m_i;
        
      public:
        BOOL Next()
        {
            WRAPPER_NO_CONTRACT;
            return m_i.Next();
        }
        FailedAssembly *GetFailedAssembly()
        {
            WRAPPER_NO_CONTRACT;
            return dac_cast<PTR_FailedAssembly>(m_i.GetElement());
        }
        SIZE_T GetIndex()
        {
            WRAPPER_NO_CONTRACT;
            return m_i.GetIndex();
        }

      private:
        friend class AppDomain;
        // Cannot have constructor so this iterator can be used inside a union
        static FailedAssemblyIterator Create(AppDomain *pDomain)
        {
            WRAPPER_NO_CONTRACT;
            FailedAssemblyIterator i;

            i.m_i = pDomain->m_failedAssemblies.Iterate();
            return i;
        }
    };
    friend class FailedAssemblyIterator;

    FailedAssemblyIterator IterateFailedAssembliesEx()
    {
        WRAPPER_NO_CONTRACT;
        return FailedAssemblyIterator::Create(this);
    }

    //---------------------------------------------------------
    // Stub caches for Method stubs
    //---------------------------------------------------------

public:

private:
    Volatile<BOOL> m_fIsBindingModelLocked;
public:
    BOOL IsHostAssemblyResolverInUse();
    BOOL IsBindingModelLocked();
    BOOL LockBindingModel();

    UMEntryThunkCache *GetUMEntryThunkCache();

    ILStubCache* GetILStubCache()
    {
        LIMITED_METHOD_CONTRACT;
        return &m_ILStubCache;
    }

    static AppDomain* GetDomain(ILStubCache* pILStubCache)
    {
        return CONTAINING_RECORD(pILStubCache, AppDomain, m_ILStubCache);
    }

    enum {
        CONTEXT_INITIALIZED =               0x0001,
        USER_CREATED_DOMAIN =               0x0002, // created by call to AppDomain.CreateDomain
        ALLOCATEDCOM =                      0x0008,
        LOAD_SYSTEM_ASSEMBLY_EVENT_SENT =   0x0040,
        REMOTING_CONFIGURED_FOR_DOMAIN =    0x0100,
        COMPILATION_DOMAIN =                0x0400, // Are we ngenning?
        APP_DOMAIN_CAN_BE_UNLOADED =        0x0800, // if need extra bits, can derive this at runtime
        ORPHANED_LOCKS =                    0x1000, // Orphaned locks exist in this appdomain.
        PASSIVE_DOMAIN =                    0x2000, // Can we execute code in this AppDomain
        VERIFICATION_DOMAIN =               0x4000, // This is a verification domain
        ILLEGAL_VERIFICATION_DOMAIN =       0x8000, // This can't be a verification domain
        IGNORE_UNHANDLED_EXCEPTIONS =      0x10000, // AppDomain was created using the APPDOMAIN_IGNORE_UNHANDLED_EXCEPTIONS flag
        ENABLE_PINVOKE_AND_CLASSIC_COMINTEROP    =      0x20000, // AppDomain was created using the APPDOMAIN_ENABLE_PINVOKE_AND_CLASSIC_COMINTEROP flag
        ENABLE_SKIP_PLAT_CHECKS         = 0x200000, // Skip various assembly checks (like platform check)
        ENABLE_ASSEMBLY_LOADFILE        = 0x400000, // Allow Assembly.LoadFile in CoreCLR
        DISABLE_TRANSPARENCY_ENFORCEMENT= 0x800000, // Disable enforcement of security transparency rules
    };

    SecurityContext *m_pSecContext;

    AssemblySpecBindingCache  m_AssemblyCache;
    DomainAssemblyCache       m_UnmanagedCache;
    size_t                    m_MemoryPressure;

    SString m_AppDomainManagerAssembly;
    SString m_AppDomainManagerType;
    BOOL    m_fAppDomainManagerSetInConfig;
    EInitializeNewDomainFlags m_dwAppDomainManagerInitializeDomainFlags;

    ArrayList m_NativeDllSearchDirectories;
    BOOL m_ReversePInvokeCanEnter;
    bool m_ForceTrivialWaitOperations;
    // Section to support AD unload due to escalation
public:
    static void CreateADUnloadWorker();

    static void CreateADUnloadStartEvent();

    static DWORD WINAPI ADUnloadThreadStart(void *args);

    // Default is safe unload with test hook
    void EnableADUnloadWorker();

    // If called to handle stack overflow, we can not set event, since the thread has limit stack.
    void EnableADUnloadWorker(EEPolicy::AppDomainUnloadTypes type, BOOL fHasStack = TRUE);

    static void EnableADUnloadWorkerForThreadAbort();
    static void EnableADUnloadWorkerForFinalizer();
    static void EnableADUnloadWorkerForCollectedADCleanup();

    BOOL IsUnloadRequested()
    {
        LIMITED_METHOD_CONTRACT;

        return (m_Stage == STAGE_UNLOAD_REQUESTED);
    }

    BOOL IsImageFromTrustedPath(PEImage* pImage);
    BOOL IsImageFullyTrusted(PEImage* pImage);

#ifdef FEATURE_TYPEEQUIVALENCE
private:
    VolatilePtr<TypeEquivalenceHashTable> m_pTypeEquivalenceTable;
    CrstExplicitInit m_TypeEquivalenceCrst;
public:
    TypeEquivalenceHashTable * GetTypeEquivalenceCache();
#endif

    private:
    static void ADUnloadWorkerHelper(AppDomain *pDomain);
    static CLREvent * g_pUnloadStartEvent;

#ifdef DACCESS_COMPILE
public:
    virtual void EnumMemoryRegions(CLRDataEnumMemoryFlags flags,
                                   bool enumThis);
#endif

#ifdef FEATURE_MULTICOREJIT

private:
    MulticoreJitManager m_MulticoreJitManager;

public:
    MulticoreJitManager & GetMulticoreJitManager()
    {
        LIMITED_METHOD_CONTRACT;

        return m_MulticoreJitManager;
    }

#endif

#if defined(FEATURE_TIERED_COMPILATION)

public:
    TieredCompilationManager * GetTieredCompilationManager()
    {
        LIMITED_METHOD_CONTRACT;
        return &m_tieredCompilationManager;
    }

private:
    TieredCompilationManager m_tieredCompilationManager;

public:
    CallCounter * GetCallCounter()
    {
        LIMITED_METHOD_CONTRACT;
        return &m_callCounter;
    }

private:
    CallCounter m_callCounter;
#endif

#ifdef FEATURE_COMINTEROP

private:

#endif //FEATURE_COMINTEROP

public:

private:
    // This is the root-level default load context root binder. If null, then
    // the Fusion binder is used; otherwise this binder is used.
    ReleaseHolder<ICLRPrivBinder> m_pLoadContextHostBinder;

    // -------------------------
    // IMPORTANT!
    // The shared and designer context binders are ONLY to be used in tool
    // scenarios. There are known issues where use of these binders will
    // cause application crashes, and interesting behaviors.
    // -------------------------
    
    // This is the default designer shared context root binder.
    // This is used as the parent binder for ImmersiveDesignerContextBinders
    ReleaseHolder<ICLRPrivBinder> m_pSharedContextHostBinder;

    // This is the current context root binder.
    // Normally, this variable is immutable for appdomain lifetime, but in designer scenarios
    // it may be replaced by designer context binders
    Volatile<ICLRPrivBinder *>    m_pCurrentContextHostBinder;

public:
    // Returns the current hosted binder, or null if none available.
    inline
    ICLRPrivBinder * GetCurrentLoadContextHostBinder() const
    {
        LIMITED_METHOD_CONTRACT;
        return m_pCurrentContextHostBinder;
    }

    // Returns the shared context binder, or null if none available.
    inline
    ICLRPrivBinder * GetSharedContextHostBinder() const
    {
        LIMITED_METHOD_CONTRACT;
        return m_pSharedContextHostBinder;
    }

    // Returns the load context binder, or null if none available.
    inline
    ICLRPrivBinder * GetLoadContextHostBinder() const
    {
        LIMITED_METHOD_CONTRACT;
        return m_pLoadContextHostBinder;
    }

#ifndef DACCESS_COMPILE

    // This is only called from the ImmersiveDesignerContext code
    // It is protected with a managed monitor lock
    inline
    void SetSharedContextHostBinder(ICLRPrivBinder * pBinder)
    {
        LIMITED_METHOD_CONTRACT;
        pBinder->AddRef();
        m_pSharedContextHostBinder = pBinder;
    }

    // This is called from CorHost2's implementation of ICLRPrivRuntime::CreateAppDomain.
    // Should only be called during AppDomain creation.
    inline
    void SetLoadContextHostBinder(ICLRPrivBinder * pBinder)
    {
        LIMITED_METHOD_CONTRACT;
        pBinder->AddRef();
        m_pLoadContextHostBinder = m_pCurrentContextHostBinder = pBinder;
    }

    inline
    void SetCurrentContextHostBinder(ICLRPrivBinder * pBinder)
    {
        CONTRACTL
        {
            THROWS;
            GC_TRIGGERS;
        }
        CONTRACTL_END;

        LockHolder lh(this);

#ifdef FEATURE_COMINTEROP
        if (m_pNameToTypeMap != nullptr)
        {
            delete m_pNameToTypeMap;
            m_pNameToTypeMap = nullptr;
        }

        m_vNameToTypeMapVersion++;
#endif

        m_pCurrentContextHostBinder = pBinder;
    }

#endif // DACCESS_COMPILE

    // Indicates that a hosted binder is present.
    inline
    bool HasLoadContextHostBinder()
    {
        LIMITED_METHOD_CONTRACT;
        return m_pLoadContextHostBinder != nullptr;
    }

    class ComInterfaceReleaseList
    {
        SArray<IUnknown *> m_objects;
    public:
        ~ComInterfaceReleaseList()
        {
            WRAPPER_NO_CONTRACT;

            for (COUNT_T i = 0; i < m_objects.GetCount(); i++)
            {
                IUnknown *pItf = *(m_objects.GetElements() + i);
                if (pItf != nullptr)
                    pItf->Release();
            }
        }

        // Append to the list of object to free. Only use under the AppDomain "LockHolder(pAppDomain)"
        void Append(IUnknown *pInterfaceToRelease)
        {
            WRAPPER_NO_CONTRACT;
            m_objects.Append(pInterfaceToRelease);
        }
    } AppDomainInterfaceReleaseList;

private:
    //-----------------------------------------------------------
    // Static ICLRPrivAssembly -> DomainAssembly mapping functions.
    // This map does not maintain a reference count to either key or value.
    // PEFile maintains a reference count on the ICLRPrivAssembly through its code:PEFile::m_pHostAssembly field.
    // It is removed from this hash table by code:DomainAssembly::~DomainAssembly.
    struct HostAssemblyHashTraits : public DefaultSHashTraits<PTR_DomainAssembly>
    {
    public:
        typedef PTR_ICLRPrivAssembly key_t;
        
        static key_t GetKey(element_t const & elem)
        {
            STATIC_CONTRACT_WRAPPER;
            return elem->GetFile()->GetHostAssembly();
        }
        
        static BOOL Equals(key_t key1, key_t key2) 
        {
            LIMITED_METHOD_CONTRACT;
            return dac_cast<TADDR>(key1) == dac_cast<TADDR>(key2);
        }
        
        static count_t Hash(key_t key)
        {
            STATIC_CONTRACT_LIMITED_METHOD;
            //return reinterpret_cast<count_t>(dac_cast<TADDR>(key));
            return (count_t)(dac_cast<TADDR>(key));
        }
        
        static const element_t Null() { return NULL; }
        static const element_t Deleted() { return (element_t)(TADDR)-1; }
        static bool IsNull(const element_t & e) { return e == NULL; }
        static bool IsDeleted(const element_t & e) { return dac_cast<TADDR>(e) == (TADDR)-1; }
    };

    struct OriginalFileHostAssemblyHashTraits : public HostAssemblyHashTraits
    {
    public:
        static key_t GetKey(element_t const & elem)
        {
            STATIC_CONTRACT_WRAPPER;
            return elem->GetOriginalFile()->GetHostAssembly();
        }
    };
    
    typedef SHash<HostAssemblyHashTraits> HostAssemblyMap;
    typedef SHash<OriginalFileHostAssemblyHashTraits> OriginalFileHostAssemblyMap;
    HostAssemblyMap   m_hostAssemblyMap;
    OriginalFileHostAssemblyMap   m_hostAssemblyMapForOrigFile;
    CrstExplicitInit  m_crstHostAssemblyMap;
    // Lock to serialize all Add operations (in addition to the "read-lock" above)
    CrstExplicitInit  m_crstHostAssemblyMapAdd;

public:
    // Returns DomainAssembly.
    PTR_DomainAssembly FindAssembly(PTR_ICLRPrivAssembly pHostAssembly);
    
#ifndef DACCESS_COMPILE
private:
    friend void DomainAssembly::Allocate();
    friend DomainAssembly::~DomainAssembly();

    // Called from DomainAssembly::Begin.
    void PublishHostedAssembly(
        DomainAssembly* pAssembly);

    // Called from DomainAssembly::UpdatePEFile.
    void UpdatePublishHostedAssembly(
        DomainAssembly* pAssembly,
        PTR_PEFile pFile);

    // Called from DomainAssembly::~DomainAssembly
    void UnPublishHostedAssembly(
        DomainAssembly* pAssembly);
#endif // DACCESS_COMPILE

#ifdef FEATURE_PREJIT
    friend void DomainFile::InsertIntoDomainFileWithNativeImageList();
    Volatile<DomainFile *> m_pDomainFileWithNativeImageList;
public:
    DomainFile *GetDomainFilesWithNativeImagesList()
    {
        LIMITED_METHOD_CONTRACT;
        return m_pDomainFileWithNativeImageList;
    }
#endif
};  // class AppDomain


// This holder is to be used to take a reference to make sure AppDomain* is still valid
// Please do not use if you are aleady ADU-safe
typedef Wrapper<AppDomain*,AppDomain::RefTakerAcquire,AppDomain::RefTakerRelease,NULL> AppDomainRefTaker;

// Just a ref holder
typedef ReleaseHolder<AppDomain> AppDomainRefHolder;

// This class provides a way to access AppDomain by ID
// without risking the appdomain getting invalid in the process
class AppDomainFromIDHolder
{
public:
    enum SyncType  
    {
        SyncType_GC,     // Prevents AD from being unloaded by forbidding GC for the lifetime of the object
        SyncType_ADLock  // Prevents AD from being unloaded by requiring ownership of DomainLock for the lifetime of the object
    };
protected:    
    AppDomain* m_pDomain;
#ifdef _DEBUG    
    BOOL       m_bAcquired;
    BOOL       m_bChecked;
    SyncType   m_type;
#endif
public:
    DEBUG_NOINLINE AppDomainFromIDHolder(ADID adId, BOOL bUnsafePoint, SyncType synctype=SyncType_GC);
    DEBUG_NOINLINE AppDomainFromIDHolder(SyncType synctype=SyncType_GC);
    DEBUG_NOINLINE ~AppDomainFromIDHolder();

	void* GetAddress() { return m_pDomain; } 	// Used to get an identfier for ETW
    void Assign(ADID adId, BOOL bUnsafePoint);
    void ThrowIfUnloaded();
    void Release();
    BOOL IsUnloaded() 
    {
        LIMITED_METHOD_CONTRACT;
#ifdef _DEBUG
        m_bChecked=TRUE; 
        if (m_pDomain==NULL)
        {
            // no need to enforce anything
            Release(); 
        }
#endif
        return m_pDomain==NULL;
    };
    AppDomain* operator->();
};  // class AppDomainFromIDHolder



typedef VPTR(class SystemDomain) PTR_SystemDomain;

class SystemDomain : public BaseDomain
{
    friend class AppDomainNative;
    friend class AppDomainIterator;
    friend class UnsafeAppDomainIterator;
    friend class ClrDataAccess;
    friend class AppDomainFromIDHolder;
    friend Frame *Thread::IsRunningIn(AppDomain* pDomain, int *count);

    VPTR_VTABLE_CLASS(SystemDomain, BaseDomain)
    VPTR_UNIQUE(VPTR_UNIQUE_SystemDomain)
    static AppDomain *GetAppDomainAtId(ADID indx);

public:  
    static PTR_LoaderAllocator GetGlobalLoaderAllocator();
    virtual PTR_LoaderAllocator GetLoaderAllocator() { WRAPPER_NO_CONTRACT; return GetGlobalLoaderAllocator(); }
    static AppDomain* GetAppDomainFromId(ADID indx,DWORD ADValidityKind)
    {
        CONTRACTL
        {
            NOTHROW;
            GC_NOTRIGGER;
            MODE_COOPERATIVE;
        }
        CONTRACTL_END;
        AppDomain* pRetVal;
        if (indx.m_dwId==DefaultADID)
            pRetVal= SystemDomain::System()->DefaultDomain();
        else
            pRetVal= GetAppDomainAtId(indx);
#ifdef _DEBUG
        // Only call CheckADValidity in DEBUG builds for non-NULL return values
        if (pRetVal != NULL)
            CheckADValidity(pRetVal, ADValidityKind);
#endif        
        return pRetVal;
    }
    //****************************************************************************************
    //
    // To be run during the initial start up of the EE. This must be
    // performed prior to any class operations.
    static void Attach();

    //****************************************************************************************
    //
    // To be run during shutdown. This must be done after all operations
    // that require the use of system classes (i.e., exceptions).
    // DetachBegin stops all domains, while DetachEnd deallocates domain resources.
    static void DetachBegin();

    //****************************************************************************************
    //
    // To be run during shutdown. This must be done after all operations
    // that require the use of system classes (i.e., exceptions).
    // DetachBegin stops release resources held by systemdomain and the default domain.
    static void DetachEnd();

    //****************************************************************************************
    //
    // Initializes and shutdowns the single instance of the SystemDomain
    // in the EE
#ifndef DACCESS_COMPILE
    void *operator new(size_t size, void *pInPlace);
    void operator delete(void *pMem);
#endif
    void Init();
    void Stop();
    void Terminate();
    static void LazyInitGlobalStringLiteralMap();

    //****************************************************************************************
    //
    // Load the base system classes, these classes are required before
    // any other classes are loaded
    void LoadBaseSystemClasses();

    AppDomain* DefaultDomain()
    {
        LIMITED_METHOD_DAC_CONTRACT;

        return m_pDefaultDomain;
    }

    // Notification when an assembly is loaded into the system domain
    void OnAssemblyLoad(Assembly *assem);

    //****************************************************************************************
    //
    // Global Static to get the one and only system domain
    static SystemDomain * System()
    {
        LIMITED_METHOD_DAC_CONTRACT;

        return m_pSystemDomain;
    }

    static PEAssembly* SystemFile()
    {
        WRAPPER_NO_CONTRACT;

        _ASSERTE(m_pSystemDomain);
        return System()->m_pSystemFile;
    }

    static Assembly* SystemAssembly()
    {
        WRAPPER_NO_CONTRACT;

        return System()->m_pSystemAssembly;
    }

    static Module* SystemModule()
    {
        WRAPPER_NO_CONTRACT;

        return SystemAssembly()->GetManifestModule();
    }

    static BOOL IsSystemLoaded()
    {
        WRAPPER_NO_CONTRACT;

        return System()->m_pSystemAssembly != NULL;
    }

#ifndef DACCESS_COMPILE
    static GlobalStringLiteralMap *GetGlobalStringLiteralMap()
    {
        WRAPPER_NO_CONTRACT;

        if (m_pGlobalStringLiteralMap == NULL)
        {
            SystemDomain::LazyInitGlobalStringLiteralMap();
        }
        _ASSERTE(m_pGlobalStringLiteralMap);
        return m_pGlobalStringLiteralMap;
    }
    static GlobalStringLiteralMap *GetGlobalStringLiteralMapNoCreate()
    {
        LIMITED_METHOD_CONTRACT;

        _ASSERTE(m_pGlobalStringLiteralMap);
        return m_pGlobalStringLiteralMap;
    }
#endif // DACCESS_COMPILE

    static void ActivateApplication(int *pReturnValue);

    static void InitializeDefaultDomain(BOOL allowRedirects, ICLRPrivBinder * pBinder = NULL);
    static void SetupDefaultDomain();
    static HRESULT SetupDefaultDomainNoThrow();

#if defined(FEATURE_COMINTEROP_APARTMENT_SUPPORT) && !defined(CROSSGEN_COMPILE)
    static Thread::ApartmentState GetEntryPointThreadAptState(IMDInternalImport* pScope, mdMethodDef mdMethod);
    static void SetThreadAptState(IMDInternalImport* pScope, Thread::ApartmentState state);
#endif
    static BOOL SetGlobalSharePolicyUsingAttribute(IMDInternalImport* pScope, mdMethodDef mdMethod);


    //****************************************************************************************
    //
    // Use an already exising & inited Application Domain (e.g. a subclass).
    static void LoadDomain(AppDomain     *pDomain);

#ifndef DACCESS_COMPILE
    static void MakeUnloadable(AppDomain* pApp)
    {
        WRAPPER_NO_CONTRACT;
        System()->AddDomain(pApp);
        pApp->SetCanUnload();
    }
#endif // DACCESS_COMPILE

    //****************************************************************************************
    // Methods used to get the callers module and hence assembly and app domain.
    __declspec(deprecated("This method is deprecated, use the version that takes a StackCrawlMark instead"))
    static Module* GetCallersModule(int skip);
    static MethodDesc* GetCallersMethod(StackCrawlMark* stackMark, AppDomain **ppAppDomain = NULL);
    static MethodTable* GetCallersType(StackCrawlMark* stackMark, AppDomain **ppAppDomain = NULL);
    static Module* GetCallersModule(StackCrawlMark* stackMark, AppDomain **ppAppDomain = NULL);
    static Assembly* GetCallersAssembly(StackCrawlMark* stackMark, AppDomain **ppAppDomain = NULL);

    static bool IsReflectionInvocationMethod(MethodDesc* pMeth);

#ifndef DACCESS_COMPILE
    //****************************************************************************************
    // Returns the domain associated with the current context. (this can only be a child domain)
    static inline AppDomain * GetCurrentDomain()
    {
        WRAPPER_NO_CONTRACT;
        return ::GetAppDomain();
    }
#endif //!DACCESS_COMPILE

#ifdef DEBUGGING_SUPPORTED
    //****************************************************************************************
    // Debugger/Publisher helper function to indicate creation of new app domain to debugger
    // and publishing it in the IPC block
    static void PublishAppDomainAndInformDebugger (AppDomain *pDomain);
#endif // DEBUGGING_SUPPORTED

    //****************************************************************************************
    // Helper function to remove a domain from the system
    BOOL RemoveDomain(AppDomain* pDomain); // Does not decrement the reference

#ifdef PROFILING_SUPPORTED
    //****************************************************************************************
    // Tell profiler about system created domains which are created before the profiler is
    // actually activated.
    static void NotifyProfilerStartup();

    //****************************************************************************************
    // Tell profiler at shutdown that system created domains are going away.  They are not
    // torn down using the normal sequence.
    static HRESULT NotifyProfilerShutdown();
#endif // PROFILING_SUPPORTED

    //****************************************************************************************
    // return the dev path

#ifndef DACCESS_COMPILE
    void IncrementNumAppDomains ()
    {
        LIMITED_METHOD_CONTRACT;

        s_dNumAppDomains++;
    }

    void DecrementNumAppDomains ()
    {
        LIMITED_METHOD_CONTRACT;

        s_dNumAppDomains--;
    }

    ULONG GetNumAppDomains ()
    {
        LIMITED_METHOD_CONTRACT;

        return s_dNumAppDomains;
    }
#endif // DACCESS_COMPILE

    //
    // AppDomains currently have both an index and an ID.  The
    // index is "densely" assigned; indices are reused as domains
    // are unloaded.  The Id's on the other hand, are not reclaimed
    // so may be sparse.
    //
    // Another important difference - it's OK to call GetAppDomainAtId for
    // an unloaded domain (it will return NULL), while GetAppDomainAtIndex
    // will assert if the domain is unloaded.
    //<TODO>
    // @todo:
    // I'm not really happy with this situation, but
    //  (a) we need an ID for a domain which will last the process lifetime for the
    //      remoting code.
    //  (b) we need a dense ID, for the handle table index.
    // So for now, I'm leaving both, but hopefully in the future we can come up
    // with something better.
    //</TODO>

    static ADIndex GetNewAppDomainIndex(AppDomain * pAppDomain);
    static void ReleaseAppDomainIndex(ADIndex indx);
    static PTR_AppDomain GetAppDomainAtIndex(ADIndex indx);
    static PTR_AppDomain TestGetAppDomainAtIndex(ADIndex indx);
    static DWORD GetCurrentAppDomainMaxIndex()
    {
        WRAPPER_NO_CONTRACT;

        ArrayListStatic* list = (ArrayListStatic *)&m_appDomainIndexList;
        PREFIX_ASSUME(list!=NULL);
        return list->GetCount();
    }

    static ADID GetNewAppDomainId(AppDomain *pAppDomain);
    static void ReleaseAppDomainId(ADID indx);
    
#ifndef DACCESS_COMPILE
    static ADID GetCurrentAppDomainMaxId() { ADID id; id.m_dwId=m_appDomainIdList.GetCount(); return id;}
#endif // DACCESS_COMPILE


#ifndef DACCESS_COMPILE
    DWORD RequireAppDomainCleanup()
    {
        LIMITED_METHOD_CONTRACT;
        return m_pDelayedUnloadList != 0 || m_pDelayedUnloadListOfLoaderAllocators != 0;
    }

    void AddToDelayedUnloadList(AppDomain* pDomain, BOOL bAsync)
    {
        CONTRACTL
        {
            NOTHROW;
            GC_NOTRIGGER;
            MODE_COOPERATIVE;
        }
        CONTRACTL_END;
        m_UnloadIsAsync = bAsync;
        
        CrstHolder lh(&m_DelayedUnloadCrst);
        pDomain->m_pNextInDelayedUnloadList=m_pDelayedUnloadList;
        m_pDelayedUnloadList=pDomain;
        if (m_UnloadIsAsync)
        {
            pDomain->AddRef();
            int iGCRefPoint=GCHeapUtilities::GetGCHeap()->CollectionCount(GCHeapUtilities::GetGCHeap()->GetMaxGeneration());
            if (GCHeapUtilities::IsGCInProgress())
                iGCRefPoint++;
            pDomain->SetGCRefPoint(iGCRefPoint);
        }
    }

    void AddToDelayedUnloadList(LoaderAllocator * pAllocator)
    {
        CONTRACTL
        {
            NOTHROW;
            GC_NOTRIGGER;
            MODE_COOPERATIVE;
        }
        CONTRACTL_END;

        CrstHolder lh(&m_DelayedUnloadCrst);
        pAllocator->m_pLoaderAllocatorDestroyNext=m_pDelayedUnloadListOfLoaderAllocators;
        m_pDelayedUnloadListOfLoaderAllocators=pAllocator;

        int iGCRefPoint=GCHeapUtilities::GetGCHeap()->CollectionCount(GCHeapUtilities::GetGCHeap()->GetMaxGeneration());
        if (GCHeapUtilities::IsGCInProgress())
            iGCRefPoint++;
        pAllocator->SetGCRefPoint(iGCRefPoint);
    }

    void ClearCollectedDomains();
    void ProcessClearingDomains();
    void ProcessDelayedUnloadDomains();
    
    static void SetUnloadInProgress(AppDomain *pDomain)
    {
        WRAPPER_NO_CONTRACT;

        _ASSERTE(m_pAppDomainBeingUnloaded == NULL);
        m_pAppDomainBeingUnloaded = pDomain;
        m_dwIndexOfAppDomainBeingUnloaded = pDomain->GetIndex();
    }

    static void SetUnloadDomainCleared()
    {
        LIMITED_METHOD_CONTRACT;

        // about to delete, so clear this pointer so nobody uses it
        m_pAppDomainBeingUnloaded = NULL;
    }
    static void SetUnloadComplete()
    {
        LIMITED_METHOD_CONTRACT;

        // should have already cleared the AppDomain* prior to delete
        // either we succesfully unloaded and cleared or we failed and restored the ID
        _ASSERTE(m_pAppDomainBeingUnloaded == NULL && m_dwIndexOfAppDomainBeingUnloaded.m_dwIndex != 0
            || m_pAppDomainBeingUnloaded && SystemDomain::GetAppDomainAtId(m_pAppDomainBeingUnloaded->GetId()) != NULL);
        m_pAppDomainBeingUnloaded = NULL;
        m_pAppDomainUnloadingThread = NULL;
    }

    static AppDomain *AppDomainBeingUnloaded()
    {
        LIMITED_METHOD_CONTRACT;
        return m_pAppDomainBeingUnloaded;
    }

    static ADIndex IndexOfAppDomainBeingUnloaded()
    {
        LIMITED_METHOD_CONTRACT;
        return m_dwIndexOfAppDomainBeingUnloaded;
    }

    static void SetUnloadRequestingThread(Thread *pRequestingThread)
    {
        LIMITED_METHOD_CONTRACT;
        m_pAppDomainUnloadRequestingThread = pRequestingThread;
    }

    static Thread *GetUnloadRequestingThread()
    {
        LIMITED_METHOD_CONTRACT;
        return m_pAppDomainUnloadRequestingThread;
    }

    static void SetUnloadingThread(Thread *pUnloadingThread)
    {
        LIMITED_METHOD_CONTRACT;
        m_pAppDomainUnloadingThread = pUnloadingThread;
    }

    static Thread *GetUnloadingThread()
    {
        LIMITED_METHOD_CONTRACT;
        return m_pAppDomainUnloadingThread;
    }

    static void EnumAllStaticGCRefs(promote_func* fn, ScanContext* sc);

#endif // DACCESS_COMPILE

#ifdef FEATURE_APPDOMAIN_RESOURCE_MONITORING
    // The *AD* methods are what we got from tracing through EE roots.
    // RecordTotalSurvivedBytes is the total promoted from a GC.
    static void ResetADSurvivedBytes();
    static ULONGLONG GetADSurvivedBytes();
    static void RecordTotalSurvivedBytes(size_t totalSurvivedBytes);
    static ULONGLONG GetTotalSurvivedBytes()
    {
        LIMITED_METHOD_CONTRACT;
        return m_totalSurvivedBytes;
    }
#endif //FEATURE_APPDOMAIN_RESOURCE_MONITORING

    //****************************************************************************************
    // Routines to deal with the base library (currently mscorlib.dll)
    LPCWSTR BaseLibrary()
    {
        WRAPPER_NO_CONTRACT;

        return m_BaseLibrary;
    }

#ifndef DACCESS_COMPILE
    BOOL IsBaseLibrary(SString &path)
    {
        WRAPPER_NO_CONTRACT;

        // See if it is the installation path to mscorlib
        if (path.EqualsCaseInsensitive(m_BaseLibrary, PEImage::GetFileSystemLocale()))
            return TRUE;

        // Or, it might be the GAC location of mscorlib
        if (System()->SystemAssembly() != NULL
            && path.EqualsCaseInsensitive(System()->SystemAssembly()->GetManifestFile()->GetPath(),
                                          PEImage::GetFileSystemLocale()))
            return TRUE;

        return FALSE;
    }

    BOOL IsBaseLibrarySatellite(SString &path)
    {
        WRAPPER_NO_CONTRACT;

        // See if it is the installation path to mscorlib.resources
        SString s(SString::Ascii,g_psBaseLibrarySatelliteAssemblyName);
        if (path.EqualsCaseInsensitive(s, PEImage::GetFileSystemLocale()))
            return TRUE;

        // workaround!  Must implement some code to do this string comparison for
        // mscorlib.resources in a culture-specific directory in the GAC.

        /*
        // Or, it might be the GAC location of mscorlib.resources
        if (System()->SystemAssembly() != NULL
            && path.EqualsCaseInsensitive(System()->SystemAssembly()->GetManifestFile()->GetPath(),
                                          PEImage::GetFileSystemLocale()))
            return TRUE;
        */

        return FALSE;
    }
#endif // DACCESS_COMPILE

    // Return the system directory
    LPCWSTR SystemDirectory()
    {
        WRAPPER_NO_CONTRACT;

        return m_SystemDirectory;
    }

private:

    //****************************************************************************************
    // Helper function to create the single COM domain
    void CreateDefaultDomain();

    //****************************************************************************************
    // Helper function to add a domain to the global list
    void AddDomain(AppDomain* pDomain);

    void CreatePreallocatedExceptions();

    void PreallocateSpecialObjects();

    //****************************************************************************************
    //
    static StackWalkAction CallersMethodCallback(CrawlFrame* pCrawlFrame, VOID* pClientData);
    static StackWalkAction CallersMethodCallbackWithStackMark(CrawlFrame* pCrawlFrame, VOID* pClientData);

#ifndef DACCESS_COMPILE
    // This class is not to be created through normal allocation.
    SystemDomain() 
    {
        STANDARD_VM_CONTRACT;

        m_pDefaultDomain = NULL;
        m_pDelayedUnloadList=NULL;
        m_pDelayedUnloadListOfLoaderAllocators=NULL;
        m_UnloadIsAsync = FALSE;

        m_GlobalAllocator.Init(this);
    }
#endif

    PTR_PEAssembly  m_pSystemFile;      // Single assembly (here for quicker reference);
    PTR_Assembly    m_pSystemAssembly;  // Single assembly (here for quicker reference);
    PTR_AppDomain   m_pDefaultDomain;   // Default domain for COM+ classes exposed through IClassFactory.

    GlobalLoaderAllocator m_GlobalAllocator;


    InlineSString<100>  m_BaseLibrary;

    InlineSString<100>  m_SystemDirectory;


    LPWSTR      m_pwDevpath;
    DWORD       m_dwDevpath;
    BOOL        m_fDevpath;  // have we searched the environment

    // <TODO>@TODO: CTS, we can keep the com modules in a single assembly or in different assemblies.
    // We are currently using different assemblies but this is potentitially to slow...</TODO>

    // Global domain that every one uses
    SPTR_DECL(SystemDomain, m_pSystemDomain);

    AppDomain* m_pDelayedUnloadList;
    BOOL m_UnloadIsAsync;

    LoaderAllocator * m_pDelayedUnloadListOfLoaderAllocators;

#ifdef FEATURE_APPDOMAIN_RESOURCE_MONITORING
    // This is what gets promoted for the whole GC heap.
    static size_t m_totalSurvivedBytes;
#endif //FEATURE_APPDOMAIN_RESOURCE_MONITORING

    SVAL_DECL(ArrayListStatic, m_appDomainIndexList);
#ifndef DACCESS_COMPILE
    static CrstStatic m_DelayedUnloadCrst;
    static CrstStatic       m_SystemDomainCrst;


    static ArrayListStatic  m_appDomainIdList;

    // only one ad can be unloaded at a time
    static AppDomain*   m_pAppDomainBeingUnloaded;
    // need this so can determine AD being unloaded after it has been deleted
    static ADIndex      m_dwIndexOfAppDomainBeingUnloaded;

    // if had to spin off a separate thread to do the unload, this is the original thread.
    // allows us to delay aborting it until it's the last one so that it can receive
    // notification of an unload failure
    static Thread *m_pAppDomainUnloadRequestingThread;

    // this is the thread doing the actual unload. He's allowed to enter the domain
    // even if have started unloading.
    static Thread *m_pAppDomainUnloadingThread;

    static GlobalStringLiteralMap *m_pGlobalStringLiteralMap;

    static ULONG       s_dNumAppDomains;  // Maintain a count of children app domains.

    static DWORD        m_dwLowestFreeIndex;
#endif // DACCESS_COMPILE

protected:

    // These flags let the correct native image of mscorlib to be loaded.
    // This is important for hardbinding to it

    SVAL_DECL(BOOL, s_fForceDebug);
    SVAL_DECL(BOOL, s_fForceProfiling);
    SVAL_DECL(BOOL, s_fForceInstrument);

public:
    static void     SetCompilationOverrides(BOOL fForceDebug,
                                            BOOL fForceProfiling,
                                            BOOL fForceInstrument);

    static void     GetCompilationOverrides(BOOL * fForceDebug,
                                            BOOL * fForceProfiling,
                                            BOOL * fForceInstrument);
public:
    //****************************************************************************************
    //

#ifndef DACCESS_COMPILE
#ifdef _DEBUG
inline static BOOL IsUnderDomainLock() { LIMITED_METHOD_CONTRACT; return m_SystemDomainCrst.OwnedByCurrentThread();};
#endif

    // This lock controls adding and removing domains from the system domain
    class LockHolder : public CrstHolder
    {
    public:
        LockHolder()
            : CrstHolder(&m_SystemDomainCrst)
        {
            WRAPPER_NO_CONTRACT;
        }
    };
#endif // DACCESS_COMPILE

public:
    DWORD GetTotalNumSizedRefHandles();

#ifdef DACCESS_COMPILE
public:
    virtual void EnumMemoryRegions(CLRDataEnumMemoryFlags flags,
                                   bool enumThis);
#endif

};  // class SystemDomain


//
// an UnsafeAppDomainIterator is used to iterate over all existing domains
//
// The iteration is guaranteed to include all domains that exist at the
// start & end of the iteration. This iterator is considered unsafe because it does not
// reference count the various appdomains, and can only be used when the runtime is stopped,
// or external synchronization is used. (and therefore no other thread may cause the appdomain list to change.)
//
class UnsafeAppDomainIterator
{
    friend class SystemDomain;
public:
    UnsafeAppDomainIterator(BOOL bOnlyActive)
    {
        m_bOnlyActive = bOnlyActive;
    }

    void Init()
    {
        LIMITED_METHOD_CONTRACT;
        SystemDomain* sysDomain = SystemDomain::System();
        if (sysDomain)
        {
            ArrayListStatic* list = &sysDomain->m_appDomainIndexList;
            PREFIX_ASSUME(list != NULL);
            m_i = list->Iterate();
        }
        else
        {
            m_i.SetEmpty();
        }

        m_pCurrent = NULL;
    }

    BOOL Next()
    {
        WRAPPER_NO_CONTRACT;

        while (m_i.Next())
        {
            m_pCurrent = dac_cast<PTR_AppDomain>(m_i.GetElement());
            if (m_pCurrent != NULL &&
                (m_bOnlyActive ?
                 m_pCurrent->IsActive() : m_pCurrent->IsValid()))
            {
                return TRUE;
            }
        }

        m_pCurrent = NULL;
        return FALSE;
    }

    AppDomain * GetDomain()
    {
        LIMITED_METHOD_DAC_CONTRACT;

        return m_pCurrent;
    }

  private:

    ArrayList::Iterator m_i;
    AppDomain *         m_pCurrent;
    BOOL                m_bOnlyActive;
};  // class UnsafeAppDomainIterator

//
// an AppDomainIterator is used to iterate over all existing domains.
//
// The iteration is guaranteed to include all domains that exist at the
// start & end of the iteration.  Any domains added or deleted during
// iteration may or may not be included.  The iterator also guarantees
// that the current iterated appdomain (GetDomain()) will not be deleted.
//

class AppDomainIterator : public UnsafeAppDomainIterator
{
    friend class SystemDomain;

  public:
    AppDomainIterator(BOOL bOnlyActive) : UnsafeAppDomainIterator(bOnlyActive)
    {
        WRAPPER_NO_CONTRACT;
        Init();
    }

    ~AppDomainIterator()
    {
        WRAPPER_NO_CONTRACT;

#ifndef DACCESS_COMPILE
        if (GetDomain() != NULL)
        {
#ifdef _DEBUG            
            GetDomain()->IteratorRelease();
#endif            
            GetDomain()->Release();
        }
#endif
    }

    BOOL Next()
    {
        WRAPPER_NO_CONTRACT;

#ifndef DACCESS_COMPILE
        if (GetDomain() != NULL)
        {
#ifdef _DEBUG            
            GetDomain()->IteratorRelease();
#endif            
            GetDomain()->Release();
        }

        SystemDomain::LockHolder lh;
#endif

        if (UnsafeAppDomainIterator::Next())
        {
#ifndef DACCESS_COMPILE
            GetDomain()->AddRef();
#ifdef _DEBUG            
            GetDomain()->IteratorAcquire();
#endif
#endif
            return TRUE;
        }

        return FALSE;
    }
};  // class AppDomainIterator

typedef VPTR(class SharedDomain) PTR_SharedDomain;

class SharedDomain : public BaseDomain
{
    VPTR_VTABLE_CLASS_AND_CTOR(SharedDomain, BaseDomain)

public:

    static void Attach();
    static void Detach();

    virtual BOOL IsSharedDomain() { LIMITED_METHOD_DAC_CONTRACT; return TRUE; }
    virtual PTR_LoaderAllocator GetLoaderAllocator() { WRAPPER_NO_CONTRACT; return SystemDomain::GetGlobalLoaderAllocator(); }

    virtual PTR_AppDomain AsAppDomain()
    {
        LIMITED_METHOD_CONTRACT;
        STATIC_CONTRACT_SO_TOLERANT;
        _ASSERTE(!"Not an AppDomain");
        return NULL;
    }

    static SharedDomain * GetDomain();

    void Init();
    void Terminate();

    // This will also set the tenured bit if and only if the add was successful,
    // and will make sure that the bit appears atomically set to all readers that
    // might be accessing the hash on another thread.
    MethodTable * FindIndexClass(SIZE_T index);

#ifdef FEATURE_LOADER_OPTIMIZATION
    void AddShareableAssembly(Assembly * pAssembly);

    class SharedAssemblyIterator
    {
        PtrHashMap::PtrIterator i;
        Assembly * m_pAssembly;

      public:
        SharedAssemblyIterator() :
          i(GetDomain() ? GetDomain()->m_assemblyMap.firstBucket() : NULL)
        { LIMITED_METHOD_DAC_CONTRACT; }

        BOOL Next()
        {
            WRAPPER_NO_CONTRACT;
            SUPPORTS_DAC;

            if (i.end())
                return FALSE;

            m_pAssembly = PTR_Assembly(dac_cast<TADDR>(i.GetValue()));
            ++i;
            return TRUE;
        }

        Assembly * GetAssembly()
        {
            LIMITED_METHOD_DAC_CONTRACT;

            return m_pAssembly;
        }

      private:
        friend class SharedDomain;
    };
    
    Assembly * FindShareableAssembly(SharedAssemblyLocator * pLocator);
    SIZE_T GetShareableAssemblyCount();
#endif //FEATURE_LOADER_OPTIMIZATION

private:
    friend class SharedAssemblyIterator;
    friend class SharedFileLockHolder;
    friend class ClrDataAccess;

#ifndef DACCESS_COMPILE
    void *operator new(size_t size, void *pInPlace);
    void operator delete(void *pMem);
#endif

    SPTR_DECL(SharedDomain, m_pSharedDomain);

#ifdef FEATURE_LOADER_OPTIMIZATION
    PEFileListLock          m_FileCreateLock;
    SIZE_T                  m_nextClassIndex;
    PtrHashMap              m_assemblyMap;
#endif
    
public:
#ifdef DACCESS_COMPILE
    virtual void EnumMemoryRegions(CLRDataEnumMemoryFlags flags,
                                   bool enumThis);
#endif

#ifdef FEATURE_LOADER_OPTIMIZATION
    // Hash map comparison function`
    static BOOL CompareSharedAssembly(UPTR u1, UPTR u2);
#endif
};

#ifdef FEATURE_LOADER_OPTIMIZATION
class SharedFileLockHolderBase : protected HolderBase<PEFile *>
{
  protected:
    PEFileListLock      *m_pLock;
    ListLockEntry   *m_pLockElement;

    SharedFileLockHolderBase(PEFile *value)
      : HolderBase<PEFile *>(value)
    {
        LIMITED_METHOD_CONTRACT;

        m_pLock = NULL;
        m_pLockElement = NULL;
    }

#ifndef DACCESS_COMPILE
    void DoAcquire()
    {
        STATIC_CONTRACT_THROWS;
        STATIC_CONTRACT_GC_TRIGGERS;
        STATIC_CONTRACT_FAULT;

        PEFileListLockHolder lockHolder(m_pLock);

        m_pLockElement = m_pLock->FindFileLock(m_value);
        if (m_pLockElement == NULL)
        {
            m_pLockElement = new ListLockEntry(m_pLock, m_value);
            m_pLock->AddElement(m_pLockElement);
        }
        else
            m_pLockElement->AddRef();

        lockHolder.Release();

        m_pLockElement->Enter();
    }

    void DoRelease()
    {
        STATIC_CONTRACT_NOTHROW;
        STATIC_CONTRACT_GC_TRIGGERS;
        STATIC_CONTRACT_FORBID_FAULT;

        m_pLockElement->Leave();
        m_pLockElement->Release();
        m_pLockElement = NULL;
    }
#endif // DACCESS_COMPILE
};

class SharedFileLockHolder : public BaseHolder<PEFile *, SharedFileLockHolderBase>
{
  public:
    DEBUG_NOINLINE SharedFileLockHolder(SharedDomain *pDomain, PEFile *pFile, BOOL Take = TRUE)
      : BaseHolder<PEFile *, SharedFileLockHolderBase>(pFile, FALSE)
    {
        STATIC_CONTRACT_THROWS;
        STATIC_CONTRACT_GC_TRIGGERS;
        STATIC_CONTRACT_FAULT;
        ANNOTATION_SPECIAL_HOLDER_CALLER_NEEDS_DYNAMIC_CONTRACT;

        m_pLock = &pDomain->m_FileCreateLock;
        if (Take)
            Acquire();
    }
};
#endif // FEATURE_LOADER_OPTIMIZATION

inline BOOL BaseDomain::IsDefaultDomain()
{ 
    LIMITED_METHOD_DAC_CONTRACT; 
    return (SystemDomain::System()->DefaultDomain() == this);
}

#include "comreflectioncache.inl"

#if !defined(DACCESS_COMPILE) && !defined(CROSSGEN_COMPILE)
// holds an extra reference so needs special Extract() and should not have SuppressRelease()
// Holders/Wrappers have nonvirtual methods so cannot use them as the base class
template <class AppDomainType>
class AppDomainCreationHolder 
{
private:
    // disable the copy ctor
    AppDomainCreationHolder(const AppDomainCreationHolder<AppDomainType>&) {}

protected:
    AppDomainType* m_pDomain;
    BOOL       m_bAcquired;
    void ReleaseAppDomainDuringCreation()
    {
        CONTRACTL
        {
            NOTHROW;
            WRAPPER(GC_TRIGGERS);
            PRECONDITION(m_bAcquired);
            PRECONDITION(CheckPointer(m_pDomain));
        }
        CONTRACTL_END;

        if (m_pDomain->NotReadyForManagedCode())
        {
            m_pDomain->Release();
        }
        else
        {
            STRESS_LOG2 (LF_APPDOMAIN, LL_INFO100, "Unload domain during creation [%d] %p\n", m_pDomain->GetId().m_dwId, m_pDomain);
            SystemDomain::MakeUnloadable(m_pDomain);
#ifdef _DEBUG
            DWORD hostTestADUnload = g_pConfig->GetHostTestADUnload();
            m_pDomain->EnableADUnloadWorker(hostTestADUnload != 2?EEPolicy::ADU_Safe:EEPolicy::ADU_Rude);
#else
            m_pDomain->EnableADUnloadWorker(EEPolicy::ADU_Safe);
#endif
        }
    };
    
public:
    AppDomainCreationHolder() 
    {
        m_pDomain=NULL;
        m_bAcquired=FALSE;
    };
    ~AppDomainCreationHolder()
    {
        if (m_bAcquired) 
        {
            Release();
        }
    };
    void Assign(AppDomainType* pDomain)
    {
        if(m_bAcquired)
            Release();
        m_pDomain=pDomain;
        if(m_pDomain)
        {
            AppDomain::RefTakerAcquire(m_pDomain);
#ifdef _DEBUG
            m_pDomain->IncCreationCount();
#endif // _DEBUG
        }
        m_bAcquired=TRUE;
    };
    
    void Release()
    {
        _ASSERTE(m_bAcquired);
        if(m_pDomain)
        {
#ifdef _DEBUG
            m_pDomain->DecCreationCount();
#endif // _DEBUG
            if(!m_pDomain->IsDefaultDomain())
                ReleaseAppDomainDuringCreation();
            AppDomain::RefTakerRelease(m_pDomain);
        };
        m_bAcquired=FALSE;
    };

    AppDomainType* Extract()
    {
        _ASSERTE(m_bAcquired);
        if(m_pDomain)
        {
#ifdef _DEBUG
            m_pDomain->DecCreationCount();
#endif // _DEBUG
            AppDomain::RefTakerRelease(m_pDomain);
        }
        m_bAcquired=FALSE;
        return m_pDomain;
    };

    AppDomainType* operator ->()
    {
        _ASSERTE(m_bAcquired);
        return m_pDomain;
    }

    operator AppDomainType*()
    {
        _ASSERTE(m_bAcquired);
        return m_pDomain;
    }

    void DoneCreating()
    {
        Extract();
    }
};
#endif // !DACCESS_COMPILE && !CROSSGEN_COMPILE

#endif