1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
//
// File: clsload.cpp
//
// ============================================================================
#include "common.h"
#include "winwrap.h"
#include "ceeload.h"
#include "siginfo.hpp"
#include "vars.hpp"
#include "clsload.hpp"
#include "classhash.inl"
#include "class.h"
#include "method.hpp"
#include "ecall.h"
#include "stublink.h"
#include "object.h"
#include "excep.h"
#include "threads.h"
#include "comsynchronizable.h"
#include "threads.h"
#include "dllimport.h"
#include "security.h"
#include "dbginterface.h"
#include "log.h"
#include "eeconfig.h"
#include "fieldmarshaler.h"
#include "jitinterface.h"
#include "vars.hpp"
#include "assembly.hpp"
#include "perfcounters.h"
#include "eeprofinterfaces.h"
#include "eehash.h"
#include "typehash.h"
#include "comdelegate.h"
#include "array.h"
#include "stackprobe.h"
#include "posterror.h"
#include "wrappers.h"
#include "generics.h"
#include "typestring.h"
#include "typedesc.h"
#include "cgencpu.h"
#include "eventtrace.h"
#include "typekey.h"
#include "pendingload.h"
#include "proftoeeinterfaceimpl.h"
#include "mdaassistants.h"
#include "virtualcallstub.h"
#include "stringarraylist.h"
// This method determines the "loader module" for an instantiated type
// or method. The rule must ensure that any types involved in the
// instantiated type or method do not outlive the loader module itself
// with respect to app-domain unloading (e.g. MyList<MyType> can't be
// put in the module of MyList if MyList's assembly is
// app-domain-neutral but MyType's assembly is app-domain-specific).
// The rule we use is:
//
// * Pick the first type in the class instantiation, followed by
// method instantiation, whose loader module is non-shared (app-domain-bound)
// * If no type is app-domain-bound, return the module containing the generic type itself
//
// Some useful effects of this rule (for ngen purposes) are:
//
// * G<object,...,object> lives in the module defining G
// * non-mscorlib instantiations of mscorlib-defined generic types live in the module
// of the instantiation (when only one module is invloved in the instantiation)
//
/* static */
PTR_Module ClassLoader::ComputeLoaderModuleWorker(
Module * pDefinitionModule, // the module that declares the generic type or method
mdToken token, // method or class token for this item
Instantiation classInst, // the type arguments to the type (if any)
Instantiation methodInst) // the type arguments to the method (if any)
{
CONTRACT(Module*)
{
NOTHROW;
GC_NOTRIGGER;
FORBID_FAULT;
MODE_ANY;
PRECONDITION(CheckPointer(pDefinitionModule, NULL_OK));
POSTCONDITION(CheckPointer(RETVAL));
SO_INTOLERANT;
SUPPORTS_DAC;
}
CONTRACT_END
if (classInst.IsEmpty() && methodInst.IsEmpty())
RETURN PTR_Module(pDefinitionModule);
#ifndef DACCESS_COMPILE
#ifdef FEATURE_NATIVE_IMAGE_GENERATION
//
// Use special loader module placement during compilation of fragile native images.
//
// ComputeLoaderModuleForCompilation algorithm assumes that we are using fragile native image
// for CoreLib (or compiling CoreLib itself). It is not the case for ReadyToRun compilation because
// CoreLib as always treated as IL there (see code:PEFile::ShouldTreatNIAsMSIL for details).
//
if (IsCompilationProcess() && !IsReadyToRunCompilation())
{
RETURN(ComputeLoaderModuleForCompilation(pDefinitionModule, token, classInst, methodInst));
}
#endif // FEATURE_PREJIT
#endif // #ifndef DACCESS_COMPILE
Module *pFirstNonSharedLoaderModule = NULL;
Module *pFirstNonSystemSharedModule = NULL;
Module *pLoaderModule = NULL;
if (pDefinitionModule)
{
if (pDefinitionModule->IsCollectible())
goto ComputeCollectibleLoaderModule;
if (!pDefinitionModule->GetAssembly()->IsDomainNeutral())
{
pFirstNonSharedLoaderModule = pDefinitionModule;
}
else
if (!pDefinitionModule->IsSystem())
{
pFirstNonSystemSharedModule = pDefinitionModule;
}
}
for (DWORD i = 0; i < classInst.GetNumArgs(); i++)
{
TypeHandle classArg = classInst[i];
_ASSERTE(!classArg.IsEncodedFixup());
Module* pModule = classArg.GetLoaderModule();
if (pModule->IsCollectible())
goto ComputeCollectibleLoaderModule;
if (!pModule->GetAssembly()->IsDomainNeutral())
{
if (pFirstNonSharedLoaderModule == NULL)
pFirstNonSharedLoaderModule = pModule;
}
else
if (!pModule->IsSystem())
{
if (pFirstNonSystemSharedModule == NULL)
pFirstNonSystemSharedModule = pModule;
}
}
for (DWORD i = 0; i < methodInst.GetNumArgs(); i++)
{
TypeHandle methodArg = methodInst[i];
_ASSERTE(!methodArg.IsEncodedFixup());
Module *pModule = methodArg.GetLoaderModule();
if (pModule->IsCollectible())
goto ComputeCollectibleLoaderModule;
if (!pModule->GetAssembly()->IsDomainNeutral())
{
if (pFirstNonSharedLoaderModule == NULL)
pFirstNonSharedLoaderModule = pModule;
}
else
if (!pModule->IsSystem())
{
if (pFirstNonSystemSharedModule == NULL)
pFirstNonSystemSharedModule = pModule;
}
}
// RULE: Prefer modules in non-shared assemblies.
// This ensures safety of app-domain unloading.
if (pFirstNonSharedLoaderModule != NULL)
{
pLoaderModule = pFirstNonSharedLoaderModule;
}
else if (pFirstNonSystemSharedModule != NULL)
{
#ifdef FEATURE_FULL_NGEN
// pFirstNonSystemSharedModule may be module of speculative generic instantiation.
// If we are domain neutral, we have to use constituent of the instantiation to store
// statics. We need to ensure that we can create DomainModule in all domains
// that this instantiations may get activated in. PZM is good approximation of such constituent.
pLoaderModule = Module::ComputePreferredZapModule(pDefinitionModule, classInst, methodInst);
#else
// Use pFirstNonSystemSharedModule just so C<object> ends up in module C - it
// shouldn't actually matter at all though.
pLoaderModule = pFirstNonSystemSharedModule;
#endif
}
else
{
CONSISTENCY_CHECK(MscorlibBinder::GetModule() && MscorlibBinder::GetModule()->IsSystem());
pLoaderModule = MscorlibBinder::GetModule();
}
if (FALSE)
{
ComputeCollectibleLoaderModule:
LoaderAllocator *pLoaderAllocatorOfDefiningType = NULL;
LoaderAllocator *pOldestLoaderAllocator = NULL;
Module *pOldestLoaderModule = NULL;
UINT64 oldestFoundAge = 0;
DWORD classArgsCount = classInst.GetNumArgs();
DWORD totalArgsCount = classArgsCount + methodInst.GetNumArgs();
if (pDefinitionModule != NULL) pLoaderAllocatorOfDefiningType = pDefinitionModule->GetLoaderAllocator();
for (DWORD i = 0; i < totalArgsCount; i++) {
TypeHandle arg;
if (i < classArgsCount)
arg = classInst[i];
else
arg = methodInst[i - classArgsCount];
Module *pModuleCheck = arg.GetLoaderModule();
LoaderAllocator *pLoaderAllocatorCheck = pModuleCheck->GetLoaderAllocator();
if (pLoaderAllocatorCheck != pLoaderAllocatorOfDefiningType &&
pLoaderAllocatorCheck->IsCollectible() &&
pLoaderAllocatorCheck->GetCreationNumber() > oldestFoundAge)
{
pOldestLoaderModule = pModuleCheck;
pOldestLoaderAllocator = pLoaderAllocatorCheck;
oldestFoundAge = pLoaderAllocatorCheck->GetCreationNumber();
}
}
// Only if we didn't find a different loader allocator than the defining loader allocator do we
// use the defining loader allocator
if (pOldestLoaderModule != NULL)
pLoaderModule = pOldestLoaderModule;
else
pLoaderModule = pDefinitionModule;
}
RETURN PTR_Module(pLoaderModule);
}
#ifndef DACCESS_COMPILE
#ifdef FEATURE_NATIVE_IMAGE_GENERATION
/* static */
PTR_Module ClassLoader::ComputeLoaderModuleForCompilation(
Module * pDefinitionModule, // the module that declares the generic type or method
mdToken token, // method or class token for this item
Instantiation classInst, // the type arguments to the type (if any)
Instantiation methodInst) // the type arguments to the method (if any)
{
CONTRACT(Module*)
{
NOTHROW;
GC_NOTRIGGER;
FORBID_FAULT;
MODE_ANY;
PRECONDITION(CheckPointer(pDefinitionModule, NULL_OK));
POSTCONDITION(CheckPointer(RETVAL));
SO_INTOLERANT;
}
CONTRACT_END
// The NGEN rule for compiling constructed types and instantiated methods
// into modules other than their "natural" LoaderModule. This is at the heart of
// "full generics NGEN".
//
// If this instantiation doesn't have a unique home then use the ngen module
// OK, we're certainly NGEN'ing. And if we're NGEN'ing then we're not on the debugger thread.
CONSISTENCY_CHECK(((GetThread() && GetAppDomain()) || IsGCThread()) &&
"unexpected: running a load on debug thread but IsCompilationProcess() returned TRUE");
// Save it into its PreferredZapModule if it's always going to be saved there.
// This is a stable choice - no need to record it in the table (as we do for others below)
if (Module::IsAlwaysSavedInPreferredZapModule(classInst, methodInst))
{
RETURN (Module::ComputePreferredZapModule(pDefinitionModule, classInst, methodInst));
}
// Check if this compilation process has already decided on an adjustment. Once we decide
// on the LoaderModule for an item it must be stable for the duration of a
// compilation process, no matter how many modules get NGEN'd.
ZapperLoaderModuleTableKey key(pDefinitionModule,
token,
classInst,
methodInst);
Module * pZapperLoaderModule = g_pCEECompileInfo->LookupZapperLoaderModule(&key);
if (pZapperLoaderModule != NULL)
{
RETURN (pZapperLoaderModule);
}
// OK, we need to compute a non-standard zapping module.
Module * pPreferredZapModule = Module::ComputePreferredZapModule(pDefinitionModule, classInst, methodInst);
// Check if we're NGEN'ing but where perhaps the compilation domain
// isn't set up yet. This can happen in following situations:
// - Managed code running during startup before compilation domain is setup.
// - Exceptions (e.g. invalid program exceptions) thrown from compilation domain and caught in default domain
// We're a little stuck - we can't force the item into an NGEN image at this point. So just bail out
// and use the loader module we've computed without recording the choice. The loader module should always
// be mscorlib in this case.
AppDomain * pAppDomain = GetAppDomain();
if (!pAppDomain->IsCompilationDomain() ||
!pAppDomain->ToCompilationDomain()->GetTargetModule())
{
_ASSERTE(pPreferredZapModule->IsSystem() || IsNgenPDBCompilationProcess());
RETURN (pPreferredZapModule);
}
Module * pTargetModule = pAppDomain->ToCompilationDomain()->GetTargetModule();
// If it is multi-module assembly and we have not saved PZM yet, do not create
// speculative instantiation - just save it in PZM.
if (pTargetModule->GetAssembly() == pPreferredZapModule->GetAssembly() &&
!pPreferredZapModule->IsModuleSaved())
{
pZapperLoaderModule = pPreferredZapModule;
}
else
{
// Everything else can be saved into the current module.
pZapperLoaderModule = pTargetModule;
}
// If generating WinMD resilient code and we so far choose to use the target module,
// we need to check if the definition module or any of the instantiation type can
// cause version resilient problems.
if (g_fNGenWinMDResilient && pZapperLoaderModule == pTargetModule)
{
if (pDefinitionModule != NULL && !pDefinitionModule->IsInCurrentVersionBubble())
{
pZapperLoaderModule = pDefinitionModule;
goto ModuleAdjustedForVersionResiliency;
}
for (DWORD i = 0; i < classInst.GetNumArgs(); i++)
{
Module * pModule = classInst[i].GetLoaderModule();
if (!pModule->IsInCurrentVersionBubble())
{
pZapperLoaderModule = pModule;
goto ModuleAdjustedForVersionResiliency;
}
}
for (DWORD i = 0; i < methodInst.GetNumArgs(); i++)
{
Module * pModule = methodInst[i].GetLoaderModule();
if (!pModule->IsInCurrentVersionBubble())
{
pZapperLoaderModule = pModule;
goto ModuleAdjustedForVersionResiliency;
}
}
ModuleAdjustedForVersionResiliency: ;
}
// Record this choice just in case we're NGEN'ing multiple modules
// to make sure we always do the same thing if we're asked to compute
// the loader module again.
// Note this whole code path only happens while NGEN'ing, so this violation
// is not so bad. It is needed since we allocate stuff on the heap.
CONTRACT_VIOLATION(ThrowsViolation|FaultViolation);
// Copy the instantiation arrays so they can escape the scope of this method.
// Since this is a permanent entry in a table for this compilation process
// we do not need to collect these. If we did have to we would do it when we deleteed the
// ZapperLoaderModuleTable.
NewArrayHolder<TypeHandle> pClassArgs = NULL;
if (!classInst.IsEmpty())
{
pClassArgs = new TypeHandle[classInst.GetNumArgs()];
for (unsigned int i = 0; i < classInst.GetNumArgs(); i++)
pClassArgs[i] = classInst[i];
}
NewArrayHolder<TypeHandle> pMethodArgs = NULL;
if (!methodInst.IsEmpty())
{
pMethodArgs = new TypeHandle[methodInst.GetNumArgs()];
for (unsigned int i = 0; i < methodInst.GetNumArgs(); i++)
pMethodArgs[i] = methodInst[i];
}
ZapperLoaderModuleTableKey key2(pDefinitionModule,
token,
Instantiation(pClassArgs, classInst.GetNumArgs()),
Instantiation(pMethodArgs, methodInst.GetNumArgs()));
g_pCEECompileInfo->RecordZapperLoaderModule(&key2, pZapperLoaderModule);
pClassArgs.SuppressRelease();
pMethodArgs.SuppressRelease();
RETURN (pZapperLoaderModule);
}
#endif // FEATURE_NATIVE_IMAGE_GENERATION
#endif // #ifndef DACCESS_COMPILE
/*static*/
Module * ClassLoader::ComputeLoaderModule(MethodTable * pMT,
mdToken token,
Instantiation methodInst)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
SUPPORTS_DAC;
}
CONTRACTL_END;
return ComputeLoaderModuleWorker(pMT->GetModule(),
token,
pMT->GetInstantiation(),
methodInst);
}
/*static*/
Module *ClassLoader::ComputeLoaderModule(TypeKey *typeKey)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
SUPPORTS_DAC;
}
CONTRACTL_END;
if (typeKey->GetKind() == ELEMENT_TYPE_CLASS)
return ComputeLoaderModuleWorker(typeKey->GetModule(),
typeKey->GetTypeToken(),
typeKey->GetInstantiation(),
Instantiation());
else if (typeKey->GetKind() == ELEMENT_TYPE_FNPTR)
return ComputeLoaderModuleForFunctionPointer(typeKey->GetRetAndArgTypes(), typeKey->GetNumArgs() + 1);
else
return ComputeLoaderModuleForParamType(typeKey->GetElementType());
}
/*static*/
BOOL ClassLoader::IsTypicalInstantiation(Module *pModule, mdToken token, Instantiation inst)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
FORBID_FAULT;
PRECONDITION(CheckPointer(pModule));
PRECONDITION(TypeFromToken(token) == mdtTypeDef || TypeFromToken(token) == mdtMethodDef);
SUPPORTS_DAC;
}
CONTRACTL_END
for (DWORD i = 0; i < inst.GetNumArgs(); i++)
{
TypeHandle thArg = inst[i];
if (thArg.IsGenericVariable())
{
TypeVarTypeDesc* tyvar = thArg.AsGenericVariable();
PREFIX_ASSUME(tyvar!=NULL);
if ((tyvar->GetTypeOrMethodDef() != token) ||
(tyvar->GetModule() != dac_cast<PTR_Module>(pModule)) ||
(tyvar->GetIndex() != i))
return FALSE;
}
else
{
return FALSE;
}
}
return TRUE;
}
// External class loader entry point: load a type by name
/*static*/
TypeHandle ClassLoader::LoadTypeByNameThrowing(Assembly *pAssembly,
LPCUTF8 nameSpace,
LPCUTF8 name,
NotFoundAction fNotFound,
ClassLoader::LoadTypesFlag fLoadTypes,
ClassLoadLevel level)
{
CONTRACT(TypeHandle)
{
if (FORBIDGC_LOADER_USE_ENABLED()) NOTHROW; else THROWS;
if (FORBIDGC_LOADER_USE_ENABLED()) GC_NOTRIGGER; else GC_TRIGGERS;
if (FORBIDGC_LOADER_USE_ENABLED()) FORBID_FAULT; else { INJECT_FAULT(COMPlusThrowOM()); }
MODE_ANY;
if (FORBIDGC_LOADER_USE_ENABLED() || fLoadTypes != LoadTypes) { LOADS_TYPE(CLASS_LOAD_BEGIN); } else { LOADS_TYPE(level); }
PRECONDITION(CheckPointer(pAssembly));
PRECONDITION(level > CLASS_LOAD_BEGIN && level <= CLASS_LOADED);
POSTCONDITION(CheckPointer(RETVAL,
(fNotFound == ThrowIfNotFound && fLoadTypes == LoadTypes )? NULL_NOT_OK : NULL_OK));
POSTCONDITION(RETVAL.IsNull() || RETVAL.CheckLoadLevel(level));
SUPPORTS_DAC;
#ifdef DACCESS_COMPILE
PRECONDITION((fNotFound == ClassLoader::ReturnNullIfNotFound) && (fLoadTypes == DontLoadTypes));
#endif
}
CONTRACT_END
NameHandle nameHandle(nameSpace, name);
if (fLoadTypes == DontLoadTypes)
nameHandle.SetTokenNotToLoad(tdAllTypes);
if (fNotFound == ThrowIfNotFound)
RETURN pAssembly->GetLoader()->LoadTypeHandleThrowIfFailed(&nameHandle, level);
else
RETURN pAssembly->GetLoader()->LoadTypeHandleThrowing(&nameHandle, level);
}
#ifndef DACCESS_COMPILE
#define DAC_LOADS_TYPE(level, expression) \
if (FORBIDGC_LOADER_USE_ENABLED() || (expression)) \
{ LOADS_TYPE(CLASS_LOAD_BEGIN); } else { LOADS_TYPE(level); }
#else
#define DAC_LOADS_TYPE(level, expression) { LOADS_TYPE(CLASS_LOAD_BEGIN); }
#endif // #ifndef DACCESS_COMPILE
//
// Find a class given name, using the classloader's global list of known classes.
// If the type is found, it will be restored unless pName->GetTokenNotToLoad() prohibits that
// Returns NULL if class not found AND pName->OKToLoad returns false
TypeHandle ClassLoader::LoadTypeHandleThrowIfFailed(NameHandle* pName, ClassLoadLevel level,
Module* pLookInThisModuleOnly/*=NULL*/)
{
CONTRACT(TypeHandle)
{
INSTANCE_CHECK;
if (FORBIDGC_LOADER_USE_ENABLED()) NOTHROW; else THROWS;
if (FORBIDGC_LOADER_USE_ENABLED()) GC_NOTRIGGER; else GC_TRIGGERS;
if (FORBIDGC_LOADER_USE_ENABLED()) FORBID_FAULT; else { INJECT_FAULT(COMPlusThrowOM()); }
DAC_LOADS_TYPE(level, !pName->OKToLoad());
MODE_ANY;
PRECONDITION(CheckPointer(pName));
PRECONDITION(level > CLASS_LOAD_BEGIN && level <= CLASS_LOADED);
POSTCONDITION(CheckPointer(RETVAL, pName->OKToLoad() ? NULL_NOT_OK : NULL_OK));
POSTCONDITION(RETVAL.IsNull() || RETVAL.CheckLoadLevel(level));
SUPPORTS_DAC;
}
CONTRACT_END;
// Lookup in the classes that this class loader knows about
TypeHandle typeHnd = LoadTypeHandleThrowing(pName, level, pLookInThisModuleOnly);
if(typeHnd.IsNull()) {
if ( pName->OKToLoad() ) {
#ifdef _DEBUG_IMPL
{
LPCUTF8 szName = pName->GetName();
if (szName == NULL)
szName = "<UNKNOWN>";
StackSString codeBase;
GetAssembly()->GetCodeBase(codeBase);
LOG((LF_CLASSLOADER, LL_INFO10, "Failed to find class \"%s\" in the manifest for assembly \"%ws\"\n", szName, (LPCWSTR)codeBase));
}
#endif
#ifndef DACCESS_COMPILE
COUNTER_ONLY(GetPerfCounters().m_Loading.cLoadFailures++);
m_pAssembly->ThrowTypeLoadException(pName, IDS_CLASSLOAD_GENERAL);
#else
DacNotImpl();
#endif
}
}
RETURN(typeHnd);
}
#ifndef DACCESS_COMPILE
//<TODO>@TODO: Need to allow exceptions to be thrown when classloader is cleaned up</TODO>
EEClassHashEntry_t* ClassLoader::InsertValue(EEClassHashTable *pClassHash, EEClassHashTable *pClassCaseInsHash, LPCUTF8 pszNamespace, LPCUTF8 pszClassName, HashDatum Data, EEClassHashEntry_t *pEncloser, AllocMemTracker *pamTracker)
{
CONTRACTL
{
INSTANCE_CHECK;
THROWS;
GC_NOTRIGGER;
MODE_ANY;
INJECT_FAULT(COMPlusThrowOM(););
}
CONTRACTL_END
LPUTF8 pszLowerCaseNS = NULL;
LPUTF8 pszLowerCaseName = NULL;
EEClassHashEntry_t *pCaseInsEntry = NULL;
EEClassHashEntry_t *pEntry = pClassHash->AllocNewEntry(pamTracker);
if (pClassCaseInsHash) {
CreateCanonicallyCasedKey(pszNamespace, pszClassName, &pszLowerCaseNS, &pszLowerCaseName);
pCaseInsEntry = pClassCaseInsHash->AllocNewEntry(pamTracker);
}
{
// ! We cannot fail after this point.
CANNOTTHROWCOMPLUSEXCEPTION();
FAULT_FORBID();
pClassHash->InsertValueUsingPreallocatedEntry(pEntry, pszNamespace, pszClassName, Data, pEncloser);
//If we're keeping a table for case-insensitive lookup, keep that up to date
if (pClassCaseInsHash)
pClassCaseInsHash->InsertValueUsingPreallocatedEntry(pCaseInsEntry, pszLowerCaseNS, pszLowerCaseName, pEntry, pEncloser);
return pEntry;
}
}
#endif // #ifndef DACCESS_COMPILE
BOOL ClassLoader::CompareNestedEntryWithExportedType(IMDInternalImport * pImport,
mdExportedType mdCurrent,
EEClassHashTable * pClassHash,
PTR_EEClassHashEntry pEntry)
{
CONTRACTL
{
INSTANCE_CHECK;
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
FORBID_FAULT;
SUPPORTS_DAC;
}
CONTRACTL_END;
LPCUTF8 Key[2];
do
{
if (FAILED(pImport->GetExportedTypeProps(
mdCurrent,
&Key[0],
&Key[1],
&mdCurrent,
NULL, //binding (type def)
NULL))) //flags
{
return FALSE;
}
if (pClassHash->CompareKeys(pEntry, Key))
{
// Reached top level class for mdCurrent - return whether
// or not pEntry is a top level class
// (pEntry is a top level class if its pEncloser is NULL)
if ((TypeFromToken(mdCurrent) != mdtExportedType) ||
(mdCurrent == mdExportedTypeNil))
{
return pEntry->GetEncloser() == NULL;
}
}
else // Keys don't match - wrong entry
{
return FALSE;
}
}
while ((pEntry = pEntry->GetEncloser()) != NULL);
// Reached the top level class for pEntry, but mdCurrent is nested
return FALSE;
}
BOOL ClassLoader::CompareNestedEntryWithTypeDef(IMDInternalImport * pImport,
mdTypeDef mdCurrent,
EEClassHashTable * pClassHash,
PTR_EEClassHashEntry pEntry)
{
CONTRACTL
{
INSTANCE_CHECK;
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
FORBID_FAULT;
SUPPORTS_DAC;
}
CONTRACTL_END;
LPCUTF8 Key[2];
do {
if (FAILED(pImport->GetNameOfTypeDef(mdCurrent, &Key[1], &Key[0])))
{
return FALSE;
}
if (pClassHash->CompareKeys(pEntry, Key)) {
// Reached top level class for mdCurrent - return whether
// or not pEntry is a top level class
// (pEntry is a top level class if its pEncloser is NULL)
if (FAILED(pImport->GetNestedClassProps(mdCurrent, &mdCurrent)))
return pEntry->GetEncloser() == NULL;
}
else // Keys don't match - wrong entry
return FALSE;
}
while ((pEntry = pEntry->GetEncloser()) != NULL);
// Reached the top level class for pEntry, but mdCurrent is nested
return FALSE;
}
BOOL ClassLoader::CompareNestedEntryWithTypeRef(IMDInternalImport * pImport,
mdTypeRef mdCurrent,
EEClassHashTable * pClassHash,
PTR_EEClassHashEntry pEntry)
{
CONTRACTL
{
INSTANCE_CHECK;
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
FORBID_FAULT;
SUPPORTS_DAC;
}
CONTRACTL_END;
LPCUTF8 Key[2];
do {
if (FAILED(pImport->GetNameOfTypeRef(mdCurrent, &Key[0], &Key[1])))
{
return FALSE;
}
if (pClassHash->CompareKeys(pEntry, Key))
{
if (FAILED(pImport->GetResolutionScopeOfTypeRef(mdCurrent, &mdCurrent)))
{
return FALSE;
}
// Reached top level class for mdCurrent - return whether
// or not pEntry is a top level class
// (pEntry is a top level class if its pEncloser is NULL)
if ((TypeFromToken(mdCurrent) != mdtTypeRef) ||
(mdCurrent == mdTypeRefNil))
return pEntry->GetEncloser() == NULL;
}
else // Keys don't match - wrong entry
return FALSE;
}
while ((pEntry = pEntry->GetEncloser())!=NULL);
// Reached the top level class for pEntry, but mdCurrent is nested
return FALSE;
}
/*static*/
BOOL ClassLoader::IsNested(Module *pModule, mdToken token, mdToken *mdEncloser)
{
CONTRACTL
{
if (FORBIDGC_LOADER_USE_ENABLED()) NOTHROW; else THROWS;
if (FORBIDGC_LOADER_USE_ENABLED()) GC_NOTRIGGER; else GC_TRIGGERS;
if (FORBIDGC_LOADER_USE_ENABLED()) FORBID_FAULT; else { INJECT_FAULT(COMPlusThrowOM()); }
MODE_ANY;
SUPPORTS_DAC;
}
CONTRACTL_END;
switch(TypeFromToken(token)) {
case mdtTypeDef:
return (SUCCEEDED(pModule->GetMDImport()->GetNestedClassProps(token, mdEncloser)));
case mdtTypeRef:
IfFailThrow(pModule->GetMDImport()->GetResolutionScopeOfTypeRef(token, mdEncloser));
return ((TypeFromToken(*mdEncloser) == mdtTypeRef) &&
(*mdEncloser != mdTypeRefNil));
case mdtExportedType:
IfFailThrow(pModule->GetAssembly()->GetManifestImport()->GetExportedTypeProps(
token,
NULL, // namespace
NULL, // name
mdEncloser,
NULL, //binding (type def)
NULL)); //flags
return ((TypeFromToken(*mdEncloser) == mdtExportedType) &&
(*mdEncloser != mdExportedTypeNil));
default:
ThrowHR(COR_E_BADIMAGEFORMAT, BFA_INVALID_TOKEN_TYPE);
}
}
BOOL ClassLoader::IsNested(NameHandle* pName, mdToken *mdEncloser)
{
CONTRACTL
{
INSTANCE_CHECK;
if (FORBIDGC_LOADER_USE_ENABLED()) NOTHROW; else THROWS;
if (FORBIDGC_LOADER_USE_ENABLED()) GC_NOTRIGGER; else GC_TRIGGERS;
if (FORBIDGC_LOADER_USE_ENABLED()) FORBID_FAULT; else { INJECT_FAULT(COMPlusThrowOM()); }
MODE_ANY;
SUPPORTS_DAC;
}
CONTRACTL_END;
if (pName->GetTypeModule()) {
if (TypeFromToken(pName->GetTypeToken()) == mdtBaseType)
{
if (!pName->GetBucket().IsNull())
return TRUE;
return FALSE;
}
else
return IsNested(pName->GetTypeModule(), pName->GetTypeToken(), mdEncloser);
}
else
return FALSE;
}
void ClassLoader::GetClassValue(NameHandleTable nhTable,
NameHandle *pName,
HashDatum *pData,
EEClassHashTable **ppTable,
Module* pLookInThisModuleOnly,
HashedTypeEntry* pFoundEntry,
Loader::LoadFlag loadFlag,
BOOL& needsToBuildHashtable)
{
CONTRACTL
{
INSTANCE_CHECK;
MODE_ANY;
if (FORBIDGC_LOADER_USE_ENABLED()) NOTHROW; else THROWS;
if (FORBIDGC_LOADER_USE_ENABLED()) GC_NOTRIGGER; else GC_TRIGGERS;
if (FORBIDGC_LOADER_USE_ENABLED()) FORBID_FAULT; else { INJECT_FAULT(COMPlusThrowOM()); }
PRECONDITION(CheckPointer(pName));
SUPPORTS_DAC;
}
CONTRACTL_END
mdToken mdEncloser;
EEClassHashEntry_t *pBucket = NULL;
needsToBuildHashtable = FALSE;
#if _DEBUG
if (pName->GetName()) {
if (pName->GetNameSpace() == NULL)
LOG((LF_CLASSLOADER, LL_INFO1000, "Looking up %s by name.\n",
pName->GetName()));
else
LOG((LF_CLASSLOADER, LL_INFO1000, "Looking up %s.%s by name.\n",
pName->GetNameSpace(), pName->GetName()));
}
#endif
BOOL isNested = IsNested(pName, &mdEncloser);
PTR_Assembly assembly = GetAssembly();
PREFIX_ASSUME(assembly != NULL);
ModuleIterator i = assembly->IterateModules();
while (i.Next())
{
Module * pCurrentClsModule = i.GetModule();
PREFIX_ASSUME(pCurrentClsModule != NULL);
if (pCurrentClsModule->IsResource())
continue;
if (pLookInThisModuleOnly && (pCurrentClsModule != pLookInThisModuleOnly))
continue;
#ifdef FEATURE_READYTORUN
if (nhTable == nhCaseSensitive && pCurrentClsModule->IsReadyToRun() && pCurrentClsModule->GetReadyToRunInfo()->HasHashtableOfTypes())
{
// For R2R modules, we only search the hashtable of token types stored in the module's image, and don't fallback
// to searching m_pAvailableClasses or m_pAvailableClassesCaseIns (in fact, we don't even allocate them for R2R modules).
// Also note that type lookups in R2R modules only support case sensitive lookups.
mdToken mdFoundTypeToken;
if (pCurrentClsModule->GetReadyToRunInfo()->TryLookupTypeTokenFromName(pName, &mdFoundTypeToken))
{
if (TypeFromToken(mdFoundTypeToken) == mdtExportedType)
{
mdToken mdUnused;
Module * pTargetModule = GetAssembly()->FindModuleByExportedType(mdFoundTypeToken, loadFlag, mdTypeDefNil, &mdUnused);
pFoundEntry->SetTokenBasedEntryValue(mdFoundTypeToken, pTargetModule);
}
else
{
pFoundEntry->SetTokenBasedEntryValue(mdFoundTypeToken, pCurrentClsModule);
}
return; // Return on the first success
}
}
else
#endif
{
EEClassHashTable* pTable = NULL;
if (nhTable == nhCaseSensitive)
{
*ppTable = pTable = pCurrentClsModule->GetAvailableClassHash();
#ifdef FEATURE_READYTORUN
if (pTable == NULL && pCurrentClsModule->IsReadyToRun() && !pCurrentClsModule->GetReadyToRunInfo()->HasHashtableOfTypes())
{
// Old R2R image generated without the hashtable of types.
// We fallback to the slow path of creating the hashtable dynamically
// at execution time in that scenario. The caller will handle
pFoundEntry->SetClassHashBasedEntryValue(NULL);
needsToBuildHashtable = TRUE;
return;
}
#endif
}
else
{
// currently we expect only these two kinds--for DAC builds, nhTable will be nhCaseSensitive
_ASSERTE(nhTable == nhCaseInsensitive);
*ppTable = pTable = pCurrentClsModule->GetAvailableClassCaseInsHash();
if (pTable == NULL)
{
// We have not built the table yet - the caller will handle
pFoundEntry->SetClassHashBasedEntryValue(NULL);
needsToBuildHashtable = TRUE;
return;
}
}
_ASSERTE(pTable);
if (isNested)
{
Module *pNameModule = pName->GetTypeModule();
PREFIX_ASSUME(pNameModule != NULL);
EEClassHashTable::LookupContext sContext;
if ((pBucket = pTable->GetValue(pName, pData, TRUE, &sContext)) != NULL)
{
switch (TypeFromToken(pName->GetTypeToken()))
{
case mdtTypeDef:
while ((!CompareNestedEntryWithTypeDef(pNameModule->GetMDImport(),
mdEncloser,
pCurrentClsModule->GetAvailableClassHash(),
pBucket->GetEncloser())) &&
(pBucket = pTable->FindNextNestedClass(pName, pData, &sContext)) != NULL);
break;
case mdtTypeRef:
while ((!CompareNestedEntryWithTypeRef(pNameModule->GetMDImport(),
mdEncloser,
pCurrentClsModule->GetAvailableClassHash(),
pBucket->GetEncloser())) &&
(pBucket = pTable->FindNextNestedClass(pName, pData, &sContext)) != NULL);
break;
case mdtExportedType:
while ((!CompareNestedEntryWithExportedType(pNameModule->GetAssembly()->GetManifestImport(),
mdEncloser,
pCurrentClsModule->GetAvailableClassHash(),
pBucket->GetEncloser())) &&
(pBucket = pTable->FindNextNestedClass(pName, pData, &sContext)) != NULL);
break;
default:
while ((pBucket->GetEncloser() != pName->GetBucket().GetClassHashBasedEntryValue()) &&
(pBucket = pTable->FindNextNestedClass(pName, pData, &sContext)) != NULL);
}
}
}
else
{
pBucket = pTable->GetValue(pName, pData, FALSE, NULL);
}
if (pBucket) // Return on the first success
{
pFoundEntry->SetClassHashBasedEntryValue(pBucket);
return;
}
}
}
// No results found: default to a NULL EEClassHashEntry_t result
pFoundEntry->SetClassHashBasedEntryValue(NULL);
}
#ifndef DACCESS_COMPILE
VOID ClassLoader::PopulateAvailableClassHashTable(Module* pModule,
AllocMemTracker *pamTracker)
{
CONTRACTL
{
INSTANCE_CHECK;
THROWS;
GC_TRIGGERS;
MODE_ANY;
INJECT_FAULT(COMPlusThrowOM(););
}
CONTRACTL_END;
mdTypeDef td;
HENUMInternal hTypeDefEnum;
IMDInternalImport * pImport = pModule->GetMDImport();
LPCSTR szWinRtNamespacePrefix = NULL;
DWORD cchWinRtNamespacePrefix = 0;
#ifdef FEATURE_COMINTEROP
SString ssFileName;
StackScratchBuffer ssFileNameBuffer;
if (pModule->GetAssembly()->IsWinMD() &&
!pModule->IsIntrospectionOnly())
{ // WinMD file in execution context (not ReflectionOnly context) - use its file name as WinRT namespace prefix
// (Windows requirement)
// Note: Reflection can work on 'unfinished' WinMD files where the types are in 'wrong' WinMD file (i.e.
// type namespace does not start with the file name)
_ASSERTE(pModule->GetFile()->IsAssembly()); // No multi-module WinMD file support
_ASSERTE(!pModule->GetFile()->GetPath().IsEmpty());
SplitPath(
pModule->GetFile()->GetPath(),
NULL, // Drive
NULL, // Directory
&ssFileName,
NULL); // Extension
szWinRtNamespacePrefix = ssFileName.GetUTF8(ssFileNameBuffer);
cchWinRtNamespacePrefix = (DWORD)strlen(szWinRtNamespacePrefix);
}
#endif //FEATURE_COMINTEROP
IfFailThrow(pImport->EnumTypeDefInit(&hTypeDefEnum));
// Now loop through all the classdefs adding the CVID and scope to the hash
while(pImport->EnumTypeDefNext(&hTypeDefEnum, &td)) {
AddAvailableClassHaveLock(pModule,
td,
pamTracker,
szWinRtNamespacePrefix,
cchWinRtNamespacePrefix);
}
pImport->EnumTypeDefClose(&hTypeDefEnum);
}
void ClassLoader::LazyPopulateCaseSensitiveHashTables()
{
CONTRACTL
{
INSTANCE_CHECK;
THROWS;
GC_TRIGGERS;
MODE_ANY;
INJECT_FAULT(COMPlusThrowOM());
}
CONTRACTL_END;
AllocMemTracker amTracker;
ModuleIterator i = GetAssembly()->IterateModules();
// Create a case-sensitive hashtable for each module, and fill it with the module's typedef entries
while (i.Next())
{
Module *pModule = i.GetModule();
PREFIX_ASSUME(pModule != NULL);
if (pModule->IsResource())
continue;
// Lazy construction of the case-sensitive hashtable of types is *only* a scenario for ReadyToRun images
// (either images compiled with an old version of crossgen, or for case-insensitive type lookups in R2R modules)
_ASSERT(pModule->IsReadyToRun());
EEClassHashTable * pNewClassHash = EEClassHashTable::Create(pModule, AVAILABLE_CLASSES_HASH_BUCKETS, FALSE /* bCaseInsensitive */, &amTracker);
pModule->SetAvailableClassHash(pNewClassHash);
PopulateAvailableClassHashTable(pModule, &amTracker);
}
// Add exported types of the manifest module to the hashtable
if (!GetAssembly()->GetManifestModule()->IsResource())
{
IMDInternalImport * pManifestImport = GetAssembly()->GetManifestImport();
HENUMInternalHolder phEnum(pManifestImport);
phEnum.EnumInit(mdtExportedType, mdTokenNil);
mdToken mdExportedType;
while (pManifestImport->EnumNext(&phEnum, &mdExportedType))
AddExportedTypeHaveLock(GetAssembly()->GetManifestModule(), mdExportedType, &amTracker);
}
amTracker.SuppressRelease();
}
void ClassLoader::LazyPopulateCaseInsensitiveHashTables()
{
CONTRACTL
{
INSTANCE_CHECK;
THROWS;
GC_TRIGGERS;
MODE_ANY;
INJECT_FAULT(COMPlusThrowOM());
}
CONTRACTL_END;
if (!GetAssembly()->GetManifestModule()->IsResource() && GetAssembly()->GetManifestModule()->GetAvailableClassHash() == NULL)
{
// This is a R2R assembly, and a case insensitive type lookup was triggered.
// Construct the case-sensitive table first, since the case-insensitive table
// create piggy-backs on the first.
LazyPopulateCaseSensitiveHashTables();
}
// Add any unhashed modules into our hash tables, and try again.
AllocMemTracker amTracker;
ModuleIterator i = GetAssembly()->IterateModules();
while (i.Next())
{
Module *pModule = i.GetModule();
if (pModule->IsResource())
continue;
if (pModule->GetAvailableClassCaseInsHash() == NULL)
{
EEClassHashTable *pNewClassCaseInsHash = pModule->GetAvailableClassHash()->MakeCaseInsensitiveTable(pModule, &amTracker);
LOG((LF_CLASSLOADER, LL_INFO10, "%s's classes being added to case insensitive hash table\n",
pModule->GetSimpleName()));
{
CANNOTTHROWCOMPLUSEXCEPTION();
FAULT_FORBID();
amTracker.SuppressRelease();
pModule->SetAvailableClassCaseInsHash(pNewClassCaseInsHash);
FastInterlockDecrement((LONG*)&m_cUnhashedModules);
}
}
}
}
/*static*/
void DECLSPEC_NORETURN ClassLoader::ThrowTypeLoadException(TypeKey *pKey,
UINT resIDWhy)
{
STATIC_CONTRACT_THROWS;
StackSString fullName;
StackSString assemblyName;
TypeString::AppendTypeKey(fullName, pKey);
pKey->GetModule()->GetAssembly()->GetDisplayName(assemblyName);
::ThrowTypeLoadException(fullName, assemblyName, NULL, resIDWhy);
}
#endif
TypeHandle ClassLoader::LoadConstructedTypeThrowing(TypeKey *pKey,
LoadTypesFlag fLoadTypes /*= LoadTypes*/,
ClassLoadLevel level /*=CLASS_LOADED*/,
const InstantiationContext *pInstContext /*=NULL*/)
{
CONTRACT(TypeHandle)
{
if (FORBIDGC_LOADER_USE_ENABLED()) NOTHROW; else THROWS;
if (FORBIDGC_LOADER_USE_ENABLED()) GC_NOTRIGGER; else GC_TRIGGERS;
if (FORBIDGC_LOADER_USE_ENABLED()) FORBID_FAULT; else { INJECT_FAULT(COMPlusThrowOM()); }
if (FORBIDGC_LOADER_USE_ENABLED() || fLoadTypes != LoadTypes) { LOADS_TYPE(CLASS_LOAD_BEGIN); } else { LOADS_TYPE(level); }
if (fLoadTypes == DontLoadTypes) SO_TOLERANT; else SO_INTOLERANT;
PRECONDITION(CheckPointer(pKey));
PRECONDITION(level > CLASS_LOAD_BEGIN && level <= CLASS_LOADED);
PRECONDITION(CheckPointer(pInstContext, NULL_OK));
POSTCONDITION(CheckPointer(RETVAL, fLoadTypes==DontLoadTypes ? NULL_OK : NULL_NOT_OK));
POSTCONDITION(RETVAL.IsNull() || RETVAL.GetLoadLevel() >= level);
MODE_ANY;
SUPPORTS_DAC;
}
CONTRACT_END
TypeHandle typeHnd;
ClassLoadLevel existingLoadLevel = CLASS_LOAD_BEGIN;
// Lookup in the classes that this class loader knows about
if (pKey->HasInstantiation() && ClassLoader::IsTypicalSharedInstantiation(pKey->GetInstantiation()))
{
_ASSERTE(pKey->GetModule() == ComputeLoaderModule(pKey));
typeHnd = pKey->GetModule()->LookupFullyCanonicalInstantiation(pKey->GetTypeToken(), &existingLoadLevel);
}
if (typeHnd.IsNull())
{
typeHnd = LookupTypeHandleForTypeKey(pKey);
if (!typeHnd.IsNull())
{
existingLoadLevel = typeHnd.GetLoadLevel();
if (existingLoadLevel >= level)
g_IBCLogger.LogTypeHashTableAccess(&typeHnd);
}
}
// If something has been published in the tables, and it's at the right level, just return it
if (!typeHnd.IsNull() && existingLoadLevel >= level)
{
RETURN typeHnd;
}
#ifndef DACCESS_COMPILE
if (typeHnd.IsNull() && pKey->HasInstantiation())
{
if (!Generics::CheckInstantiation(pKey->GetInstantiation()))
pKey->GetModule()->GetAssembly()->ThrowTypeLoadException(pKey->GetModule()->GetMDImport(), pKey->GetTypeToken(), IDS_CLASSLOAD_INVALIDINSTANTIATION);
}
#endif
// If we're not loading any types at all, then we're not creating
// instantiations either because we're in FORBIDGC_LOADER_USE mode, so
// we should bail out here.
if (fLoadTypes == DontLoadTypes)
RETURN TypeHandle();
#ifndef DACCESS_COMPILE
// If we got here, we now have to allocate a new parameterized type.
// By definition, forbidgc-users aren't allowed to reach this point.
CONSISTENCY_CHECK(!FORBIDGC_LOADER_USE_ENABLED());
Module *pLoaderModule = ComputeLoaderModule(pKey);
RETURN(pLoaderModule->GetClassLoader()->LoadTypeHandleForTypeKey(pKey, typeHnd, level, pInstContext));
#else
DacNotImpl();
RETURN(typeHnd);
#endif
}
/*static*/
void ClassLoader::EnsureLoaded(TypeHandle typeHnd, ClassLoadLevel level)
{
CONTRACTL
{
PRECONDITION(CheckPointer(typeHnd));
PRECONDITION(level > CLASS_LOAD_BEGIN && level <= CLASS_LOADED);
if (FORBIDGC_LOADER_USE_ENABLED()) NOTHROW; else THROWS;
if (FORBIDGC_LOADER_USE_ENABLED()) GC_NOTRIGGER; else GC_TRIGGERS;
if (FORBIDGC_LOADER_USE_ENABLED()) FORBID_FAULT; else { INJECT_FAULT(COMPlusThrowOM()); }
if (FORBIDGC_LOADER_USE_ENABLED()) { LOADS_TYPE(CLASS_LOAD_BEGIN); } else { LOADS_TYPE(level); }
SUPPORTS_DAC;
MODE_ANY;
}
CONTRACTL_END
#ifndef DACCESS_COMPILE // Nothing to do for the DAC case
if (typeHnd.GetLoadLevel() < level)
{
INTERIOR_STACK_PROBE_CHECK_THREAD;
#ifdef FEATURE_PREJIT
if (typeHnd.GetLoadLevel() == CLASS_LOAD_UNRESTOREDTYPEKEY)
{
typeHnd.DoRestoreTypeKey();
}
#endif
if (level > CLASS_LOAD_UNRESTORED)
{
TypeKey typeKey = typeHnd.GetTypeKey();
Module *pLoaderModule = ComputeLoaderModule(&typeKey);
pLoaderModule->GetClassLoader()->LoadTypeHandleForTypeKey(&typeKey, typeHnd, level);
}
END_INTERIOR_STACK_PROBE;
}
#endif // DACCESS_COMPILE
}
/*static*/
void ClassLoader::TryEnsureLoaded(TypeHandle typeHnd, ClassLoadLevel level)
{
WRAPPER_NO_CONTRACT;
#ifndef DACCESS_COMPILE // Nothing to do for the DAC case
EX_TRY
{
ClassLoader::EnsureLoaded(typeHnd, level);
}
EX_CATCH
{
// Some type may not load successfully. For eg. generic instantiations
// that do not satisfy the constraints of the type arguments.
}
EX_END_CATCH(RethrowTerminalExceptions);
#endif // DACCESS_COMPILE
}
// This is separated out to avoid the overhead of C++ exception handling in the non-locking case.
/* static */
TypeHandle ClassLoader::LookupTypeKeyUnderLock(TypeKey *pKey,
EETypeHashTable *pTable,
CrstBase *pLock)
{
WRAPPER_NO_CONTRACT;
SUPPORTS_DAC;
CrstHolder ch(pLock);
return pTable->GetValue(pKey);
}
/* static */
TypeHandle ClassLoader::LookupTypeKey(TypeKey *pKey,
EETypeHashTable *pTable,
CrstBase *pLock,
BOOL fCheckUnderLock)
{
CONTRACTL {
NOTHROW;
GC_NOTRIGGER;
FORBID_FAULT;
PRECONDITION(CheckPointer(pKey));
PRECONDITION(pKey->IsConstructed());
PRECONDITION(CheckPointer(pTable));
PRECONDITION(!fCheckUnderLock || CheckPointer(pLock));
MODE_ANY;
SUPPORTS_DAC;
} CONTRACTL_END;
TypeHandle th;
// If this is the GC thread, and we're hosted, we're in a sticky situation with
// SQL where we may have suspended another thread while doing Thread::SuspendRuntime.
// In this case, we have the issue that a thread holding this lock could be
// suspended, perhaps implicitly because the active thread on the SQL scheduler
// has been suspended by the GC thread. In such a case, we need to skip taking
// the lock. We can be sure that there will be no races in such a condition because
// we will only be looking for types that are already loaded, or for a type that
// is not loaded, but we will never cause the type to get loaded, and so the result
// of the lookup will not change.
#ifndef DACCESS_COMPILE
if (fCheckUnderLock && !(IsGCThread() && CLRTaskHosted()))
#else
if (fCheckUnderLock)
#endif // DACCESS_COMPILE
{
th = LookupTypeKeyUnderLock(pKey, pTable, pLock);
}
else
{
th = pTable->GetValue(pKey);
}
return th;
}
#ifdef FEATURE_PREJIT
/* static */
TypeHandle ClassLoader::LookupInPreferredZapModule(TypeKey *pKey, BOOL fCheckUnderLock)
{
CONTRACTL {
NOTHROW;
GC_NOTRIGGER;
FORBID_FAULT;
PRECONDITION(CheckPointer(pKey));
PRECONDITION(pKey->IsConstructed());
MODE_ANY;
SUPPORTS_DAC;
} CONTRACTL_END;
// First look for an NGEN'd type in the preferred ngen module
TypeHandle th;
PTR_Module pPreferredZapModule = Module::ComputePreferredZapModule(pKey);
if (pPreferredZapModule != NULL && pPreferredZapModule->HasNativeImage())
{
th = LookupTypeKey(pKey,
pPreferredZapModule->GetAvailableParamTypes(),
&pPreferredZapModule->GetClassLoader()->m_AvailableTypesLock,
fCheckUnderLock);
}
return th;
}
#endif // FEATURE_PREJIT
/* static */
TypeHandle ClassLoader::LookupInLoaderModule(TypeKey *pKey, BOOL fCheckUnderLock)
{
CONTRACTL {
NOTHROW;
GC_NOTRIGGER;
FORBID_FAULT;
PRECONDITION(CheckPointer(pKey));
PRECONDITION(pKey->IsConstructed());
MODE_ANY;
SUPPORTS_DAC;
} CONTRACTL_END;
Module *pLoaderModule = ComputeLoaderModule(pKey);
PREFIX_ASSUME(pLoaderModule!=NULL);
return LookupTypeKey(pKey,
pLoaderModule->GetAvailableParamTypes(),
&pLoaderModule->GetClassLoader()->m_AvailableTypesLock,
fCheckUnderLock);
}
/* static */
TypeHandle ClassLoader::LookupTypeHandleForTypeKey(TypeKey *pKey)
{
WRAPPER_NO_CONTRACT;
SUPPORTS_DAC;
// Make an initial lookup without taking any locks.
TypeHandle th = LookupTypeHandleForTypeKeyInner(pKey, FALSE);
// A non-null TypeHandle for the above lookup indicates success
// A null TypeHandle only indicates "well, it might have been there,
// try again with a lock". This kind of negative result will
// only happen while accessing the underlying EETypeHashTable
// during a resize, i.e. very rarely. In such a case, we just
// perform the lookup again, but indicate that appropriate locks
// should be taken.
if (th.IsNull())
{
th = LookupTypeHandleForTypeKeyInner(pKey, TRUE);
}
return th;
}
/* static */
TypeHandle ClassLoader::LookupTypeHandleForTypeKeyInner(TypeKey *pKey, BOOL fCheckUnderLock)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
FORBID_FAULT;
PRECONDITION(CheckPointer(pKey));
MODE_ANY;
SUPPORTS_DAC;
}
CONTRACTL_END
// Check if it's the typical instantiation. In this case it's not stored in the same
// way as other constructed types.
if (!pKey->IsConstructed() ||
(pKey->GetKind() == ELEMENT_TYPE_CLASS && ClassLoader::IsTypicalInstantiation(pKey->GetModule(),
pKey->GetTypeToken(),
pKey->GetInstantiation())))
{
return TypeHandle(pKey->GetModule()->LookupTypeDef(pKey->GetTypeToken()));
}
#ifdef FEATURE_PREJIT
// The following ways of finding a constructed type should be mutually exclusive!
// 1. Look for a zapped item in the PreferredZapModule
// 2. Look for a unzapped (JIT-loaded) item in the LoaderModule
TypeHandle thPZM = LookupInPreferredZapModule(pKey, fCheckUnderLock);
if (!thPZM.IsNull())
{
return thPZM;
}
#endif // FEATURE_PREJIT
// Next look in the loader module. This is where the item is guaranteed to live if
// it is not latched from an NGEN image, i.e. if it is JIT loaded.
// If the thing is not NGEN'd then this may
// be different to pPreferredZapModule. If they are the same then
// we can reuse the results of the lookup above.
TypeHandle thLM = LookupInLoaderModule(pKey, fCheckUnderLock);
if (!thLM.IsNull())
{
return thLM;
}
return TypeHandle();
}
//---------------------------------------------------------------------------
// ClassLoader::TryFindDynLinkZapType
//
// This is a major routine in the process of finding and using
// zapped generic instantiations (excluding those which were zapped into
// their PreferredZapModule).
//
// DynLinkZapItems are generic instantiations that may have been NGEN'd
// into more than one NGEN image (e.g. the code and TypeHandle for
// List<int> may in principle be zapped into several client images - it is theoretically
// an NGEN policy decision about how often this done, though for now we
// have hard-baked a strategy).
//
// There are lots of potential problems with this kind of duplication
// and the way we get around nearly all of these is to make sure that
// we only use one at most one "unique" copy of each item
// at runtime. Thus we keep tables in the SharedDomain and the AppDomain indicating
// which unique items have been chosen. If an item is "loaded" by this technique
// then it will not be loaded by any other technique.
//
// Note generic instantiations may have the good fortune to be zapped
// into the "PreferredZapModule". If so we can eager bind to them and
// they will not be considered to be DynLinkZapItems. We always
// look in the PreferredZapModule first, and we do not add an entry to the
// DynLinkZapItems table for this case.
//
// Zap references to DynLinkZapItems are always via encoded fixups, except
// for a few intra-module references when one DynLinkZapItem is "TightlyBound"
// to another, e.g. an canonical DynLinkZap MethodTable may directly refer to
// its EEClass - this is because we know that if one is used at runtime then the
// other will also be. These items should be thought of as together constituting
// one DynLinkedZapItem.
//
// This function section searches for a copy of the instantiation in various NGEN images.
// This is effectively like doing a load since we are choosing which copy of the instantiation
// to use from among a number of potential candidates. We have to have the loading lock
// for this item before we can do this to make sure no other threads choose a
// different copy of the instantiation, and that no other threads are JIT-loading
// the instantiation.
#ifndef DACCESS_COMPILE
#ifdef FEATURE_FULL_NGEN
/* static */
TypeHandle ClassLoader::TryFindDynLinkZapType(TypeKey *pKey)
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
INJECT_FAULT(COMPlusThrowOM());
PRECONDITION(CheckPointer(pKey));
PRECONDITION(pKey->IsConstructed());
MODE_ANY;
}
CONTRACTL_END;
// For the introspection-only case, we can skip this step as introspection assemblies
// do not use NGEN images.
if (pKey->IsIntrospectionOnly())
return TypeHandle();
// Never use dyn link zap items during ngen time. We will independently decide later
// whether we want to store the item into ngen image or not.
// Note that it is not good idea to make decisions based on the list of depencies here
// since their list may not be fully populated yet.
if (IsCompilationProcess())
return TypeHandle();
TypeHandle th = TypeHandle();
#ifndef CROSSGEN_COMPILE
// We need to know which domain the item must live in (DomainNeutral or AppDomain)
// Note we can't use the domain from GetLoaderModule()->GetDomain() because at NGEN
// time this may not be accurate (we may be deliberately duplicating a domain-neutral
// instantiation into a domain-specific image, in the sense that the LoaderModule
// returned by ComputeLoaderModule may be the current module being
// NGEN'd)....
BaseDomain * pRequiredDomain = BaseDomain::ComputeBaseDomain(pKey);
// Next look in each ngen'ed image in turn
// Searching the shared domain and the app domain are slightly different.
if (pRequiredDomain->IsSharedDomain())
{
// This switch to cooperative mode makes the iteration below thread safe. It ensures that the underlying
// async HashMap storage is not going to disapper while we are iterating it. Other uses of SharedAssemblyIterator
// have same problem, but I have fixed just this one as targeted ask mode fix.
GCX_COOP();
// Searching for SharedDomain instantiation involves searching all shared assemblies....
// Note we may choose to use an instantiation from an assembly that is from an NGEN
// image that is not logically speaking part of the currently running AppDomain. This
// tkaes advantage of the fact that at the moment SharedDomain NGEN images are never unloaded.
// Thus SharedDomain NGEN images effectively contribute all their instantiations to all
// AppDomains.
//
// <NOTE> This will have to change if we ever start unloading NGEN images from the SharedDomain </NOTE>
SharedDomain::SharedAssemblyIterator assem;
while (th.IsNull() && assem.Next())
{
ModuleIterator i = assem.GetAssembly()->IterateModules();
while (i.Next())
{
Module *pModule = i.GetModule();
if (!pModule->HasNativeImage())
continue;
// If the module hasn't reached FILE_LOADED in some domain, it cannot provide candidate instantiations
if (!pModule->IsReadyForTypeLoad())
continue;
TypeHandle thFromZapModule = pModule->GetAvailableParamTypes()->GetValue(pKey);
// Check that the item really is a zapped item, i.e. that it has not been JIT-loaded to the module
if (thFromZapModule.IsNull() || !thFromZapModule.IsZapped())
continue;
th = thFromZapModule;
}
}
}
else
{
// Searching for domain specific instantiation involves searching all
// domain-specific assemblies in the relevant AppDomain....
AppDomain * pDomain = pRequiredDomain->AsAppDomain();
_ASSERTE(!(pKey->IsIntrospectionOnly()));
AppDomain::AssemblyIterator assemblyIterator = pDomain->IterateAssembliesEx(
(AssemblyIterationFlags)(kIncludeLoaded | kIncludeExecution));
CollectibleAssemblyHolder<DomainAssembly *> pDomainAssembly;
while (th.IsNull() && assemblyIterator.Next(pDomainAssembly.This()))
{
CollectibleAssemblyHolder<Assembly *> pAssembly = pDomainAssembly->GetLoadedAssembly();
// Make sure the domain of the NGEN'd images associated with the assembly matches...
if (pAssembly->GetDomain() == pRequiredDomain)
{
DomainAssembly::ModuleIterator i = pDomainAssembly->IterateModules(kModIterIncludeLoaded);
while (th.IsNull() && i.Next())
{
Module * pModule = i.GetLoadedModule();
if (!pModule->HasNativeImage())
continue;
// If the module hasn't reached FILE_LOADED in some domain, it cannot provide candidate instantiations
if (!pModule->IsReadyForTypeLoad())
continue;
TypeHandle thFromZapModule = pModule->GetAvailableParamTypes()->GetValue(pKey);
// Check that the item really is a zapped item
if (thFromZapModule.IsNull() || !thFromZapModule.IsZapped())
continue;
th = thFromZapModule;
}
}
}
}
#endif // CROSSGEN_COMPILE
return th;
}
#endif // FEATURE_FULL_NGEN
#endif // !DACCESS_COMPILE
// FindClassModuleThrowing discovers which module the type you're looking for is in and loads the Module if necessary.
// Basically, it iterates through all of the assembly's modules until a name match is found in a module's
// AvailableClassHashTable.
//
// The possible outcomes are:
//
// - Function returns TRUE - class exists and we successfully found/created the containing Module. See below
// for how to deconstruct the results.
// - Function returns FALSE - class affirmatively NOT found (that means it doesn't exist as a regular type although
// it could also be a parameterized type)
// - Function throws - OOM or some other reason we couldn't do the job (if it's a case-sensitive search
// and you're looking for already loaded type or you've set the TokenNotToLoad.
// we are guaranteed not to find a reason to throw.)
//
//
// If it succeeds (returns TRUE), one of the following will occur. Check (*pType)->IsNull() to discriminate.
//
// 1. *pType: set to the null TypeHandle()
// *ppModule: set to the owning Module
// *pmdClassToken: set to the typedef
// *pmdFoundExportedType: if this name bound to an ExportedType, this contains the mdtExportedType token (otherwise,
// it's set to mdTokenNil.) You need this because in this case, *pmdClassToken is just
// a best guess and you need to verify it. (The division of labor between this
// and LoadTypeHandle could definitely be better!)
//
// 2. *pType: set to non-null TypeHandle()
// This means someone else had already done this same lookup before you and caused the actual
// TypeHandle to be cached. Since we know that's what you *really* wanted, we'll just forget the
// Module/typedef stuff and give you the actual TypeHandle.
//
//
BOOL ClassLoader::FindClassModuleThrowing(
const NameHandle * pOriginalName,
TypeHandle * pType,
mdToken * pmdClassToken,
Module ** ppModule,
mdToken * pmdFoundExportedType,
HashedTypeEntry * pFoundEntry,
Module * pLookInThisModuleOnly,
Loader::LoadFlag loadFlag)
{
CONTRACTL
{
INSTANCE_CHECK;
if (FORBIDGC_LOADER_USE_ENABLED()) NOTHROW; else THROWS;
if (FORBIDGC_LOADER_USE_ENABLED()) GC_NOTRIGGER; else GC_TRIGGERS;
if (FORBIDGC_LOADER_USE_ENABLED()) FORBID_FAULT; else { INJECT_FAULT(COMPlusThrowOM()); }
PRECONDITION(CheckPointer(pOriginalName));
PRECONDITION(CheckPointer(ppModule));
MODE_ANY;
SUPPORTS_DAC;
}
CONTRACTL_END
NameHandleTable nhTable = nhCaseSensitive; // just to initialize this ...
// Make a copy of the original name which we can modify (to lowercase)
NameHandle localName = *pOriginalName;
NameHandle * pName = &localName;
switch (pName->GetTable())
{
case nhCaseInsensitive:
{
#ifndef DACCESS_COMPILE
// GC-type users should only be loading types through tokens.
#ifdef _DEBUG_IMPL
_ASSERTE(!FORBIDGC_LOADER_USE_ENABLED());
#endif
// Use the case insensitive table
nhTable = nhCaseInsensitive;
// Create a low case version of the namespace and name
LPUTF8 pszLowerNameSpace = NULL;
LPUTF8 pszLowerClassName = NULL;
int allocLen;
if (pName->GetNameSpace())
{
allocLen = InternalCasingHelper::InvariantToLower(
NULL,
0,
pName->GetNameSpace());
if (allocLen == 0)
{
return FALSE;
}
pszLowerNameSpace = (LPUTF8)_alloca(allocLen);
if (allocLen == 1)
{
*pszLowerNameSpace = '\0';
}
else if (!InternalCasingHelper::InvariantToLower(
pszLowerNameSpace,
allocLen,
pName->GetNameSpace()))
{
return FALSE;
}
}
_ASSERTE(pName->GetName() != NULL);
allocLen = InternalCasingHelper::InvariantToLower(NULL, 0, pName->GetName());
if (allocLen == 0)
{
return FALSE;
}
pszLowerClassName = (LPUTF8)_alloca(allocLen);
if (!InternalCasingHelper::InvariantToLower(
pszLowerClassName,
allocLen,
pName->GetName()))
{
return FALSE;
}
// Substitute the lower case version of the name.
// The field are will be released when we leave this scope
pName->SetName(pszLowerNameSpace, pszLowerClassName);
break;
#else
DacNotImpl();
break;
#endif // #ifndef DACCESS_COMPILE
}
case nhCaseSensitive:
nhTable = nhCaseSensitive;
break;
}
// Remember if there are any unhashed modules. We must do this before
// the actual look to avoid a race condition with other threads doing lookups.
#ifdef LOGGING
BOOL incomplete = (m_cUnhashedModules > 0);
#endif
HashDatum Data;
EEClassHashTable * pTable = NULL;
HashedTypeEntry foundEntry;
BOOL needsToBuildHashtable;
GetClassValue(nhTable, pName, &Data, &pTable, pLookInThisModuleOnly, &foundEntry, loadFlag, needsToBuildHashtable);
// In the case of R2R modules, the search is only performed in the hashtable saved in the
// R2R image, and this is why we return (whether we found a valid typedef token or not).
// Note: case insensitive searches are not used/supported in R2R images.
if (foundEntry.GetEntryType() == HashedTypeEntry::EntryType::IsHashedTokenEntry)
{
*pType = TypeHandle();
HashedTypeEntry::TokenTypeEntry tokenAndModulePair = foundEntry.GetTokenBasedEntryValue();
switch (TypeFromToken(tokenAndModulePair.m_TypeToken))
{
case mdtTypeDef:
*pmdClassToken = tokenAndModulePair.m_TypeToken;
*pmdFoundExportedType = mdTokenNil;
break;
case mdtExportedType:
*pmdClassToken = mdTokenNil;
*pmdFoundExportedType = tokenAndModulePair.m_TypeToken;
break;
default:
_ASSERT(false);
return FALSE;
}
*ppModule = tokenAndModulePair.m_pModule;
if (pFoundEntry != NULL)
*pFoundEntry = foundEntry;
return TRUE;
}
EEClassHashEntry_t * pBucket = foundEntry.GetClassHashBasedEntryValue();
if (pBucket == NULL && needsToBuildHashtable)
{
AvailableClasses_LockHolder lh(this);
// Try again with the lock. This will protect against another thread reallocating
// the hash table underneath us
GetClassValue(nhTable, pName, &Data, &pTable, pLookInThisModuleOnly, &foundEntry, loadFlag, needsToBuildHashtable);
pBucket = foundEntry.GetClassHashBasedEntryValue();
#ifndef DACCESS_COMPILE
if ((pBucket == NULL) && (m_cUnhashedModules > 0))
{
_ASSERT(needsToBuildHashtable);
if (nhTable == nhCaseInsensitive)
{
LazyPopulateCaseInsensitiveHashTables();
}
else
{
// Note: This codepath is only valid for R2R scenarios
LazyPopulateCaseSensitiveHashTables();
}
// Try yet again with the new classes added
GetClassValue(nhTable, pName, &Data, &pTable, pLookInThisModuleOnly, &foundEntry, loadFlag, needsToBuildHashtable);
pBucket = foundEntry.GetClassHashBasedEntryValue();
_ASSERT(!needsToBuildHashtable);
}
#endif
}
if (pBucket == NULL)
{
#if defined(_DEBUG_IMPL) && !defined(DACCESS_COMPILE)
LPCUTF8 szName = pName->GetName();
if (szName == NULL)
szName = "<UNKNOWN>";
LOG((LF_CLASSLOADER, LL_INFO10, "Failed to find type \"%s\", assembly \"%ws\" in hash table. Incomplete = %d\n",
szName, GetAssembly()->GetDebugName(), incomplete));
#endif
return FALSE;
}
if (pName->GetTable() == nhCaseInsensitive)
{
_ASSERTE(Data);
pBucket = PTR_EEClassHashEntry(Data);
Data = pBucket->GetData();
}
// Lower bit is a discriminator. If the lower bit is NOT SET, it means we have
// a TypeHandle. Otherwise, we have a Module/CL.
if ((dac_cast<TADDR>(Data) & EECLASSHASH_TYPEHANDLE_DISCR) == 0)
{
TypeHandle t = TypeHandle::FromPtr(Data);
_ASSERTE(!t.IsNull());
*pType = t;
if (pFoundEntry != NULL)
{
pFoundEntry->SetClassHashBasedEntryValue(pBucket);
}
return TRUE;
}
// We have a Module/CL
if (!pTable->UncompressModuleAndClassDef(Data,
loadFlag,
ppModule,
pmdClassToken,
pmdFoundExportedType))
{
_ASSERTE(loadFlag != Loader::Load);
return FALSE;
}
*pType = TypeHandle();
if (pFoundEntry != NULL)
{
pFoundEntry->SetClassHashBasedEntryValue(pBucket);
}
return TRUE;
} // ClassLoader::FindClassModuleThrowing
#ifndef DACCESS_COMPILE
// Returns true if the full name (namespace+name) of pName matches that
// of typeHnd; otherwise false. Because this is nothrow, it will default
// to false for all exceptions (such as OOM).
bool CompareNameHandleWithTypeHandleNoThrow(
const NameHandle * pName,
TypeHandle typeHnd)
{
bool fRet = false;
EX_TRY
{
// This block is specifically designed to handle transient faults such
// as OOM exceptions.
CONTRACT_VIOLATION(FaultViolation | ThrowsViolation);
StackSString ssBuiltName;
ns::MakePath(ssBuiltName,
StackSString(SString::Utf8, pName->GetNameSpace()),
StackSString(SString::Utf8, pName->GetName()));
StackSString ssName;
typeHnd.GetName(ssName);
fRet = ssName.Equals(ssBuiltName) == TRUE;
}
EX_CATCH
{
// Technically, the above operations should never result in a non-OOM
// exception, but we'll put the rethrow line in there just in case.
CONSISTENCY_CHECK(!GET_EXCEPTION()->IsTerminal());
RethrowTerminalExceptions;
}
EX_END_CATCH(SwallowAllExceptions);
return fRet;
}
#endif // #ifndef DACCESS_COMPILE
// 1024 seems like a good bet at detecting a loop in the type forwarding.
static const UINT32 const_cMaxTypeForwardingChainSize = 1024;
// Does not throw an exception if the type was not found. Use LoadTypeHandleThrowIfFailed()
// instead if you need that.
//
// Returns:
// pName->m_pBucket
// Will be set to the 'final' TypeDef bucket if pName->GetTokenType() is mdtBaseType.
//
TypeHandle
ClassLoader::LoadTypeHandleThrowing(
NameHandle * pName,
ClassLoadLevel level,
Module * pLookInThisModuleOnly /*=NULL*/)
{
CONTRACT(TypeHandle) {
INSTANCE_CHECK;
if (FORBIDGC_LOADER_USE_ENABLED()) NOTHROW; else THROWS;
if (FORBIDGC_LOADER_USE_ENABLED()) GC_NOTRIGGER; else GC_TRIGGERS;
if (FORBIDGC_LOADER_USE_ENABLED()) FORBID_FAULT; else { INJECT_FAULT(COMPlusThrowOM()); }
DAC_LOADS_TYPE(level, !pName->OKToLoad());
PRECONDITION(level > CLASS_LOAD_BEGIN && level <= CLASS_LOADED);
PRECONDITION(CheckPointer(pName));
POSTCONDITION(RETVAL.IsNull() || RETVAL.GetLoadLevel() >= level);
MODE_ANY;
SUPPORTS_DAC;
} CONTRACT_END
TypeHandle typeHnd;
INTERIOR_STACK_PROBE_NOTHROW_CHECK_THREAD(RETURN_FROM_INTERIOR_PROBE(TypeHandle()));
Module * pFoundModule = NULL;
mdToken FoundCl;
HashedTypeEntry foundEntry;
mdExportedType FoundExportedType = mdTokenNil;
UINT32 cLoopIterations = 0;
ClassLoader * pClsLdr = this;
while (true)
{
if (cLoopIterations++ >= const_cMaxTypeForwardingChainSize)
{ // If we've looped too many times due to type forwarding, return null TypeHandle
// Would prefer to return a format exception, but the original behaviour
// was to detect a stack overflow possibility and return a null, and
// so we need to maintain this.
typeHnd = TypeHandle();
break;
}
// Look outside the lock (though we're actually still a long way from the
// lock at this point...). This may discover that the type is actually
// defined in another module...
if (!pClsLdr->FindClassModuleThrowing(
pName,
&typeHnd,
&FoundCl,
&pFoundModule,
&FoundExportedType,
&foundEntry,
pLookInThisModuleOnly,
pName->OKToLoad() ? Loader::Load
: Loader::DontLoad))
{ // Didn't find anything, no point looping indefinitely
break;
}
_ASSERTE(!foundEntry.IsNull());
if (pName->GetTypeToken() == mdtBaseType)
{ // We should return the found bucket in the pName
pName->SetBucket(foundEntry);
}
if (!typeHnd.IsNull())
{ // Found the cached value, or a constructedtype
if (typeHnd.GetLoadLevel() < level)
{
typeHnd = pClsLdr->LoadTypeDefThrowing(
typeHnd.GetModule(),
typeHnd.GetCl(),
ClassLoader::ReturnNullIfNotFound,
ClassLoader::PermitUninstDefOrRef, // When loading by name we always permit naked type defs/refs
pName->GetTokenNotToLoad(),
level);
}
break;
}
// Found a cl, pModule pair
// If the found module's class loader is not the same as the current class loader,
// then this is a forwarded type and we want to do something else (see
// code:#LoadTypeHandle_TypeForwarded).
if (pFoundModule->GetClassLoader() == pClsLdr)
{
BOOL fTrustTD = TRUE;
#ifndef DACCESS_COMPILE
CONTRACT_VIOLATION(ThrowsViolation);
BOOL fVerifyTD = (FoundExportedType != mdTokenNil) &&
!pClsLdr->GetAssembly()->GetSecurityDescriptor()->IsFullyTrusted();
// If this is an exported type with a mdTokenNil class token, then then
// exported type did not give a typedefID hint. We won't be able to trust the typedef
// here.
if ((FoundExportedType != mdTokenNil) && (FoundCl == mdTokenNil))
{
fVerifyTD = TRUE;
fTrustTD = FALSE;
}
// verify that FoundCl is a valid token for pFoundModule, because
// it may be just the hint saved in an ExportedType in another scope
else if (fVerifyTD)
{
fTrustTD = pFoundModule->GetMDImport()->IsValidToken(FoundCl);
}
#endif // #ifndef DACCESS_COMPILE
if (fTrustTD)
{
typeHnd = pClsLdr->LoadTypeDefThrowing(
pFoundModule,
FoundCl,
ClassLoader::ReturnNullIfNotFound,
ClassLoader::PermitUninstDefOrRef, // when loading by name we always permit naked type defs/refs
pName->GetTokenNotToLoad(),
level);
}
#ifndef DACCESS_COMPILE
// If we used a TypeDef saved in a ExportedType, if we didn't verify
// the hash for this internal module, don't trust the TD value.
if (fVerifyTD)
{
if (typeHnd.IsNull() || !CompareNameHandleWithTypeHandleNoThrow(pName, typeHnd))
{
if (SUCCEEDED(pClsLdr->FindTypeDefByExportedType(
pClsLdr->GetAssembly()->GetManifestImport(),
FoundExportedType,
pFoundModule->GetMDImport(),
&FoundCl)))
{
typeHnd = pClsLdr->LoadTypeDefThrowing(
pFoundModule,
FoundCl,
ClassLoader::ReturnNullIfNotFound,
ClassLoader::PermitUninstDefOrRef,
pName->GetTokenNotToLoad(),
level);
}
else
{
typeHnd = TypeHandle();
}
}
}
#endif // #ifndef DACCESS_COMPILE
break;
}
else
{ //#LoadTypeHandle_TypeForwarded
// pName is a host instance so it's okay to set fields in it in a DAC build
HashedTypeEntry& bucket = pName->GetBucket();
// Reset pName's bucket entry
if (bucket.GetEntryType() == HashedTypeEntry::IsHashedClassEntry && bucket.GetClassHashBasedEntryValue()->GetEncloser())
{
// We will be searching for the type name again, so set the nesting/context type to the
// encloser of just found type
pName->SetBucket(HashedTypeEntry().SetClassHashBasedEntryValue(bucket.GetClassHashBasedEntryValue()->GetEncloser()));
}
else
{
pName->SetBucket(HashedTypeEntry());
}
// Update the class loader for the new module/token pair.
pClsLdr = pFoundModule->GetClassLoader();
pLookInThisModuleOnly = NULL;
}
#ifndef DACCESS_COMPILE
// Replace AvailableClasses Module entry with found TypeHandle
if (!typeHnd.IsNull() &&
typeHnd.IsRestored() &&
foundEntry.GetEntryType() == HashedTypeEntry::EntryType::IsHashedClassEntry &&
(foundEntry.GetClassHashBasedEntryValue() != NULL) &&
(foundEntry.GetClassHashBasedEntryValue()->GetData() != typeHnd.AsPtr()))
{
foundEntry.GetClassHashBasedEntryValue()->SetData(typeHnd.AsPtr());
}
#endif // !DACCESS_COMPILE
}
END_INTERIOR_STACK_PROBE;
RETURN typeHnd;
} // ClassLoader::LoadTypeHandleThrowing
/* static */
TypeHandle ClassLoader::LoadPointerOrByrefTypeThrowing(CorElementType typ,
TypeHandle baseType,
LoadTypesFlag fLoadTypes/*=LoadTypes*/,
ClassLoadLevel level/*=CLASS_LOADED*/)
{
CONTRACT(TypeHandle)
{
if (FORBIDGC_LOADER_USE_ENABLED()) NOTHROW; else THROWS;
if (FORBIDGC_LOADER_USE_ENABLED()) GC_NOTRIGGER; else GC_TRIGGERS;
if (FORBIDGC_LOADER_USE_ENABLED()) FORBID_FAULT; else { INJECT_FAULT(COMPlusThrowOM()); }
if (FORBIDGC_LOADER_USE_ENABLED() || fLoadTypes != LoadTypes) { LOADS_TYPE(CLASS_LOAD_BEGIN); } else { LOADS_TYPE(level); }
MODE_ANY;
PRECONDITION(CheckPointer(baseType));
PRECONDITION(typ == ELEMENT_TYPE_BYREF || typ == ELEMENT_TYPE_PTR);
PRECONDITION(level > CLASS_LOAD_BEGIN && level <= CLASS_LOADED);
POSTCONDITION(CheckPointer(RETVAL, ((fLoadTypes == LoadTypes) ? NULL_NOT_OK : NULL_OK)));
SUPPORTS_DAC;
}
CONTRACT_END
TypeKey key(typ, baseType);
RETURN(LoadConstructedTypeThrowing(&key, fLoadTypes, level));
}
/* static */
TypeHandle ClassLoader::LoadNativeValueTypeThrowing(TypeHandle baseType,
LoadTypesFlag fLoadTypes/*=LoadTypes*/,
ClassLoadLevel level/*=CLASS_LOADED*/)
{
CONTRACT(TypeHandle)
{
if (FORBIDGC_LOADER_USE_ENABLED()) NOTHROW; else THROWS;
if (FORBIDGC_LOADER_USE_ENABLED()) GC_NOTRIGGER; else GC_TRIGGERS;
if (FORBIDGC_LOADER_USE_ENABLED()) FORBID_FAULT; else { INJECT_FAULT(COMPlusThrowOM()); }
MODE_ANY;
PRECONDITION(CheckPointer(baseType));
PRECONDITION(baseType.AsMethodTable()->IsValueType());
PRECONDITION(level > CLASS_LOAD_BEGIN && level <= CLASS_LOADED);
POSTCONDITION(CheckPointer(RETVAL, ((fLoadTypes == LoadTypes) ? NULL_NOT_OK : NULL_OK)));
}
CONTRACT_END
TypeKey key(ELEMENT_TYPE_VALUETYPE, baseType);
RETURN(LoadConstructedTypeThrowing(&key, fLoadTypes, level));
}
/* static */
TypeHandle ClassLoader::LoadFnptrTypeThrowing(BYTE callConv,
DWORD ntypars,
TypeHandle* inst,
LoadTypesFlag fLoadTypes/*=LoadTypes*/,
ClassLoadLevel level/*=CLASS_LOADED*/)
{
CONTRACT(TypeHandle)
{
if (FORBIDGC_LOADER_USE_ENABLED()) NOTHROW; else THROWS;
if (FORBIDGC_LOADER_USE_ENABLED()) GC_NOTRIGGER; else GC_TRIGGERS;
if (FORBIDGC_LOADER_USE_ENABLED()) FORBID_FAULT; else { INJECT_FAULT(COMPlusThrowOM()); }
if (FORBIDGC_LOADER_USE_ENABLED() || fLoadTypes != LoadTypes) { LOADS_TYPE(CLASS_LOAD_BEGIN); } else { LOADS_TYPE(level); }
PRECONDITION(level > CLASS_LOAD_BEGIN && level <= CLASS_LOADED);
POSTCONDITION(CheckPointer(RETVAL, ((fLoadTypes == LoadTypes) ? NULL_NOT_OK : NULL_OK)));
MODE_ANY;
SUPPORTS_DAC;
}
CONTRACT_END
TypeKey key(callConv, ntypars, inst);
RETURN(LoadConstructedTypeThrowing(&key, fLoadTypes, level));
}
// Find an instantiation of a generic type if it has already been created.
// If typeDef is not a generic type or is already instantiated then throw an exception.
// If its arity does not match ntypars then throw an exception.
// Value will be non-null if we're loading types.
/* static */
TypeHandle ClassLoader::LoadGenericInstantiationThrowing(Module *pModule,
mdTypeDef typeDef,
Instantiation inst,
LoadTypesFlag fLoadTypes/*=LoadTypes*/,
ClassLoadLevel level/*=CLASS_LOADED*/,
const InstantiationContext *pInstContext/*=NULL*/,
BOOL fFromNativeImage /*=FALSE*/)
{
// This can be called in FORBIDGC_LOADER_USE mode by the debugger to find
// a particular generic type instance that is already loaded.
CONTRACT(TypeHandle)
{
if (FORBIDGC_LOADER_USE_ENABLED()) NOTHROW; else THROWS;
if (FORBIDGC_LOADER_USE_ENABLED()) GC_NOTRIGGER; else GC_TRIGGERS;
if (FORBIDGC_LOADER_USE_ENABLED() || fLoadTypes != LoadTypes) { LOADS_TYPE(CLASS_LOAD_BEGIN); } else { LOADS_TYPE(level); }
PRECONDITION(CheckPointer(pModule));
MODE_ANY;
PRECONDITION(level > CLASS_LOAD_BEGIN && level <= CLASS_LOADED);
PRECONDITION(CheckPointer(pInstContext, NULL_OK));
POSTCONDITION(CheckPointer(RETVAL, ((fLoadTypes == LoadTypes) ? NULL_NOT_OK : NULL_OK)));
SUPPORTS_DAC;
}
CONTRACT_END
// Essentially all checks to determine if a generic instantiation of a type
// is well-formed go in this method, i.e. this is the
// "choke" point through which all attempts
// to create an instantiation flow. There is a similar choke point for generic
// methods in genmeth.cpp.
if (inst.IsEmpty() || ClassLoader::IsTypicalInstantiation(pModule, typeDef, inst))
{
TypeHandle th = LoadTypeDefThrowing(pModule, typeDef,
ThrowIfNotFound,
PermitUninstDefOrRef,
fLoadTypes == DontLoadTypes ? tdAllTypes : tdNoTypes,
level,
fFromNativeImage ? NULL : &inst);
_ASSERTE(th.GetNumGenericArgs() == inst.GetNumArgs());
RETURN th;
}
if (!fFromNativeImage)
{
TypeHandle th = ClassLoader::LoadTypeDefThrowing(pModule, typeDef,
ThrowIfNotFound,
PermitUninstDefOrRef,
fLoadTypes == DontLoadTypes ? tdAllTypes : tdNoTypes,
level,
fFromNativeImage ? NULL : &inst);
_ASSERTE(th.GetNumGenericArgs() == inst.GetNumArgs());
}
TypeKey key(pModule, typeDef, inst);
#ifndef DACCESS_COMPILE
// To avoid loading useless shared instantiations, normalize shared instantiations to the canonical form
// (e.g. Dictionary<String,_Canon> -> Dictionary<_Canon,_Canon>)
// The denormalized shared instantiations should be needed only during JITing, so it is fine to skip this
// for DACCESS_COMPILE.
if (TypeHandle::IsCanonicalSubtypeInstantiation(inst) && !IsCanonicalGenericInstantiation(inst))
{
RETURN(ClassLoader::LoadCanonicalGenericInstantiation(&key, fLoadTypes, level));
}
#endif
RETURN(LoadConstructedTypeThrowing(&key, fLoadTypes, level, pInstContext));
}
// For non-nested classes, gets the ExportedType name and finds the corresponding
// TypeDef.
// For nested classes, gets the name of the ExportedType and its encloser.
// Recursively gets and keeps the name for each encloser until we have the top
// level one. Gets the TypeDef token for that. Then, returns from the
// recursion, using the last found TypeDef token in order to find the
// next nested level down TypeDef token. Finally, returns the TypeDef
// token for the type we care about.
/*static*/
HRESULT ClassLoader::FindTypeDefByExportedType(IMDInternalImport *pCTImport, mdExportedType mdCurrent,
IMDInternalImport *pTDImport, mdTypeDef *mtd)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
FORBID_FAULT;
MODE_ANY;
SUPPORTS_DAC;
}
CONTRACTL_END
mdToken mdImpl;
LPCSTR szcNameSpace;
LPCSTR szcName;
HRESULT hr;
IfFailRet(pCTImport->GetExportedTypeProps(
mdCurrent,
&szcNameSpace,
&szcName,
&mdImpl,
NULL, //binding
NULL)); //flags
if ((TypeFromToken(mdImpl) == mdtExportedType) &&
(mdImpl != mdExportedTypeNil)) {
// mdCurrent is a nested ExportedType
IfFailRet(FindTypeDefByExportedType(pCTImport, mdImpl, pTDImport, mtd));
// Get TypeDef token for this nested type
return pTDImport->FindTypeDef(szcNameSpace, szcName, *mtd, mtd);
}
// Get TypeDef token for this top-level type
return pTDImport->FindTypeDef(szcNameSpace, szcName, mdTokenNil, mtd);
}
#ifndef DACCESS_COMPILE
VOID ClassLoader::CreateCanonicallyCasedKey(LPCUTF8 pszNameSpace, LPCUTF8 pszName, __out LPUTF8 *ppszOutNameSpace, __out LPUTF8 *ppszOutName)
{
CONTRACTL
{
INSTANCE_CHECK;
THROWS;
GC_NOTRIGGER;
INJECT_FAULT(COMPlusThrowOM(););
MODE_ANY;
}
CONTRACTL_END
// We can use the NoThrow versions here because we only call this routine if we're maintaining
// a case-insensitive hash table, and the creation of that table initialized the
// CasingHelper system.
INT32 iNSLength = InternalCasingHelper::InvariantToLowerNoThrow(NULL, 0, pszNameSpace);
if (!iNSLength)
{
COMPlusThrowOM();
}
INT32 iNameLength = InternalCasingHelper::InvariantToLowerNoThrow(NULL, 0, pszName);
if (!iNameLength)
{
COMPlusThrowOM();
}
{
//Calc & allocate path length
//Includes terminating null
S_SIZE_T allocSize = S_SIZE_T(iNSLength) + S_SIZE_T(iNameLength);
if (allocSize.IsOverflow())
{
ThrowHR(COR_E_OVERFLOW);
}
AllocMemHolder<char> pszOutNameSpace (GetAssembly()->GetHighFrequencyHeap()->AllocMem(allocSize));
*ppszOutNameSpace = pszOutNameSpace;
if (iNSLength == 1)
{
**ppszOutNameSpace = '\0';
}
else
{
if (!InternalCasingHelper::InvariantToLowerNoThrow(*ppszOutNameSpace, iNSLength, pszNameSpace))
{
COMPlusThrowOM();
}
}
*ppszOutName = *ppszOutNameSpace + iNSLength;
if (!InternalCasingHelper::InvariantToLowerNoThrow(*ppszOutName, iNameLength, pszName))
{
COMPlusThrowOM();
}
pszOutNameSpace.SuppressRelease();
}
}
#endif // #ifndef DACCESS_COMPILE
//
// Return a class that is already loaded
// Only for type refs and type defs (not type specs)
//
/*static*/
TypeHandle ClassLoader::LookupTypeDefOrRefInModule(Module *pModule, mdToken cl, ClassLoadLevel *pLoadLevel)
{
CONTRACT(TypeHandle)
{
NOTHROW;
GC_NOTRIGGER;
FORBID_FAULT;
MODE_ANY;
PRECONDITION(CheckPointer(pModule));
POSTCONDITION(CheckPointer(RETVAL, NULL_OK));
SUPPORTS_DAC;
}
CONTRACT_END
BAD_FORMAT_NOTHROW_ASSERT((TypeFromToken(cl) == mdtTypeRef ||
TypeFromToken(cl) == mdtTypeDef ||
TypeFromToken(cl) == mdtTypeSpec));
TypeHandle typeHandle;
if (TypeFromToken(cl) == mdtTypeDef)
typeHandle = pModule->LookupTypeDef(cl, pLoadLevel);
else if (TypeFromToken(cl) == mdtTypeRef)
{
typeHandle = pModule->LookupTypeRef(cl);
if (pLoadLevel && !typeHandle.IsNull())
{
*pLoadLevel = typeHandle.GetLoadLevel();
}
}
RETURN(typeHandle);
}
DomainAssembly *ClassLoader::GetDomainAssembly(AppDomain *pDomain/*=NULL*/)
{
WRAPPER_NO_CONTRACT;
return GetAssembly()->GetDomainAssembly(pDomain);
}
#ifndef DACCESS_COMPILE
//
// Free all modules associated with this loader
//
void ClassLoader::FreeModules()
{
CONTRACTL
{
INSTANCE_CHECK;
NOTHROW;
GC_TRIGGERS;
MODE_PREEMPTIVE;
DISABLED(FORBID_FAULT); //Lots of crud to clean up to make this work
}
CONTRACTL_END;
Module *pManifest = NULL;
if (GetAssembly() && (NULL != (pManifest = GetAssembly()->GetManifestModule()))) {
// Unload the manifest last, since it contains the module list in its rid map
ModuleIterator i = GetAssembly()->IterateModules();
while (i.Next()) {
// Have the module free its various tables and some of the EEClass links
if (i.GetModule() != pManifest)
i.GetModule()->Destruct();
}
// Now do the manifest module.
pManifest->Destruct();
}
}
ClassLoader::~ClassLoader()
{
CONTRACTL
{
NOTHROW;
DESTRUCTOR_CHECK;
GC_TRIGGERS;
MODE_PREEMPTIVE;
DISABLED(FORBID_FAULT); //Lots of crud to clean up to make this work
}
CONTRACTL_END
#ifdef _DEBUG
// Do not walk m_pUnresolvedClassHash at destruct time as it is loaderheap allocated memory
// and may already have been deallocated via an AllocMemTracker.
m_pUnresolvedClassHash = (PendingTypeLoadTable*)(UINT_PTR)0xcccccccc;
#endif
#ifdef _DEBUG
// LOG((
// LF_CLASSLOADER,
// INFO3,
// "Deleting classloader %x\n"
// " >EEClass data: %10d bytes\n"
// " >Classname hash: %10d bytes\n"
// " >FieldDesc data: %10d bytes\n"
// " >MethodDesc data: %10d bytes\n"
// " >GCInfo: %10d bytes\n"
// " >Interface maps: %10d bytes\n"
// " >MethodTables: %10d bytes\n"
// " >Vtables: %10d bytes\n"
// " >Static fields: %10d bytes\n"
// "# methods: %10d\n"
// "# field descs: %10d\n"
// "# classes: %10d\n"
// "# dup intf slots: %10d\n"
// "# array classrefs: %10d\n"
// "Array class overhead:%10d bytes\n",
// this,
// m_dwEEClassData,
// m_pAvailableClasses->m_dwDebugMemory,
// m_dwFieldDescData,
// m_dwMethodDescData,
// m_dwGCSize,
// m_dwInterfaceMapSize,
// m_dwMethodTableSize,
// m_dwVtableData,
// m_dwStaticFieldData,
// m_dwDebugMethods,
// m_dwDebugFieldDescs,
// m_dwDebugClasses,
// m_dwDebugDuplicateInterfaceSlots,
// ));
#endif
FreeModules();
m_UnresolvedClassLock.Destroy();
m_AvailableClassLock.Destroy();
m_AvailableTypesLock.Destroy();
}
//----------------------------------------------------------------------------
// The constructor should only initialize enough to ensure that the destructor doesn't
// crash. It cannot allocate or do anything that might fail as that would leave
// the ClassLoader undestructable. Any such tasks should be done in ClassLoader::Init().
//----------------------------------------------------------------------------
ClassLoader::ClassLoader(Assembly *pAssembly)
{
CONTRACTL
{
CONSTRUCTOR_CHECK;
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
FORBID_FAULT;
}
CONTRACTL_END
m_pAssembly = pAssembly;
m_pUnresolvedClassHash = NULL;
m_cUnhashedModules = 0;
#ifdef _DEBUG
m_dwDebugMethods = 0;
m_dwDebugFieldDescs = 0;
m_dwDebugClasses = 0;
m_dwDebugDuplicateInterfaceSlots = 0;
m_dwGCSize = 0;
m_dwInterfaceMapSize = 0;
m_dwMethodTableSize = 0;
m_dwVtableData = 0;
m_dwStaticFieldData = 0;
m_dwFieldDescData = 0;
m_dwMethodDescData = 0;
m_dwEEClassData = 0;
#endif
}
//----------------------------------------------------------------------------
// This function completes the initialization of the ClassLoader. It can
// assume the constructor is run and that the function is entered with
// ClassLoader in a safely destructable state. This function can throw
// but whether it throws or succeeds, it must leave the ClassLoader in a safely
// destructable state.
//----------------------------------------------------------------------------
VOID ClassLoader::Init(AllocMemTracker *pamTracker)
{
STANDARD_VM_CONTRACT;
m_pUnresolvedClassHash = PendingTypeLoadTable::Create(GetAssembly()->GetLowFrequencyHeap(),
UNRESOLVED_CLASS_HASH_BUCKETS,
pamTracker);
m_UnresolvedClassLock.Init(CrstUnresolvedClassLock);
// This lock is taken within the classloader whenever we have to enter a
// type in one of the modules governed by the loader.
// The process of creating these types may be reentrant. The ordering has
// not yet been sorted out, and when we sort it out we should also modify the
// ordering for m_AvailableTypesLock in BaseDomain.
m_AvailableClassLock.Init(
CrstAvailableClass,
CRST_REENTRANCY);
// This lock is taken within the classloader whenever we have to insert a new param. type into the table
// This lock also needs to be taken for a read operation in a GC_NOTRIGGER scope, thus the ANYMODE flag.
m_AvailableTypesLock.Init(
CrstAvailableParamTypes,
(CrstFlags)(CRST_UNSAFE_ANYMODE | CRST_DEBUGGER_THREAD));
#ifdef _DEBUG
CorTypeInfo::CheckConsistency();
#endif
}
#endif // #ifndef DACCESS_COMPILE
/*static*/
TypeHandle ClassLoader::LoadTypeDefOrRefOrSpecThrowing(Module *pModule,
mdToken typeDefOrRefOrSpec,
const SigTypeContext *pTypeContext,
NotFoundAction fNotFoundAction /* = ThrowIfNotFound */ ,
PermitUninstantiatedFlag fUninstantiated /* = FailIfUninstDefOrRef */,
LoadTypesFlag fLoadTypes/*=LoadTypes*/ ,
ClassLoadLevel level /* = CLASS_LOADED */,
BOOL dropGenericArgumentLevel /* = FALSE */,
const Substitution *pSubst)
{
CONTRACT(TypeHandle)
{
if (FORBIDGC_LOADER_USE_ENABLED()) NOTHROW; else THROWS;
if (FORBIDGC_LOADER_USE_ENABLED()) GC_NOTRIGGER; else GC_TRIGGERS;
MODE_ANY;
if (FORBIDGC_LOADER_USE_ENABLED()) FORBID_FAULT; else { INJECT_FAULT(COMPlusThrowOM()); }
if (FORBIDGC_LOADER_USE_ENABLED() || fLoadTypes != LoadTypes) { LOADS_TYPE(CLASS_LOAD_BEGIN); } else { LOADS_TYPE(level); }
PRECONDITION(CheckPointer(pModule));
PRECONDITION(level > CLASS_LOAD_BEGIN && level <= CLASS_LOADED);
PRECONDITION(FORBIDGC_LOADER_USE_ENABLED() || GetAppDomain()->CheckCanLoadTypes(pModule->GetAssembly()));
POSTCONDITION(CheckPointer(RETVAL, (fNotFoundAction == ThrowIfNotFound)? NULL_NOT_OK : NULL_OK));
}
CONTRACT_END
if (TypeFromToken(typeDefOrRefOrSpec) == mdtTypeSpec)
{
ULONG cSig;
PCCOR_SIGNATURE pSig;
IMDInternalImport *pInternalImport = pModule->GetMDImport();
if (FAILED(pInternalImport->GetTypeSpecFromToken(typeDefOrRefOrSpec, &pSig, &cSig)))
{
#ifndef DACCESS_COMPILE
if (fNotFoundAction == ThrowIfNotFound)
{
pModule->GetAssembly()->ThrowTypeLoadException(pInternalImport, typeDefOrRefOrSpec, IDS_CLASSLOAD_BADFORMAT);
}
#endif //!DACCESS_COMPILE
RETURN (TypeHandle());
}
SigPointer sigptr(pSig, cSig);
TypeHandle typeHnd = sigptr.GetTypeHandleThrowing(pModule, pTypeContext, fLoadTypes,
level, dropGenericArgumentLevel, pSubst);
#ifndef DACCESS_COMPILE
if ((fNotFoundAction == ThrowIfNotFound) && typeHnd.IsNull())
pModule->GetAssembly()->ThrowTypeLoadException(pInternalImport, typeDefOrRefOrSpec,
IDS_CLASSLOAD_GENERAL);
#endif
RETURN (typeHnd);
}
else
{
RETURN (LoadTypeDefOrRefThrowing(pModule, typeDefOrRefOrSpec,
fNotFoundAction,
fUninstantiated,
((fLoadTypes == LoadTypes) ? tdNoTypes : tdAllTypes),
level));
}
} // ClassLoader::LoadTypeDefOrRefOrSpecThrowing
// Given a token specifying a typeDef, and a module in which to
// interpret that token, find or load the corresponding type handle.
//
//
/*static*/
TypeHandle ClassLoader::LoadTypeDefThrowing(Module *pModule,
mdToken typeDef,
NotFoundAction fNotFoundAction /* = ThrowIfNotFound */ ,
PermitUninstantiatedFlag fUninstantiated /* = FailIfUninstDefOrRef */,
mdToken tokenNotToLoad,
ClassLoadLevel level,
Instantiation * pTargetInstantiation)
{
CONTRACT(TypeHandle)
{
if (FORBIDGC_LOADER_USE_ENABLED()) NOTHROW; else THROWS;
if (FORBIDGC_LOADER_USE_ENABLED()) GC_NOTRIGGER; else GC_TRIGGERS;
MODE_ANY;
if (FORBIDGC_LOADER_USE_ENABLED()) FORBID_FAULT; else { INJECT_FAULT(COMPlusThrowOM()); }
DAC_LOADS_TYPE(level, !NameHandle::OKToLoad(typeDef, tokenNotToLoad));
PRECONDITION(CheckPointer(pModule));
PRECONDITION(level > CLASS_LOAD_BEGIN && level <= CLASS_LOADED);
PRECONDITION(FORBIDGC_LOADER_USE_ENABLED()
|| GetAppDomain()->CheckCanLoadTypes(pModule->GetAssembly()));
POSTCONDITION(CheckPointer(RETVAL, NameHandle::OKToLoad(typeDef, tokenNotToLoad) && (fNotFoundAction == ThrowIfNotFound) ? NULL_NOT_OK : NULL_OK));
POSTCONDITION(RETVAL.IsNull() || RETVAL.GetCl() == typeDef);
SUPPORTS_DAC;
}
CONTRACT_END;
TypeHandle typeHnd;
// First, attempt to find the class if it is already loaded
ClassLoadLevel existingLoadLevel = CLASS_LOAD_BEGIN;
typeHnd = pModule->LookupTypeDef(typeDef, &existingLoadLevel);
if (!typeHnd.IsNull())
{
#ifndef DACCESS_COMPILE
// If the type is loaded, we can do cheap arity verification
if (pTargetInstantiation != NULL && pTargetInstantiation->GetNumArgs() != typeHnd.AsMethodTable()->GetNumGenericArgs())
pModule->GetAssembly()->ThrowTypeLoadException(pModule->GetMDImport(), typeDef, IDS_CLASSLOAD_TYPEWRONGNUMGENERICARGS);
#endif
if (existingLoadLevel >= level)
RETURN(typeHnd);
}
// We don't want to probe on any threads except for those with a managed thread. This function
// can be called from the GC thread etc. so need to control how we probe.
INTERIOR_STACK_PROBE_NOTHROW_CHECK_THREAD(goto Exit;);
IMDInternalImport *pInternalImport = pModule->GetMDImport();
#ifndef DACCESS_COMPILE
if (typeHnd.IsNull() && pTargetInstantiation != NULL)
{
// If the type is not loaded yet, we have to do heavy weight arity verification based on metadata
HENUMInternal hEnumGenericPars;
HRESULT hr = pInternalImport->EnumInit(mdtGenericParam, typeDef, &hEnumGenericPars);
if (FAILED(hr))
pModule->GetAssembly()->ThrowTypeLoadException(pInternalImport, typeDef, IDS_CLASSLOAD_BADFORMAT);
DWORD nGenericClassParams = pInternalImport->EnumGetCount(&hEnumGenericPars);
pInternalImport->EnumClose(&hEnumGenericPars);
if (pTargetInstantiation->GetNumArgs() != nGenericClassParams)
pModule->GetAssembly()->ThrowTypeLoadException(pInternalImport, typeDef, IDS_CLASSLOAD_TYPEWRONGNUMGENERICARGS);
}
#endif
if (IsNilToken(typeDef) || TypeFromToken(typeDef) != mdtTypeDef || !pInternalImport->IsValidToken(typeDef) )
{
LOG((LF_CLASSLOADER, LL_INFO10, "Bogus class token to load: 0x%08x\n", typeDef));
typeHnd = TypeHandle();
}
else
{
// *****************************************************************************
//
// Important invariant:
//
// The rule here is that we never go to LoadTypeHandleForTypeKey if a Find should succeed.
// This is vital, because otherwise a stack crawl will open up opportunities for
// GC. Since operations like setting up a GCFrame will trigger a crawl in stress
// mode, a GC at that point would be disastrous. We can't assert this, because
// of race conditions. (In other words, the type could suddently be find-able
// because another thread loaded it while we were in this method.
// Not found - try to load it unless we are told not to
#ifndef DACCESS_COMPILE
if ( !NameHandle::OKToLoad(typeDef, tokenNotToLoad) )
{
typeHnd = TypeHandle();
}
else
{
// Anybody who puts himself in a FORBIDGC_LOADER state has promised
// to use us only for resolving, not loading. We are now transitioning into
// loading.
#ifdef _DEBUG_IMPL
_ASSERTE(!FORBIDGC_LOADER_USE_ENABLED());
#endif
TRIGGERSGC();
if (pModule->IsReflection())
{
//if (!(pModule->IsIntrospectionOnly()))
{
// Don't try to load types that are not in available table, when this
// is an in-memory module. Raise the type-resolve event instead.
typeHnd = TypeHandle();
// Avoid infinite recursion
if (tokenNotToLoad != tdAllAssemblies)
{
AppDomain* pDomain = SystemDomain::GetCurrentDomain();
LPUTF8 pszFullName;
LPCUTF8 className;
LPCUTF8 nameSpace;
if (FAILED(pInternalImport->GetNameOfTypeDef(typeDef, &className, &nameSpace)))
{
LOG((LF_CLASSLOADER, LL_INFO10, "Bogus TypeDef record while loading: 0x%08x\n", typeDef));
typeHnd = TypeHandle();
}
else
{
MAKE_FULL_PATH_ON_STACK_UTF8(pszFullName,
nameSpace,
className);
GCX_COOP();
ASSEMBLYREF asmRef = NULL;
DomainAssembly *pDomainAssembly = NULL;
GCPROTECT_BEGIN(asmRef);
pDomainAssembly = pDomain->RaiseTypeResolveEventThrowing(
pModule->GetAssembly()->GetDomainAssembly(),
pszFullName, &asmRef);
if (asmRef != NULL)
{
_ASSERTE(pDomainAssembly != NULL);
if (pDomainAssembly->GetAssembly()->GetLoaderAllocator()->IsCollectible())
{
if (!pModule->GetLoaderAllocator()->IsCollectible())
{
LOG((LF_CLASSLOADER, LL_INFO10, "Bad result from TypeResolveEvent while loader TypeDef record: 0x%08x\n", typeDef));
COMPlusThrow(kNotSupportedException, W("NotSupported_CollectibleBoundNonCollectible"));
}
pModule->GetLoaderAllocator()->EnsureReference(pDomainAssembly->GetAssembly()->GetLoaderAllocator());
}
}
GCPROTECT_END();
if (pDomainAssembly != NULL)
{
Assembly *pAssembly = pDomainAssembly->GetAssembly();
NameHandle name(nameSpace, className);
name.SetTypeToken(pModule, typeDef);
name.SetTokenNotToLoad(tdAllAssemblies);
typeHnd = pAssembly->GetLoader()->LoadTypeHandleThrowing(&name, level);
}
}
}
}
}
else
{
TypeKey typeKey(pModule, typeDef);
typeHnd = pModule->GetClassLoader()->LoadTypeHandleForTypeKey(&typeKey,
typeHnd,
level);
}
}
#endif // !DACCESS_COMPILE
}
// If stack guards are disabled, then this label is unreferenced and produces a compile error.
#if defined(FEATURE_STACK_PROBE) && !defined(DACCESS_COMPILE)
Exit:
#endif
#ifndef DACCESS_COMPILE
if ((fUninstantiated == FailIfUninstDefOrRef) && !typeHnd.IsNull() && typeHnd.IsGenericTypeDefinition())
{
typeHnd = TypeHandle();
}
if ((fNotFoundAction == ThrowIfNotFound) && typeHnd.IsNull() && (tokenNotToLoad != tdAllTypes))
{
pModule->GetAssembly()->ThrowTypeLoadException(pModule->GetMDImport(),
typeDef,
IDS_CLASSLOAD_GENERAL);
}
#endif
;
END_INTERIOR_STACK_PROBE;
RETURN(typeHnd);
}
// Given a token specifying a typeDef or typeRef, and a module in
// which to interpret that token, find or load the corresponding type
// handle.
//
/*static*/
TypeHandle ClassLoader::LoadTypeDefOrRefThrowing(Module *pModule,
mdToken typeDefOrRef,
NotFoundAction fNotFoundAction /* = ThrowIfNotFound */ ,
PermitUninstantiatedFlag fUninstantiated /* = FailIfUninstDefOrRef */,
mdToken tokenNotToLoad,
ClassLoadLevel level)
{
CONTRACT(TypeHandle)
{
if (FORBIDGC_LOADER_USE_ENABLED()) NOTHROW; else THROWS;
if (FORBIDGC_LOADER_USE_ENABLED()) GC_NOTRIGGER; else GC_TRIGGERS;
MODE_ANY;
if (FORBIDGC_LOADER_USE_ENABLED()) FORBID_FAULT; else { INJECT_FAULT(COMPlusThrowOM()); }
PRECONDITION(CheckPointer(pModule));
PRECONDITION(level > CLASS_LOAD_BEGIN && level <= CLASS_LOADED);
PRECONDITION(FORBIDGC_LOADER_USE_ENABLED()
|| GetAppDomain()->CheckCanLoadTypes(pModule->GetAssembly()));
POSTCONDITION(CheckPointer(RETVAL, NameHandle::OKToLoad(typeDefOrRef, tokenNotToLoad) && (fNotFoundAction == ThrowIfNotFound) ? NULL_NOT_OK : NULL_OK));
POSTCONDITION(level <= CLASS_LOAD_UNRESTORED || RETVAL.IsNull() || RETVAL.IsRestored());
SUPPORTS_DAC;
}
CONTRACT_END;
// NotFoundAction could be the bizarre 'ThrowButNullV11McppWorkaround',
// which means ThrowIfNotFound EXCEPT if this might be the Everett MCPP
// Nil-token ResolutionScope for value type. In that case, it means
// ReturnNullIfNotFound.
// If we have ThrowButNullV11McppWorkaround, remember that NULL *might*
// be OK if there is no resolution scope, but change the value to
// ThrowIfNotFound.
BOOLEAN bReturnNullOkWhenNoResolutionScope = false;
if (fNotFoundAction == ThrowButNullV11McppWorkaround)
{
bReturnNullOkWhenNoResolutionScope = true;
fNotFoundAction = ThrowIfNotFound;
}
// First, attempt to find the class if it is already loaded
ClassLoadLevel existingLoadLevel = CLASS_LOAD_BEGIN;
TypeHandle typeHnd = LookupTypeDefOrRefInModule(pModule, typeDefOrRef, &existingLoadLevel);
if (!typeHnd.IsNull())
{
if (existingLoadLevel < level)
{
pModule = typeHnd.GetModule();
typeDefOrRef = typeHnd.GetCl();
}
}
if (!typeHnd.IsNull() && existingLoadLevel >= level)
{
// perform the check that it's not an uninstantiated TypeDef/TypeRef
// being used inappropriately.
if (!((fUninstantiated == FailIfUninstDefOrRef) && !typeHnd.IsNull() && typeHnd.IsGenericTypeDefinition()))
{
RETURN(typeHnd);
}
}
else
{
// otherwise try to resolve the TypeRef and/or load the corresponding TypeDef
IMDInternalImport *pInternalImport = pModule->GetMDImport();
mdToken tokType = TypeFromToken(typeDefOrRef);
if (IsNilToken(typeDefOrRef) || ((tokType != mdtTypeDef)&&(tokType != mdtTypeRef))
|| !pInternalImport->IsValidToken(typeDefOrRef) )
{
#ifdef _DEBUG
LOG((LF_CLASSLOADER, LL_INFO10, "Bogus class token to load: 0x%08x\n", typeDefOrRef));
#endif
typeHnd = TypeHandle();
}
else if (tokType == mdtTypeRef)
{
BOOL fNoResolutionScope;
Module *pFoundModule = Assembly::FindModuleByTypeRef(pModule, typeDefOrRef,
tokenNotToLoad==tdAllTypes ?
Loader::DontLoad :
Loader::Load,
&fNoResolutionScope);
if (pFoundModule != NULL)
{
// Not in my module, have to look it up by name. This is the primary path
// taken by the TypeRef case, i.e. we've resolve a TypeRef to a TypeDef/Module
// pair.
LPCUTF8 pszNameSpace;
LPCUTF8 pszClassName;
if (FAILED(pInternalImport->GetNameOfTypeRef(
typeDefOrRef,
&pszNameSpace,
&pszClassName)))
{
typeHnd = TypeHandle();
}
else
{
if (fNoResolutionScope)
{
// Everett C++ compiler can generate a TypeRef with RS=0
// without respective TypeDef for unmanaged valuetypes,
// referenced only by pointers to them,
// so we can fail to load legally w/ no exception
typeHnd = ClassLoader::LoadTypeByNameThrowing(pFoundModule->GetAssembly(),
pszNameSpace,
pszClassName,
ClassLoader::ReturnNullIfNotFound,
tokenNotToLoad==tdAllTypes ? ClassLoader::DontLoadTypes : ClassLoader::LoadTypes,
level);
if(typeHnd.IsNull() && bReturnNullOkWhenNoResolutionScope)
{
fNotFoundAction = ReturnNullIfNotFound;
RETURN(typeHnd);
}
}
else
{
NameHandle nameHandle(pModule, typeDefOrRef);
nameHandle.SetName(pszNameSpace, pszClassName);
nameHandle.SetTokenNotToLoad(tokenNotToLoad);
typeHnd = pFoundModule->GetClassLoader()->
LoadTypeHandleThrowIfFailed(&nameHandle, level,
pFoundModule->IsReflection() ? NULL : pFoundModule);
}
}
#ifndef DACCESS_COMPILE
if (!(typeHnd.IsNull()))
pModule->StoreTypeRef(typeDefOrRef, typeHnd);
#endif
}
}
else
{
// This is the mdtTypeDef case...
typeHnd = LoadTypeDefThrowing(pModule, typeDefOrRef,
fNotFoundAction,
fUninstantiated,
tokenNotToLoad,
level);
}
}
TypeHandle thRes = typeHnd;
// reject the load if it's an uninstantiated TypeDef/TypeRef
// being used inappropriately.
if ((fUninstantiated == FailIfUninstDefOrRef) && !typeHnd.IsNull() && typeHnd.IsGenericTypeDefinition())
thRes = TypeHandle();
// perform the check to throw when the thing is not found
if ((fNotFoundAction == ThrowIfNotFound) && thRes.IsNull() && (tokenNotToLoad != tdAllTypes))
{
#ifndef DACCESS_COMPILE
pModule->GetAssembly()->ThrowTypeLoadException(pModule->GetMDImport(),
typeDefOrRef,
IDS_CLASSLOAD_GENERAL);
#else
DacNotImpl();
#endif
}
RETURN(thRes);
}
/*static*/
BOOL
ClassLoader::ResolveTokenToTypeDefThrowing(
Module * pTypeRefModule,
mdTypeRef typeRefToken,
Module ** ppTypeDefModule,
mdTypeDef * pTypeDefToken,
Loader::LoadFlag loadFlag,
BOOL * pfUsesTypeForwarder) // The semantic of this parameter: TRUE if a type forwarder is found. It is never set to FALSE.
{
CONTRACT(BOOL)
{
if (FORBIDGC_LOADER_USE_ENABLED()) NOTHROW; else THROWS;
if (FORBIDGC_LOADER_USE_ENABLED()) GC_NOTRIGGER; else GC_TRIGGERS;
MODE_ANY;
if (FORBIDGC_LOADER_USE_ENABLED()) FORBID_FAULT; else { INJECT_FAULT(COMPlusThrowOM()); }
PRECONDITION(CheckPointer(pTypeRefModule));
SUPPORTS_DAC;
}
CONTRACT_END;
// It's a TypeDef already
if (TypeFromToken(typeRefToken) == mdtTypeDef)
{
if (ppTypeDefModule != NULL)
*ppTypeDefModule = pTypeRefModule;
if (pTypeDefToken != NULL)
*pTypeDefToken = typeRefToken;
RETURN TRUE;
}
TypeHandle typeHnd = pTypeRefModule->LookupTypeRef(typeRefToken);
// Type is already (partially) loaded and cached in the module's TypeRef table
// Do not return here if we are checking for type forwarders
if (!typeHnd.IsNull() && (pfUsesTypeForwarder == NULL))
{
if (ppTypeDefModule != NULL)
*ppTypeDefModule = typeHnd.GetModule();
if (pTypeDefToken != NULL)
*pTypeDefToken = typeHnd.GetCl();
RETURN TRUE;
}
BOOL fNoResolutionScope; //not used
Module * pFoundRefModule = Assembly::FindModuleByTypeRef(
pTypeRefModule,
typeRefToken,
loadFlag,
&fNoResolutionScope);
if (pFoundRefModule == NULL)
{ // We didn't find the TypeRef anywhere
RETURN FALSE;
}
// If checking for type forwarders, then we can see if a type forwarder was used based on the output of
// pFoundRefModule and typeHnd (if typeHnd is set)
if (!typeHnd.IsNull() && (pfUsesTypeForwarder != NULL))
{
if (typeHnd.GetModule() != pFoundRefModule)
{
*pfUsesTypeForwarder = TRUE;
}
if (ppTypeDefModule != NULL)
*ppTypeDefModule = typeHnd.GetModule();
if (pTypeDefToken != NULL)
*pTypeDefToken = typeHnd.GetCl();
RETURN TRUE;
}
// Not in my module, have to look it up by name
LPCUTF8 pszNameSpace;
LPCUTF8 pszClassName;
if (FAILED(pTypeRefModule->GetMDImport()->GetNameOfTypeRef(typeRefToken, &pszNameSpace, &pszClassName)))
{
RETURN FALSE;
}
NameHandle nameHandle(pTypeRefModule, typeRefToken);
nameHandle.SetName(pszNameSpace, pszClassName);
if (loadFlag != Loader::Load)
{
nameHandle.SetTokenNotToLoad(tdAllTypes);
}
return ResolveNameToTypeDefThrowing(pFoundRefModule, &nameHandle, ppTypeDefModule, pTypeDefToken, loadFlag, pfUsesTypeForwarder);
}
/*static*/
BOOL
ClassLoader::ResolveNameToTypeDefThrowing(
Module * pModule,
NameHandle * pName,
Module ** ppTypeDefModule,
mdTypeDef * pTypeDefToken,
Loader::LoadFlag loadFlag,
BOOL * pfUsesTypeForwarder) // The semantic of this parameter: TRUE if a type forwarder is found. It is never set to FALSE.
{
CONTRACT(BOOL)
{
if (FORBIDGC_LOADER_USE_ENABLED()) NOTHROW; else THROWS;
if (FORBIDGC_LOADER_USE_ENABLED()) GC_NOTRIGGER; else GC_TRIGGERS;
MODE_ANY;
if (FORBIDGC_LOADER_USE_ENABLED()) FORBID_FAULT; else { INJECT_FAULT(COMPlusThrowOM()); }
PRECONDITION(CheckPointer(pModule));
PRECONDITION(CheckPointer(pName));
SUPPORTS_DAC;
}
CONTRACT_END;
TypeHandle typeHnd;
mdToken foundTypeDef;
Module * pFoundModule;
mdExportedType foundExportedType;
Module * pSourceModule = pModule;
Module * pFoundRefModule = pModule;
for (UINT32 nTypeForwardingChainSize = 0; nTypeForwardingChainSize < const_cMaxTypeForwardingChainSize; nTypeForwardingChainSize++)
{
foundTypeDef = mdTokenNil;
pFoundModule = NULL;
foundExportedType = mdTokenNil;
if (!pSourceModule->GetClassLoader()->FindClassModuleThrowing(
pName,
&typeHnd,
&foundTypeDef,
&pFoundModule,
&foundExportedType,
NULL,
pSourceModule->IsReflection() ? NULL : pSourceModule,
loadFlag))
{
RETURN FALSE;
}
// Type is already loaded and cached in the loader's by-name table
if (!typeHnd.IsNull())
{
if ((typeHnd.GetModule() != pFoundRefModule) && (pfUsesTypeForwarder != NULL))
{ // We followed at least one type forwarder to resolve the type
*pfUsesTypeForwarder = TRUE;
}
if (ppTypeDefModule != NULL)
*ppTypeDefModule = typeHnd.GetModule();
if (pTypeDefToken != NULL)
*pTypeDefToken = typeHnd.GetCl();
RETURN TRUE;
}
if (pFoundModule == NULL)
{ // Module was probably not loaded
RETURN FALSE;
}
if (TypeFromToken(foundExportedType) != mdtExportedType)
{ // It's not exported type
_ASSERTE(foundExportedType == mdTokenNil);
if ((pFoundModule != pFoundRefModule) && (pfUsesTypeForwarder != NULL))
{ // We followed at least one type forwarder to resolve the type
*pfUsesTypeForwarder = TRUE;
}
if (pTypeDefToken != NULL)
*pTypeDefToken = foundTypeDef;
if (ppTypeDefModule != NULL)
*ppTypeDefModule = pFoundModule;
RETURN TRUE;
}
// It's exported type
// Repeat the search for the type in the newly found module
pSourceModule = pFoundModule;
}
// Type forwarding chain is too long
RETURN FALSE;
} // ClassLoader::ResolveTokenToTypeDefThrowing
#ifndef DACCESS_COMPILE
//---------------------------------------------------------------------------------------
//
//static
VOID
ClassLoader::GetEnclosingClassThrowing(
IMDInternalImport * pInternalImport,
Module * pModule,
mdTypeDef cl,
mdTypeDef * tdEnclosing)
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
INJECT_FAULT(COMPlusThrowOM());
MODE_ANY;
}
CONTRACTL_END;
_ASSERTE(tdEnclosing);
*tdEnclosing = mdTypeDefNil;
HRESULT hr = pInternalImport->GetNestedClassProps(cl, tdEnclosing);
if (FAILED(hr))
{
if (hr != CLDB_E_RECORD_NOTFOUND)
COMPlusThrowHR(hr);
return;
}
if (TypeFromToken(*tdEnclosing) != mdtTypeDef)
pModule->GetAssembly()->ThrowTypeLoadException(pInternalImport, cl, IDS_CLASSLOAD_ENCLOSING);
} // ClassLoader::GetEnclosingClassThrowing
//---------------------------------------------------------------------------------------
//
// Load a parent type or implemented interface type.
//
// If this is an instantiated type represented by a type spec, then instead of attempting to load the
// exact type, load an approximate instantiation in which all reference types are replaced by Object.
// The exact instantiated types will be loaded later by LoadInstantiatedInfo.
// We do this to avoid cycles early in class loading caused by definitions such as
// struct M : ICloneable<M> // load ICloneable<object>
// class C<T> : D<C<T>,int> for any T // load D<object,int>
//
//static
TypeHandle
ClassLoader::LoadApproxTypeThrowing(
Module * pModule,
mdToken tok,
SigPointer * pSigInst,
const SigTypeContext * pClassTypeContext)
{
CONTRACT(TypeHandle)
{
THROWS;
GC_TRIGGERS;
INJECT_FAULT(COMPlusThrowOM());
MODE_ANY;
PRECONDITION(CheckPointer(pSigInst, NULL_OK));
PRECONDITION(CheckPointer(pModule));
POSTCONDITION(CheckPointer(RETVAL));
}
CONTRACT_END;
IMDInternalImport * pInternalImport = pModule->GetMDImport();
if (TypeFromToken(tok) == mdtTypeSpec)
{
ULONG cSig;
PCCOR_SIGNATURE pSig;
IfFailThrowBF(pInternalImport->GetTypeSpecFromToken(tok, &pSig, &cSig), BFA_METADATA_CORRUPT, pModule);
SigPointer sigptr = SigPointer(pSig, cSig);
CorElementType type = ELEMENT_TYPE_END;
IfFailThrowBF(sigptr.GetElemType(&type), BFA_BAD_SIGNATURE, pModule);
// The only kind of type specs that we recognise are instantiated types
if (type != ELEMENT_TYPE_GENERICINST)
pModule->GetAssembly()->ThrowTypeLoadException(pInternalImport, tok, IDS_CLASSLOAD_GENERAL);
// Of these, we outlaw instantiated value classes (they can't be interfaces and can't be subclassed)
IfFailThrowBF(sigptr.GetElemType(&type), BFA_BAD_SIGNATURE, pModule);
if (type != ELEMENT_TYPE_CLASS)
pModule->GetAssembly()->ThrowTypeLoadException(pInternalImport, tok, IDS_CLASSLOAD_GENERAL);
mdToken genericTok = 0;
IfFailThrowBF(sigptr.GetToken(&genericTok), BFA_BAD_SIGNATURE, pModule);
IfFailThrowBF(sigptr.GetData(NULL), BFA_BAD_SIGNATURE, pModule);
if (pSigInst != NULL)
*pSigInst = sigptr;
// Try to load the generic type itself
THROW_BAD_FORMAT_MAYBE(
((TypeFromToken(genericTok) == mdtTypeRef) || (TypeFromToken(genericTok) == mdtTypeDef)),
BFA_UNEXPECTED_GENERIC_TOKENTYPE,
pModule);
TypeHandle genericTypeTH = LoadTypeDefOrRefThrowing(
pModule,
genericTok,
ClassLoader::ThrowIfNotFound,
ClassLoader::PermitUninstDefOrRef,
tdNoTypes,
CLASS_LOAD_APPROXPARENTS);
// We load interfaces at very approximate types - the generic
// interface itself. We fix this up in LoadInstantiatedInfo.
// This allows us to load recursive interfaces on structs such
// as "struct VC : I<VC>". The details of the interface
// are not currently needed during the first phase
// of setting up the method table.
if (genericTypeTH.IsInterface())
{
RETURN genericTypeTH;
}
else
{
// approxTypes, i.e. approximate reference types by Object, i.e. load the canonical type
RETURN SigPointer(pSig, cSig).GetTypeHandleThrowing(
pModule,
pClassTypeContext,
ClassLoader::LoadTypes,
CLASS_LOAD_APPROXPARENTS,
TRUE /*dropGenericArgumentLevel*/);
}
}
else
{
if (pSigInst != NULL)
*pSigInst = SigPointer();
RETURN LoadTypeDefOrRefThrowing(
pModule,
tok,
ClassLoader::ThrowIfNotFound,
ClassLoader::FailIfUninstDefOrRef,
tdNoTypes,
CLASS_LOAD_APPROXPARENTS);
}
} // ClassLoader::LoadApproxTypeThrowing
//---------------------------------------------------------------------------------------
//
//static
MethodTable *
ClassLoader::LoadApproxParentThrowing(
Module * pModule,
mdToken cl,
SigPointer * pParentInst,
const SigTypeContext * pClassTypeContext)
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
INJECT_FAULT(COMPlusThrowOM());
MODE_ANY;
}
CONTRACTL_END;
mdTypeRef crExtends;
MethodTable * pParentMethodTable = NULL;
TypeHandle parentType;
DWORD dwAttrClass;
Assembly * pAssembly = pModule->GetAssembly();
IMDInternalImport * pInternalImport = pModule->GetMDImport();
// Initialize the return value;
*pParentInst = SigPointer();
// Now load all dependencies of this class
if (FAILED(pInternalImport->GetTypeDefProps(
cl,
&dwAttrClass, // AttrClass
&crExtends)))
{
pAssembly->ThrowTypeLoadException(pInternalImport, cl, IDS_CLASSLOAD_BADFORMAT);
}
if (RidFromToken(crExtends) != mdTokenNil)
{
// Do an "approximate" load of the parent, replacing reference types in the instantiation by Object
// This is to avoid cycles in the loader e.g. on class C : D<C> or class C<T> : D<C<T>>
// We fix up the exact parent later in LoadInstantiatedInfo
parentType = LoadApproxTypeThrowing(pModule, crExtends, pParentInst, pClassTypeContext);
pParentMethodTable = parentType.GetMethodTable();
if (pParentMethodTable == NULL)
pAssembly->ThrowTypeLoadException(pInternalImport, cl, IDS_CLASSLOAD_PARENTNULL);
// cannot inherit from an interface
if (pParentMethodTable->IsInterface())
pAssembly->ThrowTypeLoadException(pInternalImport, cl, IDS_CLASSLOAD_PARENTINTERFACE);
if (IsTdInterface(dwAttrClass))
{
// Interfaces must extend from Object
if (! pParentMethodTable->IsObjectClass())
pAssembly->ThrowTypeLoadException(pInternalImport, cl, IDS_CLASSLOAD_INTERFACEOBJECT);
}
}
return pParentMethodTable;
} // ClassLoader::LoadApproxParentThrowing
// Perform a single phase of class loading
// It is the caller's responsibility to lock
/*static*/
TypeHandle ClassLoader::DoIncrementalLoad(TypeKey *pTypeKey, TypeHandle typeHnd, ClassLoadLevel currentLevel)
{
CONTRACTL
{
STANDARD_VM_CHECK;
PRECONDITION(CheckPointer(pTypeKey));
PRECONDITION(currentLevel >= CLASS_LOAD_BEGIN && currentLevel < CLASS_LOADED);
MODE_ANY;
}
CONTRACTL_END;
#ifdef _DEBUG
if (LoggingOn(LF_CLASSLOADER, LL_INFO10000))
{
SString name;
TypeString::AppendTypeKeyDebug(name, pTypeKey);
LOG((LF_CLASSLOADER, LL_INFO10000, "PHASEDLOAD: About to do incremental load of type %S (%p) from level %s\n", name.GetUnicode(), typeHnd.AsPtr(), classLoadLevelName[currentLevel]));
}
#endif
// Level is BEGIN if and only if type handle is null
CONSISTENCY_CHECK((currentLevel == CLASS_LOAD_BEGIN) == typeHnd.IsNull());
switch (currentLevel)
{
// Attain at least level CLASS_LOAD_UNRESTORED (if just locating type in ngen image)
// or at least level CLASS_LOAD_APPROXPARENTS (if creating type for the first time)
case CLASS_LOAD_BEGIN :
{
IBCLoggerAwareAllocMemTracker amTracker;
typeHnd = CreateTypeHandleForTypeKey(pTypeKey, &amTracker);
CONSISTENCY_CHECK(!typeHnd.IsNull());
TypeHandle published = PublishType(pTypeKey, typeHnd);
if (published == typeHnd)
amTracker.SuppressRelease();
typeHnd = published;
}
break;
case CLASS_LOAD_UNRESTOREDTYPEKEY :
#ifdef FEATURE_PREJIT
typeHnd.DoRestoreTypeKey();
#endif
break;
// Attain level CLASS_LOAD_APPROXPARENTS, starting with unrestored class
case CLASS_LOAD_UNRESTORED :
#ifdef FEATURE_PREJIT
{
CONSISTENCY_CHECK(!typeHnd.IsRestored_NoLogging());
if (typeHnd.IsTypeDesc())
typeHnd.AsTypeDesc()->Restore();
else
typeHnd.AsMethodTable()->Restore();
}
#endif
break;
// Attain level CLASS_LOAD_EXACTPARENTS
case CLASS_LOAD_APPROXPARENTS :
if (!typeHnd.IsTypeDesc())
{
LoadExactParents(typeHnd.AsMethodTable());
}
break;
case CLASS_LOAD_EXACTPARENTS :
case CLASS_DEPENDENCIES_LOADED :
case CLASS_LOADED :
break;
}
if (typeHnd.GetLoadLevel() >= CLASS_LOAD_EXACTPARENTS)
{
Notify(typeHnd);
}
return typeHnd;
}
/*static*/
// For non-canonical instantiations of generic types, create a fresh type by replicating the canonical instantiation
// For canonical instantiations of generic types, create a brand new method table
// For other constructed types, create a type desc and template method table if necessary
// For all other types, create a method table
TypeHandle ClassLoader::CreateTypeHandleForTypeKey(TypeKey* pKey, AllocMemTracker* pamTracker)
{
CONTRACT(TypeHandle)
{
STANDARD_VM_CHECK;
PRECONDITION(CheckPointer(pKey));
POSTCONDITION(RETVAL.CheckMatchesKey(pKey));
MODE_ANY;
}
CONTRACT_END
TypeHandle typeHnd = TypeHandle();
if (!pKey->IsConstructed())
{
typeHnd = CreateTypeHandleForTypeDefThrowing(pKey->GetModule(),
pKey->GetTypeToken(),
pKey->GetInstantiation(),
pamTracker);
}
else if (pKey->HasInstantiation())
{
#ifdef FEATURE_FULL_NGEN
// Try to find the type in an NGEN'd image.
typeHnd = TryFindDynLinkZapType(pKey);
if (!typeHnd.IsNull())
{
#ifdef _DEBUG
if (LoggingOn(LF_CLASSLOADER, LL_INFO10000))
{
SString name;
TypeString::AppendTypeKeyDebug(name, pKey);
LOG((LF_CLASSLOADER, LL_INFO10000, "GENERICS:CreateTypeHandleForTypeKey: found dyn-link ngen type %S with pointer %p in module %S\n", name.GetUnicode(), typeHnd.AsPtr(),
typeHnd.GetLoaderModule()->GetDebugName()));
}
#endif
if (typeHnd.GetLoadLevel() == CLASS_LOAD_UNRESTOREDTYPEKEY)
{
OVERRIDE_TYPE_LOAD_LEVEL_LIMIT(CLASS_LOADED);
typeHnd.DoRestoreTypeKey();
}
}
else
#endif // FEATURE_FULL_NGEN
{
if (IsCanonicalGenericInstantiation(pKey->GetInstantiation()))
{
typeHnd = CreateTypeHandleForTypeDefThrowing(pKey->GetModule(),
pKey->GetTypeToken(),
pKey->GetInstantiation(),
pamTracker);
}
else
{
typeHnd = CreateTypeHandleForNonCanonicalGenericInstantiation(pKey,
pamTracker);
}
#if defined(_DEBUG) && !defined(CROSSGEN_COMPILE)
if (Nullable::IsNullableType(typeHnd))
Nullable::CheckFieldOffsets(typeHnd);
#endif
}
}
else if (pKey->GetKind() == ELEMENT_TYPE_FNPTR)
{
Module *pLoaderModule = ComputeLoaderModule(pKey);
pLoaderModule->GetLoaderAllocator()->EnsureInstantiation(NULL, Instantiation(pKey->GetRetAndArgTypes(), pKey->GetNumArgs() + 1));
PREFIX_ASSUME(pLoaderModule!=NULL);
DWORD numArgs = pKey->GetNumArgs();
BYTE* mem = (BYTE*) pamTracker->Track(pLoaderModule->GetAssembly()->GetLowFrequencyHeap()->AllocMem(S_SIZE_T(sizeof(FnPtrTypeDesc)) + S_SIZE_T(sizeof(TypeHandle)) * S_SIZE_T(numArgs)));
typeHnd = TypeHandle(new(mem) FnPtrTypeDesc(pKey->GetCallConv(), numArgs, pKey->GetRetAndArgTypes()));
}
else
{
Module *pLoaderModule = ComputeLoaderModule(pKey);
PREFIX_ASSUME(pLoaderModule!=NULL);
CorElementType kind = pKey->GetKind();
TypeHandle paramType = pKey->GetElementType();
MethodTable *templateMT;
// Create a new type descriptor and insert into constructed type table
if (CorTypeInfo::IsArray(kind))
{
DWORD rank = pKey->GetRank();
THROW_BAD_FORMAT_MAYBE((kind != ELEMENT_TYPE_ARRAY) || rank > 0, BFA_MDARRAY_BADRANK, pLoaderModule);
THROW_BAD_FORMAT_MAYBE((kind != ELEMENT_TYPE_SZARRAY) || rank == 1, BFA_SDARRAY_BADRANK, pLoaderModule);
// Arrays of BYREFS not allowed
if (paramType.GetInternalCorElementType() == ELEMENT_TYPE_BYREF)
{
ThrowTypeLoadException(pKey, IDS_CLASSLOAD_CANTCREATEARRAYCLASS);
}
// Arrays of ByRefLike types not allowed
MethodTable* pMT = paramType.GetMethodTable();
if (pMT != NULL)
{
if (pMT->IsByRefLike())
{
ThrowTypeLoadException(pKey, IDS_CLASSLOAD_CANTCREATEARRAYCLASS);
}
}
// We really don't need this check anymore.
if (rank > MAX_RANK)
{
ThrowTypeLoadException(pKey, IDS_CLASSLOAD_RANK_TOOLARGE);
}
templateMT = pLoaderModule->CreateArrayMethodTable(paramType, kind, rank, pamTracker);
BYTE* mem = (BYTE*) pamTracker->Track(pLoaderModule->GetAssembly()->GetLowFrequencyHeap()->AllocMem(S_SIZE_T(sizeof(ArrayTypeDesc))));
typeHnd = TypeHandle(new(mem) ArrayTypeDesc(templateMT, paramType));
}
else
{
// no parameterized type allowed on a reference
if (paramType.GetInternalCorElementType() == ELEMENT_TYPE_BYREF ||
paramType.GetInternalCorElementType() == ELEMENT_TYPE_TYPEDBYREF)
{
ThrowTypeLoadException(pKey, IDS_CLASSLOAD_GENERAL);
}
// We do allow parametrized types of ByRefLike types. Languages may restrict them to produce safe or verifiable code,
// but there is not a good reason for restricting them in the runtime.
// let <Type>* type have a method table
// System.UIntPtr's method table is used for types like int*, void *, string * etc.
if (kind == ELEMENT_TYPE_PTR)
templateMT = MscorlibBinder::GetElementType(ELEMENT_TYPE_U);
else
templateMT = NULL;
BYTE* mem = (BYTE*) pamTracker->Track(pLoaderModule->GetAssembly()->GetLowFrequencyHeap()->AllocMem(S_SIZE_T(sizeof(ParamTypeDesc))));
typeHnd = TypeHandle(new(mem) ParamTypeDesc(kind, templateMT, paramType));
}
}
RETURN typeHnd;
}
// Publish a type (and possibly member information) in the loader's
// tables Types are published before they are fully loaded. In
// particular, exact parent info (base class and interfaces) is loaded
// in a later phase
/*static*/
TypeHandle ClassLoader::PublishType(TypeKey *pTypeKey, TypeHandle typeHnd)
{
CONTRACTL
{
STANDARD_VM_CHECK;
PRECONDITION(CheckPointer(typeHnd));
PRECONDITION(CheckPointer(pTypeKey));
// Key must match that of the handle
PRECONDITION(typeHnd.CheckMatchesKey(pTypeKey));
// Don't publish array template method tables; these are accessed only through type descs
PRECONDITION(typeHnd.IsTypeDesc() || !typeHnd.AsMethodTable()->IsArray());
}
CONTRACTL_END;
if (pTypeKey->IsConstructed())
{
Module *pLoaderModule = ComputeLoaderModule(pTypeKey);
EETypeHashTable *pTable = pLoaderModule->GetAvailableParamTypes();
CrstHolder ch(&pLoaderModule->GetClassLoader()->m_AvailableTypesLock);
// The type could have been loaded by a different thread as side-effect of avoiding deadlocks caused by LoadsTypeViolation
TypeHandle existing = pTable->GetValue(pTypeKey);
if (!existing.IsNull())
return existing;
pTable->InsertValue(typeHnd);
#ifdef _DEBUG
// Checks to help ensure that the CoreLib in the ngen process does not get contaminated with pointers to the compilation domains.
if (pLoaderModule->IsSystem() && IsCompilationProcess() && pLoaderModule->HasNativeImage())
{
CorElementType kind = pTypeKey->GetKind();
MethodTable *typeHandleMethodTable = typeHnd.GetMethodTable();
if ((typeHandleMethodTable != NULL) && (typeHandleMethodTable->GetLoaderAllocator() != pLoaderModule->GetLoaderAllocator()))
{
_ASSERTE(!"MethodTable of type loaded into CoreLib during NGen is not from CoreLib!");
}
if ((kind != ELEMENT_TYPE_FNPTR) && (kind != ELEMENT_TYPE_VAR) && (kind != ELEMENT_TYPE_MVAR))
{
if ((kind == ELEMENT_TYPE_SZARRAY) || (kind == ELEMENT_TYPE_ARRAY) || (kind == ELEMENT_TYPE_BYREF) || (kind == ELEMENT_TYPE_PTR) || (kind == ELEMENT_TYPE_VALUETYPE))
{
// Check to ensure param value is also part of CoreLib.
if (pTypeKey->GetElementType().GetLoaderAllocator() != pLoaderModule->GetLoaderAllocator())
{
_ASSERTE(!"Param value of type key used to load type during NGEN not located within CoreLib yet type is placed into CoreLib");
}
}
else if (kind == ELEMENT_TYPE_FNPTR)
{
// Check to ensure the parameter types of fnptr are in CoreLib
for (DWORD i = 0; i <= pTypeKey->GetNumArgs(); i++)
{
if (pTypeKey->GetRetAndArgTypes()[i].GetLoaderAllocator() != pLoaderModule->GetLoaderAllocator())
{
_ASSERTE(!"Ret or Arg type of function pointer type key used to load type during NGEN not located within CoreLib yet type is placed into CoreLib");
}
}
}
else if (kind == ELEMENT_TYPE_CLASS)
{
// Check to ensure that the generic parameters are all within CoreLib
for (DWORD i = 0; i < pTypeKey->GetNumGenericArgs(); i++)
{
if (pTypeKey->GetInstantiation()[i].GetLoaderAllocator() != pLoaderModule->GetLoaderAllocator())
{
_ASSERTE(!"Instantiation parameter of generic class type key used to load type during NGEN not located within CoreLib yet type is placed into CoreLib");
}
}
}
else
{
// Should not be able to get here
_ASSERTE(!"Unknown type key type");
}
}
}
#endif // DEBUG
}
else
{
Module *pModule = pTypeKey->GetModule();
mdTypeDef typeDef = pTypeKey->GetTypeToken();
CrstHolder ch(&pModule->GetClassLoader()->m_AvailableTypesLock);
// ! We cannot fail after this point.
CANNOTTHROWCOMPLUSEXCEPTION();
FAULT_FORBID();
// The type could have been loaded by a different thread as side-effect of avoiding deadlocks caused by LoadsTypeViolation
TypeHandle existing = pModule->LookupTypeDef(typeDef);
if (!existing.IsNull())
return existing;
MethodTable *pMT = typeHnd.AsMethodTable();
MethodTable::IntroducedMethodIterator it(pMT);
for (; it.IsValid(); it.Next())
{
MethodDesc * pMD = it.GetMethodDesc();
CONSISTENCY_CHECK(pMD != NULL && pMD->GetMethodTable() == pMT);
if (!pMD->IsUnboxingStub())
{
pModule->EnsuredStoreMethodDef(pMD->GetMemberDef(), pMD);
}
}
ApproxFieldDescIterator fdIterator(pMT, ApproxFieldDescIterator::ALL_FIELDS);
FieldDesc* pFD;
while ((pFD = fdIterator.Next()) != NULL)
{
if (pFD->GetEnclosingMethodTable() == pMT)
{
pModule->EnsuredStoreFieldDef(pFD->GetMemberDef(), pFD);
}
}
// Publish the type last - to ensure that nobody can see it until all the method and field RID maps are filled in
pModule->EnsuredStoreTypeDef(typeDef, typeHnd);
}
return typeHnd;
}
// Notify profiler and debugger that a type load has completed
// Also adjust perf counters
/*static*/
void ClassLoader::Notify(TypeHandle typeHnd)
{
CONTRACTL
{
STANDARD_VM_CHECK;
PRECONDITION(CheckPointer(typeHnd));
}
CONTRACTL_END;
LOG((LF_CLASSLOADER, LL_INFO1000, "Notify: %p %s\n", typeHnd.AsPtr(), typeHnd.IsTypeDesc() ? "typedesc" : typeHnd.AsMethodTable()->GetDebugClassName()));
if (typeHnd.IsTypeDesc())
return;
MethodTable * pMT = typeHnd.AsMethodTable();
#ifdef PROFILING_SUPPORTED
{
BEGIN_PIN_PROFILER(CORProfilerTrackClasses());
// We don't tell profilers about typedescs, as per IF above. Also, we don't
// tell profilers about:
if (
// ...generics with unbound variables
(!pMT->ContainsGenericVariables()) &&
// ...or array method tables
// (This check is mainly for NGEN restore, as JITted code won't hit
// this code path for array method tables anyway)
(!pMT->IsArray()))
{
LOG((LF_CLASSLOADER, LL_INFO1000, "Notifying profiler of Started1 %p %s\n", pMT, pMT->GetDebugClassName()));
// Record successful load of the class for the profiler
g_profControlBlock.pProfInterface->ClassLoadStarted(TypeHandleToClassID(typeHnd));
//
// Profiler can turn off TrackClasses during the Started() callback. Need to
// retest the flag here.
//
if (CORProfilerTrackClasses())
{
LOG((LF_CLASSLOADER, LL_INFO1000, "Notifying profiler of Finished1 %p %s\n", pMT, pMT->GetDebugClassName()));
g_profControlBlock.pProfInterface->ClassLoadFinished(TypeHandleToClassID(typeHnd),
S_OK);
}
}
END_PIN_PROFILER();
}
#endif //PROFILING_SUPPORTED
g_IBCLogger.LogMethodTableAccess(pMT);
if (pMT->IsTypicalTypeDefinition())
{
LOG((LF_CLASSLOADER, LL_INFO100, "Successfully loaded class %s\n", pMT->GetDebugClassName()));
#ifdef DEBUGGING_SUPPORTED
{
Module * pModule = pMT->GetModule();
// Update metadata for dynamic module.
pModule->UpdateDynamicMetadataIfNeeded();
}
if (CORDebuggerAttached())
{
LOG((LF_CORDB, LL_EVERYTHING, "NotifyDebuggerLoad clsload 2239 class %s\n", pMT->GetDebugClassName()));
typeHnd.NotifyDebuggerLoad(NULL, FALSE);
}
#endif // DEBUGGING_SUPPORTED
#if defined(ENABLE_PERF_COUNTERS)
GetPerfCounters().m_Loading.cClassesLoaded ++;
#endif
}
}
//-----------------------------------------------------------------------------
// Common helper for LoadTypeHandleForTypeKey and LoadTypeHandleForTypeKeyNoLock.
// Makes the root level call to kick off the transitive closure walk for
// the final level pushes.
//-----------------------------------------------------------------------------
static void PushFinalLevels(TypeHandle typeHnd, ClassLoadLevel targetLevel, const InstantiationContext *pInstContext)
{
CONTRACTL
{
STANDARD_VM_CHECK;
LOADS_TYPE(targetLevel);
}
CONTRACTL_END
// This phase brings the type and all its transitive dependencies to their
// final state, sans the IsFullyLoaded bit.
if (targetLevel >= CLASS_DEPENDENCIES_LOADED)
{
BOOL fBailed = FALSE;
typeHnd.DoFullyLoad(NULL, CLASS_DEPENDENCIES_LOADED, NULL, &fBailed, pInstContext);
}
// This phase does access/constraint and other type-safety checks on the type
// and on its transitive dependencies.
if (targetLevel == CLASS_LOADED)
{
DFLPendingList pendingList;
BOOL fBailed = FALSE;
typeHnd.DoFullyLoad(NULL, CLASS_LOADED, &pendingList, &fBailed, pInstContext);
// In the case of a circular dependency, one or more types will have
// had their promotions deferred.
//
// If we got to this point, all checks have successfully passed on
// the transitive closure (otherwise, DoFullyLoad would have thrown.)
//
// So we can go ahead and mark everyone as fully loaded.
//
UINT numTH = pendingList.Count();
TypeHandle *pTHPending = pendingList.Table();
for (UINT i = 0; i < numTH; i++)
{
// NOTE: It is possible for duplicates to appear in this list so
// don't do any operation that isn't idempodent.
pTHPending[i].SetIsFullyLoaded();
}
}
}
//
TypeHandle ClassLoader::LoadTypeHandleForTypeKey(TypeKey *pTypeKey,
TypeHandle typeHnd,
ClassLoadLevel targetLevel/*=CLASS_LOADED*/,
const InstantiationContext *pInstContext/*=NULL*/)
{
CONTRACTL
{
INSTANCE_CHECK;
THROWS;
GC_TRIGGERS;
MODE_ANY;
LOADS_TYPE(targetLevel);
}
CONTRACTL_END
GCX_PREEMP();
// Type loading can be recursive. Probe for sufficient stack.
//
// Execution of the FINALLY in LoadTypeHandleForTypeKey_Body can eat
// a lot of stack because LoadTypeHandleForTypeKey_Inner can rethrow
// any non-SO exceptions that it takes, ensure that we have plenty
// of stack before getting into it (>24 pages on AMD64, remember
// that num pages probed is 2*N on AMD64).
INTERIOR_STACK_PROBE_FOR(GetThread(),20);
#ifdef _DEBUG
if (LoggingOn(LF_CLASSLOADER, LL_INFO1000))
{
SString name;
TypeString::AppendTypeKeyDebug(name, pTypeKey);
LOG((LF_CLASSLOADER, LL_INFO10000, "PHASEDLOAD: LoadTypeHandleForTypeKey for type %S to level %s\n", name.GetUnicode(), classLoadLevelName[targetLevel]));
CrstHolder unresolvedClassLockHolder(&m_UnresolvedClassLock);
m_pUnresolvedClassHash->Dump();
}
#endif
// When using domain neutral assemblies (and not eagerly propagating dependency loads),
// it's possible to get here without having injected the module into the current app domain.
// GetDomainFile will accomplish that.
if (!pTypeKey->IsConstructed())
{
pTypeKey->GetModule()->GetDomainFile();
}
ClassLoadLevel currentLevel = typeHnd.IsNull() ? CLASS_LOAD_BEGIN : typeHnd.GetLoadLevel();
ClassLoadLevel targetLevelUnderLock = targetLevel < CLASS_DEPENDENCIES_LOADED ? targetLevel : (ClassLoadLevel) (CLASS_DEPENDENCIES_LOADED-1);
if (currentLevel < targetLevelUnderLock)
{
typeHnd = LoadTypeHandleForTypeKey_Body(pTypeKey,
typeHnd,
targetLevelUnderLock);
_ASSERTE(!typeHnd.IsNull());
}
_ASSERTE(typeHnd.GetLoadLevel() >= targetLevelUnderLock);
PushFinalLevels(typeHnd, targetLevel, pInstContext);
END_INTERIOR_STACK_PROBE;
return typeHnd;
}
//
TypeHandle ClassLoader::LoadTypeHandleForTypeKeyNoLock(TypeKey *pTypeKey,
ClassLoadLevel targetLevel/*=CLASS_LOADED*/,
const InstantiationContext *pInstContext/*=NULL*/)
{
CONTRACTL
{
INSTANCE_CHECK;
THROWS;
GC_TRIGGERS;
MODE_ANY;
LOADS_TYPE(targetLevel);
PRECONDITION(CheckPointer(pTypeKey));
PRECONDITION(targetLevel >= 0 && targetLevel <= CLASS_LOADED);
}
CONTRACTL_END
GCX_PREEMP();
TypeHandle typeHnd = TypeHandle();
// Type loading can be recursive. Probe for sufficient stack.
INTERIOR_STACK_PROBE_FOR(GetThread(),8);
ClassLoadLevel currentLevel = CLASS_LOAD_BEGIN;
ClassLoadLevel targetLevelUnderLock = targetLevel < CLASS_DEPENDENCIES_LOADED ? targetLevel : (ClassLoadLevel) (CLASS_DEPENDENCIES_LOADED-1);
while (currentLevel < targetLevelUnderLock)
{
typeHnd = DoIncrementalLoad(pTypeKey, typeHnd, currentLevel);
CONSISTENCY_CHECK(typeHnd.GetLoadLevel() > currentLevel);
currentLevel = typeHnd.GetLoadLevel();
}
PushFinalLevels(typeHnd, targetLevel, pInstContext);
END_INTERIOR_STACK_PROBE;
return typeHnd;
}
//---------------------------------------------------------------------------------------
//
class PendingTypeLoadHolder
{
Thread * m_pThread;
PendingTypeLoadEntry * m_pEntry;
PendingTypeLoadHolder * m_pPrevious;
public:
PendingTypeLoadHolder(PendingTypeLoadEntry * pEntry)
{
LIMITED_METHOD_CONTRACT;
m_pThread = GetThread();
m_pEntry = pEntry;
m_pPrevious = m_pThread->GetPendingTypeLoad();
m_pThread->SetPendingTypeLoad(this);
}
~PendingTypeLoadHolder()
{
LIMITED_METHOD_CONTRACT;
_ASSERTE(m_pThread->GetPendingTypeLoad() == this);
m_pThread->SetPendingTypeLoad(m_pPrevious);
}
static bool CheckForDeadLockOnCurrentThread(PendingTypeLoadEntry * pEntry)
{
LIMITED_METHOD_CONTRACT;
PendingTypeLoadHolder * pCurrent = GetThread()->GetPendingTypeLoad();
while (pCurrent != NULL)
{
if (pCurrent->m_pEntry == pEntry)
return true;
pCurrent = pCurrent->m_pPrevious;
}
return false;
}
};
//---------------------------------------------------------------------------------------
//
TypeHandle
ClassLoader::LoadTypeHandleForTypeKey_Body(
TypeKey * pTypeKey,
TypeHandle typeHnd,
ClassLoadLevel targetLevel)
{
CONTRACT(TypeHandle)
{
STANDARD_VM_CHECK;
POSTCONDITION(!typeHnd.IsNull() && typeHnd.GetLoadLevel() >= targetLevel);
}
CONTRACT_END
if (!pTypeKey->IsConstructed())
{
Module *pModule = pTypeKey->GetModule();
mdTypeDef cl = pTypeKey->GetTypeToken();
STRESS_LOG2(LF_CLASSLOADER, LL_INFO100000, "LoadTypeHandle: Loading Class from Module %p token %x\n", pModule, cl);
#ifdef _DEBUG
IMDInternalImport* pInternalImport = pModule->GetMDImport();
LPCUTF8 className;
LPCUTF8 nameSpace;
if (FAILED(pInternalImport->GetNameOfTypeDef(cl, &className, &nameSpace)))
{
className = nameSpace = "Invalid TypeDef record";
}
if (g_pConfig->ShouldBreakOnClassLoad(className))
CONSISTENCY_CHECK_MSGF(false, ("BreakOnClassLoad: typename '%s' ", className));
#endif
}
ReleaseHolder<PendingTypeLoadEntry> pLoadingEntry;
CrstHolderWithState unresolvedClassLockHolder(&m_UnresolvedClassLock, false);
retry:
unresolvedClassLockHolder.Acquire();
// Is it in the hash of classes currently being loaded?
pLoadingEntry = m_pUnresolvedClassHash->GetValue(pTypeKey);
if (pLoadingEntry)
{
pLoadingEntry->AddRef();
// It is in the hash, which means that another thread is waiting for it (or that we are
// already loading this class on this thread, which should never happen, since that implies
// a recursive dependency).
unresolvedClassLockHolder.Release();
//
// Check one last time before waiting that the type handle is not sufficiently loaded to
// prevent deadlocks
//
{
if (typeHnd.IsNull())
{
typeHnd = LookupTypeHandleForTypeKey(pTypeKey);
}
if (!typeHnd.IsNull())
{
if (typeHnd.GetLoadLevel() >= targetLevel)
RETURN typeHnd;
}
}
if (PendingTypeLoadHolder::CheckForDeadLockOnCurrentThread(pLoadingEntry))
{
// Attempting recursive load
ClassLoader::ThrowTypeLoadException(pTypeKey, IDS_CLASSLOAD_GENERAL);
}
//
// Violation of type loadlevel ordering rules depends on type load failing in case of cyclic dependency that would
// otherwise lead to deadlock. We will speculatively proceed with the type load to make it fail in the right spot,
// in backward compatible way. In case the type load succeeds, we will only let one type win in PublishType.
//
if (typeHnd.IsNull() && GetThread()->HasThreadStateNC(Thread::TSNC_LoadsTypeViolation))
{
PendingTypeLoadHolder ptlh(pLoadingEntry);
typeHnd = DoIncrementalLoad(pTypeKey, TypeHandle(), CLASS_LOAD_BEGIN);
goto retry;
}
{
// Wait for class to be loaded by another thread. This is where we start tracking the
// entry, so there is an implicit Acquire in our use of Assign here.
CrstHolder loadingEntryLockHolder(&pLoadingEntry->m_Crst);
_ASSERTE(pLoadingEntry->HasLock());
}
// Result of other thread loading the class
HRESULT hr = pLoadingEntry->m_hrResult;
if (FAILED(hr)) {
//
// Redo the lookup one more time and return a valid type if possible. The other thread could
// have hit error while loading the type to higher level than we need.
//
{
if (typeHnd.IsNull())
{
typeHnd = LookupTypeHandleForTypeKey(pTypeKey);
}
if (!typeHnd.IsNull())
{
if (typeHnd.GetLoadLevel() >= targetLevel)
RETURN typeHnd;
}
}
if (hr == E_ABORT) {
LOG((LF_CLASSLOADER, LL_INFO10, "need to retry LoadTypeHandle: %x\n", hr));
goto retry;
}
LOG((LF_CLASSLOADER, LL_INFO10, "Failed to load in other entry: %x\n", hr));
if (hr == E_OUTOFMEMORY) {
COMPlusThrowOM();
}
pLoadingEntry->ThrowException();
}
// Get a pointer to the EEClass being loaded
typeHnd = pLoadingEntry->m_typeHandle;
if (!typeHnd.IsNull())
{
// If the type load on the other thread loaded the type to the needed level, return it here.
if (typeHnd.GetLoadLevel() >= targetLevel)
RETURN typeHnd;
}
// The type load on the other thread did not load the type "enough". Begin the type load
// process again to cause us to load to the needed level.
goto retry;
}
if (typeHnd.IsNull())
{
// The class was not being loaded. However, it may have already been loaded after our
// first LoadTypeHandleThrowIfFailed() and before taking the lock.
typeHnd = LookupTypeHandleForTypeKey(pTypeKey);
}
ClassLoadLevel currentLevel = CLASS_LOAD_BEGIN;
if (!typeHnd.IsNull())
{
currentLevel = typeHnd.GetLoadLevel();
if (currentLevel >= targetLevel)
RETURN typeHnd;
}
// It was not loaded, and it is not being loaded, so we must load it. Create a new LoadingEntry
// and acquire it immediately so that other threads will block.
pLoadingEntry = new PendingTypeLoadEntry(*pTypeKey, typeHnd); // this atomically creates a crst and acquires it
if (!(m_pUnresolvedClassHash->InsertValue(pLoadingEntry)))
{
COMPlusThrowOM();
}
// Leave the global lock, so that other threads may now start waiting on our class's lock
unresolvedClassLockHolder.Release();
EX_TRY
{
PendingTypeLoadHolder ptlh(pLoadingEntry);
TRIGGERS_TYPELOAD();
while (currentLevel < targetLevel)
{
typeHnd = DoIncrementalLoad(pTypeKey, typeHnd, currentLevel);
CONSISTENCY_CHECK(typeHnd.GetLoadLevel() > currentLevel);
currentLevel = typeHnd.GetLoadLevel();
// If other threads are waiting for this load, unblock them as soon as possible to prevent deadlocks.
if (pLoadingEntry->HasWaiters())
break;
}
_ASSERTE(!typeHnd.IsNull());
pLoadingEntry->SetResult(typeHnd);
}
EX_HOOK
{
LOG((LF_CLASSLOADER, LL_INFO10, "Caught an exception loading: %x, %0x (Module)\n", pTypeKey->GetTypeToken(), pTypeKey->GetModule()));
if (!GetThread()->HasThreadStateNC(Thread::TSNC_LoadsTypeViolation))
{
// Fix up the loading entry.
Exception *pException = GET_EXCEPTION();
pLoadingEntry->SetException(pException);
}
// Unlink this class from the unresolved class list.
unresolvedClassLockHolder.Acquire();
m_pUnresolvedClassHash->DeleteValue(pTypeKey);
// Release the lock before proceeding. The unhandled exception filters take number of locks that
// have ordering violations with this lock.
unresolvedClassLockHolder.Release();
// Unblock any thread waiting to load same type as in TypeLoadEntry
pLoadingEntry->UnblockWaiters();
}
EX_END_HOOK;
// Unlink this class from the unresolved class list.
unresolvedClassLockHolder.Acquire();
m_pUnresolvedClassHash->DeleteValue(pTypeKey);
unresolvedClassLockHolder.Release();
// Unblock any thread waiting to load same type as in TypeLoadEntry. This should be done
// after pLoadingEntry is removed from m_pUnresolvedClassHash. Otherwise the other thread
// (which was waiting) will keep spinning for a while after waking up, till the current thread removes
// pLoadingEntry from m_pUnresolvedClassHash. This can cause hang in situation when the current
// thread is a background thread and so will get very less processor cycle to perform subsequent
// operations to remove the entry from hash later.
pLoadingEntry->UnblockWaiters();
if (currentLevel < targetLevel)
goto retry;
RETURN typeHnd;
} // ClassLoader::LoadTypeHandleForTypeKey_Body
#endif //!DACCESS_COMPILE
//---------------------------------------------------------------------------------------
//
//static
TypeHandle
ClassLoader::LoadArrayTypeThrowing(
TypeHandle elemType,
CorElementType arrayKind,
unsigned rank, //=0
LoadTypesFlag fLoadTypes, //=LoadTypes
ClassLoadLevel level)
{
CONTRACT(TypeHandle)
{
if (FORBIDGC_LOADER_USE_ENABLED()) NOTHROW; else THROWS;
if (FORBIDGC_LOADER_USE_ENABLED()) GC_NOTRIGGER; else GC_TRIGGERS;
if (FORBIDGC_LOADER_USE_ENABLED()) FORBID_FAULT; else { INJECT_FAULT(COMPlusThrowOM()); }
if (FORBIDGC_LOADER_USE_ENABLED() || fLoadTypes != LoadTypes) { LOADS_TYPE(CLASS_LOAD_BEGIN); } else { LOADS_TYPE(level); }
if (fLoadTypes == DontLoadTypes) SO_TOLERANT; else SO_INTOLERANT;
MODE_ANY;
SUPPORTS_DAC;
POSTCONDITION(CheckPointer(RETVAL, ((fLoadTypes == LoadTypes) ? NULL_NOT_OK : NULL_OK)));
}
CONTRACT_END
CorElementType predefinedElementType = ELEMENT_TYPE_END;
// Try finding it in our cache of primitive SD arrays
if (arrayKind == ELEMENT_TYPE_SZARRAY) {
predefinedElementType = elemType.GetSignatureCorElementType();
if (predefinedElementType <= ELEMENT_TYPE_R8) {
ArrayTypeDesc* typeDesc = g_pPredefinedArrayTypes[predefinedElementType];
if (typeDesc != 0)
RETURN(TypeHandle(typeDesc));
}
// This call to AsPtr is somewhat bogus and only used
// as an optimization. If the TypeHandle is really a TypeDesc
// then the equality checks for the optimizations below will
// fail. Thus ArrayMT should not be used elsewhere in this function
else if (elemType.AsPtr() == PTR_VOID(g_pObjectClass)) {
// Code duplicated because Object[]'s SigCorElementType is E_T_CLASS, not OBJECT
ArrayTypeDesc* typeDesc = g_pPredefinedArrayTypes[ELEMENT_TYPE_OBJECT];
if (typeDesc != 0)
RETURN(TypeHandle(typeDesc));
predefinedElementType = ELEMENT_TYPE_OBJECT;
}
else if (elemType.AsPtr() == PTR_VOID(g_pStringClass)) {
// Code duplicated because String[]'s SigCorElementType is E_T_CLASS, not STRING
ArrayTypeDesc* typeDesc = g_pPredefinedArrayTypes[ELEMENT_TYPE_STRING];
if (typeDesc != 0)
RETURN(TypeHandle(typeDesc));
predefinedElementType = ELEMENT_TYPE_STRING;
}
else {
predefinedElementType = ELEMENT_TYPE_END;
}
rank = 1;
}
#ifndef DACCESS_COMPILE
// To avoid loading useless shared instantiations, normalize shared instantiations to the canonical form
// (e.g. List<_Canon>[] -> _Canon[])
// The denormalized shared instantiations should be needed only during JITing, so it is fine to skip this
// for DACCESS_COMPILE.
if (elemType.IsCanonicalSubtype())
{
elemType = ClassLoader::CanonicalizeGenericArg(elemType);
}
#endif
TypeKey key(arrayKind, elemType, FALSE, rank);
TypeHandle th = LoadConstructedTypeThrowing(&key, fLoadTypes, level);
if (predefinedElementType != ELEMENT_TYPE_END && !th.IsNull() && th.IsFullyLoaded())
{
g_pPredefinedArrayTypes[predefinedElementType] = th.AsArray();
}
RETURN(th);
} // ClassLoader::LoadArrayTypeThrowing
#ifndef DACCESS_COMPILE
VOID ClassLoader::AddAvailableClassDontHaveLock(Module *pModule,
mdTypeDef classdef,
AllocMemTracker *pamTracker)
{
CONTRACTL
{
INSTANCE_CHECK;
THROWS;
GC_TRIGGERS;
MODE_ANY;
INJECT_FAULT(COMPlusThrowOM(););
}
CONTRACTL_END
#ifdef FEATURE_COMINTEROP
_ASSERTE(!pModule->GetAssembly()->IsWinMD()); // WinMD files should never get into this path, otherwise provide szWinRtNamespacePrefix
#endif
CrstHolder ch(&m_AvailableClassLock);
AddAvailableClassHaveLock(
pModule,
classdef,
pamTracker,
NULL, // szWinRtNamespacePrefix
0); // cchWinRtNamespacePrefix
}
// This routine must be single threaded! The reason is that there are situations which allow
// the same class name to have two different mdTypeDef tokens (for example, we load two different DLLs
// simultaneously, and they have some common class files, or we convert the same class file
// simultaneously on two threads). The problem is that we do not want to overwrite the old
// <classname> -> pModule mapping with the new one, because this may cause identity problems.
//
// This routine assumes you already have the lock. Use AddAvailableClassDontHaveLock() if you
// don't have it.
//
// Also validates that TypeDef namespace begins with szWinRTNamespacePrefix (if it is not NULL).
// The prefix should be NULL for normal non-WinRT .NET assemblies.
//
VOID ClassLoader::AddAvailableClassHaveLock(
Module * pModule,
mdTypeDef classdef,
AllocMemTracker * pamTracker,
LPCSTR szWinRtNamespacePrefix,
DWORD cchWinRtNamespacePrefix) // Optimization for faster prefix comparison implementation
{
CONTRACTL
{
INSTANCE_CHECK;
THROWS;
GC_TRIGGERS;
MODE_ANY;
INJECT_FAULT(COMPlusThrowOM(););
}
CONTRACTL_END
EEClassHashTable *pClassHash = pModule->GetAvailableClassHash();
EEClassHashTable *pClassCaseInsHash = pModule->GetAvailableClassCaseInsHash();
LPCUTF8 pszName;
LPCUTF8 pszNameSpace;
HashDatum ThrowawayData;
IMDInternalImport *pMDImport = pModule->GetMDImport();
if (FAILED(pMDImport->GetNameOfTypeDef(classdef, &pszName, &pszNameSpace)))
{
pszName = pszNameSpace = "Invalid TypeDef token";
pModule->GetAssembly()->ThrowBadImageException(pszNameSpace, pszName, BFA_INVALID_TOKEN);
}
EEClassHashEntry_t *pBucket;
mdTypeDef enclosing;
if (SUCCEEDED(pMDImport->GetNestedClassProps(classdef, &enclosing))) {
// nested type
LPCUTF8 pszEnclosingName;
LPCUTF8 pszEnclosingNameSpace;
mdTypeDef enclEnclosing;
// Find this type's encloser's entry in the available table.
// We'll save a pointer to it in the new hash entry for this type.
BOOL fNestedEncl = SUCCEEDED(pMDImport->GetNestedClassProps(enclosing, &enclEnclosing));
EEClassHashTable::LookupContext sContext;
if (FAILED(pMDImport->GetNameOfTypeDef(enclosing, &pszEnclosingName, &pszEnclosingNameSpace)))
{
pszName = pszNameSpace = "Invalid TypeDef token";
pModule->GetAssembly()->ThrowBadImageException(pszNameSpace, pszName, BFA_INVALID_TOKEN);
}
if ((pBucket = pClassHash->GetValue(pszEnclosingNameSpace,
pszEnclosingName,
&ThrowawayData,
fNestedEncl,
&sContext)) != NULL) {
if (fNestedEncl) {
// Find entry for enclosing class - NOTE, this assumes that the
// enclosing class's TypeDef or ExportedType was inserted previously,
// which assumes that, when enuming TD's, we get the enclosing class first
while ((!CompareNestedEntryWithTypeDef(pMDImport,
enclEnclosing,
pClassHash,
pBucket->GetEncloser())) &&
(pBucket = pClassHash->FindNextNestedClass(pszEnclosingNameSpace,
pszEnclosingName,
&ThrowawayData,
&sContext)) != NULL);
}
if (!pBucket) // Enclosing type not found in hash table
pModule->GetAssembly()->ThrowBadImageException(pszNameSpace, pszName, BFA_ENCLOSING_TYPE_NOT_FOUND);
// In this hash table, if the lower bit is set, it means a Module, otherwise it means EEClass*
ThrowawayData = EEClassHashTable::CompressClassDef(classdef);
InsertValue(pClassHash, pClassCaseInsHash, pszNameSpace, pszName, ThrowawayData, pBucket, pamTracker);
}
}
else {
// Don't add duplicate top-level classes. Top-level classes are
// added to the beginning of the bucket, while nested classes are
// added to the end. So, a duplicate top-level class could hide
// the previous type's EEClass* entry in the hash table.
EEClassHashEntry_t *pCaseInsEntry = NULL;
LPUTF8 pszLowerCaseNS = NULL;
LPUTF8 pszLowerCaseName = NULL;
if (pClassCaseInsHash) {
CreateCanonicallyCasedKey(pszNameSpace, pszName, &pszLowerCaseNS, &pszLowerCaseName);
pCaseInsEntry = pClassCaseInsHash->AllocNewEntry(pamTracker);
}
EEClassHashEntry_t *pEntry = pClassHash->FindItem(pszNameSpace, pszName, FALSE, NULL);
if (pEntry) {
HashDatum Data = pEntry->GetData();
if (((size_t)Data & EECLASSHASH_TYPEHANDLE_DISCR) &&
((size_t)Data & EECLASSHASH_MDEXPORT_DISCR)) {
// it's an ExportedType - check the 'already seen' bit and if on, report a class loading exception
// otherwise, set it
if ((size_t)Data & EECLASSHASH_ALREADYSEEN)
pModule->GetAssembly()->ThrowBadImageException(pszNameSpace, pszName, BFA_MULT_TYPE_SAME_NAME);
else {
Data = (HashDatum)((size_t)Data | EECLASSHASH_ALREADYSEEN);
pEntry->SetData(Data);
}
}
else {
// We want to throw an exception for a duplicate typedef.
// However, this used to be allowed in 1.0/1.1, and some third-party DLLs have
// been obfuscated so that they have duplicate private typedefs.
// We must allow this for old assemblies for app compat reasons
pModule->GetAssembly()->ThrowBadImageException(pszNameSpace, pszName, BFA_MULT_TYPE_SAME_NAME);
}
}
else {
pEntry = pClassHash->AllocNewEntry(pamTracker);
CANNOTTHROWCOMPLUSEXCEPTION();
FAULT_FORBID();
pClassHash->InsertValueUsingPreallocatedEntry(pEntry, pszNameSpace, pszName, EEClassHashTable::CompressClassDef(classdef), NULL);
if (pClassCaseInsHash)
pClassCaseInsHash->InsertValueUsingPreallocatedEntry(pCaseInsEntry, pszLowerCaseNS, pszLowerCaseName, pEntry, pEntry->GetEncloser());
}
#ifdef FEATURE_COMINTEROP
// Check WinRT namespace prefix if required
if (szWinRtNamespacePrefix != NULL)
{
DWORD dwAttr;
if (FAILED(pMDImport->GetTypeDefProps(classdef, &dwAttr, NULL)))
{
pModule->GetAssembly()->ThrowBadImageException(pszNameSpace, pszName, BFA_INVALID_TOKEN);
}
// Check only public WinRT types that are not nested (i.e. only types available for binding, excluding NoPIA)
if (IsTdPublic(dwAttr) && IsTdWindowsRuntime(dwAttr))
{
// Guaranteed by the caller - code:ClassLoader::PopulateAvailableClassHashTable
_ASSERTE(cchWinRtNamespacePrefix == strlen(szWinRtNamespacePrefix));
// Now make sure namespace is, or begins with the namespace-prefix (note: 'MyN' should not match namespace 'MyName')
// Note: Case insensitive comparison function has to be in sync with Win8 implementation
// (ExtractExactCaseNamespaceSegmentFromMetadataFile in com\WinRT\WinTypes\TypeResolution\NamespaceResolution.cpp)
BOOL fIsNamespaceSubstring = (pszNameSpace != NULL) &&
((strncmp(pszNameSpace, szWinRtNamespacePrefix, cchWinRtNamespacePrefix) == 0) ||
(_strnicmp(pszNameSpace, szWinRtNamespacePrefix, cchWinRtNamespacePrefix) == 0));
BOOL fIsSubNamespace = fIsNamespaceSubstring &&
((pszNameSpace[cchWinRtNamespacePrefix] == '\0') ||
(pszNameSpace[cchWinRtNamespacePrefix] == '.'));
if (!fIsSubNamespace)
{
pModule->GetAssembly()->ThrowBadImageException(pszNameSpace, pszName, BFA_WINRT_INVALID_NAMESPACE_FOR_TYPE);
}
}
}
#endif // FEATURE_COMINTEROP
}
}
VOID ClassLoader::AddExportedTypeDontHaveLock(Module *pManifestModule,
mdExportedType cl,
AllocMemTracker *pamTracker)
{
CONTRACTL
{
INSTANCE_CHECK;
THROWS;
GC_TRIGGERS;
MODE_ANY;
INJECT_FAULT(COMPlusThrowOM(););
}
CONTRACTL_END
CrstHolder ch(&m_AvailableClassLock);
AddExportedTypeHaveLock(
pManifestModule,
cl,
pamTracker);
}
VOID ClassLoader::AddExportedTypeHaveLock(Module *pManifestModule,
mdExportedType cl,
AllocMemTracker *pamTracker)
{
CONTRACTL
{
INSTANCE_CHECK;
THROWS;
GC_TRIGGERS;
MODE_ANY;
INJECT_FAULT(COMPlusThrowOM(););
}
CONTRACTL_END
mdToken mdImpl;
LPCSTR pszName;
LPCSTR pszNameSpace;
IMDInternalImport* pAsmImport = pManifestModule->GetMDImport();
if (FAILED(pAsmImport->GetExportedTypeProps(
cl,
&pszNameSpace,
&pszName,
&mdImpl,
NULL, // type def
NULL))) // flags
{
pManifestModule->GetAssembly()->ThrowBadImageException(pszNameSpace, pszName, BFA_INVALID_TOKEN);
}
HashDatum ThrowawayData;
if (TypeFromToken(mdImpl) == mdtExportedType)
{
// nested class
LPCUTF8 pszEnclosingNameSpace;
LPCUTF8 pszEnclosingName;
mdToken nextImpl;
if (FAILED(pAsmImport->GetExportedTypeProps(
mdImpl,
&pszEnclosingNameSpace,
&pszEnclosingName,
&nextImpl,
NULL, // type def
NULL))) // flags
{
pManifestModule->GetAssembly()->ThrowBadImageException(pszNameSpace, pszName, BFA_INVALID_TOKEN);
}
// Find entry for enclosing class - NOTE, this assumes that the
// enclosing class's ExportedType was inserted previously, which assumes that,
// when enuming ExportedTypes, we get the enclosing class first
EEClassHashEntry_t *pBucket;
EEClassHashTable::LookupContext sContext;
if ((pBucket = pManifestModule->GetAvailableClassHash()->GetValue(pszEnclosingNameSpace,
pszEnclosingName,
&ThrowawayData,
TypeFromToken(nextImpl) == mdtExportedType,
&sContext)) != NULL) {
do {
// check to see if this is the correct class
if (EEClassHashTable::UncompressModuleAndClassDef(ThrowawayData) == mdImpl) {
ThrowawayData = EEClassHashTable::CompressClassDef(cl);
// we explicitly don't check for the case insensitive hash table because we know it can't have been created yet
pManifestModule->GetAvailableClassHash()->InsertValue(pszNameSpace, pszName, ThrowawayData, pBucket, pamTracker);
}
pBucket = pManifestModule->GetAvailableClassHash()->FindNextNestedClass(pszEnclosingNameSpace, pszEnclosingName, &ThrowawayData, &sContext);
} while (pBucket);
}
// If the encloser is not in the hash table, this nested class
// was defined in the manifest module, so it doesn't need to be added
return;
}
else {
// Defined in the manifest module - add to the hash table by TypeDef instead
if (mdImpl == mdFileNil)
return;
// Don't add duplicate top-level classes
// In this hash table, if the lower bit is set, it means a Module, otherwise it means EEClass*
ThrowawayData = EEClassHashTable::CompressClassDef(cl);
// ThrowawayData is an IN OUT param. Going in its the pointer to the new value if the entry needs
// to be inserted. The OUT param points to the value stored in the hash table.
BOOL bFound;
pManifestModule->GetAvailableClassHash()->InsertValueIfNotFound(pszNameSpace, pszName, &ThrowawayData, NULL, FALSE, &bFound, pamTracker);
if (bFound) {
// Check for duplicate ExportedTypes
// Let it slide if it's pointing to the same type
mdToken foundTypeImpl;
if ((size_t)ThrowawayData & EECLASSHASH_MDEXPORT_DISCR)
{
mdExportedType foundExportedType = EEClassHashTable::UncompressModuleAndClassDef(ThrowawayData);
if (FAILED(pAsmImport->GetExportedTypeProps(
foundExportedType,
NULL, // namespace
NULL, // name
&foundTypeImpl,
NULL, // TypeDef
NULL))) // flags
{
pManifestModule->GetAssembly()->ThrowBadImageException(pszNameSpace, pszName, BFA_INVALID_TOKEN);
}
}
else
{
foundTypeImpl = mdFileNil;
}
if (mdImpl != foundTypeImpl)
{
pManifestModule->GetAssembly()->ThrowBadImageException(pszNameSpace, pszName, BFA_MULT_TYPE_SAME_NAME);
}
}
}
}
static MethodTable* GetEnclosingMethodTable(MethodTable *pMT)
{
CONTRACT(MethodTable*)
{
THROWS;
GC_TRIGGERS;
INJECT_FAULT(COMPlusThrowOM(););
MODE_ANY;
PRECONDITION(CheckPointer(pMT));
POSTCONDITION(RETVAL == NULL || RETVAL->IsTypicalTypeDefinition());
}
CONTRACT_END;
MethodTable *pmtEnclosing = NULL;
// In the common case, the method table will be either shared or in the AppDomain we're currently
// running in. If this is true, we can just access its enclosing method table directly.
//
// However, if the current method table is actually in another AppDomain (for instance, we're reflecting
// across AppDomains), then we cannot get its enclsoing type in our AppDomain since doing that may involve
// loading the enclosing type. Instead, we need to transition back to the original domain (which we
// should already be running in higher up on the stack) and get the method table we're looking for.
if (pMT->GetDomain()->IsSharedDomain() || pMT->GetDomain()->AsAppDomain() == GetAppDomain())
{
pmtEnclosing = pMT->LoadEnclosingMethodTable();
}
else
{
GCX_COOP();
ENTER_DOMAIN_PTR(pMT->GetDomain()->AsAppDomain(), ADV_RUNNINGIN);
pmtEnclosing = pMT->LoadEnclosingMethodTable();
END_DOMAIN_TRANSITION;
}
RETURN pmtEnclosing;
}
StaticAccessCheckContext::StaticAccessCheckContext(MethodDesc* pCallerMethod)
{
CONTRACTL
{
LIMITED_METHOD_CONTRACT;
PRECONDITION(CheckPointer(pCallerMethod));
}
CONTRACTL_END;
m_pCallerMethod = pCallerMethod;
m_pCallerMT = m_pCallerMethod->GetMethodTable();
m_pCallerAssembly = m_pCallerMT->GetAssembly();
}
StaticAccessCheckContext::StaticAccessCheckContext(MethodDesc* pCallerMethod, MethodTable* pCallerType)
{
CONTRACTL
{
LIMITED_METHOD_CONTRACT;
PRECONDITION(CheckPointer(pCallerMethod, NULL_OK));
PRECONDITION(CheckPointer(pCallerType));
}
CONTRACTL_END;
m_pCallerMethod = pCallerMethod;
m_pCallerMT = pCallerType;
m_pCallerAssembly = pCallerType->GetAssembly();
}
// Critical callers do not need the extra access checks
bool StaticAccessCheckContext::IsCallerCritical()
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
MODE_ANY;
}
CONTRACTL_END;
if (m_pCallerMethod == NULL || !Security::IsMethodTransparent(m_pCallerMethod))
{
return true;
}
return false;
}
//******************************************************************************
// static
AccessCheckOptions* AccessCheckOptions::s_pNormalAccessChecks;
//******************************************************************************
void AccessCheckOptions::Startup()
{
STANDARD_VM_CONTRACT;
s_pNormalAccessChecks = new AccessCheckOptions(
AccessCheckOptions::kNormalAccessibilityChecks,
NULL,
FALSE,
(MethodTable *)NULL);
}
//******************************************************************************
AccessCheckOptions::AccessCheckOptions(
const AccessCheckOptions & templateOptions,
BOOL throwIfTargetIsInaccessible,
BOOL skipCheckForCriticalCode /*=FALSE*/) :
m_pAccessContext(templateOptions.m_pAccessContext)
{
WRAPPER_NO_CONTRACT;
Initialize(
templateOptions.m_accessCheckType,
throwIfTargetIsInaccessible,
templateOptions.m_pTargetMT,
templateOptions.m_pTargetMethod,
templateOptions.m_pTargetField,
skipCheckForCriticalCode);
}
//******************************************************************************
// This function should only be called when normal accessibility is not possible.
// It returns TRUE if the target can be accessed.
// Otherwise, it either returns FALSE or throws an exception, depending on the value of throwIfTargetIsInaccessible.
BOOL AccessCheckOptions::DemandMemberAccess(AccessCheckContext *pContext, MethodTable * pTargetMT, BOOL visibilityCheck) const
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
MODE_ANY;
PRECONDITION(m_accessCheckType != kNormalAccessibilityChecks);
PRECONDITION(CheckPointer(pContext));
}
CONTRACTL_END;
_ASSERTE(m_accessCheckType != kNormalAccessibilityChecks);
if (NingenEnabled())
{
// NinGen should always perform normal accessibility checks
_ASSERTE(false);
if (m_fThrowIfTargetIsInaccessible)
{
ThrowAccessException(pContext, pTargetMT, NULL, FALSE);
}
return FALSE;
}
if (pTargetMT && pTargetMT->GetAssembly()->IsDisabledPrivateReflection())
{
if (m_fThrowIfTargetIsInaccessible)
{
ThrowAccessException(pContext, pTargetMT, NULL, FALSE);
}
return FALSE;
}
BOOL canAccessTarget = FALSE;
#ifndef CROSSGEN_COMPILE
BOOL fAccessingFrameworkCode = FALSE;
// In CoreCLR kRestrictedMemberAccess means that one can access private/internal
// classes/members in app code.
if (m_accessCheckType != kMemberAccess && pTargetMT)
{
// m_accessCheckType must be kRestrictedMemberAccess if we are running in PT.
_ASSERTE(GetAppDomain()->GetSecurityDescriptor()->IsFullyTrusted() ||
m_accessCheckType == kRestrictedMemberAccess);
if (visibilityCheck && Security::IsTransparencyEnforcementEnabled())
{
// In CoreCLR RMA means visibility checks always succeed if the target is user code.
if (m_accessCheckType == kRestrictedMemberAccess || m_accessCheckType == kRestrictedMemberAccessNoTransparency)
return TRUE;
// Accessing private types/members in platform code.
fAccessingFrameworkCode = TRUE;
}
else
{
// We allow all transparency checks to succeed in LCG methods and reflection invocation.
if (m_accessCheckType == kNormalAccessNoTransparency || m_accessCheckType == kRestrictedMemberAccessNoTransparency)
return TRUE;
}
}
// Always allow interop (NULL) callers full access.
if (pContext->IsCalledFromInterop())
return TRUE;
MethodDesc* pCallerMD = pContext->GetCallerMethod();
// critical code is exempted from all accessibility rules, regardless of the AccessCheckType.
if (pCallerMD != NULL &&
!Security::IsMethodTransparent(pCallerMD))
{
return TRUE;
}
// No Access
if (m_fThrowIfTargetIsInaccessible)
{
ThrowAccessException(pContext, pTargetMT, NULL, fAccessingFrameworkCode);
}
#endif // CROSSGEN_COMPILE
return canAccessTarget;
}
//******************************************************************************
// pFailureMT - the MethodTable that we were trying to access. It can be null
// if the failure is not because of a specific type. This will be a
// a component of the instantiation of m_pTargetMT/m_pTargetMethod/m_pTargetField.
void AccessCheckOptions::ThrowAccessException(
AccessCheckContext* pContext,
MethodTable* pFailureMT, /* = NULL */
Exception* pInnerException, /* = NULL */
BOOL fAccessingFrameworkCode /* = FALSE */) const
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
MODE_ANY;
PRECONDITION(CheckPointer(pContext));
PRECONDITION(CheckPointer(pInnerException, NULL_OK));
PRECONDITION(m_fThrowIfTargetIsInaccessible);
}
CONTRACTL_END;
GCX_COOP();
MethodDesc* pCallerMD = pContext->GetCallerMethod();
if (m_pTargetMT != NULL)
{
// If we know the specific type that caused the failure, display it.
// Else display the whole type that we are trying to access.
MethodTable * pMT = (pFailureMT != NULL) ? pFailureMT : m_pTargetMT;
ThrowTypeAccessException(pContext, pMT, 0, pInnerException, fAccessingFrameworkCode);
}
else if (m_pTargetMethod != NULL)
{
// If the caller and target method are non-null and the same, then this means that we're checking to see
// if the method has access to itself in order to validate that it has access to its parameter types,
// containing type, and return type. In this case, throw a more informative TypeAccessException to
// describe the error that occurred (for instance, "this method doesn't have access to one of its
// parameter types", rather than "this method doesn't have access to itself").
// We only want to do this if we know the exact type that caused the problem, otherwise fall back to
// throwing the standard MethodAccessException.
if (pCallerMD != NULL && m_pTargetMethod == pCallerMD && pFailureMT != NULL)
{
ThrowTypeAccessException(pContext, pFailureMT, 0, pInnerException, fAccessingFrameworkCode);
}
else
{
ThrowMethodAccessException(pContext, m_pTargetMethod, 0, pInnerException, fAccessingFrameworkCode);
}
}
else
{
_ASSERTE(m_pTargetField != NULL);
ThrowFieldAccessException(pContext, m_pTargetField, 0, pInnerException, fAccessingFrameworkCode);
}
}
//******************************************************************************
// This will do a security demand if appropriate.
// If access is not possible, this will either throw an exception or return FALSE
BOOL AccessCheckOptions::DemandMemberAccessOrFail(AccessCheckContext *pContext, MethodTable * pTargetMT, BOOL visibilityCheck) const
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
MODE_ANY;
}
CONTRACTL_END;
// m_fSkipCheckForCriticalCode is only ever set to true for CanAccessMemberForExtraChecks.
// For legacy compat we allow the access check to succeed for all AccessCheckType if the caller is critical.
if (m_fSkipCheckForCriticalCode)
{
if (pContext->IsCalledFromInterop() ||
!Security::IsMethodTransparent(pContext->GetCallerMethod()))
return TRUE;
}
if (DoNormalAccessibilityChecks())
{
if (pContext->GetCallerAssembly()->IgnoresAccessChecksTo(pTargetMT->GetAssembly()))
{
return TRUE;
}
if (m_fThrowIfTargetIsInaccessible)
{
ThrowAccessException(pContext, pTargetMT);
}
return FALSE;
}
return DemandMemberAccess(pContext, pTargetMT, visibilityCheck);
}
//******************************************************************************
// This should be called if access to the target is not possible.
// This will either throw an exception or return FALSE.
BOOL AccessCheckOptions::FailOrThrow(AccessCheckContext *pContext) const
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
MODE_ANY;
PRECONDITION(CheckPointer(pContext));
}
CONTRACTL_END;
// m_fSkipCheckForCriticalCode is only ever set to true for CanAccessMemberForExtraChecks.
// For legacy compat we allow the access check to succeed for all AccessCheckType if the caller is critical.
if (m_fSkipCheckForCriticalCode)
{
if (pContext->IsCalledFromInterop() ||
!Security::IsMethodTransparent(pContext->GetCallerMethod()))
return TRUE;
}
if (m_fThrowIfTargetIsInaccessible)
{
ThrowAccessException(pContext);
}
return FALSE;
}
// Generate access exception context strings that are due to potential security misconfiguration
void GetAccessExceptionAdditionalContextForSecurity(Assembly *pAccessingAssembly,
Assembly *pTargetAssembly,
BOOL isTransparencyError,
BOOL fAccessingFrameworkCode,
StringArrayList *pContextInformation)
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
MODE_ANY;
PRECONDITION(CheckPointer(pAccessingAssembly));
PRECONDITION(CheckPointer(pTargetAssembly));
PRECONDITION(CheckPointer(pContextInformation));
}
CONTRACTL_END;
if (fAccessingFrameworkCode)
{
SString accessingFrameworkCodeError;
EEException::GetResourceMessage(IDS_E_ACCESSING_PRIVATE_FRAMEWORK_CODE, accessingFrameworkCodeError);
pContextInformation->Append(accessingFrameworkCodeError);
}
}
// Generate additional context about the root cause of an access exception which may help in debugging it (for
// instance v4 APTCA implying transparnecy, or conditional APTCA not being enabled). If no additional
// context is available, then this returns SString.Empty.
SString GetAdditionalAccessExceptionContext(Assembly *pAccessingAssembly,
Assembly *pTargetAssembly,
BOOL isTransparencyError,
BOOL fAccessingFrameworkCode)
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
MODE_ANY;
PRECONDITION(CheckPointer(pAccessingAssembly));
PRECONDITION(CheckPointer(pTargetAssembly));
}
CONTRACTL_END;
StringArrayList contextComponents;
// See if the exception may have been caused by security
GetAccessExceptionAdditionalContextForSecurity(pAccessingAssembly,
pTargetAssembly,
isTransparencyError,
fAccessingFrameworkCode,
&contextComponents);
// Append each component of additional context we found into the additional context string in its own
// paragraph.
SString additionalContext;
for (DWORD i = 0; i < contextComponents.GetCount(); ++i)
{
SString contextComponent = contextComponents.Get(i);
if (!contextComponent.IsEmpty())
{
additionalContext.Append(W("\n\n"));
additionalContext.Append(contextComponent);
}
}
return additionalContext;
}
void DECLSPEC_NORETURN ThrowFieldAccessException(AccessCheckContext* pContext,
FieldDesc *pFD,
UINT messageID /* = 0 */,
Exception *pInnerException /* = NULL */,
BOOL fAccessingFrameworkCode /* = FALSE */)
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
MODE_ANY;
PRECONDITION(CheckPointer(pContext));
PRECONDITION(CheckPointer(pFD));
}
CONTRACTL_END;
BOOL isTransparencyError = FALSE;
MethodDesc* pCallerMD = pContext->GetCallerMethod();
if (pCallerMD != NULL)
isTransparencyError = !Security::CheckCriticalAccess(pContext, NULL, pFD, NULL);
ThrowFieldAccessException(pCallerMD,
pFD,
isTransparencyError,
messageID,
pInnerException,
fAccessingFrameworkCode);
}
void DECLSPEC_NORETURN ThrowFieldAccessException(MethodDesc* pCallerMD,
FieldDesc *pFD,
BOOL isTransparencyError,
UINT messageID /* = 0 */,
Exception *pInnerException /* = NULL */,
BOOL fAccessingFrameworkCode /* = FALSE */)
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
MODE_ANY;
PRECONDITION(CheckPointer(pCallerMD, NULL_OK));
PRECONDITION(CheckPointer(pFD));
}
CONTRACTL_END;
if (pCallerMD != NULL)
{
if (messageID == 0)
{
// Figure out if we can give a specific reason why this field access was rejected - for instance, if
// we see that the caller is transparent and accessing a critical field, then we can put that
// information into the exception message.
if (isTransparencyError)
{
messageID = IDS_E_CRITICAL_FIELD_ACCESS_DENIED;
}
else
{
messageID = IDS_E_FIELDACCESS;
}
}
SString strAdditionalContext = GetAdditionalAccessExceptionContext(pCallerMD->GetAssembly(),
pFD->GetApproxEnclosingMethodTable()->GetAssembly(),
isTransparencyError,
fAccessingFrameworkCode);
EX_THROW_WITH_INNER(EEFieldException, (pFD, pCallerMD, strAdditionalContext, messageID), pInnerException);
}
else
{
EX_THROW_WITH_INNER(EEFieldException, (pFD), pInnerException);
}
}
void DECLSPEC_NORETURN ThrowMethodAccessException(AccessCheckContext* pContext,
MethodDesc *pCalleeMD,
UINT messageID /* = 0 */,
Exception *pInnerException /* = NULL */,
BOOL fAccessingFrameworkCode /* = FALSE */)
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
MODE_ANY;
PRECONDITION(CheckPointer(pContext));
PRECONDITION(CheckPointer(pCalleeMD));
}
CONTRACTL_END;
BOOL isTransparencyError = FALSE;
MethodDesc* pCallerMD = pContext->GetCallerMethod();
if (pCallerMD != NULL)
isTransparencyError = !Security::CheckCriticalAccess(pContext, pCalleeMD, NULL, NULL);
ThrowMethodAccessException(pCallerMD,
pCalleeMD,
isTransparencyError,
messageID,
pInnerException,
fAccessingFrameworkCode);
}
void DECLSPEC_NORETURN ThrowMethodAccessException(MethodDesc* pCallerMD,
MethodDesc *pCalleeMD,
BOOL isTransparencyError,
UINT messageID /* = 0 */,
Exception *pInnerException /* = NULL */,
BOOL fAccessingFrameworkCode /* = FALSE */)
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
MODE_ANY;
PRECONDITION(CheckPointer(pCallerMD, NULL_OK));
PRECONDITION(CheckPointer(pCalleeMD));
}
CONTRACTL_END;
if (pCallerMD != NULL)
{
if (messageID == 0)
{
// Figure out if we can give a specific reason why this method access was rejected - for instance, if
// we see that the caller is transparent and the callee is critical, then we can put that
// information into the exception message.
if (isTransparencyError)
{
messageID = IDS_E_CRITICAL_METHOD_ACCESS_DENIED;
}
else
{
messageID = IDS_E_METHODACCESS;
}
}
SString strAdditionalContext = GetAdditionalAccessExceptionContext(pCallerMD->GetAssembly(),
pCalleeMD->GetAssembly(),
isTransparencyError,
fAccessingFrameworkCode);
EX_THROW_WITH_INNER(EEMethodException, (pCalleeMD, pCallerMD, strAdditionalContext, messageID), pInnerException);
}
else
{
EX_THROW_WITH_INNER(EEMethodException, (pCalleeMD), pInnerException);
}
}
void DECLSPEC_NORETURN ThrowTypeAccessException(AccessCheckContext* pContext,
MethodTable *pMT,
UINT messageID /* = 0 */,
Exception *pInnerException /* = NULL */,
BOOL fAccessingFrameworkCode /* = FALSE */)
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
MODE_ANY;
PRECONDITION(CheckPointer(pContext));
PRECONDITION(CheckPointer(pMT));
}
CONTRACTL_END;
BOOL isTransparencyError = FALSE;
MethodDesc* pCallerMD = pContext->GetCallerMethod();
if (pCallerMD != NULL)
isTransparencyError = !Security::CheckCriticalAccess(pContext, NULL, NULL, pMT);
ThrowTypeAccessException(pCallerMD,
pMT,
isTransparencyError,
messageID,
pInnerException,
fAccessingFrameworkCode);
}
void DECLSPEC_NORETURN ThrowTypeAccessException(MethodDesc* pCallerMD,
MethodTable *pMT,
BOOL isTransparencyError,
UINT messageID /* = 0 */,
Exception *pInnerException /* = NULL */,
BOOL fAccessingFrameworkCode /* = FALSE */)
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
MODE_ANY;
PRECONDITION(CheckPointer(pCallerMD, NULL_OK));
PRECONDITION(CheckPointer(pMT));
}
CONTRACTL_END;
if (pCallerMD != NULL)
{
if (messageID == 0)
{
// Figure out if we can give a specific reason why this type access was rejected - for instance, if
// we see that the caller is transparent and is accessing a critical type, then we can put that
// information into the exception message.
if (isTransparencyError)
{
messageID = IDS_E_CRITICAL_TYPE_ACCESS_DENIED;
}
else
{
messageID = IDS_E_TYPEACCESS;
}
}
SString strAdditionalContext = GetAdditionalAccessExceptionContext(pCallerMD->GetAssembly(),
pMT->GetAssembly(),
isTransparencyError,
fAccessingFrameworkCode);
EX_THROW_WITH_INNER(EETypeAccessException, (pMT, pCallerMD, strAdditionalContext, messageID), pInnerException);
}
else
{
EX_THROW_WITH_INNER(EETypeAccessException, (pMT), pInnerException);
}
}
//******************************************************************************
// This function determines whether a method [if transparent]
// can access a specified target (e.g. Type, Method, Field)
static BOOL CheckTransparentAccessToCriticalCode(
AccessCheckContext* pContext,
DWORD dwMemberAccess,
MethodTable* pTargetMT,
MethodDesc* pOptionalTargetMethod,
FieldDesc* pOptionalTargetField,
MethodTable* pOptionalTargetType,
const AccessCheckOptions & accessCheckOptions)
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
MODE_ANY;
PRECONDITION(CheckPointer(pContext));
PRECONDITION(accessCheckOptions.TransparencyCheckNeeded());
}
CONTRACTL_END;
if (!Security::IsTransparencyEnforcementEnabled())
return TRUE;
// At most one of these should be non-NULL
_ASSERTE(1 >= ((pOptionalTargetMethod ? 1 : 0) +
(pOptionalTargetField ? 1 : 0) +
(pOptionalTargetType ? 1 : 0)));
// if the caller [Method] is transparent, do special security checks
// check if security disallows access to target member
if (!Security::CheckCriticalAccess(
pContext,
pOptionalTargetMethod,
pOptionalTargetField,
pOptionalTargetType))
{
#ifdef _DEBUG
if (g_pConfig->LogTransparencyErrors())
{
SecurityTransparent::LogTransparencyError(pContext->GetCallerMethod(), "Transparent code accessing a critical type, method, or field", pOptionalTargetMethod);
}
#endif // _DEBUG
return accessCheckOptions.DemandMemberAccessOrFail(pContext, pTargetMT, FALSE /*visibilityCheck*/);
}
return TRUE;
} // static BOOL CheckTransparentAccessToCriticalCode
//---------------------------------------------------------------------------------------
//
// Checks to see if access to a member with assembly visiblity is allowed.
//
// Arguments:
// pAccessingAssembly - The assembly requesting access to the internal member
// pTargetAssembly - The assembly which contains the target member
// pOptionalTargetField - Internal field being accessed OR
// pOptionalTargetMethod - Internal type being accessed OR
// pOptionalTargetType - Internal type being accessed
//
// Return Value:
// TRUE if pTargetAssembly is pAccessingAssembly, or if pTargetAssembly allows
// pAccessingAssembly friend access to the target. FALSE otherwise.
//
static BOOL AssemblyOrFriendAccessAllowed(Assembly *pAccessingAssembly,
Assembly *pTargetAssembly,
FieldDesc *pOptionalTargetField,
MethodDesc *pOptionalTargetMethod,
MethodTable *pOptionalTargetType)
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
PRECONDITION(CheckPointer(pAccessingAssembly));
PRECONDITION(CheckPointer(pTargetAssembly));
PRECONDITION(pOptionalTargetField != NULL || pOptionalTargetMethod != NULL || pOptionalTargetType != NULL);
PRECONDITION(pOptionalTargetField == NULL || pOptionalTargetMethod == NULL);
}
CONTRACTL_END;
if (pAccessingAssembly == pTargetAssembly)
{
return TRUE;
}
if (pAccessingAssembly->IgnoresAccessChecksTo(pTargetAssembly))
{
return TRUE;
}
#if defined(FEATURE_REMOTING) && !defined(CROSSGEN_COMPILE)
else if (pAccessingAssembly->GetDomain() != pTargetAssembly->GetDomain() &&
pAccessingAssembly->GetFusionAssemblyName()->IsEqual(pTargetAssembly->GetFusionAssemblyName(), ASM_CMPF_NAME | ASM_CMPF_PUBLIC_KEY_TOKEN) == S_OK)
{
// If we're accessing an internal type across AppDomains, we'll end up saying that an assembly is
// not allowed to access internal types in itself, since the Assembly *'s will not compare equal.
// This ends up being confusing for users who don't have a deep understanding of the loader and type
// system, and also creates different behavior if your assembly is shared vs unshared (if you are
// shared, your Assembly *'s will match since they're in the shared domain).
//
// In order to ease the confusion, we'll consider assemblies to be friends of themselves in this
// scenario -- if a name and public key match succeeds, we'll grant internal access across domains.
return TRUE;
}
#endif // FEATURE_REMOTING && !CROSSGEN_COMPILE
else if (pOptionalTargetField != NULL)
{
return pTargetAssembly->GrantsFriendAccessTo(pAccessingAssembly, pOptionalTargetField);
}
else if (pOptionalTargetMethod != NULL)
{
return pTargetAssembly->GrantsFriendAccessTo(pAccessingAssembly, pOptionalTargetMethod);
}
else
{
return pTargetAssembly->GrantsFriendAccessTo(pAccessingAssembly, pOptionalTargetType);
}
}
//******************************************************************************
// This function determines whether a target class is accessible from
// some given class.
/* static */
BOOL ClassLoader::CanAccessMethodInstantiation( // True if access is legal, false otherwise.
AccessCheckContext* pContext,
MethodDesc* pOptionalTargetMethod, // The desired method; if NULL, return TRUE (or)
const AccessCheckOptions & accessCheckOptions)
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
INJECT_FAULT(COMPlusThrowOM(););
MODE_ANY;
PRECONDITION(CheckPointer(pContext));
}
CONTRACTL_END
// If there is no target method just allow access.
// NB: the caller may just be checking access to a field or class, so we allow for NULL.
if (!pOptionalTargetMethod)
return TRUE;
// Is the desired target an instantiated generic method?
if (pOptionalTargetMethod->HasMethodInstantiation())
{ // check that the current class has access
// to all of the instantiating classes.
Instantiation inst = pOptionalTargetMethod->GetMethodInstantiation();
for (DWORD i = 0; i < inst.GetNumArgs(); i++)
{
TypeHandle th = inst[i];
MethodTable* pMT = th.GetMethodTableOfElementType();
// Either a TypeVarTypeDesc or a FnPtrTypeDesc. No access check needed.
if (pMT == NULL)
continue;
if (!CanAccessClass(
pContext,
pMT,
th.GetAssembly(),
accessCheckOptions))
{
return FALSE;
}
}
// If we are here, the current class has access to all of the target's instantiating args,
}
return TRUE;
}
//******************************************************************************
// This function determines whether a target class is accessible from
// some given class.
// CanAccessClass does the following checks:
// 1. Transparency check on the target class
// 2. Recursively calls CanAccessClass on the generic arguments of the target class if it is generic.
// 3. Visibility check on the target class, if the target class is nested, this will be translated
// to a member access check on the enclosing type (calling CanAccess with appropriate dwProtection.
//
/* static */
BOOL ClassLoader::CanAccessClass( // True if access is legal, false otherwise.
AccessCheckContext* pContext, // The caller context
MethodTable* pTargetClass, // The desired target class.
Assembly* pTargetAssembly, // Assembly containing the target class.
const AccessCheckOptions & accessCheckOptions,
BOOL checkTargetTypeTransparency)// = TRUE
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
INJECT_FAULT(COMPlusThrowOM(););
MODE_ANY;
PRECONDITION(CheckPointer(pContext));
PRECONDITION(CheckPointer(pTargetClass));
}
CONTRACTL_END
// If there is no target class, allow access.
// @todo: what does that mean?
//if (!pTargetClass)
// return TRUE;
// check transparent/critical on type
// Note that dwMemberAccess is of no use here since we don't have a target method yet. It really should be made an optional arg.
// For now, we pass in mdPublic.
if (checkTargetTypeTransparency && accessCheckOptions.TransparencyCheckNeeded())
{
if (!CheckTransparentAccessToCriticalCode(
pContext,
mdPublic,
pTargetClass,
NULL,
NULL,
pTargetClass,
accessCheckOptions))
{
// no need to call accessCheckOptions.DemandMemberAccessOrFail here because
// CheckTransparentAccessToCriticalCode does that already
return FALSE;
}
}
// Step 2: Recursively call CanAccessClass on the generic type arguments
// Is the desired target a generic instantiation?
if (pTargetClass->HasInstantiation())
{ // Yes, so before going any further, check that the current class has access
// to all of the instantiating classes.
Instantiation inst = pTargetClass->GetInstantiation();
for (DWORD i = 0; i < inst.GetNumArgs(); i++)
{
TypeHandle th = inst[i];
MethodTable* pMT = th.GetMethodTableOfElementType();
// Either a TypeVarTypeDesc or a FnPtrTypeDesc. No access check needed.
if (pMT == NULL)
continue;
if (!CanAccessClass(
pContext,
pMT,
th.GetAssembly(),
accessCheckOptions,
checkTargetTypeTransparency))
{
// no need to call accessCheckOptions.DemandMemberAccessOrFail here because the base case in
// CanAccessClass does that already
return FALSE;
}
}
// If we are here, the current class has access to all of the desired target's instantiating args.
// Now, check whether the current class has access to the desired target itself.
}
// Step 3: Visibility Check
if (!pTargetClass->GetClass()->IsNested())
{ // a non-nested class can be either all public or accessible only from its own assembly (and friends).
if (IsTdPublic(pTargetClass->GetClass()->GetProtection()))
{
return TRUE;
}
else
{
// Always allow interop callers full access.
if (pContext->IsCalledFromInterop())
return TRUE;
Assembly* pCurrentAssembly = pContext->GetCallerAssembly();
_ASSERTE(pCurrentAssembly != NULL);
if (AssemblyOrFriendAccessAllowed(pCurrentAssembly,
pTargetAssembly,
NULL,
NULL,
pTargetClass))
{
return TRUE;
}
else
{
return accessCheckOptions.DemandMemberAccessOrFail(pContext, pTargetClass, TRUE /*visibilityCheck*/);
}
}
}
// If we are here, the desired target class is nested. Translate the type flags
// to corresponding method access flags. We need to make a note if friend access was allowed to the
// type being checked since we're not passing it directly to the recurisve call to CanAccess, and
// instead are just passing in the dwProtectionFlags.
DWORD dwProtection = pTargetClass->GetClass()->GetProtection();
switch(dwProtection) {
case tdNestedPublic:
dwProtection = mdPublic;
break;
case tdNestedFamily:
dwProtection = mdFamily;
break;
case tdNestedPrivate:
dwProtection = mdPrivate;
break;
case tdNestedFamORAssem:
// If we can access the class because we have assembly or friend access, we have satisfied the
// FamORAssem accessibility, so we we can simplify it down to public. Otherwise we require that
// family access be allowed to grant access.
case tdNestedFamANDAssem:
// If we don't grant assembly or friend access to the target class, then there is no way we
// could satisfy the FamANDAssem requirement. Otherwise, since we have satsified the Assm
// portion, we only need to check for the Fam portion.
case tdNestedAssembly:
// If we don't grant assembly or friend access to the target class, and that class has assembly
// protection, we can fail the request now. Otherwise we can check to make sure a public member
// of the outer class is allowed, since we have satisfied the target's accessibility rules.
// Always allow interop callers full access.
if (pContext->IsCalledFromInterop())
return TRUE;
if (AssemblyOrFriendAccessAllowed(pContext->GetCallerAssembly(), pTargetAssembly, NULL, NULL, pTargetClass))
dwProtection = (dwProtection == tdNestedFamANDAssem) ? mdFamily : mdPublic;
else if (dwProtection == tdNestedFamORAssem)
dwProtection = mdFamily;
else
return accessCheckOptions.DemandMemberAccessOrFail(pContext, pTargetClass, TRUE /*visibilityCheck*/);
break;
default:
THROW_BAD_FORMAT_MAYBE(!"Unexpected class visibility flag value", BFA_BAD_VISIBILITY, pTargetClass);
}
// The desired target class is nested, so translate the class access request into
// a member access request. That is, if the current class is trying to access A::B,
// check if it can access things in A with the visibility of B.
// So, pass A as the desired target class and visibility of B within A as the member access
// We've already done transparency check above. No need to do it again.
return ClassLoader::CanAccess(
pContext,
GetEnclosingMethodTable(pTargetClass),
pTargetAssembly,
dwProtection,
NULL,
NULL,
accessCheckOptions,
FALSE,
FALSE);
} // BOOL ClassLoader::CanAccessClass()
//******************************************************************************
// This is a front-end to CheckAccessMember that handles the nested class scope. If can't access
// from the current point and are a nested class, then try from the enclosing class.
// It does two things in addition to CanAccessMember:
// 1. If the caller class doesn't have access to the caller, see if the enclosing class does.
// 2. CanAccessMemberForExtraChecks which checks whether the caller class has access to
// the signature of the target method or field.
//
// checkTargetMethodTransparency is set to FALSE only when the check is for JIT-compilation
// because the JIT has a mechanism to insert a callout for the case where
// we need to perform the currentMD <-> TargetMD check at runtime.
/* static */
BOOL ClassLoader::CanAccess( // TRUE if access is allowed, FALSE otherwise.
AccessCheckContext* pContext, // The caller context
MethodTable* pTargetMT, // The class containing the desired target member.
Assembly* pTargetAssembly, // Assembly containing that class.
DWORD dwMemberAccess, // Member access flags of the desired target member (as method bits).
MethodDesc* pOptionalTargetMethod, // The target method; NULL if the target is a not a method or
// there is no need to check the method's instantiation.
FieldDesc* pOptionalTargetField, // or The desired field; if NULL, return TRUE
const AccessCheckOptions & accessCheckOptions, // = s_NormalAccessChecks
BOOL checkTargetMethodTransparency, // = TRUE
BOOL checkTargetTypeTransparency) // = TRUE
{
CONTRACT(BOOL)
{
THROWS;
GC_TRIGGERS;
INJECT_FAULT(COMPlusThrowOM(););
PRECONDITION(CheckPointer(pContext));
MODE_ANY;
}
CONTRACT_END;
// Recursive: CanAccess->CheckAccessMember->CanAccessClass->CanAccess
INTERIOR_STACK_PROBE(GetThread());
AccessCheckOptions accessCheckOptionsNoThrow(accessCheckOptions, FALSE);
if (!CheckAccessMember(pContext,
pTargetMT,
pTargetAssembly,
dwMemberAccess,
pOptionalTargetMethod,
pOptionalTargetField,
// Suppress exceptions for nested classes since this is not a hard-failure,
// and we can do additional checks
accessCheckOptionsNoThrow,
checkTargetMethodTransparency,
checkTargetTypeTransparency))
{
// If we're here, CheckAccessMember didn't allow access.
BOOL canAccess = FALSE;
// If the current class is nested, there may be an enclosing class that might have access
// to the target. And if the pCurrentMT == NULL, the current class is global, and so there
// is no enclosing class.
MethodTable* pCurrentMT = pContext->GetCallerMT();
// if this is called from interop, the CheckAccessMember call above should have already succeeded.
_ASSERTE(!pContext->IsCalledFromInterop());
BOOL isNestedClass = (pCurrentMT && pCurrentMT->GetClass()->IsNested());
if (isNestedClass)
{
// A nested class also has access to anything that the enclosing class does, so
// recursively check whether the enclosing class can access the desired target member.
MethodTable * pEnclosingMT = GetEnclosingMethodTable(pCurrentMT);
StaticAccessCheckContext accessContext(pContext->GetCallerMethod(),
pEnclosingMT,
pContext->GetCallerAssembly());
// On failure, do not throw from inside this call since that will cause the exception message
// to refer to the enclosing type.
canAccess = ClassLoader::CanAccess(
&accessContext,
pTargetMT,
pTargetAssembly,
dwMemberAccess,
pOptionalTargetMethod,
pOptionalTargetField,
accessCheckOptionsNoThrow,
checkTargetMethodTransparency,
checkTargetTypeTransparency);
}
if (!canAccess)
{
BOOL fail = accessCheckOptions.FailOrThrow(pContext);
RETURN_FROM_INTERIOR_PROBE(fail);
}
}
// For member access, we do additional checks to ensure that the specific member can
// be accessed
if (!CanAccessMemberForExtraChecks(
pContext,
pTargetMT,
pOptionalTargetMethod,
pOptionalTargetField,
accessCheckOptions,
checkTargetMethodTransparency))
{
RETURN_FROM_INTERIOR_PROBE(FALSE);
}
RETURN_FROM_INTERIOR_PROBE(TRUE);
END_INTERIOR_STACK_PROBE;
} // BOOL ClassLoader::CanAccess()
//******************************************************************************
// Performs additional checks for member access
BOOL ClassLoader::CanAccessMemberForExtraChecks(
AccessCheckContext* pContext,
MethodTable* pTargetExactMT,
MethodDesc* pOptionalTargetMethod,
FieldDesc* pOptionalTargetField,
const AccessCheckOptions & accessCheckOptions,
BOOL checkTargetMethodTransparency)
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
MODE_ANY;
PRECONDITION(CheckPointer(pContext));
}
CONTRACTL_END;
// Critical callers do not need the extra checks
// This early-out saves the cost of all the subsequent work
if (pContext->IsCallerCritical())
{
return TRUE;
}
if (pOptionalTargetMethod == NULL && pOptionalTargetField == NULL)
return TRUE;
_ASSERTE((pOptionalTargetMethod == NULL) != (pOptionalTargetField == NULL));
// We should always do checks on member signatures. But for backward compatibility we skip this check
// for critical callers. And since we don't want to look for the caller here which might incur a stack walk,
// we delay the check to DemandMemberAccessOrFail time.
AccessCheckOptions legacyAccessCheckOptions(accessCheckOptions, accessCheckOptions.Throws(), TRUE);
if (pOptionalTargetMethod)
{
// A method is accessible only if all the types in the signature
// are also accessible.
if (!CanAccessSigForExtraChecks(pContext,
pOptionalTargetMethod,
pTargetExactMT,
legacyAccessCheckOptions,
checkTargetMethodTransparency))
{
return FALSE;
}
}
else
{
_ASSERTE(pOptionalTargetField != NULL);
// A field is accessible only if the field type is also accessible
TypeHandle fieldType = pOptionalTargetField->GetExactFieldType(TypeHandle(pTargetExactMT));
CorElementType fieldCorType = fieldType.GetSignatureCorElementType();
MethodTable * pFieldTypeMT = fieldType.GetMethodTableOfElementType();
// No access check needed on a generic variable or a function pointer
if (pFieldTypeMT != NULL)
{
if (!CanAccessClassForExtraChecks(pContext,
pFieldTypeMT,
pFieldTypeMT->GetAssembly(),
legacyAccessCheckOptions,
TRUE))
{
return FALSE;
}
}
}
return TRUE;
}
//******************************************************************************
// Can all the types in the signature of the pTargetMethodSig be accessed?
//
// "ForExtraChecks" means that we only do extra checks (security and transparency)
// instead of the usual loader visibility checks. Post V2, we can enable all checks.
BOOL ClassLoader::CanAccessSigForExtraChecks( // TRUE if access is allowed, FALSE otherwise.
AccessCheckContext* pContext,
MethodDesc* pTargetMethodSig, // The target method. If this is a shared method, pTargetExactMT gives
// additional information about the exact type
MethodTable* pTargetExactMT, // or The desired field; if NULL, return TRUE
const AccessCheckOptions & accessCheckOptions,
BOOL checkTargetTransparency)
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
MODE_ANY;
PRECONDITION(CheckPointer(pContext));
}
CONTRACTL_END;
MetaSig sig(pTargetMethodSig, TypeHandle(pTargetExactMT));
// First, check the return type
TypeHandle retType = sig.GetRetTypeHandleThrowing();
MethodTable * pRetMT = retType.GetMethodTableOfElementType();
// No access check needed on a generic variable or a function pointer
if (pRetMT != NULL)
{
if (!CanAccessClassForExtraChecks(pContext,
pRetMT,
retType.GetAssembly(),
accessCheckOptions,
checkTargetTransparency))
{
return FALSE;
}
}
//
// Now walk all the arguments in the signature
//
for (CorElementType argType = sig.NextArg(); argType != ELEMENT_TYPE_END; argType = sig.NextArg())
{
TypeHandle thArg = sig.GetLastTypeHandleThrowing();
MethodTable * pArgMT = thArg.GetMethodTableOfElementType();
// Either a TypeVarTypeDesc or a FnPtrTypeDesc. No access check needed.
if (pArgMT == NULL)
continue;
BOOL canAcesssElement = CanAccessClassForExtraChecks(
pContext,
pArgMT,
thArg.GetAssembly(),
accessCheckOptions,
checkTargetTransparency);
if (!canAcesssElement)
{
return FALSE;
}
}
return TRUE;
}
//******************************************************************************
// Can the type be accessed?
//
// "ForExtraChecks" means that we only do extra checks (security and transparency)
// instead of the usual loader visibility checks. Post V2, we can enable all checks.
BOOL ClassLoader::CanAccessClassForExtraChecks( // True if access is legal, false otherwise.
AccessCheckContext* pContext,
MethodTable* pTargetClass, // The desired target class.
Assembly* pTargetAssembly, // Assembly containing that class.
const AccessCheckOptions & accessCheckOptions,
BOOL checkTargetTypeTransparency)
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
MODE_ANY;
PRECONDITION(CheckPointer(pContext));
}
CONTRACTL_END;
// ------------- Old comments begins ------------
// Critical callers do not need the extra checks
// TODO: can we enable full access checks now?
// ------------- Old comments ends ------------
// We shouldn't bypass accessibility check on member signature for FT/Critical callers
return CanAccessClass(pContext,
pTargetClass,
pTargetAssembly,
accessCheckOptions,
checkTargetTypeTransparency);
}
//******************************************************************************
// This is the helper function for the corresponding CanAccess()
// It does the following checks:
// 1. CanAccessClass on pTargetMT
// 2. CanAccessMethodInstantiation if the pOptionalTargetMethod is provided and is generic.
// 3. Transparency check on pTargetMT, pOptionalTargetMethod and pOptionalTargetField.
// 4. Visibility check on dwMemberAccess (on pTargetMT)
/* static */
BOOL ClassLoader::CheckAccessMember( // TRUE if access is allowed, false otherwise.
AccessCheckContext* pContext,
MethodTable* pTargetMT, // The class containing the desired target member.
Assembly* pTargetAssembly, // Assembly containing that class.
DWORD dwMemberAccess, // Member access flags of the desired target member (as method bits).
MethodDesc* pOptionalTargetMethod, // The target method; NULL if the target is a not a method or
// there is no need to check the method's instantiation.
FieldDesc* pOptionalTargetField, // target field, NULL if there is no Target field
const AccessCheckOptions & accessCheckOptions,
BOOL checkTargetMethodTransparency,
BOOL checkTargetTypeTransparency
)
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
INJECT_FAULT(COMPlusThrowOM(););
PRECONDITION(CheckPointer(pContext));
MODE_ANY;
}
CONTRACTL_END
// we're trying to access a member that is contained in the class pTargetClass, so need to
// check if have access to pTargetClass itself from the current point before worry about
// having access to the member within the class
if (!CanAccessClass(pContext,
pTargetMT,
pTargetAssembly,
accessCheckOptions,
checkTargetTypeTransparency))
{
return FALSE;
}
// If we are trying to access a generic method, we have to ensure its instantiation is accessible.
// Note that we need to perform transparency checks on the instantiation even if we have
// checkTargetMethodTransparency set to false, since generic type parameters by design do not effect
// the transparency of the generic method that is closing over them. This means standard transparency
// checks between caller and closed callee may succeed even if the callee's closure includes a critical type.
if (!CanAccessMethodInstantiation(
pContext,
pOptionalTargetMethod,
accessCheckOptions))
{
return FALSE;
}
// pOptionalTargetMethod and pOptionalTargetField can never be NULL at the same time.
_ASSERTE(pOptionalTargetMethod == NULL || pOptionalTargetField == NULL);
// Perform transparency checks
// We don't need to do transparency check against pTargetMT here because
// it was already done in CanAccessClass above.
if (accessCheckOptions.TransparencyCheckNeeded() &&
((checkTargetMethodTransparency && pOptionalTargetMethod) ||
pOptionalTargetField))
{
if (!CheckTransparentAccessToCriticalCode(
pContext,
dwMemberAccess,
pTargetMT,
pOptionalTargetMethod,
pOptionalTargetField,
NULL,
accessCheckOptions))
{
return FALSE;
}
}
if (IsMdPublic(dwMemberAccess))
{
return TRUE;
}
// Always allow interop callers full access.
if (pContext->IsCalledFromInterop())
return TRUE;
MethodTable* pCurrentMT = pContext->GetCallerMT();
if (IsMdPrivateScope(dwMemberAccess))
{
if (pCurrentMT != NULL && pCurrentMT->GetModule() == pTargetMT->GetModule())
{
return TRUE;
}
else
{
return accessCheckOptions.DemandMemberAccessOrFail(pContext, pTargetMT, TRUE /*visibilityCheck*/);
}
}
#ifdef _DEBUG
if (pTargetMT == NULL &&
(IsMdFamORAssem(dwMemberAccess) ||
IsMdFamANDAssem(dwMemberAccess) ||
IsMdFamily(dwMemberAccess))) {
THROW_BAD_FORMAT_MAYBE(!"Family flag is not allowed on global functions", BFA_FAMILY_ON_GLOBAL, pTargetMT);
}
#endif
if (pTargetMT == NULL ||
IsMdAssem(dwMemberAccess) ||
IsMdFamORAssem(dwMemberAccess) ||
IsMdFamANDAssem(dwMemberAccess))
{
// If the member has Assembly accessibility, grant access if the current
// class is in the same assembly as the desired target member, or if the
// desired target member's assembly grants friend access to the current
// assembly.
// @todo: What does it mean for the target class to be NULL?
Assembly* pCurrentAssembly = pContext->GetCallerAssembly();
// pCurrentAssembly should never be NULL, unless we are called from interop,
// in which case we should have already returned TRUE.
_ASSERTE(pCurrentAssembly != NULL);
const BOOL fAssemblyOrFriendAccessAllowed = AssemblyOrFriendAccessAllowed(pCurrentAssembly,
pTargetAssembly,
pOptionalTargetField,
pOptionalTargetMethod,
pTargetMT);
if ((pTargetMT == NULL || IsMdAssem(dwMemberAccess) || IsMdFamORAssem(dwMemberAccess)) &&
fAssemblyOrFriendAccessAllowed)
{
return TRUE;
}
else if (IsMdFamANDAssem(dwMemberAccess) &&
!fAssemblyOrFriendAccessAllowed)
{
return accessCheckOptions.DemandMemberAccessOrFail(pContext, pTargetMT, TRUE /*visibilityCheck*/);
}
}
// Nested classes can access all members of the parent class.
while(pCurrentMT != NULL)
{
//@GENERICSVER:
if (pTargetMT->HasSameTypeDefAs(pCurrentMT))
return TRUE;
if (IsMdPrivate(dwMemberAccess))
{
if (!pCurrentMT->GetClass()->IsNested())
{
return accessCheckOptions.DemandMemberAccessOrFail(pContext, pTargetMT, TRUE /*visibilityCheck*/);
}
}
else if (IsMdFamORAssem(dwMemberAccess) || IsMdFamily(dwMemberAccess) || IsMdFamANDAssem(dwMemberAccess))
{
if (CanAccessFamily(pCurrentMT, pTargetMT))
{
return TRUE;
}
}
pCurrentMT = GetEnclosingMethodTable(pCurrentMT);
}
return accessCheckOptions.DemandMemberAccessOrFail(pContext, pTargetMT, TRUE /*visibilityCheck*/);
}
// The family check is actually in two parts (Partition I, 8.5.3.2). The first part:
//
// ...accessible to referents that support the same type
// (i.e., an exact type and all of the types that inherit
// from it).
//
// Translation: pCurrentClass must be the same type as pTargetClass or a derived class. (i.e. Derived
// can access Base.protected but Unrelated cannot access Base.protected).
//
// The second part:
//
// For verifiable code (see Section 8.8), there is an additional
// requirement that can require a runtime check: the reference
// shall be made through an item whose exact type supports
// the exact type of the referent. That is, the item whose
// member is being accessed shall inherit from the type
// performing the access.
//
// Translation: The C++ protected rule. For those unfamiliar, it means that:
// if you have:
// GrandChild : Child
// and
// Child : Parent
// and
// Parent {
// protected:
// int protectedField;
// }
//
// Child::function(GrandChild * o) {
// o->protectedField; //This access is legal.
// }
//
// GrandChild:function2(Child * o) {
// o->protectedField; //This access is illegal.
// }
//
// The reason for this rule is that if you had:
// Sibling : Parent
//
// Child::function3( Sibling * o ) {
// o->protectedField; //This access is illegal
// }
//
// This is intuitively correct. However, you need to prevent:
// Child::function4( Sibling * o ) {
// ((Parent*)o)->protectedField;
// }
//
// Which means that you must access protected fields through a type that is yourself or one of your
// derived types.
//This checks the first part of the rule above.
/* static */
BOOL ClassLoader::CanAccessFamily(
MethodTable *pCurrentClass,
MethodTable *pTargetClass)
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
INJECT_FAULT(COMPlusThrowOM(););
MODE_ANY;
PRECONDITION(CheckPointer(pTargetClass));
}
CONTRACTL_END
_ASSERTE(pCurrentClass);
_ASSERTE(pTargetClass);
//Look to see if Current is a child of the Target.
while (pCurrentClass) {
MethodTable *pCurInstance = pCurrentClass;
while (pCurInstance) {
//This is correct. csc is incredibly lax about generics. Essentially if you are a subclass of
//any type of generic it lets you access it. Since the standard is totally unclear, mirror that
//behavior here.
if (pCurInstance->HasSameTypeDefAs(pTargetClass)) {
return TRUE;
}
pCurInstance = pCurInstance->GetParentMethodTable();
}
///Looking at 8.5.3, it looks like a protected member of a nested class in a parent type is also
//accessible.
pCurrentClass = GetEnclosingMethodTable(pCurrentClass);
}
return FALSE;
}
//If instance is an inner class, this also succeeds if the outer class conforms to 8.5.3.2. A nested class
//is enclosed inside of the enclosing class' open type. So we need to ignore generic variables. That also
//helps us with:
/*
class Base {
protected int m_family;
}
class Derived<T> : Base {
class Inner {
public int function(Derived<T> d) {
return d.m_family;
}
}
}
*/
//Since the inner T is not the same T as the enclosing T (since accessing generic variables is a CLS rule,
//not a CLI rule), we see that as a comparison between Derived<T> and Derived<T'>. CanCastTo rejects that.
//Instead we just check against the typedef of the two types. This ignores all generic parameters (formal
//or not).
BOOL CanAccessFamilyVerificationEnclosingHelper(MethodTable * pMTCurrentEnclosingClass,
TypeHandle thInstanceClass)
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
MODE_ANY;
}
CONTRACTL_END
_ASSERTE(pMTCurrentEnclosingClass);
if (thInstanceClass.IsGenericVariable())
{
//In this case it is a TypeVarTypeDesc (i.e. T). If this access would be legal due to a
//constraint:
//
/*
public class My<T>
{
public class Inner<U> where U : My<T>
{
public int foo(U u)
{
return u.field;
}
}
protected int field;
}
*/
//We need to find the generic class constraint. (The above is legal because U must be a My<T> which makes this
//legal by 8.5.3.2)
// There may only be 1 class constraint on a generic parameter
// Get the constraints on this generic variable
// At most 1 of them is a class constraint.
// That class constraint methodtable can go through the normal search for matching typedef logic below
TypeVarTypeDesc *tyvar = thInstanceClass.AsGenericVariable();
DWORD numConstraints;
TypeHandle *constraints = tyvar->GetConstraints(&numConstraints, CLASS_DEPENDENCIES_LOADED);
if (constraints == NULL)
{
// If we did not find a class constraint, we cannot generate a methodtable to search for
return FALSE;
}
else
{
for (DWORD i = 0; i < numConstraints; i++)
{
if (!constraints[i].IsInterface())
{
// We have found the class constraint on this TypeVarTypeDesc
// Recurse on the found class constraint. It is possible that this constraint may also be a TypeVarTypeDesc
//class Outer4<T>
//{
// protected int field;
//
// public class Inner<U,V> where V:U where U : Outer4<T>
// {
// public int Method(V param) { return (++param.field); }
// }
//}
return CanAccessFamilyVerificationEnclosingHelper(pMTCurrentEnclosingClass, constraints[i]);
}
}
// If we did not find a class constraint, we cannot generate a methodtable to search for
return FALSE;
}
}
do
{
MethodTable * pAccessor = pMTCurrentEnclosingClass;
//If thInstanceClass is a MethodTable, we should only be doing the TypeDef comparison (see
//above).
if (!thInstanceClass.IsTypeDesc())
{
MethodTable *pInstanceMT = thInstanceClass.AsMethodTable();
// This is a CanCastTo implementation for classes, assuming we should ignore generic instantiation parameters.
do
{
if (pAccessor->HasSameTypeDefAs(pInstanceMT))
return TRUE;
pInstanceMT = pInstanceMT->GetParentMethodTable();
}while(pInstanceMT);
}
else
{
// Leave this logic in place for now, as I'm not fully confident it can't happen, and we are very close to RTM
// This logic was originally written to handle TypeVarTypeDescs, but those are now handled above.
_ASSERTE(FALSE);
if (thInstanceClass.CanCastTo(TypeHandle(pAccessor)))
return TRUE;
}
pMTCurrentEnclosingClass = GetEnclosingMethodTable(pMTCurrentEnclosingClass);
}while(pMTCurrentEnclosingClass);
return FALSE;
}
//This checks the verification only part of the rule above.
//From the example above:
// GrandChild::function2(Child * o) {
// o->protectedField; //This access is illegal.
// }
// pCurrentClass is GrandChild and pTargetClass is Child. This check is completely unnecessary for statics,
// but by legacy convention you can use GrandChild for pTargetClass in that case.
BOOL ClassLoader::CanAccessFamilyVerification(TypeHandle thCurrentClass,
TypeHandle thInstanceClass)
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
INJECT_FAULT(COMPlusThrowOM(););
MODE_ANY;
PRECONDITION(!thCurrentClass.IsNull());
PRECONDITION(!thCurrentClass.IsTypeDesc());
}
CONTRACTL_END
//Check to see if Instance is equal to or derived from pCurrentClass.
//
//In some cases the type we have for the instance type is actually a TypeVarTypeDesc. In those cases we
//need to check against the constraints (You're accessing a member through a 'T' with a type constraint
//that makes this legal). For those cases, CanCastTo does what I want.
MethodTable * pAccessor = thCurrentClass.GetMethodTable();
if (thInstanceClass.CanCastTo(TypeHandle(pAccessor)))
return TRUE;
//ArrayTypeDescs are the only typedescs that have methods, and their methods don't have IL. All other
//TypeDescs don't need to be here. So only run this on MethodTables.
if (!thInstanceClass.IsNull())
{
return CanAccessFamilyVerificationEnclosingHelper(pAccessor, thInstanceClass);
}
return FALSE;
}
#endif // #ifndef DACCESS_COMPILE
#ifdef DACCESS_COMPILE
void
ClassLoader::EnumMemoryRegions(CLRDataEnumMemoryFlags flags)
{
WRAPPER_NO_CONTRACT;
SUPPORTS_DAC;
DAC_ENUM_DTHIS();
EMEM_OUT(("MEM: %p ClassLoader\n", dac_cast<TADDR>(this)));
if (m_pAssembly.IsValid())
{
ModuleIterator modIter = GetAssembly()->IterateModules();
while (modIter.Next())
{
modIter.GetModule()->EnumMemoryRegions(flags, true);
}
}
}
#endif // #ifdef DACCESS_COMPILE
|