summaryrefslogtreecommitdiff
path: root/src/vm/appdomain.hpp
blob: 5bc45d7943e6b0aad0dabb690a879ac02fb26174 (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
// 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 "testhookmgr.h"
#include "gcheaputilities.h"
#include "gchandleutilities.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"

#include "tieredcompilation.h"

#include "codeversion.h"

class BaseDomain;
class SystemDomain;
class AppDomain;
class CompilationDomain;
class AppDomainEnum;
class AssemblySink;
class EEMarshalingData;
class GlobalStringLiteralMap;
class StringLiteralMap;
class MngStdInterfacesInfo;
class DomainModule;
class DomainAssembly;
struct InteropMethodTableData;
class LoadLevelLimiter;
class TypeEquivalenceHashTable;
class StringArrayList;

#ifdef FEATURE_COMINTEROP
class ComCallWrapperCache;
struct SimpleComCallWrapper;
class RCWRefCache;
#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;
            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;
            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

#define OFFSETOF__DomainLocalModule__m_pDataBlob_                    (6 * TARGET_POINTER_SIZE)
#ifdef FEATURE_64BIT_ALIGNMENT
#define OFFSETOF__DomainLocalModule__NormalDynamicEntry__m_pDataBlob (TARGET_POINTER_SIZE /* m_pGCStatics */ + TARGET_POINTER_SIZE /* m_padding */)
#else
#define OFFSETOF__DomainLocalModule__NormalDynamicEntry__m_pDataBlob TARGET_POINTER_SIZE /* m_pGCStatics */
#endif

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

    // 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 * GetOsPageSize())
#define LOW_FREQUENCY_HEAP_COMMIT_SIZE         (1 * GetOsPageSize())

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

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

// --------------------------------------------------------------------------------
// 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_data)->Equals(pFile))
            {
                return pEntry;
            }
        }

        return NULL;
    }
#endif // DACCESS_COMPILE

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

    DEBUG_NOINLINE static void HolderLeave(PEFileListLock *pThis)
    {
        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;

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

    ~FileLoadLock();
    DomainFile *GetDomainFile();
    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

    typedef ListLockBase<NativeCodeVersion> JitListLock;
    typedef ListLockEntryBase<NativeCodeVersion> JitListLockEntry;


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

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

    virtual BOOL IsAppDomain()    { LIMITED_METHOD_DAC_CONTRACT; return FALSE; }

    BOOL IsSharedDomain() { LIMITED_METHOD_DAC_CONTRACT; return FALSE; }
    BOOL IsDefaultDomain() { LIMITED_METHOD_DAC_CONTRACT; return TRUE; }

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

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

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

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

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

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

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

#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)
    IGCHandleStore* GetHandleStore()
    {
        LIMITED_METHOD_CONTRACT;
        return m_handleStore;
    }

    OBJECTHANDLE CreateTypedHandle(OBJECTREF object, HandleType type)
    {
        WRAPPER_NO_CONTRACT;
        return ::CreateHandleCommon(m_handleStore, 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;
        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)
    {
        WRAPPER_NO_CONTRACT;
        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)
    {
        WRAPPER_NO_CONTRACT;
        return ::CreateDependentHandle(m_handleStore, primary, 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;
    JitListLock      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

    IGCHandleStore* m_handleStore;

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

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

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

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

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

    //****************************************************************************************
    // 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);
#ifndef DACCESS_COMPILE
    void RemoveTypesFromTypeIDMap(LoaderAllocator* pLoaderAllocator);
#endif // DACCESS_COMPILE

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

#ifdef FEATURE_CODE_VERSIONING
private:
    CodeVersionManager m_codeVersionManager;

public:
    CodeVersionManager* GetCodeVersionManager() { return &m_codeVersionManager; }
#endif //FEATURE_CODE_VERSIONING

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

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

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

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

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

    VPTR_VTABLE_CLASS(AppDomain, BaseDomain)

public:
#ifndef DACCESS_COMPILE
    AppDomain();
    virtual ~AppDomain();
    static void Create();
#endif

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

#if defined(FEATURE_COMINTEROP)
    HRESULT SetWinrtApplicationContext(LPCWSTR pwzAppLocalWinMD);
#endif // FEATURE_COMINTEROP

    bool MustForceTrivialWaitOperations();
    void SetForceTrivialWaitOperations();

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

    // final assembly cleanup
    void ShutdownFreeLoaderAllocators();
    
    void ReleaseFiles();
    
    virtual BOOL IsAppDomain() { LIMITED_METHOD_DAC_CONTRACT; return TRUE; }
    virtual PTR_AppDomain AsAppDomain() { LIMITED_METHOD_CONTRACT; return dac_cast<PTR_AppDomain>(this); }

    OBJECTREF GetRawExposedObject() { LIMITED_METHOD_CONTRACT; return NULL; }
    OBJECTHANDLE GetRawExposedObjectHandleForDebugger() { LIMITED_METHOD_DAC_CONTRACT; return NULL; }

#ifdef FEATURE_COMINTEROP
    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 DeleteElementsOnDestructSHashTraits<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);
    BOOL RemoveNativeImageDependency(AssemblySpec* pSpec);

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

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

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

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

    DomainAssembly *LoadDomainAssembly( AssemblySpec* pIdentity,
                                        PEAssembly *pFile,
                                        FileLoadLevel targetLevel);


    CHECK CheckValidModule(Module *pModule);

    // 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 RemoveFileFromCache(PEAssembly *pFile);

    BOOL AddAssemblyToCache(AssemblySpec* pSpec, DomainAssembly *pAssembly);
    BOOL RemoveAssemblyFromCache(DomainAssembly* pAssembly);

    BOOL AddExceptionToCache(AssemblySpec* pSpec, Exception *ex);
    void AddUnmanagedImageToCache(LPCWSTR libraryName, HMODULE hMod);
    HMODULE FindUnmanagedImageInCache(LPCWSTR libraryName);
    //****************************************************************************************
    //
    // Adds or removes an assembly to the domain.
    void AddAssembly(DomainAssembly * assem);
    void RemoveAssembly(DomainAssembly * pAsm);

    BOOL ContainsAssembly(Assembly * assem);

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

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

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


    PEAssembly *TryResolveAssembly(AssemblySpec *pSpec);

    // 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);
    }
#endif // DACCESS_COMPILE

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

    void SetupSharedStatics();

    //****************************************************************************************
    //
    // 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);
    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
    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();
#endif // FEATURE_COMINTEROP

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

    TPIndex GetTPIndex()
    {
        LIMITED_METHOD_CONTRACT;
        return m_tpIndex;
    }

    IUnknown *CreateFusionContext();

    void SetIgnoreUnhandledExceptions()
    {
        LIMITED_METHOD_CONTRACT;

        m_dwFlags |= IGNORE_UNHANDLED_EXCEPTIONS;
    }

    BOOL IgnoreUnhandledExceptions()
    {
        LIMITED_METHOD_CONTRACT;

        return (m_dwFlags & IGNORE_UNHANDLED_EXCEPTIONS);
    }

    void SetCompilationDomain()
    {
        LIMITED_METHOD_CONTRACT;

        m_dwFlags |= COMPILATION_DOMAIN;
    }

    BOOL IsCompilationDomain();

    PTR_CompilationDomain ToCompilationDomain()
    {
        LIMITED_METHOD_CONTRACT;

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

    static void ExceptionUnwind(Frame *pFrame);

    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;
    }
    // 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;
#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 NotReadyForManagedCode()
    {
        LIMITED_METHOD_CONTRACT;

        return m_Stage < STAGE_READYFORMANAGEDCODE;
    }

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

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

#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:
    size_t EstimateSize();
    EEClassFactoryInfoHashTable* SetupClassFactHash();
#ifdef FEATURE_COMINTEROP
    DispIDCache* SetupRefDispIDCache();
#endif // FEATURE_COMINTEROP

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

private:
    void RaiseLoadingAssemblyEvent(DomainAssembly* pAssembly);

    friend class DomainAssembly;

private:
    BOOL RaiseUnhandledExceptionEvent(OBJECTREF *pThrowable, BOOL isTerminating);

    enum Stage {
        STAGE_CREATING,
        STAGE_READYFORMANAGEDCODE,
        STAGE_ACTIVE,
        STAGE_OPEN,
        // Don't delete the following *_DONOTUSE members and in case a new member needs to be added,
        // add it at the end. The reason is that debugger stuff has its own copy of this enum and 
        // it can use the members that are marked as *_DONOTUSE here when debugging older version 
        // of the runtime.
        STAGE_UNLOAD_REQUESTED_DONOTUSE,
        STAGE_EXITING_DONOTUSE,
        STAGE_EXITED_DONOTUSE,
        STAGE_FINALIZING_DONOTUSE,
        STAGE_FINALIZED_DONOTUSE,
        STAGE_HANDLETABLE_NOACCESS_DONOTUSE,
        STAGE_CLEARED_DONOTUSE,
        STAGE_COLLECTED_DONOTUSE,
        STAGE_CLOSED_DONOTUSE
    };
    void SetStage(Stage stage)
    {
        CONTRACTL
        {
            NOTHROW;
            GC_NOTRIGGER;
            MODE_ANY;
        }
        CONTRACTL_END;
        STRESS_LOG1(LF_APPDOMAIN, LL_INFO100,"Updating AD stage, stage=%d\n",stage);
        TESTHOOKCALL(AppDomainStageChanged(DefaultADID,m_Stage,stage));
        Stage lastStage=m_Stage;
        while (lastStage !=stage) 
            lastStage = (Stage)FastInterlockCompareExchange((LONG*)&m_Stage,stage,lastStage);
    };

    // 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);
    
public:
    void SetGCRefPoint(int gccounter)
    {
        LIMITED_METHOD_CONTRACT;
        GetLoaderAllocator()->SetGCRefPoint(gccounter);
    }
    int  GetGCRefPoint()
    {
        LIMITED_METHOD_CONTRACT;
        return GetLoaderAllocator()->GetGCRefPoint();
    }

    void AddMemoryPressure();
    void RemoveMemoryPressure();

    void UnlinkClass(MethodTable *pMT);

    Assembly *GetRootAssembly()
    {
        LIMITED_METHOD_CONTRACT;
        return m_pRootAssembly;
    }

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

private:
    // The one and only AppDomain
    SPTR_DECL(AppDomain, m_pTheAppDomain);

    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.

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

    // this cache stores the RCWs in this domain
    RCWCache *m_pRCWCache;

    // this cache stores the RCW -> CCW references in this domain
    RCWRefCache *m_pRCWRefCache;
#endif // FEATURE_COMINTEROP

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

    Volatile<Stage> m_Stage;

    ArrayList        m_failedAssemblies;

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

    enum {
        CONTEXT_INITIALIZED =               0x0001,
        LOAD_SYSTEM_ASSEMBLY_EVENT_SENT =   0x0040,
        COMPILATION_DOMAIN =                0x0400, // Are we ngenning?
        IGNORE_UNHANDLED_EXCEPTIONS =      0x10000, // AppDomain was created using the APPDOMAIN_IGNORE_UNHANDLED_EXCEPTIONS flag
    };

    AssemblySpecBindingCache  m_AssemblyCache;
    DomainAssemblyCache       m_UnmanagedCache;
    size_t                    m_MemoryPressure;

    ArrayList m_NativeDllSearchDirectories;
    BOOL m_ReversePInvokeCanEnter;
    bool m_ForceTrivialWaitOperations;

public:

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

    private:

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

#endif

#ifdef FEATURE_COMINTEROP

private:

#endif //FEATURE_COMINTEROP

public:

    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 element_t Null() { return NULL; }
        static 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;

typedef VPTR(class SystemDomain) PTR_SystemDomain;

class SystemDomain : public BaseDomain
{
    friend class AppDomainNative;
    friend class AppDomainIterator;
    friend class UnsafeAppDomainIterator;
    friend class ClrDataAccess;

    VPTR_VTABLE_CLASS(SystemDomain, BaseDomain)
    VPTR_UNIQUE(VPTR_UNIQUE_SystemDomain)

public:  
    static PTR_LoaderAllocator GetGlobalLoaderAllocator();

    //****************************************************************************************
    //
    // 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();
    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 AppDomain::GetCurrentDomain();
    }

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

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

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

    //****************************************************************************************
    // Methods used to get the callers module and hence assembly and app domain.

    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

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

    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 ProcessDelayedUnloadLoaderAllocators();
    
    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_pDelayedUnloadListOfLoaderAllocators=NULL;

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

    GlobalLoaderAllocator m_GlobalAllocator;


    InlineSString<100>  m_BaseLibrary;

    InlineSString<100>  m_SystemDirectory;

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

    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

#ifndef DACCESS_COMPILE
    static CrstStatic m_DelayedUnloadCrst;
    static CrstStatic       m_SystemDomainCrst;

    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.)
// In CoreCLR, this iterator doesn't use a list as there is at most 1 AppDomain, and instead will find the only AppDomain, or not.
//
class UnsafeAppDomainIterator
{
    friend class SystemDomain;
public:
    UnsafeAppDomainIterator(BOOL bOnlyActive)
    {
        m_bOnlyActive = bOnlyActive;
    }

    void Init()
    {
        LIMITED_METHOD_CONTRACT;
        m_iterationCount = 0;
        m_pCurrent = NULL;
    }

    BOOL Next()
    {
        WRAPPER_NO_CONTRACT;

        if (m_iterationCount == 0)
        {
            m_iterationCount++;
            m_pCurrent = AppDomain::GetCurrentDomain();
            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:

    int                 m_iterationCount;
    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

#include "comreflectioncache.inl"

#endif