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
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/*============================================================
**
** Header: Assembly.cpp
**
**
** Purpose: Implements assembly (loader domain) architecture
**
**
===========================================================*/
#include "common.h"
#include <stdlib.h>
#include "assembly.hpp"
#include "appdomain.hpp"
#include "security.h"
#include "perfcounters.h"
#include "assemblyname.hpp"
#include "eeprofinterfaces.h"
#include "reflectclasswriter.h"
#include "comdynamic.h"
#include <wincrypt.h>
#include "urlmon.h"
#include "sha1.h"
#include "eeconfig.h"
#include "strongname.h"
#include "ceefilegenwriter.h"
#include "assemblynative.hpp"
#include "threadsuspend.h"
#ifdef FEATURE_PREJIT
#include "corcompile.h"
#endif
#include "appdomainnative.hpp"
#include "customattribute.h"
#include "winnls.h"
#include "caparser.h"
#include "../md/compiler/custattr.h"
#include "mdaassistants.h"
#include "peimagelayout.inl"
// Define these macro's to do strict validation for jit lock and class init entry leaks.
// This defines determine if the asserts that verify for these leaks are defined or not.
// These asserts can sometimes go off even if no entries have been leaked so this defines
// should be used with caution.
//
// If we are inside a .cctor when the application shut's down then the class init lock's
// head will be set and this will cause the assert to go off.,
//
// If we are jitting a method when the application shut's down then the jit lock's head
// will be set causing the assert to go off.
//#define STRICT_JITLOCK_ENTRY_LEAK_DETECTION
//#define STRICT_CLSINITLOCK_ENTRY_LEAK_DETECTION
#ifndef DACCESS_COMPILE
// This value is to make it easier to diagnose Assembly Loader "grant set" crashes.
// See Dev11 bug 358184 for more details.
// This value is not thread safe and is not intended to be. It is just a best
// effort to collect more data on the problem. Is is possible, though unlikely,
// that thread A would record a reason for an upcoming crash,
// thread B would then record a different reason, and we would then
// crash on thread A, thus ending up with the recorded reason not matching
// the thread we crash in. Be aware of this when using this value
// to help your debugging.
DWORD g_dwLoaderReasonForNotSharing = 0; // See code:DomainFile::m_dwReasonForRejectingNativeImage for a similar variable.
// These will sometimes result in a crash with error code 0x80131401 SECURITY_E_INCOMPATIBLE_SHARE
// "Loading this assembly would produce a different grant set from other instances."
enum ReasonForNotSharing
{
ReasonForNotSharing_NoInfoRecorded = 0x1,
ReasonForNotSharing_NullDomainassembly = 0x2,
ReasonForNotSharing_DebuggerFlagMismatch = 0x3,
ReasonForNotSharing_NullPeassembly = 0x4,
ReasonForNotSharing_MissingAssemblyClosure1 = 0x5,
ReasonForNotSharing_MissingAssemblyClosure2 = 0x6,
ReasonForNotSharing_MissingDependenciesResolved = 0x7,
ReasonForNotSharing_ClosureComparisonFailed = 0x8,
};
#define NO_FRIEND_ASSEMBLIES_MARKER ((FriendAssemblyDescriptor *)S_FALSE)
//----------------------------------------------------------------------------------------------
// The ctor's job is to initialize the Assembly enough so that the dtor can safely run.
// It cannot do any allocations or operations that might fail. Those operations should be done
// in Assembly::Init()
//----------------------------------------------------------------------------------------------
Assembly::Assembly(BaseDomain *pDomain, PEAssembly* pFile, DebuggerAssemblyControlFlags debuggerFlags, BOOL fIsCollectible) :
m_FreeFlag(0),
m_pDomain(pDomain),
m_pClassLoader(NULL),
m_pEntryPoint(NULL),
m_pManifest(NULL),
m_pManifestFile(clr::SafeAddRef(pFile)),
m_pOnDiskManifest(NULL),
m_pFriendAssemblyDescriptor(NULL),
m_pbStrongNameKeyPair(NULL),
m_pwStrongNameKeyContainer(NULL),
m_isDynamic(false),
#ifdef FEATURE_COLLECTIBLE_TYPES
m_isCollectible(fIsCollectible),
#endif
m_needsToHideManifestForEmit(FALSE),
m_dwDynamicAssemblyAccess(ASSEMBLY_ACCESS_RUN),
m_nextAvailableModuleIndex(1),
m_pLoaderAllocator(NULL),
m_isDisabledPrivateReflection(0),
#ifdef FEATURE_COMINTEROP
m_pITypeLib(NULL),
m_winMDStatus(WinMDStatus_Unknown),
m_pManifestWinMDImport(NULL),
#endif // FEATURE_COMINTEROP
m_pSharedSecurityDesc(NULL),
m_pTransparencyBehavior(NULL),
m_fIsDomainNeutral(pDomain == SharedDomain::GetDomain()),
#ifdef FEATURE_LOADER_OPTIMIZATION
m_bMissingDependenciesCheckDone(FALSE),
#endif // FEATURE_LOADER_OPTIMIZATION
m_debuggerFlags(debuggerFlags),
m_fTerminated(FALSE),
m_HostAssemblyId(0)
#ifdef FEATURE_COMINTEROP
, m_InteropAttributeStatus(INTEROP_ATTRIBUTE_UNSET)
#endif
{
STANDARD_VM_CONTRACT;
}
// This name needs to stay in sync with AssemblyBuilder.MANIFEST_MODULE_NAME
// which is used in AssemblyBuilder.InitManifestModule
#define REFEMIT_MANIFEST_MODULE_NAME W("RefEmit_InMemoryManifestModule")
//----------------------------------------------------------------------------------------------
// Does most Assembly initialization tasks. It can assume the ctor has already run
// and the assembly is safely destructable. Whether this function throws or succeeds,
// it must leave the Assembly in a safely destructable state.
//----------------------------------------------------------------------------------------------
void Assembly::Init(AllocMemTracker *pamTracker, LoaderAllocator *pLoaderAllocator)
{
STANDARD_VM_CONTRACT;
if (IsSystem())
{
_ASSERTE(pLoaderAllocator == NULL); // pLoaderAllocator may only be non-null for collectible types
m_pLoaderAllocator = SystemDomain::GetGlobalLoaderAllocator();
}
else
{
if (!IsDomainNeutral())
{
if (!IsCollectible())
{
// pLoaderAllocator will only be non-null for reflection emit assemblies
_ASSERTE((pLoaderAllocator == NULL) || (pLoaderAllocator == GetDomain()->AsAppDomain()->GetLoaderAllocator()));
m_pLoaderAllocator = GetDomain()->AsAppDomain()->GetLoaderAllocator();
}
else
{
_ASSERTE(pLoaderAllocator != NULL); // ppLoaderAllocator must be non-null for collectible assemblies
m_pLoaderAllocator = pLoaderAllocator;
}
}
else
{
_ASSERTE(pLoaderAllocator == NULL); // pLoaderAllocator may only be non-null for collectible types
// use global loader heaps
m_pLoaderAllocator = SystemDomain::GetGlobalLoaderAllocator();
}
}
_ASSERTE(m_pLoaderAllocator != NULL);
m_pClassLoader = new ClassLoader(this);
m_pClassLoader->Init(pamTracker);
m_pSharedSecurityDesc = Security::CreateSharedSecurityDescriptor(this);
COUNTER_ONLY(GetPerfCounters().m_Loading.cAssemblies++);
#ifndef CROSSGEN_COMPILE
if (GetManifestFile()->IsDynamic())
// manifest modules of dynamic assemblies are always transient
m_pManifest = ReflectionModule::Create(this, GetManifestFile(), pamTracker, REFEMIT_MANIFEST_MODULE_NAME, TRUE);
else
#endif
m_pManifest = Module::Create(this, mdFileNil, GetManifestFile(), pamTracker);
PrepareModuleForAssembly(m_pManifest, pamTracker);
CacheManifestFiles();
if (!m_pManifest->IsReadyToRun())
CacheManifestExportedTypes(pamTracker);
// Check for the assemblies that contain SIMD Vector types.
// If we encounter a non-trusted assembly with these names, we will simply not recognize any of its
// methods as intrinsics.
LPCUTF8 assemblyName = GetSimpleName();
const int length = sizeof("System.Numerics") - 1;
if ((strncmp(assemblyName, "System.Numerics", length) == 0) &&
((assemblyName[length] == '\0') || (strcmp(assemblyName+length, ".Vectors") == 0)))
{
m_fIsSIMDVectorAssembly = true;
}
else
{
m_fIsSIMDVectorAssembly = false;
}
// We'll load the friend assembly information lazily. For the ngen case we should avoid
// loading it entirely.
//CacheFriendAssemblyInfo();
{
CANNOTTHROWCOMPLUSEXCEPTION();
FAULT_FORBID();
//Cannot fail after this point.
PublishModuleIntoAssembly(m_pManifest);
return; // Explicit return to let you know you are NOT welcome to add code after the CANNOTTHROW/FAULT_FORBID expires
}
}
BOOL Assembly::IsDisabledPrivateReflection()
{
CONTRACTL
{
THROWS;
}
CONTRACTL_END;
enum { UNINITIALIZED, ENABLED, DISABLED};
if (m_isDisabledPrivateReflection == UNINITIALIZED)
{
IMDInternalImport *pImport = GetManifestImport();
HRESULT hr = pImport->GetCustomAttributeByName(GetManifestToken(), DISABLED_PRIVATE_REFLECTION_TYPE, NULL, 0);
IfFailThrow(hr);
if (hr == S_OK)
{
m_isDisabledPrivateReflection = DISABLED;
}
else
{
m_isDisabledPrivateReflection = ENABLED;
}
}
return m_isDisabledPrivateReflection == DISABLED;
}
#ifndef CROSSGEN_COMPILE
Assembly::~Assembly()
{
CONTRACTL
{
NOTHROW;
GC_TRIGGERS;
DISABLED(FORBID_FAULT); //Must clean up some profiler stuff
}
CONTRACTL_END
Terminate();
if (m_pFriendAssemblyDescriptor != NULL && m_pFriendAssemblyDescriptor != NO_FRIEND_ASSEMBLIES_MARKER)
delete m_pFriendAssemblyDescriptor;
if (m_pbStrongNameKeyPair && (m_FreeFlag & FREE_KEY_PAIR))
delete[] m_pbStrongNameKeyPair;
if (m_pwStrongNameKeyContainer && (m_FreeFlag & FREE_KEY_CONTAINER))
delete[] m_pwStrongNameKeyContainer;
if (IsDynamic()) {
if (m_pOnDiskManifest)
// clear the on disk manifest if it is not cleared yet.
m_pOnDiskManifest = NULL;
}
if (m_pManifestFile)
{
m_pManifestFile->Release();
}
#ifdef FEATURE_COMINTEROP
if (m_pManifestWinMDImport)
{
m_pManifestWinMDImport->Release();
}
#endif // FEATURE_COMINTEROP
}
#ifdef FEATURE_PREJIT
void Assembly::DeleteNativeCodeRanges()
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_PREEMPTIVE;
FORBID_FAULT;
}
CONTRACTL_END
ModuleIterator i = IterateModules();
while (i.Next())
i.GetModule()->DeleteNativeCodeRanges();
}
#endif
#ifdef PROFILING_SUPPORTED
void ProfilerCallAssemblyUnloadStarted(Assembly* assemblyUnloaded)
{
WRAPPER_NO_CONTRACT;
{
BEGIN_PIN_PROFILER(CORProfilerPresent());
GCX_PREEMP();
g_profControlBlock.pProfInterface->AssemblyUnloadStarted((AssemblyID)assemblyUnloaded);
END_PIN_PROFILER();
}
}
void ProfilerCallAssemblyUnloadFinished(Assembly* assemblyUnloaded)
{
WRAPPER_NO_CONTRACT;
{
BEGIN_PIN_PROFILER(CORProfilerPresent());
GCX_PREEMP();
g_profControlBlock.pProfInterface->AssemblyUnloadFinished((AssemblyID) assemblyUnloaded, S_OK);
END_PIN_PROFILER();
}
}
#endif
void Assembly::StartUnload()
{
STATIC_CONTRACT_NOTHROW;
STATIC_CONTRACT_GC_TRIGGERS;
STATIC_CONTRACT_FORBID_FAULT;
#ifdef PROFILING_SUPPORTED
if (CORProfilerTrackAssemblyLoads())
{
ProfilerCallAssemblyUnloadStarted(this);
}
#endif
// we need to release tlb files eagerly
#ifdef FEATURE_COMINTEROP
if(g_fProcessDetach == FALSE)
{
DefaultCatchFilterParam param; param.pv = COMPLUS_EXCEPTION_EXECUTE_HANDLER;
PAL_TRY(Assembly *, pThis, this)
{
if (pThis->m_pITypeLib && pThis->m_pITypeLib != (ITypeLib*)-1) {
pThis->m_pITypeLib->Release();
pThis->m_pITypeLib = NULL;
}
}
PAL_EXCEPT_FILTER(DefaultCatchFilter)
{
}
PAL_ENDTRY
}
#endif // FEATURE_COMINTEROP
}
void Assembly::Terminate( BOOL signalProfiler )
{
STATIC_CONTRACT_NOTHROW;
STATIC_CONTRACT_GC_TRIGGERS;
STRESS_LOG1(LF_LOADER, LL_INFO100, "Assembly::Terminate (this = 0x%p)\n", reinterpret_cast<void *>(this));
if (this->m_fTerminated)
return;
Security::DeleteSharedSecurityDescriptor(m_pSharedSecurityDesc);
m_pSharedSecurityDesc = NULL;
if (m_pClassLoader != NULL)
{
GCX_PREEMP();
delete m_pClassLoader;
m_pClassLoader = NULL;
}
if (m_pLoaderAllocator != NULL)
{
if (IsCollectible())
{
// This cleanup code starts resembling parts of AppDomain::Terminate too much.
// It would be useful to reduce duplication and also establish clear responsibilites
// for LoaderAllocator::Destroy, Assembly::Terminate, LoaderAllocator::Terminate
// and LoaderAllocator::~LoaderAllocator. We need to establish how these
// cleanup paths interact with app-domain unload and process tear-down, too.
if (!IsAtProcessExit())
{
// Suspend the EE to do some clean up that can only occur
// while no threads are running.
GCX_COOP (); // SuspendEE may require current thread to be in Coop mode
// SuspendEE cares about the reason flag only when invoked for a GC
// Other values are typically ignored. If using SUSPEND_FOR_APPDOMAIN_SHUTDOWN
// is inappropriate, we can introduce a new flag or hijack an unused one.
ThreadSuspend::SuspendEE(ThreadSuspend::SUSPEND_FOR_APPDOMAIN_SHUTDOWN);
}
ExecutionManager::Unload(m_pLoaderAllocator);
m_pLoaderAllocator->UninitVirtualCallStubManager();
MethodTable::ClearMethodDataCache();
_ASSERTE(m_pDomain->IsAppDomain());
AppDomain *pAppDomain = m_pDomain->AsAppDomain();
ClearJitGenericHandleCache(pAppDomain);
if (!IsAtProcessExit())
{
// Resume the EE.
ThreadSuspend::RestartEE(FALSE, TRUE);
}
// Once the manifest file is tenured, the managed LoaderAllocatorScout is responsible for cleanup.
if (m_pManifest != NULL && m_pManifest->IsTenured())
{
pAppDomain->RegisterLoaderAllocatorForDeletion(m_pLoaderAllocator);
}
}
m_pLoaderAllocator = NULL;
}
COUNTER_ONLY(GetPerfCounters().m_Loading.cAssemblies--);
#ifdef PROFILING_SUPPORTED
if (CORProfilerTrackAssemblyLoads())
{
ProfilerCallAssemblyUnloadFinished(this);
}
#endif // PROFILING_SUPPORTED
this->m_fTerminated = TRUE;
}
#endif // CROSSGEN_COMPILE
Assembly * Assembly::Create(
BaseDomain * pDomain,
PEAssembly * pFile,
DebuggerAssemblyControlFlags debuggerFlags,
BOOL fIsCollectible,
AllocMemTracker * pamTracker,
LoaderAllocator * pLoaderAllocator)
{
STANDARD_VM_CONTRACT;
NewHolder<Assembly> pAssembly (new Assembly(pDomain, pFile, debuggerFlags, fIsCollectible));
// If there are problems that arise from this call stack, we'll chew up a lot of stack
// with the various EX_TRY/EX_HOOKs that we will encounter.
INTERIOR_STACK_PROBE_FOR(GetThread(), DEFAULT_ENTRY_PROBE_SIZE);
#ifdef PROFILING_SUPPORTED
{
BEGIN_PIN_PROFILER(CORProfilerTrackAssemblyLoads());
GCX_COOP();
g_profControlBlock.pProfInterface->AssemblyLoadStarted((AssemblyID)(Assembly *) pAssembly);
END_PIN_PROFILER();
}
// Need TRY/HOOK instead of holder so we can get HR of exception thrown for profiler callback
EX_TRY
#endif
{
pAssembly->Init(pamTracker, pLoaderAllocator);
}
#ifdef PROFILING_SUPPORTED
EX_HOOK
{
{
BEGIN_PIN_PROFILER(CORProfilerTrackAssemblyLoads());
GCX_COOP();
g_profControlBlock.pProfInterface->AssemblyLoadFinished((AssemblyID)(Assembly *) pAssembly,
GET_EXCEPTION()->GetHR());
END_PIN_PROFILER();
}
}
EX_END_HOOK;
#endif
pAssembly.SuppressRelease();
END_INTERIOR_STACK_PROBE;
return pAssembly;
} // Assembly::Create
#ifndef CROSSGEN_COMPILE
Assembly *Assembly::CreateDynamic(AppDomain *pDomain, CreateDynamicAssemblyArgs *args)
{
// WARNING: not backout clean
CONTRACT(Assembly *)
{
THROWS;
GC_TRIGGERS;
INJECT_FAULT(COMPlusThrowOM(););
MODE_COOPERATIVE;
PRECONDITION(CheckPointer(args));
}
CONTRACT_END;
// This must be before creation of the AllocMemTracker so that the destructor for the AllocMemTracker happens before the destructor for pLoaderAllocator.
// That is necessary as the allocation of Assembly objects and other related details is done on top of heaps located in
// the loader allocator objects.
NewHolder<LoaderAllocator> pLoaderAllocator;
AllocMemTracker amTracker;
AllocMemTracker *pamTracker = &amTracker;
Assembly *pRetVal = NULL;
AppDomain *pCallersDomain;
MethodDesc *pmdEmitter = SystemDomain::GetCallersMethod(args->stackMark, &pCallersDomain);
// Called either from interop or async delegate invocation. Rejecting because we don't
// know how to set the correct permission on the new dynamic assembly.
if (!pmdEmitter)
COMPlusThrow(kInvalidOperationException);
Assembly *pCallerAssembly = pmdEmitter->GetAssembly();
// First, we set up a pseudo-manifest file for the assembly.
// Set up the assembly name
STRINGREF strRefName = (STRINGREF) args->assemblyName->GetSimpleName();
if (strRefName == NULL)
COMPlusThrow(kArgumentException, W("ArgumentNull_AssemblyNameName"));
StackSString name;
strRefName->GetSString(name);
if (name.GetCount() == 0)
COMPlusThrow(kArgumentException, W("ArgumentNull_AssemblyNameName"));
SString::Iterator i = name.Begin();
if (COMCharacter::nativeIsWhiteSpace(*i)
|| name.Find(i, '\\')
|| name.Find(i, ':')
|| name.Find(i, '/'))
{
COMPlusThrow(kArgumentException, W("Argument_InvalidAssemblyName"));
}
// Set up the assembly manifest metadata
// When we create dynamic assembly, we always use a working copy of IMetaDataAssemblyEmit
// to store temporary runtime assembly information. This is to preserve the invariant that
// an assembly must have a PEFile with proper metadata.
// This working copy of IMetaDataAssemblyEmit will store every AssemblyRef as a simple name
// reference as we must have an instance of Assembly(can be dynamic assembly) before we can
// add such a reference. Also because the referenced assembly if dynamic strong name, it may
// not be ready to be hashed!
SafeComHolder<IMetaDataAssemblyEmit> pAssemblyEmit;
PEFile::DefineEmitScope(
IID_IMetaDataAssemblyEmit,
&pAssemblyEmit);
// remember the hash algorithm
ULONG ulHashAlgId = args->assemblyName->GetAssemblyHashAlgorithm();
if (ulHashAlgId == 0)
ulHashAlgId = CALG_SHA1;
ASSEMBLYMETADATA assemData;
memset(&assemData, 0, sizeof(assemData));
// get the version info (default to 0.0.0.0 if none)
VERSIONREF versionRef = (VERSIONREF) args->assemblyName->GetVersion();
if (versionRef != NULL)
{
assemData.usMajorVersion = (USHORT)versionRef->GetMajor();
assemData.usMinorVersion = (USHORT)versionRef->GetMinor();
assemData.usBuildNumber = (USHORT)versionRef->GetBuild();
assemData.usRevisionNumber = (USHORT)versionRef->GetRevision();
}
struct _gc
{
OBJECTREF granted;
OBJECTREF denied;
OBJECTREF cultureinfo;
STRINGREF pString;
OBJECTREF orArrayOrContainer;
OBJECTREF throwable;
OBJECTREF strongNameKeyPair;
} gc;
ZeroMemory(&gc, sizeof(gc));
GCPROTECT_BEGIN(gc);
StackSString culture;
gc.cultureinfo = args->assemblyName->GetCultureInfo();
if (gc.cultureinfo != NULL)
{
MethodDescCallSite getName(METHOD__CULTURE_INFO__GET_NAME, &gc.cultureinfo);
ARG_SLOT args2[] =
{
ObjToArgSlot(gc.cultureinfo)
};
// convert culture info into a managed string form
gc.pString = getName.Call_RetSTRINGREF(args2);
gc.pString->GetSString(culture);
assemData.szLocale = (LPWSTR) (LPCWSTR) culture;
}
SBuffer publicKey;
if (args->assemblyName->GetPublicKey() != NULL)
{
publicKey.Set(args->assemblyName->GetPublicKey()->GetDataPtr(),
args->assemblyName->GetPublicKey()->GetNumComponents());
}
// get flags
DWORD dwFlags = args->assemblyName->GetFlags();
// Now create a dynamic PE file out of the name & metadata
PEAssemblyHolder pFile;
{
GCX_PREEMP();
mdAssembly ma;
IfFailThrow(pAssemblyEmit->DefineAssembly(publicKey, publicKey.GetSize(), ulHashAlgId,
name, &assemData, dwFlags,
&ma));
pFile = PEAssembly::Create(pCallerAssembly->GetManifestFile(), pAssemblyEmit, args->access & ASSEMBLY_ACCESS_REFLECTION_ONLY);
// Dynamically created modules (aka RefEmit assemblies) do not have a LoadContext associated with them since they are not bound
// using an actual binder. As a result, we will assume the same binding/loadcontext information for the dynamic assembly as its
// caller/creator to ensure that any assembly loads triggered by the dynamic assembly are resolved using the intended load context.
//
// If the creator assembly has a HostAssembly associated with it, then use it for binding. Otherwise, the creator is dynamic
// and will have a fallback load context binder associated with it.
ICLRPrivBinder *pFallbackLoadContextBinder = nullptr;
// There is always a manifest file - wehther working with static or dynamic assemblies.
PEFile *pCallerAssemblyManifestFile = pCallerAssembly->GetManifestFile();
_ASSERTE(pCallerAssemblyManifestFile != NULL);
if (!pCallerAssemblyManifestFile->IsDynamic())
{
// Static assemblies with do not have fallback load context
_ASSERTE(pCallerAssemblyManifestFile->GetFallbackLoadContextBinder() == nullptr);
if (pCallerAssemblyManifestFile->IsSystem())
{
// CoreLibrary is always bound to TPA binder
pFallbackLoadContextBinder = pDomain->GetTPABinderContext();
}
else
{
// Fetch the binder from the host assembly
PTR_ICLRPrivAssembly pCallerAssemblyHostAssembly = pCallerAssemblyManifestFile->GetHostAssembly();
_ASSERTE(pCallerAssemblyHostAssembly != nullptr);
UINT_PTR assemblyBinderID = 0;
IfFailThrow(pCallerAssemblyHostAssembly->GetBinderID(&assemblyBinderID));
pFallbackLoadContextBinder = reinterpret_cast<ICLRPrivBinder *>(assemblyBinderID);
}
}
else
{
// Creator assembly is dynamic too, so use its fallback load context for the one
// we are creating.
pFallbackLoadContextBinder = pCallerAssemblyManifestFile->GetFallbackLoadContextBinder();
}
// At this point, we should have a fallback load context binder to work with
_ASSERTE(pFallbackLoadContextBinder != nullptr);
// Set it as the fallback load context binder for the dynamic assembly being created
pFile->SetFallbackLoadContextBinder(pFallbackLoadContextBinder);
}
AssemblyLoadSecurity loadSecurity;
// In SilverLight all dynamic assemblies should be transparent and partially trusted, even if they are
// created by platform assemblies. Thus they should inherit the grant sets from the appdomain not the
// parent assembly.
IApplicationSecurityDescriptor *pCurrentDomainSecDesc = ::GetAppDomain()->GetSecurityDescriptor();
gc.granted = pCurrentDomainSecDesc->GetGrantedPermissionSet();
DWORD dwSpecialFlags = pCurrentDomainSecDesc->GetSpecialFlags();
// If the dynamic assembly creator did not specify evidence for the newly created assembly, then it
// should inherit the grant set of the creation assembly.
if (loadSecurity.m_pAdditionalEvidence == NULL)
{
loadSecurity.m_pGrantSet = &gc.granted;
loadSecurity.m_pRefusedSet = &gc.denied;
loadSecurity.m_dwSpecialFlags = dwSpecialFlags;
}
NewHolder<DomainAssembly> pDomainAssembly;
{
GCX_PREEMP();
// Create a new LoaderAllocator if appropriate
if ((args->access & ASSEMBLY_ACCESS_COLLECT) != 0)
{
AssemblyLoaderAllocator *pAssemblyLoaderAllocator = new AssemblyLoaderAllocator();
pLoaderAllocator = pAssemblyLoaderAllocator;
// Some of the initialization functions are not virtual. Call through the derived class
// to prevent calling the base class version.
pAssemblyLoaderAllocator->Init(pDomain);
// Setup the managed proxy now, but do not actually transfer ownership to it.
// Once everything is setup and nothing can fail anymore, the ownership will be
// atomically transfered by call to LoaderAllocator::ActivateManagedTracking().
pAssemblyLoaderAllocator->SetupManagedTracking(&args->loaderAllocator);
}
else
{
pLoaderAllocator = pDomain->GetLoaderAllocator();
pLoaderAllocator.SuppressRelease();
}
// Create a domain assembly
pDomainAssembly = new DomainAssembly(pDomain, pFile, &loadSecurity, pLoaderAllocator);
}
// Start loading process
{
// Create a concrete assembly
// (!Do not remove scoping brace: order is important here: the Assembly holder must destruct before the AllocMemTracker!)
NewHolder<Assembly> pAssem;
{
GCX_PREEMP();
// Assembly::Create will call SuppressRelease on the NewHolder that holds the LoaderAllocator when it transfers ownership
pAssem = Assembly::Create(pDomain, pFile, pDomainAssembly->GetDebuggerInfoBits(), args->access & ASSEMBLY_ACCESS_COLLECT ? TRUE : FALSE, pamTracker, pLoaderAllocator);
ReflectionModule* pModule = (ReflectionModule*) pAssem->GetManifestModule();
pModule->SetCreatingAssembly( pCallerAssembly );
if ((args->access & ASSEMBLY_ACCESS_COLLECT) != 0)
{
// Initializing the virtual call stub manager is delayed to remove the need for the LoaderAllocator destructor to properly handle
// uninitializing the VSD system. (There is a need to suspend the runtime, and that's tricky)
pLoaderAllocator->InitVirtualCallStubManager(pDomain, TRUE);
}
}
pAssem->m_isDynamic = true;
pAssem->m_dwDynamicAssemblyAccess = args->access;
// Making the dynamic assembly opportunistically critical in full trust CoreCLR and transparent otherwise.
if (!GetAppDomain()->GetSecurityDescriptor()->IsFullyTrusted())
{
args->flags = kTransparentAssembly;
}
// Fake up a module security descriptor for the assembly.
TokenSecurityDescriptorFlags tokenFlags = TokenSecurityDescriptorFlags_None;
if (args->flags & kAllCriticalAssembly)
tokenFlags |= TokenSecurityDescriptorFlags_AllCritical;
if (args->flags & kAptcaAssembly)
tokenFlags |= TokenSecurityDescriptorFlags_APTCA;
if (args->flags & kCriticalAssembly)
tokenFlags |= TokenSecurityDescriptorFlags_Critical;
if (args->flags & kTransparentAssembly)
tokenFlags |= TokenSecurityDescriptorFlags_Transparent;
if (args->flags & kTreatAsSafeAssembly)
tokenFlags |= TokenSecurityDescriptorFlags_TreatAsSafe;
_ASSERTE(pAssem->GetManifestModule()->m_pModuleSecurityDescriptor != NULL);
pAssem->GetManifestModule()->m_pModuleSecurityDescriptor->OverrideTokenFlags(tokenFlags);
// Set the additional strong name information
pAssem->SetStrongNameLevel(Assembly::SN_NONE);
if (publicKey.GetSize() > 0)
{
pAssem->SetStrongNameLevel(Assembly::SN_PUBLIC_KEY);
{
// Since we have no way to validate the public key of a dynamic assembly we don't allow
// partial trust code to emit a dynamic assembly with an arbitrary public key.
// Ideally we shouldn't allow anyone to emit a dynamic assembly with only a public key,
// but we allow a couple of exceptions to reduce the compat risk: full trust, caller's own key.
// As usual we treat anonymously hosted dynamic methods as partial trust code.
DomainAssembly* pCallerDomainAssembly = pCallerAssembly->GetDomainAssembly(pCallersDomain);
if (!pCallerDomainAssembly->GetSecurityDescriptor()->IsFullyTrusted() ||
pCallerDomainAssembly == pCallersDomain->GetAnonymouslyHostedDynamicMethodsAssembly())
{
DWORD cbKey = 0;
const void* pKey = pCallerAssembly->GetPublicKey(&cbKey);
if (!publicKey.Equals((const BYTE *)pKey, cbKey))
COMPlusThrow(kInvalidOperationException, W("InvalidOperation_StrongNameKeyPairRequired"));
}
}
}
//we need to suppress release for pAssem to avoid double release
pAssem.SuppressRelease ();
{
GCX_PREEMP();
// Finish loading process
// <TODO> would be REALLY nice to unify this with main loading loop </TODO>
pDomainAssembly->Begin();
pDomainAssembly->SetAssembly(pAssem);
pDomainAssembly->m_level = FILE_LOAD_ALLOCATE;
pDomainAssembly->DeliverSyncEvents();
pDomainAssembly->DeliverAsyncEvents();
pDomainAssembly->FinishLoad();
pDomainAssembly->ClearLoading();
pDomainAssembly->m_level = FILE_ACTIVE;
}
// Force the transparency of the module to be computed now, so that we can catch any errors due to
// inconsistent assembly level attributes during the assembly creation call, rather than at some
// later point.
pAssem->GetManifestModule()->m_pModuleSecurityDescriptor->VerifyDataComputed();
{
CANNOTTHROWCOMPLUSEXCEPTION();
FAULT_FORBID();
//Cannot fail after this point
pDomainAssembly.SuppressRelease(); // This also effectively suppresses the release of the pAssem
pamTracker->SuppressRelease();
// Once we reach this point, the loader allocator lifetime is controlled by the Assembly object.
if ((args->access & ASSEMBLY_ACCESS_COLLECT) != 0)
{
// Atomically transfer ownership to the managed heap
pLoaderAllocator->ActivateManagedTracking();
pLoaderAllocator.SuppressRelease();
}
pAssem->SetIsTenured();
pRetVal = pAssem;
}
}
GCPROTECT_END();
RETURN pRetVal;
} // Assembly::CreateDynamic
#endif // CROSSGEN_COMPILE
void Assembly::SetDomainAssembly(DomainAssembly *pDomainAssembly)
{
CONTRACTL
{
PRECONDITION(CheckPointer(pDomainAssembly));
THROWS;
GC_TRIGGERS;
INJECT_FAULT(COMPlusThrowOM(););
}
CONTRACTL_END;
GetManifestModule()->SetDomainFile(pDomainAssembly);
IAssemblySecurityDescriptor *pSec = pDomainAssembly->GetSecurityDescriptor();
GCX_COOP();
pSec->ResolvePolicy(GetSharedSecurityDescriptor(), pDomainAssembly->ShouldSkipPolicyResolution());
} // Assembly::SetDomainAssembly
#endif // #ifndef DACCESS_COMPILE
DomainAssembly *Assembly::GetDomainAssembly(AppDomain *pDomain)
{
CONTRACT(DomainAssembly *)
{
PRECONDITION(CheckPointer(pDomain, NULL_NOT_OK));
POSTCONDITION(CheckPointer(RETVAL));
THROWS;
GC_TRIGGERS;
}
CONTRACT_END;
RETURN GetManifestModule()->GetDomainAssembly(pDomain);
}
DomainAssembly *Assembly::FindDomainAssembly(AppDomain *pDomain)
{
CONTRACT(DomainAssembly *)
{
PRECONDITION(CheckPointer(pDomain));
POSTCONDITION(CheckPointer(RETVAL, NULL_OK));
NOTHROW;
GC_NOTRIGGER;
FORBID_FAULT;
SO_TOLERANT;
SUPPORTS_DAC;
}
CONTRACT_END;
PREFIX_ASSUME (GetManifestModule() !=NULL);
RETURN GetManifestModule()->FindDomainAssembly(pDomain);
}
BOOL Assembly::IsIntrospectionOnly()
{
WRAPPER_NO_CONTRACT;
return m_pManifestFile->IsIntrospectionOnly();
}
PTR_LoaderHeap Assembly::GetLowFrequencyHeap()
{
WRAPPER_NO_CONTRACT;
return GetLoaderAllocator()->GetLowFrequencyHeap();
}
PTR_LoaderHeap Assembly::GetHighFrequencyHeap()
{
WRAPPER_NO_CONTRACT;
return GetLoaderAllocator()->GetHighFrequencyHeap();
}
PTR_LoaderHeap Assembly::GetStubHeap()
{
WRAPPER_NO_CONTRACT;
return GetLoaderAllocator()->GetStubHeap();
}
PTR_BaseDomain Assembly::GetDomain()
{
LIMITED_METHOD_CONTRACT;
SUPPORTS_DAC;
_ASSERTE(m_pDomain);
return (m_pDomain);
}
IAssemblySecurityDescriptor *Assembly::GetSecurityDescriptor(AppDomain *pDomain)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
SO_TOLERANT;
}
CONTRACTL_END
IAssemblySecurityDescriptor* pSecDesc;
if (pDomain == NULL)
{
#ifndef DACCESS_COMPILE
pDomain = ::GetAppDomain();
#else //DACCESS_COMPILE
DacNotImpl();
#endif //DACCESS_COMPILE
}
PREFIX_ASSUME(FindDomainAssembly(pDomain) != NULL);
pSecDesc = FindDomainAssembly(pDomain)->GetSecurityDescriptor();
CONSISTENCY_CHECK(pSecDesc != NULL);
return pSecDesc;
}
#ifndef DACCESS_COMPILE
const SecurityTransparencyBehavior *Assembly::GetSecurityTransparencyBehavior()
{
CONTRACT(const SecurityTransparencyBehavior *)
{
THROWS;
GC_TRIGGERS;
POSTCONDITION(CheckPointer(RETVAL));
}
CONTRACT_END;
if (m_pTransparencyBehavior == NULL)
{
ModuleSecurityDescriptor *pModuleSecurityDescriptor = ModuleSecurityDescriptor::GetModuleSecurityDescriptor(this);
SetSecurityTransparencyBehavior(SecurityTransparencyBehavior::GetTransparencyBehavior(pModuleSecurityDescriptor->GetSecurityRuleSet()));
}
RETURN(m_pTransparencyBehavior);
}
// This method is like GetTransparencyBehavior, but will not attempt to get the transparency behavior if we
// don't already know it, and therefore may return NULL
const SecurityTransparencyBehavior *Assembly::TryGetSecurityTransparencyBehavior()
{
LIMITED_METHOD_CONTRACT;
return m_pTransparencyBehavior;
}
// The transparency behavior object passed to this method must have a lifetime of at least as long
// as the assembly itself.
void Assembly::SetSecurityTransparencyBehavior(const SecurityTransparencyBehavior *pTransparencyBehavior)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
PRECONDITION(CheckPointer(pTransparencyBehavior));
PRECONDITION(m_pTransparencyBehavior == NULL || m_pTransparencyBehavior == pTransparencyBehavior);
}
CONTRACTL_END;
m_pTransparencyBehavior = pTransparencyBehavior;
}
void Assembly::SetParent(BaseDomain* pParent)
{
LIMITED_METHOD_CONTRACT;
m_pDomain = pParent;
}
#endif // !DACCCESS_COMPILE
mdFile Assembly::GetManifestFileToken(LPCSTR name)
{
return mdFileNil;
}
mdFile Assembly::GetManifestFileToken(IMDInternalImport *pImport, mdFile kFile)
{
WRAPPER_NO_CONTRACT;
SUPPORTS_DAC;
LPCSTR name;
if ((TypeFromToken(kFile) != mdtFile) ||
!pImport->IsValidToken(kFile))
{
BAD_FORMAT_NOTHROW_ASSERT(!"Invalid File token");
return mdTokenNil;
}
if (FAILED(pImport->GetFileProps(kFile, &name, NULL, NULL, NULL)))
{
BAD_FORMAT_NOTHROW_ASSERT(!"Invalid File token");
return mdTokenNil;
}
return GetManifestFileToken(name);
}
Module *Assembly::FindModuleByExportedType(mdExportedType mdType,
Loader::LoadFlag loadFlag,
mdTypeDef mdNested,
mdTypeDef* pCL)
{
CONTRACT(Module *)
{
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;
POSTCONDITION(CheckPointer(RETVAL, loadFlag==Loader::Load ? NULL_NOT_OK : NULL_OK));
SUPPORTS_DAC;
}
CONTRACT_END
mdToken mdLinkRef;
mdToken mdBinding;
IMDInternalImport *pManifestImport = GetManifestImport();
IfFailThrow(pManifestImport->GetExportedTypeProps(
mdType,
NULL,
NULL,
&mdLinkRef, // Impl
&mdBinding, // Hint
NULL)); // dwflags
// Don't trust the returned tokens.
if (!pManifestImport->IsValidToken(mdLinkRef))
{
if (loadFlag != Loader::Load)
{
RETURN NULL;
}
else
{
ThrowHR(COR_E_BADIMAGEFORMAT, BFA_INVALID_TOKEN);
}
}
switch(TypeFromToken(mdLinkRef)) {
case mdtAssemblyRef:
{
*pCL = mdTypeDefNil; // We don't trust the mdBinding token
Assembly *pAssembly = NULL;
switch(loadFlag)
{
case Loader::Load:
{
#ifndef DACCESS_COMPILE
// LoadAssembly never returns NULL
DomainAssembly * pDomainAssembly =
GetManifestModule()->LoadAssembly(::GetAppDomain(), mdLinkRef);
PREFIX_ASSUME(pDomainAssembly != NULL);
RETURN pDomainAssembly->GetCurrentModule();
#else
_ASSERTE(!"DAC shouldn't attempt to trigger loading");
return NULL;
#endif // !DACCESS_COMPILE
};
case Loader::DontLoad:
pAssembly = GetManifestModule()->GetAssemblyIfLoaded(mdLinkRef);
break;
case Loader::SafeLookup:
pAssembly = GetManifestModule()->LookupAssemblyRef(mdLinkRef);
break;
default:
_ASSERTE(FALSE);
}
if (pAssembly)
RETURN pAssembly->GetManifestModule();
else
RETURN NULL;
}
case mdtFile:
{
// We may not want to trust this TypeDef token, since it
// was saved in a scope other than the one it was defined in
if (mdNested == mdTypeDefNil)
*pCL = mdBinding;
else
*pCL = mdNested;
// Note that we don't want to attempt a LoadModule if a GetModuleIfLoaded will
// succeed, because it has a stronger contract.
Module *pModule = GetManifestModule()->GetModuleIfLoaded(mdLinkRef, TRUE, FALSE);
#ifdef DACCESS_COMPILE
return pModule;
#else
if (pModule != NULL)
RETURN pModule;
if(loadFlag==Loader::SafeLookup)
return NULL;
// We should never get here in the GC case - the above should have succeeded.
CONSISTENCY_CHECK(!FORBIDGC_LOADER_USE_ENABLED());
DomainFile * pDomainModule = GetManifestModule()->LoadModule(::GetAppDomain(), mdLinkRef, FALSE, loadFlag!=Loader::Load);
if (pDomainModule == NULL)
RETURN NULL;
else
{
pModule = pDomainModule->GetCurrentModule();
if (pModule == NULL)
{
_ASSERTE(loadFlag!=Loader::Load);
}
RETURN pModule;
}
#endif // DACCESS_COMPILE
}
case mdtExportedType:
// Only override the nested type token if it hasn't been set yet.
if (mdNested != mdTypeDefNil)
mdBinding = mdNested;
RETURN FindModuleByExportedType(mdLinkRef, loadFlag, mdBinding, pCL);
default:
ThrowHR(COR_E_BADIMAGEFORMAT, BFA_INVALID_TOKEN_TYPE);
}
} // Assembly::FindModuleByExportedType
// The returned Module is non-NULL unless you prevented the load by setting loadFlag=Loader::DontLoad.
/* static */
Module * Assembly::FindModuleByTypeRef(
Module * pModule,
mdTypeRef tkType,
Loader::LoadFlag loadFlag,
BOOL * pfNoResolutionScope)
{
CONTRACT(Module *)
{
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(pModule));
PRECONDITION(TypeFromToken(tkType) == mdtTypeRef);
PRECONDITION(CheckPointer(pfNoResolutionScope));
POSTCONDITION( CheckPointer(RETVAL, loadFlag==Loader::Load ? NULL_NOT_OK : NULL_OK) );
SUPPORTS_DAC;
}
CONTRACT_END
// WARNING! Correctness of the type forwarder detection algorithm in code:ClassLoader::ResolveTokenToTypeDefThrowing
// relies on this function not performing any form of type forwarding itself.
IMDInternalImport * pImport;
mdTypeRef tkTopLevelEncloserTypeRef;
pImport = pModule->GetMDImport();
if (TypeFromToken(tkType) != mdtTypeRef)
{
ThrowHR(COR_E_BADIMAGEFORMAT, BFA_INVALID_TOKEN_TYPE);
}
{
// Find the top level encloser
GCX_NOTRIGGER();
// If nested, get top level encloser's impl
int iter = 0;
int maxIter = 1000;
do
{
_ASSERTE(TypeFromToken(tkType) == mdtTypeRef);
tkTopLevelEncloserTypeRef = tkType;
if (!pImport->IsValidToken(tkType) || iter >= maxIter)
{
break;
}
IfFailThrow(pImport->GetResolutionScopeOfTypeRef(tkType, &tkType));
// nil-scope TR okay if there's an ExportedType
// Return manifest file
if (IsNilToken(tkType))
{
*pfNoResolutionScope = TRUE;
RETURN(pModule);
}
iter++;
}
while (TypeFromToken(tkType) == mdtTypeRef);
}
*pfNoResolutionScope = FALSE;
#ifndef DACCESS_COMPILE
if (!pImport->IsValidToken(tkType)) // redundant check only when invalid token already found.
{
THROW_BAD_FORMAT(BFA_BAD_TYPEREF_TOKEN, pModule);
}
#endif //!DACCESS_COMPILE
switch (TypeFromToken(tkType))
{
case mdtModule:
{
// Type is in the referencing module.
GCX_NOTRIGGER();
CANNOTTHROWCOMPLUSEXCEPTION();
RETURN( pModule );
}
case mdtModuleRef:
{
if ((loadFlag != Loader::Load) || IsGCThread() || IsStackWalkerThread())
{
// Either we're not supposed to load, or we're doing a GC or stackwalk
// in which case we shouldn't need to load. So just look up the module
// and return what we find.
RETURN(pModule->LookupModule(tkType,FALSE));
}
#ifndef DACCESS_COMPILE
DomainFile * pActualDomainFile = pModule->LoadModule(::GetAppDomain(), tkType, FALSE, loadFlag!=Loader::Load);
if (pActualDomainFile == NULL)
{
RETURN NULL;
}
else
{
RETURN(pActualDomainFile->GetModule());
}
#else //DACCESS_COMPILE
_ASSERTE(loadFlag!=Loader::Load);
DacNotImpl();
RETURN NULL;
#endif //DACCESS_COMPILE
}
break;
case mdtAssemblyRef:
{
// Do this first because it has a strong contract
Assembly * pAssembly = NULL;
#if defined(FEATURE_COMINTEROP) || !defined(DACCESS_COMPILE)
LPCUTF8 szNamespace = NULL;
LPCUTF8 szClassName = NULL;
#endif
#ifdef FEATURE_COMINTEROP
if (pModule->HasBindableIdentity(tkType))
#endif// FEATURE_COMINTEROP
{
_ASSERTE(!IsAfContentType_WindowsRuntime(pModule->GetAssemblyRefFlags(tkType)));
if (loadFlag == Loader::SafeLookup)
{
pAssembly = pModule->LookupAssemblyRef(tkType);
}
else
{
pAssembly = pModule->GetAssemblyIfLoaded(tkType);
}
}
#ifdef FEATURE_COMINTEROP
else
{
_ASSERTE(IsAfContentType_WindowsRuntime(pModule->GetAssemblyRefFlags(tkType)));
if (FAILED(pImport->GetNameOfTypeRef(
tkTopLevelEncloserTypeRef,
&szNamespace,
&szClassName)))
{
THROW_BAD_FORMAT(BFA_BAD_TYPEREF_TOKEN, pModule);
}
pAssembly = pModule->GetAssemblyIfLoaded(
tkType,
szNamespace,
szClassName,
NULL); // pMDImportOverride
}
#endif // FEATURE_COMINTEROP
if (pAssembly != NULL)
{
RETURN pAssembly->m_pManifest;
}
#ifdef DACCESS_COMPILE
RETURN NULL;
#else
if (loadFlag != Loader::Load)
{
RETURN NULL;
}
DomainAssembly * pDomainAssembly = pModule->LoadAssembly(
::GetAppDomain(),
tkType,
szNamespace,
szClassName);
if (pDomainAssembly == NULL)
RETURN NULL;
pAssembly = pDomainAssembly->GetCurrentAssembly();
if (pAssembly == NULL)
{
RETURN NULL;
}
else
{
RETURN pAssembly->m_pManifest;
}
#endif //!DACCESS_COMPILE
}
default:
ThrowHR(COR_E_BADIMAGEFORMAT, BFA_INVALID_TOKEN_TYPE);
}
} // Assembly::FindModuleByTypeRef
#ifndef DACCESS_COMPILE
Module *Assembly::FindModuleByName(LPCSTR pszModuleName)
{
CONTRACT(Module *)
{
THROWS;
GC_TRIGGERS;
INJECT_FAULT(COMPlusThrowOM(););
MODE_ANY;
POSTCONDITION(CheckPointer(RETVAL));
}
CONTRACT_END;
CQuickBytes qbLC;
// Need to perform case insensitive hashing.
UTF8_TO_LOWER_CASE(pszModuleName, qbLC);
pszModuleName = (LPUTF8) qbLC.Ptr();
mdFile kFile = GetManifestFileToken(pszModuleName);
if (kFile == mdTokenNil)
ThrowHR(COR_E_UNAUTHORIZEDACCESS);
if (this == SystemDomain::SystemAssembly())
RETURN m_pManifest->GetModuleIfLoaded(kFile, TRUE, TRUE);
else
RETURN m_pManifest->LoadModule(::GetAppDomain(), kFile)->GetModule();
}
void Assembly::CacheManifestExportedTypes(AllocMemTracker *pamTracker)
{
CONTRACT_VOID
{
THROWS;
GC_TRIGGERS;
INJECT_FAULT(COMPlusThrowOM(););
}
CONTRACT_END;
// Prejitted assemblies are expected to have their table prebuilt.
// If not, we do it here at load time (as if we would jit the assembly).
if (m_pManifest->IsPersistedObject(m_pManifest->m_pAvailableClasses))
RETURN;
mdToken mdExportedType;
HENUMInternalHolder phEnum(GetManifestImport());
phEnum.EnumInit(mdtExportedType,
mdTokenNil);
ClassLoader::AvailableClasses_LockHolder lh(m_pClassLoader);
for(int i = 0; GetManifestImport()->EnumNext(&phEnum, &mdExportedType); i++)
m_pClassLoader->AddExportedTypeHaveLock(GetManifestModule(),
mdExportedType,
pamTracker);
RETURN;
}
void Assembly::CacheManifestFiles()
{
}
//<TODO>@TODO: if module is not signed it needs to acquire the
//permissions from the assembly.</TODO>
void Assembly::PrepareModuleForAssembly(Module* module, AllocMemTracker *pamTracker)
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
INJECT_FAULT(COMPlusThrowOM(););
PRECONDITION(CheckPointer(module));
}
CONTRACTL_END;
if (module->m_pAvailableClasses != NULL && !module->IsPersistedObject(module->m_pAvailableClasses))
{
// ! We intentionally do not take the AvailableClass lock here. It creates problems at
// startup and we haven't yet published the module yet so nobody should be searching it.
m_pClassLoader->PopulateAvailableClassHashTable(module, pamTracker);
}
#ifdef DEBUGGING_SUPPORTED
// Modules take the DebuggerAssemblyControlFlags down from its
// parent Assembly initially.
module->SetDebuggerInfoBits(GetDebuggerInfoBits());
LOG((LF_CORDB, LL_INFO10, "Module %s: bits=0x%x\n",
module->GetFile()->GetSimpleName(),
module->GetDebuggerInfoBits()));
#endif // DEBUGGING_SUPPORTED
m_pManifest->EnsureFileCanBeStored(module->GetModuleRef());
}
// This is the final step of publishing a Module into an Assembly. This step cannot fail.
void Assembly::PublishModuleIntoAssembly(Module *module)
{
CONTRACTL
{
NOTHROW;
GC_TRIGGERS;
FORBID_FAULT;
}
CONTRACTL_END
GetManifestModule()->EnsuredStoreFile(module->GetModuleRef(), module);
FastInterlockIncrement((LONG*)&m_pClassLoader->m_cUnhashedModules);
}
//*****************************************************************************
// Set up the list of names of any friend assemblies
void Assembly::CacheFriendAssemblyInfo()
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
INJECT_FAULT(COMPlusThrowOM(););
}
CONTRACTL_END
if (m_pFriendAssemblyDescriptor == NULL)
{
FriendAssemblyDescriptor *pFriendAssemblies = FriendAssemblyDescriptor::CreateFriendAssemblyDescriptor(this->GetManifestFile());
if (pFriendAssemblies == NULL)
{
pFriendAssemblies = NO_FRIEND_ASSEMBLIES_MARKER;
}
void *pvPreviousDescriptor = InterlockedCompareExchangeT(&m_pFriendAssemblyDescriptor,
pFriendAssemblies,
NULL);
if (pvPreviousDescriptor != NULL && pFriendAssemblies != NO_FRIEND_ASSEMBLIES_MARKER)
{
if (pFriendAssemblies != NO_FRIEND_ASSEMBLIES_MARKER)
{
delete pFriendAssemblies;
}
}
}
} // void Assembly::CacheFriendAssemblyInfo()
//*****************************************************************************
// Is the given assembly a friend of this assembly?
bool Assembly::GrantsFriendAccessTo(Assembly *pAccessingAssembly, FieldDesc *pFD)
{
WRAPPER_NO_CONTRACT;
CacheFriendAssemblyInfo();
if (m_pFriendAssemblyDescriptor == NO_FRIEND_ASSEMBLIES_MARKER)
{
return false;
}
return m_pFriendAssemblyDescriptor->GrantsFriendAccessTo(pAccessingAssembly, pFD);
}
bool Assembly::GrantsFriendAccessTo(Assembly *pAccessingAssembly, MethodDesc *pMD)
{
WRAPPER_NO_CONTRACT;
CacheFriendAssemblyInfo();
if (m_pFriendAssemblyDescriptor == NO_FRIEND_ASSEMBLIES_MARKER)
{
return false;
}
return m_pFriendAssemblyDescriptor->GrantsFriendAccessTo(pAccessingAssembly, pMD);
}
bool Assembly::GrantsFriendAccessTo(Assembly *pAccessingAssembly, MethodTable *pMT)
{
WRAPPER_NO_CONTRACT;
CacheFriendAssemblyInfo();
if (m_pFriendAssemblyDescriptor == NO_FRIEND_ASSEMBLIES_MARKER)
{
return false;
}
return m_pFriendAssemblyDescriptor->GrantsFriendAccessTo(pAccessingAssembly, pMT);
}
bool Assembly::IgnoresAccessChecksTo(Assembly *pAccessedAssembly)
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
PRECONDITION(CheckPointer(pAccessedAssembly));
}
CONTRACTL_END;
CacheFriendAssemblyInfo();
if (m_pFriendAssemblyDescriptor == NO_FRIEND_ASSEMBLIES_MARKER)
{
return false;
}
if (pAccessedAssembly->IsDisabledPrivateReflection())
{
return false;
}
if (!m_fIsDomainNeutral && !GetSecurityDescriptor(GetDomain()->AsAppDomain())->IsFullyTrusted())
{
return false;
}
return m_pFriendAssemblyDescriptor->IgnoresAccessChecksTo(pAccessedAssembly);
}
#ifndef CROSSGEN_COMPILE
enum CorEntryPointType
{
EntryManagedMain, // void main(String[])
EntryCrtMain // unsigned main(void)
};
#ifdef STRESS_THREAD
struct Stress_Thread_Param
{
MethodDesc *pFD;
GlobalStrongHandleHolder argHandle;
short numSkipArgs;
CorEntryPointType EntryType;
Thread* pThread;
public:
Stress_Thread_Param()
: pFD(NULL),
argHandle(),
numSkipArgs(0),
EntryType(EntryManagedMain),
pThread(NULL)
{ LIMITED_METHOD_CONTRACT; }
Stress_Thread_Param* Clone ()
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
MODE_ANY;
}
CONTRACTL_END;
NewHolder<Stress_Thread_Param> retVal= new Stress_Thread_Param;
retVal->pFD = pFD;
if (argHandle.GetValue()!=NULL)
{
GCX_COOP();
retVal->argHandle.Assign(CreateDuplicateHandle(argHandle.GetValue()));
}
retVal->numSkipArgs = numSkipArgs;
retVal->EntryType = EntryType;
retVal->pThread = pThread;
return retVal.Extract();
}
};
struct Stress_Thread_Worker_Param
{
Stress_Thread_Param *lpParameter;
ULONG retVal;
};
static void Stress_Thread_Proc_Worker_Impl(Stress_Thread_Worker_Param * args)
{
STATIC_CONTRACT_THROWS;
args->retVal = E_FAIL;
Stress_Thread_Param* lpParam = (Stress_Thread_Param *)args->lpParameter;
ARG_SLOT stackVar = 0;
MethodDescCallSite threadStart(lpParam->pFD);
// Build the parameter array and invoke the method.
if (lpParam->EntryType == EntryManagedMain)
{
PTRARRAYREF StrArgArray = (PTRARRAYREF)ObjectFromHandle(lpParam->argHandle.GetValue());
stackVar = ObjToArgSlot(StrArgArray);
}
if (lpParam->pFD->IsVoid())
{
threadStart.Call(&stackVar);
args->retVal = GetLatchedExitCode();
}
else
{
// We are doing the same cast as in RunMain. Main is required to return INT32 if it returns.
ARG_SLOT retVal = (INT32)threadStart.Call_RetArgSlot(&stackVar);
args->retVal = static_cast<ULONG>(retVal);
}
}
// wrap into EX_TRY_NOCATCH and call the real thing
static void Stress_Thread_Proc_Worker (LPVOID ptr)
{
STATIC_CONTRACT_THROWS;
EX_TRY_NOCATCH(Stress_Thread_Worker_Param *, args, (Stress_Thread_Worker_Param *) ptr)
{
Stress_Thread_Proc_Worker_Impl(args);
//<TODO>
// When we get mainCRTStartup from the C++ then this should be able to go away.</TODO>
fflush(stdout);
fflush(stderr);
}
EX_END_NOCATCH
}
static DWORD WINAPI __stdcall Stress_Thread_Proc (LPVOID lpParameter)
{
STATIC_CONTRACT_THROWS;
Stress_Thread_Worker_Param args = {(Stress_Thread_Param*)lpParameter,0};
Stress_Thread_Param *lpParam = (Stress_Thread_Param *)lpParameter;
Thread *pThread = lpParam->pThread;
if (!pThread->HasStarted())
return 0;
_ASSERTE(::GetAppDomain() != NULL);
BEGIN_SO_INTOLERANT_CODE_NO_THROW_CHECK_THREAD(return E_FAIL);
EX_TRY
{
ADID KickOffDomain = pThread->GetKickOffDomainId();
// should always have a kickoff domain - a thread should never start in a domain that is unloaded
// because otherwise it would have been collected because nobody can hold a reference to thread object
// in a domain that has been unloaded. But it is possible that we started the unload, in which
// case this thread wouldn't be allowed in or would be punted anyway.
if (KickOffDomain != lpParam->pThread->GetDomain()->GetId())
pThread->DoADCallBack(KickOffDomain, Stress_Thread_Proc_Worker, &args);
else
Stress_Thread_Proc_Worker(&args);
}
EX_CATCH
{
}
EX_END_CATCH(SwallowAllExceptions);
delete (Stress_Thread_Param *) lpParameter;
// Enable preemptive GC so a GC thread can suspend me.
GCX_PREEMP_NO_DTOR();
DestroyThread(pThread);
END_SO_INTOLERANT_CODE;
return args.retVal;
}
static void Stress_Thread_Start (LPVOID lpParameter)
{
CONTRACT_VOID
{
THROWS;
GC_TRIGGERS;
INJECT_FAULT(COMPlusThrowOM());
MODE_ANY;
}
CONTRACT_END;
Thread *pCurThread = GetThread();
if (pCurThread->m_stressThreadCount == -1) {
pCurThread->m_stressThreadCount = g_pConfig->GetStressThreadCount();
}
DWORD dwThreads = pCurThread->m_stressThreadCount;
if (dwThreads <= 1)
RETURN;
Thread ** threads = new Thread* [dwThreads-1];
DWORD n;
for (n = 0; n < dwThreads-1; n ++)
{
threads[n] = SetupUnstartedThread();
threads[n]->m_stressThreadCount = dwThreads/2;
Stress_Thread_Param *param = ((Stress_Thread_Param*)lpParameter)->Clone();
param->pThread = threads[n];
if (!threads[n]->CreateNewThread(0, Stress_Thread_Proc, param))
{
delete param;
threads[n]->DecExternalCount(FALSE);
ThrowOutOfMemory();
}
threads[n]->SetThreadPriority (THREAD_PRIORITY_NORMAL);
}
for (n = 0; n < dwThreads-1; n ++)
{
threads[n]->StartThread();
}
__SwitchToThread (0, CALLER_LIMITS_SPINNING);
RETURN;
}
void Stress_Thread_RunMain(MethodDesc* pFD, CorEntryPointType EntryType, short numSkipArgs, OBJECTHANDLE argHandle)
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
MODE_ANY;
}
CONTRACTL_END;
Stress_Thread_Param Param;
Param.pFD = pFD;
Param.argHandle.Assign(argHandle);
Param.numSkipArgs = numSkipArgs;
Param.EntryType = EntryType;
Param.pThread = NULL;
Stress_Thread_Start (&Param);
}
#endif // STRESS_THREAD
void DECLSPEC_NORETURN ThrowMainMethodException(MethodDesc* pMD, UINT resID)
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
MODE_ANY;
INJECT_FAULT(COMPlusThrowOM());
}
CONTRACTL_END;
DefineFullyQualifiedNameForClassW();
LPCWSTR szClassName = GetFullyQualifiedNameForClassW(pMD->GetMethodTable());
LPCUTF8 szUTFMethodName;
if (FAILED(pMD->GetMDImport()->GetNameOfMethodDef(pMD->GetMemberDef(), &szUTFMethodName)))
{
szUTFMethodName = "Invalid MethodDef record";
}
PREFIX_ASSUME(szUTFMethodName!=NULL);
MAKE_WIDEPTR_FROMUTF8(szMethodName, szUTFMethodName);
COMPlusThrowHR(COR_E_METHODACCESS, resID, szClassName, szMethodName);
}
// Returns true if this is a valid main method?
void ValidateMainMethod(MethodDesc * pFD, CorEntryPointType *pType)
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
MODE_ANY;
INJECT_FAULT(COMPlusThrowOM());
PRECONDITION(CheckPointer(pType));
}
CONTRACTL_END;
// Must be static, but we don't care about accessibility
if ((pFD->GetAttrs() & mdStatic) == 0)
ThrowMainMethodException(pFD, IDS_EE_MAIN_METHOD_MUST_BE_STATIC);
if (pFD->GetNumGenericClassArgs() != 0 || pFD->GetNumGenericMethodArgs() != 0)
ThrowMainMethodException(pFD, IDS_EE_LOAD_BAD_MAIN_SIG);
// Check for types
SigPointer sig(pFD->GetSigPointer());
ULONG nCallConv;
if (FAILED(sig.GetData(&nCallConv)))
ThrowMainMethodException(pFD, BFA_BAD_SIGNATURE);
if (nCallConv != IMAGE_CEE_CS_CALLCONV_DEFAULT)
ThrowMainMethodException(pFD, IDS_EE_LOAD_BAD_MAIN_SIG);
ULONG nParamCount;
if (FAILED(sig.GetData(&nParamCount)))
ThrowMainMethodException(pFD, BFA_BAD_SIGNATURE);
CorElementType nReturnType;
if (FAILED(sig.GetElemType(&nReturnType)))
ThrowMainMethodException(pFD, BFA_BAD_SIGNATURE);
if ((nReturnType != ELEMENT_TYPE_VOID) && (nReturnType != ELEMENT_TYPE_I4) && (nReturnType != ELEMENT_TYPE_U4))
ThrowMainMethodException(pFD, IDS_EE_MAIN_METHOD_HAS_INVALID_RTN);
if (nParamCount == 0)
*pType = EntryCrtMain;
else {
*pType = EntryManagedMain;
if (nParamCount != 1)
ThrowMainMethodException(pFD, IDS_EE_TO_MANY_ARGUMENTS_IN_MAIN);
CorElementType argType;
CorElementType argType2 = ELEMENT_TYPE_END;
if (FAILED(sig.GetElemType(&argType)))
ThrowMainMethodException(pFD, BFA_BAD_SIGNATURE);
if (argType == ELEMENT_TYPE_SZARRAY)
if (FAILED(sig.GetElemType(&argType2)))
ThrowMainMethodException(pFD, BFA_BAD_SIGNATURE);
if (argType != ELEMENT_TYPE_SZARRAY || argType2 != ELEMENT_TYPE_STRING)
ThrowMainMethodException(pFD, IDS_EE_LOAD_BAD_MAIN_SIG);
}
}
/* static */
HRESULT RunMain(MethodDesc *pFD ,
short numSkipArgs,
INT32 *piRetVal,
PTRARRAYREF *stringArgs /*=NULL*/)
{
STATIC_CONTRACT_THROWS;
_ASSERTE(piRetVal);
DWORD cCommandArgs = 0; // count of args on command line
LPWSTR *wzArgs = NULL; // command line args
HRESULT hr = S_OK;
*piRetVal = -1;
// The exit code for the process is communicated in one of two ways. If the
// entrypoint returns an 'int' we take that. Otherwise we take a latched
// process exit code. This can be modified by the app via setting
// Environment's ExitCode property.
//
// When we're executing the default exe main in the default domain, set the latched exit code to
// zero as a default. If it gets set to something else by user code then that value will be returned.
//
// StringArgs appears to be non-null only when the main method is explicitly invoked via the hosting api
// or through creating a subsequent domain and running an exe within it. In those cases we don't
// want to reset the (global) latched exit code.
if (stringArgs == NULL)
SetLatchedExitCode(0);
if (!pFD) {
_ASSERTE(!"Must have a function to call!");
return E_FAIL;
}
CorEntryPointType EntryType = EntryManagedMain;
ValidateMainMethod(pFD, &EntryType);
if ((EntryType == EntryManagedMain) &&
(stringArgs == NULL)) {
return E_INVALIDARG;
}
ETWFireEvent(Main_V1);
struct Param
{
MethodDesc *pFD;
short numSkipArgs;
INT32 *piRetVal;
PTRARRAYREF *stringArgs;
CorEntryPointType EntryType;
DWORD cCommandArgs;
LPWSTR *wzArgs;
} param;
param.pFD = pFD;
param.numSkipArgs = numSkipArgs;
param.piRetVal = piRetVal;
param.stringArgs = stringArgs;
param.EntryType = EntryType;
param.cCommandArgs = cCommandArgs;
param.wzArgs = wzArgs;
EX_TRY_NOCATCH(Param *, pParam, ¶m)
{
MethodDescCallSite threadStart(pParam->pFD);
PTRARRAYREF StrArgArray = NULL;
GCPROTECT_BEGIN(StrArgArray);
// Build the parameter array and invoke the method.
if (pParam->EntryType == EntryManagedMain) {
if (pParam->stringArgs == NULL) {
// Allocate a COM Array object with enough slots for cCommandArgs - 1
StrArgArray = (PTRARRAYREF) AllocateObjectArray((pParam->cCommandArgs - pParam->numSkipArgs), g_pStringClass);
// Create Stringrefs for each of the args
for (DWORD arg = pParam->numSkipArgs; arg < pParam->cCommandArgs; arg++) {
STRINGREF sref = StringObject::NewString(pParam->wzArgs[arg]);
StrArgArray->SetAt(arg - pParam->numSkipArgs, (OBJECTREF) sref);
}
}
else
StrArgArray = *pParam->stringArgs;
}
#ifdef STRESS_THREAD
OBJECTHANDLE argHandle = (StrArgArray != NULL) ? CreateGlobalStrongHandle (StrArgArray) : NULL;
Stress_Thread_RunMain(pParam->pFD, pParam->EntryType, pParam->numSkipArgs, argHandle);
#endif
ARG_SLOT stackVar = ObjToArgSlot(StrArgArray);
if (pParam->pFD->IsVoid())
{
// Set the return value to 0 instead of returning random junk
*pParam->piRetVal = 0;
threadStart.Call(&stackVar);
}
else
{
*pParam->piRetVal = (INT32)threadStart.Call_RetArgSlot(&stackVar);
if (pParam->stringArgs == NULL)
{
SetLatchedExitCode(*pParam->piRetVal);
}
}
GCPROTECT_END();
//<TODO>
// When we get mainCRTStartup from the C++ then this should be able to go away.</TODO>
fflush(stdout);
fflush(stderr);
}
EX_END_NOCATCH
ETWFireEvent(MainEnd_V1);
return hr;
}
static void RunMainPre()
{
LIMITED_METHOD_CONTRACT;
_ASSERTE(GetThread() != 0);
g_fWeControlLifetime = TRUE;
}
static void RunMainPost()
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
MODE_ANY;
INJECT_FAULT(COMPlusThrowOM(););
PRECONDITION(CheckPointer(GetThread()));
}
CONTRACTL_END
GCX_PREEMP();
ThreadStore::s_pThreadStore->WaitForOtherThreads();
DWORD dwSecondsToSleep = g_pConfig->GetSleepOnExit();
// if dwSeconds is non-zero then we will sleep for that many seconds
// before we exit this allows the vaDumpCmd to detect that our process
// has gone idle and this allows us to get a vadump of our process at
// this point in it's execution
//
if (dwSecondsToSleep != 0)
{
ClrSleepEx(dwSecondsToSleep * 1000, FALSE);
}
}
INT32 Assembly::ExecuteMainMethod(PTRARRAYREF *stringArgs, BOOL waitForOtherThreads)
{
CONTRACTL
{
INSTANCE_CHECK;
THROWS;
GC_TRIGGERS;
MODE_ANY;
ENTRY_POINT;
INJECT_FAULT(COMPlusThrowOM());
}
CONTRACTL_END;
// reset the error code for std C
errno=0;
HRESULT hr = S_OK;
INT32 iRetVal = 0;
BEGIN_ENTRYPOINT_THROWS;
Thread *pThread = GetThread();
MethodDesc *pMeth;
{
// This thread looks like it wandered in -- but actually we rely on it to keep the process alive.
pThread->SetBackground(FALSE);
GCX_COOP();
pMeth = GetEntryPoint();
if (pMeth) {
RunMainPre();
// Set the root assembly as the assembly that is containing the main method
// The root assembly is used in the GetEntryAssembly method that on CoreCLR is used
// to get the TargetFrameworkMoniker for the app
AppDomain * pDomain = pThread->GetDomain();
pDomain->SetRootAssembly(pMeth->GetAssembly());
hr = RunMain(pMeth, 1, &iRetVal, stringArgs);
}
}
//RunMainPost is supposed to be called on the main thread of an EXE,
//after that thread has finished doing useful work. It contains logic
//to decide when the process should get torn down. So, don't call it from
// AppDomain.ExecuteAssembly()
if (pMeth) {
if (waitForOtherThreads)
RunMainPost();
}
else {
StackSString displayName;
GetDisplayName(displayName);
COMPlusThrowHR(COR_E_MISSINGMETHOD, IDS_EE_FAILED_TO_FIND_MAIN, displayName);
}
IfFailThrow(hr);
END_ENTRYPOINT_THROWS;
return iRetVal;
}
#endif // CROSSGEN_COMPILE
MethodDesc* Assembly::GetEntryPoint()
{
CONTRACT(MethodDesc*)
{
THROWS;
INJECT_FAULT(COMPlusThrowOM(););
MODE_ANY;
// Can return NULL if no entry point.
POSTCONDITION(CheckPointer(RETVAL, NULL_OK));
}
CONTRACT_END;
if (m_pEntryPoint)
RETURN m_pEntryPoint;
mdToken mdEntry = m_pManifestFile->GetEntryPointToken();
if (IsNilToken(mdEntry))
RETURN NULL;
Module *pModule = NULL;
switch(TypeFromToken(mdEntry)) {
case mdtFile:
pModule = m_pManifest->LoadModule(::GetAppDomain(), mdEntry, FALSE)->GetModule();
mdEntry = pModule->GetEntryPointToken();
if ( (TypeFromToken(mdEntry) != mdtMethodDef) ||
(!pModule->GetMDImport()->IsValidToken(mdEntry)) )
pModule = NULL;
break;
case mdtMethodDef:
if (m_pManifestFile->GetPersistentMDImport()->IsValidToken(mdEntry))
pModule = m_pManifest;
break;
}
// May be unmanaged entrypoint
if (!pModule)
RETURN NULL;
// We need to get its properties and the class token for this MethodDef token.
mdToken mdParent;
if (FAILED(pModule->GetMDImport()->GetParentToken(mdEntry, &mdParent))) {
StackSString displayName;
GetDisplayName(displayName);
COMPlusThrowHR(COR_E_BADIMAGEFORMAT, IDS_EE_ILLEGAL_TOKEN_FOR_MAIN, displayName);
}
// For the entrypoint, also validate if the paramList is valid or not. We do this check
// by asking for the return-value (sequence 0) parameter to MDInternalRO::FindParamOfMethod.
// Incase the parameter list is invalid, CLDB_E_FILE_CORRUPT will be returned
// byMDInternalRO::FindParamOfMethod and we will bail out.
//
// If it does not exist (return value CLDB_E_RECORD_NOTFOUND) or if it is found (S_OK),
// we do not bother as the values would have come upon ensurin a valid parameter record
// list.
mdParamDef pdParam;
HRESULT hrValidParamList = pModule->GetMDImport()->FindParamOfMethod(mdEntry, 0, &pdParam);
if (hrValidParamList == CLDB_E_FILE_CORRUPT)
{
// Throw an exception for bad_image_format (because of corrupt metadata)
StackSString displayName;
GetDisplayName(displayName);
COMPlusThrowHR(COR_E_BADIMAGEFORMAT, IDS_EE_ILLEGAL_TOKEN_FOR_MAIN, displayName);
}
if (mdParent != COR_GLOBAL_PARENT_TOKEN) {
GCX_COOP();
// This code needs a class init frame, because without it, the
// debugger will assume any code that results from searching for a
// type handle (ie, loading an assembly) is the first line of a program.
FrameWithCookie<DebuggerClassInitMarkFrame> __dcimf;
MethodTable * pInitialMT = ClassLoader::LoadTypeDefOrRefThrowing(pModule, mdParent,
ClassLoader::ThrowIfNotFound,
ClassLoader::FailIfUninstDefOrRef).GetMethodTable();
m_pEntryPoint = MemberLoader::FindMethod(pInitialMT, mdEntry);
__dcimf.Pop();
}
else
{
m_pEntryPoint = pModule->FindMethod(mdEntry);
}
RETURN m_pEntryPoint;
}
#ifndef CROSSGEN_COMPILE
OBJECTREF Assembly::GetExposedObject()
{
CONTRACT(OBJECTREF)
{
GC_TRIGGERS;
THROWS;
INJECT_FAULT(COMPlusThrowOM(););
MODE_COOPERATIVE;
}
CONTRACT_END;
RETURN GetDomainAssembly()->GetExposedAssemblyObject();
}
#endif // CROSSGEN_COMPILE
/* static */
BOOL Assembly::FileNotFound(HRESULT hr)
{
LIMITED_METHOD_CONTRACT;
return IsHRESULTForExceptionKind(hr, kFileNotFoundException) ||
#ifdef FEATURE_COMINTEROP
(hr == RO_E_METADATA_NAME_NOT_FOUND) ||
#endif //FEATURE_COMINTEROP
(hr == CLR_E_BIND_TYPE_NOT_FOUND);
}
BOOL Assembly::GetResource(LPCSTR szName, DWORD *cbResource,
PBYTE *pbInMemoryResource, Assembly** pAssemblyRef,
LPCSTR *szFileName, DWORD *dwLocation,
StackCrawlMark *pStackMark, BOOL fSkipSecurityCheck,
BOOL fSkipRaiseResolveEvent)
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
INJECT_FAULT(COMPlusThrowOM(););
}
CONTRACTL_END;
DomainAssembly *pAssembly = NULL;
BOOL result = GetDomainAssembly()->GetResource(szName, cbResource,
pbInMemoryResource, &pAssembly,
szFileName, dwLocation, pStackMark, fSkipSecurityCheck,
fSkipRaiseResolveEvent);
if (result && pAssemblyRef != NULL && pAssembly!=NULL)
*pAssemblyRef = pAssembly->GetAssembly();
return result;
}
#ifdef FEATURE_PREJIT
BOOL Assembly::IsInstrumented()
{
STATIC_CONTRACT_THROWS;
STATIC_CONTRACT_GC_TRIGGERS;
STATIC_CONTRACT_FAULT;
BOOL isInstrumented = false;
EX_TRY
{
FAULT_NOT_FATAL();
isInstrumented = IsInstrumentedHelper();
}
EX_CATCH
{
isInstrumented = false;
}
EX_END_CATCH(RethrowTerminalExceptions);
return isInstrumented;
}
BOOL Assembly::IsInstrumentedHelper()
{
STATIC_CONTRACT_THROWS;
STATIC_CONTRACT_GC_TRIGGERS;
STATIC_CONTRACT_FAULT;
// Dynamic Assemblies cannot be instrumented
if (IsDynamic())
return false;
// We must have a native image in order to perform IBC instrumentation
if (!GetManifestFile()->HasNativeImage())
return false;
// @Consider using the full name instead of the short form
// (see GetFusionAssemblyName()->IsEqual).
LPCUTF8 szZapBBInstr = g_pConfig->GetZapBBInstr();
LPCUTF8 szAssemblyName = GetSimpleName();
if (!szZapBBInstr || !szAssemblyName ||
(*szZapBBInstr == '\0') || (*szAssemblyName == '\0'))
return false;
// Convert to unicode so that we can do a case insensitive comparison
SString instrumentedAssemblyNamesList(SString::Utf8, szZapBBInstr);
SString assemblyName(SString::Utf8, szAssemblyName);
const WCHAR *wszInstrumentedAssemblyNamesList = instrumentedAssemblyNamesList.GetUnicode();
const WCHAR *wszAssemblyName = assemblyName.GetUnicode();
// wszInstrumentedAssemblyNamesList is a space separated list of assembly names.
// We need to determine if wszAssemblyName is in this list.
// If there is a "*" in the list, then all assemblies match.
const WCHAR * pCur = wszInstrumentedAssemblyNamesList;
do
{
_ASSERTE(pCur[0] != W('\0'));
const WCHAR * pNextSpace = wcschr(pCur, W(' '));
_ASSERTE(pNextSpace == NULL || pNextSpace[0] == W(' '));
if (pCur != pNextSpace)
{
// pCur is not pointing to a space
_ASSERTE(pCur[0] != W(' '));
if (pCur[0] == W('*') && (pCur[1] == W(' ') || pCur[1] == W('\0')))
return true;
if (pNextSpace == NULL)
{
// We have reached the last name in the list. There are no more spaces.
return (SString::_wcsicmp(wszAssemblyName, pCur) == 0);
}
else
{
if (SString::_wcsnicmp(wszAssemblyName, pCur, static_cast<COUNT_T>(pNextSpace - pCur)) == 0)
return true;
}
}
pCur = pNextSpace + 1;
}
while (pCur[0] != W('\0'));
return false;
}
#endif // FEATURE_PREJIT
//***********************************************************
// Add an assembly to the assemblyref list. pAssemEmitter specifies where
// the AssemblyRef is emitted to.
//***********************************************************
mdAssemblyRef Assembly::AddAssemblyRef(Assembly *refedAssembly, IMetaDataAssemblyEmit *pAssemEmitter, BOOL fUsePublicKeyToken)
{
CONTRACT(mdAssemblyRef)
{
THROWS;
GC_TRIGGERS;
INJECT_FAULT(COMPlusThrowOM(););
PRECONDITION(CheckPointer(refedAssembly));
PRECONDITION(CheckPointer(pAssemEmitter, NULL_NOT_OK));
POSTCONDITION(!IsNilToken(RETVAL));
POSTCONDITION(TypeFromToken(RETVAL) == mdtAssemblyRef);
}
CONTRACT_END;
SafeComHolder<IMetaDataAssemblyEmit> emitHolder;
AssemblySpec spec;
spec.InitializeSpec(refedAssembly->GetManifestFile());
if (refedAssembly->IsCollectible())
{
if (this->IsCollectible())
this->GetLoaderAllocator()->EnsureReference(refedAssembly->GetLoaderAllocator());
else
COMPlusThrow(kNotSupportedException, W("NotSupported_CollectibleBoundNonCollectible"));
}
mdAssemblyRef ar;
IfFailThrow(spec.EmitToken(pAssemEmitter, &ar, fUsePublicKeyToken));
RETURN ar;
} // Assembly::AddAssemblyRef
//***********************************************************
// Add a typedef to the runtime TypeDef table of this assembly
//***********************************************************
void Assembly::AddType(
Module *pModule,
mdTypeDef cl)
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
INJECT_FAULT(COMPlusThrowOM(););
}
CONTRACTL_END
AllocMemTracker amTracker;
if (pModule->GetAssembly() != this)
{
// you cannot add a typedef outside of the assembly to the typedef table
_ASSERTE(!"Bad usage!");
}
m_pClassLoader->AddAvailableClassDontHaveLock(pModule,
cl,
&amTracker);
amTracker.SuppressRelease();
}
//***********************************************************
// Add an ExportedType to the runtime TypeDef table of this assembly
//***********************************************************
void Assembly::AddExportedType(mdExportedType cl)
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
INJECT_FAULT(COMPlusThrowOM(););
}
CONTRACTL_END
AllocMemTracker amTracker;
m_pClassLoader->AddExportedTypeDontHaveLock(GetManifestModule(),
cl,
&amTracker);
amTracker.SuppressRelease();
}
HRESULT STDMETHODCALLTYPE
GetAssembliesByName(LPCWSTR szAppBase,
LPCWSTR szPrivateBin,
LPCWSTR szAssemblyName,
IUnknown *ppIUnk[],
ULONG cMax,
ULONG *pcAssemblies)
{
CONTRACTL
{
NOTHROW;
MODE_PREEMPTIVE;
GC_TRIGGERS;
INJECT_FAULT(return E_OUTOFMEMORY;);
}
CONTRACTL_END
HRESULT hr = S_OK;
if (g_fEEInit) {
// Cannot call this during EE startup
return MSEE_E_ASSEMBLYLOADINPROGRESS;
}
if (!(szAssemblyName && ppIUnk && pcAssemblies))
return E_POINTER;
hr = COR_E_NOTSUPPORTED;
return hr;
}// Used by the IMetadata API's to access an assemblies metadata.
#ifdef FEATURE_LOADER_OPTIMIZATION
void Assembly::SetMissingDependenciesCheckDone()
{
LIMITED_METHOD_CONTRACT;
m_bMissingDependenciesCheckDone=TRUE;
};
BOOL Assembly::MissingDependenciesCheckDone()
{
LIMITED_METHOD_CONTRACT;
return m_bMissingDependenciesCheckDone;
};
BOOL Assembly::CanBeShared(DomainAssembly *pDomainAssembly)
{
PTR_PEAssembly pFile=pDomainAssembly->GetFile();
if(pFile == NULL)
return FALSE;
if(pFile->IsDynamic())
return FALSE;
if(IsSystem() && pFile->IsSystem())
return TRUE;
if ((pDomainAssembly->GetDebuggerInfoBits()&~(DACF_PDBS_COPIED|DACF_IGNORE_PDBS|DACF_OBSOLETE_TRACK_JIT_INFO))
!= (m_debuggerFlags&~(DACF_PDBS_COPIED|DACF_IGNORE_PDBS|DACF_OBSOLETE_TRACK_JIT_INFO)))
{
LOG((LF_CODESHARING,
LL_INFO100,
"We can't share it, desired debugging flags %x are different than %x\n",
pDomainAssembly->GetDebuggerInfoBits(), (m_debuggerFlags&~(DACF_PDBS_COPIED|DACF_IGNORE_PDBS|DACF_OBSOLETE_TRACK_JIT_INFO))));
STRESS_LOG2(LF_CODESHARING, LL_INFO100,"Flags diff= %08x [%08x/%08x]",pDomainAssembly->GetDebuggerInfoBits(),
m_debuggerFlags);
return FALSE;
}
return TRUE;
}
#endif // FEATURE_LOADER_OPTIMIZATION
#if defined(FEATURE_CORESYSTEM)
BOOL Assembly::AllowUntrustedCaller()
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
INJECT_FAULT(COMPlusThrowOM(););
}
CONTRACTL_END
return ModuleSecurityDescriptor::GetModuleSecurityDescriptor(this)->IsAPTCA();
}
#endif // defined(FEATURE_CORESYSTEM)
void DECLSPEC_NORETURN Assembly::ThrowTypeLoadException(LPCUTF8 pszFullName, UINT resIDWhy)
{
WRAPPER_NO_CONTRACT;
ThrowTypeLoadException(NULL, pszFullName, NULL,
resIDWhy);
}
void DECLSPEC_NORETURN Assembly::ThrowTypeLoadException(LPCUTF8 pszNameSpace, LPCUTF8 pszTypeName,
UINT resIDWhy)
{
WRAPPER_NO_CONTRACT;
ThrowTypeLoadException(pszNameSpace, pszTypeName, NULL,
resIDWhy);
}
void DECLSPEC_NORETURN Assembly::ThrowTypeLoadException(NameHandle *pName, UINT resIDWhy)
{
STATIC_CONTRACT_THROWS;
if (pName->GetName()) {
ThrowTypeLoadException(pName->GetNameSpace(),
pName->GetName(),
NULL,
resIDWhy);
}
else
ThrowTypeLoadException(pName->GetTypeModule()->GetMDImport(),
pName->GetTypeToken(),
resIDWhy);
}
void DECLSPEC_NORETURN Assembly::ThrowTypeLoadException(IMDInternalImport *pInternalImport,
mdToken token,
UINT resIDWhy)
{
WRAPPER_NO_CONTRACT;
ThrowTypeLoadException(pInternalImport, token, NULL, resIDWhy);
}
void DECLSPEC_NORETURN Assembly::ThrowTypeLoadException(IMDInternalImport *pInternalImport,
mdToken token,
LPCUTF8 pszFieldOrMethodName,
UINT resIDWhy)
{
STATIC_CONTRACT_THROWS;
char pszBuff[32];
LPCUTF8 pszClassName = (LPCUTF8)pszBuff;
LPCUTF8 pszNameSpace = "Invalid_Token";
if(pInternalImport->IsValidToken(token))
{
switch (TypeFromToken(token)) {
case mdtTypeRef:
if (FAILED(pInternalImport->GetNameOfTypeRef(token, &pszNameSpace, &pszClassName)))
{
pszNameSpace = pszClassName = "Invalid TypeRef record";
}
break;
case mdtTypeDef:
if (FAILED(pInternalImport->GetNameOfTypeDef(token, &pszClassName, &pszNameSpace)))
{
pszNameSpace = pszClassName = "Invalid TypeDef record";
}
break;
case mdtTypeSpec:
// If you see this assert, you need to make sure the message for
// this resID is appropriate for TypeSpecs
_ASSERTE((resIDWhy == IDS_CLASSLOAD_GENERAL) ||
(resIDWhy == IDS_CLASSLOAD_BADFORMAT) ||
(resIDWhy == IDS_CLASSLOAD_TYPESPEC));
resIDWhy = IDS_CLASSLOAD_TYPESPEC;
}
}
else
sprintf_s(pszBuff, sizeof(pszBuff), "0x%8.8X", token);
ThrowTypeLoadException(pszNameSpace, pszClassName,
pszFieldOrMethodName, resIDWhy);
}
void DECLSPEC_NORETURN Assembly::ThrowTypeLoadException(LPCUTF8 pszNameSpace,
LPCUTF8 pszTypeName,
LPCUTF8 pszMethodName,
UINT resIDWhy)
{
STATIC_CONTRACT_THROWS;
StackSString displayName;
GetDisplayName(displayName);
::ThrowTypeLoadException(pszNameSpace, pszTypeName, displayName,
pszMethodName, resIDWhy);
}
void DECLSPEC_NORETURN Assembly::ThrowBadImageException(LPCUTF8 pszNameSpace,
LPCUTF8 pszTypeName,
UINT resIDWhy)
{
STATIC_CONTRACT_THROWS;
StackSString displayName;
GetDisplayName(displayName);
StackSString fullName;
SString sNameSpace(SString::Utf8, pszNameSpace);
SString sTypeName(SString::Utf8, pszTypeName);
fullName.MakeFullNamespacePath(sNameSpace, sTypeName);
COMPlusThrowHR(COR_E_BADIMAGEFORMAT, resIDWhy, fullName, displayName);
}
#ifdef FEATURE_COMINTEROP
//
// Manage an ITypeLib pointer for this Assembly.
//
ITypeLib* Assembly::GetTypeLib()
{
CONTRACTL
{
NOTHROW;
GC_TRIGGERS;
FORBID_FAULT;
}
CONTRACTL_END
// Get the value we are going to return.
ITypeLib *pResult = m_pITypeLib;
// If there is a value, AddRef() it.
if (pResult && pResult != (ITypeLib*)-1)
pResult->AddRef();
return pResult;
} // ITypeLib* Assembly::GetTypeLib()
void Assembly::SetTypeLib(ITypeLib *pNew)
{
CONTRACTL
{
NOTHROW;
GC_TRIGGERS;
FORBID_FAULT;
}
CONTRACTL_END
ITypeLib *pOld;
pOld = InterlockedExchangeT(&m_pITypeLib, pNew);
// TypeLibs are refcounted pointers.
if (pNew != pOld)
{
if (pNew && pNew != (ITypeLib*)-1)
pNew->AddRef();
if (pOld && pOld != (ITypeLib*)-1)
pOld->Release();
}
} // void Assembly::SetTypeLib()
Assembly::WinMDStatus Assembly::GetWinMDStatus()
{
LIMITED_METHOD_CONTRACT;
if (m_winMDStatus == WinMDStatus_Unknown)
{
IWinMDImport *pWinMDImport = GetManifestWinMDImport();
if (pWinMDImport != NULL)
{
BOOL bIsWinMDExp;
VERIFY(SUCCEEDED(pWinMDImport->IsScenarioWinMDExp(&bIsWinMDExp)));
if (bIsWinMDExp)
{
// this is a managed backed WinMD
m_winMDStatus = WinMDStatus_IsManagedWinMD;
}
else
{
// this is a pure WinMD
m_winMDStatus = WinMDStatus_IsPureWinMD;
}
}
else
{
// this is not a WinMD at all
m_winMDStatus = WinMDStatus_IsNotWinMD;
}
}
return m_winMDStatus;
}
bool Assembly::IsWinMD()
{
LIMITED_METHOD_CONTRACT;
return GetWinMDStatus() != WinMDStatus_IsNotWinMD;
}
bool Assembly::IsManagedWinMD()
{
LIMITED_METHOD_CONTRACT;
return GetWinMDStatus() == WinMDStatus_IsManagedWinMD;
}
IWinMDImport *Assembly::GetManifestWinMDImport()
{
LIMITED_METHOD_CONTRACT;
if (m_pManifestWinMDImport == NULL)
{
ReleaseHolder<IWinMDImport> pWinMDImport;
if (SUCCEEDED(m_pManifest->GetMDImport()->QueryInterface(IID_IWinMDImport, (void **)&pWinMDImport)))
{
if (InterlockedCompareExchangeT<IWinMDImport *>(&m_pManifestWinMDImport, pWinMDImport, NULL) == NULL)
{
pWinMDImport.SuppressRelease();
}
}
}
return m_pManifestWinMDImport;
}
#endif // FEATURE_COMINTEROP
#endif // #ifndef DACCESS_COMPILE
#ifndef DACCESS_COMPILE
void Assembly::EnsureActive()
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
INJECT_FAULT(COMPlusThrowOM(););
}
CONTRACTL_END;
GetDomainAssembly()->EnsureActive();
}
#endif //!DACCESS_COMPILE
CHECK Assembly::CheckActivated()
{
#ifndef DACCESS_COMPILE
WRAPPER_NO_CONTRACT;
CHECK(GetDomainAssembly()->CheckActivated());
#endif
CHECK_OK;
}
#ifdef DACCESS_COMPILE
void
Assembly::EnumMemoryRegions(CLRDataEnumMemoryFlags flags)
{
WRAPPER_NO_CONTRACT;
SUPPORTS_DAC;
// We don't need Assembly info in triage dumps.
if (flags == CLRDATA_ENUM_MEM_TRIAGE)
{
return;
}
DAC_ENUM_DTHIS();
EMEM_OUT(("MEM: %p Assembly\n", dac_cast<TADDR>(this)));
if (m_pDomain.IsValid())
{
m_pDomain->EnumMemoryRegions(flags, true);
}
if (m_pClassLoader.IsValid())
{
m_pClassLoader->EnumMemoryRegions(flags);
}
if (m_pManifest.IsValid())
{
m_pManifest->EnumMemoryRegions(flags, true);
}
if (m_pManifestFile.IsValid())
{
m_pManifestFile->EnumMemoryRegions(flags);
}
}
#endif
#ifndef DACCESS_COMPILE
FriendAssemblyDescriptor::FriendAssemblyDescriptor()
{
}
FriendAssemblyDescriptor::~FriendAssemblyDescriptor()
{
CONTRACTL
{
DESTRUCTOR_CHECK;
}
CONTRACTL_END;
ArrayList::Iterator itFullAccessAssemblies = m_alFullAccessFriendAssemblies.Iterate();
while (itFullAccessAssemblies.Next())
{
FriendAssemblyName_t *pFriendAssemblyName = static_cast<FriendAssemblyName_t *>(itFullAccessAssemblies.GetElement());
delete pFriendAssemblyName;
}
}
//---------------------------------------------------------------------------------------
//
// Builds a FriendAssemblyDescriptor for a given assembly
//
// Arguments:
// pAssembly - assembly to get friend assembly information for
//
// Return Value:
// A friend assembly descriptor if the assembly declares any friend assemblies, otherwise NULL
//
// static
FriendAssemblyDescriptor *FriendAssemblyDescriptor::CreateFriendAssemblyDescriptor(PEAssembly *pAssembly)
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
PRECONDITION(CheckPointer(pAssembly));
}
CONTRACTL_END
NewHolder<FriendAssemblyDescriptor> pFriendAssemblies = new FriendAssemblyDescriptor;
// We're going to do this twice, once for InternalsVisibleTo and once for IgnoresAccessChecks
ReleaseHolder<IMDInternalImport> pImport(pAssembly->GetMDImportWithRef());
for(int count = 0 ; count < 2 ; ++count)
{
_ASSERTE(pImport != NULL);
MDEnumHolder hEnum(pImport);
HRESULT hr = S_OK;
if (count == 0)
{
hr = pImport->EnumCustomAttributeByNameInit(TokenFromRid(1, mdtAssembly), FRIEND_ASSEMBLY_TYPE, &hEnum);
}
else
{
hr = pImport->EnumCustomAttributeByNameInit(TokenFromRid(1, mdtAssembly), SUBJECT_ASSEMBLY_TYPE, &hEnum);
}
IfFailThrow(hr);
// Nothing to do if there are no attributes
if (hr == S_FALSE)
{
continue;
}
// Enumerate over the declared friends
mdCustomAttribute tkAttribute;
while (pImport->EnumNext(&hEnum, &tkAttribute))
{
// Get raw custom attribute.
const BYTE *pbAttr = NULL; // Custom attribute data as a BYTE*.
ULONG cbAttr = 0; // Size of custom attribute data.
if (FAILED(pImport->GetCustomAttributeAsBlob(tkAttribute, reinterpret_cast<const void **>(&pbAttr), &cbAttr)))
{
THROW_BAD_FORMAT(BFA_INVALID_TOKEN, pAssembly);
}
CustomAttributeParser cap(pbAttr, cbAttr);
if (FAILED(cap.ValidateProlog()))
{
THROW_BAD_FORMAT(BFA_BAD_CA_HEADER, pAssembly);
}
// Get the name of the friend assembly.
LPCUTF8 szString;
ULONG cbString;
if (FAILED(cap.GetNonNullString(&szString, &cbString)))
{
THROW_BAD_FORMAT(BFA_BAD_CA_HEADER, pAssembly);
}
// Convert the string to Unicode.
StackSString displayName(SString::Utf8, szString, cbString);
// Create an AssemblyNameObject from the string.
FriendAssemblyNameHolder pFriendAssemblyName;
StackScratchBuffer buffer;
pFriendAssemblyName = new FriendAssemblyName_t;
hr = pFriendAssemblyName->Init(displayName.GetUTF8(buffer));
if (SUCCEEDED(hr))
{
hr = pFriendAssemblyName->CheckFriendAssemblyName();
}
if (FAILED(hr))
{
THROW_HR_ERROR_WITH_INFO(hr, pAssembly);
}
if (count == 1)
{
pFriendAssemblies->AddSubjectAssembly(pFriendAssemblyName);
pFriendAssemblyName.SuppressRelease();
// Below checks are unnecessary for IgnoresAccessChecks
continue;
}
// CoreCLR does not have a valid scenario for strong-named assemblies requiring their dependencies
// to be strong-named as well.
pFriendAssemblies->AddFriendAssembly(pFriendAssemblyName);
pFriendAssemblyName.SuppressRelease();
}
}
pFriendAssemblies.SuppressRelease();
return pFriendAssemblies.Extract();
}
//---------------------------------------------------------------------------------------
//
// Adds an assembly to the list of friend assemblies for this descriptor
//
// Arguments:
// pFriendAssembly - friend assembly to add to the list
// fAllInternalsVisible - true if all internals are visible to the friend, false if only specifically
// marked internals are visible
//
// Notes:
// This method takes ownership of the friend assembly name. It is not thread safe and does not check to
// see if an assembly has already been added to the friend assembly list.
//
void FriendAssemblyDescriptor::AddFriendAssembly(FriendAssemblyName_t *pFriendAssembly)
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
PRECONDITION(CheckPointer(pFriendAssembly));
}
CONTRACTL_END
m_alFullAccessFriendAssemblies.Append(pFriendAssembly);
}
void FriendAssemblyDescriptor::AddSubjectAssembly(FriendAssemblyName_t *pFriendAssembly)
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
PRECONDITION(CheckPointer(pFriendAssembly));
}
CONTRACTL_END
m_subjectAssemblies.Append(pFriendAssembly);
}
// static
bool FriendAssemblyDescriptor::IsAssemblyOnList(PEAssembly *pAssembly, const ArrayList &alAssemblyNames)
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
PRECONDITION(CheckPointer(pAssembly));
}
CONTRACTL_END;
AssemblySpec asmDef;
asmDef.InitializeSpec(pAssembly);
ArrayList::ConstIterator itAssemblyNames = alAssemblyNames.Iterate();
while (itAssemblyNames.Next())
{
const FriendAssemblyName_t *pFriendAssemblyName = static_cast<const FriendAssemblyName_t *>(itAssemblyNames.GetElement());
HRESULT hr = AssemblySpec::RefMatchesDef(pFriendAssemblyName, &asmDef) ? S_OK : S_FALSE;
if (hr == S_OK)
{
return true;
}
}
return false;
}
#endif // !DACCESS_COMPILE
|