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
|
// 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.
// --------------------------------------------------------------------------------
// PEFile.cpp
//
// --------------------------------------------------------------------------------
#include "common.h"
#include "pefile.h"
#include "strongname.h"
#include "corperm.h"
#include "eecontract.h"
#include "apithreadstress.h"
#include "eeconfig.h"
#include "product_version.h"
#include "eventtrace.h"
#include "corperm.h"
#include "dbginterface.h"
#include "peimagelayout.inl"
#include "dlwrap.h"
#include "invokeutil.h"
#ifdef FEATURE_PREJIT
#include "compile.h"
#endif
#include "strongnameinternal.h"
#include "../binder/inc/applicationcontext.hpp"
#include "clrprivbinderutil.h"
#include "../binder/inc/coreclrbindercommon.h"
#ifdef FEATURE_PREJIT
#include "compile.h"
#ifdef DEBUGGING_SUPPORTED
SVAL_IMPL_INIT(DWORD, PEFile, s_NGENDebugFlags, 0);
#endif
#endif
#include "sha1.h"
#ifndef DACCESS_COMPILE
// ================================================================================
// PEFile class - this is an abstract base class for PEModule and PEAssembly
// <TODO>@todo: rename TargetFile</TODO>
// ================================================================================
PEFile::PEFile(PEImage *identity, BOOL fCheckAuthenticodeSignature/*=TRUE*/) :
#if _DEBUG
m_pDebugName(NULL),
#endif
m_identity(NULL),
m_openedILimage(NULL),
#ifdef FEATURE_PREJIT
m_nativeImage(NULL),
m_fCanUseNativeImage(TRUE),
#endif
m_MDImportIsRW_Debugger_Use_Only(FALSE),
m_bHasPersistentMDImport(FALSE),
m_pMDImport(NULL),
m_pImporter(NULL),
m_pEmitter(NULL),
m_pMetadataLock(::new SimpleRWLock(PREEMPTIVE, LOCK_TYPE_DEFAULT)),
m_refCount(1),
m_hash(NULL),
m_flags(0),
m_fStrongNameVerified(FALSE)
,m_pHostAssembly(nullptr)
,m_pFallbackLoadContextBinder(nullptr)
{
CONTRACTL
{
CONSTRUCTOR_CHECK;
THROWS;
GC_TRIGGERS;
MODE_ANY;
}
CONTRACTL_END;
if (identity)
{
identity->AddRef();
m_identity = identity;
if(identity->IsOpened())
{
//already opened, prepopulate
identity->AddRef();
m_openedILimage = identity;
}
}
}
PEFile::~PEFile()
{
CONTRACTL
{
DESTRUCTOR_CHECK;
NOTHROW;
GC_TRIGGERS;
MODE_ANY;
}
CONTRACTL_END;
ReleaseMetadataInterfaces(TRUE);
if (m_hash != NULL)
delete m_hash;
#ifdef FEATURE_PREJIT
if (m_nativeImage != NULL)
{
MarkNativeImageInvalidIfOwned();
m_nativeImage->Release();
}
#endif //FEATURE_PREJIT
if (m_openedILimage != NULL)
m_openedILimage->Release();
if (m_identity != NULL)
m_identity->Release();
if (m_pMetadataLock)
delete m_pMetadataLock;
if (m_pHostAssembly != NULL)
{
m_pHostAssembly->Release();
}
}
#ifndef DACCESS_COMPILE
void PEFile::ReleaseIL()
{
WRAPPER_NO_CONTRACT;
if (m_openedILimage!=NULL )
{
ReleaseMetadataInterfaces(TRUE, TRUE);
if (m_identity != NULL)
{
m_identity->Release();
m_identity=NULL;
}
m_openedILimage->Release();
m_openedILimage = NULL;
}
}
#endif
/* static */
PEFile *PEFile::Open(PEImage *image)
{
CONTRACT(PEFile *)
{
PRECONDITION(image != NULL);
PRECONDITION(image->CheckFormat());
POSTCONDITION(RETVAL != NULL);
POSTCONDITION(!RETVAL->IsModule());
POSTCONDITION(!RETVAL->IsAssembly());
THROWS;
GC_TRIGGERS;
MODE_ANY;
INJECT_FAULT(COMPlusThrowOM(););
}
CONTRACT_END;
PEFile *pFile = new PEFile(image, FALSE);
if (image->HasNTHeaders() && image->HasCorHeader())
pFile->OpenMDImport_Unsafe(); //no one else can see the object yet
#if _DEBUG
pFile->m_debugName = image->GetPath();
pFile->m_debugName.Normalize();
pFile->m_pDebugName = pFile->m_debugName;
#endif
RETURN pFile;
}
// ------------------------------------------------------------
// Loader support routines
// ------------------------------------------------------------
template<class T> void CoTaskFree(T *p)
{
if (p != NULL)
{
p->T::~T();
CoTaskMemFree(p);
}
}
NEW_WRAPPER_TEMPLATE1(CoTaskNewHolder, CoTaskFree<_TYPE>);
//-----------------------------------------------------------------------------------------------------
// Catch attempts to load x64 assemblies on x86, etc.
//-----------------------------------------------------------------------------------------------------
static void ValidatePEFileMachineType(PEFile *peFile)
{
STANDARD_VM_CONTRACT;
if (peFile->IsIntrospectionOnly())
return; // ReflectionOnly assemblies permitted to violate CPU restrictions
if (peFile->IsDynamic())
return; // PEFiles for ReflectionEmit assemblies don't cache the machine type.
if (peFile->IsResource())
return; // PEFiles for resource assemblies don't cache the machine type.
if (peFile->HasNativeImage())
return; // If it passed the native binder, no need to do the check again esp. at the risk of inviting an IL page-in.
DWORD peKind;
DWORD actualMachineType;
peFile->GetPEKindAndMachine(&peKind, &actualMachineType);
if (actualMachineType == IMAGE_FILE_MACHINE_I386 && ((peKind & (peILonly | pe32BitRequired)) == peILonly))
return; // Image is marked CPU-agnostic.
if (actualMachineType != IMAGE_FILE_MACHINE_NATIVE && actualMachineType != IMAGE_FILE_MACHINE_NATIVE_NI)
{
#ifdef _TARGET_AMD64_
// v4.0 64-bit compatibility workaround. The 64-bit v4.0 CLR's Reflection.Load(byte[]) api does not detect cpu-matches. We should consider fixing that in
// the next SxS release. In the meantime, this bypass will retain compat for 64-bit v4.0 CLR for target platforms that existed at the time.
//
// Though this bypass kicks in for all Load() flavors, the other Load() flavors did detect cpu-matches through various other code paths that still exist.
// Or to put it another way, this #ifdef makes the (4.5 only) ValidatePEFileMachineType() a NOP for x64, hence preserving 4.0 compatibility.
if (actualMachineType == IMAGE_FILE_MACHINE_I386 || actualMachineType == IMAGE_FILE_MACHINE_IA64)
return;
#endif // _WIN64_
// Image has required machine that doesn't match the CLR.
StackSString name;
if (peFile->IsAssembly())
((PEAssembly*)peFile)->GetDisplayName(name);
else
name = StackSString(SString::Utf8, peFile->GetSimpleName());
COMPlusThrow(kBadImageFormatException, IDS_CLASSLOAD_WRONGCPU, name.GetUnicode());
}
return; // If we got here, all is good.
}
void PEFile::LoadLibrary(BOOL allowNativeSkip/*=TRUE*/) // if allowNativeSkip==FALSE force IL image load
{
CONTRACT_VOID
{
INSTANCE_CHECK;
POSTCONDITION(CheckLoaded());
STANDARD_VM_CHECK;
}
CONTRACT_END;
// Catch attempts to load x64 assemblies on x86, etc.
ValidatePEFileMachineType(this);
// See if we've already loaded it.
if (CheckLoaded(allowNativeSkip))
{
RETURN;
}
// Note that we may be racing other threads here, in the case of domain neutral files
// Resource images are always flat.
if (IsResource())
{
GetILimage()->LoadNoMetaData(IsIntrospectionOnly());
RETURN;
}
#if !defined(_TARGET_64BIT_)
if (!HasNativeImage() && (!GetILimage()->Has32BitNTHeaders()) && !IsIntrospectionOnly())
{
// Tried to load 64-bit assembly on 32-bit platform.
EEFileLoadException::Throw(this, COR_E_BADIMAGEFORMAT, NULL);
}
#endif
// We need contents now
if (!HasNativeImage())
{
EnsureImageOpened();
}
if (IsIntrospectionOnly())
{
GetILimage()->LoadForIntrospection();
RETURN;
}
//---- Below this point, only do the things necessary for execution ----
_ASSERTE(!IsIntrospectionOnly());
#ifdef FEATURE_PREJIT
// For on-disk Dlls, we can call LoadLibrary
if (IsDll() && !((HasNativeImage()?m_nativeImage:GetILimage())->GetPath().IsEmpty()))
{
// Note that we may get a DllMain notification inside here.
if (allowNativeSkip && HasNativeImage())
{
m_nativeImage->Load();
if(!m_nativeImage->IsNativeILILOnly())
GetILimage()->Load(); // For IJW we have to load IL also...
}
else
GetILimage()->Load();
}
else
#endif // FEATURE_PREJIT
{
// Since we couldn't call LoadLibrary, we must be an IL only image
// or the image may still contain unfixed up stuff
// Note that we make an exception for CompilationDomains, since PEImage
// will map non-ILOnly images in a compilation domain.
if (!GetILimage()->IsILOnly() && !GetAppDomain()->IsCompilationDomain())
{
if (!GetILimage()->HasV1Metadata())
ThrowHR(COR_E_FIXUPSINEXE); // <TODO>@todo: better error</TODO>
}
// If we are already mapped, we can just use the current image.
#ifdef FEATURE_PREJIT
if (allowNativeSkip && HasNativeImage())
{
m_nativeImage->LoadFromMapped();
if( !m_nativeImage->IsNativeILILOnly())
GetILimage()->LoadFromMapped(); // For IJW we have to load IL also...
}
else
#endif
{
if (GetILimage()->IsFile())
{
#ifdef PLATFORM_UNIX
if (GetILimage()->IsILOnly())
{
GetILimage()->Load();
}
else
#endif // PLATFORM_UNIX
{
GetILimage()->LoadFromMapped();
}
}
else
{
GetILimage()->LoadNoFile();
}
}
}
RETURN;
}
void PEFile::SetLoadedHMODULE(HMODULE hMod)
{
CONTRACT_VOID
{
INSTANCE_CHECK;
PRECONDITION(CheckPointer(hMod));
POSTCONDITION(CheckLoaded());
THROWS;
GC_TRIGGERS;
MODE_ANY;
INJECT_FAULT(COMPlusThrowOM(););
}
CONTRACT_END;
// See if the image is an internal PEImage.
GetILimage()->SetLoadedHMODULE(hMod);
RETURN;
}
/* static */
void PEFile::DefineEmitScope(
GUID iid,
void **ppEmit)
{
CONTRACT_VOID
{
PRECONDITION(CheckPointer(ppEmit));
POSTCONDITION(CheckPointer(*ppEmit));
THROWS;
GC_TRIGGERS;
MODE_ANY;
INJECT_FAULT(COMPlusThrowOM(););
}
CONTRACT_END;
SafeComHolder<IMetaDataDispenserEx> pDispenser;
// Get the Dispenser interface.
MetaDataGetDispenser(
CLSID_CorMetaDataDispenser,
IID_IMetaDataDispenserEx,
(void **)&pDispenser);
if (pDispenser == NULL)
{
ThrowOutOfMemory();
}
// Set the option on the dispenser turn on duplicate check for TypeDef and moduleRef
VARIANT varOption;
V_VT(&varOption) = VT_UI4;
V_I4(&varOption) = MDDupDefault | MDDupTypeDef | MDDupModuleRef | MDDupExportedType | MDDupAssemblyRef | MDDupPermission | MDDupFile;
IfFailThrow(pDispenser->SetOption(MetaDataCheckDuplicatesFor, &varOption));
// Set minimal MetaData size
V_VT(&varOption) = VT_UI4;
V_I4(&varOption) = MDInitialSizeMinimal;
IfFailThrow(pDispenser->SetOption(MetaDataInitialSize, &varOption));
// turn on the thread safety!
V_I4(&varOption) = MDThreadSafetyOn;
IfFailThrow(pDispenser->SetOption(MetaDataThreadSafetyOptions, &varOption));
IfFailThrow(pDispenser->DefineScope(CLSID_CorMetaDataRuntime, 0, iid, (IUnknown **)ppEmit));
RETURN;
} // PEFile::DefineEmitScope
// ------------------------------------------------------------
// Identity
// ------------------------------------------------------------
BOOL PEFile::Equals(PEFile *pFile)
{
CONTRACTL
{
INSTANCE_CHECK;
PRECONDITION(CheckPointer(pFile));
GC_NOTRIGGER;
NOTHROW;
CANNOT_TAKE_LOCK;
MODE_ANY;
}
CONTRACTL_END;
// Same object is equal
if (pFile == this)
return TRUE;
// Execution and introspection files are NOT equal
if ( (!IsIntrospectionOnly()) != !(pFile->IsIntrospectionOnly()) )
{
return FALSE;
}
// Different host assemblies cannot be equal unless they are associated with the same host binder
// It's ok if only one has a host binder because multiple threads can race to load the same assembly
// and that may cause temporary candidate PEAssembly objects that never get bound to a host assembly
// because another thread beats it; the losing thread will pick up the PEAssembly in the cache.
if (pFile->HasHostAssembly() && this->HasHostAssembly())
{
UINT_PTR fileBinderId = 0;
if (FAILED(pFile->GetHostAssembly()->GetBinderID(&fileBinderId)))
return FALSE;
UINT_PTR thisBinderId = 0;
if (FAILED(this->GetHostAssembly()->GetBinderID(&thisBinderId)))
return FALSE;
if (fileBinderId != thisBinderId)
return FALSE;
}
// Same identity is equal
if (m_identity != NULL && pFile->m_identity != NULL
&& m_identity->Equals(pFile->m_identity))
return TRUE;
// Same image is equal
if (m_openedILimage != NULL && pFile->m_openedILimage != NULL
&& m_openedILimage->Equals(pFile->m_openedILimage))
return TRUE;
return FALSE;
}
BOOL PEFile::Equals(PEImage *pImage)
{
CONTRACTL
{
INSTANCE_CHECK;
PRECONDITION(CheckPointer(pImage));
GC_NOTRIGGER;
NOTHROW;
MODE_ANY;
}
CONTRACTL_END;
// Same object is equal
if (pImage == m_identity || pImage == m_openedILimage)
return TRUE;
#ifdef FEATURE_PREJIT
if(pImage == m_nativeImage)
return TRUE;
#endif
// Same identity is equal
if (m_identity != NULL
&& m_identity->Equals(pImage))
return TRUE;
// Same image is equal
if (m_openedILimage != NULL
&& m_openedILimage->Equals(pImage))
return TRUE;
return FALSE;
}
// ------------------------------------------------------------
// Descriptive strings
// ------------------------------------------------------------
void PEFile::GetCodeBaseOrName(SString &result)
{
CONTRACTL
{
INSTANCE_CHECK;
THROWS;
GC_TRIGGERS;
MODE_ANY;
INJECT_FAULT(COMPlusThrowOM(););
}
CONTRACTL_END;
if (m_identity != NULL && !m_identity->GetPath().IsEmpty())
{
result.Set(m_identity->GetPath());
}
else if (IsAssembly())
{
((PEAssembly*)this)->GetCodeBase(result);
}
else
result.SetUTF8(GetSimpleName());
}
// ------------------------------------------------------------
// Checks
// ------------------------------------------------------------
CHECK PEFile::CheckLoaded(BOOL bAllowNativeSkip/*=TRUE*/)
{
CONTRACT_CHECK
{
INSTANCE_CHECK;
NOTHROW;
GC_NOTRIGGER;
SO_TOLERANT;
MODE_ANY;
}
CONTRACT_CHECK_END;
CHECK(IsLoaded(bAllowNativeSkip)
// We are allowed to skip LoadLibrary in most cases for ngen'ed IL only images
|| (bAllowNativeSkip && HasNativeImage() && IsILOnly()));
CHECK_OK;
}
// ------------------------------------------------------------
// Metadata access
// ------------------------------------------------------------
PTR_CVOID PEFile::GetMetadata(COUNT_T *pSize)
{
CONTRACT(PTR_CVOID)
{
INSTANCE_CHECK;
POSTCONDITION(CheckPointer(pSize, NULL_OK));
POSTCONDITION(CheckPointer(RETVAL, NULL_OK));
THROWS;
GC_TRIGGERS;
MODE_ANY;
SUPPORTS_DAC;
}
CONTRACT_END;
#ifdef FEATURE_PREJIT
if (HasNativeImageMetadata())
{
RETURN m_nativeImage->GetMetadata(pSize);
}
#endif
if (IsDynamic()
|| !GetILimage()->HasNTHeaders()
|| !GetILimage()->HasCorHeader())
{
if (pSize != NULL)
*pSize = 0;
RETURN NULL;
}
else
{
RETURN GetILimage()->GetMetadata(pSize);
}
}
#endif // #ifndef DACCESS_COMPILE
PTR_CVOID PEFile::GetLoadedMetadata(COUNT_T *pSize)
{
CONTRACT(PTR_CVOID)
{
INSTANCE_CHECK;
POSTCONDITION(CheckPointer(pSize, NULL_OK));
POSTCONDITION(CheckPointer(RETVAL, NULL_OK));
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
SUPPORTS_DAC;
}
CONTRACT_END;
#ifdef FEATURE_PREJIT
if (HasNativeImageMetadata())
{
RETURN GetLoadedNative()->GetMetadata(pSize);
}
#endif
if (!HasLoadedIL()
|| !GetLoadedIL()->HasNTHeaders()
|| !GetLoadedIL()->HasCorHeader())
{
if (pSize != NULL)
*pSize = 0;
RETURN NULL;
}
else
{
RETURN GetLoadedIL()->GetMetadata(pSize);
}
}
TADDR PEFile::GetIL(RVA il)
{
CONTRACT(TADDR)
{
INSTANCE_CHECK;
PRECONDITION(il != 0);
PRECONDITION(!IsDynamic());
PRECONDITION(!IsResource());
#ifndef DACCESS_COMPILE
PRECONDITION(CheckLoaded());
#endif
POSTCONDITION(RETVAL != NULL);
THROWS;
GC_NOTRIGGER;
MODE_ANY;
SUPPORTS_DAC;
}
CONTRACT_END;
PEImageLayout *image = NULL;
#ifdef FEATURE_PREJIT
// Note it is important to get the IL from the native image if
// available, since we are using the metadata from the native image
// which has different IL rva's.
if (HasNativeImageMetadata())
{
image = GetLoadedNative();
#ifndef DACCESS_COMPILE
// NGen images are trusted to be well-formed.
_ASSERTE(image->CheckILMethod(il));
#endif
}
else
#endif // FEATURE_PREJIT
{
image = GetLoadedIL();
#ifndef DACCESS_COMPILE
// Verify that the IL blob is valid before giving it out
if (!image->CheckILMethod(il))
COMPlusThrowHR(COR_E_BADIMAGEFORMAT, BFA_BAD_IL_RANGE);
#endif
}
RETURN image->GetRvaData(il);
}
#ifndef DACCESS_COMPILE
void PEFile::OpenImporter()
{
CONTRACTL
{
INSTANCE_CHECK;
THROWS;
GC_NOTRIGGER;
MODE_ANY;
INJECT_FAULT(COMPlusThrowOM(););
}
CONTRACTL_END;
// Make sure internal MD is in RW format.
ConvertMDInternalToReadWrite();
IMetaDataImport2 *pIMDImport = NULL;
IfFailThrow(GetMetaDataPublicInterfaceFromInternal((void*)GetPersistentMDImport(),
IID_IMetaDataImport2,
(void **)&pIMDImport));
// Atomically swap it into the field (release it if we lose the race)
if (FastInterlockCompareExchangePointer(&m_pImporter, pIMDImport, NULL) != NULL)
pIMDImport->Release();
}
void PEFile::ConvertMDInternalToReadWrite()
{
CONTRACTL
{
INSTANCE_CHECK;
THROWS;
GC_NOTRIGGER;
MODE_ANY;
INJECT_FAULT(EX_THROW(EEMessageException, (E_OUTOFMEMORY)););
}
CONTRACTL_END;
IMDInternalImport *pOld; // Old (current RO) value of internal import.
IMDInternalImport *pNew = NULL; // New (RW) value of internal import.
// Take a local copy of *ppImport. This may be a pointer to an RO
// or to an RW MDInternalXX.
pOld = m_pMDImport;
IMetaDataImport *pIMDImport = m_pImporter;
if (pIMDImport != NULL)
{
HRESULT hr = GetMetaDataInternalInterfaceFromPublic(pIMDImport, IID_IMDInternalImport, (void **)&pNew);
if (FAILED(hr))
{
EX_THROW(EEMessageException, (hr));
}
if (pNew == pOld)
{
pNew->Release();
return;
}
}
else
{
// If an RO, convert to an RW, return S_OK. If already RW, no conversion
// needed, return S_FALSE.
HRESULT hr = ConvertMDInternalImport(pOld, &pNew);
if (FAILED(hr))
{
EX_THROW(EEMessageException, (hr));
}
// If no conversion took place, don't change pointers.
if (hr == S_FALSE)
return;
}
// Swap the pointers in a thread safe manner. If the contents of *ppImport
// equals pOld then no other thread got here first, and the old contents are
// replaced with pNew. The old contents are returned.
_ASSERTE(m_bHasPersistentMDImport);
if (FastInterlockCompareExchangePointer(&m_pMDImport, pNew, pOld) == pOld)
{
//if the debugger queries, it will now see that we have RW metadata
m_MDImportIsRW_Debugger_Use_Only = TRUE;
// Swapped -- get the metadata to hang onto the old Internal import.
HRESULT hr=m_pMDImport->SetUserContextData(pOld);
_ASSERTE(SUCCEEDED(hr)||!"Leaking old MDImport");
IfFailThrow(hr);
}
else
{ // Some other thread finished first. Just free the results of this conversion.
pNew->Release();
}
}
void PEFile::ConvertMetadataToRWForEnC()
{
CONTRACTL
{
THROWS;
GC_NOTRIGGER;
SO_INTOLERANT;
MODE_ANY;
}
CONTRACTL_END;
// This should only ever be called on EnC capable files.
// One can check this using Module::IsEditAndContinueCapable().
// This should only be called if we're debugging, stopped, and on the helper thread.
_ASSERTE(CORDebuggerAttached());
_ASSERTE((g_pDebugInterface != NULL) && g_pDebugInterface->ThisIsHelperThread());
_ASSERTE((g_pDebugInterface != NULL) && g_pDebugInterface->IsStopped());
// Convert the metadata to RW for Edit and Continue, properly replacing the metadata import interface pointer and
// properly preserving the old importer. This will be called before the EnC system tries to apply a delta to the module's
// metadata. ConvertMDInternalToReadWrite() does that quite nicely for us.
ConvertMDInternalToReadWrite();
}
void PEFile::OpenMDImport_Unsafe()
{
CONTRACTL
{
INSTANCE_CHECK;
THROWS;
GC_TRIGGERS;
MODE_ANY;
INJECT_FAULT(COMPlusThrowOM(););
}
CONTRACTL_END;
if (m_pMDImport != NULL)
return;
#ifdef FEATURE_PREJIT
if (m_nativeImage != NULL
&& m_nativeImage->GetMDImport() != NULL
)
{
// Use native image for metadata
m_flags |= PEFILE_HAS_NATIVE_IMAGE_METADATA;
m_pMDImport=m_nativeImage->GetMDImport();
}
else
#endif
{
#ifdef FEATURE_PREJIT
m_flags &= ~PEFILE_HAS_NATIVE_IMAGE_METADATA;
#endif
if (!IsDynamic()
&& GetILimage()->HasNTHeaders()
&& GetILimage()->HasCorHeader())
{
m_pMDImport=GetILimage()->GetMDImport();
}
else
ThrowHR(COR_E_BADIMAGEFORMAT);
m_bHasPersistentMDImport=TRUE;
}
_ASSERTE(m_pMDImport);
m_pMDImport->AddRef();
}
void PEFile::OpenEmitter()
{
CONTRACTL
{
INSTANCE_CHECK;
THROWS;
GC_NOTRIGGER;
MODE_ANY;
INJECT_FAULT(COMPlusThrowOM(););
}
CONTRACTL_END;
// Make sure internal MD is in RW format.
ConvertMDInternalToReadWrite();
IMetaDataEmit *pIMDEmit = NULL;
IfFailThrow(GetMetaDataPublicInterfaceFromInternal((void*)GetPersistentMDImport(),
IID_IMetaDataEmit,
(void **)&pIMDEmit));
// Atomically swap it into the field (release it if we lose the race)
if (FastInterlockCompareExchangePointer(&m_pEmitter, pIMDEmit, NULL) != NULL)
pIMDEmit->Release();
}
void PEFile::ReleaseMetadataInterfaces(BOOL bDestructor, BOOL bKeepNativeData/*=FALSE*/)
{
CONTRACTL
{
INSTANCE_CHECK;
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
PRECONDITION(bDestructor||m_pMetadataLock->IsWriterLock());
}
CONTRACTL_END;
_ASSERTE(bDestructor || !m_bHasPersistentMDImport);
if (m_pImporter != NULL)
{
m_pImporter->Release();
m_pImporter = NULL;
}
if (m_pEmitter != NULL)
{
m_pEmitter->Release();
m_pEmitter = NULL;
}
if (m_pMDImport != NULL && (!bKeepNativeData || !HasNativeImage()))
{
m_pMDImport->Release();
m_pMDImport=NULL;
}
}
// ------------------------------------------------------------
// PE file access
// ------------------------------------------------------------
// Note that most of these APIs are currently passed through
// to the main image. However, in the near future they will
// be rerouted to the native image in the prejitted case so
// we can avoid using the original IL image.
#endif //!DACCESS_COMPILE
#ifdef FEATURE_PREJIT
#ifndef DACCESS_COMPILE
// ------------------------------------------------------------
// Native image access
// ------------------------------------------------------------
void PEFile::SetNativeImage(PEImage *image)
{
CONTRACT_VOID
{
INSTANCE_CHECK;
PRECONDITION(!HasNativeImage());
STANDARD_VM_CHECK;
}
CONTRACT_END;
_ASSERTE(image != NULL);
PREFIX_ASSUME(image != NULL);
if (image->GetLoadedLayout()->GetBase() != image->GetLoadedLayout()->GetPreferredBase())
{
ExternalLog(LL_WARNING,
W("Native image loaded at base address") LFMT_ADDR
W("rather than preferred address:") LFMT_ADDR ,
DBG_ADDR(image->GetLoadedLayout()->GetBase()),
DBG_ADDR(image->GetLoadedLayout()->GetPreferredBase()));
}
#ifdef FEATURE_TREAT_NI_AS_MSIL_DURING_DIAGNOSTICS
// In Apollo, first ask if we're supposed to be ignoring the prejitted code &
// structures in NGENd images. If so, bail now and do not set m_nativeImage. We've
// already set m_identity & m_openedILimage (possibly even pointing to the
// NGEN/Triton image), and will use those PEImages to find and JIT IL (even if they
// point to an NGENd/Tritonized image).
if (ShouldTreatNIAsMSIL())
RETURN;
#endif
m_nativeImage = image;
m_nativeImage->AddRef();
m_nativeImage->Load();
m_nativeImage->AllocateLazyCOWPages();
#if defined(_TARGET_AMD64_) && !defined(CROSSGEN_COMPILE)
static ConfigDWORD configNGenReserveForJumpStubs;
int percentReserveForJumpStubs = configNGenReserveForJumpStubs.val(CLRConfig::INTERNAL_NGenReserveForJumpStubs);
if (percentReserveForJumpStubs != 0)
{
PEImageLayout * pLayout = image->GetLoadedLayout();
ExecutionManager::GetEEJitManager()->EnsureJumpStubReserve((BYTE *)pLayout->GetBase(), pLayout->GetVirtualSize(),
percentReserveForJumpStubs * (pLayout->GetVirtualSize() / 100));
}
#endif
ExternalLog(LL_INFO100, W("Attempting to use native image %s."), image->GetPath().GetUnicode());
RETURN;
}
void PEFile::ClearNativeImage()
{
CONTRACT_VOID
{
INSTANCE_CHECK;
PRECONDITION(HasNativeImage());
POSTCONDITION(!HasNativeImage());
THROWS;
GC_TRIGGERS;
MODE_ANY;
INJECT_FAULT(COMPlusThrowOM(););
}
CONTRACT_END;
ExternalLog(LL_WARNING, "Discarding native image.");
MarkNativeImageInvalidIfOwned();
{
GCX_PREEMP();
SafeComHolderPreemp<IMDInternalImport> pOldImport=GetMDImportWithRef();
SimpleWriteLockHolder lock(m_pMetadataLock);
EX_TRY
{
ReleaseMetadataInterfaces(FALSE);
m_flags &= ~PEFILE_HAS_NATIVE_IMAGE_METADATA;
if (m_nativeImage)
m_nativeImage->Release();
m_nativeImage = NULL;
// Make sure our normal image is open
EnsureImageOpened();
// Reopen metadata from normal image
OpenMDImport();
}
EX_HOOK
{
RestoreMDImport(pOldImport);
}
EX_END_HOOK;
}
RETURN;
}
extern DWORD g_dwLogLevel;
//===========================================================================================================
// Encapsulates CLR and Fusion logging for runtime verification of native images.
//===========================================================================================================
static void RuntimeVerifyVLog(DWORD level, LoggableAssembly *pLogAsm, const WCHAR *fmt, va_list args)
{
STANDARD_VM_CONTRACT;
BOOL fOutputToDebugger = (level == LL_ERROR && IsDebuggerPresent());
BOOL fOutputToLogging = LoggingOn(LF_ZAP, level);
StackSString message;
message.VPrintf(fmt, args);
if (fOutputToLogging)
{
SString displayString = pLogAsm->DisplayString();
LOG((LF_ZAP, level, "%s: \"%S\"\n", "ZAP", displayString.GetUnicode()));
LOG((LF_ZAP, level, "%S", message.GetUnicode()));
LOG((LF_ZAP, level, "\n"));
}
if (fOutputToDebugger)
{
SString displayString = pLogAsm->DisplayString();
WszOutputDebugString(W("CLR:("));
WszOutputDebugString(displayString.GetUnicode());
WszOutputDebugString(W(") "));
WszOutputDebugString(message);
WszOutputDebugString(W("\n"));
}
}
//===========================================================================================================
// Encapsulates CLR and Fusion logging for runtime verification of native images.
//===========================================================================================================
static void RuntimeVerifyLog(DWORD level, LoggableAssembly *pLogAsm, const WCHAR *fmt, ...)
{
STANDARD_VM_CONTRACT;
// Avoid calling RuntimeVerifyVLog unless logging is on
if ( ((level == LL_ERROR) && IsDebuggerPresent())
|| LoggingOn(LF_ZAP, level)
)
{
va_list args;
va_start(args, fmt);
RuntimeVerifyVLog(level, pLogAsm, fmt, args);
va_end(args);
}
}
//==============================================================================
static const LPCWSTR CorCompileRuntimeDllNames[NUM_RUNTIME_DLLS] =
{
MAKEDLLNAME_W(W("coreclr")),
MAKEDLLNAME_W(W("clrjit"))
};
LPCWSTR CorCompileGetRuntimeDllName(CorCompileRuntimeDlls id)
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
MODE_ANY;
SO_INTOLERANT;
INJECT_FAULT(COMPlusThrowOM(););
}
CONTRACTL_END;
return CorCompileRuntimeDllNames[id];
}
#ifndef CROSSGEN_COMPILE
//==============================================================================
// Will always return a valid HMODULE for CLR_INFO, but will return NULL for NGEN_COMPILER_INFO
// if the DLL has not yet been loaded (it does not try to cause a load).
// Gets set by IJitManager::LoadJit (yes, this breaks the abstraction boundary).
HMODULE s_ngenCompilerDll = NULL;
extern HMODULE CorCompileGetRuntimeDll(CorCompileRuntimeDlls id)
{
CONTRACTL
{
THROWS;
GC_NOTRIGGER;
MODE_ANY;
SO_INTOLERANT;
INJECT_FAULT(COMPlusThrowOM(););
}
CONTRACTL_END;
// Currently special cased for every entry.
static_assert_no_msg(NUM_RUNTIME_DLLS == 2);
static_assert_no_msg(CORECLR_INFO == 0);
HMODULE hMod = NULL;
// Try to load the correct DLL
switch (id)
{
case CORECLR_INFO:
hMod = GetCLRModule();
break;
default:
COMPlusThrowNonLocalized(kExecutionEngineException,
W("Invalid runtime DLL ID"));
break;
}
return hMod;
}
#endif // CROSSGEN_COMPILE
//===========================================================================================================
// Helper for RuntimeVerifyNativeImageVersion(). Compares the loaded clr.dll and clrjit.dll's against
// the ones the native image was compiled against.
//===========================================================================================================
static BOOL RuntimeVerifyNativeImageTimestamps(const CORCOMPILE_VERSION_INFO *info, LoggableAssembly *pLogAsm)
{
STANDARD_VM_CONTRACT;
return TRUE;
}
//===========================================================================================================
// Validates that an NI matches the running CLR, OS, CPU, etc. This is the entrypoint used by the CLR loader.
//
//===========================================================================================================
BOOL PEAssembly::CheckNativeImageVersion(PEImage *peimage)
{
STANDARD_VM_CONTRACT;
//
// Get the zap version header. Note that modules will not have version
// headers - they add no additional versioning constraints from their
// assemblies.
//
PEImageLayoutHolder image=peimage->GetLayout(PEImageLayout::LAYOUT_ANY,PEImage::LAYOUT_CREATEIFNEEDED);
if (!image->HasNativeHeader())
return FALSE;
if (!image->CheckNativeHeaderVersion())
{
// Wrong native image version is fatal error on CoreCLR
ThrowHR(COR_E_NI_AND_RUNTIME_VERSION_MISMATCH);
}
CORCOMPILE_VERSION_INFO *info = image->GetNativeVersionInfo();
if (info == NULL)
return FALSE;
LoggablePEAssembly logAsm(this);
if (!RuntimeVerifyNativeImageVersion(info, &logAsm))
{
// Wrong native image version is fatal error on CoreCLR
ThrowHR(COR_E_NI_AND_RUNTIME_VERSION_MISMATCH);
}
CorCompileConfigFlags configFlags = PEFile::GetNativeImageConfigFlagsWithOverrides();
// Otherwise, match regardless of the instrumentation flags
configFlags = (CorCompileConfigFlags) (configFlags & ~(CORCOMPILE_CONFIG_INSTRUMENTATION_NONE | CORCOMPILE_CONFIG_INSTRUMENTATION));
if ((info->wConfigFlags & configFlags) != configFlags)
{
return FALSE;
}
return TRUE;
}
//===========================================================================================================
// Validates that an NI matches the running CLR, OS, CPU, etc.
//
// For historial reasons, some versions of the runtime perform this check at native bind time (preferrred),
// while others check at CLR load time.
//
// This is the common funnel for both versions and is agnostic to whether the "assembly" is represented
// by a CLR object or Fusion object.
//===========================================================================================================
BOOL RuntimeVerifyNativeImageVersion(const CORCOMPILE_VERSION_INFO *info, LoggableAssembly *pLogAsm)
{
STANDARD_VM_CONTRACT;
if (!RuntimeVerifyNativeImageTimestamps(info, pLogAsm))
return FALSE;
//
// Check that the EE version numbers are the same.
//
if (info->wVersionMajor != VER_MAJORVERSION
|| info->wVersionMinor != VER_MINORVERSION
|| info->wVersionBuildNumber != VER_PRODUCTBUILD
|| info->wVersionPrivateBuildNumber != VER_PRODUCTBUILD_QFE)
{
RuntimeVerifyLog(LL_ERROR, pLogAsm, W("CLR version recorded in native image doesn't match the current CLR."));
return FALSE;
}
//
// Check checked/free status
//
if (info->wBuild !=
#if _DEBUG
CORCOMPILE_BUILD_CHECKED
#else
CORCOMPILE_BUILD_FREE
#endif
)
{
RuntimeVerifyLog(LL_ERROR, pLogAsm, W("Checked/free mismatch with native image."));
return FALSE;
}
//
// Check processor
//
if (info->wMachine != IMAGE_FILE_MACHINE_NATIVE_NI)
{
RuntimeVerifyLog(LL_ERROR, pLogAsm, W("Processor type recorded in native image doesn't match this machine's processor."));
return FALSE;
}
#ifndef CROSSGEN_COMPILE
//
// Check the processor specific ID
//
CORINFO_CPU cpuInfo;
GetSpecificCpuInfo(&cpuInfo);
if (!IsCompatibleCpuInfo(&cpuInfo, &info->cpuInfo))
{
RuntimeVerifyLog(LL_ERROR, pLogAsm, W("Required CPU features recorded in native image don't match this machine's processor."));
return FALSE;
}
#endif // CROSSGEN_COMPILE
//
// The zap is up to date.
//
RuntimeVerifyLog(LL_INFO100, pLogAsm, W("Native image has correct version information."));
return TRUE;
}
#endif // !DACCESS_COMPILE
/* static */
CorCompileConfigFlags PEFile::GetNativeImageConfigFlags(BOOL fForceDebug/*=FALSE*/,
BOOL fForceProfiling/*=FALSE*/,
BOOL fForceInstrument/*=FALSE*/)
{
LIMITED_METHOD_DAC_CONTRACT;
CorCompileConfigFlags result = (CorCompileConfigFlags)0;
// Debugging
#ifdef DEBUGGING_SUPPORTED
// if these have been set, the take precedence over anything else
if (s_NGENDebugFlags)
{
if ((s_NGENDebugFlags & CORCOMPILE_CONFIG_DEBUG_NONE) != 0)
{
result = (CorCompileConfigFlags) (result|CORCOMPILE_CONFIG_DEBUG_NONE);
}
else
{
if ((s_NGENDebugFlags & CORCOMPILE_CONFIG_DEBUG) != 0)
{
result = (CorCompileConfigFlags) (result|CORCOMPILE_CONFIG_DEBUG);
}
}
}
else
#endif // DEBUGGING_SUPPORTED
{
if (fForceDebug)
{
result = (CorCompileConfigFlags) (result|CORCOMPILE_CONFIG_DEBUG);
}
else
{
result = (CorCompileConfigFlags) (result|CORCOMPILE_CONFIG_DEBUG_DEFAULT);
}
}
// Profiling
#ifdef PROFILING_SUPPORTED
if (fForceProfiling || CORProfilerUseProfileImages())
{
result = (CorCompileConfigFlags) (result|CORCOMPILE_CONFIG_PROFILING);
result = (CorCompileConfigFlags) (result & ~(CORCOMPILE_CONFIG_DEBUG_NONE|
CORCOMPILE_CONFIG_DEBUG|
CORCOMPILE_CONFIG_DEBUG_DEFAULT));
}
else
#endif //PROFILING_SUPPORTED
result = (CorCompileConfigFlags) (result|CORCOMPILE_CONFIG_PROFILING_NONE);
// Instrumentation
#ifndef DACCESS_COMPILE
BOOL instrumented = (!IsCompilationProcess() && g_pConfig->GetZapBBInstr());
#else
BOOL instrumented = FALSE;
#endif
if (instrumented || fForceInstrument)
{
result = (CorCompileConfigFlags) (result|CORCOMPILE_CONFIG_INSTRUMENTATION);
}
else
{
result = (CorCompileConfigFlags) (result|CORCOMPILE_CONFIG_INSTRUMENTATION_NONE);
}
// NOTE: Right now we are not taking instrumentation into account when binding.
return result;
}
CorCompileConfigFlags PEFile::GetNativeImageConfigFlagsWithOverrides()
{
LIMITED_METHOD_DAC_CONTRACT;
BOOL fForceDebug, fForceProfiling, fForceInstrument;
SystemDomain::GetCompilationOverrides(&fForceDebug,
&fForceProfiling,
&fForceInstrument);
return PEFile::GetNativeImageConfigFlags(fForceDebug,
fForceProfiling,
fForceInstrument);
}
#ifndef DACCESS_COMPILE
//===========================================================================================================
// Validates that a hard-dep matches the a parent NI's compile-time hard-dep.
//
// For historial reasons, some versions of the runtime perform this check at native bind time (preferrred),
// while others check at CLR load time.
//
// This is the common funnel for both versions and is agnostic to whether the "assembly" is represented
// by a CLR object or Fusion object.
//
//===========================================================================================================
BOOL RuntimeVerifyNativeImageDependency(const CORCOMPILE_NGEN_SIGNATURE &ngenSigExpected,
const CORCOMPILE_VERSION_INFO *pActual,
LoggableAssembly *pLogAsm)
{
STANDARD_VM_CONTRACT;
if (ngenSigExpected != pActual->signature)
{
// Signature did not match
SString displayString = pLogAsm->DisplayString();
RuntimeVerifyLog(LL_ERROR,
pLogAsm,
W("Rejecting native image because native image dependency %s ")
W("had a different identity than expected"),
displayString.GetUnicode());
return FALSE;
}
return TRUE;
}
// Wrapper function for use by parts of the runtime that actually have a CORCOMPILE_DEPENDENCY to work with.
BOOL RuntimeVerifyNativeImageDependency(const CORCOMPILE_DEPENDENCY *pExpected,
const CORCOMPILE_VERSION_INFO *pActual,
LoggableAssembly *pLogAsm)
{
WRAPPER_NO_CONTRACT;
return RuntimeVerifyNativeImageDependency(pExpected->signNativeImage,
pActual,
pLogAsm);
}
#endif // !DACCESS_COMPILE
#ifdef DEBUGGING_SUPPORTED
//
// Called through ICorDebugAppDomain2::SetDesiredNGENCompilerFlags to specify
// which kinds of ngen'd images fusion should load wrt debugging support
// Overrides any previous settings
//
void PEFile::SetNGENDebugFlags(BOOL fAllowOpt)
{
CONTRACTL
{
GC_NOTRIGGER;
NOTHROW;
MODE_ANY;
SUPPORTS_DAC;
}
CONTRACTL_END;
if (fAllowOpt)
s_NGENDebugFlags = CORCOMPILE_CONFIG_DEBUG_NONE;
else
s_NGENDebugFlags = CORCOMPILE_CONFIG_DEBUG;
}
//
// Called through ICorDebugAppDomain2::GetDesiredNGENCompilerFlags to determine
// which kinds of ngen'd images fusion should load wrt debugging support
//
void PEFile::GetNGENDebugFlags(BOOL *fAllowOpt)
{
CONTRACTL
{
GC_NOTRIGGER;
NOTHROW;
MODE_ANY;
SUPPORTS_DAC;
}
CONTRACTL_END;
CorCompileConfigFlags configFlags = PEFile::GetNativeImageConfigFlagsWithOverrides();
*fAllowOpt = ((configFlags & CORCOMPILE_CONFIG_DEBUG) == 0);
}
#endif // DEBUGGING_SUPPORTED
#ifndef DACCESS_COMPILE
#ifdef FEATURE_TREAT_NI_AS_MSIL_DURING_DIAGNOSTICS
//---------------------------------------------------------------------------------------
//
// Used in Apollo, this method determines whether profiling or debugging has requested
// the runtime to provide debuggable / profileable code. In other CLR builds, this would
// normally result in requiring the appropriate NGEN scenario be loaded (/Debug or
// /Profile) and to JIT if unavailable. In Apollo, however, these NGEN scenarios are
// never available, and even MSIL assemblies are often not available. So this function
// tells its caller to use the NGENd assembly as if it were an MSIL assembly--ignore the
// prejitted code and prebaked structures, and just JIT code and load classes from
// scratch.
//
// Return Value:
// nonzero iff NGENd images should be treated as MSIL images.
//
// static
BOOL PEFile::ShouldTreatNIAsMSIL()
{
LIMITED_METHOD_CONTRACT;
// Never use fragile native image content during ReadyToRun compilation. It would
// produces non-version resilient images because of wrong cached values for
// MethodTable::IsLayoutFixedInCurrentVersionBubble, etc.
if (IsReadyToRunCompilation())
return TRUE;
// Ask profiling API & config vars whether NGENd images should be avoided
// completely.
if (!NGENImagesAllowed())
return TRUE;
// Ask profiling and debugging if they're requesting us to use ngen /Debug or
// /Profile images (which aren't available under Apollo)
CorCompileConfigFlags configFlags = PEFile::GetNativeImageConfigFlagsWithOverrides();
if ((configFlags & (CORCOMPILE_CONFIG_DEBUG | CORCOMPILE_CONFIG_PROFILING)) != 0)
return TRUE;
return FALSE;
}
#endif // FEATURE_TREAT_NI_AS_MSIL_DURING_DIAGNOSTICS
#endif //!DACCESS_COMPILE
#endif // FEATURE_PREJIT
#ifndef DACCESS_COMPILE
// ------------------------------------------------------------
// Resource access
// ------------------------------------------------------------
void PEFile::GetEmbeddedResource(DWORD dwOffset, DWORD *cbResource, PBYTE *pbInMemoryResource)
{
CONTRACTL
{
INSTANCE_CHECK;
THROWS;
GC_TRIGGERS;
MODE_ANY;
INJECT_FAULT(ThrowOutOfMemory(););
}
CONTRACTL_END;
// NOTE: it's not clear whether to load this from m_image or m_loadedImage.
// m_loadedImage is probably preferable, but this may be called by security
// before the image is loaded.
PEImage *image;
#ifdef FEATURE_PREJIT
if (m_nativeImage != NULL)
image = m_nativeImage;
else
#endif
{
EnsureImageOpened();
image = GetILimage();
}
PEImageLayoutHolder theImage(image->GetLayout(PEImageLayout::LAYOUT_ANY,PEImage::LAYOUT_CREATEIFNEEDED));
if (!theImage->CheckResource(dwOffset))
ThrowHR(COR_E_BADIMAGEFORMAT);
COUNT_T size;
const void *resource = theImage->GetResource(dwOffset, &size);
*cbResource = size;
*pbInMemoryResource = (PBYTE) resource;
}
// ------------------------------------------------------------
// File loading
// ------------------------------------------------------------
PEAssembly *
PEFile::LoadAssembly(
mdAssemblyRef kAssemblyRef,
IMDInternalImport * pImport, // = NULL
LPCUTF8 szWinRtTypeNamespace, // = NULL
LPCUTF8 szWinRtTypeClassName) // = NULL
{
CONTRACT(PEAssembly *)
{
INSTANCE_CHECK;
THROWS;
GC_TRIGGERS;
MODE_ANY;
POSTCONDITION(CheckPointer(RETVAL));
INJECT_FAULT(COMPlusThrowOM(););
}
CONTRACT_END;
if (pImport == NULL)
pImport = GetPersistentMDImport();
if (((TypeFromToken(kAssemblyRef) != mdtAssembly) &&
(TypeFromToken(kAssemblyRef) != mdtAssemblyRef)) ||
(!pImport->IsValidToken(kAssemblyRef)))
{
ThrowHR(COR_E_BADIMAGEFORMAT);
}
AssemblySpec spec;
spec.InitializeSpec(kAssemblyRef, pImport, GetAppDomain()->FindAssembly(GetAssembly()), IsIntrospectionOnly());
if (szWinRtTypeClassName != NULL)
spec.SetWindowsRuntimeType(szWinRtTypeNamespace, szWinRtTypeClassName);
RETURN GetAppDomain()->BindAssemblySpec(&spec, TRUE, IsIntrospectionOnly());
}
// ------------------------------------------------------------
// Logging
// ------------------------------------------------------------
#ifdef FEATURE_PREJIT
void PEFile::ExternalLog(DWORD facility, DWORD level, const WCHAR *fmt, ...)
{
WRAPPER_NO_CONTRACT;
va_list args;
va_start(args, fmt);
ExternalVLog(facility, level, fmt, args);
va_end(args);
}
void PEFile::ExternalLog(DWORD level, const WCHAR *fmt, ...)
{
WRAPPER_NO_CONTRACT;
va_list args;
va_start(args, fmt);
ExternalVLog(LF_ZAP, level, fmt, args);
va_end(args);
}
void PEFile::ExternalLog(DWORD level, const char *msg)
{
WRAPPER_NO_CONTRACT;
// It is OK to use %S here. We know that msg is ASCII-only.
ExternalLog(level, W("%S"), msg);
}
void PEFile::ExternalVLog(DWORD facility, DWORD level, const WCHAR *fmt, va_list args)
{
CONTRACT_VOID
{
THROWS;
GC_TRIGGERS;
}
CONTRACT_END;
BOOL fOutputToDebugger = (level == LL_ERROR && IsDebuggerPresent());
BOOL fOutputToLogging = LoggingOn(facility, level);
if (!fOutputToDebugger && !fOutputToLogging)
return;
StackSString message;
message.VPrintf(fmt, args);
if (fOutputToLogging)
{
if (GetMDImport() != NULL)
LOG((facility, level, "%s: \"%s\"\n", (facility == LF_ZAP ? "ZAP" : "LOADER"), GetSimpleName()));
else
LOG((facility, level, "%s: \"%S\"\n", (facility == LF_ZAP ? "ZAP" : "LOADER"), ((const WCHAR *)GetPath())));
LOG((facility, level, "%S", message.GetUnicode()));
LOG((facility, level, "\n"));
}
if (fOutputToDebugger)
{
WszOutputDebugString(W("CLR:("));
StackSString codebase;
GetCodeBaseOrName(codebase);
WszOutputDebugString(codebase);
WszOutputDebugString(W(") "));
WszOutputDebugString(message);
WszOutputDebugString(W("\n"));
}
RETURN;
}
void PEFile::FlushExternalLog()
{
LIMITED_METHOD_CONTRACT;
}
#endif
BOOL PEFile::GetResource(LPCSTR szName, DWORD *cbResource,
PBYTE *pbInMemoryResource, DomainAssembly** pAssemblyRef,
LPCSTR *szFileName, DWORD *dwLocation,
StackCrawlMark *pStackMark, BOOL fSkipSecurityCheck,
BOOL fSkipRaiseResolveEvent, DomainAssembly* pDomainAssembly, AppDomain* pAppDomain)
{
CONTRACTL
{
INSTANCE_CHECK;
THROWS;
MODE_ANY;
INJECT_FAULT(COMPlusThrowOM(););
WRAPPER(GC_TRIGGERS);
}
CONTRACTL_END;
mdToken mdLinkRef;
DWORD dwResourceFlags;
DWORD dwOffset;
mdManifestResource mdResource;
Assembly* pAssembly = NULL;
PEFile* pPEFile = NULL;
ReleaseHolder<IMDInternalImport> pImport (GetMDImportWithRef());
if (SUCCEEDED(pImport->FindManifestResourceByName(szName, &mdResource)))
{
pPEFile = this;
IfFailThrow(pImport->GetManifestResourceProps(
mdResource,
NULL, //&szName,
&mdLinkRef,
&dwOffset,
&dwResourceFlags));
}
else
{
if (fSkipRaiseResolveEvent || pAppDomain == NULL)
return FALSE;
DomainAssembly* pParentAssembly = GetAppDomain()->FindAssembly(GetAssembly());
pAssembly = pAppDomain->RaiseResourceResolveEvent(pParentAssembly, szName);
if (pAssembly == NULL)
return FALSE;
pDomainAssembly = pAssembly->GetDomainAssembly(pAppDomain);
pPEFile = pDomainAssembly->GetFile();
if (FAILED(pAssembly->GetManifestImport()->FindManifestResourceByName(
szName,
&mdResource)))
{
return FALSE;
}
if (dwLocation != 0)
{
if (pAssemblyRef != NULL)
*pAssemblyRef = pDomainAssembly;
*dwLocation = *dwLocation | 2; // ResourceLocation.containedInAnotherAssembly
}
IfFailThrow(pPEFile->GetPersistentMDImport()->GetManifestResourceProps(
mdResource,
NULL, //&szName,
&mdLinkRef,
&dwOffset,
&dwResourceFlags));
}
switch(TypeFromToken(mdLinkRef)) {
case mdtAssemblyRef:
{
if (pDomainAssembly == NULL)
return FALSE;
AssemblySpec spec;
spec.InitializeSpec(mdLinkRef, GetPersistentMDImport(), pDomainAssembly, pDomainAssembly->GetFile()->IsIntrospectionOnly());
pDomainAssembly = spec.LoadDomainAssembly(FILE_LOADED);
if (dwLocation) {
if (pAssemblyRef)
*pAssemblyRef = pDomainAssembly;
*dwLocation = *dwLocation | 2; // ResourceLocation.containedInAnotherAssembly
}
return pDomainAssembly->GetResource(szName,
cbResource,
pbInMemoryResource,
pAssemblyRef,
szFileName,
dwLocation,
pStackMark,
fSkipSecurityCheck,
fSkipRaiseResolveEvent);
}
case mdtFile:
if (mdLinkRef == mdFileNil)
{
// The resource is embedded in the manifest file
#ifndef CROSSGEN_COMPILE
if (!IsMrPublic(dwResourceFlags) && pStackMark && !fSkipSecurityCheck)
{
Assembly *pCallersAssembly = SystemDomain::GetCallersAssembly(pStackMark);
if (pCallersAssembly && // full trust for interop
(!pCallersAssembly->GetManifestFile()->Equals(this)))
{
RefSecContext sCtx(AccessCheckOptions::kMemberAccess);
AccessCheckOptions accessCheckOptions(
AccessCheckOptions::kMemberAccess, /*accessCheckType*/
NULL, /*pAccessContext*/
FALSE, /*throwIfTargetIsInaccessible*/
(MethodTable *) NULL /*pTargetMT*/
);
// SL: return TRUE only if the caller is critical
// Desktop: return TRUE only if demanding MemberAccess succeeds
if (!accessCheckOptions.DemandMemberAccessOrFail(&sCtx, NULL, TRUE /*visibilityCheck*/))
return FALSE;
}
}
#endif // CROSSGEN_COMPILE
if (dwLocation) {
*dwLocation = *dwLocation | 5; // ResourceLocation.embedded |
// ResourceLocation.containedInManifestFile
return TRUE;
}
pPEFile->GetEmbeddedResource(dwOffset, cbResource, pbInMemoryResource);
return TRUE;
}
return FALSE;
default:
ThrowHR(COR_E_BADIMAGEFORMAT, BFA_INVALID_TOKEN_IN_MANIFESTRES);
}
}
void PEFile::GetPEKindAndMachine(DWORD* pdwKind, DWORD* pdwMachine)
{
WRAPPER_NO_CONTRACT;
if (IsResource() || IsDynamic())
{
if (pdwKind)
*pdwKind = 0;
if (pdwMachine)
*pdwMachine = 0;
return;
}
#ifdef FEATURE_PREJIT
if (IsNativeLoaded())
{
CONSISTENCY_CHECK(HasNativeImage());
m_nativeImage->GetNativeILPEKindAndMachine(pdwKind, pdwMachine);
return;
}
#ifndef DACCESS_COMPILE
if (!HasOpenedILimage())
{
//don't want to touch the IL image unless we already have
ReleaseHolder<PEImage> pNativeImage = GetNativeImageWithRef();
if (pNativeImage)
{
pNativeImage->GetNativeILPEKindAndMachine(pdwKind, pdwMachine);
return;
}
}
#endif // DACCESS_COMPILE
#endif // FEATURE_PREJIT
GetILimage()->GetPEKindAndMachine(pdwKind, pdwMachine);
return;
}
ULONG PEFile::GetILImageTimeDateStamp()
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
}
CONTRACTL_END;
#ifdef FEATURE_PREJIT
if (IsNativeLoaded())
{
CONSISTENCY_CHECK(HasNativeImage());
// The IL image's time stamp is copied to the native image.
CORCOMPILE_VERSION_INFO* pVersionInfo = GetLoadedNative()->GetNativeVersionInfoMaybeNull();
if (pVersionInfo == NULL)
{
return 0;
}
else
{
return pVersionInfo->sourceAssembly.timeStamp;
}
}
#endif // FEATURE_PREJIT
return GetLoadedIL()->GetTimeDateStamp();
}
// ================================================================================
// PEAssembly class - a PEFile which represents an assembly
// ================================================================================
// Statics initialization.
/* static */
void PEAssembly::Attach()
{
STANDARD_VM_CONTRACT;
}
PEAssembly::PEAssembly(
CoreBindResult* pBindResultInfo,
IMetaDataEmit* pEmit,
PEFile *creator,
BOOL system,
BOOL introspectionOnly/*=FALSE*/,
PEImage * pPEImageIL /*= NULL*/,
PEImage * pPEImageNI /*= NULL*/,
ICLRPrivAssembly * pHostAssembly /*= NULL*/)
: PEFile(pBindResultInfo ? (pBindResultInfo->GetPEImage() ? pBindResultInfo->GetPEImage() :
(pBindResultInfo->HasNativeImage() ? pBindResultInfo->GetNativeImage() : NULL)
): pPEImageIL? pPEImageIL:(pPEImageNI? pPEImageNI:NULL), FALSE),
m_creator(clr::SafeAddRef(creator)),
m_bIsFromGAC(FALSE),
m_bIsOnTpaList(FALSE)
,m_fProfileAssembly(0)
{
CONTRACTL
{
CONSTRUCTOR_CHECK;
PRECONDITION(CheckPointer(pEmit, NULL_OK));
PRECONDITION(CheckPointer(creator, NULL_OK));
PRECONDITION(pBindResultInfo == NULL || (pPEImageIL == NULL && pPEImageNI == NULL));
STANDARD_VM_CHECK;
}
CONTRACTL_END;
if (introspectionOnly)
{
if (!system) // Implementation restriction: mscorlib.dll cannot be loaded as introspection. The architecture depends on there being exactly one mscorlib.
{
m_flags |= PEFILE_INTROSPECTIONONLY;
}
}
m_flags |= PEFILE_ASSEMBLY;
if (system)
m_flags |= PEFILE_SYSTEM;
// We check the precondition above that either pBindResultInfo is null or both pPEImageIL and pPEImageNI are,
// so we'll only get a max of one native image passed in.
if (pPEImageNI != NULL)
{
SetNativeImage(pPEImageNI);
}
#ifdef FEATURE_PREJIT
if (pBindResultInfo && pBindResultInfo->HasNativeImage())
SetNativeImage(pBindResultInfo->GetNativeImage());
#endif
// If we have no native image, we require a mapping for the file.
if (!HasNativeImage() || !IsILOnly())
EnsureImageOpened();
// Initialize the status of the assembly being in the GAC, or being part of the TPA list, before
// we start to do work (like strong name verification) that relies on those states to be valid.
if(pBindResultInfo != nullptr)
{
m_bIsFromGAC = pBindResultInfo->IsFromGAC();
m_bIsOnTpaList = pBindResultInfo->IsOnTpaList();
}
// Check security related stuff
VerifyStrongName();
// Open metadata eagerly to minimize failure windows
if (pEmit == NULL)
OpenMDImport_Unsafe(); //constructor, cannot race with anything
else
{
_ASSERTE(!m_bHasPersistentMDImport);
IfFailThrow(GetMetaDataInternalInterfaceFromPublic(pEmit, IID_IMDInternalImport,
(void **)&m_pMDImport));
m_pEmitter = pEmit;
pEmit->AddRef();
m_bHasPersistentMDImport=TRUE;
m_MDImportIsRW_Debugger_Use_Only = TRUE;
}
// m_pMDImport can be external
// Make sure this is an assembly
if (!m_pMDImport->IsValidToken(TokenFromRid(1, mdtAssembly)))
ThrowHR(COR_E_ASSEMBLYEXPECTED);
// Verify name eagerly
LPCUTF8 szName = GetSimpleName();
if (!*szName)
{
ThrowHR(COR_E_BADIMAGEFORMAT, BFA_EMPTY_ASSEMDEF_NAME);
}
// Set the host assembly and binding context as the AssemblySpec initialization
// for CoreCLR will expect to have it set.
if (pHostAssembly != nullptr)
{
m_pHostAssembly = clr::SafeAddRef(pHostAssembly);
}
if(pBindResultInfo != nullptr)
{
// Cannot have both pHostAssembly and a coreclr based bind
_ASSERTE(pHostAssembly == nullptr);
pBindResultInfo->GetBindAssembly(&m_pHostAssembly);
}
#if _DEBUG
GetCodeBaseOrName(m_debugName);
m_debugName.Normalize();
m_pDebugName = m_debugName;
AssemblySpec spec;
spec.InitializeSpec(this);
spec.GetFileOrDisplayName(ASM_DISPLAYF_VERSION |
ASM_DISPLAYF_CULTURE |
ASM_DISPLAYF_PUBLIC_KEY_TOKEN,
m_sTextualIdentity);
#endif
}
PEAssembly *PEAssembly::Open(
PEAssembly * pParent,
PEImage * pPEImageIL,
PEImage * pPEImageNI,
ICLRPrivAssembly * pHostAssembly,
BOOL fIsIntrospectionOnly)
{
STANDARD_VM_CONTRACT;
PEAssembly * pPEAssembly = new PEAssembly(
nullptr, // BindResult
nullptr, // IMetaDataEmit
pParent, // PEFile creator
FALSE, // isSystem
fIsIntrospectionOnly,
pPEImageIL,
pPEImageNI,
pHostAssembly);
return pPEAssembly;
}
PEAssembly::~PEAssembly()
{
CONTRACTL
{
DESTRUCTOR_CHECK;
NOTHROW;
GC_TRIGGERS; // Fusion uses crsts on AddRef/Release
MODE_ANY;
}
CONTRACTL_END;
GCX_PREEMP();
if (m_creator != NULL)
m_creator->Release();
}
#ifndef DACCESS_COMPILE
void PEAssembly::ReleaseIL()
{
CONTRACTL
{
INSTANCE_CHECK;
NOTHROW;
GC_TRIGGERS;
MODE_ANY;
}
CONTRACTL_END;
GCX_PREEMP();
if (m_creator != NULL)
{
m_creator->Release();
m_creator=NULL;
}
PEFile::ReleaseIL();
}
#endif
/* static */
PEAssembly *PEAssembly::OpenSystem(IUnknown * pAppCtx)
{
STANDARD_VM_CONTRACT;
PEAssembly *result = NULL;
EX_TRY
{
result = DoOpenSystem(pAppCtx);
}
EX_HOOK
{
Exception *ex = GET_EXCEPTION();
// Rethrow non-transient exceptions as file load exceptions with proper
// context
if (!ex->IsTransient())
EEFileLoadException::Throw(SystemDomain::System()->BaseLibrary(), ex->GetHR(), ex);
}
EX_END_HOOK;
return result;
}
/* static */
PEAssembly *PEAssembly::DoOpenSystem(IUnknown * pAppCtx)
{
CONTRACT(PEAssembly *)
{
POSTCONDITION(CheckPointer(RETVAL));
STANDARD_VM_CHECK;
}
CONTRACT_END;
ETWOnStartup (FusionBinding_V1, FusionBindingEnd_V1);
CoreBindResult bindResult;
ReleaseHolder<ICLRPrivAssembly> pPrivAsm;
IfFailThrow(CCoreCLRBinderHelper::BindToSystem(&pPrivAsm, !IsCompilationProcess() || g_fAllowNativeImages));
if(pPrivAsm != NULL)
{
bindResult.Init(pPrivAsm, TRUE, TRUE);
}
RETURN new PEAssembly(&bindResult, NULL, NULL, TRUE, FALSE);
}
#ifndef CROSSGEN_COMPILE
/* static */
PEAssembly *PEAssembly::OpenMemory(PEAssembly *pParentAssembly,
const void *flat, COUNT_T size,
BOOL isIntrospectionOnly/*=FALSE*/,
CLRPrivBinderLoadFile* pBinderToUse)
{
STANDARD_VM_CONTRACT;
PEAssembly *result = NULL;
EX_TRY
{
result = DoOpenMemory(pParentAssembly, flat, size, isIntrospectionOnly, pBinderToUse);
}
EX_HOOK
{
Exception *ex = GET_EXCEPTION();
// Rethrow non-transient exceptions as file load exceptions with proper
// context
if (!ex->IsTransient())
EEFileLoadException::Throw(pParentAssembly, flat, size, ex->GetHR(), ex);
}
EX_END_HOOK;
return result;
}
// Thread stress
class DoOpenFlatStress : APIThreadStress
{
public:
PEAssembly *pParentAssembly;
const void *flat;
COUNT_T size;
DoOpenFlatStress(PEAssembly *pParentAssembly, const void *flat, COUNT_T size)
: pParentAssembly(pParentAssembly), flat(flat), size(size) {LIMITED_METHOD_CONTRACT;}
void Invoke()
{
WRAPPER_NO_CONTRACT;
PEAssemblyHolder result(PEAssembly::OpenMemory(pParentAssembly, flat, size, FALSE));
}
};
/* static */
PEAssembly *PEAssembly::DoOpenMemory(
PEAssembly *pParentAssembly,
const void *flat,
COUNT_T size,
BOOL isIntrospectionOnly,
CLRPrivBinderLoadFile* pBinderToUse)
{
CONTRACT(PEAssembly *)
{
PRECONDITION(CheckPointer(flat));
PRECONDITION(CheckOverflow(flat, size));
PRECONDITION(CheckPointer(pParentAssembly));
STANDARD_VM_CHECK;
POSTCONDITION(CheckPointer(RETVAL));
}
CONTRACT_END;
// Thread stress
DoOpenFlatStress ts(pParentAssembly, flat, size);
// Note that we must have a flat image stashed away for two reasons.
// First, we need a private copy of the data which we can verify
// before doing the mapping. And secondly, we can only compute
// the strong name hash on a flat image.
PEImageHolder image(PEImage::LoadFlat(flat, size));
// Need to verify that this is a CLR assembly
if (!image->CheckILFormat())
ThrowHR(COR_E_BADIMAGEFORMAT, BFA_BAD_IL);
CoreBindResult bindResult;
ReleaseHolder<ICLRPrivAssembly> assembly;
IfFailThrow(CCoreCLRBinderHelper::GetAssemblyFromImage(image, NULL, &assembly));
bindResult.Init(assembly,FALSE,FALSE);
RETURN new PEAssembly(&bindResult, NULL, pParentAssembly, FALSE, isIntrospectionOnly);
}
#endif // !CROSSGEN_COMPILE
PEAssembly* PEAssembly::Open(CoreBindResult* pBindResult,
BOOL isSystem, BOOL isIntrospectionOnly)
{
return new PEAssembly(pBindResult,NULL,NULL,isSystem,isIntrospectionOnly);
};
/* static */
PEAssembly *PEAssembly::Create(PEAssembly *pParentAssembly,
IMetaDataAssemblyEmit *pAssemblyEmit,
BOOL bIsIntrospectionOnly)
{
CONTRACT(PEAssembly *)
{
PRECONDITION(CheckPointer(pParentAssembly));
PRECONDITION(CheckPointer(pAssemblyEmit));
STANDARD_VM_CHECK;
POSTCONDITION(CheckPointer(RETVAL));
}
CONTRACT_END;
// Set up the metadata pointers in the PEAssembly. (This is the only identity
// we have.)
SafeComHolder<IMetaDataEmit> pEmit;
pAssemblyEmit->QueryInterface(IID_IMetaDataEmit, (void **)&pEmit);
PEAssemblyHolder pFile(new PEAssembly(NULL, pEmit, pParentAssembly, FALSE, bIsIntrospectionOnly));
RETURN pFile.Extract();
}
#ifdef FEATURE_PREJIT
void PEAssembly::SetNativeImage(PEImage * image)
{
CONTRACTL
{
INSTANCE_CHECK;
STANDARD_VM_CHECK;
}
CONTRACTL_END;
image->Load();
if (CheckNativeImageVersion(image))
{
PEFile::SetNativeImage(image);
#if 0
//Enable this code if you want to make sure we never touch the flat layout in the presence of the
//ngen image.
//#if defined(_DEBUG)
//find all the layouts in the il image and make sure we never touch them.
unsigned ignored = 0;
PTR_PEImageLayout layout = m_ILimage->GetLayout(PEImageLayout::LAYOUT_FLAT, 0);
if (layout != NULL)
{
//cache a bunch of PE metadata in the PEDecoder
m_ILimage->CheckILFormat();
//we also need some of metadata (for the public key), so cache this too
DWORD verifyOutputFlags;
m_ILimage->VerifyStrongName(&verifyOutputFlags);
//fudge this by a few pages to make sure we can still mess with the PE headers
const size_t fudgeSize = 4096 * 4;
ClrVirtualProtect((void*)(((char *)layout->GetBase()) + fudgeSize),
layout->GetSize() - fudgeSize, 0, &ignored);
layout->Release();
}
#endif
}
else
{
ExternalLog(LL_WARNING, "Native image is not correct version.");
}
}
#endif // FEATURE_PREJIT
BOOL PEAssembly::IsSourceGAC()
{
WRAPPER_NO_CONTRACT;
return m_bIsFromGAC;
};
#endif // #ifndef DACCESS_COMPILE
#ifndef DACCESS_COMPILE
// ------------------------------------------------------------
// Hash support
// ------------------------------------------------------------
void PEAssembly::VerifyStrongName()
{
CONTRACTL
{
INSTANCE_CHECK;
THROWS;
GC_TRIGGERS;
MODE_ANY;
INJECT_FAULT(COMPlusThrowOM(););
}
CONTRACTL_END;
// If we've already done the signature checks, we don't need to do them again.
if (m_fStrongNameVerified)
{
return;
}
// Without FUSION/GAC, we need to verify SN on all assemblies, except dynamic assemblies.
if (IsDynamic())
{
m_flags |= PEFILE_SKIP_MODULE_HASH_CHECKS;
m_fStrongNameVerified = TRUE;
return;
}
// Next, verify the strong name, if necessary
// Check format of image. Note we must delay this until after the GAC status has been
// checked, to handle the case where we are not loading m_image.
EnsureImageOpened();
if (m_nativeImage == NULL && !GetILimage()->IsTrustedNativeImage())
{
if (!GetILimage()->CheckILFormat())
ThrowHR(COR_E_BADIMAGEFORMAT);
}
// Check the strong name if present.
if (IsIntrospectionOnly())
{
// For introspection assemblies, we don't need to check strong names and we don't
// need to do module hash checks.
m_flags |= PEFILE_SKIP_MODULE_HASH_CHECKS;
}
else
{
// Runtime policy on CoreCLR is to skip verification of ALL assemblies
m_flags |= PEFILE_SKIP_MODULE_HASH_CHECKS;
m_fStrongNameVerified = TRUE;
}
m_fStrongNameVerified = TRUE;
}
BOOL PEAssembly::IsProfileAssembly()
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
MODE_ANY;
}
CONTRACTL_END;
//
// For now, cache the result of the check below. This cache should be removed once/if the check below
// becomes cheap (e.g. does not access metadata anymore).
//
if (VolatileLoadWithoutBarrier(&m_fProfileAssembly) != 0)
{
return m_fProfileAssembly > 0;
}
//
// In order to be a platform (profile) assembly, you must be from a trusted location (TPA list)
// If we are binding by TPA list and this assembly is on it, IsSourceGAC is true => Assembly is Profile
// If the assembly is a WinMD, it is automatically trusted since all WinMD scenarios are full trust scenarios.
//
// The check for Silverlight strongname platform assemblies is legacy backdoor. It was introduced by accidental abstraction leak
// from the old Silverlight binder, people took advantage of it and we cannot easily get rid of it now. See DevDiv #710462.
//
BOOL bProfileAssembly = IsSourceGAC() && (IsSystem() || m_bIsOnTpaList);
m_fProfileAssembly = bProfileAssembly ? 1 : -1;
return bProfileAssembly;
}
// ------------------------------------------------------------
// Descriptive strings
// ------------------------------------------------------------
// Effective path is the path of nearest parent (creator) assembly which has a nonempty path.
const SString &PEAssembly::GetEffectivePath()
{
CONTRACTL
{
INSTANCE_CHECK;
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
}
CONTRACTL_END;
PEAssembly *pAssembly = this;
while (pAssembly->m_identity == NULL
|| pAssembly->m_identity->GetPath().IsEmpty())
{
if (pAssembly->m_creator)
pAssembly = pAssembly->m_creator->GetAssembly();
else // Unmanaged exe which loads byte[]/IStream assemblies
return SString::Empty();
}
return pAssembly->m_identity->GetPath();
}
// Codebase is the fusion codebase or path for the assembly. It is in URL format.
// Note this may be obtained from the parent PEFile if we don't have a path or fusion
// assembly.
//
// fCopiedName means to get the "shadow copied" path rather than the original path, if applicable
void PEAssembly::GetCodeBase(SString &result, BOOL fCopiedName/*=FALSE*/)
{
CONTRACTL
{
INSTANCE_CHECK;
THROWS;
GC_TRIGGERS;
MODE_ANY;
INJECT_FAULT(COMPlusThrowOM(););
}
CONTRACTL_END;
// All other cases use the file path.
result.Set(GetEffectivePath());
if (!result.IsEmpty())
PathToUrl(result);
}
/* static */
void PEAssembly::PathToUrl(SString &string)
{
CONTRACTL
{
PRECONDITION(PEImage::CheckCanonicalFullPath(string));
THROWS;
GC_NOTRIGGER;
MODE_ANY;
INJECT_FAULT(COMPlusThrowOM(););
}
CONTRACTL_END;
SString::Iterator i = string.Begin();
#if !defined(PLATFORM_UNIX)
if (i[0] == W('\\'))
{
// Network path
string.Insert(i, SL("file://"));
string.Skip(i, SL("file://"));
}
else
{
// Disk path
string.Insert(i, SL("file:///"));
string.Skip(i, SL("file:///"));
}
#else
// Unix doesn't have a distinction between a network or a local path
_ASSERTE( i[0] == W('\\') || i[0] == W('/'));
SString sss(SString::Literal, W("file://"));
string.Insert(i, sss);
string.Skip(i, sss);
#endif
while (string.Find(i, W('\\')))
{
string.Replace(i, W('/'));
}
}
void PEAssembly::UrlToPath(SString &string)
{
CONTRACT_VOID
{
THROWS;
GC_NOTRIGGER;
}
CONTRACT_END;
SString::Iterator i = string.Begin();
SString sss2(SString::Literal, W("file://"));
#if !defined(PLATFORM_UNIX)
SString sss3(SString::Literal, W("file:///"));
if (string.MatchCaseInsensitive(i, sss3))
string.Delete(i, 8);
else
#endif
if (string.MatchCaseInsensitive(i, sss2))
string.Delete(i, 7);
while (string.Find(i, W('/')))
{
string.Replace(i, W('\\'));
}
RETURN;
}
BOOL PEAssembly::FindLastPathSeparator(const SString &path, SString::Iterator &i)
{
#ifdef PLATFORM_UNIX
SString::Iterator slash = i;
SString::Iterator backSlash = i;
BOOL foundSlash = path.FindBack(slash, '/');
BOOL foundBackSlash = path.FindBack(backSlash, '\\');
if (!foundSlash && !foundBackSlash)
return FALSE;
else if (foundSlash && !foundBackSlash)
i = slash;
else if (!foundSlash && foundBackSlash)
i = backSlash;
else
i = (backSlash > slash) ? backSlash : slash;
return TRUE;
#else
return path.FindBack(i, '\\');
#endif //PLATFORM_UNIX
}
// ------------------------------------------------------------
// Logging
// ------------------------------------------------------------
#ifdef FEATURE_PREJIT
void PEAssembly::ExternalVLog(DWORD facility, DWORD level, const WCHAR *fmt, va_list args)
{
CONTRACT_VOID
{
THROWS;
GC_TRIGGERS;
}
CONTRACT_END;
PEFile::ExternalVLog(facility, level, fmt, args);
RETURN;
}
void PEAssembly::FlushExternalLog()
{
CONTRACT_VOID
{
THROWS;
GC_TRIGGERS;
}
CONTRACT_END;
RETURN;
}
#endif //FEATURE_PREJIT
// ------------------------------------------------------------
// Metadata access
// ------------------------------------------------------------
HRESULT PEFile::GetVersion(USHORT *pMajor, USHORT *pMinor, USHORT *pBuild, USHORT *pRevision)
{
CONTRACTL
{
INSTANCE_CHECK;
PRECONDITION(CheckPointer(pMajor, NULL_OK));
PRECONDITION(CheckPointer(pMinor, NULL_OK));
PRECONDITION(CheckPointer(pBuild, NULL_OK));
PRECONDITION(CheckPointer(pRevision, NULL_OK));
NOTHROW;
WRAPPER(GC_TRIGGERS);
MODE_ANY;
}
CONTRACTL_END;
AssemblyMetaDataInternal md;
HRESULT hr = S_OK;;
if (m_bHasPersistentMDImport)
{
_ASSERTE(GetPersistentMDImport()->IsValidToken(TokenFromRid(1, mdtAssembly)));
IfFailRet(GetPersistentMDImport()->GetAssemblyProps(TokenFromRid(1, mdtAssembly), NULL, NULL, NULL, NULL, &md, NULL));
}
else
{
ReleaseHolder<IMDInternalImport> pImport(GetMDImportWithRef());
_ASSERTE(pImport->IsValidToken(TokenFromRid(1, mdtAssembly)));
IfFailRet(pImport->GetAssemblyProps(TokenFromRid(1, mdtAssembly), NULL, NULL, NULL, NULL, &md, NULL));
}
if (pMajor != NULL)
*pMajor = md.usMajorVersion;
if (pMinor != NULL)
*pMinor = md.usMinorVersion;
if (pBuild != NULL)
*pBuild = md.usBuildNumber;
if (pRevision != NULL)
*pRevision = md.usRevisionNumber;
return hr;
}
void PEFile::EnsureImageOpened()
{
WRAPPER_NO_CONTRACT;
if (IsDynamic())
return;
#ifdef FEATURE_PREJIT
if(HasNativeImage())
m_nativeImage->GetLayout(PEImageLayout::LAYOUT_ANY,PEImage::LAYOUT_CREATEIFNEEDED)->Release();
else
#endif
GetILimage()->GetLayout(PEImageLayout::LAYOUT_ANY,PEImage::LAYOUT_CREATEIFNEEDED)->Release();
}
#endif // #ifndef DACCESS_COMPILE
#ifdef DACCESS_COMPILE
void
PEFile::EnumMemoryRegions(CLRDataEnumMemoryFlags flags)
{
WRAPPER_NO_CONTRACT;
SUPPORTS_DAC;
// sizeof(PEFile) == 0xb8
DAC_ENUM_VTHIS();
EMEM_OUT(("MEM: %p PEFile\n", dac_cast<TADDR>(this)));
#ifdef _DEBUG
// Not a big deal if it's NULL or fails.
m_debugName.EnumMemoryRegions(flags);
#endif
if (m_identity.IsValid())
{
m_identity->EnumMemoryRegions(flags);
}
if (GetILimage().IsValid())
{
GetILimage()->EnumMemoryRegions(flags);
}
#ifdef FEATURE_PREJIT
if (m_nativeImage.IsValid())
{
m_nativeImage->EnumMemoryRegions(flags);
DacEnumHostDPtrMem(m_nativeImage->GetLoadedLayout()->GetNativeVersionInfo());
}
#endif
}
void
PEAssembly::EnumMemoryRegions(CLRDataEnumMemoryFlags flags)
{
WRAPPER_NO_CONTRACT;
PEFile::EnumMemoryRegions(flags);
if (m_creator.IsValid())
{
m_creator->EnumMemoryRegions(flags);
}
}
#endif // #ifdef DACCESS_COMPILE
//-------------------------------------------------------------------------------
// Make best-case effort to obtain an image name for use in an error message.
//
// This routine must expect to be called before the this object is fully loaded.
// It can return an empty if the name isn't available or the object isn't initialized
// enough to get a name, but it mustn't crash.
//-------------------------------------------------------------------------------
LPCWSTR PEFile::GetPathForErrorMessages()
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
INJECT_FAULT(COMPlusThrowOM(););
SUPPORTS_DAC_HOST_ONLY;
}
CONTRACTL_END
if (!IsDynamic())
{
return m_identity->GetPathForErrorMessages();
}
else
{
return W("");
}
}
#ifdef DACCESS_COMPILE
TADDR PEFile::GetMDInternalRWAddress()
{
if (!m_MDImportIsRW_Debugger_Use_Only)
return 0;
else
{
// This line of code is a bit scary, but it is correct for now at least...
// 1) We are using 'm_pMDImport_Use_Accessor' directly, and not the accessor. The field is
// named this way to prevent debugger code that wants a host implementation of IMDInternalImport
// from accidentally trying to use this pointer. This pointer is a target pointer, not
// a host pointer. However in this function we do want the target pointer, so the usage is
// accurate.
// 2) ASSUMPTION: We are assuming that the only valid implementation of RW metadata is
// MDInternalRW. If that ever changes we would need some way to disambiguate, and
// probably this entire code path would need to be redesigned.
// 3) ASSUMPTION: We are assuming that no pointer adjustment is required to convert between
// IMDInternalImport*, IMDInternalImportENC* and MDInternalRW*. Ideally I was hoping to do this with a
// static_cast<> but the compiler complains that the ENC<->RW is an unrelated conversion.
return (TADDR) m_pMDImport_UseAccessor;
}
}
#endif
// Returns the ICLRPrivBinder* instance associated with the PEFile
PTR_ICLRPrivBinder PEFile::GetBindingContext()
{
LIMITED_METHOD_CONTRACT;
PTR_ICLRPrivBinder pBindingContext = NULL;
// CoreLibrary is always bound in context of the TPA Binder. However, since it gets loaded and published
// during EEStartup *before* DefaultContext Binder (aka TPAbinder) is initialized, we dont have a binding context to publish against.
// Thus, we will always return NULL for its binding context.
if (!IsSystem())
{
pBindingContext = dac_cast<PTR_ICLRPrivBinder>(GetHostAssembly());
if (!pBindingContext)
{
// If we do not have any binding context, check if we are dealing with
// a dynamically emitted assembly and if so, use its fallback load context
// binder reference.
if (IsDynamic())
{
pBindingContext = GetFallbackLoadContextBinder();
}
}
}
return pBindingContext;
}
|