Welcome to mirror list, hosted at ThFree Co, Russian Federation.

__ComObject.cs « Shared « src « System.Private.Interop « src - github.com/mono/corert.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 0efd00ae2b50e39c76c0db97b31ee768c41dc4c2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
// 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.
// ----------------------------------------------------------------------------------
// Interop library code
//
// Implementation for RCWs
//
// NOTE:
//   These source code are being published to InternalAPIs and consumed by RH builds
//   Use PublishInteropAPI.bat to keep the InternalAPI copies in sync
// ---------------------------------------------------------------------------------
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Generic.Internal;
using System.ComponentModel;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Text;
using System.Runtime;

using Internal.NativeFormat;

#if !RHTESTCL && PROJECTN && ENABLE_WINRT
using Internal.Runtime.Augments;
using Internal.Runtime.TypeLoader;
#endif

namespace System
{
    /// <summary>
    /// Helper class to finalize this RCW object
    /// When we have managed class deriving from native class, if it has a finalizer, the finalizer won't
    /// have a call to base __ComObject because compiler doesn't see it. Also, developer can call
    /// SuppressFinalize and by pass the finalizer altogether without knowing that they've by passed the
    /// finalizer of the base __ComObject.
    /// The solution here is to simply rely on another object to do the finalization.
    /// Note that we can't do this in the ComCallableObject's finalizer (we don't have it now) because the
    /// the CCW would have shorter life time than the actual managed object so it might've destroyed the base
    /// RCW before managed class is gone.
    /// </summary>
    internal class RCWFinalizer
    {
        private __ComObject m_comObject;

        internal RCWFinalizer(__ComObject comObject)
        {
            m_comObject = comObject;
        }

        ~RCWFinalizer()
        {
            m_comObject.Cleanup(disposing: false);
        }
    }

    [CLSCompliant(false)]
    public abstract class __ComGenericInterfaceDispatcher
    {
        public __ComObject m_comObject;
        public __ComGenericInterfaceDispatcher() { }
    }

    /// <summary>
    /// This is the weakly-typed RCW and also base class of all strongly-typed RCWs
    /// NOTE: Managed debugger depends on type name: "System.__ComObject"
    /// </summary>
    [EditorBrowsable(EditorBrowsableState.Never)]
    [CLSCompliant(false)]
#if !RHTESTCL && PROJECTN && ENABLE_WINRT
    public unsafe class __ComObject : CastableObject, ICastable
#else
    public unsafe class __ComObject : ICastable
#endif
    {
        #region Private variables

        /// <summary>
        /// RCW Identity interface pointer + context
        /// This supports all the cross-apartment marshalling
        /// </summary>
        [DebuggerBrowsable(DebuggerBrowsableState.Never)]
        ContextBoundInterfacePointer m_baseIUnknown;

        /// <summary>
        /// Base IUnknown of this RCW. When we QI we'll be using this IUnknown
        /// Note that this is not necessarily the identity IUnknown, which is why I name it "Base" IUnknown
        /// If this is default(IntPtr), this RCW is not initialized yet
        /// </summary>
        [DebuggerBrowsable(DebuggerBrowsableState.Never)]
        internal IntPtr BaseIUnknown_UnsafeNoAddRef { get { return m_baseIUnknown.ComPointer_UnsafeNoAddRef; } }

        /// <summary>
        /// Internal RCW ref count
        /// NOTE: this is different from ref count on the underlying COM object
        /// Each time when you marshal a native pointer into a RCW, the RCW gets one AddRef
        /// Typically you don't need to release as garbage collector will automatically take care of it
        /// But you can call Marshal.ReleaseComObject if you want explicit release it as early as possible
        /// </summary>
        [DebuggerBrowsable(DebuggerBrowsableState.Never)]
        int m_refCount;

        /// <summary>
        /// Flags of this __ComObject. See ComObjectFlags for the possible value
        /// </summary>
        [DebuggerBrowsable(DebuggerBrowsableState.Never)]
        ComObjectFlags m_flags;

        /// <summary>
        /// A reference to CCW
        /// This makes sure the lifetime of the CCW and this RCW is tied together in aggregation scenario
        /// </summary>
        [DebuggerBrowsable(DebuggerBrowsableState.Never)]
        ComCallableObject m_outer;

        /// <summary>
        /// Saved identity IUnknown vtbl at creation time
        /// This is mostly used as a way to diagnose what the underlying COM object really is (if the vtbl
        /// is still there, of course) in case the COM object was destroyed due to an extra release
        /// </summary>
        [DebuggerBrowsable(DebuggerBrowsableState.Never)]
        IntPtr m_savedIUnknownVtbl;

        [DebuggerBrowsable(DebuggerBrowsableState.Never)]
        internal IntPtr SavedIUnknownVtbl { get { return m_savedIUnknownVtbl; } }

        /// <summary>
        /// Fixed array of cached interfaces that are lock-free
        /// @TODO: Make this a struct instead of an array object
        /// NOTE: Managed Debugger depends on field name "m_cachedInterfaces" and field type:SimpleComInterfaceCacheItem
        /// Update managed debugger whenever field name/field type is changed.
        /// See CordbObjectValue::GetInterfaceData in debug\dbi\values.cpp
        /// </summary>
        [DebuggerBrowsable(DebuggerBrowsableState.Never)]
        internal SimpleComInterfaceCacheItem[] m_cachedInterfaces;
        internal const int FIXED_CACHE_SIZE = 8;

        /// <summary>
        /// Growable additional cached interfaces.  Access this via AcquireAdditionalCacheExclusive/ForRead
        /// NOTE: Managed Debugger depends on field name: "m_additionalCachedInterfaces_dontAccessDirectly" and field type: AdditionalComInterfaceCacheContext
        /// Update managed debugger whenever field name/field type is changed.
        /// See CordbObjectValue::GetInterfaceData in debug\dbi\values.cpp
        /// </summary>
        [DebuggerBrowsable(DebuggerBrowsableState.Never)]
        private AdditionalComInterfaceCacheContext[] m_additionalCachedInterfaces_dontAccessDirectly;

        // if m_additionalCachedInterfaces_dontAccessDirectly == CacheLocked, the cache is being updated and
        // cannot be read or written from another thread.  We do this instead of using a "real" lock, to save space.
        [DebuggerBrowsable(DebuggerBrowsableState.Never)]
        private static readonly AdditionalComInterfaceCacheContext[] CacheLocked = new AdditionalComInterfaceCacheContext[0];

        /// <summary>
        /// Finalizer helper object that does cleanup.
        /// See RCWFinalizer class for more details.
        /// </summary>
        [DebuggerBrowsable(DebuggerBrowsableState.Never)]
        private RCWFinalizer m_finalizer;

#if !RHTESTCL && PROJECTN && ENABLE_WINRT
        [DebuggerBrowsable(DebuggerBrowsableState.Never)]
        private static readonly System.Collections.Generic.Dictionary<RuntimeTypeHandle, RuntimeTypeHandle> s_DynamicRCWAdapters = 
            new System.Collections.Generic.Dictionary<RuntimeTypeHandle, RuntimeTypeHandle>();
#endif

        #endregion

        #region Debugging Private Variables

#if DEBUG
        /// <summary>
        /// Runtime class name of this WinRT __ComObject. This is helpful when you want to understand why
        /// you get back a __ComObject instead of a strongly-typed RCW
        /// </summary>
        [DebuggerBrowsable(DebuggerBrowsableState.Never)]
        internal string m_runtimeClassName;

        /// <summary>
        /// sequential allocation ID of this COM object
        /// useful when you are debugging bugs where the program's behavior is deterministic
        /// </summary>
        [DebuggerBrowsable(DebuggerBrowsableState.Never)]
        internal uint m_allocationId;

        /// <summary>
        /// Next allocation ID
        /// Typed as int to make sure InterlockedExchange.Add is happy
        /// </summary>
        [DebuggerBrowsable(DebuggerBrowsableState.Never)]
        internal static int s_nextAllocationId;
#endif

        /// <summary>
        /// Return allocation ID in debug build
        /// INTERNAL only - not in public contract
        /// </summary>
        [DebuggerBrowsable(DebuggerBrowsableState.Never)]
        public uint AllocationId
        {
            get
            {
#if DEBUG
                return m_allocationId;
#else
                return 0xffffffff;
#endif
            }
        }

        #endregion

        /// <summary>
        /// Gets/sets the outer CCW
        /// Only used in aggregation scenarios
        /// We only set the outer CCW during creation of managed object that derives from native
        /// </summary>
        [DebuggerBrowsable(DebuggerBrowsableState.Never)]
        internal ComCallableObject Outer
        {
            get
            {
                return m_outer;
            }
            set
            {
                m_outer = value;
            }
        }

        private AdditionalComInterfaceCacheContext[] AcquireAdditionalCacheExclusive()
        {
            AdditionalComInterfaceCacheContext[] additionalCache;

            SpinWait spin = new SpinWait();

            while ((additionalCache = Interlocked.Exchange(ref m_additionalCachedInterfaces_dontAccessDirectly, CacheLocked)) == CacheLocked)
                spin.SpinOnce();

            return additionalCache;
        }

        private void ReleaseAdditionalCacheExclusive(AdditionalComInterfaceCacheContext[] contexts)
        {
            Debug.Assert(m_additionalCachedInterfaces_dontAccessDirectly == CacheLocked);
            Volatile.Write(ref m_additionalCachedInterfaces_dontAccessDirectly, contexts);
        }

        private AdditionalComInterfaceCacheContext[] AcquireAdditionalCacheForRead()
        {
            SpinWait spin = new SpinWait();
            AdditionalComInterfaceCacheContext[] additionalCache;

            while ((additionalCache = Volatile.Read(ref m_additionalCachedInterfaces_dontAccessDirectly)) == CacheLocked)
                spin.SpinOnce();

            return additionalCache;
        }

        /// <returns>True is added, false if duplication found</returns>
        private bool AddToAdditionalCache(ContextCookie contextCookie, RuntimeTypeHandle interfaceType, IntPtr pComPtr, object adapter, bool checkDup)
        {
            var additionalCache = AcquireAdditionalCacheExclusive();

            bool added = false;

            try
            {
                //
                // Try to find this context
                //
                int firstFree = -1;

                if (additionalCache != null)
                {
                    for (int i = 0; i < additionalCache.Length; i++)
                    {
                        if (additionalCache[i] == null)
                        {
                            if (firstFree == -1)
                            {
                                firstFree = i;
                            }
                        }
                        else if (additionalCache[i].context.ContextCookie.Equals(contextCookie))
                        {
                            return additionalCache[i].Add(interfaceType, pComPtr, adapter, checkDup);
                        }
                    }
                }

                //
                // This is a new context.
                //
                if (firstFree == -1)
                {
                    //
                    // Need a bigger array
                    //
                    AdditionalComInterfaceCacheContext[] newCache;

                    if (additionalCache != null)
                    {
                        newCache = new AdditionalComInterfaceCacheContext[additionalCache.Length + 1];
                        Array.Copy(additionalCache, newCache, additionalCache.Length);
                        firstFree = additionalCache.Length;
                    }
                    else
                    {
                        newCache = new AdditionalComInterfaceCacheContext[1];
                        firstFree = 0;
                    }

                    additionalCache = newCache;
                }

                var newContext = new AdditionalComInterfaceCacheContext(contextCookie);
                added = newContext.Add(interfaceType, pComPtr, adapter, checkDup);
                Volatile.Write(ref additionalCache[firstFree], newContext);
            }
            finally
            {
                ReleaseAdditionalCacheExclusive(additionalCache);
            }

            return added;
        }

        #region Constructor and Finalizer

        static __ComObject()
        {
#if !RHTESTCL && PROJECTN && ENABLE_WINRT
            // Projected types
            s_DynamicRCWAdapters[typeof(IEnumerable<>).TypeHandle]                                                  = typeof(IEnumerable_RCWAdapter<>).TypeHandle;
            s_DynamicRCWAdapters[typeof(IList<>).TypeHandle]                                                        = typeof(IList_RCWAdapter<>).TypeHandle;
            s_DynamicRCWAdapters[typeof(IReadOnlyList<>).TypeHandle]                                                = typeof(IReadOnlyList_RCWAdapter<>).TypeHandle;
            s_DynamicRCWAdapters[typeof(IDictionary<,>).TypeHandle]                                                 = typeof(IDictionary_RCWAdapter<,>).TypeHandle;
            s_DynamicRCWAdapters[typeof(IReadOnlyDictionary<,>).TypeHandle]                                         = typeof(IReadOnlyDictionary_RCWAdapter<,>).TypeHandle;
            s_DynamicRCWAdapters[typeof(global::Windows.Foundation.Collections.IKeyValuePair<,>).TypeHandle]        = typeof(IKeyValuePair_RCWAdapter<,>).TypeHandle;
            
            // Non-projected types
            s_DynamicRCWAdapters[typeof(global::Windows.Foundation.Collections.IIterator<>).TypeHandle]             = typeof(IIterator_RCWAdapter<>).TypeHandle;
            s_DynamicRCWAdapters[typeof(global::Windows.Foundation.Collections.IMapChangedEventArgs<>).TypeHandle]  = typeof(IMapChangedEventArgs_RCWAdapter<>).TypeHandle;
            s_DynamicRCWAdapters[typeof(global::Windows.Foundation.IAsyncOperationWithProgress<,>).TypeHandle]      = typeof(IAsyncOperationWithProgress_RCWAdapter<,>).TypeHandle;
            s_DynamicRCWAdapters[typeof(global::Windows.Foundation.IAsyncOperation<>).TypeHandle]                   = typeof(IAsyncOperation_RCWAdapter<>).TypeHandle;
            s_DynamicRCWAdapters[typeof(global::Windows.Foundation.IAsyncActionWithProgress<>).TypeHandle]          = typeof(IAsyncActionWithProgress_RCWAdapter<>).TypeHandle;

            // Root constructors of RCW adapters that are base classes of other RCW adapters
            new IList_RCWAdapter<object>();                 // Base class of the IObservableVector RCW adapter
            new IDictionary_RCWAdapter<object, object>();   // Base class of the IObservableMap RCW adapter
#endif
        }

        /// <summary>
        /// Default constructor for RCW 'new' code path
        /// This only initialize __ComObject to a default, non-usable state
        /// Please use Attach to initialize the RCW
        /// Aggregation requires this to be a two-step process in order to access 'this' pointer
        /// </summary>
        [MethodImpl(MethodImplOptions.NoInlining)]
        public __ComObject()
        {
            __InitToDefaultState();
        }

        /// <summary>
        /// Attaching ctor of __ComObject for RCW marshalling code path in order to create a weakly typed RCW
        /// Initialize and Attach to a existing Com Object
        /// if pBaseIUnknown is default(IntPtr), does initialization only
        /// </summary>
        /// <param name="pBaseIUnknown">Base IUnknown*. Could be Zero</param>
        [MethodImpl(MethodImplOptions.NoInlining)]
        internal __ComObject(IntPtr pBaseIUnknown, RuntimeTypeHandle classType)
        {
            this.__AttachingCtor(pBaseIUnknown, classType);
        }

        /// <summary>
        /// Attaching ctor used by CreateComObjectInternal. Always used following RhNewObject call therefore the
        /// default constructor is not ran. Other code should call __Attach/__AttachAndRelease (which assumes
        /// default constructor has ran)
        /// </summary>
        /// <remarks>
        /// 'int' return value type is a dummy here, it's used because of a limitation on our AddrOf/Call support
        /// </remarks>
        internal static int AttachingCtor(__ComObject comObject, IntPtr pBaseIUnknown, RuntimeTypeHandle classType)
        {
            comObject.__AttachingCtor(pBaseIUnknown, classType);
            return 0;
        }

        /// <summary>
        /// Attaching ctor used by CreateComObjectInternal. Always used following RhNewObject call therefore the
        /// default constructor is not ran. Other code should call __Attach/__AttachAndRelease (which assumes
        /// default constructor has ran)
        /// </summary>
        private void __AttachingCtor(IntPtr pBaseIUnknown, RuntimeTypeHandle classType)
        {
            __InitToDefaultState();

            if (pBaseIUnknown != default(IntPtr))
                __Attach(pBaseIUnknown, classType);
        }

        /// <summary>
        /// This method updates the flags to represent the right GCPressureRange that is filtered by the MCG by reading the [Windows.Foundation.Metadata.GcPressureAttribute].
        /// By default all the __ComObject get the default GCPressure.
        /// This method, also calls the GC.AddMemoryPressure(); with the right mappings for different ranges created in GCMemoryPressureConstants
        /// </summary>
        /// <param name="gcMemoryPressureRange"></param>
        private void AddGCMemoryPressure(GCPressureRange gcMemoryPressureRange)
        {
#if ENABLE_WINRT
            switch (gcMemoryPressureRange)
            {
                case GCPressureRange.WinRT_Default:
                    m_flags |= ComObjectFlags.GCPressure_Set;
                    break;
                case GCPressureRange.WinRT_Low:
                    m_flags |= (ComObjectFlags.GCPressureWinRT_Low | ComObjectFlags.GCPressure_Set);
                    break;
                case GCPressureRange.WinRT_Medium:
                    m_flags |= (ComObjectFlags.GCPressureWinRT_Medium | ComObjectFlags.GCPressure_Set);
                    break;
                case GCPressureRange.WinRT_High:
                    m_flags |= (ComObjectFlags.GCPressureWinRT_High | ComObjectFlags.GCPressure_Set);
                    break;
                default:
                    Debug.Fail("Incorrect GCPressure value");
                    return;
            }

            Debug.Assert(IsGCPressureSet);

            GC.AddMemoryPressure(GCMemoryPressure);
#endif
        }

        /// <summary>
        /// This method updates the flags to represent the right GCPressureRange that is filtered by the MCG by reading the [Windows.Foundation.Metadata.GcPressureAttribute].
        /// By default all the __ComObject get the default GCPressure.
        /// This method, also calls the GC.AddMemoryPressure(); with the right mappings for different ranges created in GCMemoryPressureConstants
        /// </summary>
        /// <param name="gcMemoryPressureRange"></param>
        private void UpdateComMarshalingType(ComMarshalingType marshallingType)
        {
            switch (marshallingType)
            {
                case ComMarshalingType.Inhibit:
                    m_flags |= ComObjectFlags.MarshalingBehavior_Inhibit;
                    break;
                case ComMarshalingType.Free:
                    m_flags |= ComObjectFlags.MarshalingBehavior_Free;
                    break;
                case ComMarshalingType.Standard:
                    m_flags |= ComObjectFlags.MarshalingBehavior_Standard;
                    break;
            }
        }

        [DebuggerBrowsable(DebuggerBrowsableState.Never)]
        private ComMarshalingType MarshalingType
        {
            get
            {
                switch (m_flags & ComObjectFlags.MarshalingBehavior_Mask)
                {
                    case ComObjectFlags.MarshalingBehavior_Inhibit:
                        return ComMarshalingType.Inhibit;

                    case ComObjectFlags.MarshalingBehavior_Free:
                        return ComMarshalingType.Free;

                    case ComObjectFlags.MarshalingBehavior_Standard:
                        return ComMarshalingType.Standard;

                    default:
                        return ComMarshalingType.Unknown;
                }
            }
        }

        [DebuggerBrowsable(DebuggerBrowsableState.Never)]
        private bool IsGCPressureSet
        {
            get
            {
                return ((m_flags & ComObjectFlags.GCPressure_Set) != 0);
            }
        }

        /// <summary>
        /// This property creates the mapping between the GCPressure ranges to the actual memory pressure in bytes per RCW.
        /// The different mapping ranges are defined in GCMemoryPressureConstants
        /// </summary>
#if ENABLE_WINRT
        [DebuggerBrowsable(DebuggerBrowsableState.Never)]
        private int GCMemoryPressure
        {
            get
            {
                Debug.Assert(IsGCPressureSet, "GCPressureRange.Unknown");

                switch (m_flags & ComObjectFlags.GCPressureWinRT_Mask)
                {
                    case ComObjectFlags.GCPressureWinRT_Low: return GCMemoryPressureConstants.GC_PRESSURE_WINRT_LOW;

                    case ComObjectFlags.GCPressureWinRT_Medium: return GCMemoryPressureConstants.GC_PRESSURE_WINRT_MEDIUM;

                    case ComObjectFlags.GCPressureWinRT_High: return GCMemoryPressureConstants.GC_PRESSURE_WINRT_HIGH;

                    default: return GCMemoryPressureConstants.GC_PRESSURE_DEFAULT;
                }
            }
        }
#endif

        /// <summary>
        /// Initialize RCW to default state
        /// </summary>
        private void __InitToDefaultState()
        {
            m_flags = ComObjectFlags.None;
            m_refCount = 1;
            m_cachedInterfaces = new SimpleComInterfaceCacheItem[FIXED_CACHE_SIZE];
#if DEBUG
            m_allocationId = (uint)Interlocked.Add(ref s_nextAllocationId, 1);
#endif
        }

        private unsafe IntPtr GetVtbl(IntPtr pUnk)
        {
            return new IntPtr((*(void**)pUnk));
        }

        /// <summary>
        /// Attach this RCW to a IUnknown *
        /// NOTE: This function is not CLS-compliant but we'll only call this from C# code.
        /// The '__' prefix is added to avoid name conflict in sub classes
        /// </summary>
        /// <remarks>
        /// Should only be called from RCW 'new' code path
        /// </remarks>
        /// <param name="pBaseIUnknown">IUnknown *. Should never be Zero</param>
        private void __Attach(IntPtr pBaseIUnknown)
        {
            __Attach(pBaseIUnknown, this.GetTypeHandle());
        }

        /// <summary>
        /// Attach this RCW to a IUnknown *
        /// NOTE: This function is not CLS-compliant but we'll only call this from C# code.
        /// The '__' prefix is added to avoid name conflict in sub classes
        /// </summary>
        /// <param name="pBaseIUnknown">IUnknown *. Should never be Zero</param>
        private void __Attach(IntPtr pBaseIUnknown, RuntimeTypeHandle classType)
        {
            Debug.Assert(pBaseIUnknown != default(IntPtr));

            //
            // Read information from classType and apply on the RCW
            //
            if (!classType.IsNull())
            {
                GCPressureRange gcPressureRange = classType.GetGCPressureRange();
                if (gcPressureRange != GCPressureRange.None)
                    AddGCMemoryPressure(gcPressureRange);

                UpdateComMarshalingType(classType.GetMarshalingType());
            }

            // Save the IUnknown vtbl for debugging in case the object has been incorrectly destroyed
            m_savedIUnknownVtbl = GetVtbl(pBaseIUnknown);

            m_baseIUnknown.Initialize(pBaseIUnknown, MarshalingType);

#if ENABLE_WINRT
            IntPtr pJupiterObj =
                McgMarshal.ComQueryInterfaceNoThrow(pBaseIUnknown, ref Interop.COM.IID_IJupiterObject);

            if (pJupiterObj != default(IntPtr))
            {
                m_flags |= ComObjectFlags.IsJupiterObject;

                m_cachedInterfaces[0].Assign(pJupiterObj, InternalTypes.IJupiterObject);
                RCWWalker.OnJupiterRCWCreated(this);

                //
                // If this COM object is aggregated, don't keep a ref count on IJupiterObject
                // Otherwise this would keep the CCW alive and therefore keeping this RCW alive, forming
                // a cycle
                //
                if (IsAggregated)
                    McgMarshal.ComRelease(pJupiterObj);

                pJupiterObj = default(IntPtr);
            }
#endif
            // Insert self into global cache, assuming pBaseIUnknown *is* the identity
            if (!ComObjectCache.Add(pBaseIUnknown, this))
            {
                // Add failed - this means somebody else beat us in creating the RCW
                // We need to make this RCW a duplicate RCW
                m_flags |= ComObjectFlags.IsDuplicate;
            }

            if (IsJupiterObject)
            {
                RCWWalker.AfterJupiterRCWCreated(this);
            }

            // Register for finalization of this RCW
            m_finalizer = new RCWFinalizer(this);

            if (InteropEventProvider.IsEnabled())
                InteropEventProvider.Log.TaskRCWCreation(
                    (long)InteropExtensions.GetObjectID(this),
                    this.GetTypeHandle().GetRawValue().ToInt64(),
#if ENABLE_WINRT
                    McgComHelpers.GetRuntimeClassName(this),
#else
                    null,
#endif
                    (long)ContextCookie.pCookie,
                    (long)m_flags);
        }

        /// <summary>
        /// Attach RCW to the returned interface pointer from the factory and release the extra release
        /// Potentially we could optimize RCW to "swallow" the extra reference and avoid an extra pair of
        /// AddRef & Release
        /// </summary>
        [CLSCompliant(false)]
        public void __AttachAndRelease(IntPtr pBaseIUnknown)
        {
            try
            {
                if (pBaseIUnknown != default(IntPtr))
                {
                    __Attach(pBaseIUnknown);
                }
            }
            finally
            {
                McgMarshal.ComSafeRelease(pBaseIUnknown);
            }
        }

        #endregion

        #region Properties

        /// <summary>
        /// Whether this __ComObject represents a Jupiter UI object that implements IJupiterObject for life
        /// time tracking purposes
        /// </summary>
        [DebuggerBrowsable(DebuggerBrowsableState.Never)]
        internal bool IsJupiterObject
        {
            [GCCallback]
            get
            {
                return (m_flags & ComObjectFlags.IsJupiterObject) != 0;
            }
        }

        /// <summary>
        /// Whether this RCW is used as a baseclass of a managed class. For example, MyButton: Button
        /// </summary>
        [DebuggerBrowsable(DebuggerBrowsableState.Never)]
        internal bool ExtendsComObject
        {
            get
            {
                return (m_flags & ComObjectFlags.ExtendsComObject) != 0;
            }

            set
            {
                //
                // NOTE: This isn't thread safe, but you are only supposed to call this from the constructor
                // anyway from MCG inside a ctor
                //
                if (value)
                    m_flags |= ComObjectFlags.ExtendsComObject;
                else
                    m_flags &= (~ComObjectFlags.ExtendsComObject);
            }
        }

        /// <summary>
        /// Whether this RCW/underlying COM object is being aggregated.
        /// Note that ExtendsComObject is not necessarily the same as aggregation. It just that this is true
        /// in .NET Native (but not true in desktop CLR, where extends a COM object could mean either
        /// aggregation or containment, depending on whether the underlying COM objects supports it)
        /// </summary>
        [DebuggerBrowsable(DebuggerBrowsableState.Never)]
        internal bool IsAggregated
        {
            get
            {
                // In .NET Native - extending a COM base object means aggregation
                return ExtendsComObject;
            }
        }

        #endregion

        #region Jupiter Lifetime

        /// <remarks>
        /// WARNING: This function might be called under a GC callback. Please read the comments in
        /// GCCallbackAttribute to understand all the implications before you make any changes
        /// </remarks>
        [GCCallback]
        internal unsafe __com_IJupiterObject* GetIJupiterObject_NoAddRef()
        {
            Debug.Assert(IsJupiterObject);
            RuntimeTypeHandle interfaceType;
            Debug.Assert(m_cachedInterfaces[0].TryGetType(out interfaceType) && interfaceType.IsIJupiterObject());

            // Slot 0 is always IJupiterObject*
            return (__com_IJupiterObject*)m_cachedInterfaces[0].GetPtr().ToPointer();
        }

        #endregion

        #region Lifetime Management

        /// <summary>
        /// AddRef on the RCW
        /// See m_refCount for more details
        /// </summary>
        internal int AddRef()
        {
            int newRefCount = Threading.Interlocked.Increment(ref m_refCount);

            if (InteropEventProvider.IsEnabled())
                InteropEventProvider.Log.TaskRCWRefCountInc((long)InteropExtensions.GetObjectID(this), newRefCount);

            return newRefCount;
        }

        /// <summary>
        /// Release on the RCW
        /// See m_refCount for more details
        /// </summary>
        internal int Release()
        {
            int newRefCount = Threading.Interlocked.Decrement(ref m_refCount);

            if (InteropEventProvider.IsEnabled())
                InteropEventProvider.Log.TaskRCWRefCountDec((long)InteropExtensions.GetObjectID(this), newRefCount);

            if (newRefCount == 0)
            {
                Cleanup(disposing: true);
            }

            return newRefCount;
        }

        /// <summary>
        /// Completely release the RCW by setting m_refCount to 0
        /// </summary>
        internal void FinalReleaseSelf()
        {
            int prevCount = Threading.Interlocked.Exchange(ref m_refCount, 0);

            if (prevCount > 0)
            {
                Cleanup(disposing: true);
            }
        }

        /// <summary>
        /// Returns the current ref count
        /// </summary>
        internal int PeekRefCount()
        {
            return m_refCount;
        }

        internal void Cleanup(bool disposing)
        {
            //
            // If the RCW hasn't been initialized yet or has already cleaned by ReleaseComObject - skip
            //
            if (m_baseIUnknown.IsDisposed)
            {
                return;
            }

            RCWFinalizer rcwFinalizer = Interlocked.Exchange(ref m_finalizer, null);

            //
            // Another thread is attempting to clean up this __ComObject instance and we lost the race
            //
            if (rcwFinalizer == null)
            {
                return;
            }

            //
            // If the cleanup is not being performed by RCWFinalizer on the finalizer thread then suppress the 
            // finalization of RCWFinalizer since we don't need it
            //
            if (disposing)
            {
                GC.SuppressFinalize(rcwFinalizer);
            }

            if (InteropEventProvider.IsEnabled())
                InteropEventProvider.Log.TaskRCWFinalization((long)InteropExtensions.GetObjectID(this), this.m_refCount);

            //
            // Remove self from cache if this RCW is not a duplicate RCW
            // Duplicate RCW is not stored in the cache
            //
            if (!IsDuplicate)
                ComObjectCache.Remove(m_baseIUnknown.ComPointer_UnsafeNoAddRef, this);

            //
            // Check if we're in the right context for our base IUnknown
            //
            ContextEntry baseContext = m_baseIUnknown.ContextEntry;
            bool inBaseContext = IsFreeThreaded || baseContext.IsCurrent;

            //
            // We didn't AddRef on cached interfaces if this is an aggregated COM object
            // So don't release either
            //
            if (!IsAggregated)
            {
                //
                // For Jupiter objects, start with index 1 because we need the IJupiterObject* to call
                // BeforeRelease
                //
                int startIndex = 0;

                if (IsJupiterObject)
                {
                    RuntimeTypeHandle zeroSlotInterfaceType;
                    Debug.Assert(m_cachedInterfaces[0].TryGetType(out zeroSlotInterfaceType) && zeroSlotInterfaceType.IsIJupiterObject());
                    startIndex = 1;
                }

                //
                // Disposing simple fixed cache
                //
                for (int i = startIndex; i < FIXED_CACHE_SIZE; ++i)
                {
                    IntPtr ptr;
                    if (m_cachedInterfaces[i].TryGetPtr(out ptr))
                    {
                        if (IsJupiterObject)
                            RCWWalker.BeforeRelease(this);

                        if (inBaseContext)
                            McgMarshal.ComRelease(ptr);
                        else
                            baseContext.EnqueueDelayedComRelease(ptr);
                    }
                }

                //
                // Disposing additional cache
                //
                AdditionalComInterfaceCacheContext[] cacheContext = AcquireAdditionalCacheForRead();
                if (cacheContext != null)
                {
                    for (int i = 0; i < cacheContext.Length; i++)
                    {
                        var cache = cacheContext[i];
                        if (cache == null) continue;

                        bool isCacheContextCurrent = cache.context.IsCurrent;

                        foreach (var cacheEntry in cache.items)
                        {
                            if (IsJupiterObject)
                                RCWWalker.BeforeRelease(this);

                            if (isCacheContextCurrent)
                                McgMarshal.ComRelease(cacheEntry.ptr);
                            else
                                cache.context.EnqueueDelayedComRelease(cacheEntry.ptr);
                        }
                    }
                }
            }

            //
            // Dispose self
            //
            if (IsJupiterObject)
                RCWWalker.BeforeRelease(this);

            m_baseIUnknown.Dispose(inBaseContext);

            //
            // Last step
            // Dispose IJupiterObject*
            //
            if (IsJupiterObject && !IsAggregated)
            {
                RuntimeTypeHandle interfaceType;
                Debug.Assert(m_cachedInterfaces[0].TryGetType(out interfaceType) && interfaceType.IsIJupiterObject());

                RCWWalker.BeforeRelease(this);

                if (inBaseContext)
                    McgMarshal.ComRelease(m_cachedInterfaces[0].GetPtr());
                else
                    baseContext.EnqueueDelayedComRelease(m_cachedInterfaces[0].GetPtr());
            }

            if (IsAggregated)
            {
                //
                // Release the extra AddRef that we did when we create the aggregated CCW
                // This makes sure the CCW is released is nobody else is holding on it and delay the cleanup
                // if there is anybody holding on to it until the final release.
                // For example, Jupiter object's release are posted to the STA thread, which means their
                // final release won't get called until the STA thread process them, and this would
                // create a problem if we clean up CCW in RCW finalization and the jupiter object's
                // final release touch the CCW (such as as Release or QI on ICCW).
                //
                m_outer.Release();
            }

#if ENABLE_WINRT
            if (IsGCPressureSet)
                GC.RemoveMemoryPressure(GCMemoryPressure);
#endif
        }

        internal void RemoveInterfacesForContext(ContextCookie currentContext)
        {
            Debug.Assert(currentContext.IsCurrent && !currentContext.IsDefault);

            //
            // Only clean up if this object is context bound, which could be either
            // 1) context-bound and not free threaded
            // 2) is a jupiter object (which is be free-threaded but considered STA)
            //
            if (IsFreeThreaded && !IsJupiterObject)
                return;

            if (m_baseIUnknown.ContextCookie.Equals(currentContext))
            {
                // We cannot use this object any more, as calls to IUnknown will fail.
                FinalReleaseSelf();
            }
            else
            {
                // We know that the base IUnknown is not in this context; therefore nothing in the
                // "simple" cache is in this context.  But we may have marshaled interfaces into this context,
                // and stored them in the "additional" cache.  Remove and release those interfaces now.
                AdditionalComInterfaceCacheContext[] cache = AcquireAdditionalCacheExclusive();

                try
                {
                    if (cache != null)
                    {
                        for (int i = 0; i < cache.Length; i++)
                        {
                            AdditionalComInterfaceCacheContext cacheContext = cache[i];

                            if (cacheContext != null &&
                                cacheContext.context.ContextCookie.Equals(currentContext))
                            {
                                // Remove the context from the cache . Note that there might be
                                // active readers using cache[i] and it's up to the reader to check
                                // if cache[i] is null
                                cache[i] = null;

                                if (!IsAggregated)
                                {
                                    // Release all interfaces in the context
                                    foreach (var cacheEntry in cacheContext.items)
                                    {
                                        if (IsJupiterObject)
                                            RCWWalker.BeforeRelease(this);

                                        McgMarshal.ComRelease(cacheEntry.ptr);
                                    }
                                }
                            }
                        }
                    }
                }
                finally
                {
                    ReleaseAdditionalCacheExclusive(cache);
                }
            }
        }

        #endregion

        #region Properties

        /// <summary>
        /// Whether the RCW is free-threaded
        /// <summary>
        [DebuggerBrowsable(DebuggerBrowsableState.Never)]
        internal bool IsFreeThreaded
        {
            get
            {
                return m_baseIUnknown.IsFreeThreaded;
            }
        }

        /// <summary>
        /// Whether the RCW is a duplicate RCW that is not saved in cache
        /// </summary>
        [DebuggerBrowsable(DebuggerBrowsableState.Never)]
        internal bool IsDuplicate
        {
            get
            {
                return (m_flags & ComObjectFlags.IsDuplicate) != 0;
            }
        }

        /// <summary>
        /// Returns the context cookie where this RCW is created
        /// </summary>
        [DebuggerBrowsable(DebuggerBrowsableState.Never)]
        internal ContextCookie ContextCookie
        {
            get
            {
                return m_baseIUnknown.ContextCookie;
            }
        }

        [DebuggerBrowsable(DebuggerBrowsableState.Never)]
        internal ComObjectFlags Flags
        {
            get
            {
                return m_flags;
            }
        }

        #endregion

        #region QueryInterface
        /// <summary>
        /// QueryInterface for the specified IID and returns a Non-AddRefed COM interface pointer for the
        /// the interface you've specified. The returned interface pointer is always callable from current
        /// context
        /// NOTE: This version uses RuntimeTypeHandle and is much faster than GUID version
        /// </summary>
        /// <returns>A non-AddRef-ed interface pointer that is callable under current context</returns>
        private int QueryInterface_NoAddRef(
            RuntimeTypeHandle interfaceType,
            bool cacheOnly,
            out IntPtr pComPtr)
        {
#if !RHTESTCL
            // Throw if the underlying object is already disposed.
            if (m_baseIUnknown.IsDisposed)
            {
                throw new InvalidComObjectException(SR.Excep_InvalidComObject_NoRCW_Wrapper);
            }
#endif

            ContextCookie currentCookie = ContextCookie.Default;

            //
            // Do we have an existing cached interface in the simple cache that matches
            //

            // For free-threaded RCWs we don't care about context
            bool matchContext = m_baseIUnknown.IsFreeThreaded;

            if (!matchContext)
            {
                // In most cases WinRT objects are free-threaded, so we'll usually skip the context cookie
                // check
                // If we did came here, initialize the currentCookie for use later and check whether the
                // coookie matches
                currentCookie = ContextCookie.Current;
                matchContext = currentCookie.Equals(m_baseIUnknown.ContextCookie);
            }

            if (matchContext)
            {
                //
                // Search for simple fixed locking cache where context always match
                // NOTE: it is important to use Length instead of the constant because the compiler would
                // eliminate the range check (for the most part) when we are using Length
                //
                for (int i = 0; i < m_cachedInterfaces.Length; ++i)
                {
                    //
                    // Check whether this is the same COM interface as cached
                    //
                    if (m_cachedInterfaces[i].TryReadCachedNativeInterface(interfaceType, out pComPtr))
                    {
                        return Interop.COM.S_OK;
                    }
                }
            }

            //
            // No match found in the simple interface cache
            // Proceed to the slow path only if we want to do the actual cache look-up.
            //
            return QueryInterface_NoAddRef_Slow(interfaceType, ref currentCookie, cacheOnly, out pComPtr);
        }

        /// <summary>
        /// QueryInterface for the specified IID and returns a Non-AddRefed COM interface pointer for the
        /// the interface you've specified. The returned interface pointer is always callable from current
        /// context
        /// NOTE: This version uses RuntimeTypeHandle and is much faster than GUID version
        /// </summary>
        /// <returns>A non-AddRef-ed interface pointer that is callable under current context</returns>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        internal IntPtr QueryInterface_NoAddRef_Internal(
            RuntimeTypeHandle interfaceType,
            bool cacheOnly = false,
            bool throwOnQueryInterfaceFailure = true)
        {

#if !RHTESTCL
            // Throw if the underlying object is already disposed.
            if (m_baseIUnknown.IsDisposed)
            {
                throw new InvalidComObjectException(SR.Excep_InvalidComObject_NoRCW_Wrapper);
            }
#endif
            bool matchContext = m_baseIUnknown.IsFreeThreaded || m_baseIUnknown.ContextCookie.Equals(ContextCookie.Current);
            if (matchContext)
            {
                //
                // Search for simple fixed locking cache where context always match
                // NOTE: it is important to use Length instead of the constant because the compiler would
                // eliminate the range check (for the most part) when we are using Length
                //
                int i = 0;
                do
                {
                    IntPtr cachedComPtr;
                    if (m_cachedInterfaces[i].TryReadCachedNativeInterface(interfaceType, out cachedComPtr))
                    {
                        return cachedComPtr;
                    }
                } while (++i < m_cachedInterfaces.Length);
            }

            IntPtr pComPtr;
            ContextCookie currentCookie = ContextCookie.Current;
            //
            // No match found in the simple interface cache
            // Proceed to the slow path only if we want to do the actual cache look-up.
            //
            int hr = QueryInterface_NoAddRef_Slow(interfaceType, ref currentCookie, cacheOnly, out pComPtr);
            if (throwOnQueryInterfaceFailure && pComPtr == default(IntPtr))
            {
                throw CreateInvalidCastExceptionForFailedQI(interfaceType, hr);
            }
            return pComPtr;
        }

        /// <summary>
        /// Slow path of QueryInterface that does not look at any cache.
        /// NOTE: MethodImpl(NoInlining) is necessary because Bartok is trying to be "helpful" by inlining
        /// these calls while in other cases it does not inline when it should.
        /// </summary>
        [MethodImpl(MethodImplOptions.NoInlining)]
        private int QueryInterface_NoAddRef_SlowNoCacheLookup(
            RuntimeTypeHandle interfaceType,
            ContextCookie currentCookie,
            out IntPtr pComPtr)
        {

#if ENABLE_WINRT
            // Make sure cookie is initialized
            Debug.Assert(!currentCookie.IsDefault);
#endif

            // Before we QI, we need to make sure we always QI in the right context by retrieving
            // the right IUnknown under current context
            // NOTE: This IUnknown* is AddRef-ed
            //
            if (m_baseIUnknown.IsFreeThreaded || m_baseIUnknown.ContextCookie.Equals(currentCookie))
            {
                //
                // We are in the right context - we can use the IUnknown directly
                //
                return QueryInterfaceAndInsertToCache_NoAddRef(
                    m_baseIUnknown.ComPointer_UnsafeNoAddRef,
                    interfaceType,
                    currentCookie,
                    out pComPtr);
            }
            else
            {
                //
                // Not in the right context - we need to get the right IUnknown through marshalling
                //
                IntPtr pIUnknown = default(IntPtr);

                try
                {
                    pIUnknown = m_baseIUnknown.GetIUnknownForCurrContext(currentCookie);

                    return QueryInterfaceAndInsertToCache_NoAddRef(
                        pIUnknown,
                        interfaceType,
                        currentCookie,
                        out pComPtr);
                }
                finally
                {
                    if (pIUnknown != default(IntPtr))
                    {
                        McgMarshal.ComRelease(pIUnknown);
                    }
                }
            }
        }

        /// <summary>
        /// Slow path of QueryInterface that looks up additional interface cache and does a QueryInterface if
        /// no match can be found in the cache
        /// NOTE: MethodImpl(NoInlining) is necessary becauase Bartok is trying to be "helpful" by inlining
        /// these calls while in other cases it does not inline when it should.
        /// </summary>
        [MethodImpl(MethodImplOptions.NoInlining)]
        private int QueryInterface_NoAddRef_Slow(
            RuntimeTypeHandle interfaceType,
            ref ContextCookie currentCookie,
            bool cacheOnly,
            out IntPtr pComPtr)
        {
            // Make sure cookie is initialized
            if (currentCookie.IsDefault)
                currentCookie = ContextCookie.Current;

            if (TryGetInterfacePointerFromAdditionalCache_NoAddRef(interfaceType, out pComPtr, currentCookie))
            {
                //
                // We've found a match in the additional interface cache
                //
                return 0;
            }

            if (!cacheOnly)
            {
                return QueryInterface_NoAddRef_SlowNoCacheLookup(interfaceType, currentCookie, out pComPtr);
            }

            pComPtr = default(IntPtr);
            return 0;
        }

        /// <summary>
        /// Do a QueryInterface and insert the returned pointer to the cache
        /// Return the QI-ed interface pointer as a result - no need to release
        /// </summary>
        private int QueryInterfaceAndInsertToCache_NoAddRef(
            IntPtr pIUnknown,
            RuntimeTypeHandle interfaceType,
            ContextCookie currentCookie,
            out IntPtr pComPtr)
        {
            int hr = 0;
            //
            // QI the underlying COM object and insert into cache
            // Cache will assume it is already add-refed, so no need to release
            //
            Guid intfGuid = interfaceType.GetInterfaceGuid();
            pComPtr = McgMarshal.ComQueryInterfaceNoThrow(pIUnknown, ref intfGuid, out hr);
            IntPtr pTempComPtr = pComPtr;

            try
            {
                if (InteropEventProvider.IsEnabled())
                    InteropEventProvider.Log.TaskRCWQueryInterface(
                        (long)InteropExtensions.GetObjectID(this), (long)ContextCookie.pCookie,
                        intfGuid,
                        interfaceType.GetRawValue().ToInt64());

                if (pComPtr == default(IntPtr))
                {
                    if (InteropEventProvider.IsEnabled())
                        InteropEventProvider.Log.TaskRCWQueryInterfaceFailure(
                            (long)InteropExtensions.GetObjectID(this), (long)ContextCookie.pCookie,
                            intfGuid, hr);

                    return hr;
                }

                //
                // Cache the result and zero out pComItf if we want to transfer the ref count
                //
                InsertIntoCache(interfaceType, currentCookie, ref pTempComPtr, false);
                return 0;
            }
            finally
            {
                McgMarshal.ComSafeRelease(pTempComPtr);
            }
        }

        internal RuntimeTypeHandle FindCastableGenericInterfaceInCache(RuntimeTypeHandle interfaceType, out IntPtr pComPtr)
        {
            pComPtr = IntPtr.Zero;

#if !RHTESTCL
            // Throw if the underlying object is already disposed.
            if (m_baseIUnknown.IsDisposed)
            {
                throw new InvalidComObjectException(SR.Excep_InvalidComObject_NoRCW_Wrapper);
            }
#endif

#if !RHTESTCL && PROJECTN

            //
            // Search the existing cached interfaces in the simple cache that we can cast to the input interface type
            //

            // For free-threaded RCWs we don't care about context
            bool matchContext = m_baseIUnknown.IsFreeThreaded;

            if (!matchContext)
            {
                // In most cases WinRT objects are free-threaded, so we'll usually skip the context cookie
                // check
                // If we did came here, initialize the currentCookie for use later and check whether the
                // coookie matches
                matchContext = ContextCookie.Current.Equals(m_baseIUnknown.ContextCookie);
            }

            if (matchContext)
            {
                //
                // Search for simple fixed locking cache where context always match
                // NOTE: it is important to use Length instead of the constant because the compiler would
                // eliminate the range check (for the most part) when we are using Length
                //
                for (int i = 0; i < m_cachedInterfaces.Length; ++i)
                {
                    RuntimeTypeHandle castableInterface;
                    if (m_cachedInterfaces[i].IsCastableEntry(interfaceType, out pComPtr, out castableInterface))
                    {
                        if (castableInterface.IsGenericType())
                            return castableInterface;
                    }
                }
            }
            
            //
            // Search for additional growable interface cache
            //
            AdditionalComInterfaceCacheContext[] cacheContext = AcquireAdditionalCacheForRead();
            if (cacheContext != null)
            {
                for (int i = 0; i < cacheContext.Length; i++)
                {
                    var cache = cacheContext[i];
                    if (cache == null) continue;

                    if (cache.context.ContextCookie.Equals(ContextCookie.Current))
                    {
                        foreach (var item in cache.items)
                        {
                            if (!item.typeHandle.IsGenericType())
                                continue;

                            if (!InteropExtensions.AreTypesAssignable(item.typeHandle, interfaceType))
                                continue;

                            pComPtr = item.ptr;
                            return item.typeHandle;
                        }
                    }
                }
            }
#endif

            return default(RuntimeTypeHandle);
        }

        private InvalidCastException CreateInvalidCastExceptionForFailedQI(RuntimeTypeHandle interfaceType, int hr)
        {
#if RHTESTCL
            throw new InvalidCastException();
#elif ENABLE_WINRT
            string comObjectDisplayName = this.GetType().TypeHandle.GetDisplayName();
            string interfaceDisplayName = interfaceType.GetDisplayName();

            if (comObjectDisplayName == null)
            {
                comObjectDisplayName = "System.__ComObject";
            }

            if (interfaceDisplayName == null)
            {
                interfaceDisplayName = SR.MissingMetadataType;
            }

            if (hr == Interop.COM.E_NOINTERFACE && interfaceType.IsSupportIInspectable())
            {
                // If this is a WinRT secenario and the failure is E_NOINTERFACE then display the standard
                // InvalidCastException as most developers are not interested in IID's or HRESULTS
                return new InvalidCastException(SR.Format(SR.InvalidCast_WinRT, comObjectDisplayName, interfaceDisplayName));
            }
            else
            {
                string errorMessage = ExternalInterop.GetMessage(hr);

                if(errorMessage == null)
                {
                    errorMessage = String.Format("({0} 0x{1:X})", SR.Excep_FromHResult, hr);
                }
                else
                {
                    errorMessage = String.Format("{0} ({1} 0x{2:X})", errorMessage, SR.Excep_FromHResult, hr);
                }

                return new InvalidCastException(SR.Format(
                    SR.InvalidCast_Com,
                    comObjectDisplayName,
                    interfaceDisplayName,
                    interfaceType.GetInterfaceGuid().ToString("B").ToUpper(),
                    errorMessage));
            }
#else // !ENABLE_WINRT
            string errorMessage = String.Format("({0} 0x{1:X})", SR.Excep_FromHResult, hr);
            string interfaceDisplayName = interfaceType.GetDisplayName();

            return new InvalidCastException(SR.Format(
                   SR.InvalidCast_Com,
                   "__ComObject",
                   interfaceDisplayName,
                   interfaceType.GetInterfaceGuid().ToString("B").ToUpper(),
                   errorMessage));

#endif
        }

        #endregion

        #region Cache Management

        /// <summary>
        /// Insert COM interface pointer into our cache. The cache will NOT do a AddRef and will transfer
        /// the ref count ownership to itself
        /// Note: this function might introduce duplicates in the cache, but we don't really care
        /// </summary>
        internal void InsertIntoCache(
            RuntimeTypeHandle interfaceType,
            ContextCookie cookie,
            ref IntPtr pComPtr,
            bool checkDup)
        {
            Debug.Assert(cookie.IsCurrent);

            bool cachedInSimpleCache = false;

            //
            // Instantiate the dynamic adapter object, if needed
            //
            ComInterfaceDynamicAdapter adapter = null;

            if (interfaceType.HasDynamicAdapterClass())
            {
                adapter = (ComInterfaceDynamicAdapter)InteropExtensions.RuntimeNewObject(interfaceType.GetDynamicAdapterClassType());
                adapter.Initialize(this);
            }
            else if (m_baseIUnknown.IsFreeThreaded || cookie.Equals(m_baseIUnknown.ContextCookie))
            {
                //
                // Search for a match, or free slots in interface cache only when the context matches
                //
                for (int i = 0; i < FIXED_CACHE_SIZE; ++i)
                {
                    if (m_cachedInterfaces[i].Assign(pComPtr, interfaceType))
                    {
                        cachedInSimpleCache = true;
                        break;
                    }
                    else if (checkDup)
                    {
                        if (m_cachedInterfaces[i].IsMatchingEntry(pComPtr, interfaceType)) // found exact match, no need to store
                        {
                            return; // If duplicate found, skipping clear pComPtr and RCWWalker.AfterAddRef
                        }
                    }
                }
            }

            if (!cachedInSimpleCache)
            {
                if (!AddToAdditionalCache(cookie, interfaceType, pComPtr, adapter, checkDup))
                {
                    return; // If duplicate found, skipping clear pComPtr and RCWWalker.AfterAddRef
                }
            }

            if (!IsAggregated)
            {
                //
                // "Swallow" the ref count and transfer it into our cache if this is not aggregation
                // Optionally call out to jupiter to tell them we've "done an AddRef"
                //
                pComPtr = default(IntPtr);

                if (IsJupiterObject)
                    RCWWalker.AfterAddRef(this);
            }
            else
            {
                //
                // Otherwise, this COM object is aggregated
                // We can't add ref on the interface pointer because this would keep the CCW
                // alive which would keep this RCW alive, forming a cycle.
                // NOTE: Since in aggregation it is invalid to maintain a tear-off's
                // lifetime separately (due to the outer IUnknown delegation), we can safely
                // keep this interface pointer cached without a AddRef
                //
            }
        }

        /// <summary>
        /// Look up additional interface cache that are context-aware, growing cache which requires locking
        /// </summary>
        private bool TryGetInterfacePointerFromAdditionalCache_NoAddRef(RuntimeTypeHandle interfaceType, out IntPtr pComPtr, ContextCookie currentCookie)
        {
            //
            // Search for additional growable interface cache
            //
            AdditionalComInterfaceCacheContext[] cacheContext = AcquireAdditionalCacheForRead();
            if (cacheContext != null)
            {
                for (int i = 0; i < cacheContext.Length; i++)
                {
                    var cache = cacheContext[i];
                    if (cache == null) continue;

                    if (cache.context.ContextCookie.Equals(currentCookie))
                    {
                        foreach (var item in cache.items)
                        {
                            if (item.typeHandle.Equals(interfaceType))
                            {
                                pComPtr = item.ptr;
                                return true;
                            }
                        }
                    }
                }
            }

            pComPtr = default(IntPtr);
            return false;
        }
        #endregion

        #region CastableObject implementation for weakly typed RCWs
#if !RHTESTCL && PROJECTN && ENABLE_WINRT
        object CastToICollectionHelper(RuntimeTypeHandle genericTypeDef, RuntimeTypeHandle[] genericArguments, bool testForIDictionary)
        {
            Debug.Assert(genericTypeDef.Equals(typeof(ICollection<>).TypeHandle) || genericTypeDef.Equals(typeof(IReadOnlyCollection<>).TypeHandle));

            bool isReadOnly = genericTypeDef.Equals(typeof(IReadOnlyCollection<>).TypeHandle);

            bool isICollectionOfKvp = false;
            RuntimeTypeHandle[] ikvpArgs = null;

            if (genericArguments[0].IsGenericType())
            {
                RuntimeTypeHandle kvpTypeDef = RuntimeAugments.GetGenericInstantiation(genericArguments[0], out ikvpArgs);
                isICollectionOfKvp = kvpTypeDef.Equals(typeof(KeyValuePair<,>).TypeHandle);
            }

            // Ignore a QI on the IDictionary<,> type if the ICollection<T> interface is not instantiated over KeyValuePair<,>
            if (testForIDictionary && !isICollectionOfKvp)
                return null;

            RuntimeTypeHandle iTypeToQI;
            RuntimeTypeHandle genericTypeDefToQuery = testForIDictionary ? typeof(IDictionary<,>).TypeHandle : typeof(IList<>).TypeHandle;
            RuntimeTypeHandle[] genericTypeArgs = testForIDictionary ? ikvpArgs : genericArguments;

            if (isReadOnly)
                genericTypeDefToQuery = testForIDictionary ? typeof(IReadOnlyDictionary<,>).TypeHandle : typeof(IReadOnlyList<>).TypeHandle;

            Debug.Assert(
                ( testForIDictionary && genericTypeArgs != null && genericTypeArgs.Length == 2) ||
                (!testForIDictionary && genericTypeArgs != null && genericTypeArgs.Length == 1));

            if (!TypeLoaderEnvironment.Instance.TryGetConstructedGenericTypeForComponents(genericTypeDefToQuery, genericTypeArgs, out iTypeToQI))
                return null;    // ERROR

            RuntimeTypeHandle resolvedICollectionType;
            if (TryQITypeForICollection(iTypeToQI, default(RuntimeTypeHandle), out resolvedICollectionType))
            {
                Debug.Assert(iTypeToQI.Equals(resolvedICollectionType));

                if (testForIDictionary)
                {
                    // IDictionary<,> case
                    if (isReadOnly)
                        return McgComHelpers.CreateGenericComDispatcher(typeof(IReadOnlyDictionary_RCWAdapter<,>).TypeHandle, genericTypeArgs, this);
                    else
                        return McgComHelpers.CreateGenericComDispatcher(typeof(IDictionary_RCWAdapter<,>).TypeHandle, genericTypeArgs, this);
                }
                else
                {
                    // IList<> case
                    if (isReadOnly)
                        return McgComHelpers.CreateGenericComDispatcher(typeof(IReadOnlyList_RCWAdapter<>).TypeHandle, genericTypeArgs, this);
                    else
                        return McgComHelpers.CreateGenericComDispatcher(typeof(IList_RCWAdapter<>).TypeHandle, genericTypeArgs, this);
                }
            } 
            else if (isReadOnly && !testForIDictionary)
            {
                //
                // Check for a variant type cast in the cache for IReadOnlyList<T>: IReadOnlyList supports CoVariance
                //
                IntPtr pComPtr; 
                RuntimeTypeHandle variantInterfaceType = FindCastableGenericInterfaceInCache(iTypeToQI, out pComPtr);
                if (!variantInterfaceType.IsInvalid())
                {
                    RuntimeTypeHandle[] variantGenericArguments;
                    RuntimeTypeHandle variantGenericTypeDef = RuntimeAugments.GetGenericInstantiation(variantInterfaceType, out variantGenericArguments);
                    return McgComHelpers.CreateGenericComDispatcher(typeof(IReadOnlyList_RCWAdapter<>).TypeHandle, variantGenericArguments, this);
                }
            }

            // Cannot cast...
            return null;
        }

        /// <summary>
        /// ================================================================================================
        /// COMMENTS from CastableObject.CastToInterface
        ///
        /// This is called if casting this object to the given interface type would otherwise fail. Casting
        /// here means the IL isinst and castclass instructions in the case where they are given an interface
        /// type as the target type.
        ///
        /// It allows the implementor to return an alternate class type which does implement the interface. The
        /// interface lookup shall be performed again on this type and the corresponding implemented method on 
        /// that class called instead.
        ///
        /// Naturally, since the call is dispatched to a method on a class which does not match the type of the
        /// this pointer, extreme care must be taken in the implementation of the interface methods of this
        /// surrogate type.
        ///
        /// No exception should be thrown from this method (it will cause unpredictable effects, including the
        /// possibility of an immediate failfast).
        /// If the cast cannot be done and this API is called during castclass, then we simply return null so that
        /// the usual InvalidCastException can be thrown, otherwise we also assign an alternate exception to the 
        /// castError output parameter. This parameter is ignored on successful casts or during the evaluation of 
        /// an isinst.
        /// 
        /// The results of this call should be invariant for the same class, interface type pair. That is
        /// because this is the only guard placed before an interface invocation at runtime. If a type decides
        /// it no longer wants to implement a given interface it has no way to synchronize with callers that
        /// have already cached this relationship and can invoke directly via the interface pointer.
        /// 
        /// The results of this lookup are cached so computation of the result is not as perf-sensitive as
        /// IsInstanceOfInterface.
        /// ==========================================================================================
        ///
        /// If this function is called, this means we are being casted with a non-supported interface.
        /// This means:
        /// 1. The object is a weakly-typed RCW __ComObject
        /// 2. The object is a strongly-typed RCW __ComObject derived type, but might support more interface
        /// than what its metadata has specified
        ///
        /// In this case, we perform a QueryInterface to see if we really support that interface
        /// 
        /// Once the QueryInterface is successful, we need to return the correct stub class that implement the 
        /// interface so that RH knows how to dispatch the call, for example:
        ///
        /// class IFoo_RCWAdapter<T>: __ComGenericInterfaceDispatcher, IFoo<T>
        /// {
        ///     public IFoo<T>.Func()
        ///     {
        ///         // ...
        ///     }
        /// }
        /// 
        /// </summary>
        /// <param name="interfaceType">The interface being casted to</param>
        /// <param name="produceCastErrorException">Flag indicating whether casting exceptions should be
        /// produced on unsuccessful casts (i.e. this is a castclass scenario).</param>
        /// <param name="castError">More specific cast failure other than the default InvalidCastException
        /// prepared by the runtime</param>
        /// <returns>Dispatcher class that implements the interface if the cast is valid, null otherwise. </returns>
        protected override object CastToInterface(RuntimeTypeHandle interfaceType, bool produceCastErrorException, out Exception castError)
        {
            // TODO: We currently don't search into any of the MCG generated data in this function, because we still have the old ICastable
            // support. The runtime will call into the ICastable.IsInstanceOfInterface API first (which searches the MCG data), and 
            // will *only* call CastableObject.CastToInterface when the former returns null.
            // When we completely remove the support for ICastable, we'll need to change the behavior of this API to first search into the 
            // MCG generated data for a cast, before returning a dynamically instantiated RCW dispatcher.

            castError = null;
            IntPtr pComPtr = IntPtr.Zero;

            if (!McgModuleManager.UseDynamicInterop)
                return null;

            // CastableObject support used for generics *only* for now

            if (!interfaceType.IsGenericType())
            {
                RuntimeTypeHandle genericInterfaceType = FindCastableGenericInterfaceInCache(interfaceType, out pComPtr);
                if (genericInterfaceType.IsInvalid())
                    return null;
            
                Debug.Assert(genericInterfaceType.IsGenericType());

                interfaceType = genericInterfaceType;
            }

            try
            {
                RuntimeTypeHandle[] genericArguments;
                RuntimeTypeHandle genericTypeDef = RuntimeAugments.GetGenericInstantiation(interfaceType, out genericArguments);

                //
                // ICollection<T> is a very special interface, which could map to either IDictionary<,> or IList<>
                //
                if (genericTypeDef.Equals(typeof(ICollection<>).TypeHandle) || genericTypeDef.Equals(typeof(IReadOnlyCollection<>).TypeHandle))
                {
                    // QI for the IDictionary<,> interface before looking for the IList<KVP<>> interface.
                    // The reason we do it in 2 steps and try the IDictionary cast first is for performance. 
                    // Dynamically instantiating the interface type could be an expensive operation if the 
                    // instantiation was not compiled statically by the toolchain, so we dynamically instantiate 
                    // and QI one type at a time (QI is much cheaper than dynamic type creation).

                    object adapter;

                    if ((adapter = CastToICollectionHelper(genericTypeDef, genericArguments, true /* testForIDictionary */)) != null)
                        return adapter;

                    if ((adapter = CastToICollectionHelper(genericTypeDef, genericArguments, false /* testForIDictionary */)) != null)
                        return adapter;

                    // Cannot cast...
                    return null;
                }

                //
                // Check if we can cast the COM object to the requested interface type
                //
                IntPtr interfacePtr = QueryInterface_NoAddRef_Internal(interfaceType, /* cacheOnly= */ true, /* throwOnQueryInterfaceFailure= */ false);
                if (interfacePtr == IntPtr.Zero)
                {
                    ContextCookie currentCookie = ContextCookie.Current;
            
                    QueryInterface_NoAddRef_SlowNoCacheLookup(interfaceType, currentCookie, out interfacePtr);
                    if (interfacePtr == IntPtr.Zero)
                    {
                        //
                        // Check for a variant type cast in the cache
                        //
                        RuntimeTypeHandle variantInterfaceType = FindCastableGenericInterfaceInCache(interfaceType, out pComPtr);
                        if (variantInterfaceType.IsInvalid())
                            return null;

                        genericTypeDef = RuntimeAugments.GetGenericInstantiation(variantInterfaceType, out genericArguments);
                    }
                }

                //
                // Handle various interface types. Currently, there are a handful of generic 
                // interfaces in WinRT, and we have hand-written dispatchers for all of them.
                //
                RuntimeTypeHandle rcwAdapterType;
                if (s_DynamicRCWAdapters.TryGetValue(genericTypeDef, out rcwAdapterType))
                {
                    return McgComHelpers.CreateGenericComDispatcher(rcwAdapterType, genericArguments, this);
                }

                //
                // There are some special-case adapters generated by MCG today (IObservableMap, and IObservableVector).
                //
                rcwAdapterType = genericTypeDef.GetDynamicAdapterClassType();
                if (!rcwAdapterType.IsInvalid())
                {
                    Debug.Assert(
                        genericTypeDef.Equals(typeof(global::Windows.Foundation.Collections.IObservableVector<>).TypeHandle) ||
                        genericTypeDef.Equals(typeof(global::Windows.Foundation.Collections.IObservableMap<,>).TypeHandle));

                    return McgComHelpers.CreateGenericComDispatcher(rcwAdapterType, genericArguments, this);
                }
            }
            catch (Exception ex)
            {
                // We are not allowed to leak exception out from here
                // Instead, set castError to the exception being thrown
                castError = ex;
            }

            return null;
        }
#endif
        #endregion

        #region ICastable implementation for weakly typed RCWs
        /// <summary>
        /// ================================================================================================
        /// COMMENTS from ICastable.IsInstanceOfInterface
        ///
        /// This is called if casting this object to the given interface type would otherwise fail. Casting
        /// here means the IL isinst and castclass instructions in the case where they are given an interface
        /// type as the target type.
        ///
        /// A return value of true indicates the cast is valid.
        ///
        /// If false is returned when this is called as part of a castclass then the usual InvalidCastException
        /// will be thrown unless an alternate exception is assigned to the castError output parameter. This
        /// parameter is ignored on successful casts or during the evaluation of an isinst (which returns null
        /// rather than throwing on error).
        ///
        /// No exception should be thrown from this method (it will cause unpredictable effects, including the
        /// possibility of an immediate failfast).
        ///
        /// The results of this call are not cached, so it is advisable to provide a performant implementation.
        ///
        /// The results of this call should be invariant for the same class, interface type pair. That is
        /// because this is the only guard placed before an interface invocation at runtime. If a type decides
        /// it no longer wants to implement a given interface it has no way to synchronize with callers that
        /// have already cached this relationship and can invoke directly via the interface pointer.
        /// ================================================================================================
        ///
        /// If this function is called, this means we are being casted with a non-supported interface.
        /// This means:
        /// 1. The object is a weakly-typed RCW __ComObject
        /// 2. The object is a strongly-typed RCW __ComObject derived type, but might support more interface
        /// than what its metadata has specified
        ///
        /// In this case, we perform a QueryInterface to see if we really support that interface
        /// </summary>
        /// <param name="interfaceType">The interface being casted to</param>
        /// <param name="castError">More specific cast failure other than the default InvalidCastException
        /// prepared by the runtime</param>
        /// <returns>True means it is supported. False no. </returns>
        bool ICastable.IsInstanceOfInterface(RuntimeTypeHandle interfaceType, out Exception castError)
        {
            castError = null;
            IntPtr pComPtr;

            //
            // We have a mode where we force everything to go through the dynamic interop path. When that mode
            // is used, mcg will not generate dispatchers for generic RCWs, so we need to make sure that we
            // don't return true in this API, and end up with a FailFast in the implementation of ICastable.GetImplType 
            // below, just because we can't find the adapter.
            // When dynamic interop is not enabled, we can just skip that check here, and pretend the interface has
            // a valid dispatcher, if the checks in this function succeed.
            // TODO: This will change when we remove the support for the traditional ICastable and replace it with CastableObject.
            //
            bool hasValidDispatcher = true;

#if !RHTESTCL && PROJECTN && ENABLE_WINRT
            hasValidDispatcher = McgModuleManager.UseDynamicInterop && interfaceType.IsGenericType() ? 
                !interfaceType.GetDispatchClassType().IsInvalid() : 
                true;
#endif

            try
            {
                pComPtr = QueryInterface_NoAddRef_Internal(interfaceType, /* cacheOnly= */ true, /* throwOnQueryInterfaceFailure= */ false);
                if (pComPtr != default(IntPtr))
                    return hasValidDispatcher;

                //
                // This is typeHandle for ICollection<KeyValuePair<>> which could be
                // Dictionary or List<KeyValuePair<>>
                //
                RuntimeTypeHandle secondTypeHandle;
                RuntimeTypeHandle firstTypeHandle;
                if (McgModuleManager.TryGetTypeHandleForICollecton(interfaceType, out firstTypeHandle, out secondTypeHandle))
                {
                    if (!firstTypeHandle.IsNull() || !secondTypeHandle.IsNull())
                    {
                        RuntimeTypeHandle resolvedTypeHandle;
                        if (!TryQITypeForICollection(firstTypeHandle, secondTypeHandle, out resolvedTypeHandle))
                            return false;

                        // Again... only check for a valid dispatcher when dynamic interop is in use (see explanation above)
                        return McgModuleManager.UseDynamicInterop ? !resolvedTypeHandle.GetDispatchClassType().IsInvalid() : true;
                    }
                }

                //
                // any data for interfaceType
                //
                if (!interfaceType.HasInterfaceData())
                    return false;

                //
                // QI for that interfce
                //
                int hr = QueryInterface_NoAddRef(interfaceType, /* cacheOnly= */ false, out pComPtr);
                if (pComPtr != default(IntPtr))
                    return hasValidDispatcher;

                //
                // Is there a dynamic adapter for the interface?
                //
                if (interfaceType.HasDynamicAdapterClass() && GetDynamicAdapterInternal(interfaceType, default(RuntimeTypeHandle)) != null)
                    return hasValidDispatcher;

                castError = CreateInvalidCastExceptionForFailedQI(interfaceType, hr);
                return false;
            }
            catch (Exception ex)
            {
                // We are not allowed to leak exception out from here
                // Instead, set castError to the exception being thrown
                castError = ex;
            }

            return false;
        }

        /// <summary>
        ///
        /// ================================================================================================
        /// COMMENTS from ICastable.GetImplType
        ///
        /// This is called as part of the interface dispatch mechanism when the dispatcher logic cannot find
        /// the given interface type in the interface map of this object.
        ///
        /// It allows the implementor to return an alternate class type which does implement the interface. The
        /// interface lookup shall be performed again on this type (failure to find the interface this time
        /// resulting in a fail fast) and the corresponding implemented method on that class called instead.
        ///
        /// Naturally, since the call is dispatched to a method on a class which does not match the type of the
        /// this pointer, extreme care must be taken in the implementation of the interface methods of this
        /// surrogate type.
        ///
        /// No exception should be thrown from this method (it will cause unpredictable effects, including the
        /// possibility of an immediate failfast).
        ///
        /// There is no error path defined here. By construction all interface dispatches will already have
        /// been verified via the castclass/isinst mechanism (and thus a call to IsInstanceOfInterface above)
        /// so this method is expected to succeed in all cases. The contract for interface dispatch does not
        /// include any errors from the infrastructure, of which this is a part.
        ///
        /// The results of this lookup are cached so computation of the result is not as perf-sensitive as
        /// IsInstanceOfInterface.
        /// ==========================================================================================
        ///
        /// If we are here, it means we've previously succeeded in ICastable.IsInstanceOfInterface, and
        /// we need to return the correct stub class that implement the interface so that RH knows how to
        /// dispatch the call, for example:
        ///
        /// class IFoo_StubClass: __ComObject, IFoo
        /// {
        ///     public IFoo.Bar()
        ///     {
        ///         // Interop code for IFoo.Bar goes here
        ///     }
        /// }
        ///
        /// Note that the stub class in this case needs to be compatible in terms of object layout with
        /// 'this', and the most obvious way to get that is to derive from __ComObject
        /// </summary>
        /// <param name="interfaceType">The interface type we need to dispatch</param>
        /// <returns>The stub class where RH dispatch interface calls to</returns>
        RuntimeTypeHandle ICastable.GetImplType(RuntimeTypeHandle interfaceType)
        {
            RuntimeTypeHandle dispatchClassType = interfaceType.GetDispatchClassType();
            if (!dispatchClassType.IsInvalid())
                return dispatchClassType;

            // ICollection<T>/IReadOnlyCollection<T> case
            RuntimeTypeHandle firstICollectionType;
            RuntimeTypeHandle secondICollectionType;
            if (McgModuleManager.TryGetTypeHandleForICollecton(interfaceType, out firstICollectionType, out secondICollectionType))
            {
                RuntimeTypeHandle resolvedICollectionType;
                if (!secondICollectionType.IsNull())
                {
                    // if _ComObject doesn't support QI for first ICollectionType and second ICollectionType,
                    // return interfaceType, so later,we will have invalidcast exception
                    if (!TryQITypeForICollection(firstICollectionType, secondICollectionType, out resolvedICollectionType))
                        return interfaceType;
                }
                else
                {
                    resolvedICollectionType = firstICollectionType;
                }

                dispatchClassType = resolvedICollectionType.GetDispatchClassType();
                if (!dispatchClassType.IsInvalid())
                    return dispatchClassType;
            }

#if !RHTESTCL
            // RCW is discarded for this interface type
            Environment.FailFast(McgTypeHelpers.GetDiagnosticMessageForMissingType(interfaceType));
#else
            Environment.FailFast("RCW is discarded.");
#endif
            // Never hit
            return default(RuntimeTypeHandle);
        }

#endregion

        //
        // Get the dynamic adapter object associated with this COM object for the given interface.
        // If the first typeInfo fails, try the second one. If both fails to get a dynamic adapter
        // this function throws an InvalidCastException
        //
        internal unsafe object GetDynamicAdapter(RuntimeTypeHandle requestedType, RuntimeTypeHandle targetType)
        {
            object result = GetDynamicAdapterInternal(requestedType, targetType);
            if (result == null)
            {
                //
                // We did not find a suitable dynamic adapter for the type. Throw InvalidCastException
                //
                throw new System.InvalidCastException();
            }

            return result;
        }

        /// <summary>
        /// This method resolves the Type for ICollection<KeyValuePair<>> which can't be 
        /// determined statically. 
        /// </summary>
        /// <param name="firstTypeHandle">Type for the Dictionary\ReadOnlyDictionary.</param>
        /// <param name="secondaryTypeHandle">Type for the List or ReadOnlyList.</param>
        /// <param name="resolvedTypeHandle">Type for ICollection<KeyValuePair<>> determined at runtime.</param>
        /// <returns>Success or failure of resolution.</returns>
        private bool TryQITypeForICollection(RuntimeTypeHandle firstTypeHandle, RuntimeTypeHandle secondaryTypeHandle, out RuntimeTypeHandle resolvedTypeHandle)
        {
            IntPtr interfacePtr;

            // In case __ComObject can be type casted to both IDictionary and IList<KeyValuePair<>>
            // we give IDictionary the preference. first Type point to the RuntimeTypeHandle for IDictionary.

            // We first check in the cache for both.
            // We then check for IDictionary first and IList later.

            // In case none of them succeeds we return false with resolvedTypeHandle set to null.
            resolvedTypeHandle = default(RuntimeTypeHandle);

            // We first check the cache for the two interfaces if this does not succeed we then actually
            // go to the query interface check.
            if (!firstTypeHandle.IsNull())
            {
                interfacePtr = QueryInterface_NoAddRef_Internal(firstTypeHandle, /* cacheOnly= */ true, /* throwOnQueryInterfaceFailure= */ false);
                if (interfacePtr != default(IntPtr))
                {
                    resolvedTypeHandle = firstTypeHandle;
                    return true;
                }
            }

            if (!secondaryTypeHandle.IsNull())
            {
                interfacePtr = QueryInterface_NoAddRef_Internal(secondaryTypeHandle, /* cacheOnly= */ true, /* throwOnQueryInterfaceFailure= */ false);
                if (interfacePtr != default(IntPtr))
                {
                    resolvedTypeHandle = secondaryTypeHandle;
                    return true;
                }
            }

            ContextCookie currentCookie = ContextCookie.Current;
            if (!firstTypeHandle.IsNull())
            {
                QueryInterface_NoAddRef_SlowNoCacheLookup(firstTypeHandle, currentCookie, out interfacePtr);
                if (interfacePtr != default(IntPtr))
                {
                    resolvedTypeHandle = firstTypeHandle;
                    return true;
                }
            }

            if (!secondaryTypeHandle.IsNull())
            {
                QueryInterface_NoAddRef_SlowNoCacheLookup(secondaryTypeHandle, currentCookie, out interfacePtr);
                if (interfacePtr != default(IntPtr))
                {
                    resolvedTypeHandle = secondaryTypeHandle;
                    return true;
                }
            }

            if (!firstTypeHandle.IsNull())
            {
                if (firstTypeHandle.HasDynamicAdapterClass() && GetDynamicAdapterInternal(firstTypeHandle, default(RuntimeTypeHandle)) != null)
                {
                    resolvedTypeHandle = firstTypeHandle;
                    return true;
                }
            }

            if (!secondaryTypeHandle.IsNull())
            {
                if (secondaryTypeHandle.HasDynamicAdapterClass() && GetDynamicAdapterInternal(secondaryTypeHandle, default(RuntimeTypeHandle)) != null)
                {
                    resolvedTypeHandle = secondaryTypeHandle;
                    return true;
                }
            }          
            
            return false;
        }

        private unsafe object GetDynamicAdapterUsingQICache(RuntimeTypeHandle requestedType, AdditionalComInterfaceCacheContext[] cacheContext)
        {
            //
            // Fast path: make a first pass through the cache to find an exact match we've already QI'd for.
            //
            if (cacheContext != null)
            {
                for (int i = 0; i < cacheContext.Length; i++)
                {
                    var cache = cacheContext[i];
                    if (cache == null) continue;

                    foreach (AdditionalComInterfaceCacheItem existingType in cache.items)
                    {
                        if (existingType.typeHandle.Equals(requestedType))
                            return existingType.dynamicAdapter;
                    }
                }
            }

            //
            // We may not have QI'd for this interface yet.  Do so now, in case the object directly supports
            // the requested interface.  If we find it, call ourselves again so our fast path will pick it up.
            //
            if (QueryInterface_NoAddRef_Internal(requestedType, /* cacheOnly= */ false, /* throwOnQueryInterfaceFailure= */ false) != default(IntPtr) && requestedType.HasDynamicAdapterClass())
                return GetDynamicAdapterInternal(requestedType, default(RuntimeTypeHandle));

            return null;
        }

        private unsafe object GetDynamicAdapterUsingVariance(RuntimeTypeHandle requestedType, AdditionalComInterfaceCacheContext[] cacheContext)
        {
            //
            // We may have already QI'd for an interface of a *compatible* type.  For example, we may be asking for
            // IEnumerable, and we know the object supports IEnumerable<Foo>.  Or we may be asking for
            // IReadOnlyList<object>, but the object supports IReadOnlyList<Foo>.  So we search for any existing
            // adapter that implements the requested interface.
            //
            if (cacheContext != null)
            {
                for (int i = 0; i < cacheContext.Length; i++)
                {
                    var cache = cacheContext[i];
                    if (cache == null) continue;

                    foreach (AdditionalComInterfaceCacheItem existingType in cache.items)
                    {
                        if (existingType.dynamicAdapter != null && InteropExtensions.IsInstanceOfInterface(existingType.dynamicAdapter, requestedType))
                            return existingType.dynamicAdapter;
                    }
                }
            }


            //
            // We may have already QI'd for an interface of a compatible type, but not a type with a dynamic adapter.
            // For example, we've QI'd for IList<T>, and we're now asking for IEnumerable.  Every IList<T> is an IEnumerable<T>,
            // which is an IEnumerable - but we haven't constructed an adapter for IEnumerable<T> yet.
            //
            for (int i = 0; i < m_cachedInterfaces.Length; ++i)
            {
                RuntimeTypeHandle cachedType;
                if (m_cachedInterfaces[i].TryGetType(out cachedType))
                {
                    object adapter = FindDynamicAdapterForInterface(requestedType, cachedType);

                    if (adapter != null)
                        return adapter;
                }
            }

            if (cacheContext != null)
            {
                for (int i = 0; i < cacheContext.Length; i++)
                {
                    var cache = cacheContext[i];
                    if (cache == null) continue;

                    foreach (AdditionalComInterfaceCacheItem existingType in cache.items)
                    {
                        // in a race, it's possible someone else already set up an adapter.
                        if (existingType.dynamicAdapter != null && InteropExtensions.IsInstanceOfInterface(existingType.dynamicAdapter, requestedType))
                            return existingType.dynamicAdapter;

                        object adapter = FindDynamicAdapterForInterface(requestedType, existingType.typeHandle);

                        if (adapter != null)
                            return adapter;
                    }
                }
            }

            //
            // At this point we *could* just go ahead and QI for every known type that is assignable to the requested type.
            // But that is potentially hundreds of types, and we may be making these calls across process boundaries, which
            // would be very expensive.  At any rate, the CLR doesn't do this, so we'll maintain compatibility and simply fail
            // here.
            //
            return null;
        }

        /// <summary>
        /// The GetDynamicAdapterInternal searches for the Dynamic Adapter in the following order:
        /// 1. Search exact match for requestedType in cache and QI
        /// 2. Search exact match for targetType in cache and QI
        /// 3. Search cache using variant rules for requestedType
        /// </summary>
        private unsafe object GetDynamicAdapterInternal(RuntimeTypeHandle requestedType, RuntimeTypeHandle targetType)
        {
            Debug.Assert(requestedType.HasDynamicAdapterClass() || requestedType.IsGenericType());

            Debug.Assert(targetType.IsNull() || targetType.HasDynamicAdapterClass());

            AdditionalComInterfaceCacheContext[] cacheContext = AcquireAdditionalCacheForRead();

            //
            //  Try to find an exact match for requestedType in the cache and QI
            //
            object dynamicAdapter = GetDynamicAdapterUsingQICache(requestedType, cacheContext);

            if (dynamicAdapter != null)
                return dynamicAdapter;

            //
            // If targetType is null or targetType and requestedType are same we don't need 
            // process targetType because that will not provide us the required dynamic adapter
            //
            if (!targetType.IsNull() && !requestedType.Equals(targetType))
            {
                dynamicAdapter = GetDynamicAdapterUsingQICache(targetType, cacheContext);

                if (dynamicAdapter != null)
                    return dynamicAdapter;
            }

            //
            // Search for exact matche of requestedType and targetType failed. Try to get dynamic
            // adapter for types using variance.
            //
            dynamicAdapter = GetDynamicAdapterUsingVariance(requestedType, cacheContext);
            if (dynamicAdapter != null)
                return dynamicAdapter;

#if !RHTESTCL && PROJECTN && ENABLE_WINRT
            // Try dynamic rcw, The Caller will generate/throw exception if return null
            Exception e;
            dynamicAdapter = CastToInterface(requestedType, /*produceCastErrorException*/ false, out e);
#endif

            return dynamicAdapter;
        }

        private object FindDynamicAdapterForInterface(RuntimeTypeHandle requestedType, RuntimeTypeHandle existingType)
        {
            if (!existingType.IsNull() && // IJupiterObject has a null InterfaceType
                InteropExtensions.AreTypesAssignable(existingType, requestedType))
            {
                //
                // Now we need to find a type that is assignable *from* the compatible type, and *to* the requested
                // type.  So if we just found IList<T>, and are asking for IEnumerable, we need to find IEnumerable<T>.
                // We can't directly construct a RuntimeTypeHandle for IEnumerable<T> without reflection, so we have to
                // go search McgModuleManager for a suitable type.
                //
                RuntimeTypeHandle intermediateType = McgModuleManager.FindTypeSupportDynamic(
                    type => InteropExtensions.AreTypesAssignable(existingType, type) &&
                            InteropExtensions.AreTypesAssignable(type, requestedType) &&
                            QueryInterface_NoAddRef_Internal(type, /* cacheOnly= */ false, /* throwOnQueryInterfaceFailure= */ false) != default(IntPtr));

                if (!intermediateType.IsNull())
                    return GetDynamicAdapterInternal(intermediateType, default(RuntimeTypeHandle));
            }

            return null;
        }

#if ENABLE_WINRT

        /// <summary>
        /// Try to find matching Property in cached interface
        /// </summary>
        /// <param name="matchingDelegate"></param>
        /// <returns>if it cann't find it, return null</returns>
        internal PropertyInfo GetMatchingProperty(Func<PropertyInfo, bool> matchingDelegate)
        {
            BindingFlags Everything = BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance;
            // first check Simple ComInterface Cache
            for (int i = 0; i < m_cachedInterfaces.Length; i++)
            {
                RuntimeTypeHandle cachedType;
                if (m_cachedInterfaces[i].TryGetType(out cachedType))
                {
                    Type interfaceType = InteropExtensions.GetTypeFromHandle(cachedType);
                    foreach (PropertyInfo propertyInfo in interfaceType.GetProperties(Everything))
                    {
                        if (matchingDelegate(propertyInfo))
                            return propertyInfo;
                    }
                }
            }

            // Check additional interface cache
            AdditionalComInterfaceCacheContext[] cacheContext = AcquireAdditionalCacheForRead();
            if (cacheContext != null)
            {
                for (int i = 0; i < cacheContext.Length; i++)
                {
                    var item = cacheContext[i];
                    if (item != null)
                    {
                        Type interfaceType = InteropExtensions.GetTypeFromHandle(item.items.GetTypeHandle());
                        foreach (var propertyInfo in interfaceType.GetProperties(Everything))
                        {
                            if (matchingDelegate(propertyInfo))
                                return propertyInfo;
                        }
                    }
                }
            }

            // doesn't find anything
            return null;
        }
#endif

        /// <summary>
        /// This method implements the ToString() method for weakly typed RCWs
        /// 1. Compute whether the __ComObject supports IStringable and cache the value.
        /// 2. If the __ComObject supports IStringable call ToString() of that method.
        /// 3. else call default Object.ToString() method.
        /// </summary>
        /// <returns></returns>
        public override string ToString()
        {
#if ENABLE_WINRT
            string toString;

            if (IStringableHelper.TryGetIStringableToString(this, out toString))
            {
                return toString;
            }
            else
#endif
            {
                return base.ToString();
            }
        }
    }

}

namespace System.Runtime.InteropServices
{
    /// <summary>
    /// Represents COM context cookie
    /// NOTE: The cookie could become INVALID if the context/apartment is gone and reused for another context!!!
    /// It is only safe if you use it with ContextEntry which can make sure the context cookie can always
    /// be valid
    /// </summary>
    internal struct ContextCookie
    {
        internal IntPtr pCookie;

        private ContextCookie(IntPtr _pCookie)
        {
            pCookie = _pCookie;
        }

        /// <summary>
        /// Returns the default context cookie
        /// </summary>
        internal static ContextCookie Default
        {
            get
            {
                return new ContextCookie(default(IntPtr));
            }
        }

        /// <summary>
        /// Whether this is a default context cookie
        /// </summary>
        internal bool IsDefault
        {
            get
            {
                return pCookie == default(IntPtr);
            }
        }

        /// <summary>
        /// Whether the two context cookie are the same
        /// </summary>
        internal bool Equals(ContextCookie cookie)
        {
            return (this.pCookie == cookie.pCookie);
        }

        /// <summary>
        /// Whether this context cookie matches the current context
        /// NOTE: This does a P/Invoke so try to avoid this whenever possible
        /// </summary>
        internal bool IsCurrent
        {
            get
            {
                return (Current.pCookie == this.pCookie);
            }
        }

        /// <summary>
        /// Retrieve ContextCookie of current apartment
        /// NOTE: This does a P/Invoke so try to cache this whenever possible
        /// </summary>
        /// <returns>The current context cookie</returns>
        internal static ContextCookie Current
        {

            [MethodImpl(MethodImplOptions.NoInlining)]
            get
            {
#if ENABLE_MIN_WINRT
                IntPtr pCookie;
                int hr = ExternalInterop.CoGetContextToken(out pCookie);
                if (hr < 0)
                {
                    Debug.Fail("CoGetContextToken failed");
                    pCookie = default(IntPtr);
                }
                return new ContextCookie(pCookie);

#else
                return ContextCookie.Default;
#endif
            }
        }
    }

    /// <summary>
    /// Comparer for ContextCookie
    /// </summary>
    internal class ContextCookieComparer : IEqualityComparer<ContextCookie>
    {
        bool IEqualityComparer<ContextCookie>.Equals(ContextCookie x, ContextCookie y)
        {
            return x.Equals(y);
        }

        int IEqualityComparer<ContextCookie>.GetHashCode(ContextCookie obj)
        {
            return obj.pCookie.GetHashCode();
        }
    }

    /// <summary>
    /// Marshaling type of a ContextBoundInterfacePointer
    /// </summary>
    internal enum ComMarshalingType
    {
        /// <summary>
        /// It has not yet been computed or the MarshalingBehavior[MarshalingType.InvalidMarshaling] or we found an unknown value in the attribute itself.
        /// </summary>
        Unknown,

        /// <summary>
        /// This COM object does not support marshalling and says so in its WinRT metadata
        /// We should not attempt to do any marshalling and should fail immediately
        /// </summary>
        Inhibit,

        /// <summary>
        /// A free-threaded COM object
        /// This is usually indicated by
        /// 1. This object aggregates FTM
        /// 2. This object implements IAgileObject
        /// 3. This object says so in WinRT metadata
        /// </summary>
        Free,

        /// <summary>
        /// A normal COM interface pointer that supports marshalling
        /// NOTE: This doesn't mean the actual underlying object supports marshalling - it only means
        /// we ATTEMPT to do such marshalling
        /// </summary>
        Standard
    }

    /// <summary>
    /// A interface pointer that is COM-context-aware and will always return you the correct marshalled
    /// interface pointer for the current context
    /// </summary>
    internal struct ContextBoundInterfacePointer
    {
        /// <summary>
        /// The COM interface pointer
        /// </summary>
        private IntPtr m_pComPtr;

        /// <summary>
        /// The ContextEntry where this COM interface pointer is obtained
        /// NOTE: Unlike CLR, this is always non-null
        /// </summary>
        private ContextEntry m_context;

        /// <summary>
        /// Stream that contains a marshalled COM pointer that can be unmarshalled to any context
        /// Once we've created a stream, we cache it here.  A thread that needs to do marshaling will first
        /// "check out" this stream by Interlocked.Exchange'ing a null into this field, and using the previous
        /// value.  In a race, another thread might see a null stream, in which case it will just create a new
        /// one.  This should be rare.
        /// </summary>
        private IntPtr m_pCachedStream;

        /// <summary>
        /// The threading type of this ContextBoundInterfacePointer
        /// </summary>
        private ComMarshalingType m_type;

        /// <summary>
        /// Initialize a context bound interface pointer with current context cookie
        /// </summary>
        /// <param name="currentCookie">Passed in for better perf</param>
        internal void Initialize(IntPtr pComPtr, ComMarshalingType type)
        {
            m_pComPtr = pComPtr;
            McgMarshal.ComAddRef(m_pComPtr);

            // Initialize current context
            // NOTE: Unlike CLR, we always initialize the current context cookie
            // This is done to avoid having another m_contextCookie field
            m_context = ContextEntry.GetCurrentContext(ContextCookie.Current);

            // This is a good opportunity to clean up any interfaces that need released in this context
            m_context.PerformDelayedCleanup();

            if (type == ComMarshalingType.Unknown)
            {
                m_type = GetComMarshalingBehaviorAtRuntime();
            }
            else
            {
                m_type = type;
            }

            Debug.Assert(!IsUnknown, "m_type can't be null");
        }

        /// <summary>
        /// Returns a AddRefed COM pointer - you'll need to release it by calling McgMarshal.ComRelease
        /// </summary>
        internal IntPtr GetIUnknownForCurrContext(ContextCookie currentCookie)
        {
            Debug.Assert(currentCookie.IsCurrent);

            // Matching context or FreeThreaded should already be handled
            Debug.Assert(!(m_context.ContextCookie.Equals(currentCookie) || IsFreeThreaded));

#if !RHTESTCL
            if (IsInhibit)
            {
                throw new System.InvalidCastException(SR.Arg_NoMarshalCreatedObjectUsedOutOfTreadContext);
            }
#endif
            return GetAddRefedComPointerForCurrentContext();
        }

        /// <summary>
        /// Returns the "raw" interface pointer without a AddRef
        /// It can only be used as a comparison, or under the context where this context bound interface
        /// pointer is obtained
        /// </summary>
        internal IntPtr ComPointer_UnsafeNoAddRef
        {
            get
            {
                return m_pComPtr;
            }
        }

        /// <summary>
        /// Returns the ContextCookie where this context bound interface pointer is obtained *INITIALLY*
        /// </summary>
        internal ContextCookie ContextCookie
        {
            get
            {
                return m_context.ContextCookie;
            }
        }

        /// <summary>
        /// Returns the ContextEntry where this context bound interface pointer is obtained *INITIALLY*
        /// </summary>
        internal ContextEntry ContextEntry
        {
            get
            {
                return m_context;
            }
        }

        /// <summary>
        /// This method get's the ComMarshalingType by checking the IntPtr at runtime.
        /// </summary>
        /// <returns></returns>
        private ComMarshalingType GetComMarshalingBehaviorAtRuntime()
        {
            Debug.Assert(IsUnknown, "ComMarshalingType is not ComMarshalingType.Uknown");

            if (McgComHelpers.IsFreeThreaded(m_pComPtr))
            {
                // The object is free threaded and hence.
                return ComMarshalingType.Free;
            }

            IntPtr pINoMarshal = McgMarshal.ComQueryInterfaceNoThrow(m_pComPtr, ref Interop.COM.IID_INoMarshal);

            if (pINoMarshal != default(IntPtr))
            {
                McgMarshal.ComSafeRelease(m_pComPtr);
                pINoMarshal = default(IntPtr);

                // This object implements INoMarshal and hence the marshaling across context is inhibited.
                return ComMarshalingType.Inhibit;
            }

            return ComMarshalingType.Standard;
        }

        /// <summary>
        /// Whether this interface pointer represents a free-threaded COM object
        /// </summary>
        internal bool IsFreeThreaded
        {
            get
            {
                return m_type == ComMarshalingType.Free;
            }
        }

        /// <summary>
        /// Whether this interface pointer represents a COM object which can't be marshaled to other contexts.
        /// </summary>
        internal bool IsInhibit
        {
            get
            {
                return m_type == ComMarshalingType.Inhibit;
            }
        }

        /// <summary>
        /// Whether this interface pointer represents a COM object that supports marshalling
        /// </summary>
        internal bool IsStandard
        {
            get
            {
                return m_type == ComMarshalingType.Standard;
            }
        }

        /// <summary>
        /// Whether this interface pointer represents a COM object that supports marshalling
        /// </summary>
        internal bool IsUnknown
        {
            get
            {
                return m_type == ComMarshalingType.Unknown;
            }
        }

        // Used to indicate that there is a marshaled stream, but it's currently in use by some thread.
        const int StreamInUse = 1;

        /// <summary>
        /// Marshales the IUnknown* into a stream and then unmarshal it back to the current context
        /// </summary>
        /// <returns>A AddRef-ed interface pointer that can be used under current context</returns>
        private IntPtr GetAddRefedComPointerForCurrentContext()
        {
            Debug.Assert(IsStandard, "ComMarshalingType is not standard");
            bool failedBefore = false;
            IntPtr pStream = IntPtr.Zero;

            //
            // Acquire the cached stream.
            //
            SpinWait spin = new SpinWait();

            while ((pStream = Interlocked.Exchange(ref m_pCachedStream, (IntPtr)StreamInUse)) == (IntPtr)StreamInUse)
                spin.SpinOnce();

            //
            // Keep retrying until we encounter a critical failure, fail twice, or succeed
            //
            while (true)
            {
                try
                {
                    //
                    // If we have a cached stream, use it.  Otherwise, try to marshal this com pointer 
                    // to a stream.
                    //
                    if (pStream == IntPtr.Zero)
                    {
                        pStream = MarshalComPointerToStream();
                    }

                    if (pStream == IntPtr.Zero)
                    {
                        //
                        // NOTE: This is different than CLR
                        // In CLR we hand out the raw IUnknown pointer and hope it works (and it usually does, 
                        // until it does not).
                        // In ProjectN we try to do the right thing and fail here
                        //
                        throw new InvalidCastException();
                    }
                    else
                    {
                        //
                        // First, reset the stream (ignoring any errors).
                        // 
                        McgComHelpers.SeekStreamToBeginning(pStream);

                        //
                        // Marshalling into stream has succeeded
                        // Now try unmarshal the stream into a pointer of current context
                        //
                        IntPtr pUnknown;
                        int hr = ExternalInterop.CoUnmarshalInterface(pStream, ref Interop.COM.IID_IUnknown, out pUnknown);

                        if (hr < 0)
                        {
                            //
                            // Unmarshalled failed and the stream is now no good.
                            //
                            McgComHelpers.SafeReleaseStream(pStream);
                            pStream = IntPtr.Zero;

                            // If we've already failed before, stop retrying and fail immediately
                            if (failedBefore)
                            {
                                throw new InvalidCastException();
                            }

                            // Remember we've already failed before and avoid infinite loop
                            failedBefore = true;
                        }
                        else
                        {
                            //
                            // Reset the stream (ignoring any errors).
                            // 
                            McgComHelpers.SeekStreamToBeginning(pStream);
                            return pUnknown;
                        }
                    }
                }
                finally
                {
                    Volatile.Write(ref m_pCachedStream, pStream);
                }
            }
        }

        /// <summary>
        /// Marshals m_pComPtr into a IStream*
        /// </summary>
        private IntPtr MarshalComPointerToStream()
        {
            if (!m_context.IsCurrent)
                return MarshalComPointerToStream_InDifferentContext(m_context, m_pComPtr);
            
            // Current Context
            return MarshalComPointerToStream_InCurrentContext(m_pComPtr);
        }

        private static IntPtr MarshalComPointerToStream_InDifferentContext(ContextEntry context, IntPtr pComPtr)
        {
            IntPtr pStream = IntPtr.Zero;
            context.EnterContext(() =>
            {
                pStream = MarshalComPointerToStream_InCurrentContext(pComPtr);
            });
            return pStream;
        }

        private static  IntPtr MarshalComPointerToStream_InCurrentContext(IntPtr pComPtr)
        {
            IntPtr pStream;
            if (MarshalInterThreadInterfaceInStream(ref Interop.COM.IID_IUnknown, pComPtr, out pStream))
                return pStream;

            return IntPtr.Zero;
        }

        /// <summary>
        /// Marshal IUnknown * into a IStream*
        /// </summary>
        /// <returns>True if succeeded, false otherwise</returns>
        private static bool MarshalInterThreadInterfaceInStream(ref Guid iid, IntPtr pUnknown, out IntPtr pRetStream)
        {
            ulong lSize;

            //
            // Retrieve maximum size required
            //
            int hr = ExternalInterop.CoGetMarshalSizeMax(
                out lSize,
                ref Interop.COM.IID_IUnknown,
                pUnknown,
                Interop.COM.MSHCTX.MSHCTX_INPROC,
                IntPtr.Zero,
                Interop.COM.MSHLFLAGS.MSHLFLAGS_TABLESTRONG
            );

            IntPtr pStream = IntPtr.Zero;

            try
            {
                if (hr == Interop.COM.S_OK)
                {
                    //
                    // Create a stream
                    //
                    pStream = __com_IStream.CreateMemStm(lSize);
                    if (pStream != IntPtr.Zero)
                    {
                        //
                        // Masrhal the interface into the stream TABLE STRONG
                        //
                        hr = ExternalInterop.CoMarshalInterface(
                            pStream,
                            ref iid,
                            pUnknown,
                            Interop.COM.MSHCTX.MSHCTX_INPROC,
                            IntPtr.Zero,
                            Interop.COM.MSHLFLAGS.MSHLFLAGS_TABLESTRONG
                        );
                    }
                    else
                    {
                        pRetStream = IntPtr.Zero;
                        return false;
                    }
                }

                if (hr >= 0)
                {
                    if (McgComHelpers.SeekStreamToBeginning(pStream))
                    {
                        //
                        // Everything succeeded - transfer ownership to pRetStream
                        //
                        pRetStream = pStream;
                        pStream = IntPtr.Zero;

                        return true;
                    }
                }

                pRetStream = IntPtr.Zero;
                return false;
            }
            finally
            {
                if (pStream != IntPtr.Zero)
                {
                    McgMarshal.ComRelease(pStream);
                }
            }
        }

        /// <summary>
        /// Whether this has been already disposed
        /// </summary>
        internal bool IsDisposed
        {
            get
            {
                return m_pComPtr == default(IntPtr);
            }
        }

        /// <summary>
        /// Dispose and set status to disposed
        /// </summary>
        internal void Dispose(bool inCurrentContext)
        {
            if (IsDisposed)
                throw new ObjectDisposedException("");

            if (inCurrentContext)
                McgMarshal.ComRelease(m_pComPtr);
            else
                m_context.EnqueueDelayedComRelease(m_pComPtr);

            m_pComPtr = default(IntPtr);

            // Use ContextEntry.EnqueueDelayedStreamRelease to make sure the cached streeam is released in the correct context(apartment)
            // According to MSDN: CoReleaseMarshalData function
            // You must call the CoReleaseMarshalData function in the same apartment that called CoMarshalInterface to marshal the object into the stream
            if (m_pCachedStream != default(IntPtr))
            {
                m_context.EnqueueDelayedStreamRelease(m_pCachedStream);
                m_pCachedStream = default(IntPtr);
            }
        }
    }

    /// <summary>
    /// Represents a COM context. It has the following characteristics:
    /// 1. All ContextEntry objects are managed in a global cache, and as a result you won't get duplicated
    /// ContextEntry for the same context.
    /// 2. This ContextEntry keeps a ref count on m_pObjectContext - as a result the context won't become
    /// invalid. This is VERY important
    /// </summary>
    internal class ContextEntry
    {
        /// <summary>
        /// The cookie that represents the COM context
        /// It is used as unique ID
        /// </summary>
        private ContextCookie m_cookie;

        /// <summary>
        /// The AddRefed IObjectContext* for this context
        /// Used for the context transition
        /// The AddRef is real important because it prevents the target context from going away, and prevents
        /// m_cookie and m_pObjectContext becoming invalid
        /// </summary>
        private IntPtr m_pObjectContext;

        /// <summary>
        /// Initialize a new context entry
        /// This is used by GetCurrentContext
        /// After initialization, ref count = 1
        /// </summary>
        /// <param name="cookie">Current cookie. Passed for better perf</param>
        private ContextEntry(ContextCookie cookie)
        {
            // Make sure the cookie is the current context cookie
            // We pass the cookie in for better performance (avoid a P/Invoke)
            Debug.Assert(cookie.IsCurrent);
            m_cookie = cookie;
            m_pObjectContext = IntPtr.Zero;

#if ENABLE_MIN_WINRT
            int hr = ExternalInterop.CoGetObjectContext(ref Interop.COM.IID_IUnknown, out m_pObjectContext);
            if (hr < 0)
            {
                throw Marshal.GetExceptionForHR(hr);
            }
#endif
        }

        /// <summary>
        /// Returns the context cookie associated with this context
        /// </summary>
        internal ContextCookie ContextCookie
        {
            get
            {
                return m_cookie;
            }
        }

        /// <summary>
        /// Whether this context is the current context
        /// </summary>
        internal bool IsCurrent
        {
            get
            {
                return m_cookie.IsCurrent;
            }
        }

        ~ContextEntry()
        {
            if (!Environment.HasShutdownStarted)
            {
                // m_pObjectContext could be NULL
                McgMarshal.ComSafeRelease(m_pObjectContext);
                m_pObjectContext = default(IntPtr);
            }            
        }

        internal static void RemoveCurrentContext()
        {
            ContextCookie cookie = ContextCookie.Current;
            ComObjectCache.RemoveRCWsForContext(cookie);
            ContextEntryManager.RemoveContextEntry(cookie);
        }

        /// <summary>
        /// User-defined callback type
        /// This callback will be called in the right context with data that was passed to EnterContext
        /// </summary>
        internal delegate void EnterContextCallback();

        /// <summary>
        /// Transition to this context and make the callback in that context
        /// </summary>
        /// <returns>True if succeed. False otherwise</returns>
        internal unsafe bool EnterContext(EnterContextCallback callback)
        {
            //
            // Retrieve the IContextCallback interface from the IObjectContext
            //
            IntPtr pContextCallback =
                McgMarshal.ComQueryInterfaceNoThrow(m_pObjectContext, ref Interop.COM.IID_IContextCallback);

            if (pContextCallback == IntPtr.Zero)
                throw new InvalidCastException();

            //
            // Setup the callback data structure with the callback Args
            //
            Interop.COM.ComCallData comCallData = new Interop.COM.ComCallData();
            comCallData.dwDispid = 0;
            comCallData.dwReserved = 0;

            //
            // Allocate a GCHandle in order to pass a managed class in ComCallData.pUserDefined
            //
            GCHandle gchCallback = GCHandle.Alloc(callback);

            try
            {
                comCallData.pUserDefined = GCHandle.ToIntPtr(gchCallback);

                //
                // Call IContextCallback::ContextCallback to transition into the right context
                // This is a blocking operation
                //
                Interop.COM.__IContextCallback* pContextCallbackNativePtr =
                    (Interop.COM.__IContextCallback*)(void*)pContextCallback;
                fixed (Guid* unsafe_iid = &Interop.COM.IID_IEnterActivityWithNoLock)
                {
                    int hr = CalliIntrinsics.StdCall__int(
                        pContextCallbackNativePtr->vtbl->pfnContextCallback,
                        pContextCallbackNativePtr,                              // Don't forget 'this pointer
                        AddrOfIntrinsics.AddrOf<AddrOfIntrinsics.AddrOfTarget1>(EnterContextCallbackProc),
                        &comCallData,
                        unsafe_iid,
                        (int)2,
                        IntPtr.Zero);

                    return (hr >= 0);
                }
            }
            finally
            {
                gchCallback.Free();
            }
        }

        /// <summary>
        /// This is the callback gets called in the right context and we'll call to the user callback with
        /// user supplied data
        /// </summary>
        [NativeCallable]
        private static unsafe int EnterContextCallbackProc(IntPtr ptr)
        {
            Interop.COM.ComCallData* pComCallData = (Interop.COM.ComCallData*)ptr;
            GCHandle gchCallback = GCHandle.FromIntPtr(pComCallData->pUserDefined);
            EnterContextCallback callback = (EnterContextCallback)gchCallback.Target;
            callback();
            return Interop.COM.S_OK;
        }

        /// <summary>
        /// Manage ContextCookie->ContextEntry mapping
        /// </summary>
        internal static class ContextEntryManager
        {
            [ThreadStatic]
            static ContextEntry s_lastContextEntry;

            internal static ContextEntry GetContextEntry(ContextCookie currentCookie)
            {
                ContextEntry last = s_lastContextEntry;

                // Shortcut to skip locking + dictionary lookup
                if ((last != null) && currentCookie.Equals(last.ContextCookie))
                {
                    return last;
                }
                else
                {
                    return GetContextEntrySlow(currentCookie);
                }
            }

            static ContextEntry GetContextEntrySlow(ContextCookie currentCookie)
            {
                try
                {
                    s_contextEntryLock.Acquire();

                    //
                    // Look up ContextEntry based on cache
                    //
                    ContextEntry contextEntry;

                    if (!s_contextEntryCache.TryGetValue(currentCookie, out contextEntry))
                    {
                        //
                        // Not found - create new entry in cache
                        //
                        contextEntry = new ContextEntry(currentCookie);

                        s_contextEntryCache.Add(currentCookie, contextEntry);
                    }

                    s_lastContextEntry = contextEntry; // Update cached entry

                    return contextEntry;
                }
                finally
                {
                    s_contextEntryLock.Release();
                }
            }

            /// <summary>
            /// Remove context entry from global cache
            /// </summary>
            internal static void RemoveContextEntry(ContextCookie cookie)
            {
                try
                {
                    s_contextEntryLock.Acquire();

                    s_lastContextEntry = null;   // Clear cached entry

                    s_contextEntryCache.Remove(cookie);
                }
                finally
                {
                    s_contextEntryLock.Release();
                }
            }

            /// <summary>
            /// Global cache for every contextEntry
            /// This is done to avoid duplication
            /// </summary>
            static System.Collections.Generic.Internal.Dictionary<ContextCookie, ContextEntry> s_contextEntryCache;

            /// <summary>
            /// Lock that protects m_contextEntryCache
            /// </summary>
            static Lock s_contextEntryLock;

            internal static void InitializeStatics()
            {
                s_contextEntryCache = new System.Collections.Generic.Internal.Dictionary<ContextCookie, ContextEntry>(new ContextCookieComparer());

                s_contextEntryLock = new Lock();
            }
        }

        /// <summary>
        /// Retrieve current ContextEntry from cache
        /// </summary>
        /// <param name="currentCookie">Current context cookie. Passed in for better perf</param>
        internal static ContextEntry GetCurrentContext(ContextCookie currentCookie)
        {
            Debug.Assert(currentCookie.IsCurrent);
            return ContextEntryManager.GetContextEntry(currentCookie);
        }

        private Lock m_delayedReleaseListLock = new Lock();
        
        //
        // Per-context list of interfaces that need to be released, next time we get a chance to do
        // so in this context.
        //
        private System.Collections.Generic.Internal.List<IntPtr> m_delayedReleaseList;
        
        //
        // Per-context list of Stream that need to be released, next time we get a chance to do
        // so in this context.
        //
        private System.Collections.Generic.Internal.List<IntPtr> m_delayedReleaseStreamList;

        internal void EnqueueDelayedComRelease(IntPtr pComPtr)
        {
            try
            {
                m_delayedReleaseListLock.Acquire();

                if (m_delayedReleaseList == null)
                    m_delayedReleaseList = new System.Collections.Generic.Internal.List<IntPtr>(25);
                m_delayedReleaseList.Add(pComPtr);
            }
            finally
            {
                m_delayedReleaseListLock.Release();
            }
        }

        internal void EnqueueDelayedStreamRelease(IntPtr pStream)
        {
            try
            {
                m_delayedReleaseListLock.Acquire();

                if (m_delayedReleaseStreamList == null)
                    m_delayedReleaseStreamList = new System.Collections.Generic.Internal.List<IntPtr>(25);

                m_delayedReleaseStreamList.Add(pStream);
            }
            finally
            {
                m_delayedReleaseListLock.Release();
            }
        }

        internal void PerformDelayedCleanup()
        {
            // fast path, hopefully inlined
            if (m_delayedReleaseList != null)
                PerformDelayedCleanupWorker();
        }

        private void PerformDelayedCleanupWorker()
        {
            Debug.Assert(this.IsCurrent);

            System.Collections.Generic.Internal.List<IntPtr> list = null;
            System.Collections.Generic.Internal.List<IntPtr> streamlist = null;

            try
            {
                m_delayedReleaseListLock.Acquire();

                if (m_delayedReleaseList != null)
                {
                    list = m_delayedReleaseList;
                    m_delayedReleaseList = null;
                }

                if (m_delayedReleaseStreamList != null)
                {
                    streamlist = m_delayedReleaseStreamList;
                    m_delayedReleaseStreamList = null;
                }
            }
            finally
            {
                m_delayedReleaseListLock.Release();
            }

            if (list != null)
            {
                for (int i = 0; i < list.Count; i++)
                {
                    McgMarshal.ComSafeRelease(list[i]);
                }
            }

            if (streamlist != null)
            {
                for (int i = 0; i < streamlist.Count; i++)
                {
                    McgComHelpers.SafeReleaseStream(streamlist[i]);
                }
            }
        }
    }

    /// <summary>
    /// Simplified version of ComInterfaceCacheItem that only contains IID + ptr
    /// The cached interface will always have the same context as the RCW
    /// </summary>
    internal unsafe struct SimpleComInterfaceCacheItem
    {
        /// <summary>
        /// NOTE: Managed debugger depends on field name:"ptr" and field type:IntPtr
        /// Update managed debugger whenever field name/field type is changed.
        /// See CordbObjectValue::GetInterfaceData in debug\dbi\values.cpp
        /// </summary>
        private IntPtr ptr;    // Interface pointer under this context

        /// <summary>
        /// RuntimeTypeHandle is added to the cache to make faster cache lookups.
        /// </summary>
        private RuntimeTypeHandle typeHandle;

        /// <summary>
        /// Indict whether the entry is filled or not
        /// Note: This field should be accessed only through Volatile.Read/Write
        /// </summary>
        private bool hasValue;

        private bool HasValue
        {
            get { 
                return Volatile.Read(ref hasValue);
            }
        }

        /// <summary>
        /// Assign ComPointer/RuntimeTypeHandle
        /// </summary>
        /// <returns>Return true if winning race. False otherwise</returns>
        internal bool Assign(IntPtr pComPtr, RuntimeTypeHandle handle)
        {
            if (Interlocked.CompareExchange(ref ptr, pComPtr, default(IntPtr)) == default(IntPtr))
            {
                Debug.Assert(!HasValue, "Entry should be empty");
                // We win the race
                // The aforementioned  compareExchange ensures that if the key is there the value will be there
                // too. It doesn't guarantee the correct value of the other key. So we should be careful about retrieving
                // cache item using one key and trying to access the other key of the cache as it might lead to interesting
                // problems
                typeHandle = handle;
                Volatile.Write(ref hasValue, true);

                return true;
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// Get Ptr value
        /// </summary>
        /// <returns></returns>
        internal bool TryGetPtr(out IntPtr retIntPtr)
        {
            if (HasValue)
            {
                retIntPtr = ptr;
                return true;
            }
            else
            {
                retIntPtr = default(IntPtr);
                return false;
            }
        }

        internal bool TryGetType(out RuntimeTypeHandle retInterface)
        {
            if (HasValue)
            {
                retInterface = typeHandle;
                return true;
            }
            else
            {
                retInterface = default(RuntimeTypeHandle);
                return false;
            }
        }

        /// <summary>
        /// NOTE: This Func doesn't check whether the item "hasValue" or not
        /// Please make sure 'this' has value, then call this GetPtr(); 
        /// </summary>
        /// <returns></returns>
        internal IntPtr GetPtr()
        {
            Debug.Assert(HasValue, "Please make sure item contains valid data or you can use TryGetTypeInfo instead.");
            return ptr;
        }



        /// <summary>
        /// Check whether current entry matching the passed fields value
        /// </summary>
        internal bool IsMatchingEntry(IntPtr pComPtr, RuntimeTypeHandle interfaceType)
        {
            if (HasValue)
            {
                if (ptr == pComPtr && typeHandle.Equals(interfaceType))
                    return true;
            }

            return false;
        }

        internal bool IsCastableEntry(RuntimeTypeHandle interfaceType, out IntPtr pComPtr, out RuntimeTypeHandle entryType)
        {
            if (HasValue)
            {
                if (InteropExtensions.AreTypesAssignable(typeHandle, interfaceType))
                {
                    pComPtr = ptr;
                    entryType = typeHandle;
                    return true;
                }
            }

            pComPtr = IntPtr.Zero;
            entryType = default(RuntimeTypeHandle);
            return false;
        }

        /// <summary>
        /// If current entry's RuntimeTypeHandle equals to the passed RuntimeTypeHandle, then return true and its interface pointer
        /// </summary>
        internal bool TryReadCachedNativeInterface(RuntimeTypeHandle interfaceType, out IntPtr pComPtr)
        {
            if (HasValue)
            {
                if (typeHandle.Equals(interfaceType))
                {
                    pComPtr = ptr;
                    return true;
                }
            }

            pComPtr = default(IntPtr);
            return false;
        }
    }

    /// <summary>
    /// Caches information about a particular COM interface under a particular COM context
    /// </summary>
    internal struct AdditionalComInterfaceCacheItem
    {
        /// <summary>
        /// Create a new cached item
        /// Assumes the interface pointer has already been AddRef-ed
        /// Will transfer the ref count to this data structure
        /// </summary>
        internal AdditionalComInterfaceCacheItem(RuntimeTypeHandle interfaceType, IntPtr pComPtr, object adapter)
        {
            typeHandle = interfaceType;
            ptr = pComPtr;
            dynamicAdapter = adapter;
        }
        /// <summary>
        /// NOTE: Managed debugger depends on field name: "typeHandle" and field type: RuntimeTypeHandle
        /// See CordbObjectValue::WalkAdditionalCacheItem in debug\dbi\values.cpp
        /// </summary>
        internal readonly RuntimeTypeHandle typeHandle;        // Table entry of this cached COM interface
        /// <summary>
        /// NOTE: Managed debugger depends on field name: "ptr" and field type: IntPtr
        /// See CordbObjectValue::WalkAdditionalCacheItem in debug\dbi\values.cpp
        /// </summary>
        internal readonly IntPtr ptr;             // Interface pointer under this context
        internal readonly object dynamicAdapter;  // Adapter object for this type.  Only used for some projected interfaces.
    }

    internal class AdditionalComInterfaceCacheContext
    {
        internal AdditionalComInterfaceCacheContext(ContextCookie contextCookie)
        {
            context = ContextEntry.GetCurrentContext(contextCookie);
        }

        /// <returns>false if duplicate found</returns>
        internal unsafe bool Add(RuntimeTypeHandle interfaceType, IntPtr pComPtr, object adapter, bool checkDup)
        {
            if (checkDup) // checkDup
            {
                foreach (AdditionalComInterfaceCacheItem existingType in items)
                {
                    if (existingType.typeHandle.Equals(interfaceType))
                    {
                        return false;
                    }
                }
            }

            items.Add(new AdditionalComInterfaceCacheItem(interfaceType, pComPtr, adapter));

            return true;
        }

        internal readonly ContextEntry context;
        /// <summary>
        /// NOTE: Managed debugger depends on field name: "items" and field type:WithInlineStorage
        /// Update managed debugger whenever field name/field type is changed.
        /// See CordbObjectValue::GetInterfaceData in debug\dbi\values.cpp
        /// </summary>
        internal LightweightList<AdditionalComInterfaceCacheItem>.WithInlineStorage items;
    }

    [Flags]
    enum ComObjectFlags
    {
        /// <summary>
        /// Default value
        /// </summary>
        None = 0,

        /// <summary>
        /// A Duplicate RCW that has the same identity pointer as another RCW in the cache
        /// This could be created due to a race or intentionally
        /// We don't put duplicate RCWs into our cache
        /// </summary>
        IsDuplicate = 0x1,

        /// <summary>
        /// This RCW represents a Jupiter object
        /// </summary>
        IsJupiterObject = 0x2,

        /// <summary>
        /// Whether this is a managed class deriving from a RCW. For example, managed MyButton class deriving
        /// from native Button class. Button RCW is being aggregated by MyButton CCW
        /// </summary>
        ExtendsComObject = 0x4,

        /// <summary>
        /// These enums are used to find the right GCPressure values.
        /// We have 5 possible states.
        /// a. None.
        /// b. Default
        /// c. GCPressureRange.Low
        /// d. GCPressureRange.Medium
        /// e. GCPressureRange.High
        ///
        /// We basically use 3 bits for the 5 values as follows.
        /// 1. None - Represented by the absence of GCPressure_Set bit.
        /// 2. Default - Presence of only GCPRessure_Set
        /// 3. All the rest are marked by 2 in conjunction with specific GCPressureRange.
        ///
        /// We need to use the state None and Default both since some of the __ComObjects are created without really initiating them with any basePtr and hence while
        /// releasing the ComObject we need to know whether we Added GC.AddMemoryPressure for the given __ComObject or not.
        /// This also ensures 1-1 mapping between the AddMemoryPressure and RemoveMemoryPressure.
        /// </summary>

        GCPressure_Set = 0x8,
        GCPressureWinRT_Low = 0x10,
        GCPressureWinRT_Medium = 0x20,
        GCPressureWinRT_High = 0x30,

        GCPressureWinRT_Mask = 0x30,

        /// <summary>
        /// This represents the types MarshalingBehavior.
        /// </summary>
        MarshalingBehavior_Inhibit = 0x40,
        MarshalingBehavior_Free = 0x80,
        MarshalingBehavior_Standard = 0xc0,

        MarshalingBehavior_Mask = 0xc0,
        // Add other enums here.
    }

#if ENABLE_WINRT
    /// <summary>
    /// This class helps call the IStringableToString() by QI IStringable.ToString() method call.
    /// </summary>
    internal class IStringableHelper
    {
        internal static unsafe bool TryGetIStringableToString(object obj, out string toStringResult)
        {
            bool isIStringableToString = false;
            toStringResult = String.Empty;

            __ComObject comObject = obj as __ComObject;

            if (comObject != null)
            {
                // Check whether the object implements IStringable
                // If so, use IStringable.ToString() behavior
                IntPtr pIStringableItf = comObject.QueryInterface_NoAddRef_Internal(InternalTypes.IStringable, /* cacheOnly= */ false, /* throwOnQueryInterfaceFailure= */ false);

                if (pIStringableItf != default(IntPtr))
                {
                    __com_IStringable* pIStringable = (__com_IStringable*)pIStringableItf;
                    void* unsafe_hstring = null;

                    // The method implements isIStringableToString
                    isIStringableToString = true;

                    try
                    {
                        int hr = CalliIntrinsics.StdCall__int(
                            pIStringable->pVtable->pfnToString,
                            pIStringable,
                            &unsafe_hstring
                            );

                        GC.KeepAlive(obj);

                        // Don't throw if the call fails
                        if (hr >= 0)
                        {
                            toStringResult = McgMarshal.HStringToString(new IntPtr(unsafe_hstring));
                        }
                    }
                    finally
                    {
                        if (unsafe_hstring != null)
                            McgMarshal.FreeHString(new IntPtr(unsafe_hstring));
                    }
                }
            }

            return isIStringableToString;
        }
    }
#endif

    internal enum GCPressureRange
    {
        None,
        WinRT_Default,
        WinRT_Low,
        WinRT_Medium,
        WinRT_High
    }

#if !RHTESTCL
    /// <summary>
    /// These values are taken from the CLR implementation and can be changed later if perf shows so.
    /// </summary>
    internal struct GCMemoryPressureConstants
    {
#if WIN64
        internal const int GC_PRESSURE_DEFAULT       = 1000;
        internal const int GC_PRESSURE_WINRT_LOW        = 12000;
        internal const int GC_PRESSURE_WINRT_MEDIUM     = 120000;
        internal const int GC_PRESSURE_WINRT_HIGH       = 1200000;
#else
        internal const int GC_PRESSURE_DEFAULT = 750;
        internal const int GC_PRESSURE_WINRT_LOW = 8000;
        internal const int GC_PRESSURE_WINRT_MEDIUM = 80000;
        internal const int GC_PRESSURE_WINRT_HIGH = 800000;
#endif
    }
#endif


    //
    // Base class for all "dynamic adapters."  This allows us to instantiate
    // these via RhNewObject (which requires a default constructor), and also
    // initialize them (via ComInterfaceDynamicAdapter.Initialize).
    //
    [CLSCompliant(false)]
    [EditorBrowsable(EditorBrowsableState.Never)]
    public class ComInterfaceDynamicAdapter
    {
        __ComObject m_comObject;

        internal void Initialize(__ComObject comObject)
        {
            m_comObject = comObject;
        }

        public __ComObject ComObject
        {
            get
            {
                return m_comObject;
            }
        }
    }

    /// <summary>
    /// A global cache for all __ComObject(s)
    /// We do a lookup based on IUnknown to find the corresponding cached __ComObject the cache
    /// </summary>
    /// <remarks>
    /// If a __ComObject is in finalizer queue, it is no longer considered valid in the cache
    /// The reason is to avoid unintentionally resurrecting __ComObject during marshalling and therefore
    /// resurrecting anything that is pointed by __ComObject that might already been finalized.
    /// Therefore, all __ComObject are tracked with short weak GC handles.
    /// </remarks>
    /// <remarks>
    /// NOTE: Not all __ComObject are stored in ComObject cache. __ComObject with IsDuplicated == true
    /// are not saved here, because they are not the "identity" RCW for that specific interface pointer and
    /// there can only be one
    /// </remarks>
    internal static class ComObjectCache
    {
        /// <summary>
        /// Adds the __ComObject into cache
        /// This either insert its into the cache, or updates an inavlid entry with this __ComObject
        /// </summary>
        /// <returns>true if add/update succeeded. false if there is already a valid entry in the cache.
        /// In that case, you should insert it as a duplicate RCW
        /// </returns>
        internal static bool Add(IntPtr pComItf, __ComObject o)
        {
            int hashCode = pComItf.GetHashCode();

            try
            {
                s_lock.Acquire();

                IntPtr handlePtr;

                if (s_comObjectMap.TryGetValue(pComItf, hashCode, out handlePtr))
                {
                    GCHandle handle = GCHandle.FromIntPtr(handlePtr);
                    __ComObject cachedComObject = (__ComObject)handle.Target;

                    if (cachedComObject == null)
                    {
                        //
                        // We have another __ComObject in the cache but it is now in the finalizer queue
                        // We can safely reuse this entry for this new object
                        // This could happen if the same interface pointer is marshalled back to managed
                        // code again
                        //
                        handle.Target = o;
                    }
                    else
                    {
                        //
                        // There is a already a valid __ComObject in the cache
                        // This is a "duplicate" RCW and we don't need to insert it into the cache as
                        // we won't be returning this RCW during lookup
                        //
                        return false;
                    }
                }
                else
                {
                    GCHandle newHandle = GCHandle.Alloc(o, GCHandleType.Weak);
                    handlePtr = GCHandle.ToIntPtr(newHandle);
                    s_comObjectMap.Add(pComItf, handlePtr, hashCode);
                }

                return true;
            }
            finally
            {
                s_lock.Release();
            }
        }

        /// <summary>
        /// Remove entry from the global IUnknown->__ComObject map
        /// </summary>
        internal static void Remove(IntPtr pComItf, __ComObject o)
        {
            Debug.Assert(o != null);

            try
            {
                s_lock.Acquire();

                //
                // Only remove if the entry is indeed in the cache and is a match
                // The entry might not be even in the cache if the following event occurs:
                // 1. a RCW A is created for interface pointer 0x100 and is added into cache with key=0x100
                // 2. RCW A is not referenced anymore and is now in the fnialization queue
                // 3. The same interface pointer 0x100 is marshalled back into managed again - this time
                // we should NOT reuse the same RCW to resurrect it. See the remark section in this class
                // for more details. We will create a new RCW B, and it's not a duplicate.
                // 4. RCW B is also considered dead and enters the finalizer queue
                // 5. RCW A now finally gets its chance to finalize, and remove 0x100 from the cache, as
                // cachedObject is now null (was pointing to RCW B which is now in finalize queue)
                // 5. RCW B eventually gets its chance to finalize, and there is no 0x100 in the cache
                //
                IntPtr handlePtr;

                if (s_comObjectMap.TryGetValue(pComItf, out handlePtr))
                {
                    GCHandle handle = GCHandle.FromIntPtr(handlePtr);
                    Object cachedObject = handle.Target;

                    //
                    // Only remove if
                    // 1) The cached object matches
                    // 2) The cached object is null, which means it is now invalidated and we can
                    // safely remove it now
                    //
                    // If the cached object is non-null and doesn't match, this means there is a new
                    // __ComObject that now occupies this cache entry and we should not remove it
                    //
                    if (cachedObject == o ||
                        cachedObject == null)
                    {
                        //
                        // Remove it from the map and free the handle
                        // The order is very important as GC could come at any time
                        // We want to destroy the handle after we've remove this entry from the list
                        // NOTE: if GC comes before we even remove it from the list, it's OK because we
                        // haven't actually released the interfaces in the RCW yet
                        //
                        s_comObjectMap.Remove(pComItf);
                        handle.Free();
                    }
                }
            }
            finally
            {
                s_lock.Release();
            }
        }

        /// <summary>
        /// Return the corresponding __ComObject that has the IUnknown* as its identity
        /// NOTE: If a __ComObject is in finalizer queue or is resurrected, it is not considered valid and
        /// won't be returned. This is done to avoid resurrection by accident during marshalling
        /// </summary>
        internal static __ComObject Lookup(IntPtr pComItf)
        {
            try
            {
                s_lock.Acquire();

                IntPtr handlePtr;

                if (s_comObjectMap.TryGetValue(pComItf, out handlePtr))
                {
                    object target = GCHandle.FromIntPtr(handlePtr).Target;
                    Debug.Assert(target == null || target is __ComObject);

                    return InteropExtensions.UncheckedCast<__ComObject>(target);
                }

                return null;
            }
            finally
            {
                s_lock.Release();
            }
        }

        internal static void RemoveRCWsForContext(ContextCookie contextCookie)
        {
            try
            {
                s_lock.Acquire();

                System.Collections.Generic.Internal.Dictionary<IntPtr, IntPtr> map = s_comObjectMap;

                for (int i = 0; i < map.GetMaxCount(); i++)
                {
                    IntPtr handlePtr = default(IntPtr);

                    if (map.GetValue(i, ref handlePtr) && (handlePtr != default(IntPtr)))
                    {
                        GCHandle handle = GCHandle.FromIntPtr(handlePtr);
                        __ComObject obj = handle.Target as __ComObject;

                        if (obj != null)
                            obj.RemoveInterfacesForContext(contextCookie);
                    }
                }
            }
            finally
            {
                s_lock.Release();
            }
        }

        static Lock s_lock;

        /// <summary>
        /// Map of all __ComObject instances
        /// This points to an index in s_comObjectList
        /// </summary>
        internal static System.Collections.Generic.Internal.Dictionary<IntPtr, IntPtr> s_comObjectMap;

        internal static void InitializeStatics()
        {
            s_lock = new Lock();

            s_comObjectMap = new System.Collections.Generic.Internal.Dictionary<IntPtr, IntPtr>(101, new EqualityComparerForIntPtr());
        }
    }

    internal sealed class EqualityComparerForIntPtr : EqualityComparer<IntPtr>
    {
        public override bool Equals(IntPtr x, IntPtr y)
        {
            return x == y;
        }

        public override int GetHashCode(IntPtr x)
        {
            return x.GetHashCode();
        }
    }

#if ENABLE_MIN_WINRT
    /// <summary>
    /// WinRT factory cache item caching the context + factory RCW
    /// </summary>
    internal struct FactoryCacheItem
    {
        internal ContextEntry contextEntry;
        internal __ComObject factoryObject;
    }

    /// <summary>
    /// WinRT Factory cache
    /// We only remember the last cached factory per context + type
    /// The type part is obvious but the context part is probably less so.
    /// When we retrieve a factory, we must make sure the factory interface pointer is the same as if we
    /// were calling RoGetActivationFactory from the current context. This is VERY important for factories
    /// that are 'BOTH'. If you have a 'BOTH' factory created in STA, and marshal that factory to a MTA,
    /// when you call marshalled factory interface pointer in MTA, you'll get a STA object! That is different
    /// from when you call RoGetActivationFactory in MTA and call the factory which creates a MTA object
    /// </summary>
    internal class FactoryCache
    {
        private System.Collections.Concurrent.ConcurrentDictionary<string, FactoryCacheItem> m_cachedFactories = new System.Collections.Concurrent.ConcurrentDictionary<string, FactoryCacheItem>();

        private static volatile FactoryCache s_factoryCache;

        internal static FactoryCache Get()
        {
            if (s_factoryCache == null)
            {
                Interlocked.CompareExchange(ref s_factoryCache, new FactoryCache(), null);
            }

            return s_factoryCache;
        }

        /// <summary>
        /// Retrieve the class factory for a specific type
        /// </summary>
        private static unsafe __ComObject GetActivationFactoryInternal(
            string typeName,
            RuntimeTypeHandle factoryItf,
            ContextEntry currentContext)
        {
            IntPtr pFactory = default(IntPtr);
            try
            {
                Guid itfGuid = factoryItf.GetInterfaceGuid();
                ExternalInterop.RoGetActivationFactory(typeName, ref itfGuid, out pFactory);

                return (__ComObject)McgComHelpers.ComInterfaceToComObject(
                    pFactory,
                    factoryItf,
                    default(RuntimeTypeHandle),
                    currentContext.ContextCookie,           // Only want factory RCW from matching context
                    McgComHelpers.CreateComObjectFlags.SkipTypeResolutionAndUnboxing
                    );
            }
            finally
            {
                if (pFactory != default(IntPtr))
                    McgMarshal.ComRelease(pFactory);
            }
        }

        /// <summary>
        /// Retrieves the class factory RCW for the specified class name + IID under the right context
        /// The context part is really important
        /// </summary>
        internal __ComObject GetActivationFactory(string className, RuntimeTypeHandle factoryIntf, bool skipCache = false)
        {
            ContextEntry currentContext = ContextEntry.GetCurrentContext(ContextCookie.Current);

            FactoryCacheItem cacheItem;

            if (!skipCache)
            {
                if (m_cachedFactories.TryGetValue(className, out cacheItem))
                {
                    if (cacheItem.contextEntry == currentContext)
                    {
                        //
                        // We've found a matching entry
                        //
                        return cacheItem.factoryObject;
                    }
                }
            }

            //
            // No matching entry found - let's create a new one
            // This is kinda slow so do it outside of a lock
            //
            __ComObject factoryObject = GetActivationFactoryInternal(className, factoryIntf, currentContext);

            cacheItem.contextEntry = currentContext;
            cacheItem.factoryObject = factoryObject;

            if (!skipCache)
            {
                //
                // Insert into or update cache
                //
                m_cachedFactories[className] = cacheItem;
            }

            return cacheItem.factoryObject;
        }
    }
#endif
}