1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
//
// File: DllImport.cpp
//
//
// P/Invoke support.
//
#include "common.h"
#include "vars.hpp"
#include "stublink.h"
#include "threads.h"
#include "excep.h"
#include "dllimport.h"
#include "method.hpp"
#include "siginfo.hpp"
#include "comdelegate.h"
#include "ceeload.h"
#include "mlinfo.h"
#include "eeconfig.h"
#include "comutilnative.h"
#include "corhost.h"
#include "asmconstants.h"
#include "mdaassistants.h"
#include "customattribute.h"
#include "ilstubcache.h"
#include "typeparse.h"
#include "sigbuilder.h"
#include "sigformat.h"
#include "strongnameholders.h"
#include "ecall.h"
#include <formattype.h>
#include "../md/compiler/custattr.h"
#ifdef FEATURE_COMINTEROP
#include "runtimecallablewrapper.h"
#include "clrtocomcall.h"
#endif // FEATURE_COMINTEROP
#ifdef FEATURE_PREJIT
#include "compile.h"
#endif // FEATURE_PREJIT
#include "eventtrace.h"
#include "clr/fs/path.h"
using namespace clr::fs;
// remove when we get an updated SDK
#define LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR 0x00000100
#define LOAD_LIBRARY_SEARCH_DEFAULT_DIRS 0x00001000
void AppendEHClause(int nClauses, COR_ILMETHOD_SECT_EH * pEHSect, ILStubEHClause * pClause, int * pCurIdx)
{
LIMITED_METHOD_CONTRACT;
if (pClause->kind == ILStubEHClause::kNone)
return;
int idx = *pCurIdx;
*pCurIdx = idx + 1;
CorExceptionFlag flags;
switch (pClause->kind)
{
case ILStubEHClause::kFinally: flags = COR_ILEXCEPTION_CLAUSE_FINALLY; break;
case ILStubEHClause::kTypedCatch: flags = COR_ILEXCEPTION_CLAUSE_NONE; break;
default:
UNREACHABLE_MSG("unexpected ILStubEHClause kind");
}
_ASSERTE(idx < nClauses);
pEHSect->Fat.Clauses[idx].Flags = flags;
pEHSect->Fat.Clauses[idx].TryOffset = pClause->dwTryBeginOffset;
pEHSect->Fat.Clauses[idx].TryLength = pClause->cbTryLength;
pEHSect->Fat.Clauses[idx].HandlerOffset = pClause->dwHandlerBeginOffset;
pEHSect->Fat.Clauses[idx].HandlerLength = pClause->cbHandlerLength;
pEHSect->Fat.Clauses[idx].ClassToken = pClause->dwTypeToken;
}
VOID PopulateEHSect(COR_ILMETHOD_SECT_EH * pEHSect, int nClauses, ILStubEHClause * pOne, ILStubEHClause * pTwo)
{
LIMITED_METHOD_CONTRACT;
pEHSect->Fat.Kind = (CorILMethod_Sect_EHTable | CorILMethod_Sect_FatFormat);
pEHSect->Fat.DataSize = COR_ILMETHOD_SECT_EH_FAT::Size(nClauses);
int curIdx = 0;
AppendEHClause(nClauses, pEHSect, pOne, &curIdx);
AppendEHClause(nClauses, pEHSect, pTwo, &curIdx);
}
StubSigDesc::StubSigDesc(MethodDesc *pMD, PInvokeStaticSigInfo* pSigInfo /*= NULL*/)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
SUPPORTS_DAC;
}
CONTRACTL_END
m_pMD = pMD;
if (pSigInfo != NULL)
{
m_sig = pSigInfo->GetSignature();
m_pModule = pSigInfo->GetModule();
}
else
{
_ASSERTE(pMD != NULL);
m_sig = pMD->GetSignature();
m_pModule = pMD->GetModule(); // Used for token resolution.
}
if (pMD != NULL)
{
m_tkMethodDef = pMD->GetMemberDef();
SigTypeContext::InitTypeContext(pMD, &m_typeContext);
m_pLoaderModule = pMD->GetLoaderModule(); // Used for ILStubCache selection and MethodTable creation.
}
else
{
m_tkMethodDef = mdMethodDefNil;
m_pLoaderModule = m_pModule;
}
INDEBUG(InitDebugNames());
}
StubSigDesc::StubSigDesc(MethodDesc *pMD, Signature sig, Module *pModule)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
SUPPORTS_DAC;
PRECONDITION(!sig.IsEmpty());
PRECONDITION(pModule != NULL);
}
CONTRACTL_END
m_pMD = pMD;
m_sig = sig;
m_pModule = pModule;
if (pMD != NULL)
{
m_tkMethodDef = pMD->GetMemberDef();
SigTypeContext::InitTypeContext(pMD, &m_typeContext);
m_pLoaderModule = pMD->GetLoaderModule(); // Used for ILStubCache selection and MethodTable creation.
}
else
{
m_tkMethodDef = mdMethodDefNil;
m_pLoaderModule = m_pModule;
}
INDEBUG(InitDebugNames());
}
#ifndef DACCESS_COMPILE
class StubState
{
public:
virtual void SetLastError(BOOL fSetLastError) = 0;
virtual void BeginEmit(DWORD dwStubFlags) = 0;
virtual void MarshalReturn(MarshalInfo* pInfo, int argOffset) = 0;
virtual void MarshalArgument(MarshalInfo* pInfo, int argOffset, UINT nativeStackOffset) = 0;
virtual void MarshalLCID(int argIdx) = 0;
#ifdef FEATURE_COMINTEROP
virtual void MarshalHiddenLengthArgument(MarshalInfo *pInfo, BOOL isForReturnArray) = 0;
virtual void MarshalFactoryReturn() = 0;
#endif // FEATURE_COMINTEROP
virtual void EmitInvokeTarget(MethodDesc *pStubMD) = 0;
virtual void FinishEmit(MethodDesc* pMD) = 0;
virtual ~StubState()
{
LIMITED_METHOD_CONTRACT;
}
};
class ILStubState : public StubState
{
protected:
ILStubState(
Module* pStubModule,
const Signature &signature,
SigTypeContext* pTypeContext,
BOOL fTargetHasThis,
BOOL fStubHasThis,
DWORD dwStubFlags,
int iLCIDParamIdx,
MethodDesc* pTargetMD)
: m_slIL(dwStubFlags, pStubModule, signature, pTypeContext, pTargetMD, iLCIDParamIdx, fTargetHasThis, fStubHasThis)
{
STANDARD_VM_CONTRACT;
m_fSetLastError = 0;
}
public:
void SetLastError(BOOL fSetLastError)
{
LIMITED_METHOD_CONTRACT;
m_fSetLastError = fSetLastError;
}
// We use three stub linkers to generate IL stubs. The pre linker is the main one. It does all the marshaling and
// then calls the target method. The post return linker is only used to unmarshal the return value after we return
// from the target method. The post linker handles all the unmarshaling for by ref arguments and clean-up. It
// also checks if we should throw an exception etc.
//
// Currently, we have two "emittable" ILCodeLabel's. The first one is at the beginning of the pre linker. This
// label is used to emit code to declare and initialize clean-up flags. Each argument which requires clean-up
// emits one flag. This flag is set only after the marshaling is done, and it is checked before we do any clean-up
// in the finally.
//
// The second "emittable" ILCodeLabel is at the beginning of the post linker. It is used to emit code which is
// not safe to run in the case of an exception. The rest of the post linker is wrapped in a finally, and it contains
// with the necessary clean-up which should be executed in both normal and exception cases.
void BeginEmit(DWORD dwStubFlags)
{
WRAPPER_NO_CONTRACT;
m_slIL.Begin(dwStubFlags);
m_dwStubFlags = dwStubFlags;
}
void MarshalReturn(MarshalInfo* pInfo, int argOffset)
{
CONTRACTL
{
STANDARD_VM_CHECK;
PRECONDITION(CheckPointer(pInfo));
}
CONTRACTL_END;
pInfo->GenerateReturnIL(&m_slIL, argOffset,
SF_IsForwardStub(m_dwStubFlags),
SF_IsFieldGetterStub(m_dwStubFlags),
SF_IsHRESULTSwapping(m_dwStubFlags));
}
void MarshalArgument(MarshalInfo* pInfo, int argOffset, UINT nativeStackOffset)
{
CONTRACTL
{
STANDARD_VM_CHECK;
PRECONDITION(CheckPointer(pInfo));
}
CONTRACTL_END;
pInfo->GenerateArgumentIL(&m_slIL, argOffset, nativeStackOffset, SF_IsForwardStub(m_dwStubFlags));
}
#ifdef FEATURE_COMINTEROP
// Marshal the hidden length parameter for the managed parameter in pInfo
virtual void MarshalHiddenLengthArgument(MarshalInfo *pInfo, BOOL isForReturnArray)
{
STANDARD_VM_CONTRACT;
pInfo->MarshalHiddenLengthArgument(&m_slIL, SF_IsForwardStub(m_dwStubFlags), isForReturnArray);
if (SF_IsReverseStub(m_dwStubFlags))
{
// Hidden length arguments appear explicitly in the native signature
// however, they are not in the managed signature.
m_slIL.AdjustTargetStackDeltaForExtraParam();
}
}
void MarshalFactoryReturn()
{
CONTRACTL
{
STANDARD_VM_CHECK;
PRECONDITION(SF_IsCOMStub(m_dwStubFlags));
PRECONDITION(SF_IsWinRTCtorStub(m_dwStubFlags));
}
CONTRACTL_END;
ILCodeStream *pcsSetup = m_slIL.GetSetupCodeStream();
ILCodeStream *pcsDispatch = m_slIL.GetDispatchCodeStream();
ILCodeStream *pcsUnmarshal = m_slIL.GetReturnUnmarshalCodeStream();
ILCodeStream *pcsCleanup = m_slIL.GetCleanupCodeStream();
/*
* SETUP
*/
// create a local to hold the returned pUnk and initialize to 0 in case the factory fails
// and we try to release it during cleanup
LocalDesc locDescFactoryRetVal(ELEMENT_TYPE_I);
DWORD dwFactoryRetValLocalNum = pcsSetup->NewLocal(locDescFactoryRetVal);
pcsSetup->EmitLoadNullPtr();
pcsSetup->EmitSTLOC(dwFactoryRetValLocalNum);
DWORD dwInnerIInspectableLocalNum = -1;
DWORD dwOuterIInspectableLocalNum = -1;
if (SF_IsWinRTCompositionStub(m_dwStubFlags))
{
// Create locals to store the outer and inner IInspectable values and initialize to null
// Note that we do this in the setup stream so that we're guaranteed to have a null-initialized
// value in the cleanup stream
LocalDesc locDescOuterIInspectable(ELEMENT_TYPE_I);
dwOuterIInspectableLocalNum = pcsSetup->NewLocal(locDescOuterIInspectable);
pcsSetup->EmitLoadNullPtr();
pcsSetup->EmitSTLOC(dwOuterIInspectableLocalNum);
LocalDesc locDescInnerIInspectable(ELEMENT_TYPE_I);
dwInnerIInspectableLocalNum = pcsSetup->NewLocal(locDescInnerIInspectable);
pcsSetup->EmitLoadNullPtr();
pcsSetup->EmitSTLOC(dwInnerIInspectableLocalNum);
}
/*
* DISPATCH
*/
// For composition factories, add the two extra params
if (SF_IsWinRTCompositionStub(m_dwStubFlags))
{
// Get outer IInspectable. The helper will return NULL if this is the "top-level" constructor,
// and the appropriate outer pointer otherwise.
pcsDispatch->EmitLoadThis();
m_slIL.EmitLoadStubContext(pcsDispatch, m_dwStubFlags);
pcsDispatch->EmitCALL(METHOD__STUBHELPERS__GET_OUTER_INSPECTABLE, 2, 1);
pcsDispatch->EmitSTLOC(dwOuterIInspectableLocalNum);
// load the outer IInspectable (3rd last argument)
pcsDispatch->SetStubTargetArgType(ELEMENT_TYPE_I, false);
pcsDispatch->EmitLDLOC(dwOuterIInspectableLocalNum);
// pass pointer to where inner non-delegating IInspectable should be stored (2nd last argument)
LocalDesc locDescInnerPtr(ELEMENT_TYPE_I);
locDescInnerPtr.MakeByRef();
pcsDispatch->SetStubTargetArgType(&locDescInnerPtr, false);
pcsDispatch->EmitLDLOCA(dwInnerIInspectableLocalNum);
}
// pass pointer to the local to the factory method (last argument)
locDescFactoryRetVal.MakeByRef();
pcsDispatch->SetStubTargetArgType(&locDescFactoryRetVal, false);
pcsDispatch->EmitLDLOCA(dwFactoryRetValLocalNum);
/*
* UNMARSHAL
*/
// Mark that the factory method has succesfully returned and so cleanup will be necessary after
// this point.
m_slIL.EmitSetArgMarshalIndex(pcsUnmarshal, NDirectStubLinker::CLEANUP_INDEX_RETVAL_UNMARSHAL);
// associate the 'this' RCW with one of the returned interface pointers
pcsUnmarshal->EmitLoadThis();
// now we need to find the right interface pointer to load
if (dwInnerIInspectableLocalNum != -1)
{
// We may have a composition scenario
ILCodeLabel* pNonCompositionLabel = pcsUnmarshal->NewCodeLabel();
ILCodeLabel* pLoadedLabel = pcsUnmarshal->NewCodeLabel();
// Did we pass an outer IInspectable?
pcsUnmarshal->EmitLDLOC(dwOuterIInspectableLocalNum);
pcsUnmarshal->EmitBRFALSE(pNonCompositionLabel);
// yes, this is a composition scenario
{
// ignore the delegating interface pointer (will be released in cleanup below) - we can
// re-create it by QI'ing the non-delegating one.
// Note that using this could be useful in the future (avoids an extra QueryInterface call)
// Just load the non-delegating interface pointer
pcsUnmarshal->EmitLDLOCA(dwInnerIInspectableLocalNum);
pcsUnmarshal->EmitBR(pLoadedLabel);
}
// else, no this is a non-composition scenario
{
pcsUnmarshal->EmitLabel(pNonCompositionLabel);
// ignore the non-delegating interface pointer (which should be null, but will regardless get
// cleaned up below in the event the factory doesn't follow the pattern properly).
// Just load the regular delegating interface pointer
pcsUnmarshal->EmitLDLOCA(dwFactoryRetValLocalNum);
}
pcsUnmarshal->EmitLabel(pLoadedLabel);
}
else
{
// Definitely can't be a composition scenario - use the only pointer we have
pcsUnmarshal->EmitLDLOCA(dwFactoryRetValLocalNum);
}
pcsUnmarshal->EmitCALL(METHOD__MARSHAL__INITIALIZE_WRAPPER_FOR_WINRT, 2, 0);
/*
* CLEANUP
*/
// release the returned interface pointer in the finally block
m_slIL.SetCleanupNeeded();
ILCodeLabel *pSkipCleanupLabel = pcsCleanup->NewCodeLabel();
m_slIL.EmitCheckForArgCleanup(pcsCleanup,
NDirectStubLinker::CLEANUP_INDEX_RETVAL_UNMARSHAL,
NDirectStubLinker::BranchIfNotMarshaled,
pSkipCleanupLabel);
EmitInterfaceClearNative(pcsCleanup, dwFactoryRetValLocalNum);
// Note that it's a no-op to pass NULL to Clear_Native, so we call it even though we don't
// know if we assigned to the inner/outer IInspectable
if (dwInnerIInspectableLocalNum != -1)
{
EmitInterfaceClearNative(pcsCleanup, dwInnerIInspectableLocalNum);
}
if (dwOuterIInspectableLocalNum != -1)
{
EmitInterfaceClearNative(pcsCleanup, dwOuterIInspectableLocalNum);
}
pcsCleanup->EmitLabel(pSkipCleanupLabel);
}
static void EmitInterfaceClearNative(ILCodeStream* pcsEmit, DWORD dwLocalNum)
{
STANDARD_VM_CONTRACT;
ILCodeLabel *pSkipClearNativeLabel = pcsEmit->NewCodeLabel();
pcsEmit->EmitLDLOC(dwLocalNum);
pcsEmit->EmitBRFALSE(pSkipClearNativeLabel);
pcsEmit->EmitLDLOC(dwLocalNum);
pcsEmit->EmitCALL(METHOD__INTERFACEMARSHALER__CLEAR_NATIVE, 1, 0);
pcsEmit->EmitLabel(pSkipClearNativeLabel);
}
#endif // FEATURE_COMINTEROP
void MarshalLCID(int argIdx)
{
STANDARD_VM_CONTRACT;
ILCodeStream* pcs = m_slIL.GetDispatchCodeStream();
#ifdef FEATURE_USE_LCID
if (SF_IsReverseStub(m_dwStubFlags))
{
if ((m_slIL.GetStubTargetCallingConv() & IMAGE_CEE_CS_CALLCONV_HASTHIS) == IMAGE_CEE_CS_CALLCONV_HASTHIS)
{
// the arg number will be incremented by LDARG if we are in an instance method
_ASSERTE(argIdx > 0);
argIdx--;
}
LocalDesc locDescThread(MscorlibBinder::GetClass(CLASS__THREAD));
DWORD dwThreadLocalNum = pcs->NewLocal(locDescThread);
// call Thread.get_CurrentThread()
pcs->EmitCALL(METHOD__THREAD__GET_CURRENT_THREAD, 0, 1);
pcs->EmitDUP();
pcs->EmitSTLOC(dwThreadLocalNum);
// call current_thread.get_CurrentCulture()
pcs->EmitCALL(METHOD__THREAD__GET_CULTURE, 1, 1);
// save the current culture
LocalDesc locDescCulture(MscorlibBinder::GetClass(CLASS__CULTURE_INFO));
DWORD dwCultureLocalNum = pcs->NewLocal(locDescCulture);
pcs->EmitSTLOC(dwCultureLocalNum);
// set a new one based on the LCID passed from unmanaged
pcs->EmitLDLOC(dwThreadLocalNum);
pcs->EmitLDARG(argIdx);
// call CultureInfo..ctor(lcid)
// call current_thread.set_CurrentCulture(culture)
pcs->EmitNEWOBJ(METHOD__CULTURE_INFO__INT_CTOR, 1);
pcs->EmitCALL(METHOD__THREAD__SET_CULTURE, 2, 0);
// and restore the current one after the call
m_slIL.SetCleanupNeeded();
ILCodeStream *pcsCleanup = m_slIL.GetCleanupCodeStream();
// call current_thread.set_CurrentCulture(original_culture)
pcsCleanup->EmitLDLOC(dwThreadLocalNum);
pcsCleanup->EmitLDLOC(dwCultureLocalNum);
pcsCleanup->EmitCALL(METHOD__THREAD__SET_CULTURE, 1, 1);
}
else
{
if (SF_IsCOMStub(m_dwStubFlags))
{
// We used to get LCID from current thread's culture here. The code
// was replaced by the hardcoded LCID_ENGLISH_US as requested by VSTO.
pcs->EmitLDC(0x0409); // LCID_ENGLISH_US
}
else
{
// call Thread.get_CurrentThread()
// call current_thread.get_CurrentCulture()
pcs->EmitCALL(METHOD__THREAD__GET_CURRENT_THREAD, 0, 1);
pcs->EmitCALL(METHOD__THREAD__GET_CULTURE, 1, 1);
//call CultureInfo.get_LCID(this)
pcs->EmitCALL(METHOD__CULTURE_INFO__GET_ID, 1, 1);
}
}
#else // FEATURE_USE_LCID
if (SF_IsForwardStub(m_dwStubFlags))
{
pcs->EmitLDC(0x0409); // LCID_ENGLISH_US
}
#endif // FEATURE_USE_LCID
// add the extra arg to the unmanaged signature
LocalDesc locDescNative(ELEMENT_TYPE_I4);
pcs->SetStubTargetArgType(&locDescNative, false);
if (SF_IsReverseStub(m_dwStubFlags))
{
// reverse the effect of SetStubTargetArgType on the stack delta
// (the LCID argument is explicitly passed from unmanaged but does not
// show up in the managed signature in any way)
m_slIL.AdjustTargetStackDeltaForExtraParam();
}
}
void SwapStubSignatures(MethodDesc* pStubMD)
{
STANDARD_VM_CONTRACT;
//
// Since the stub handles native-to-managed transitions, we have to swap the
// stub-state-calculated stub target sig with the stub sig itself. This is
// because the stub target sig represents the native signature and the stub
// sig represents the managed signature.
//
// The first step is to convert the managed signature to a module-independent
// signature and then pass it off to SetStubTargetMethodSig. Note that the
// ILStubResolver will copy the sig, so we only need to make a temporary copy
// of it.
//
SigBuilder sigBuilder;
{
SigPointer sigPtr(pStubMD->GetSig());
sigPtr.ConvertToInternalSignature(pStubMD->GetModule(), NULL, &sigBuilder);
}
//
// The second step is to reset the sig on the stub MethodDesc to be the
// stub-state-calculated stub target sig.
//
{
//
// make a domain-local copy of the sig so that this state can outlive the
// compile time state.
//
DWORD cbNewSig;
PCCOR_SIGNATURE pNewSig;
cbNewSig = GetStubTargetMethodSigLength();
pNewSig = (PCCOR_SIGNATURE)(void *)pStubMD->GetLoaderAllocator()->GetHighFrequencyHeap()->AllocMem(S_SIZE_T(cbNewSig));
memcpyNoGCRefs((void *)pNewSig, GetStubTargetMethodSig(), cbNewSig);
pStubMD->AsDynamicMethodDesc()->SetStoredMethodSig(pNewSig, cbNewSig);
SigPointer sigPtr(pNewSig, cbNewSig);
ULONG callConvInfo;
IfFailThrow(sigPtr.GetCallingConvInfo(&callConvInfo));
if (callConvInfo & CORINFO_CALLCONV_HASTHIS)
{
((PTR_DynamicMethodDesc)pStubMD)->m_dwExtendedFlags &= ~mdStatic;
pStubMD->ClearStatic();
}
else
{
((PTR_DynamicMethodDesc)pStubMD)->m_dwExtendedFlags |= mdStatic;
pStubMD->SetStatic();
}
#ifndef _TARGET_X86_
// we store the real managed argument stack size in the stub MethodDesc on non-X86
UINT stackSize = pStubMD->SizeOfArgStack();
if (!FitsInU2(stackSize))
COMPlusThrow(kMarshalDirectiveException, IDS_EE_SIGTOOCOMPLEX);
pStubMD->AsDynamicMethodDesc()->SetNativeStackArgSize(static_cast<WORD>(stackSize));
#endif // _TARGET_X86_
}
DWORD cbTempModuleIndependentSigLength;
BYTE * pTempModuleIndependentSig = (BYTE *)sigBuilder.GetSignature(&cbTempModuleIndependentSigLength);
// Finish it
SetStubTargetMethodSig(pTempModuleIndependentSig,
cbTempModuleIndependentSigLength);
}
void EmitInvokeTarget(MethodDesc *pStubMD)
{
STANDARD_VM_CONTRACT;
m_slIL.DoNDirect(m_slIL.GetDispatchCodeStream(), m_dwStubFlags, pStubMD);
}
#ifdef FEATURE_COMINTEROP
void EmitExceptionHandler(LocalDesc* pNativeReturnType, LocalDesc* pManagedReturnType,
ILCodeLabel** ppTryEndAndCatchBeginLabel, ILCodeLabel ** ppCatchEndAndReturnLabel)
{
STANDARD_VM_CONTRACT;
ILCodeStream* pcsExceptionHandler = m_slIL.NewCodeStream(ILStubLinker::kExceptionHandler);
*ppTryEndAndCatchBeginLabel = pcsExceptionHandler->NewCodeLabel();
*ppCatchEndAndReturnLabel = pcsExceptionHandler->NewCodeLabel();
pcsExceptionHandler->EmitLEAVE(*ppCatchEndAndReturnLabel);
pcsExceptionHandler->EmitLabel(*ppTryEndAndCatchBeginLabel);
BYTE nativeReturnElemType = pNativeReturnType->ElementType[0]; // return type of the stub
BYTE managedReturnElemType = pManagedReturnType->ElementType[0]; // return type of the mananged target
bool returnTheHRESULT = SF_IsHRESULTSwapping(m_dwStubFlags) ||
(managedReturnElemType == ELEMENT_TYPE_I4) ||
(managedReturnElemType == ELEMENT_TYPE_U4);
#ifdef MDA_SUPPORTED
if (!returnTheHRESULT)
{
MdaExceptionSwallowedOnCallFromCom* mda = MDA_GET_ASSISTANT(ExceptionSwallowedOnCallFromCom);
if (mda)
{
// on the stack: exception object, but the stub linker doesn't know it
pcsExceptionHandler->EmitCALL(METHOD__STUBHELPERS__GET_STUB_CONTEXT, 0, 1);
pcsExceptionHandler->EmitCALL(METHOD__STUBHELPERS__TRIGGER_EXCEPTION_SWALLOWED_MDA,
1, // WARNING: This method takes 2 input args, the exception object and the stub context.
// But the ILStubLinker has no knowledge that the exception object is on the
// stack (because it is unaware that we've just entered a catch block), so we
// lie and claim that we only take one input argument.
1); // returns the exception object back
}
}
#endif // MDA_SUPPORTED
DWORD retvalLocalNum = m_slIL.GetReturnValueLocalNum();
BinderMethodID getHRForException;
if (SF_IsWinRTStub(m_dwStubFlags))
{
getHRForException = METHOD__MARSHAL__GET_HR_FOR_EXCEPTION_WINRT;
}
else
{
getHRForException = METHOD__MARSHAL__GET_HR_FOR_EXCEPTION;
}
pcsExceptionHandler->EmitCALL(getHRForException,
0, // WARNING: This method takes 1 input arg, the exception object. But the ILStubLinker
// has no knowledge that the exception object is on the stack (because it is
// unaware that we've just entered a catch block), so we lie and claim that we
// don't take any input arguments.
1);
switch (nativeReturnElemType)
{
default:
UNREACHABLE_MSG("Unexpected element type found on native return type.");
break;
case ELEMENT_TYPE_VOID:
_ASSERTE(retvalLocalNum == (DWORD)-1);
pcsExceptionHandler->EmitPOP();
break;
case ELEMENT_TYPE_I4:
case ELEMENT_TYPE_U4:
{
if (!returnTheHRESULT)
{
pcsExceptionHandler->EmitPOP();
pcsExceptionHandler->EmitLDC(0);
pcsExceptionHandler->EmitCONV_T((CorElementType)nativeReturnElemType);
}
_ASSERTE(retvalLocalNum != (DWORD)-1);
pcsExceptionHandler->EmitSTLOC(retvalLocalNum);
}
break;
case ELEMENT_TYPE_R4:
pcsExceptionHandler->EmitPOP();
pcsExceptionHandler->EmitLDC_R4(CLR_NAN_32);
_ASSERTE(retvalLocalNum != (DWORD)-1);
pcsExceptionHandler->EmitSTLOC(retvalLocalNum);
break;
case ELEMENT_TYPE_R8:
pcsExceptionHandler->EmitPOP();
pcsExceptionHandler->EmitLDC_R8(CLR_NAN_64);
_ASSERTE(retvalLocalNum != (DWORD)-1);
pcsExceptionHandler->EmitSTLOC(retvalLocalNum);
break;
case ELEMENT_TYPE_INTERNAL:
{
TypeHandle returnTypeHnd = pNativeReturnType->InternalToken;
CONSISTENCY_CHECK(returnTypeHnd.IsValueType());
_ASSERTE(retvalLocalNum != (DWORD)-1);
pcsExceptionHandler->EmitLDLOCA(retvalLocalNum);
pcsExceptionHandler->EmitINITOBJ(m_slIL.GetDispatchCodeStream()->GetToken(returnTypeHnd));
}
break;
case ELEMENT_TYPE_BOOLEAN:
case ELEMENT_TYPE_CHAR:
case ELEMENT_TYPE_I1:
case ELEMENT_TYPE_U1:
case ELEMENT_TYPE_I2:
case ELEMENT_TYPE_U2:
case ELEMENT_TYPE_I8:
case ELEMENT_TYPE_U8:
case ELEMENT_TYPE_I:
case ELEMENT_TYPE_U:
pcsExceptionHandler->EmitPOP();
pcsExceptionHandler->EmitLDC(0);
pcsExceptionHandler->EmitCONV_T((CorElementType)nativeReturnElemType);
_ASSERTE(retvalLocalNum != (DWORD)-1);
pcsExceptionHandler->EmitSTLOC(retvalLocalNum);
break;
}
pcsExceptionHandler->EmitLEAVE(*ppCatchEndAndReturnLabel);
pcsExceptionHandler->EmitLabel(*ppCatchEndAndReturnLabel);
if (nativeReturnElemType != ELEMENT_TYPE_VOID)
{
_ASSERTE(retvalLocalNum != (DWORD)-1);
pcsExceptionHandler->EmitLDLOC(retvalLocalNum);
}
pcsExceptionHandler->EmitRET();
}
#endif // FEATURE_COMINTEROP
void FinishEmit(MethodDesc* pStubMD)
{
STANDARD_VM_CONTRACT;
ILCodeStream* pcsMarshal = m_slIL.GetMarshalCodeStream();
ILCodeStream* pcsUnmarshal = m_slIL.GetUnmarshalCodeStream();
ILCodeStream* pcsDispatch = m_slIL.GetDispatchCodeStream();
if (SF_IsHRESULTSwapping(m_dwStubFlags) && m_slIL.StubHasVoidReturnType())
{
// if the return type is void, but we're doing HRESULT swapping, we
// need to set the return type here. Otherwise, the return value
// marshaler will do this.
pcsMarshal->SetStubTargetReturnType(ELEMENT_TYPE_I4); // HRESULT
if (SF_IsReverseStub(m_dwStubFlags))
{
// reverse interop needs to seed the return value if the
// managed function returns void but we're doing hresult
// swapping.
pcsUnmarshal->EmitLDC(S_OK);
}
}
LocalDesc nativeReturnType;
LocalDesc managedReturnType;
bool hasTryCatchForHRESULT = SF_IsReverseCOMStub(m_dwStubFlags)
&& !SF_IsFieldGetterStub(m_dwStubFlags)
&& !SF_IsFieldSetterStub(m_dwStubFlags);
#ifdef FEATURE_COMINTEROP
if (hasTryCatchForHRESULT)
{
m_slIL.GetStubTargetReturnType(&nativeReturnType);
m_slIL.GetStubReturnType(&managedReturnType);
}
#endif // FEATURE_COMINTEROP
if (SF_IsHRESULTSwapping(m_dwStubFlags) && SF_IsReverseStub(m_dwStubFlags))
{
m_slIL.AdjustTargetStackDeltaForReverseInteropHRESULTSwapping();
}
if (SF_IsForwardCOMStub(m_dwStubFlags))
{
// Compensate for the 'this' parameter.
m_slIL.AdjustTargetStackDeltaForExtraParam();
}
#if defined(_TARGET_X86_)
// unmanaged CALLI will get an extra arg with the real target address if host hook is enabled
if (SF_IsCALLIStub(m_dwStubFlags) && NDirect::IsHostHookEnabled())
{
pcsMarshal->SetStubTargetArgType(ELEMENT_TYPE_I, false);
}
#endif // _TARGET_X86_
// Don't touch target signatures from this point on otherwise it messes up the
// cache in ILStubState::GetStubTargetMethodSig.
#ifdef _DEBUG
{
// The native and local signatures should not have any tokens.
// All token references should have been converted to
// ELEMENT_TYPE_INTERNAL.
//
// Note that MetaSig::GetReturnType and NextArg will normalize
// ELEMENT_TYPE_INTERNAL back to CLASS or VALUETYPE.
//
// <TODO> need to recursively check ELEMENT_TYPE_FNPTR signatures </TODO>
SigTypeContext typeContext; // this is an empty type context: COM calls are guaranteed to not be generics.
MetaSig nsig(
GetStubTargetMethodSig(),
GetStubTargetMethodSigLength(),
MscorlibBinder::GetModule(),
&typeContext);
CorElementType type;
IfFailThrow(nsig.GetReturnProps().PeekElemType(&type));
CONSISTENCY_CHECK(ELEMENT_TYPE_CLASS != type && ELEMENT_TYPE_VALUETYPE != type);
while (ELEMENT_TYPE_END != (type = nsig.NextArg()))
{
IfFailThrow(nsig.GetArgProps().PeekElemType(&type));
CONSISTENCY_CHECK(ELEMENT_TYPE_CLASS != type && ELEMENT_TYPE_VALUETYPE != type);
}
}
#endif // _DEBUG
#ifdef FEATURE_COMINTEROP
if (SF_IsForwardCOMStub(m_dwStubFlags))
{
#if defined(MDA_SUPPORTED)
// We won't use this NGEN'ed stub if RaceOnRCWCleanup is enabled at run-time
if (!SF_IsNGENedStub(m_dwStubFlags))
{
// This code may change the type of the frame we use, so it has to be run before the code below where we
// retrieve the stack arg size based on the frame type.
MdaRaceOnRCWCleanup* mda = MDA_GET_ASSISTANT(RaceOnRCWCleanup);
if (mda)
{
// Here we have to register the RCW of the "this" object to the RCWStack and schedule the clean-up for it.
// Emit a call to StubHelpers::StubRegisterRCW() and StubHelpers::StubUnregisterRCW() to do this.
m_slIL.EmitLoadRCWThis(pcsMarshal, m_dwStubFlags);
pcsMarshal->EmitCALL(METHOD__STUBHELPERS__STUB_REGISTER_RCW, 1, 0);
// We use an extra local to track whether we need to unregister the RCW on cleanup
ILCodeStream *pcsSetup = m_slIL.GetSetupCodeStream();
DWORD dwRCWRegisteredLocalNum = pcsSetup->NewLocal(ELEMENT_TYPE_BOOLEAN);
pcsSetup->EmitLDC(0);
pcsSetup->EmitSTLOC(dwRCWRegisteredLocalNum);
pcsMarshal->EmitLDC(1);
pcsMarshal->EmitSTLOC(dwRCWRegisteredLocalNum);
ILCodeStream *pcsCleanup = m_slIL.GetCleanupCodeStream();
ILCodeLabel *pSkipCleanupLabel = pcsCleanup->NewCodeLabel();
m_slIL.SetCleanupNeeded();
pcsCleanup->EmitLDLOC(dwRCWRegisteredLocalNum);
pcsCleanup->EmitBRFALSE(pSkipCleanupLabel);
m_slIL.EmitLoadRCWThis(pcsCleanup, m_dwStubFlags);
pcsCleanup->EmitCALL(METHOD__STUBHELPERS__STUB_UNREGISTER_RCW, 1, 0);
pcsCleanup->EmitLabel(pSkipCleanupLabel);
}
}
#endif // MDA_SUPPORTED
}
#endif // FEATURE_COMINTEROP
// <NOTE>
// The profiler helpers below must be called immediately before and after the call to the target.
// The debugger trace call helpers are invoked from StubRareDisableWorker
// </NOTE>
#if defined(PROFILING_SUPPORTED)
DWORD dwMethodDescLocalNum = -1;
// Notify the profiler of call out of the runtime
if (!SF_IsReverseCOMStub(m_dwStubFlags) && (CORProfilerTrackTransitions() || SF_IsNGENedStubForProfiling(m_dwStubFlags)))
{
dwMethodDescLocalNum = m_slIL.EmitProfilerBeginTransitionCallback(pcsDispatch, m_dwStubFlags);
_ASSERTE(dwMethodDescLocalNum != -1);
}
#endif // PROFILING_SUPPORTED
#ifdef MDA_SUPPORTED
if (SF_IsForwardStub(m_dwStubFlags) && !SF_IsNGENedStub(m_dwStubFlags) &&
MDA_GET_ASSISTANT(GcManagedToUnmanaged))
{
m_slIL.EmitCallGcCollectForMDA(pcsDispatch, m_dwStubFlags);
}
#endif // MDA_SUPPORTED
// For CoreClr, clear the last error before calling the target that returns last error.
// There isn't always a way to know the function have failed without checking last error,
// in particular on Unix.
if (m_fSetLastError && SF_IsForwardStub(m_dwStubFlags))
{
pcsDispatch->EmitCALL(METHOD__STUBHELPERS__CLEAR_LAST_ERROR, 0, 0);
}
// Invoke the target (calli, call method, call delegate, get/set field, etc.)
EmitInvokeTarget(pStubMD);
// Saving last error must be the first thing we do after returning from the target
if (m_fSetLastError && SF_IsForwardStub(m_dwStubFlags))
{
pcsDispatch->EmitCALL(METHOD__STUBHELPERS__SET_LAST_ERROR, 0, 0);
}
#if defined(_TARGET_X86_)
if (SF_IsForwardDelegateStub(m_dwStubFlags))
{
// the delegate may have an intercept stub attached to its sync block so we should
// prevent it from being garbage collected when the call is in progress
pcsDispatch->EmitLoadThis();
pcsDispatch->EmitCALL(METHOD__GC__KEEP_ALIVE, 1, 0);
}
#endif // defined(_TARGET_X86_)
#ifdef MDA_SUPPORTED
if (SF_IsForwardStub(m_dwStubFlags) && !SF_IsNGENedStub(m_dwStubFlags) &&
MDA_GET_ASSISTANT(GcUnmanagedToManaged))
{
m_slIL.EmitCallGcCollectForMDA(pcsDispatch, m_dwStubFlags);
}
#endif // MDA_SUPPORTED
#ifdef VERIFY_HEAP
if (SF_IsForwardStub(m_dwStubFlags) && g_pConfig->InteropValidatePinnedObjects())
{
// call StubHelpers.ValidateObject/StubHelpers.ValidateByref on pinned locals
m_slIL.EmitObjectValidation(pcsDispatch, m_dwStubFlags);
}
#endif // VERIFY_HEAP
#if defined(PROFILING_SUPPORTED)
// Notify the profiler of return back into the runtime
if (dwMethodDescLocalNum != -1)
{
m_slIL.EmitProfilerEndTransitionCallback(pcsDispatch, m_dwStubFlags, dwMethodDescLocalNum);
}
#endif // PROFILING_SUPPORTED
#ifdef FEATURE_COMINTEROP
if (SF_IsForwardCOMStub(m_dwStubFlags))
{
// Make sure that the RCW stays alive for the duration of the call. Note that if we do HRESULT
// swapping, we'll pass 'this' to GetCOMHRExceptionObject after returning from the target so
// GC.KeepAlive is not necessary.
if (!SF_IsHRESULTSwapping(m_dwStubFlags))
{
m_slIL.EmitLoadRCWThis(pcsDispatch, m_dwStubFlags);
pcsDispatch->EmitCALL(METHOD__GC__KEEP_ALIVE, 1, 0);
}
}
#endif // FEATURE_COMINTEROP
if (SF_IsHRESULTSwapping(m_dwStubFlags))
{
if (SF_IsForwardStub(m_dwStubFlags))
{
ILCodeLabel* pSkipThrowLabel = pcsDispatch->NewCodeLabel();
pcsDispatch->EmitDUP();
pcsDispatch->EmitLDC(0);
pcsDispatch->EmitBGE(pSkipThrowLabel);
#ifdef FEATURE_COMINTEROP
if (SF_IsCOMStub(m_dwStubFlags))
{
m_slIL.EmitLoadStubContext(pcsDispatch, m_dwStubFlags);
m_slIL.EmitLoadRCWThis(pcsDispatch, m_dwStubFlags);
if (SF_IsWinRTStub(m_dwStubFlags))
{
pcsDispatch->EmitCALL(METHOD__STUBHELPERS__GET_COM_HR_EXCEPTION_OBJECT_WINRT, 3, 1);
}
else
{
pcsDispatch->EmitCALL(METHOD__STUBHELPERS__GET_COM_HR_EXCEPTION_OBJECT, 3, 1);
}
}
else
#endif // FEATURE_COMINTEROP
{
pcsDispatch->EmitCALL(METHOD__STUBHELPERS__GET_HR_EXCEPTION_OBJECT, 1, 1);
}
pcsDispatch->EmitTHROW();
pcsDispatch->EmitLDC(0); // keep the IL stack balanced across the branch and the fall-through
pcsDispatch->EmitLabel(pSkipThrowLabel);
pcsDispatch->EmitPOP();
}
}
m_slIL.End(m_dwStubFlags);
if (!hasTryCatchForHRESULT) // we will 'leave' the try scope and then 'ret' from outside
{
pcsUnmarshal->EmitRET();
}
CORJIT_FLAGS jitFlags(CORJIT_FLAGS::CORJIT_FLAG_IL_STUB);
if (m_slIL.HasInteropParamExceptionInfo())
{
// This code will not use the secret parameter, so we do not
// tell the JIT to bother with it.
m_slIL.ClearCode();
m_slIL.GenerateInteropParamException(pcsMarshal);
}
else if (SF_IsFieldGetterStub(m_dwStubFlags) || SF_IsFieldSetterStub(m_dwStubFlags))
{
// Field access stubs are not shared and do not use the secret parameter.
}
#ifndef _WIN64
else if (SF_IsForwardDelegateStub(m_dwStubFlags) ||
(SF_IsForwardCOMStub(m_dwStubFlags) && SF_IsWinRTDelegateStub(m_dwStubFlags)))
{
// Forward delegate stubs get all the context they need in 'this' so they
// don't use the secret parameter. Except for AMD64 where we use the secret
// argument to pass the real target to the stub-for-host.
}
#endif // !_WIN64
else
{
// All other IL stubs will need to use the secret parameter.
jitFlags.Set(CORJIT_FLAGS::CORJIT_FLAG_PUBLISH_SECRET_PARAM);
}
if (SF_IsReverseStub(m_dwStubFlags))
{
SwapStubSignatures(pStubMD);
}
ILCodeLabel* pTryEndAndCatchBeginLabel = NULL; // try ends at the same place the catch begins
ILCodeLabel* pCatchEndAndReturnLabel = NULL; // catch ends at the same place we resume afterwards
#ifdef FEATURE_COMINTEROP
if (hasTryCatchForHRESULT)
{
EmitExceptionHandler(&nativeReturnType, &managedReturnType, &pTryEndAndCatchBeginLabel, &pCatchEndAndReturnLabel);
}
#endif // FEATURE_COMINTEROP
UINT maxStack;
size_t cbCode;
DWORD cbSig;
BYTE * pbBuffer;
BYTE * pbLocalSig;
cbCode = m_slIL.Link(&maxStack);
cbSig = m_slIL.GetLocalSigSize();
ILStubResolver * pResolver = pStubMD->AsDynamicMethodDesc()->GetILStubResolver();
COR_ILMETHOD_DECODER * pILHeader = pResolver->AllocGeneratedIL(cbCode, cbSig, maxStack);
pbBuffer = (BYTE *)pILHeader->Code;
pbLocalSig = (BYTE *)pILHeader->LocalVarSig;
_ASSERTE(cbSig == pILHeader->cbLocalVarSig);
ILStubEHClause cleanupTryFinally = { 0 };
ILStubEHClause convertToHRTryCatch = { 0 };
m_slIL.GetCleanupFinallyOffsets(&cleanupTryFinally);
#ifdef FEATURE_COMINTEROP
if (hasTryCatchForHRESULT)
{
convertToHRTryCatch.kind = ILStubEHClause::kTypedCatch;
convertToHRTryCatch.dwTryBeginOffset = 0;
convertToHRTryCatch.dwHandlerBeginOffset = ((DWORD)pTryEndAndCatchBeginLabel->GetCodeOffset());
convertToHRTryCatch.cbTryLength = convertToHRTryCatch.dwHandlerBeginOffset - convertToHRTryCatch.dwTryBeginOffset;
convertToHRTryCatch.cbHandlerLength = ((DWORD)pCatchEndAndReturnLabel->GetCodeOffset()) - convertToHRTryCatch.dwHandlerBeginOffset;
convertToHRTryCatch.dwTypeToken = pcsDispatch->GetToken(g_pObjectClass);
}
#endif // FEATURE_COMINTEROP
int nEHClauses = 0;
if (convertToHRTryCatch.cbHandlerLength != 0)
nEHClauses++;
if (cleanupTryFinally.cbHandlerLength != 0)
nEHClauses++;
if (nEHClauses > 0)
{
COR_ILMETHOD_SECT_EH* pEHSect = pResolver->AllocEHSect(nEHClauses);
PopulateEHSect(pEHSect, nEHClauses, &cleanupTryFinally, &convertToHRTryCatch);
}
m_slIL.GenerateCode(pbBuffer, cbCode);
m_slIL.GetLocalSig(pbLocalSig, cbSig);
pResolver->SetJitFlags(jitFlags);
#ifdef LOGGING
LOG((LF_STUBS, LL_INFO1000, "---------------------------------------------------------------------\n"));
LOG((LF_STUBS, LL_INFO1000, "NDirect IL stub dump: %s::%s\n", pStubMD->m_pszDebugClassName, pStubMD->m_pszDebugMethodName));
if (LoggingEnabled() && LoggingOn(LF_STUBS, LL_INFO1000))
{
CQuickBytes qbManaged;
CQuickBytes qbLocal;
PCCOR_SIGNATURE pManagedSig;
ULONG cManagedSig;
IMDInternalImport* pIMDI = MscorlibBinder::GetModule()->GetMDImport();
pStubMD->GetSig(&pManagedSig, &cManagedSig);
PrettyPrintSig(pManagedSig, cManagedSig, "*", &qbManaged, pStubMD->GetMDImport(), NULL);
PrettyPrintSig(pbLocalSig, cbSig, NULL, &qbLocal, pIMDI, NULL);
LOG((LF_STUBS, LL_INFO1000, "incoming managed sig: %p: %s\n", pManagedSig, qbManaged.Ptr()));
LOG((LF_STUBS, LL_INFO1000, "locals sig: %p: %s\n", pbLocalSig+1, qbLocal.Ptr()));
if (cleanupTryFinally.cbHandlerLength != 0)
{
LOG((LF_STUBS, LL_INFO1000, "try_begin: 0x%04x try_end: 0x%04x finally_begin: 0x%04x finally_end: 0x%04x \n",
cleanupTryFinally.dwTryBeginOffset, cleanupTryFinally.dwTryBeginOffset + cleanupTryFinally.cbTryLength,
cleanupTryFinally.dwHandlerBeginOffset, cleanupTryFinally.dwHandlerBeginOffset + cleanupTryFinally.cbHandlerLength));
}
if (convertToHRTryCatch.cbHandlerLength != 0)
{
LOG((LF_STUBS, LL_INFO1000, "try_begin: 0x%04x try_end: 0x%04x catch_begin: 0x%04x catch_end: 0x%04x type_token: 0x%08x\n",
convertToHRTryCatch.dwTryBeginOffset, convertToHRTryCatch.dwTryBeginOffset + convertToHRTryCatch.cbTryLength,
convertToHRTryCatch.dwHandlerBeginOffset, convertToHRTryCatch.dwHandlerBeginOffset + convertToHRTryCatch.cbHandlerLength,
convertToHRTryCatch.dwTypeToken));
}
LogILStubFlags(LF_STUBS, LL_INFO1000, m_dwStubFlags);
m_slIL.LogILStub(jitFlags);
}
LOG((LF_STUBS, LL_INFO1000, "^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n"));
#endif // LOGGING
}
#ifdef LOGGING
//---------------------------------------------------------------------------------------
//
static inline void LogOneFlag(DWORD flags, DWORD flag, LPCSTR str, DWORD facility, DWORD level)
{
LIMITED_METHOD_CONTRACT;
if (flags & flag)
{
LOG((facility, level, str));
}
}
static void LogILStubFlags(DWORD facility, DWORD level, DWORD dwStubFlags)
{
LIMITED_METHOD_CONTRACT;
LOG((facility, level, "dwStubFlags: 0x%08x\n", dwStubFlags));
LogOneFlag(dwStubFlags, NDIRECTSTUB_FL_CONVSIGASVARARG, " NDIRECTSTUB_FL_CONVSIGASVARARG\n", facility, level);
LogOneFlag(dwStubFlags, NDIRECTSTUB_FL_BESTFIT, " NDIRECTSTUB_FL_BESTFIT\n", facility, level);
LogOneFlag(dwStubFlags, NDIRECTSTUB_FL_THROWONUNMAPPABLECHAR, " NDIRECTSTUB_FL_THROWONUNMAPPABLECHAR\n", facility, level);
LogOneFlag(dwStubFlags, NDIRECTSTUB_FL_NGENEDSTUB, " NDIRECTSTUB_FL_NGENEDSTUB\n", facility, level);
LogOneFlag(dwStubFlags, NDIRECTSTUB_FL_DELEGATE, " NDIRECTSTUB_FL_DELEGATE\n", facility, level);
LogOneFlag(dwStubFlags, NDIRECTSTUB_FL_DOHRESULTSWAPPING, " NDIRECTSTUB_FL_DOHRESULTSWAPPING\n", facility, level);
LogOneFlag(dwStubFlags, NDIRECTSTUB_FL_REVERSE_INTEROP, " NDIRECTSTUB_FL_REVERSE_INTEROP\n", facility, level);
#ifdef FEATURE_COMINTEROP
LogOneFlag(dwStubFlags, NDIRECTSTUB_FL_COM, " NDIRECTSTUB_FL_COM\n", facility, level);
#endif // FEATURE_COMINTEROP
LogOneFlag(dwStubFlags, NDIRECTSTUB_FL_NGENEDSTUBFORPROFILING, " NDIRECTSTUB_FL_NGENEDSTUBFORPROFILING\n", facility, level);
LogOneFlag(dwStubFlags, NDIRECTSTUB_FL_GENERATEDEBUGGABLEIL, " NDIRECTSTUB_FL_GENERATEDEBUGGABLEIL\n", facility, level);
LogOneFlag(dwStubFlags, NDIRECTSTUB_FL_UNMANAGED_CALLI, " NDIRECTSTUB_FL_UNMANAGED_CALLI\n", facility, level);
LogOneFlag(dwStubFlags, NDIRECTSTUB_FL_TRIGGERCCTOR, " NDIRECTSTUB_FL_TRIGGERCCTOR\n", facility, level);
#ifdef FEATURE_COMINTEROP
LogOneFlag(dwStubFlags, NDIRECTSTUB_FL_FIELDGETTER, " NDIRECTSTUB_FL_FIELDGETTER\n", facility, level);
LogOneFlag(dwStubFlags, NDIRECTSTUB_FL_FIELDSETTER, " NDIRECTSTUB_FL_FIELDSETTER\n", facility, level);
LogOneFlag(dwStubFlags, NDIRECTSTUB_FL_WINRT, " NDIRECTSTUB_FL_WINRT\n", facility, level);
LogOneFlag(dwStubFlags, NDIRECTSTUB_FL_WINRTDELEGATE, " NDIRECTSTUB_FL_WINRTDELEGATE\n", facility, level);
LogOneFlag(dwStubFlags, NDIRECTSTUB_FL_WINRTSHAREDGENERIC, " NDIRECTSTUB_FL_WINRTSHAREDGENERIC\n", facility, level);
LogOneFlag(dwStubFlags, NDIRECTSTUB_FL_WINRTCTOR, " NDIRECTSTUB_FL_WINRTCTOR\n", facility, level);
LogOneFlag(dwStubFlags, NDIRECTSTUB_FL_WINRTCOMPOSITION, " NDIRECTSTUB_FL_WINRTCOMPOSITION\n", facility, level);
LogOneFlag(dwStubFlags, NDIRECTSTUB_FL_WINRTSTATIC, " NDIRECTSTUB_FL_WINRTSTATIC\n", facility, level);
LogOneFlag(dwStubFlags, NDIRECTSTUB_FL_WINRTHASREDIRECTION, " NDIRECTSTUB_FL_WINRTHASREDIRECTION\n", facility, level);
#endif // FEATURE_COMINTEROP
//
// no need to log the internal flags, let's just assert what we expect to see...
//
CONSISTENCY_CHECK(!SF_IsCOMLateBoundStub(dwStubFlags));
CONSISTENCY_CHECK(!SF_IsCOMEventCallStub(dwStubFlags));
DWORD dwKnownMask =
NDIRECTSTUB_FL_CONVSIGASVARARG |
NDIRECTSTUB_FL_BESTFIT |
NDIRECTSTUB_FL_THROWONUNMAPPABLECHAR |
NDIRECTSTUB_FL_NGENEDSTUB |
NDIRECTSTUB_FL_DELEGATE |
NDIRECTSTUB_FL_DOHRESULTSWAPPING |
NDIRECTSTUB_FL_REVERSE_INTEROP |
NDIRECTSTUB_FL_NGENEDSTUBFORPROFILING |
NDIRECTSTUB_FL_GENERATEDEBUGGABLEIL |
NDIRECTSTUB_FL_UNMANAGED_CALLI |
NDIRECTSTUB_FL_TRIGGERCCTOR |
#ifdef FEATURE_COMINTEROP
NDIRECTSTUB_FL_COM |
NDIRECTSTUB_FL_COMLATEBOUND | // internal
NDIRECTSTUB_FL_COMEVENTCALL | // internal
NDIRECTSTUB_FL_FIELDGETTER |
NDIRECTSTUB_FL_FIELDSETTER |
NDIRECTSTUB_FL_WINRT |
NDIRECTSTUB_FL_WINRTDELEGATE |
NDIRECTSTUB_FL_WINRTCTOR |
NDIRECTSTUB_FL_WINRTCOMPOSITION |
NDIRECTSTUB_FL_WINRTSTATIC |
NDIRECTSTUB_FL_WINRTHASREDIRECTION |
#endif // FEATURE_COMINTEROP
NULL;
DWORD dwUnknownFlags = dwStubFlags & ~dwKnownMask;
if (0 != dwUnknownFlags)
{
LOG((facility, level, "UNKNOWN FLAGS: 0x%08x\n", dwUnknownFlags));
}
}
#endif // LOGGING
PCCOR_SIGNATURE GetStubTargetMethodSig()
{
CONTRACT(PCCOR_SIGNATURE)
{
STANDARD_VM_CHECK;
POSTCONDITION(CheckPointer(RETVAL, NULL_NOT_OK));
}
CONTRACT_END;
BYTE *pb;
if (!m_qbNativeFnSigBuffer.Size())
{
DWORD cb = m_slIL.GetStubTargetMethodSigSize();
pb = (BYTE *)m_qbNativeFnSigBuffer.AllocThrows(cb);
m_slIL.GetStubTargetMethodSig(pb, cb);
}
else
{
pb = (BYTE*)m_qbNativeFnSigBuffer.Ptr();
}
RETURN pb;
}
DWORD
GetStubTargetMethodSigLength()
{
WRAPPER_NO_CONTRACT;
return m_slIL.GetStubTargetMethodSigSize();
}
void SetStubTargetMethodSig(PCCOR_SIGNATURE pSig, DWORD cSig)
{
WRAPPER_NO_CONTRACT;
m_slIL.SetStubTargetMethodSig(pSig, cSig);
m_qbNativeFnSigBuffer.Shrink(0);
}
TokenLookupMap* GetTokenLookupMap() { WRAPPER_NO_CONTRACT; return m_slIL.GetTokenLookupMap(); }
protected:
CQuickBytes m_qbNativeFnSigBuffer;
NDirectStubLinker m_slIL;
BOOL m_fSetLastError;
DWORD m_dwStubFlags;
};
class PInvoke_ILStubState : public ILStubState
{
public:
PInvoke_ILStubState(Module* pStubModule, const Signature &signature, SigTypeContext *pTypeContext, DWORD dwStubFlags,
CorPinvokeMap unmgdCallConv, int iLCIDParamIdx, MethodDesc* pTargetMD)
: ILStubState(
pStubModule,
signature,
pTypeContext,
TargetHasThis(dwStubFlags),
StubHasThis(dwStubFlags),
dwStubFlags,
iLCIDParamIdx,
pTargetMD)
{
STANDARD_VM_CONTRACT;
if (SF_IsForwardStub(dwStubFlags))
{
m_slIL.SetCallingConvention(unmgdCallConv, SF_IsVarArgStub(dwStubFlags));
}
}
private:
static BOOL TargetHasThis(DWORD dwStubFlags)
{
//
// in reverse pinvoke on delegate, the managed target will
// have a 'this' pointer, but the unmanaged signature does
// not.
//
return SF_IsReverseDelegateStub(dwStubFlags);
}
static BOOL StubHasThis(DWORD dwStubFlags)
{
//
// in forward pinvoke on a delegate, the stub will have a
// 'this' pointer, but the unmanaged target will not.
//
return SF_IsForwardDelegateStub(dwStubFlags);
}
};
#ifdef FEATURE_COMINTEROP
class CLRToCOM_ILStubState : public ILStubState
{
public:
CLRToCOM_ILStubState(Module* pStubModule, const Signature &signature, SigTypeContext *pTypeContext, DWORD dwStubFlags,
int iLCIDParamIdx, MethodDesc* pTargetMD)
: ILStubState(
pStubModule,
signature,
pTypeContext,
TRUE,
!SF_IsWinRTStaticStub(dwStubFlags), // fStubHasThis
dwStubFlags,
iLCIDParamIdx,
pTargetMD)
{
STANDARD_VM_CONTRACT;
if (SF_IsForwardStub(dwStubFlags))
{
m_slIL.SetCallingConvention(pmCallConvStdcall, SF_IsVarArgStub(dwStubFlags));
}
}
void BeginEmit(DWORD dwStubFlags) // CLR to COM IL
{
STANDARD_VM_CONTRACT;
ILStubState::BeginEmit(dwStubFlags);
ILCodeStream *pcsDispatch = m_slIL.GetDispatchCodeStream();
// add the 'this' COM IP parameter to the target CALLI
m_slIL.GetMarshalCodeStream()->SetStubTargetArgType(ELEMENT_TYPE_I, false);
// convert 'this' to COM IP and the target method entry point
m_slIL.EmitLoadRCWThis(pcsDispatch, m_dwStubFlags);
#ifdef _TARGET_64BIT_
if (SF_IsWinRTDelegateStub(m_dwStubFlags))
{
// write the stub context (EEImplMethodDesc representing the Invoke)
// into the secret arg so it shows up in the InlinedCallFrame and can
// be used by stub for host
pcsDispatch->EmitCALL(METHOD__STUBHELPERS__GET_STUB_CONTEXT_ADDR, 0, 1);
m_slIL.EmitLoadStubContext(pcsDispatch, dwStubFlags);
pcsDispatch->EmitSTIND_I();
pcsDispatch->EmitCALL(METHOD__STUBHELPERS__GET_STUB_CONTEXT, 0, 1);
}
else
#endif // _TARGET_64BIT_
{
m_slIL.EmitLoadStubContext(pcsDispatch, dwStubFlags);
}
pcsDispatch->EmitLDLOCA(m_slIL.GetTargetEntryPointLocalNum());
BinderMethodID getCOMIPMethod;
bool fDoPostCallIPCleanup = true;
if (!SF_IsNGENedStub(dwStubFlags) && NDirect::IsHostHookEnabled())
{
// always use the non-optimized helper if we are hosted
getCOMIPMethod = METHOD__STUBHELPERS__GET_COM_IP_FROM_RCW;
}
else if (SF_IsWinRTStub(dwStubFlags))
{
// WinRT uses optimized helpers
if (SF_IsWinRTSharedGenericStub(dwStubFlags))
getCOMIPMethod = METHOD__STUBHELPERS__GET_COM_IP_FROM_RCW_WINRT_SHARED_GENERIC;
else if (SF_IsWinRTDelegateStub(dwStubFlags))
getCOMIPMethod = METHOD__STUBHELPERS__GET_COM_IP_FROM_RCW_WINRT_DELEGATE;
else
getCOMIPMethod = METHOD__STUBHELPERS__GET_COM_IP_FROM_RCW_WINRT;
// GetCOMIPFromRCW_WinRT, GetCOMIPFromRCW_WinRTSharedGeneric, and GetCOMIPFromRCW_WinRTDelegate
// always cache the COM interface pointer so no post-call cleanup is needed
fDoPostCallIPCleanup = false;
}
else
{
// classic COM interop uses the non-optimized helper
getCOMIPMethod = METHOD__STUBHELPERS__GET_COM_IP_FROM_RCW;
}
DWORD dwIPRequiresCleanupLocalNum = (DWORD)-1;
if (fDoPostCallIPCleanup)
{
dwIPRequiresCleanupLocalNum = pcsDispatch->NewLocal(ELEMENT_TYPE_BOOLEAN);
pcsDispatch->EmitLDLOCA(dwIPRequiresCleanupLocalNum);
// StubHelpers.GetCOMIPFromRCW(object objSrc, IntPtr pCPCMD, out IntPtr ppTarget, out bool pfNeedsRelease)
pcsDispatch->EmitCALL(getCOMIPMethod, 4, 1);
}
else
{
// StubHelpers.GetCOMIPFromRCW_WinRT*(object objSrc, IntPtr pCPCMD, out IntPtr ppTarget)
pcsDispatch->EmitCALL(getCOMIPMethod, 3, 1);
}
// save it because we'll need it to compute the CALLI target and release it
pcsDispatch->EmitDUP();
pcsDispatch->EmitSTLOC(m_slIL.GetTargetInterfacePointerLocalNum());
if (fDoPostCallIPCleanup)
{
// make sure it's Release()'ed after the call
m_slIL.SetCleanupNeeded();
ILCodeStream *pcsCleanup = m_slIL.GetCleanupCodeStream();
ILCodeLabel *pSkipThisCleanup = pcsCleanup->NewCodeLabel();
// and if it requires cleanup (i.e. it's not taken from the RCW cache)
pcsCleanup->EmitLDLOC(dwIPRequiresCleanupLocalNum);
pcsCleanup->EmitBRFALSE(pSkipThisCleanup);
pcsCleanup->EmitLDLOC(m_slIL.GetTargetInterfacePointerLocalNum());
pcsCleanup->EmitCALL(METHOD__INTERFACEMARSHALER__CLEAR_NATIVE, 1, 0);
pcsCleanup->EmitLabel(pSkipThisCleanup);
}
}
};
class COMToCLR_ILStubState : public ILStubState
{
public:
COMToCLR_ILStubState(Module* pStubModule, const Signature &signature, SigTypeContext *pTypeContext, DWORD dwStubFlags,
int iLCIDParamIdx, MethodDesc* pTargetMD)
: ILStubState(
pStubModule,
signature,
pTypeContext,
TRUE,
TRUE,
dwStubFlags,
iLCIDParamIdx,
pTargetMD)
{
STANDARD_VM_CONTRACT;
}
void BeginEmit(DWORD dwStubFlags) // COM to CLR IL
{
STANDARD_VM_CONTRACT;
ILStubState::BeginEmit(dwStubFlags);
if (SF_IsWinRTStaticStub(dwStubFlags))
{
// we are not loading 'this' because the target is static
m_slIL.AdjustTargetStackDeltaForExtraParam();
}
else
{
// load this
m_slIL.GetDispatchCodeStream()->EmitLoadThis();
}
}
void MarshalFactoryReturn()
{
CONTRACTL
{
STANDARD_VM_CHECK;
PRECONDITION(SF_IsWinRTCtorStub(m_dwStubFlags));
}
CONTRACTL_END;
ILCodeStream *pcsSetup = m_slIL.GetSetupCodeStream();
ILCodeStream *pcsDispatch = m_slIL.GetDispatchCodeStream();
ILCodeStream *pcsUnmarshal = m_slIL.GetReturnUnmarshalCodeStream();
ILCodeStream *pcsExCleanup = m_slIL.GetExceptionCleanupCodeStream();
LocalDesc locDescFactoryRetVal(ELEMENT_TYPE_I);
DWORD dwFactoryRetValLocalNum = pcsSetup->NewLocal(locDescFactoryRetVal);
pcsSetup->EmitLoadNullPtr();
pcsSetup->EmitSTLOC(dwFactoryRetValLocalNum);
locDescFactoryRetVal.MakeByRef();
// expect one additional argument - pointer to a location that receives the created instance
DWORD dwRetValArgNum = pcsDispatch->SetStubTargetArgType(&locDescFactoryRetVal, false);
m_slIL.AdjustTargetStackDeltaForExtraParam();
// convert 'this' to an interface pointer corresponding to the default interface of this class
pcsUnmarshal->EmitLoadThis();
pcsUnmarshal->EmitCALL(METHOD__STUBHELPERS__GET_STUB_CONTEXT, 0, 1);
pcsUnmarshal->EmitCALL(METHOD__STUBHELPERS__GET_WINRT_FACTORY_RETURN_VALUE, 2, 1);
pcsUnmarshal->EmitSTLOC(dwFactoryRetValLocalNum);
// assign it to the location pointed to by the argument
pcsUnmarshal->EmitLDARG(dwRetValArgNum);
pcsUnmarshal->EmitLDLOC(dwFactoryRetValLocalNum);
pcsUnmarshal->EmitSTIND_I();
// on exception, we want to release the IInspectable's and assign NULL to output locations
m_slIL.SetExceptionCleanupNeeded();
EmitInterfaceClearNative(pcsExCleanup, dwFactoryRetValLocalNum);
// *retVal = NULL
pcsExCleanup->EmitLDARG(dwRetValArgNum);
pcsExCleanup->EmitLoadNullPtr();
pcsExCleanup->EmitSTIND_I();
}
};
class COMToCLRFieldAccess_ILStubState : public COMToCLR_ILStubState
{
public:
COMToCLRFieldAccess_ILStubState(Module* pStubModule, const Signature &signature, SigTypeContext *pTypeContext,
DWORD dwStubFlags, FieldDesc* pFD)
: COMToCLR_ILStubState(
pStubModule,
signature,
pTypeContext,
dwStubFlags,
-1,
NULL)
{
STANDARD_VM_CONTRACT;
_ASSERTE(pFD != NULL);
m_pFD = pFD;
}
void EmitInvokeTarget(MethodDesc *pStubMD)
{
STANDARD_VM_CONTRACT;
ILCodeStream* pcsDispatch = m_slIL.GetDispatchCodeStream();
if (SF_IsFieldGetterStub(m_dwStubFlags))
{
pcsDispatch->EmitLDFLD(pcsDispatch->GetToken(m_pFD));
}
else
{
CONSISTENCY_CHECK(SF_IsFieldSetterStub(m_dwStubFlags));
pcsDispatch->EmitSTFLD(pcsDispatch->GetToken(m_pFD));
}
}
protected:
FieldDesc *m_pFD;
};
#endif // FEATURE_COMINTEROP
NDirectStubLinker::NDirectStubLinker(
DWORD dwStubFlags,
Module* pModule,
const Signature &signature,
SigTypeContext *pTypeContext,
MethodDesc* pTargetMD,
int iLCIDParamIdx,
BOOL fTargetHasThis,
BOOL fStubHasThis)
: ILStubLinker(pModule, signature, pTypeContext, pTargetMD, fTargetHasThis, fStubHasThis, !SF_IsCOMStub(dwStubFlags)),
m_pCleanupFinallyBeginLabel(NULL),
m_pCleanupFinallyEndLabel(NULL),
m_pSkipExceptionCleanupLabel(NULL),
#ifdef FEATURE_COMINTEROP
m_dwWinRTFactoryObjectLocalNum(-1),
#endif // FEATURE_COMINTEROP
m_fHasCleanupCode(FALSE),
m_fHasExceptionCleanupCode(FALSE),
m_fCleanupWorkListIsSetup(FALSE),
m_dwThreadLocalNum(-1),
m_dwCleanupWorkListLocalNum(-1),
m_dwRetValLocalNum(-1),
m_ErrorResID(-1),
m_ErrorParamIdx(-1),
m_iLCIDParamIdx(iLCIDParamIdx),
m_dwStubFlags(dwStubFlags)
{
STANDARD_VM_CONTRACT;
m_pcsSetup = NewCodeStream(ILStubLinker::kSetup); // do any one-time setup work
m_pcsMarshal = NewCodeStream(ILStubLinker::kMarshal); // marshals arguments
m_pcsDispatch = NewCodeStream(ILStubLinker::kDispatch); // sets up arguments and makes call
m_pcsRetUnmarshal = NewCodeStream(ILStubLinker::kReturnUnmarshal); // unmarshals return value
m_pcsUnmarshal = NewCodeStream(ILStubLinker::kUnmarshal); // unmarshals arguments
m_pcsExceptionCleanup = NewCodeStream(ILStubLinker::kExceptionCleanup); // MAY NOT THROW: goes in a finally and does exception-only cleanup
m_pcsCleanup = NewCodeStream(ILStubLinker::kCleanup); // MAY NOT THROW: goes in a finally and does unconditional cleanup
//
// Add locals
m_dwArgMarshalIndexLocalNum = NewLocal(ELEMENT_TYPE_I4);
m_pcsMarshal->EmitLDC(0);
m_pcsMarshal->EmitSTLOC(m_dwArgMarshalIndexLocalNum);
#ifdef FEATURE_COMINTEROP
//
// Forward COM interop needs a local to hold target interface pointer
//
if (SF_IsForwardCOMStub(m_dwStubFlags))
{
m_dwTargetEntryPointLocalNum = NewLocal(ELEMENT_TYPE_I);
m_dwTargetInterfacePointerLocalNum = NewLocal(ELEMENT_TYPE_I);
m_pcsSetup->EmitLoadNullPtr();
m_pcsSetup->EmitSTLOC(m_dwTargetInterfacePointerLocalNum);
}
#endif // FEATURE_COMINTEROP
}
void NDirectStubLinker::SetCallingConvention(CorPinvokeMap unmngCallConv, BOOL fIsVarArg)
{
LIMITED_METHOD_CONTRACT;
ULONG uNativeCallingConv = 0;
#if !defined(_TARGET_X86_)
if (fIsVarArg)
{
// The JIT has to use a different calling convention for unmanaged vararg targets on 64-bit and ARM:
// any float values must be duplicated in the corresponding general-purpose registers.
uNativeCallingConv = CORINFO_CALLCONV_NATIVEVARARG;
}
else
#endif // !_TARGET_X86_
{
switch (unmngCallConv)
{
case pmCallConvCdecl:
uNativeCallingConv = CORINFO_CALLCONV_C;
break;
case pmCallConvStdcall:
uNativeCallingConv = CORINFO_CALLCONV_STDCALL;
break;
case pmCallConvThiscall:
uNativeCallingConv = CORINFO_CALLCONV_THISCALL;
break;
default:
_ASSERTE(!"Invalid calling convention.");
uNativeCallingConv = CORINFO_CALLCONV_STDCALL;
break;
}
}
SetStubTargetCallingConv((CorCallingConvention)uNativeCallingConv);
}
void NDirectStubLinker::EmitSetArgMarshalIndex(ILCodeStream* pcsEmit, UINT uArgIdx)
{
WRAPPER_NO_CONTRACT;
//
// This sets our state local variable that tracks the progress of the stub execution.
// In the finally block we test this variable to see what cleanup we need to do. The
// variable starts with the value of 0 and is assigned the following values as the
// stub executes:
//
// CLEANUP_INDEX_ARG0_MARSHAL + 1 - 1st argument marshaled
// CLEANUP_INDEX_ARG0_MARSHAL + 2 - 2nd argument marshaled
// ...
// CLEANUP_INDEX_ARG0_MARSHAL + n - nth argument marshaled
// CLEANUP_INDEX_RETVAL_UNMARSHAL + 1 - return value unmarshaled
// CLEANUP_INDEX_ARG0_UNMARSHAL + 1 - 1st argument unmarshaled
// CLEANUP_INDEX_ARG0_UNMARSHAL + 2 - 2nd argument unmarshaled
// ...
// CLEANUP_INDEX_ARG0_UNMARSHAL + n - nth argument unmarshaled
// CLEANUP_INDEX_ALL_DONE + 1 - ran to completion, no exception thrown
//
// Note: There may be gaps, i.e. if say 2nd argument does not need cleanup, the
// state variable will never be assigned the corresponding value. However, the
// value must always monotonically increase so we can use <=, >, etc.
//
pcsEmit->EmitLDC(uArgIdx + 1);
pcsEmit->EmitSTLOC(m_dwArgMarshalIndexLocalNum);
}
void NDirectStubLinker::EmitCheckForArgCleanup(ILCodeStream* pcsEmit, UINT uArgIdx, ArgCleanupBranchKind branchKind, ILCodeLabel* pSkipCleanupLabel)
{
STANDARD_VM_CONTRACT;
SetCleanupNeeded();
// See EmitSetArgMarshalIndex.
pcsEmit->EmitLDLOC(m_dwArgMarshalIndexLocalNum);
pcsEmit->EmitLDC(uArgIdx);
switch (branchKind)
{
case BranchIfMarshaled:
{
// we branch to the label if the argument has been marshaled
pcsEmit->EmitBGT(pSkipCleanupLabel);
break;
}
case BranchIfNotMarshaled:
{
// we branch to the label if the argument has not been marshaled
pcsEmit->EmitBLE(pSkipCleanupLabel);
break;
}
default:
UNREACHABLE();
}
}
int NDirectStubLinker::GetLCIDParamIdx()
{
LIMITED_METHOD_CONTRACT;
return m_iLCIDParamIdx;
}
ILCodeStream* NDirectStubLinker::GetSetupCodeStream()
{
LIMITED_METHOD_CONTRACT;
return m_pcsSetup;
}
ILCodeStream* NDirectStubLinker::GetMarshalCodeStream()
{
LIMITED_METHOD_CONTRACT;
return m_pcsMarshal;
}
ILCodeStream* NDirectStubLinker::GetUnmarshalCodeStream()
{
LIMITED_METHOD_CONTRACT;
return m_pcsUnmarshal;
}
ILCodeStream* NDirectStubLinker::GetReturnUnmarshalCodeStream()
{
LIMITED_METHOD_CONTRACT;
return m_pcsRetUnmarshal;
}
ILCodeStream* NDirectStubLinker::GetDispatchCodeStream()
{
LIMITED_METHOD_CONTRACT;
return m_pcsDispatch;
}
ILCodeStream* NDirectStubLinker::GetCleanupCodeStream()
{
LIMITED_METHOD_CONTRACT;
return m_pcsCleanup;
}
ILCodeStream* NDirectStubLinker::GetExceptionCleanupCodeStream()
{
LIMITED_METHOD_CONTRACT;
return m_pcsExceptionCleanup;
}
void NDirectStubLinker::AdjustTargetStackDeltaForExtraParam()
{
LIMITED_METHOD_CONTRACT;
//
// Compensate for the extra parameter.
//
m_iTargetStackDelta++;
}
void NDirectStubLinker::AdjustTargetStackDeltaForReverseInteropHRESULTSwapping()
{
WRAPPER_NO_CONTRACT;
//
// In the case of reverse pinvoke, we build up the 'target'
// signature as if it were normal forward pinvoke and then
// switch that signature (representing the native sig) with
// the stub's sig (representing the managed sig). However,
// as a side-effect, our calcualted target stack delta is
// wrong.
//
// The only way that we support a different stack delta is
// through hresult swapping. So this code "undoes" the
// deltas that would have been applied in that case.
//
if (StubHasVoidReturnType())
{
//
// If the managed return type is void, undo the HRESULT
// return type added to our target sig for HRESULT swapping.
// No extra argument will have been added because it makes
// no sense to add an extry byref void argument.
//
m_iTargetStackDelta--;
}
else
{
//
// no longer pop the extra byref argument from the stack
//
m_iTargetStackDelta++;
}
}
void NDirectStubLinker::SetInteropParamExceptionInfo(UINT resID, UINT paramIdx)
{
LIMITED_METHOD_CONTRACT;
// only keep the first one
if (HasInteropParamExceptionInfo())
{
return;
}
m_ErrorResID = resID;
m_ErrorParamIdx = paramIdx;
}
bool NDirectStubLinker::HasInteropParamExceptionInfo()
{
LIMITED_METHOD_CONTRACT;
return !(((DWORD)-1 == m_ErrorResID) && ((DWORD)-1 == m_ErrorParamIdx));
}
void NDirectStubLinker::GenerateInteropParamException(ILCodeStream* pcsEmit)
{
STANDARD_VM_CONTRACT;
pcsEmit->EmitLDC(m_ErrorResID);
pcsEmit->EmitLDC(m_ErrorParamIdx);
pcsEmit->EmitCALL(METHOD__STUBHELPERS__THROW_INTEROP_PARAM_EXCEPTION, 2, 0);
pcsEmit->EmitLDNULL();
pcsEmit->EmitTHROW();
}
#ifdef FEATURE_COMINTEROP
DWORD NDirectStubLinker::GetTargetInterfacePointerLocalNum()
{
LIMITED_METHOD_CONTRACT;
CONSISTENCY_CHECK(m_dwTargetInterfacePointerLocalNum != (DWORD)-1);
return m_dwTargetInterfacePointerLocalNum;
}
DWORD NDirectStubLinker::GetTargetEntryPointLocalNum()
{
LIMITED_METHOD_CONTRACT;
CONSISTENCY_CHECK(m_dwTargetEntryPointLocalNum != (DWORD)-1);
return m_dwTargetEntryPointLocalNum;
}
void NDirectStubLinker::EmitLoadRCWThis(ILCodeStream *pcsEmit, DWORD dwStubFlags)
{
STANDARD_VM_CONTRACT;
if (SF_IsForwardStub(dwStubFlags) &&
(SF_IsWinRTCtorStub(dwStubFlags) || SF_IsWinRTStaticStub(dwStubFlags)))
{
// WinRT ctor/static stubs make the call on the factory object instead of 'this'
if (m_dwWinRTFactoryObjectLocalNum == (DWORD)-1)
{
m_dwWinRTFactoryObjectLocalNum = NewLocal(ELEMENT_TYPE_OBJECT);
// get the factory object
EmitLoadStubContext(m_pcsSetup, dwStubFlags);
m_pcsSetup->EmitCALL(METHOD__STUBHELPERS__GET_WINRT_FACTORY_OBJECT, 1, 1);
m_pcsSetup->EmitSTLOC(m_dwWinRTFactoryObjectLocalNum);
}
pcsEmit->EmitLDLOC(m_dwWinRTFactoryObjectLocalNum);
}
else
{
pcsEmit->EmitLoadThis();
}
}
#endif // FEATURE_COMINTEROP
DWORD NDirectStubLinker::GetCleanupWorkListLocalNum()
{
LIMITED_METHOD_CONTRACT;
CONSISTENCY_CHECK(m_dwCleanupWorkListLocalNum != (DWORD)-1);
return m_dwCleanupWorkListLocalNum;
}
DWORD NDirectStubLinker::GetThreadLocalNum()
{
STANDARD_VM_CONTRACT;
if (m_dwThreadLocalNum == (DWORD)-1)
{
// The local is created and initialized lazily when first asked.
m_dwThreadLocalNum = NewLocal(ELEMENT_TYPE_I);
m_pcsSetup->EmitCALL(METHOD__THREAD__INTERNAL_GET_CURRENT_THREAD, 0, 1);
m_pcsSetup->EmitSTLOC(m_dwThreadLocalNum);
}
return m_dwThreadLocalNum;
}
DWORD NDirectStubLinker::GetReturnValueLocalNum()
{
LIMITED_METHOD_CONTRACT;
return m_dwRetValLocalNum;
}
BOOL NDirectStubLinker::IsCleanupNeeded()
{
LIMITED_METHOD_CONTRACT;
return (m_fHasCleanupCode || IsCleanupWorkListSetup());
}
BOOL NDirectStubLinker::IsExceptionCleanupNeeded()
{
LIMITED_METHOD_CONTRACT;
return m_fHasExceptionCleanupCode;
}
void NDirectStubLinker::InitCleanupCode()
{
CONTRACTL
{
STANDARD_VM_CHECK;
PRECONDITION(NULL == m_pCleanupFinallyBeginLabel);
}
CONTRACTL_END;
m_pCleanupFinallyBeginLabel = NewCodeLabel();
m_pcsExceptionCleanup->EmitLabel(m_pCleanupFinallyBeginLabel);
}
void NDirectStubLinker::InitExceptionCleanupCode()
{
CONTRACTL
{
STANDARD_VM_CHECK;
PRECONDITION(NULL == m_pSkipExceptionCleanupLabel);
}
CONTRACTL_END;
SetCleanupNeeded();
// we want to skip the entire exception cleanup if no exception has been thrown
m_pSkipExceptionCleanupLabel = NewCodeLabel();
EmitCheckForArgCleanup(m_pcsExceptionCleanup, CLEANUP_INDEX_ALL_DONE, BranchIfMarshaled, m_pSkipExceptionCleanupLabel);
}
void NDirectStubLinker::SetCleanupNeeded()
{
WRAPPER_NO_CONTRACT;
if (!m_fHasCleanupCode)
{
m_fHasCleanupCode = TRUE;
InitCleanupCode();
}
}
void NDirectStubLinker::SetExceptionCleanupNeeded()
{
WRAPPER_NO_CONTRACT;
if (!m_fHasExceptionCleanupCode)
{
m_fHasExceptionCleanupCode = TRUE;
InitExceptionCleanupCode();
}
}
void NDirectStubLinker::NeedsCleanupList()
{
STANDARD_VM_CONTRACT;
if (!IsCleanupWorkListSetup())
{
m_fCleanupWorkListIsSetup = TRUE;
SetCleanupNeeded();
// we setup a new local that will hold the cleanup work list
LocalDesc desc(MscorlibBinder::GetClass(CLASS__CLEANUP_WORK_LIST));
m_dwCleanupWorkListLocalNum = NewLocal(desc);
}
}
BOOL NDirectStubLinker::IsCleanupWorkListSetup ()
{
LIMITED_METHOD_CONTRACT;
return m_fCleanupWorkListIsSetup;
}
void NDirectStubLinker::LoadCleanupWorkList(ILCodeStream* pcsEmit)
{
STANDARD_VM_CONTRACT;
NeedsCleanupList();
pcsEmit->EmitLDLOCA(GetCleanupWorkListLocalNum());
}
void NDirectStubLinker::Begin(DWORD dwStubFlags)
{
STANDARD_VM_CONTRACT;
#ifdef FEATURE_COMINTEROP
if (SF_IsWinRTHasRedirection(dwStubFlags))
{
_ASSERTE(SF_IsForwardCOMStub(dwStubFlags));
// The very first thing we need to do is check whether the call should be routed to
// the marshaling stub for the corresponding projected WinRT interface. If so, we
// tail-call there.
m_pcsSetup->EmitLoadThis();
EmitLoadStubContext(m_pcsSetup, dwStubFlags);
m_pcsSetup->EmitCALL(METHOD__STUBHELPERS__SHOULD_CALL_WINRT_INTERFACE, 2, 1);
ILCodeLabel *pNoRedirection = m_pcsSetup->NewCodeLabel();
m_pcsSetup->EmitBRFALSE(pNoRedirection);
MethodDesc *pAdapterMD = WinRTInterfaceRedirector::GetStubMethodForRedirectedInterfaceMethod(
GetTargetMD(),
TypeHandle::Interop_ManagedToNative);
CONSISTENCY_CHECK(pAdapterMD != NULL && !pAdapterMD->HasMethodInstantiation());
m_pcsSetup->EmitJMP(m_pcsSetup->GetToken(pAdapterMD));
m_pcsSetup->EmitLabel(pNoRedirection);
}
#endif // FEATURE_COMINTEROP
if (SF_IsForwardStub(dwStubFlags))
{
if (SF_IsStubWithCctorTrigger(dwStubFlags))
{
EmitLoadStubContext(m_pcsSetup, dwStubFlags);
m_pcsSetup->EmitCALL(METHOD__STUBHELPERS__INIT_DECLARING_TYPE, 1, 0);
}
}
else
{
#ifdef MDA_SUPPORTED
if (!SF_IsNGENedStub(dwStubFlags) && MDA_GET_ASSISTANT(GcUnmanagedToManaged))
{
EmitCallGcCollectForMDA(m_pcsSetup, dwStubFlags);
}
#endif // MDA_SUPPORTED
if (SF_IsDelegateStub(dwStubFlags))
{
#if defined(MDA_SUPPORTED)
// GC was induced (gcUnmanagedToManagedMDA), arguments have been marshaled, and we are about
// to touch the UMEntryThunk and extract the delegate target from it so this is the right time
// to do the collected delegate MDA check.
// The call to CheckCollectedDelegateMDA is emitted regardless of whether the MDA is on at the
// moment. This is to avoid having to ignore NGENed stubs without the call just as we do for
// the GC MDA (callbackOncollectedDelegateMDA is turned on under managed debugger by default
// so the impact would be substantial). The helper bails out fast if the MDA is not enabled.
EmitLoadStubContext(m_pcsDispatch, dwStubFlags);
m_pcsDispatch->EmitCALL(METHOD__STUBHELPERS__CHECK_COLLECTED_DELEGATE_MDA, 1, 0);
#endif // MDA_SUPPORTED
//
// recover delegate object from UMEntryThunk
EmitLoadStubContext(m_pcsDispatch, dwStubFlags); // load UMEntryThunk*
m_pcsDispatch->EmitLDC(offsetof(UMEntryThunk, m_pObjectHandle));
m_pcsDispatch->EmitADD();
m_pcsDispatch->EmitLDIND_I(); // get OBJECTHANDLE
m_pcsDispatch->EmitLDIND_REF(); // get Delegate object
m_pcsDispatch->EmitLDFLD(GetToken(MscorlibBinder::GetField(FIELD__DELEGATE__TARGET)));
}
}
m_pCleanupTryBeginLabel = NewCodeLabel();
m_pcsMarshal->EmitLabel(m_pCleanupTryBeginLabel);
}
void NDirectStubLinker::End(DWORD dwStubFlags)
{
STANDARD_VM_CONTRACT;
ILCodeStream* pcs = m_pcsUnmarshal;
bool hasTryCatchForHRESULT = SF_IsReverseCOMStub(dwStubFlags)
&& !SF_IsFieldGetterStub(dwStubFlags)
&& !SF_IsFieldSetterStub(dwStubFlags);
//
// Create a local for the return value and store the return value in it.
//
if (IsCleanupNeeded() || hasTryCatchForHRESULT)
{
// Save the return value if necessary, since the IL stack will be emptied when we leave a try block.
LocalDesc locDescRetVal;
if (SF_IsForwardStub(dwStubFlags))
{
GetStubReturnType(&locDescRetVal);
}
else
{
GetStubTargetReturnType(&locDescRetVal);
}
if (!( (locDescRetVal.cbType == 1) && (locDescRetVal.ElementType[0] == ELEMENT_TYPE_VOID) ))
{
m_dwRetValLocalNum = m_pcsRetUnmarshal->NewLocal(locDescRetVal);
if (SF_IsReverseStub(dwStubFlags) && StubHasVoidReturnType())
{
// if the target returns void and we are doing HRESULT swapping, S_OK is loaded
// in the unmarshal stream
m_pcsUnmarshal->EmitSTLOC(m_dwRetValLocalNum);
}
else
{
// otherwise the return value is loaded in the return unmarshal stream
m_pcsRetUnmarshal->EmitSTLOC(m_dwRetValLocalNum);
}
}
else if (hasTryCatchForHRESULT && (locDescRetVal.ElementType[0] != ELEMENT_TYPE_VOID))
{
m_dwRetValLocalNum = m_pcsRetUnmarshal->NewLocal(locDescRetVal);
}
}
//
// Emit end-of-try and end-of-finally code for the try/finally
//
if (IsCleanupNeeded())
{
m_pCleanupFinallyEndLabel = NewCodeLabel();
m_pCleanupTryEndLabel = NewCodeLabel();
if (IsExceptionCleanupNeeded())
{
// if we made it here, no exception has been thrown
EmitSetArgMarshalIndex(m_pcsUnmarshal, CLEANUP_INDEX_ALL_DONE);
}
// Emit a leave at the end of the try block. If we have an outer try/catch, we need
// to leave to the beginning of the ExceptionHandler code stream, which follows the
// Cleanup code stream. If we don't, we can just leave to the tail end of the
// Unmarshal code stream where we'll emit our RET.
ILCodeLabel* pLeaveTarget = m_pCleanupTryEndLabel;
if (hasTryCatchForHRESULT)
{
pLeaveTarget = m_pCleanupFinallyEndLabel;
}
m_pcsUnmarshal->EmitLEAVE(pLeaveTarget);
m_pcsUnmarshal->EmitLabel(m_pCleanupTryEndLabel);
// Emit a call to destroy the clean-up list if needed.
if (IsCleanupWorkListSetup())
{
LoadCleanupWorkList(m_pcsCleanup);
m_pcsCleanup->EmitCALL(METHOD__STUBHELPERS__DESTROY_CLEANUP_LIST, 1, 0);
}
// Emit the endfinally.
m_pcsCleanup->EmitENDFINALLY();
m_pcsCleanup->EmitLabel(m_pCleanupFinallyEndLabel);
}
#ifdef MDA_SUPPORTED
if (SF_IsReverseStub(dwStubFlags) && !SF_IsNGENedStub(dwStubFlags) &&
MDA_GET_ASSISTANT(GcManagedToUnmanaged))
{
EmitCallGcCollectForMDA(pcs, dwStubFlags);
}
#endif // MDA_SUPPORTED
if (IsExceptionCleanupNeeded())
{
m_pcsExceptionCleanup->EmitLabel(m_pSkipExceptionCleanupLabel);
}
// Reload the return value
if ((m_dwRetValLocalNum != (DWORD)-1) && !hasTryCatchForHRESULT)
{
pcs->EmitLDLOC(m_dwRetValLocalNum);
}
}
void NDirectStubLinker::DoNDirect(ILCodeStream *pcsEmit, DWORD dwStubFlags, MethodDesc * pStubMD)
{
STANDARD_VM_CONTRACT;
if (SF_IsForwardStub(dwStubFlags)) // managed-to-native
{
if (SF_IsDelegateStub(dwStubFlags)) // delegate invocation
{
// get the delegate unmanaged target - we call a helper instead of just grabbing
// the _methodPtrAux field because we may need to intercept the call for host, MDA, etc.
pcsEmit->EmitLoadThis();
#ifdef _TARGET_64BIT_
// on AMD64 GetDelegateTarget will return address of the generic stub for host when we are hosted
// and update the secret argument with real target - the secret arg will be embedded in the
// InlinedCallFrame by the JIT and fetched via TLS->Thread->Frame->Datum by the stub for host
pcsEmit->EmitCALL(METHOD__STUBHELPERS__GET_STUB_CONTEXT_ADDR, 0, 1);
#else // !_TARGET_64BIT_
// we don't need to do this on x86 because stub for host is generated dynamically per target
pcsEmit->EmitLDNULL();
#endif // !_TARGET_64BIT_
pcsEmit->EmitCALL(METHOD__STUBHELPERS__GET_DELEGATE_TARGET, 2, 1);
}
else // direct invocation
{
if (SF_IsCALLIStub(dwStubFlags)) // unmanaged CALLI
{
// if we ever NGEN CALLI stubs, this would have to be done differently
_ASSERTE(!SF_IsNGENedStub(dwStubFlags));
// for managed-to-unmanaged CALLI that requires marshaling, the target is passed
// as the secret argument to the stub by GenericPInvokeCalliHelper (asmhelpers.asm)
EmitLoadStubContext(pcsEmit, dwStubFlags);
#ifdef _WIN64
// the secret arg has been shifted to left and ORed with 1 (see code:GenericPInvokeCalliHelper)
pcsEmit->EmitLDC(1);
pcsEmit->EmitSHR_UN();
#endif
}
else
#ifdef FEATURE_COMINTEROP
if (!SF_IsCOMStub(dwStubFlags)) // forward P/Invoke
#endif // FEATURE_COMINTEROP
{
EmitLoadStubContext(pcsEmit, dwStubFlags);
{
// Perf: inline the helper for now
//pcsEmit->EmitCALL(METHOD__STUBHELPERS__GET_NDIRECT_TARGET, 1, 1);
pcsEmit->EmitLDC(offsetof(NDirectMethodDesc, ndirect.m_pWriteableData));
pcsEmit->EmitADD();
if (decltype(NDirectMethodDesc::ndirect.m_pWriteableData)::isRelative)
{
pcsEmit->EmitDUP();
}
pcsEmit->EmitLDIND_I();
if (decltype(NDirectMethodDesc::ndirect.m_pWriteableData)::isRelative)
{
pcsEmit->EmitADD();
}
pcsEmit->EmitLDIND_I();
}
}
#ifdef FEATURE_COMINTEROP
else
{
// this is a CLR -> COM call
// the target has been computed by StubHelpers::GetCOMIPFromRCW
pcsEmit->EmitLDLOC(m_dwTargetEntryPointLocalNum);
}
#endif // FEATURE_COMINTEROP
}
}
else // native-to-managed
{
if (SF_IsDelegateStub(dwStubFlags)) // reverse P/Invoke via delegate
{
int tokDelegate_methodPtr = pcsEmit->GetToken(MscorlibBinder::GetField(FIELD__DELEGATE__METHOD_PTR));
EmitLoadStubContext(pcsEmit, dwStubFlags);
pcsEmit->EmitLDC(offsetof(UMEntryThunk, m_pObjectHandle));
pcsEmit->EmitADD();
pcsEmit->EmitLDIND_I(); // Get OBJECTHANDLE
pcsEmit->EmitLDIND_REF(); // Get Delegate object
pcsEmit->EmitLDFLD(tokDelegate_methodPtr); // get _methodPtr
}
#ifdef FEATURE_COMINTEROP
else if (SF_IsCOMStub(dwStubFlags)) // COM -> CLR call
{
// managed target is passed directly in the secret argument
EmitLoadStubContext(pcsEmit, dwStubFlags);
}
#endif // FEATURE_COMINTEROP
else // direct reverse P/Invoke (CoreCLR hosting)
{
EmitLoadStubContext(pcsEmit, dwStubFlags);
CONSISTENCY_CHECK(0 == offsetof(UMEntryThunk, m_pManagedTarget)); // if this changes, just add back the EmitLDC/EmitADD below
// pcsEmit->EmitLDC(offsetof(UMEntryThunk, m_pManagedTarget));
// pcsEmit->EmitADD();
pcsEmit->EmitLDIND_I(); // Get UMEntryThunk::m_pManagedTarget
}
}
// For managed-to-native calls, the rest of the work is done by the JIT. It will
// erect InlinedCallFrame, flip GC mode, and use the specified calling convention
// to call the target. For native-to-managed calls, this is an ordinary managed
// CALLI and nothing special happens.
pcsEmit->EmitCALLI(TOKEN_ILSTUB_TARGET_SIG, 0, m_iTargetStackDelta);
}
void NDirectStubLinker::EmitLogNativeArgument(ILCodeStream* pslILEmit, DWORD dwPinnedLocal)
{
STANDARD_VM_CONTRACT;
if (SF_IsForwardPInvokeStub(m_dwStubFlags) && !SF_IsForwardDelegateStub(m_dwStubFlags))
{
// get the secret argument via intrinsic
pslILEmit->EmitCALL(METHOD__STUBHELPERS__GET_STUB_CONTEXT, 0, 1);
}
else
{
// no secret argument
pslILEmit->EmitLoadNullPtr();
}
pslILEmit->EmitLDLOC(dwPinnedLocal);
pslILEmit->EmitCALL(METHOD__STUBHELPERS__LOG_PINNED_ARGUMENT, 2, 0);
}
void NDirectStubLinker::GetCleanupFinallyOffsets(ILStubEHClause * pClause)
{
CONTRACTL
{
STANDARD_VM_CHECK;
PRECONDITION(CheckPointer(pClause));
}
CONTRACTL_END;
if (m_pCleanupFinallyEndLabel)
{
_ASSERTE(m_pCleanupFinallyBeginLabel);
_ASSERTE(m_pCleanupTryBeginLabel);
_ASSERTE(m_pCleanupTryEndLabel);
pClause->kind = ILStubEHClause::kFinally;
pClause->dwTryBeginOffset = (DWORD)m_pCleanupTryBeginLabel->GetCodeOffset();
pClause->cbTryLength = (DWORD)m_pCleanupTryEndLabel->GetCodeOffset() - pClause->dwTryBeginOffset;
pClause->dwHandlerBeginOffset = (DWORD)m_pCleanupFinallyBeginLabel->GetCodeOffset();
pClause->cbHandlerLength = (DWORD)m_pCleanupFinallyEndLabel->GetCodeOffset() - pClause->dwHandlerBeginOffset;
}
}
void NDirectStubLinker::ClearCode()
{
WRAPPER_NO_CONTRACT;
ILStubLinker::ClearCode();
m_pCleanupTryBeginLabel = 0;
m_pCleanupTryEndLabel = 0;
m_pCleanupFinallyBeginLabel = 0;
m_pCleanupFinallyEndLabel = 0;
}
#ifdef PROFILING_SUPPORTED
DWORD NDirectStubLinker::EmitProfilerBeginTransitionCallback(ILCodeStream* pcsEmit, DWORD dwStubFlags)
{
STANDARD_VM_CONTRACT;
if (SF_IsForwardDelegateStub(dwStubFlags) || SF_IsCALLIStub(dwStubFlags))
{
// secret argument does not contain MD nor UMEntryThunk
pcsEmit->EmitLoadNullPtr();
}
else
{
EmitLoadStubContext(pcsEmit, dwStubFlags);
}
if (SF_IsForwardStub(dwStubFlags))
{
pcsEmit->EmitLDLOC(GetThreadLocalNum());
}
else
{
// we use a null pThread to indicate reverse interop
pcsEmit->EmitLDC(NULL);
}
// In the unmanaged delegate case, we need the "this" object to retrieve the MD
// in StubHelpers::ProfilerEnterCallback().
if (SF_IsDelegateStub(dwStubFlags))
{
if (SF_IsForwardStub(dwStubFlags))
{
pcsEmit->EmitLoadThis();
}
else
{
EmitLoadStubContext(pcsEmit, dwStubFlags); // load UMEntryThunk*
pcsEmit->EmitLDC(offsetof(UMEntryThunk, m_pObjectHandle));
pcsEmit->EmitADD();
pcsEmit->EmitLDIND_I(); // get OBJECTHANDLE
pcsEmit->EmitLDIND_REF(); // get Delegate object
}
}
else
{
pcsEmit->EmitLDC(NULL);
}
pcsEmit->EmitCALL(METHOD__STUBHELPERS__PROFILER_BEGIN_TRANSITION_CALLBACK, 3, 1);
// Store the MD for StubHelpers::ProfilerLeaveCallback().
DWORD dwMethodDescLocalNum = pcsEmit->NewLocal(ELEMENT_TYPE_I);
pcsEmit->EmitSTLOC(dwMethodDescLocalNum);
return dwMethodDescLocalNum;
}
void NDirectStubLinker::EmitProfilerEndTransitionCallback(ILCodeStream* pcsEmit, DWORD dwStubFlags, DWORD dwMethodDescLocalNum)
{
STANDARD_VM_CONTRACT;
pcsEmit->EmitLDLOC(dwMethodDescLocalNum);
if (SF_IsReverseStub(dwStubFlags))
{
// we use a null pThread to indicate reverse interop
pcsEmit->EmitLDC(NULL);
}
else
{
pcsEmit->EmitLDLOC(GetThreadLocalNum());
}
pcsEmit->EmitCALL(METHOD__STUBHELPERS__PROFILER_END_TRANSITION_CALLBACK, 2, 0);
}
#endif // PROFILING_SUPPPORTED
#ifdef VERIFY_HEAP
void NDirectStubLinker::EmitValidateLocal(ILCodeStream* pcsEmit, DWORD dwLocalNum, bool fIsByref, DWORD dwStubFlags)
{
STANDARD_VM_CONTRACT;
pcsEmit->EmitLDLOC(dwLocalNum);
if (SF_IsDelegateStub(dwStubFlags))
{
pcsEmit->EmitLoadNullPtr();
pcsEmit->EmitLoadThis();
}
else if (SF_IsCALLIStub(dwStubFlags))
{
pcsEmit->EmitLoadNullPtr();
pcsEmit->EmitLDNULL();
}
else
{
// P/Invoke, CLR->COM
EmitLoadStubContext(pcsEmit, dwStubFlags);
pcsEmit->EmitLDNULL();
}
if (fIsByref)
{
// StubHelpers.ValidateByref(byref, pMD, pThis)
pcsEmit->EmitCALL(METHOD__STUBHELPERS__VALIDATE_BYREF, 3, 0);
}
else
{
// StubHelpers.ValidateObject(obj, pMD, pThis)
pcsEmit->EmitCALL(METHOD__STUBHELPERS__VALIDATE_OBJECT, 3, 0);
}
}
void NDirectStubLinker::EmitObjectValidation(ILCodeStream* pcsEmit, DWORD dwStubFlags)
{
STANDARD_VM_CONTRACT;
// generate validation callouts for pinned locals
CQuickBytes qbLocalSig;
DWORD cbSig = GetLocalSigSize();
qbLocalSig.AllocThrows(cbSig);
PCOR_SIGNATURE pSig = (PCOR_SIGNATURE)qbLocalSig.Ptr();
GetLocalSig(pSig, cbSig);
SigPointer ptr(pSig, cbSig);
IfFailThrow(ptr.GetData(NULL)); // IMAGE_CEE_CS_CALLCONV_LOCAL_SIG
ULONG numLocals;
IfFailThrow(ptr.GetData(&numLocals));
for (ULONG i = 0; i < numLocals; i++)
{
BYTE modifier;
IfFailThrow(ptr.PeekByte(&modifier));
if (modifier == ELEMENT_TYPE_PINNED)
{
IfFailThrow(ptr.GetByte(NULL));
IfFailThrow(ptr.PeekByte(&modifier));
EmitValidateLocal(pcsEmit, i, (modifier == ELEMENT_TYPE_BYREF), dwStubFlags);
}
IfFailThrow(ptr.SkipExactlyOne());
}
}
#endif // VERIFY_HEAP
// Loads the 'secret argument' passed to the stub.
void NDirectStubLinker::EmitLoadStubContext(ILCodeStream* pcsEmit, DWORD dwStubFlags)
{
STANDARD_VM_CONTRACT;
CONSISTENCY_CHECK(!SF_IsForwardDelegateStub(dwStubFlags));
CONSISTENCY_CHECK(!SF_IsFieldGetterStub(dwStubFlags) && !SF_IsFieldSetterStub(dwStubFlags));
#ifdef FEATURE_COMINTEROP
if (SF_IsWinRTDelegateStub(dwStubFlags) && SF_IsForwardStub(dwStubFlags))
{
// we have the delegate 'this' but we need the EEImpl/Instantiated 'Invoke' MD pointer
// (Delegate.GetInvokeMethod does not return exact instantiated MD so we call our own helper)
pcsEmit->EmitLoadThis();
pcsEmit->EmitCALL(METHOD__STUBHELPERS__GET_DELEGATE_INVOKE_METHOD, 1, 1);
}
else
#endif // FEATURE_COMINTEROP
{
// get the secret argument via intrinsic
pcsEmit->EmitCALL(METHOD__STUBHELPERS__GET_STUB_CONTEXT, 0, 1);
}
}
#ifdef MDA_SUPPORTED
void NDirectStubLinker::EmitCallGcCollectForMDA(ILCodeStream *pcsEmit, DWORD dwStubFlags)
{
STANDARD_VM_CONTRACT;
ILCodeLabel *pSkipGcLabel = NULL;
if (SF_IsForwardPInvokeStub(dwStubFlags) &&
!SF_IsDelegateStub(dwStubFlags) &&
!SF_IsCALLIStub(dwStubFlags))
{
// don't call GC if this is a QCall
EmitLoadStubContext(pcsEmit, dwStubFlags);
pcsEmit->EmitCALL(METHOD__STUBHELPERS__IS_QCALL, 1, 1);
pSkipGcLabel = pcsEmit->NewCodeLabel();
pcsEmit->EmitBRTRUE(pSkipGcLabel);
}
pcsEmit->EmitCALL(METHOD__STUBHELPERS__TRIGGER_GC_FOR_MDA, 0, 0);
if (pSkipGcLabel != NULL)
{
pcsEmit->EmitLabel(pSkipGcLabel);
}
}
#endif // MDA_SUPPORTED
#ifdef FEATURE_COMINTEROP
class DispatchStubState : public StubState // For CLR-to-COM late-bound/eventing calls
{
public:
DispatchStubState()
: m_dwStubFlags(0),
m_lateBoundFlags(0)
{
WRAPPER_NO_CONTRACT;
}
void SetLastError(BOOL fSetLastError)
{
LIMITED_METHOD_CONTRACT;
CONSISTENCY_CHECK(!fSetLastError);
}
void BeginEmit(DWORD dwStubFlags)
{
LIMITED_METHOD_CONTRACT;
CONSISTENCY_CHECK(SF_IsCOMStub(dwStubFlags));
m_dwStubFlags = dwStubFlags;
}
void MarshalReturn(MarshalInfo* pInfo, int argOffset)
{
CONTRACTL
{
STANDARD_VM_CHECK;
PRECONDITION(CheckPointer(pInfo));
}
CONTRACTL_END;
}
void MarshalArgument(MarshalInfo* pInfo, int argOffset, UINT nativeStackOffset)
{
CONTRACTL
{
STANDARD_VM_CHECK;
PRECONDITION(CheckPointer(pInfo));
}
CONTRACTL_END;
if (SF_IsCOMLateBoundStub(m_dwStubFlags) && pInfo->GetDispWrapperType() != 0)
{
m_lateBoundFlags |= ComPlusCallInfo::kRequiresArgumentWrapping;
}
}
void MarshalLCID(int argIdx)
{
LIMITED_METHOD_CONTRACT;
}
#ifdef FEATURE_COMINTEROP
void MarshalHiddenLengthArgument(MarshalInfo *, BOOL)
{
LIMITED_METHOD_CONTRACT;
}
void MarshalFactoryReturn()
{
LIMITED_METHOD_CONTRACT;
UNREACHABLE();
}
#endif // FEATURE_COMINTEROP
void EmitInvokeTarget(MethodDesc *pStubMD)
{
LIMITED_METHOD_CONTRACT;
UNREACHABLE_MSG("Should never come to DispatchStubState::EmitInvokeTarget");
}
void FinishEmit(MethodDesc *pMD)
{
STANDARD_VM_CONTRACT;
// set flags directly on the interop MD
_ASSERTE(pMD->IsComPlusCall());
((ComPlusCallMethodDesc *)pMD)->SetLateBoundFlags(m_lateBoundFlags);
}
protected:
DWORD m_dwStubFlags;
BYTE m_lateBoundFlags; // ComPlusCallMethodDesc::Flags
};
#endif // FEATURE_COMINTEROP
void PInvokeStaticSigInfo::PreInit(Module* pModule, MethodTable * pMT)
{
CONTRACTL
{
THROWS;
GC_NOTRIGGER;
MODE_ANY;
}
CONTRACTL_END;
// initialize data members
m_wFlags = 0;
m_pModule = pModule;
m_callConv = (CorPinvokeMap)0;
SetBestFitMapping (TRUE);
SetThrowOnUnmappableChar (FALSE);
SetLinkFlags (nlfNone);
SetCharSet (nltAnsi);
m_error = 0;
// assembly/type level m_bestFit & m_bThrowOnUnmappableChar
BOOL bBestFit;
BOOL bThrowOnUnmappableChar;
if (pMT != NULL)
{
EEClass::GetBestFitMapping(pMT, &bBestFit, &bThrowOnUnmappableChar);
}
else
{
ReadBestFitCustomAttribute(m_pModule->GetMDImport(), mdTypeDefNil, &bBestFit, &bThrowOnUnmappableChar);
}
SetBestFitMapping (bBestFit);
SetThrowOnUnmappableChar (bThrowOnUnmappableChar);
}
void PInvokeStaticSigInfo::PreInit(MethodDesc* pMD)
{
CONTRACTL
{
THROWS;
GC_NOTRIGGER;
MODE_ANY;
}
CONTRACTL_END;
PreInit(pMD->GetModule(), pMD->GetMethodTable());
SetIsStatic (pMD->IsStatic());
m_sig = pMD->GetSignature();
if (pMD->IsEEImpl())
{
CONSISTENCY_CHECK(pMD->GetMethodTable()->IsDelegate());
SetIsDelegateInterop(TRUE);
}
}
PInvokeStaticSigInfo::PInvokeStaticSigInfo(
MethodDesc* pMD, LPCUTF8 *pLibName, LPCUTF8 *pEntryPointName, ThrowOnError throwOnError)
{
CONTRACTL
{
THROWS;
GC_NOTRIGGER;
MODE_ANY;
}
CONTRACTL_END;
DllImportInit(pMD, pLibName, pEntryPointName);
if (throwOnError)
ReportErrors();
}
PInvokeStaticSigInfo::PInvokeStaticSigInfo(MethodDesc* pMD, ThrowOnError throwOnError)
{
CONTRACTL
{
THROWS;
GC_NOTRIGGER;
MODE_ANY;
PRECONDITION(CheckPointer(pMD));
}
CONTRACTL_END;
HRESULT hr = S_OK;
MethodTable * pMT = pMD->GetMethodTable();
if (!pMT->IsDelegate())
{
DllImportInit(pMD, NULL, NULL);
return;
}
// initialize data members to defaults
PreInit(pMD);
// System.Runtime.InteropServices.UnmanagedFunctionPointerAttribute
BYTE* pData = NULL;
LONG cData = 0;
CorPinvokeMap callConv = (CorPinvokeMap)0;
HRESULT hRESULT = pMT->GetMDImport()->GetCustomAttributeByName(
pMT->GetCl(), g_UnmanagedFunctionPointerAttribute, (const VOID **)(&pData), (ULONG *)&cData);
IfFailThrow(hRESULT);
if(cData != 0)
{
CustomAttributeParser ca(pData, cData);
CaArg args[1];
args[0].InitEnum(SERIALIZATION_TYPE_I4, (ULONG)m_callConv);
IfFailGo(ParseKnownCaArgs(ca, args, lengthof(args)));
enum UnmanagedFunctionPointerNamedArgs
{
MDA_CharSet,
MDA_BestFitMapping,
MDA_ThrowOnUnmappableChar,
MDA_SetLastError,
MDA_PreserveSig,
MDA_Last,
};
CaNamedArg namedArgs[MDA_Last];
namedArgs[MDA_CharSet].InitI4FieldEnum("CharSet", "System.Runtime.InteropServices.CharSet", (ULONG)GetCharSet());
namedArgs[MDA_BestFitMapping].InitBoolField("BestFitMapping", (ULONG)GetBestFitMapping());
namedArgs[MDA_ThrowOnUnmappableChar].InitBoolField("ThrowOnUnmappableChar", (ULONG)GetThrowOnUnmappableChar());
namedArgs[MDA_SetLastError].InitBoolField("SetLastError", 0);
namedArgs[MDA_PreserveSig].InitBoolField("PreserveSig", 0);
IfFailGo(ParseKnownCaNamedArgs(ca, namedArgs, lengthof(namedArgs)));
callConv = (CorPinvokeMap)(args[0].val.u4 << 8);
CorNativeLinkType nlt = (CorNativeLinkType)0;
// XXX Tue 07/19/2005
// Keep in sync with the handling of CorPInvokeMap in
// PInvokeStaticSigInfo::DllImportInit.
switch( namedArgs[MDA_CharSet].val.u4 )
{
case 0:
case nltAnsi:
nlt = nltAnsi; break;
case nltUnicode:
case nltAuto: // Since Win9x isn't supported anymore, nltAuto always represents unicode strings.
nlt = nltUnicode; break;
default:
hr = E_FAIL; goto ErrExit;
}
SetCharSet ( nlt );
SetBestFitMapping (namedArgs[MDA_BestFitMapping].val.u1);
SetThrowOnUnmappableChar (namedArgs[MDA_ThrowOnUnmappableChar].val.u1);
if (namedArgs[MDA_SetLastError].val.u1)
SetLinkFlags ((CorNativeLinkFlags)(nlfLastError | GetLinkFlags()));
if (namedArgs[MDA_PreserveSig].val.u1)
SetLinkFlags ((CorNativeLinkFlags)(nlfNoMangle | GetLinkFlags()));
}
ErrExit:
if (hr != S_OK)
SetError(IDS_EE_NDIRECT_BADNATL);
InitCallConv(callConv, pMD->IsVarArg());
if (throwOnError)
ReportErrors();
}
PInvokeStaticSigInfo::PInvokeStaticSigInfo(
Signature sig, Module* pModule, ThrowOnError throwOnError)
{
CONTRACTL
{
THROWS;
GC_NOTRIGGER;
MODE_ANY;
PRECONDITION(CheckPointer(pModule));
}
CONTRACTL_END;
PreInit(pModule, NULL);
m_sig = sig;
SetIsStatic (!(MetaSig::GetCallingConvention(pModule, sig) & IMAGE_CEE_CS_CALLCONV_HASTHIS));
InitCallConv((CorPinvokeMap)0, FALSE);
if (throwOnError)
ReportErrors();
}
void PInvokeStaticSigInfo::DllImportInit(MethodDesc* pMD, LPCUTF8 *ppLibName, LPCUTF8 *ppEntryPointName)
{
CONTRACTL
{
THROWS;
GC_NOTRIGGER;
MODE_ANY;
PRECONDITION(CheckPointer(pMD));
// These preconditions to prevent multithreaded regression
// where pMD->ndirect.m_szLibName was passed in directly, cleared
// by this API, then accessed on another thread before being reset here.
PRECONDITION(CheckPointer(ppLibName, NULL_OK) && (!ppLibName || *ppLibName == NULL));
PRECONDITION(CheckPointer(ppEntryPointName, NULL_OK) && (!ppEntryPointName || *ppEntryPointName == NULL));
}
CONTRACTL_END;
// initialize data members to defaults
PreInit(pMD);
// System.Runtime.InteropServices.DllImportAttribute
IMDInternalImport *pInternalImport = pMD->GetMDImport();
CorPinvokeMap mappingFlags = pmMaxValue;
mdModuleRef modref = mdModuleRefNil;
if (FAILED(pInternalImport->GetPinvokeMap(pMD->GetMemberDef(), (DWORD*)&mappingFlags, ppEntryPointName, &modref)))
{
InitCallConv((CorPinvokeMap)0, pMD->IsVarArg());
return;
}
// out parameter pEntryPointName
if (ppEntryPointName && *ppEntryPointName == NULL)
*ppEntryPointName = pMD->GetName();
// out parameter pLibName
if (ppLibName != NULL)
{
if (FAILED(pInternalImport->GetModuleRefProps(modref, ppLibName)))
{
SetError(IDS_CLASSLOAD_BADFORMAT);
return;
}
}
// m_callConv
InitCallConv((CorPinvokeMap)(mappingFlags & pmCallConvMask), pMD->IsVarArg());
// m_bestFit
CorPinvokeMap bestFitMask = (CorPinvokeMap)(mappingFlags & pmBestFitMask);
if (bestFitMask == pmBestFitEnabled)
SetBestFitMapping (TRUE);
else if (bestFitMask == pmBestFitDisabled)
SetBestFitMapping (FALSE);
// m_bThrowOnUnmappableChar
CorPinvokeMap unmappableMask = (CorPinvokeMap)(mappingFlags & pmThrowOnUnmappableCharMask);
if (unmappableMask == pmThrowOnUnmappableCharEnabled)
SetThrowOnUnmappableChar (TRUE);
else if (unmappableMask == pmThrowOnUnmappableCharDisabled)
SetThrowOnUnmappableChar (FALSE);
// inkFlags : CorPinvoke -> CorNativeLinkFlags
if (mappingFlags & pmSupportsLastError)
SetLinkFlags ((CorNativeLinkFlags)(GetLinkFlags() | nlfLastError));
if (mappingFlags & pmNoMangle)
SetLinkFlags ((CorNativeLinkFlags)(GetLinkFlags() | nlfNoMangle));
// XXX Tue 07/19/2005
// Keep in sync with the handling of CorNativeLinkType in
// PInvokeStaticSigInfo::PInvokeStaticSigInfo.
// charset : CorPinvoke -> CorNativeLinkType
CorPinvokeMap charSetMask = (CorPinvokeMap)(mappingFlags & (pmCharSetNotSpec | pmCharSetAnsi | pmCharSetUnicode | pmCharSetAuto));
if (charSetMask == pmCharSetNotSpec || charSetMask == pmCharSetAnsi)
{
SetCharSet (nltAnsi);
}
else if (charSetMask == pmCharSetUnicode || charSetMask == pmCharSetAuto)
{
// Since Win9x isn't supported anymore, pmCharSetAuto always represents unicode strings.
SetCharSet (nltUnicode);
}
else
{
SetError(IDS_EE_NDIRECT_BADNATL);
}
}
inline CorPinvokeMap GetDefaultCallConv(BOOL bIsVarArg)
{
#ifdef PLATFORM_UNIX
return pmCallConvCdecl;
#else // PLATFORM_UNIX
return bIsVarArg ? pmCallConvCdecl : pmCallConvStdcall;
#endif // !PLATFORM_UNIX
}
void PInvokeStaticSigInfo::InitCallConv(CorPinvokeMap callConv, BOOL bIsVarArg)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
}
CONTRACTL_END
// Convert WinAPI methods to either StdCall or CDecl based on if they are varargs or not.
if (callConv == pmCallConvWinapi)
callConv = GetDefaultCallConv(bIsVarArg);
CorPinvokeMap sigCallConv = (CorPinvokeMap)0;
BOOL fSuccess = MetaSig::GetUnmanagedCallingConvention(m_pModule, m_sig.GetRawSig(), m_sig.GetRawSigLen(), &sigCallConv);
if (!fSuccess)
{
SetError(IDS_EE_NDIRECT_BADNATL); //Bad metadata format
}
// Do the same WinAPI to StdCall or CDecl for the signature calling convention as well. We need
// to do this before we check to make sure the PInvoke map calling convention and the
// signature calling convention match for compatibility reasons.
if (sigCallConv == pmCallConvWinapi)
sigCallConv = GetDefaultCallConv(bIsVarArg);
if (callConv != 0 && sigCallConv != 0 && callConv != sigCallConv)
SetError(IDS_EE_NDIRECT_BADNATL_CALLCONV);
if (callConv == 0 && sigCallConv == 0)
m_callConv = GetDefaultCallConv(bIsVarArg);
else if (callConv != 0)
m_callConv = callConv;
else
m_callConv = sigCallConv;
if (bIsVarArg && m_callConv != pmCallConvCdecl)
SetError(IDS_EE_NDIRECT_BADNATL_VARARGS_CALLCONV);
}
void PInvokeStaticSigInfo::ReportErrors()
{
CONTRACTL
{
THROWS;
GC_NOTRIGGER;
MODE_ANY;
}
CONTRACTL_END;
if (m_error != 0)
COMPlusThrow(kTypeLoadException, m_error);
}
//---------------------------------------------------------
// Does a class or method have a NAT_L CustomAttribute?
//
// S_OK = yes
// S_FALSE = no
// FAILED = unknown because something failed.
//---------------------------------------------------------
/*static*/
HRESULT NDirect::HasNAT_LAttribute(IMDInternalImport *pInternalImport, mdToken token, DWORD dwMemberAttrs)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
PRECONDITION(CheckPointer(pInternalImport));
PRECONDITION(TypeFromToken(token) == mdtMethodDef);
}
CONTRACTL_END;
// Check method flags first before trying to find the custom value
if (!IsReallyMdPinvokeImpl(dwMemberAttrs))
return S_FALSE;
DWORD mappingFlags;
LPCSTR pszImportName;
mdModuleRef modref;
if (SUCCEEDED(pInternalImport->GetPinvokeMap(token, &mappingFlags, &pszImportName, &modref)))
return S_OK;
return S_FALSE;
}
// Either MD or signature & module must be given.
/*static*/
BOOL NDirect::MarshalingRequired(MethodDesc *pMD, PCCOR_SIGNATURE pSig /*= NULL*/, Module *pModule /*= NULL*/)
{
CONTRACTL
{
STANDARD_VM_CHECK;
PRECONDITION(pMD != NULL || (pSig != NULL && pModule != NULL));
}
CONTRACTL_END;
// As a by-product, when returning FALSE we will also set the native stack size to the MD if it's
// an NDirectMethodDesc. This number is needed to link the P/Invoke (it determines the @n entry
// point name suffix and affects alignment thunk generation on the Mac). If this method returns
// TRUE, the stack size will be set when building the marshaling IL stub.
DWORD dwStackSize = 0;
CorPinvokeMap callConv = (CorPinvokeMap)0;
if (pMD != NULL)
{
if (pMD->IsNDirect() || pMD->IsComPlusCall())
{
// HRESULT swapping is handled by stub
if ((pMD->GetImplAttrs() & miPreserveSig) == 0)
return TRUE;
}
// SetLastError is handled by stub
PInvokeStaticSigInfo sigInfo(pMD);
if (sigInfo.GetLinkFlags() & nlfLastError)
return TRUE;
// LCID argument is handled by stub
if (GetLCIDParameterIndex(pMD) != -1)
return TRUE;
// making sure that cctor has run may be handled by stub
if (pMD->IsNDirect() && ((NDirectMethodDesc *)pMD)->IsClassConstructorTriggeredByILStub())
return TRUE;
callConv = sigInfo.GetCallConv();
}
if (pSig == NULL)
{
PREFIX_ASSUME(pMD != NULL);
pSig = pMD->GetSig();
pModule = pMD->GetModule();
}
// Check to make certain that the signature only contains types that marshal trivially
SigPointer ptr(pSig);
IfFailThrow(ptr.GetCallingConvInfo(NULL));
ULONG numArgs;
IfFailThrow(ptr.GetData(&numArgs));
numArgs++; // +1 for return type
// We'll need to parse parameter native types
mdParamDef *pParamTokenArray = (mdParamDef *)_alloca(numArgs * sizeof(mdParamDef));
IMDInternalImport *pMDImport = pModule->GetMDImport();
SigTypeContext emptyTypeContext;
mdMethodDef methodToken = mdMethodDefNil;
if (pMD != NULL)
{
methodToken = pMD->GetMemberDef();
}
CollateParamTokens(pMDImport, methodToken, numArgs - 1, pParamTokenArray);
for (ULONG i = 0; i < numArgs; i++)
{
SigPointer arg = ptr;
CorElementType type;
IfFailThrow(arg.PeekElemType(&type));
switch (type)
{
case ELEMENT_TYPE_PTR:
{
IfFailThrow(arg.GetElemType(NULL)); // skip ELEMENT_TYPE_PTR
IfFailThrow(arg.PeekElemType(&type));
if (type == ELEMENT_TYPE_VALUETYPE)
{
if ((arg.HasCustomModifier(pModule,
"Microsoft.VisualC.NeedsCopyConstructorModifier",
ELEMENT_TYPE_CMOD_REQD)) ||
(arg.HasCustomModifier(pModule,
"System.Runtime.CompilerServices.IsCopyConstructed",
ELEMENT_TYPE_CMOD_REQD)))
{
return TRUE;
}
}
if (i > 0) dwStackSize += sizeof(SLOT);
break;
}
case ELEMENT_TYPE_INTERNAL:
// this check is not functional in DAC and provides no security against a malicious dump
// the DAC is prepared to receive an invalid type handle
#ifndef DACCESS_COMPILE
if (pModule->IsSigInIL(arg.GetPtr()))
THROW_BAD_FORMAT(BFA_BAD_SIGNATURE, (Module*)pModule);
#endif
/* Fall thru */
case ELEMENT_TYPE_VALUETYPE:
{
TypeHandle hndArgType = arg.GetTypeHandleThrowing(pModule, &emptyTypeContext);
// JIT can handle internal blittable value types
if (!hndArgType.IsBlittable() && !hndArgType.IsEnum())
{
return TRUE;
}
// return value is fine as long as it can be normalized to an integer
if (i == 0)
{
CorElementType normalizedType = hndArgType.GetInternalCorElementType();
if (normalizedType == ELEMENT_TYPE_VALUETYPE)
{
// it is a structure even after normalization
return TRUE;
}
}
else
{
dwStackSize += StackElemSize(hndArgType.GetSize());
}
break;
}
case ELEMENT_TYPE_BOOLEAN:
case ELEMENT_TYPE_CHAR:
{
// Bool requires marshaling
// Char may require marshaling (MARSHAL_TYPE_ANSICHAR)
return TRUE;
}
default:
{
if (CorTypeInfo::IsPrimitiveType(type) || type == ELEMENT_TYPE_FNPTR)
{
if (i > 0) dwStackSize += StackElemSize(CorTypeInfo::Size(type));
}
else
{
// other non-primitive type - requires marshaling
return TRUE;
}
}
}
// check for explicit MarshalAs
NativeTypeParamInfo paramInfo;
if (pParamTokenArray[i] != mdParamDefNil)
{
if (!ParseNativeTypeInfo(pParamTokenArray[i], pMDImport, ¶mInfo) ||
paramInfo.m_NativeType != NATIVE_TYPE_DEFAULT)
{
// Presence of MarshalAs does not necessitate marshaling (it could as well be the default
// for the type), but it's a good enough heuristic. We definitely don't want to duplicate
// the logic from code:MarshalInfo.MarshalInfo here.
return TRUE;
}
}
IfFailThrow(ptr.SkipExactlyOne());
}
if (!FitsInU2(dwStackSize))
return TRUE;
// do not set the stack size for varargs - the number is call site specific
if (pMD != NULL && !pMD->IsVarArg())
{
if (pMD->IsNDirect())
{
((NDirectMethodDesc *)pMD)->SetStackArgumentSize(static_cast<WORD>(dwStackSize), callConv);
}
#ifdef FEATURE_COMINTEROP
else if (pMD->IsComPlusCall())
{
// calling convention is always stdcall
((ComPlusCallMethodDesc *)pMD)->SetStackArgumentSize(static_cast<WORD>(dwStackSize));
}
#endif // FEATURE_COMINTEROP
}
return FALSE;
}
// factorization of CreateNDirectStubWorker
static MarshalInfo::MarshalType DoMarshalReturnValue(MetaSig& msig,
mdParamDef* params,
CorNativeLinkType nlType,
CorNativeLinkFlags nlFlags,
UINT argidx, // this is used for reverse pinvoke hresult swapping
StubState* pss,
BOOL fThisCall,
int argOffset,
DWORD dwStubFlags,
MethodDesc *pMD,
UINT& nativeStackOffset,
bool& fStubNeedsCOM,
int nativeArgIndex
DEBUG_ARG(LPCUTF8 pDebugName)
DEBUG_ARG(LPCUTF8 pDebugClassName)
)
{
CONTRACTL
{
STANDARD_VM_CHECK;
PRECONDITION(CheckPointer(params));
PRECONDITION(CheckPointer(pss));
PRECONDITION(CheckPointer(pMD, NULL_OK));
}
CONTRACTL_END;
MarshalInfo::MarshalType marshalType = (MarshalInfo::MarshalType) 0xcccccccc;
MarshalInfo::MarshalScenario ms;
#ifdef FEATURE_COMINTEROP
if (SF_IsCOMStub(dwStubFlags))
{
if (SF_IsWinRTStub(dwStubFlags))
ms = MarshalInfo::MARSHAL_SCENARIO_WINRT;
else
ms = MarshalInfo::MARSHAL_SCENARIO_COMINTEROP;
}
else
#endif // FEATURE_COMINTEROP
{
ms = MarshalInfo::MARSHAL_SCENARIO_NDIRECT;
}
#ifdef FEATURE_COMINTEROP
if (SF_IsWinRTCtorStub(dwStubFlags))
{
_ASSERTE(msig.GetReturnType() == ELEMENT_TYPE_VOID);
_ASSERTE(SF_IsHRESULTSwapping(dwStubFlags));
pss->MarshalFactoryReturn();
nativeStackOffset += sizeof(LPVOID);
if (SF_IsWinRTCompositionStub(dwStubFlags))
{
nativeStackOffset += 2 * sizeof(LPVOID);
}
}
else
#endif // FEATURE_COMINTEROP
if (msig.GetReturnType() != ELEMENT_TYPE_VOID)
{
MarshalInfo returnInfo(msig.GetModule(),
msig.GetReturnProps(),
msig.GetSigTypeContext(),
params[0],
ms,
nlType,
nlFlags,
FALSE,
argidx,
msig.NumFixedArgs(),
SF_IsBestFit(dwStubFlags),
SF_IsThrowOnUnmappableChar(dwStubFlags),
TRUE,
pMD,
TRUE
DEBUG_ARG(pDebugName)
DEBUG_ARG(pDebugClassName)
DEBUG_ARG(0)
);
marshalType = returnInfo.GetMarshalType();
fStubNeedsCOM |= returnInfo.MarshalerRequiresCOM();
#ifdef FEATURE_COMINTEROP
if (marshalType == MarshalInfo::MARSHAL_TYPE_HIDDENLENGTHARRAY)
{
// Hidden length arrays are only valid with HRESULT swapping
if (!SF_IsHRESULTSwapping(dwStubFlags))
{
COMPlusThrow(kMarshalDirectiveException, IDS_EE_COM_UNSUPPORTED_SIG);
}
// We should be safe to cast here - giant signatures will fail to marashal later with IDS_EE_SIGTOOCOMPLEX
returnInfo.SetHiddenLengthParamIndex(static_cast<UINT16>(nativeArgIndex));
// Inject the hidden argument so that it winds up at the end of the method signature
pss->MarshalHiddenLengthArgument(&returnInfo, TRUE);
nativeStackOffset += returnInfo.GetHiddenLengthParamStackSize();
if (SF_IsReverseStub(dwStubFlags))
{
++argOffset;
}
}
if (SF_IsCOMStub(dwStubFlags))
{
if (marshalType == MarshalInfo::MARSHAL_TYPE_VALUECLASS ||
marshalType == MarshalInfo::MARSHAL_TYPE_BLITTABLEVALUECLASS ||
marshalType == MarshalInfo::MARSHAL_TYPE_GUID ||
marshalType == MarshalInfo::MARSHAL_TYPE_DECIMAL)
{
#ifndef _TARGET_X86_
// We cannot optimize marshalType to MARSHAL_TYPE_GENERIC_* because the JIT works with exact types
// and would refuse to compile the stub if it implicitly converted between scalars and value types (also see
// code:MarshalInfo.MarhalInfo where we do the optimization on x86). We want to throw only if the structure
// is too big to be returned in registers.
if (marshalType != MarshalInfo::MARSHAL_TYPE_BLITTABLEVALUECLASS ||
IsUnmanagedValueTypeReturnedByRef(returnInfo.GetNativeArgSize()))
#endif // _TARGET_X86_
{
if (!SF_IsHRESULTSwapping(dwStubFlags) && !SF_IsCOMLateBoundStub(dwStubFlags))
{
// Note that this limitation is very likely not needed anymore and could be lifted if we care.
COMPlusThrow(kMarshalDirectiveException, IDS_EE_COM_UNSUPPORTED_SIG);
}
}
pss->MarshalReturn(&returnInfo, argOffset);
}
else
{
// We don't support native methods that return VARIANTs directly.
if (marshalType == MarshalInfo::MARSHAL_TYPE_OBJECT)
{
if (!SF_IsHRESULTSwapping(dwStubFlags) && !SF_IsCOMLateBoundStub(dwStubFlags))
{
COMPlusThrow(kMarshalDirectiveException, IDS_EE_COM_UNSUPPORTED_SIG);
}
}
pss->MarshalReturn(&returnInfo, argOffset);
}
}
else
#endif // FEATURE_COMINTEROP
{
if (marshalType > MarshalInfo::MARSHAL_TYPE_DOUBLE && IsUnsupportedValueTypeReturn(msig))
{
if (marshalType == MarshalInfo::MARSHAL_TYPE_BLITTABLEVALUECLASS
|| marshalType == MarshalInfo::MARSHAL_TYPE_GUID
|| marshalType == MarshalInfo::MARSHAL_TYPE_DECIMAL
#ifdef FEATURE_COMINTEROP
|| marshalType == MarshalInfo::MARSHAL_TYPE_DATETIME
#endif // FEATURE_COMINTEROP
)
{
if (SF_IsHRESULTSwapping(dwStubFlags))
{
// V1 restriction: we could implement this but it's late in the game to do so.
COMPlusThrow(kMarshalDirectiveException, IDS_EE_NDIRECT_UNSUPPORTED_SIG);
}
}
else if (marshalType == MarshalInfo::MARSHAL_TYPE_HANDLEREF)
{
COMPlusThrow(kMarshalDirectiveException, IDS_EE_BADMARSHAL_HANDLEREFRESTRICTION);
}
else
{
COMPlusThrow(kMarshalDirectiveException, IDS_EE_NDIRECT_UNSUPPORTED_SIG);
}
}
#ifdef FEATURE_COMINTEROP
if (marshalType == MarshalInfo::MARSHAL_TYPE_OBJECT && !SF_IsHRESULTSwapping(dwStubFlags))
{
// No support for returning variants. This is a V1 restriction, due to the late date,
// don't want to add the special-case code to support this in light of low demand.
COMPlusThrow(kMarshalDirectiveException, IDS_EE_NOVARIANTRETURN);
}
#endif // FEATURE_COMINTEROP
pss->MarshalReturn(&returnInfo, argOffset);
}
}
return marshalType;
}
static inline UINT GetStackOffsetFromStackSize(UINT stackSize, bool fThisCall)
{
LIMITED_METHOD_CONTRACT;
#ifdef _TARGET_X86_
if (fThisCall)
{
// -1 means that the argument is not on the stack
return (stackSize >= sizeof(SLOT) ? (stackSize - sizeof(SLOT)) : (UINT)-1);
}
#endif // _TARGET_X86_
return stackSize;
}
#ifdef FEATURE_COMINTEROP
struct HiddenParameterInfo
{
MarshalInfo *pManagedParam; // Managed parameter which required the hidden parameter
int nativeIndex; // 0 based index into the native method signature where the hidden parameter should be injected
};
// Get the indexes of any hidden length parameters to be marshaled for the method
//
// At return, each value in the ppParamIndexes array is a 0 based index into the native method signature where
// the length parameter for a hidden length array should be passed. The MarshalInfo objects will also be
// updated such that they all have explicit marshaling information.
//
// The caller is responsible for freeing the memory pointed to by ppParamIndexes
void CheckForHiddenParameters(DWORD cParamMarshalInfo,
__in_ecount(cParamMarshalInfo) MarshalInfo *pParamMarshalInfo,
__out DWORD *pcHiddenNativeParameters,
__out HiddenParameterInfo **ppHiddenNativeParameters)
{
CONTRACTL
{
STANDARD_VM_CHECK;
PRECONDITION(CheckPointer(pParamMarshalInfo));
PRECONDITION(CheckPointer(pcHiddenNativeParameters));
PRECONDITION(CheckPointer(ppHiddenNativeParameters));
}
CONTRACTL_END;
NewArrayHolder<HiddenParameterInfo> hiddenParamInfo(new HiddenParameterInfo[cParamMarshalInfo]);
DWORD foundInfoCount = 0;
for (DWORD iParam = 0; iParam < cParamMarshalInfo; ++iParam)
{
// Look for hidden length arrays, which all require additional parameters to be added
if (pParamMarshalInfo[iParam].GetMarshalType() == MarshalInfo::MARSHAL_TYPE_HIDDENLENGTHARRAY)
{
DWORD currentNativeIndex = iParam + foundInfoCount;
// The location of the length parameter is implicitly just before the array pointer.
// We'll give it our current index, and bumping the found count will push us back a slot.
// We should be safe to cast here - giant signatures will fail to marashal later with IDS_EE_SIGTOOCOMPLEX
pParamMarshalInfo[iParam].SetHiddenLengthParamIndex(static_cast<UINT16>(currentNativeIndex));
hiddenParamInfo[foundInfoCount].nativeIndex = pParamMarshalInfo[iParam].HiddenLengthParamIndex();
hiddenParamInfo[foundInfoCount].pManagedParam = &(pParamMarshalInfo[iParam]);
++foundInfoCount;
}
}
*pcHiddenNativeParameters = foundInfoCount;
*ppHiddenNativeParameters = hiddenParamInfo.Extract();
}
bool IsHiddenParameter(int nativeArgIndex,
DWORD cHiddenParameters,
__in_ecount(cHiddenParameters) HiddenParameterInfo *pHiddenParameters,
__out HiddenParameterInfo **ppHiddenParameterInfo)
{
CONTRACTL
{
STANDARD_VM_CHECK;
PRECONDITION(cHiddenParameters == 0 || CheckPointer(pHiddenParameters));
PRECONDITION(CheckPointer(ppHiddenParameterInfo));
}
CONTRACTL_END;
*ppHiddenParameterInfo = NULL;
for (DWORD i = 0; i < cHiddenParameters; ++i)
{
_ASSERTE(pHiddenParameters[i].nativeIndex != -1);
if (pHiddenParameters[i].nativeIndex == nativeArgIndex)
{
*ppHiddenParameterInfo = &(pHiddenParameters[i]);
return true;
}
}
return false;
}
#endif // FEATURE_COMINTEROP
//---------------------------------------------------------
// Creates a new stub for a N/Direct call. Return refcount is 1.
// Note that this function may now throw if it fails to create
// a stub.
//---------------------------------------------------------
static void CreateNDirectStubWorker(StubState* pss,
StubSigDesc* pSigDesc,
CorNativeLinkType nlType,
CorNativeLinkFlags nlFlags,
CorPinvokeMap unmgdCallConv,
DWORD dwStubFlags,
MethodDesc *pMD,
mdParamDef* pParamTokenArray,
int iLCIDArg
)
{
CONTRACTL
{
STANDARD_VM_CHECK;
PRECONDITION(CheckPointer(pss));
PRECONDITION(CheckPointer(pSigDesc));
PRECONDITION(CheckPointer(pMD, NULL_OK));
PRECONDITION(!pMD || pMD->IsILStub() || (0 != pMD->GetMethodTable()->IsDelegate()) == SF_IsDelegateStub(dwStubFlags));
}
CONTRACTL_END;
SF_ConsistencyCheck(dwStubFlags);
#ifdef _DEBUG
if (g_pConfig->ShouldBreakOnInteropStubSetup(pSigDesc->m_pDebugName))
CONSISTENCY_CHECK_MSGF(false, ("BreakOnInteropStubSetup: '%s' ", pSigDesc->m_pDebugName));
#endif // _DEBUG
Stub* pstub = NULL;
if (SF_IsCOMStub(dwStubFlags))
{
_ASSERTE(0 == nlType);
_ASSERTE(0 == nlFlags);
_ASSERTE(0 == unmgdCallConv);
}
else
{
_ASSERTE(nlType == nltAnsi || nlType == nltUnicode);
}
Module *pModule = pSigDesc->m_pModule;
//
// Set up signature walking objects.
//
MetaSig msig(pSigDesc->m_sig,
pModule,
&pSigDesc->m_typeContext);
if (SF_IsVarArgStub(dwStubFlags))
msig.SetTreatAsVarArg();
bool fThisCall = (unmgdCallConv == pmCallConvThiscall);
pss->SetLastError(nlFlags & nlfLastError);
// This has been in the product since forward P/Invoke via delegates was
// introduced. It's wrong, but please keep it for backward compatibility.
if (SF_IsDelegateStub(dwStubFlags))
pss->SetLastError(TRUE);
pss->BeginEmit(dwStubFlags);
if (-1 != iLCIDArg)
{
// LCID is not supported on WinRT
_ASSERTE(!SF_IsWinRTStub(dwStubFlags));
// The code to handle the LCID will call MarshalLCID before calling MarshalArgument
// on the argument the LCID should go after. So we just bump up the index here.
iLCIDArg++;
}
int numArgs = msig.NumFixedArgs();
// thiscall must have at least one parameter (the "this")
if (fThisCall && numArgs == 0)
COMPlusThrow(kMarshalDirectiveException, IDS_EE_NDIRECT_BADNATL_THISCALL);
//
// Now, emit the IL.
//
int argOffset = 0;
MarshalInfo::MarshalType marshalType = (MarshalInfo::MarshalType) 0xcccccccc;
//
// Marshal the return value.
//
UINT nativeStackSize = (SF_IsCOMStub(dwStubFlags) ? sizeof(SLOT) : 0);
bool fHasCopyCtorArgs = false;
bool fStubNeedsCOM = SF_IsCOMStub(dwStubFlags);
// Normally we would like this to be false so that we use the correct signature
// in the IL_STUB, (i.e if it returns a value class then the signature will use that)
// When this bool is true we change the return type to void and explicitly add a
// return buffer argument as the first argument.
BOOL fMarshalReturnValueFirst = false;
// We can only change fMarshalReturnValueFirst to true when we are NOT doing HRESULT-swapping!
//
if (!SF_IsHRESULTSwapping(dwStubFlags))
{
#if defined(_TARGET_X86_) || defined(_TARGET_ARM_)
// JIT32 has problems in generating code for pinvoke ILStubs which do a return in return buffer.
// Therefore instead we change the signature of calli to return void and make the return buffer as first
// argument. This matches the ABI i.e. return buffer is passed as first arg. So native target will get the
// return buffer in correct register.
// The return structure secret arg comes first, however byvalue return is processed at
// the end because it could be the HRESULT-swapped argument which always comes last.
#ifdef UNIX_X86_ABI
// For functions with value type class, managed and unmanaged calling convention differ
fMarshalReturnValueFirst = HasRetBuffArgUnmanagedFixup(&msig);
#else // UNIX_X86_ABI
fMarshalReturnValueFirst = HasRetBuffArg(&msig);
#endif // UNIX_X86_ABI
#endif // defined(_TARGET_X86_) || defined(_TARGET_ARM_)
}
if (fMarshalReturnValueFirst)
{
marshalType = DoMarshalReturnValue(msig,
pParamTokenArray,
nlType,
nlFlags,
0,
pss,
fThisCall,
argOffset,
dwStubFlags,
pMD,
nativeStackSize,
fStubNeedsCOM,
0
DEBUG_ARG(pSigDesc->m_pDebugName)
DEBUG_ARG(pSigDesc->m_pDebugClassName)
);
if (marshalType == MarshalInfo::MARSHAL_TYPE_DATE ||
marshalType == MarshalInfo::MARSHAL_TYPE_CURRENCY ||
marshalType == MarshalInfo::MARSHAL_TYPE_ARRAYWITHOFFSET ||
marshalType == MarshalInfo::MARSHAL_TYPE_HANDLEREF ||
marshalType == MarshalInfo::MARSHAL_TYPE_ARGITERATOR
#ifdef FEATURE_COMINTEROP
|| marshalType == MarshalInfo::MARSHAL_TYPE_OLECOLOR
#endif // FEATURE_COMINTEROP
)
{
// These are special non-blittable types returned by-ref in managed,
// but marshaled as primitive values returned by-value in unmanaged.
}
else
{
// This is an ordinary value type - see if it is returned by-ref.
MethodTable *pRetMT = msig.GetRetTypeHandleThrowing().AsMethodTable();
if (IsUnmanagedValueTypeReturnedByRef(pRetMT->GetNativeSize()))
{
nativeStackSize += sizeof(LPVOID);
}
}
}
//
// Marshal the arguments
//
MarshalInfo::MarshalScenario ms;
#ifdef FEATURE_COMINTEROP
if (SF_IsCOMStub(dwStubFlags))
{
if (SF_IsWinRTStub(dwStubFlags))
ms = MarshalInfo::MARSHAL_SCENARIO_WINRT;
else
ms = MarshalInfo::MARSHAL_SCENARIO_COMINTEROP;
}
else
#endif // FEATURE_COMINTEROP
{
ms = MarshalInfo::MARSHAL_SCENARIO_NDIRECT;
}
// Build up marshaling information for each of the method's parameters
SIZE_T cbParamMarshalInfo;
if (!ClrSafeInt<SIZE_T>::multiply(sizeof(MarshalInfo), numArgs, cbParamMarshalInfo))
{
COMPlusThrowHR(COR_E_OVERFLOW);
}
NewArrayHolder<BYTE> pbParamMarshalInfo(new BYTE[cbParamMarshalInfo]);
MarshalInfo *pParamMarshalInfo = reinterpret_cast<MarshalInfo *>(pbParamMarshalInfo.GetValue());
MetaSig paramInfoMSig(msig);
for (int i = 0; i < numArgs; ++i)
{
paramInfoMSig.NextArg();
new(&(pParamMarshalInfo[i])) MarshalInfo(paramInfoMSig.GetModule(),
paramInfoMSig.GetArgProps(),
paramInfoMSig.GetSigTypeContext(),
pParamTokenArray[i + 1],
ms,
nlType,
nlFlags,
TRUE,
i + 1,
numArgs,
SF_IsBestFit(dwStubFlags),
SF_IsThrowOnUnmappableChar(dwStubFlags),
TRUE,
pMD,
TRUE
DEBUG_ARG(pSigDesc->m_pDebugName)
DEBUG_ARG(pSigDesc->m_pDebugClassName)
DEBUG_ARG(i + 1));
}
#ifdef FEATURE_COMINTEROP
// Check to see if we need to inject any additional hidden parameters
DWORD cHiddenNativeParameters;
NewArrayHolder<HiddenParameterInfo> pHiddenNativeParameters;
CheckForHiddenParameters(numArgs, pParamMarshalInfo, &cHiddenNativeParameters, &pHiddenNativeParameters);
// Hidden parameters and LCID do not mix
_ASSERTE(!(cHiddenNativeParameters > 0 && iLCIDArg != -1));
#endif // FEATURE_COMINTEROP
// Marshal the parameters
int argidx = 1;
int nativeArgIndex = 0;
while (argidx <= numArgs)
{
#ifdef FEATURE_COMINTEROP
HiddenParameterInfo *pHiddenParameter;
// Check to see if we need to inject a hidden parameter
if (IsHiddenParameter(nativeArgIndex, cHiddenNativeParameters, pHiddenNativeParameters, &pHiddenParameter))
{
pss->MarshalHiddenLengthArgument(pHiddenParameter->pManagedParam, FALSE);
nativeStackSize += pHiddenParameter->pManagedParam->GetHiddenLengthParamStackSize();
if (SF_IsReverseStub(dwStubFlags))
{
++argOffset;
}
}
else
#endif // FEATURE_COMINTEROP
{
//
// Check to see if this is the parameter after which we need to insert the LCID.
//
if (argidx == iLCIDArg)
{
pss->MarshalLCID(argidx);
nativeStackSize += sizeof(LPVOID);
if (SF_IsReverseStub(dwStubFlags))
argOffset++;
}
msig.NextArg();
MarshalInfo &info = pParamMarshalInfo[argidx - 1];
#ifdef FEATURE_COMINTEROP
// For the hidden-length array, length parameters must occur before the parameter containing the array pointer
_ASSERTE(info.GetMarshalType() != MarshalInfo::MARSHAL_TYPE_HIDDENLENGTHARRAY || nativeArgIndex > info.HiddenLengthParamIndex());
#endif // FEATURE_COMINTEROP
pss->MarshalArgument(&info, argOffset, GetStackOffsetFromStackSize(nativeStackSize, fThisCall));
nativeStackSize += info.GetNativeArgSize();
fStubNeedsCOM |= info.MarshalerRequiresCOM();
if (fThisCall && argidx == 1)
{
// make sure that the first parameter is enregisterable
if (info.GetNativeArgSize() > sizeof(SLOT))
COMPlusThrow(kMarshalDirectiveException, IDS_EE_NDIRECT_BADNATL_THISCALL);
}
argidx++;
}
++nativeArgIndex;
}
// Check to see if this is the parameter after which we need to insert the LCID.
if (argidx == iLCIDArg)
{
pss->MarshalLCID(argidx);
nativeStackSize += sizeof(LPVOID);
if (SF_IsReverseStub(dwStubFlags))
argOffset++;
}
if (!fMarshalReturnValueFirst)
{
// This could be a HRESULT-swapped argument so it must come last.
marshalType = DoMarshalReturnValue(msig,
pParamTokenArray,
nlType,
nlFlags,
argidx,
pss,
fThisCall,
argOffset,
dwStubFlags,
pMD,
nativeStackSize,
fStubNeedsCOM,
nativeArgIndex
DEBUG_ARG(pSigDesc->m_pDebugName)
DEBUG_ARG(pSigDesc->m_pDebugClassName)
);
// If the return value is a SafeHandle or CriticalHandle, mark the stub method.
// Interop methods that use this stub will have an implicit reliability contract
// (see code:TAStackCrawlCallBack).
if (!SF_IsHRESULTSwapping(dwStubFlags))
{
if (marshalType == MarshalInfo::MARSHAL_TYPE_SAFEHANDLE ||
marshalType == MarshalInfo::MARSHAL_TYPE_CRITICALHANDLE)
{
if (pMD->IsDynamicMethod())
pMD->AsDynamicMethodDesc()->SetUnbreakable(true);
}
}
}
if (SF_IsHRESULTSwapping(dwStubFlags))
{
if (msig.GetReturnType() != ELEMENT_TYPE_VOID)
nativeStackSize += sizeof(LPVOID);
}
if (pMD->IsDynamicMethod())
{
// Set the native stack size to the IL stub MD. It is needed for alignment
// thunk generation on the Mac and stdcall name decoration on Windows.
// We do not store it directly in the interop MethodDesc here because due
// to sharing we come here only for the first call with given signature and
// the target MD may even be NULL.
#ifdef _TARGET_X86_
if (fThisCall)
{
_ASSERTE(nativeStackSize >= sizeof(SLOT));
nativeStackSize -= sizeof(SLOT);
}
#else // _TARGET_X86_
//
// The algorithm to compute nativeStackSize on the fly is x86-specific.
// Recompute the correct size for other platforms from the stub signature.
//
if (SF_IsForwardStub(dwStubFlags))
{
// It would be nice to compute the correct value for forward stubs too.
// The value is only used in MarshalNative::NumParamBytes right now,
// and changing what MarshalNative::NumParamBytes returns is
// a potential breaking change.
}
else
{
// native stack size is updated in code:ILStubState.SwapStubSignatures
}
#endif // _TARGET_X86_
if (!FitsInU2(nativeStackSize))
COMPlusThrow(kMarshalDirectiveException, IDS_EE_SIGTOOCOMPLEX);
DynamicMethodDesc *pDMD = pMD->AsDynamicMethodDesc();
pDMD->SetNativeStackArgSize(static_cast<WORD>(nativeStackSize));
pDMD->SetHasCopyCtorArgs(fHasCopyCtorArgs);
pDMD->SetStubNeedsCOMStarted(fStubNeedsCOM);
}
// FinishEmit needs to know the native stack arg size so we call it after the number
// has been set in the stub MD (code:DynamicMethodDesc.SetNativeStackArgSize)
pss->FinishEmit(pMD);
}
class NDirectStubHashBlob : public ILStubHashBlobBase
{
public:
Module* m_pModule;
WORD m_unmgdCallConv;
BYTE m_nlType; // C_ASSERTS are in NDirect::CreateHashBlob
BYTE m_nlFlags;
DWORD m_StubFlags;
INT32 m_iLCIDArg;
INT32 m_nParams;
BYTE m_rgbSigAndParamData[1];
// (dwParamAttr, cbNativeType) // length: number of parameters
// NativeTypeBlob // length: number of parameters
// BYTE m_rgbSigData[]; // length: determined by sig walk
};
// For better performance and less memory fragmentation,
// I'm using structure here to avoid allocating 3 different arrays.
struct ParamInfo
{
DWORD dwParamAttr;
ULONG cbNativeType;
PCCOR_SIGNATURE pvNativeType;
};
ILStubHashBlob* NDirect::CreateHashBlob(NDirectStubParameters* pParams)
{
STANDARD_VM_CONTRACT;
NDirectStubHashBlob* pBlob;
IMDInternalImport* pInternalImport = pParams->m_pModule->GetMDImport();
CQuickBytes paramInfoBytes;
paramInfoBytes.AllocThrows(sizeof(ParamInfo)*pParams->m_nParamTokens);
ParamInfo *paramInfos = (ParamInfo *)paramInfoBytes.Ptr();
::ZeroMemory(paramInfos, sizeof(ParamInfo) * pParams->m_nParamTokens);
size_t cbNativeTypeTotal = 0;
//
// Collect information for function parameters
//
for (int idx = 0; idx < pParams->m_nParamTokens; idx++)
{
mdParamDef token = pParams->m_pParamTokenArray[idx];
if (TypeFromToken(token) == mdtParamDef && mdParamDefNil != token)
{
USHORT usSequence_Ignore; // We don't need usSequence in the hash as the param array is already sorted
LPCSTR szParamName_Ignore;
IfFailThrow(pInternalImport->GetParamDefProps(token, &usSequence_Ignore, ¶mInfos[idx].dwParamAttr, &szParamName_Ignore));
if (paramInfos[idx].dwParamAttr & pdHasFieldMarshal)
{
IfFailThrow(pInternalImport->GetFieldMarshal(token, ¶mInfos[idx].pvNativeType, ¶mInfos[idx].cbNativeType));
cbNativeTypeTotal += paramInfos[idx].cbNativeType;
}
}
}
SigPointer sigPtr = pParams->m_sig.CreateSigPointer();
// note that ConvertToInternalSignature also resolves generics so different instantiations will get different
// hash blobs for methods that have generic parameters in their signature
SigBuilder sigBuilder;
sigPtr.ConvertToInternalSignature(pParams->m_pModule, pParams->m_pTypeContext, &sigBuilder, /* bSkipCustomModifier = */ FALSE);
DWORD cbSig;
PVOID pSig = sigBuilder.GetSignature(&cbSig);
//
// Build hash blob for IL stub sharing
//
S_SIZE_T cbSizeOfBlob = S_SIZE_T(offsetof(NDirectStubHashBlob, m_rgbSigAndParamData)) +
S_SIZE_T(sizeof(ULONG)) * S_SIZE_T(pParams->m_nParamTokens) + // Parameter attributes
S_SIZE_T(sizeof(DWORD)) * S_SIZE_T(pParams->m_nParamTokens) + // Native type blob size
S_SIZE_T(cbNativeTypeTotal) + // Native type blob data
S_SIZE_T(cbSig); // Signature
if (cbSizeOfBlob.IsOverflow())
COMPlusThrowHR(COR_E_OVERFLOW);
static_assert_no_msg(nltMaxValue <= 0xFF);
static_assert_no_msg(nlfMaxValue <= 0xFF);
static_assert_no_msg(pmMaxValue <= 0xFFFF);
NewArrayHolder<BYTE> pBytes = new BYTE[cbSizeOfBlob.Value()];
// zero out the hash bytes to ensure all bit fields are deterministically set
ZeroMemory(pBytes, cbSizeOfBlob.Value());
pBlob = (NDirectStubHashBlob*)(BYTE*)pBytes;
pBlob->m_pModule = NULL;
if (SF_IsNGENedStub(pParams->m_dwStubFlags))
{
// don't share across modules if we are ngening the stub
pBlob->m_pModule = pParams->m_pModule;
}
pBlob->m_cbSizeOfBlob = cbSizeOfBlob.Value();
pBlob->m_unmgdCallConv = static_cast<WORD>(pParams->m_unmgdCallConv);
pBlob->m_nlType = static_cast<BYTE>(pParams->m_nlType);
pBlob->m_nlFlags = static_cast<BYTE>(pParams->m_nlFlags & ~nlfNoMangle); // this flag does not affect the stub
pBlob->m_iLCIDArg = pParams->m_iLCIDArg;
pBlob->m_StubFlags = pParams->m_dwStubFlags;
pBlob->m_nParams = pParams->m_nParamTokens;
BYTE* pBlobParams = &pBlob->m_rgbSigAndParamData[0];
//
// Write (dwParamAttr, cbNativeType) for parameters
//
// Note that these need to be aligned and it is why they are written before the byte blobs
// I'm putting asserts here so that it will assert even in non-IA64 platforms to catch bugs
//
_ASSERTE((DWORD_PTR)pBlobParams % sizeof(DWORD) == 0);
_ASSERTE(sizeof(DWORD) == sizeof(ULONG));
for (int i = 0; i < pParams->m_nParamTokens; ++i)
{
// We only care about In/Out/HasFieldMarshal
// Other attr are about optional/default values which are not used in marshalling,
// but only used in compilers
*((DWORD *)pBlobParams) = paramInfos[i].dwParamAttr & (pdIn | pdOut | pdHasFieldMarshal);
pBlobParams += sizeof(DWORD);
*((ULONG *)pBlobParams) = paramInfos[i].cbNativeType;
pBlobParams += sizeof(ULONG);
}
//
// Write native type blob for parameters
//
for (int i = 0; i < pParams->m_nParamTokens; ++i)
{
memcpy(pBlobParams, paramInfos[i].pvNativeType, paramInfos[i].cbNativeType);
pBlobParams += paramInfos[i].cbNativeType;
}
//
// Copy signature
//
memcpy(pBlobParams, pSig, cbSig);
// Verify that we indeed have reached the end
_ASSERTE(pBlobParams + cbSig == (BYTE *)pBlob + cbSizeOfBlob.Value());
pBytes.SuppressRelease();
return (ILStubHashBlob*)pBlob;
}
// static inline
ILStubCache* NDirect::GetILStubCache(NDirectStubParameters* pParams)
{
CONTRACTL
{
THROWS;
GC_NOTRIGGER;
MODE_ANY;
}
CONTRACTL_END;
// Use the m_pLoaderModule instead of m_pModule
// They could be different for methods on generic types.
return pParams->m_pLoaderModule->GetILStubCache();
}
// static
MethodDesc* NDirect::GetStubMethodDesc(
MethodDesc *pTargetMD,
NDirectStubParameters* pParams,
ILStubHashBlob* pHashParams,
AllocMemTracker* pamTracker,
bool& bILStubCreator,
MethodDesc* pLastMD)
{
CONTRACT(MethodDesc*)
{
STANDARD_VM_CHECK;
PRECONDITION(CheckPointer(pParams));
PRECONDITION(!pParams->m_sig.IsEmpty());
PRECONDITION(CheckPointer(pParams->m_pModule));
PRECONDITION(CheckPointer(pTargetMD, NULL_OK));
POSTCONDITION(CheckPointer(RETVAL));
}
CONTRACT_END;
MethodDesc* pMD;
ILStubCache* pCache = NDirect::GetILStubCache(pParams);
pMD = pCache->GetStubMethodDesc(pTargetMD,
pHashParams,
pParams->m_dwStubFlags,
pParams->m_pModule,
pParams->m_sig.GetRawSig(),
pParams->m_sig.GetRawSigLen(),
pamTracker,
bILStubCreator,
pLastMD);
RETURN pMD;
}
// static
void NDirect::RemoveILStubCacheEntry(NDirectStubParameters* pParams, ILStubHashBlob* pHashParams)
{
CONTRACTL
{
STANDARD_VM_CHECK;
PRECONDITION(CheckPointer(pParams));
PRECONDITION(CheckPointer(pHashParams));
PRECONDITION(!pParams->m_sig.IsEmpty());
PRECONDITION(CheckPointer(pParams->m_pModule));
}
CONTRACTL_END;
LOG((LF_STUBS, LL_INFO1000, "Exception happened when generating IL of stub clr!CreateInteropILStub StubMD: %p, HashBlob: %p \n", pParams, pHashParams));
ILStubCache* pCache = NDirect::GetILStubCache(pParams);
pCache->DeleteEntry(pHashParams);
}
// static
void NDirect::AddMethodDescChunkWithLockTaken(NDirectStubParameters* pParams, MethodDesc *pMD)
{
CONTRACTL
{
STANDARD_VM_CHECK;
PRECONDITION(CheckPointer(pParams));
PRECONDITION(!pParams->m_sig.IsEmpty());
PRECONDITION(CheckPointer(pParams->m_pModule));
}
CONTRACTL_END;
ILStubCache* pCache = NDirect::GetILStubCache(pParams);
pCache->AddMethodDescChunkWithLockTaken(pMD);
}
//
// Additional factorization of CreateNDirectStub. This hoists all the metadata accesses
// into one location so that we can leave CreateNDirectStubWorker to just generate the
// IL. This allows us to cache a stub based on the inputs to CreateNDirectStubWorker
// instead of having to generate the IL first before doing the caching.
//
void CreateNDirectStubAccessMetadata(StubSigDesc* pSigDesc, // IN
CorPinvokeMap unmgdCallConv, // IN
DWORD* pdwStubFlags, // IN/OUT
int* piLCIDArg, // OUT
int* pNumArgs // OUT
)
{
STANDARD_VM_CONTRACT;
if (SF_IsCOMStub(*pdwStubFlags))
{
_ASSERTE(0 == unmgdCallConv);
}
else
{
if (unmgdCallConv != pmCallConvStdcall &&
unmgdCallConv != pmCallConvCdecl &&
unmgdCallConv != pmCallConvThiscall)
{
COMPlusThrow(kTypeLoadException, IDS_INVALID_PINVOKE_CALLCONV);
}
}
#ifdef FEATURE_COMINTEROP
if (SF_IsDelegateStub(*pdwStubFlags))
{
_ASSERTE(!SF_IsWinRTStub(*pdwStubFlags));
if (pSigDesc->m_pMD->GetMethodTable()->IsProjectedFromWinRT())
{
// We do not allow P/Invoking via WinRT delegates to better segregate WinRT
// from classic interop scenarios.
COMPlusThrow(kMarshalDirectiveException, IDS_EE_DELEGATEPINVOKE_WINRT);
}
}
#endif // FEATURE_COMINTEROP
MetaSig msig(pSigDesc->m_sig,
pSigDesc->m_pModule,
&pSigDesc->m_typeContext);
if (SF_IsVarArgStub(*pdwStubFlags))
msig.SetTreatAsVarArg();
(*pNumArgs) = msig.NumFixedArgs();
IMDInternalImport* pInternalImport = pSigDesc->m_pModule->GetMDImport();
_ASSERTE(!SF_IsHRESULTSwapping(*pdwStubFlags));
mdMethodDef md = pSigDesc->m_tkMethodDef;
if (md != mdMethodDefNil)
{
DWORD dwDescrOffset;
DWORD dwImplFlags;
IfFailThrow(pInternalImport->GetMethodImplProps(
md,
&dwDescrOffset,
&dwImplFlags));
#ifdef FEATURE_COMINTEROP
if (SF_IsWinRTStub(*pdwStubFlags))
{
// All WinRT methods do HRESULT swapping
if (IsMiPreserveSig(dwImplFlags))
{
COMPlusThrow(kMarshalDirectiveException, IDS_EE_PRESERVESIG_WINRT);
}
(*pdwStubFlags) |= NDIRECTSTUB_FL_DOHRESULTSWAPPING;
}
else
#endif // FEATURE_COMINTEROP
if (SF_IsReverseStub(*pdwStubFlags))
{
// only COM-to-CLR call supports hresult swapping in the reverse direction
if (SF_IsCOMStub(*pdwStubFlags) && !IsMiPreserveSig(dwImplFlags))
{
(*pdwStubFlags) |= NDIRECTSTUB_FL_DOHRESULTSWAPPING;
}
}
else
{
// fwd pinvoke, fwd com interop support hresult swapping.
// delegate to an unmanaged method does not.
if (!IsMiPreserveSig(dwImplFlags) && !SF_IsDelegateStub(*pdwStubFlags))
{
(*pdwStubFlags) |= NDIRECTSTUB_FL_DOHRESULTSWAPPING;
}
}
}
if (pSigDesc->m_pMD != NULL)
{
(*piLCIDArg) = GetLCIDParameterIndex(pSigDesc->m_pMD);
}
else
{
(*piLCIDArg) = -1;
}
// Check to see if we need to do LCID conversion.
if ((*piLCIDArg) != -1 && (*piLCIDArg) > (*pNumArgs))
{
COMPlusThrow(kIndexOutOfRangeException, IDS_EE_INVALIDLCIDPARAM);
}
if (SF_IsCOMStub(*pdwStubFlags) && !SF_IsWinRTStaticStub(*pdwStubFlags))
{
CONSISTENCY_CHECK(msig.HasThis());
}
else
{
if (msig.HasThis() && !SF_IsDelegateStub(*pdwStubFlags))
{
COMPlusThrow(kInvalidProgramException, VLDTR_E_FMD_PINVOKENOTSTATIC);
}
}
}
void NDirect::PopulateNDirectMethodDesc(NDirectMethodDesc* pNMD, PInvokeStaticSigInfo* pSigInfo, BOOL throwOnError /*= TRUE*/)
{
if (pNMD->IsSynchronized() && throwOnError)
COMPlusThrow(kTypeLoadException, IDS_EE_NOSYNCHRONIZED);
WORD ndirectflags = 0;
if (pNMD->MethodDesc::IsVarArg())
ndirectflags |= NDirectMethodDesc::kVarArgs;
LPCUTF8 szLibName = NULL, szEntryPointName = NULL;
new (pSigInfo) PInvokeStaticSigInfo(pNMD, &szLibName, &szEntryPointName,
(throwOnError ? PInvokeStaticSigInfo::THROW_ON_ERROR : PInvokeStaticSigInfo::NO_THROW_ON_ERROR));
if (pSigInfo->GetCharSet() == nltAnsi)
ndirectflags |= NDirectMethodDesc::kNativeAnsi;
CorNativeLinkFlags linkflags = pSigInfo->GetLinkFlags();
if (linkflags & nlfLastError)
ndirectflags |= NDirectMethodDesc::kLastError;
if (linkflags & nlfNoMangle)
ndirectflags |= NDirectMethodDesc::kNativeNoMangle;
CorPinvokeMap callConv = pSigInfo->GetCallConv();
if (callConv == pmCallConvStdcall)
ndirectflags |= NDirectMethodDesc::kStdCall;
if (callConv == pmCallConvThiscall)
ndirectflags |= NDirectMethodDesc::kThisCall;
if (pNMD->GetLoaderModule()->IsSystem() && strcmp(szLibName, "QCall") == 0)
{
ndirectflags |= NDirectMethodDesc::kIsQCall;
}
else
{
EnsureWritablePages(&pNMD->ndirect);
pNMD->ndirect.m_pszLibName.SetValueMaybeNull(szLibName);
pNMD->ndirect.m_pszEntrypointName.SetValueMaybeNull(szEntryPointName);
}
#ifdef _TARGET_X86_
if (ndirectflags & NDirectMethodDesc::kStdCall)
{
// Compute the kStdCallWithRetBuf flag which is needed at link time for entry point mangling.
MetaSig msig(pNMD);
ArgIterator argit(&msig);
if (argit.HasRetBuffArg())
{
MethodTable *pRetMT = msig.GetRetTypeHandleThrowing().AsMethodTable();
if (IsUnmanagedValueTypeReturnedByRef(pRetMT->GetNativeSize()))
{
ndirectflags |= NDirectMethodDesc::kStdCallWithRetBuf;
}
}
}
#endif // _TARGET_X86_
// Call this exactly ONCE per thread. Do not publish incomplete prestub flags
// or you will introduce a race condition.
pNMD->InterlockedSetNDirectFlags(ndirectflags);
}
#ifdef FEATURE_COMINTEROP
// Find the MethodDesc of the predefined IL stub method by either
// 1) looking at redirected adapter interfaces, OR
// 2) looking at special attributes for the specific interop scenario (specified by dwStubFlags).
// Currently only ManagedToNativeComInteropStubAttribute is supported.
// It returns NULL if no such attribute(s) can be found.
// But if the attribute is found and is invalid, or something went wrong in the looking up
// process, an exception will be thrown. If everything goes well, you'll get the MethodDesc
// of the stub method
HRESULT FindPredefinedILStubMethod(MethodDesc *pTargetMD, DWORD dwStubFlags, MethodDesc **ppRetStubMD)
{
CONTRACT(HRESULT)
{
THROWS;
GC_TRIGGERS;
MODE_ANY;
PRECONDITION(CheckPointer(pTargetMD));
PRECONDITION(CheckPointer(ppRetStubMD));
PRECONDITION(*ppRetStubMD == NULL);
}
CONTRACT_END;
HRESULT hr;
MethodTable *pTargetMT = pTargetMD->GetMethodTable();
// Check if this is a redirected interface - we have static stubs in mscorlib for those.
if (SF_IsForwardCOMStub(dwStubFlags) && pTargetMT->IsInterface())
{
// Redirect generic redirected interfaces to the corresponding adapter methods in mscorlib
if (pTargetMT->HasInstantiation())
{
MethodDesc *pAdapterMD = WinRTInterfaceRedirector::GetStubMethodForRedirectedInterfaceMethod(pTargetMD, TypeHandle::Interop_ManagedToNative);
if (pAdapterMD != NULL)
{
*ppRetStubMD = pAdapterMD;
return S_OK;
}
}
}
//
// Find out if we have the attribute
//
const void *pBytes;
ULONG cbBytes;
// Support v-table forward classic COM interop calls only
if (SF_IsCOMStub(dwStubFlags) && SF_IsForwardStub(dwStubFlags) && !SF_IsWinRTStub(dwStubFlags))
{
if (pTargetMT->HasInstantiation())
{
// ManagedToNativeComInteropStubAttribute is not supported with generics
return E_FAIL;
}
if (pTargetMD->IsFCall())
{
// ManagedToNativeComInteropStubAttribute is not supported on FCalls (i.e. methods on legacy
// interfaces forwarded to CustomMarshalers.dll such as IEnumerable::GetEnumerator)
return E_FAIL;
}
_ASSERTE(pTargetMD->IsComPlusCall());
if (pTargetMD->IsInterface())
{
_ASSERTE(!pTargetMD->GetAssembly()->IsWinMD());
hr = pTargetMD->GetMDImport()->GetCustomAttributeByName(
pTargetMD->GetMemberDef(),
FORWARD_INTEROP_STUB_METHOD_TYPE,
&pBytes,
&cbBytes);
if (FAILED(hr))
RETURN hr;
// GetCustomAttributeByName returns S_FALSE when it cannot find the attribute but nothing fails...
// Translate that to E_FAIL
else if (hr == S_FALSE)
RETURN E_FAIL;
}
else
{
// We are dealing with the class, use the interface MD instead
// After second thought I believe we don't need to check the class MD.
// We can think stubs as part of public interface, and if the interface is public,
// the stubs should also be accessible
MethodDesc *pInterfaceMD = pTargetMD->GetInterfaceMD();
if (pInterfaceMD)
{
hr = FindPredefinedILStubMethod(pInterfaceMD, dwStubFlags, ppRetStubMD);
RETURN hr;
}
else
RETURN E_FAIL;
}
}
else
RETURN E_FAIL;
//
// Parse the attribute
//
CustomAttributeParser parser(pBytes, cbBytes);
IfFailRet(parser.SkipProlog());
LPCUTF8 pTypeName;
ULONG cbTypeName;
IfFailRet(parser.GetNonEmptyString(&pTypeName, &cbTypeName));
LPCUTF8 pMethodName;
ULONG cbMethodName;
IfFailRet(parser.GetNonEmptyString(&pMethodName, &cbMethodName));
StackSString typeName(SString::Utf8, pTypeName, cbTypeName);
StackSString methodName(SString::Utf8, pMethodName, cbMethodName);
//
// Retrieve the type
//
TypeHandle stubClassType;
stubClassType = TypeName::GetTypeUsingCASearchRules(typeName.GetUnicode(), pTargetMT->GetAssembly());
MethodTable *pStubClassMT = stubClassType.AsMethodTable();
StackSString stubClassName;
pStubClassMT->_GetFullyQualifiedNameForClassNestedAware(stubClassName);
StackSString targetInterfaceName;
pTargetMT->_GetFullyQualifiedNameForClassNestedAware(targetInterfaceName);
// Restrict to same assembly only to reduce test cost
if (stubClassType.GetAssembly() != pTargetMT->GetAssembly())
{
COMPlusThrow(
kArgumentException,
IDS_EE_INTEROP_STUB_CA_MUST_BE_WITHIN_SAME_ASSEMBLY,
stubClassName.GetUnicode(),
targetInterfaceName.GetUnicode()
);
}
if (stubClassType.HasInstantiation())
{
COMPlusThrow(
kArgumentException,
IDS_EE_INTEROP_STUB_CA_STUB_CLASS_MUST_NOT_BE_GENERIC,
stubClassName.GetUnicode()
);
}
if (stubClassType.IsInterface())
{
COMPlusThrow(
kArgumentException,
IDS_EE_INTEROP_STUB_CA_STUB_CLASS_MUST_NOT_BE_INTERFACE,
stubClassName.GetUnicode()
);
}
//
// Locate the MethodDesc for the stub method
//
MethodDesc *pStubMD = NULL;
{
PCCOR_SIGNATURE pTargetSig = NULL;
DWORD pcTargetSig = 0;
SigTypeContext typeContext; // NO generics supported
pTargetMD->GetSig(&pTargetSig, &pcTargetSig);
MetaSig msig(pTargetSig,
pcTargetSig,
pTargetMD->GetModule(),
&typeContext);
_ASSERTE(msig.HasThis());
SigBuilder stubSigBuilder;
//
// Append calling Convention, NumOfArgs + 1,
//
stubSigBuilder.AppendByte(msig.GetCallingConvention() & ~IMAGE_CEE_CS_CALLCONV_HASTHIS);
stubSigBuilder.AppendData(msig.NumFixedArgs() + 1);
//
// Append return type
//
SigPointer pReturn = msig.GetReturnProps();
LPBYTE pReturnTypeBegin = (LPBYTE)pReturn.GetPtr();
IfFailThrow(pReturn.SkipExactlyOne());
LPBYTE pReturnTypeEnd = (LPBYTE)pReturn.GetPtr();
stubSigBuilder.AppendBlob(pReturnTypeBegin, pReturnTypeEnd - pReturnTypeBegin);
//
// Append 'this'
//
stubSigBuilder.AppendElementType(ELEMENT_TYPE_CLASS);
stubSigBuilder.AppendToken(pTargetMT->GetCl());
//
// Copy rest of the arguments
//
if (msig.NextArg() != ELEMENT_TYPE_END)
{
SigPointer pFirstArg = msig.GetArgProps();
LPBYTE pArgBegin = (LPBYTE) pFirstArg.GetPtr();
LPBYTE pArgEnd = (LPBYTE) pTargetSig + pcTargetSig;
stubSigBuilder.AppendBlob(pArgBegin, pArgEnd - pArgBegin);
}
//
// Allocate new memory and copy over
//
DWORD pcStubSig = 0;
PCCOR_SIGNATURE pStubSig = (PCCOR_SIGNATURE) stubSigBuilder.GetSignature(&pcStubSig);
//
// Find method using name + signature
//
StackScratchBuffer buffer;
LPCUTF8 szMethodNameUTF8 = methodName.GetUTF8(buffer);
pStubMD = MemberLoader::FindMethod(stubClassType.GetMethodTable(),
szMethodNameUTF8,
pStubSig,
pcStubSig,
pTargetMT->GetModule());
if (pStubMD == NULL)
{
CQuickBytes qbSig;
PrettyPrintSig(
pStubSig,
pcStubSig,
szMethodNameUTF8,
&qbSig,
pTargetMD->GetMDImport(),
NULL);
// Unfortunately the PrettyPrintSig doesn't print 'static' when the function is static
// so we need to append 'static' here. No need to localize
SString signature(SString::Utf8, (LPCUTF8)"static ");
signature.AppendUTF8((LPCUTF8) qbSig.Ptr());
COMPlusThrow(
kMissingMethodException,
IDS_EE_INTEROP_STUB_CA_STUB_METHOD_MISSING,
signature.GetUnicode(),
stubClassName.GetUnicode()
);
}
}
//
// Check the Stub MD
//
// Verify that the target interop method can call the stub method
_ASSERTE(pTargetMD != NULL);
StaticAccessCheckContext accessContext(pTargetMD, pTargetMT);
if (!ClassLoader::CanAccess(
&accessContext,
pStubClassMT,
stubClassType.GetAssembly(),
pStubMD->GetAttrs(),
pStubMD,
NULL))
{
StackSString interopMethodName(SString::Utf8, pTargetMD->GetName());
COMPlusThrow(
kMethodAccessException,
IDS_EE_INTEROP_STUB_CA_NO_ACCESS_TO_STUB_METHOD,
interopMethodName.GetUnicode(),
methodName.GetUnicode()
);
}
// The FindMethod call will make sure that it is static by matching signature.
// So there is no need to check and throw
_ASSERTE(pStubMD->IsStatic());
*ppRetStubMD = pStubMD;
RETURN S_OK;
}
#endif // FEATURE_COMINTEROP
MethodDesc* CreateInteropILStub(
ILStubState* pss,
StubSigDesc* pSigDesc,
CorNativeLinkType nlType,
CorNativeLinkFlags nlFlags,
CorPinvokeMap unmgdCallConv,
DWORD dwStubFlags, // NDirectStubFlags
int nParamTokens,
mdParamDef* pParamTokenArray,
int iLCIDArg
)
{
CONTRACT(MethodDesc*)
{
STANDARD_VM_CHECK;
PRECONDITION(CheckPointer(pSigDesc));
POSTCONDITION(CheckPointer(RETVAL));
}
CONTRACT_END;
///////////////////////////////
//
// MethodDesc creation
//
///////////////////////////////
MethodDesc* pStubMD = NULL;
Module* pModule = pSigDesc->m_pModule;
Module* pLoaderModule = pSigDesc->m_pLoaderModule;
MethodDesc* pTargetMD = pSigDesc->m_pMD;
//
// pTargetMD may be null in the case of calli pinvoke
// and vararg pinvoke.
//
#ifdef FEATURE_COMINTEROP
//
// Try to locate predefined IL stub either defined in user code or hardcoded in CLR
// If there is one, use the pointed method as the stub.
// Skip pTargetMD == NULL case for reverse interop calls
//
if (pTargetMD && SUCCEEDED(FindPredefinedILStubMethod(pTargetMD, dwStubFlags, &pStubMD)))
{
#ifndef CROSSGEN_COMPILE
// We are about to execute method in pStubMD which could be in another module.
// Call EnsureActive before make the call
// This cannot be done during NGEN/PEVerify (in PASSIVE_DOMAIN) so I've moved it here
pStubMD->EnsureActive();
if (pStubMD->IsPreImplemented())
RestoreNGENedStub(pStubMD);
#endif
RETURN pStubMD;
}
#endif // FEATURE_COMINTEROP
// Otherwise, fall back to generating IL stub on-the-fly
NDirectStubParameters params(pSigDesc->m_sig,
&pSigDesc->m_typeContext,
pModule,
pLoaderModule,
nlType,
nlFlags,
unmgdCallConv,
dwStubFlags,
nParamTokens,
pParamTokenArray,
iLCIDArg
);
// The following two ILStubCreatorHelperHolder are to recover the status when an
// exception happen during the generation of the IL stubs. We need to free the
// memory allocated and restore the ILStubCache.
//
// The following block is logically divided into two phases. The first phase is
// CreateOrGet IL Stub phase which we take a domain level lock. The second phase
// is IL generation phase which we take a MethodDesc level lock. Taking two locks
// is mainly designed for performance.
//
// ilStubCreatorHelper contains an instance of AllocMemTracker which tracks the
// allocated memory during the creation of MethodDesc so that we are able to remove
// them when releasing the ILStubCreatorHelperHolder or destructing ILStubCreatorHelper
// When removing IL Stub from Cache, we have a constraint that only the thread which
// creates the stub can remove it. Otherwise, any thread hits cache and gets the stub will
// remove it from cache if OOM occurs
{
ILStubCreatorHelper ilStubCreatorHelper(pTargetMD, ¶ms);
// take the domain level lock
ListLockHolder pILStubLock(pLoaderModule->GetDomain()->GetILStubGenLock());
{
// The holder will free the allocated MethodDesc and restore the ILStubCache
// if exception happen.
ILStubCreatorHelperHolder pCreateOrGetStubHolder(&ilStubCreatorHelper);
pStubMD = pCreateOrGetStubHolder->GetStubMD();
///////////////////////////////
//
// IL generation
//
///////////////////////////////
{
// take the MethodDesc level locker
ListLockEntryHolder pEntry(ListLockEntry::Find(pILStubLock, pStubMD, "il stub gen lock"));
ListLockEntryLockHolder pEntryLock(pEntry, FALSE);
// We can release the holder for the first phase now
pCreateOrGetStubHolder.SuppressRelease();
{
// The holder will free the allocated MethodDesc and restore the ILStubCache
// if exception happen. The reason to get the holder again is to
ILStubCreatorHelperHolder pGenILHolder(&ilStubCreatorHelper);
if (!pEntryLock.DeadlockAwareAcquire())
{
// the IL generation is not recursive!
UNREACHABLE_MSG("unexpected deadlock in IL stub generation!");
}
if (SF_IsSharedStub(params.m_dwStubFlags))
{
// Assure that pStubMD we have now has not been destroyed by other threads
pGenILHolder->GetStubMethodDesc();
while (pStubMD != pGenILHolder->GetStubMD())
{
pStubMD = pGenILHolder->GetStubMD();
pEntry.Assign(ListLockEntry::Find(pILStubLock, pStubMD, "il stub gen lock"));
pEntryLock.Assign(pEntry, FALSE);
if (!pEntryLock.DeadlockAwareAcquire())
{
// the IL generation is not recursive!
UNREACHABLE_MSG("unexpected deadlock in IL stub generation!");
}
pGenILHolder->GetStubMethodDesc();
}
}
for (;;)
{
// We have the entry lock now, we can release the global lock
pILStubLock.Release();
if (pEntry->m_hrResultCode != S_FALSE)
{
// We came in to generate the IL but someone
// beat us so there's nothing to do
break;
}
ILStubResolver* pResolver = pStubMD->AsDynamicMethodDesc()->GetILStubResolver();
CONSISTENCY_CHECK((NULL == pResolver->GetStubMethodDesc()) || (pStubMD == pResolver->GetStubMethodDesc()));
if (pResolver->IsILGenerated())
{
// this stub already has its IL generated
break;
}
//
// Check that the stub signature and MethodDesc are compatible. The JIT
// interface functions depend on this.
//
{
SigPointer ptr = pSigDesc->m_sig.CreateSigPointer();
ULONG callConvInfo;
IfFailThrow(ptr.GetCallingConvInfo(&callConvInfo));
BOOL fSigIsStatic = !(callConvInfo & IMAGE_CEE_CS_CALLCONV_HASTHIS);
// CreateNDirectStubWorker will throw an exception for these cases.
BOOL fCanHaveThis = SF_IsDelegateStub(dwStubFlags) || SF_IsCOMStub(dwStubFlags);
if (fSigIsStatic || fCanHaveThis)
{
CONSISTENCY_CHECK(pStubMD->IsStatic() == (DWORD)fSigIsStatic);
}
}
{
ILStubGenHolder sgh(pResolver);
pResolver->SetStubMethodDesc(pStubMD);
pResolver->SetStubTargetMethodDesc(pTargetMD);
CreateNDirectStubWorker(pss,
pSigDesc,
nlType,
nlFlags,
unmgdCallConv,
dwStubFlags,
pStubMD,
pParamTokenArray,
iLCIDArg);
pResolver->SetTokenLookupMap(pss->GetTokenLookupMap());
pResolver->SetStubTargetMethodSig(
pss->GetStubTargetMethodSig(),
pss->GetStubTargetMethodSigLength());
// we successfully generated the IL stub
sgh.SuppressRelease();
}
pEntry->m_hrResultCode = S_OK;
break;
}
// Link the MethodDesc onto the method table with the lock taken
NDirect::AddMethodDescChunkWithLockTaken(¶ms, pStubMD);
pGenILHolder.SuppressRelease();
}
}
}
ilStubCreatorHelper.SuppressRelease();
}
#if defined(_TARGET_X86_)
if (SF_IsForwardStub(dwStubFlags) && pTargetMD != NULL && !pTargetMD->IsVarArg())
{
// copy the stack arg byte count from the stub MD to the target MD - this number is computed
// during stub generation and is copied to all target MDs that share the stub
// (we don't set it for varargs - the number is call site specific)
// also copy the "takes parameters with copy constructors" flag which is needed to generate
// appropriate intercept stub
WORD cbStackArgSize = pStubMD->AsDynamicMethodDesc()->GetNativeStackArgSize();
BOOL fHasCopyCtorArgs = pStubMD->AsDynamicMethodDesc()->HasCopyCtorArgs();
if (pTargetMD->IsNDirect())
{
NDirectMethodDesc *pTargetNMD = (NDirectMethodDesc *)pTargetMD;
pTargetNMD->SetStackArgumentSize(cbStackArgSize, (CorPinvokeMap)0);
pTargetNMD->SetHasCopyCtorArgs(fHasCopyCtorArgs);
}
#ifdef FEATURE_COMINTEROP
else
{
if (SF_IsCOMStub(dwStubFlags))
{
ComPlusCallInfo *pComInfo = ComPlusCallInfo::FromMethodDesc(pTargetMD);
if (pComInfo != NULL)
{
pComInfo->SetStackArgumentSize(cbStackArgSize);
pComInfo->SetHasCopyCtorArgs(fHasCopyCtorArgs);
}
}
}
#endif // FEATURE_COMINTEROP
}
#endif // defined(_TARGET_X86_)
RETURN pStubMD;
}
MethodDesc* NDirect::CreateCLRToNativeILStub(
StubSigDesc* pSigDesc,
CorNativeLinkType nlType,
CorNativeLinkFlags nlFlags,
CorPinvokeMap unmgdCallConv,
DWORD dwStubFlags) // NDirectStubFlags
{
CONTRACT(MethodDesc*)
{
STANDARD_VM_CHECK;
PRECONDITION(CheckPointer(pSigDesc));
POSTCONDITION(CheckPointer(RETVAL));
}
CONTRACT_END;
int iLCIDArg = 0;
int numArgs = 0;
int numParamTokens = 0;
mdParamDef* pParamTokenArray = NULL;
CreateNDirectStubAccessMetadata(pSigDesc,
unmgdCallConv,
&dwStubFlags,
&iLCIDArg,
&numArgs);
Module *pModule = pSigDesc->m_pModule;
numParamTokens = numArgs + 1;
pParamTokenArray = (mdParamDef*)_alloca(numParamTokens * sizeof(mdParamDef));
CollateParamTokens(pModule->GetMDImport(), pSigDesc->m_tkMethodDef, numArgs, pParamTokenArray);
MethodDesc *pMD = pSigDesc->m_pMD;
NewHolder<ILStubState> pStubState;
#ifdef FEATURE_COMINTEROP
if (SF_IsCOMStub(dwStubFlags))
{
if (SF_IsReverseStub(dwStubFlags))
{
pStubState = new COMToCLR_ILStubState(pModule, pSigDesc->m_sig, &pSigDesc->m_typeContext, dwStubFlags, iLCIDArg, pMD);
}
else
{
pStubState = new CLRToCOM_ILStubState(pModule, pSigDesc->m_sig, &pSigDesc->m_typeContext, dwStubFlags, iLCIDArg, pMD);
}
}
else
#endif
{
pStubState = new PInvoke_ILStubState(pModule, pSigDesc->m_sig, &pSigDesc->m_typeContext, dwStubFlags, unmgdCallConv, iLCIDArg, pMD);
}
MethodDesc* pStubMD;
pStubMD = CreateInteropILStub(
pStubState,
pSigDesc,
nlType,
nlFlags,
unmgdCallConv,
dwStubFlags,
numParamTokens,
pParamTokenArray,
iLCIDArg);
RETURN pStubMD;
}
#ifdef FEATURE_COMINTEROP
MethodDesc* NDirect::CreateFieldAccessILStub(
PCCOR_SIGNATURE szMetaSig,
DWORD cbMetaSigSize,
Module* pModule,
mdFieldDef fd,
DWORD dwStubFlags, // NDirectStubFlags
FieldDesc* pFD)
{
CONTRACT(MethodDesc*)
{
STANDARD_VM_CHECK;
PRECONDITION(CheckPointer(szMetaSig));
PRECONDITION(CheckPointer(pModule));
PRECONDITION(CheckPointer(pFD, NULL_OK));
PRECONDITION(SF_IsFieldGetterStub(dwStubFlags) || SF_IsFieldSetterStub(dwStubFlags));
POSTCONDITION(CheckPointer(RETVAL));
}
CONTRACT_END;
int numArgs = (SF_IsFieldSetterStub(dwStubFlags) ? 1 : 0);
int numParamTokens = numArgs + 1;
// make sure we capture marshaling metadata
mdParamDef* pParamTokenArray = (mdParamDef *)_alloca(numParamTokens * sizeof(mdParamDef));
pParamTokenArray[0] = mdParamDefNil;
pParamTokenArray[numArgs] = (mdParamDef)fd;
// fields are never preserve-sig
dwStubFlags |= NDIRECTSTUB_FL_DOHRESULTSWAPPING;
// convert field signature to getter/setter signature
SigBuilder sigBuilder;
sigBuilder.AppendData(IMAGE_CEE_CS_CALLCONV_DEFAULT | IMAGE_CEE_CS_CALLCONV_HASTHIS);
sigBuilder.AppendData(numArgs);
if (SF_IsFieldSetterStub(dwStubFlags))
{
// managed setter returns void
sigBuilder.AppendElementType(ELEMENT_TYPE_VOID);
}
CONSISTENCY_CHECK(*szMetaSig == IMAGE_CEE_CS_CALLCONV_FIELD);
sigBuilder.AppendBlob((const PVOID)(szMetaSig + 1), cbMetaSigSize - 1);
szMetaSig = (PCCOR_SIGNATURE)sigBuilder.GetSignature(&cbMetaSigSize);
StubSigDesc sigDesc(NULL, Signature(szMetaSig, cbMetaSigSize), pModule);
#ifdef _DEBUG
sigDesc.m_pDebugName = pFD->GetDebugName();
sigDesc.m_pDebugClassName = pFD->GetEnclosingMethodTable()->GetDebugClassName();
#endif // _DEBUG
Signature signature(szMetaSig, cbMetaSigSize);
NewHolder<ILStubState> pStubState = new COMToCLRFieldAccess_ILStubState(pModule, signature, &sigDesc.m_typeContext, dwStubFlags, pFD);
MethodDesc* pStubMD;
pStubMD = CreateInteropILStub(
pStubState,
&sigDesc,
(CorNativeLinkType)0,
(CorNativeLinkFlags)0,
(CorPinvokeMap)0,
dwStubFlags,
numParamTokens,
pParamTokenArray,
-1);
RETURN pStubMD;
}
#endif // FEATURE_COMINTEROP
MethodDesc* NDirect::CreateCLRToNativeILStub(PInvokeStaticSigInfo* pSigInfo,
DWORD dwStubFlags,
MethodDesc* pMD)
{
STANDARD_VM_CONTRACT;
StubSigDesc sigDesc(pMD, pSigInfo);
if (SF_IsWinRTDelegateStub(dwStubFlags))
{
_ASSERTE(pMD->IsEEImpl());
return CreateCLRToNativeILStub(&sigDesc,
(CorNativeLinkType)0,
(CorNativeLinkFlags)0,
(CorPinvokeMap)0,
(pSigInfo->GetStubFlags() | dwStubFlags) & ~NDIRECTSTUB_FL_DELEGATE);
}
else
{
return CreateCLRToNativeILStub(&sigDesc,
pSigInfo->GetCharSet(),
pSigInfo->GetLinkFlags(),
pSigInfo->GetCallConv(),
pSigInfo->GetStubFlags() | dwStubFlags);
}
}
MethodDesc* NDirect::GetILStubMethodDesc(NDirectMethodDesc* pNMD, PInvokeStaticSigInfo* pSigInfo, DWORD dwStubFlags)
{
STANDARD_VM_CONTRACT;
MethodDesc* pStubMD = NULL;
if (!pNMD->IsVarArgs() || SF_IsForNumParamBytes(dwStubFlags))
{
if (pNMD->IsClassConstructorTriggeredByILStub())
{
dwStubFlags |= NDIRECTSTUB_FL_TRIGGERCCTOR;
}
pStubMD = CreateCLRToNativeILStub(
pSigInfo,
dwStubFlags & ~NDIRECTSTUB_FL_FOR_NUMPARAMBYTES,
pNMD);
}
return pStubMD;
}
MethodDesc* GetStubMethodDescFromInteropMethodDesc(MethodDesc* pMD, DWORD dwStubFlags)
{
STANDARD_VM_CONTRACT;
BOOL fGcMdaEnabled = FALSE;
#ifdef MDA_SUPPORTED
if (MDA_GET_ASSISTANT(GcManagedToUnmanaged) || MDA_GET_ASSISTANT(GcUnmanagedToManaged))
{
// We never generate checks for these MDAs to NGEN'ed stubs so if they are
// enabled, a new stub must be generated (the perf impact is huge anyway).
fGcMdaEnabled = TRUE;
}
#endif // MDA_SUPPORTED
#ifdef FEATURE_COMINTEROP
if (SF_IsReverseCOMStub(dwStubFlags))
{
if (fGcMdaEnabled)
return NULL;
// reverse COM stubs live in a hash table
StubMethodHashTable *pHash = pMD->GetLoaderModule()->GetStubMethodHashTable();
return (pHash == NULL ? NULL : pHash->FindMethodDesc(pMD));
}
else
#endif // FEATURE_COMINTEROP
if (pMD->IsNDirect())
{
NDirectMethodDesc* pNMD = (NDirectMethodDesc*)pMD;
return ((fGcMdaEnabled && !pNMD->IsQCall()) ? NULL : pNMD->ndirect.m_pStubMD.GetValueMaybeNull());
}
#ifdef FEATURE_COMINTEROP
else if (pMD->IsComPlusCall() || pMD->IsGenericComPlusCall())
{
#ifdef MDA_SUPPORTED
if (MDA_GET_ASSISTANT(RaceOnRCWCleanup))
{
// we never generate this callout to NGEN'ed stubs
return NULL;
}
#endif // MDA_SUPPORTED
if (NDirect::IsHostHookEnabled())
{
MethodTable *pMT = pMD->GetMethodTable();
if (pMT->IsProjectedFromWinRT() || pMT->IsWinRTRedirectedInterface(TypeHandle::Interop_ManagedToNative))
{
// WinRT NGENed stubs are optimized for the non-hosted scenario and
// must be rejected if we are hosted.
return NULL;
}
}
if (fGcMdaEnabled)
return NULL;
ComPlusCallInfo *pComInfo = ComPlusCallInfo::FromMethodDesc(pMD);
return (pComInfo == NULL ? NULL : pComInfo->m_pStubMD.GetValueMaybeNull());
}
#endif // FEATURE_COMINTEROP
else if (pMD->IsEEImpl())
{
if (fGcMdaEnabled)
return NULL;
DelegateEEClass *pClass = (DelegateEEClass *)pMD->GetClass();
if (SF_IsReverseStub(dwStubFlags))
{
return pClass->m_pReverseStubMD;
}
else
{
#ifdef FEATURE_COMINTEROP
if (SF_IsWinRTDelegateStub(dwStubFlags))
{
if (NDirect::IsHostHookEnabled() && pMD->GetMethodTable()->IsProjectedFromWinRT())
{
// WinRT NGENed stubs are optimized for the non-hosted scenario and
// must be rejected if we are hosted.
return NULL;
}
return pClass->m_pComPlusCallInfo->m_pStubMD.GetValueMaybeNull();
}
else
#endif // FEATURE_COMINTEROP
{
return pClass->m_pForwardStubMD;
}
}
}
else if (pMD->IsIL())
{
// these are currently only created at runtime, not at NGEN time
return NULL;
}
else
{
UNREACHABLE_MSG("unexpected type of MethodDesc");
}
}
#ifndef CROSSGEN_COMPILE
PCODE NDirect::GetStubForILStub(MethodDesc* pManagedMD, MethodDesc** ppStubMD, DWORD dwStubFlags)
{
CONTRACT(PCODE)
{
STANDARD_VM_CHECK;
PRECONDITION(CheckPointer(pManagedMD));
POSTCONDITION(RETVAL != NULL);
}
CONTRACT_END;
// pStubMD, if provided, must be preimplemented.
CONSISTENCY_CHECK( (*ppStubMD == NULL) || (*ppStubMD)->IsPreImplemented() );
if (NULL == *ppStubMD)
{
PInvokeStaticSigInfo sigInfo(pManagedMD);
*ppStubMD = NDirect::CreateCLRToNativeILStub(&sigInfo, dwStubFlags, pManagedMD);
}
RETURN JitILStub(*ppStubMD);
}
PCODE NDirect::GetStubForILStub(NDirectMethodDesc* pNMD, MethodDesc** ppStubMD, DWORD dwStubFlags)
{
STANDARD_VM_CONTRACT;
PCODE pStub = NULL;
// pStubMD, if provided, must be preimplemented.
CONSISTENCY_CHECK( (*ppStubMD == NULL) || (*ppStubMD)->IsPreImplemented() );
if (NULL == *ppStubMD)
{
PInvokeStaticSigInfo sigInfo;
NDirect::PopulateNDirectMethodDesc(pNMD, &sigInfo, /* throwOnError = */ !SF_IsForNumParamBytes(dwStubFlags));
*ppStubMD = NDirect::GetILStubMethodDesc(pNMD, &sigInfo, dwStubFlags);
}
if (SF_IsForNumParamBytes(dwStubFlags))
return NULL;
if (*ppStubMD)
{
pStub = JitILStub(*ppStubMD);
}
else
{
CONSISTENCY_CHECK(pNMD->IsVarArgs());
//
// varargs goes through vararg NDirect stub
//
pStub = TheVarargNDirectStub(pNMD->HasRetBuffArg());
}
{
NDirectLink(pNMD);
}
//
// NOTE: there is a race in updating this MethodDesc. We depend on all
// threads getting back the same DynamicMethodDesc for a particular
// NDirectMethodDesc, in that case, the locking around the actual JIT
// operation will prevent the code from being jitted more than once.
// By the time we get here, all threads get the same address of code
// back from the JIT operation and they all just fill in the same value
// here.
//
// In the NGEN case, all threads will get the same preimplemented code
// address much like the JIT case.
//
return pStub;
}
PCODE JitILStub(MethodDesc* pStubMD)
{
STANDARD_VM_CONTRACT;
PCODE pCode = pStubMD->GetNativeCode();
if (pCode == NULL)
{
///////////////////////////////
//
// Code generation
//
///////////////////////////////
if (pStubMD->IsDynamicMethod())
{
//
// A dynamically generated IL stub
//
pCode = pStubMD->PrepareInitialCode();
_ASSERTE(pCode == pStubMD->GetNativeCode());
}
else
{
//
// A static IL stub that is pointing to a static method in user assembly
// Compile it and return the native code
//
// This returns the stable entry point
pCode = pStubMD->DoPrestub(NULL);
_ASSERTE(pCode == pStubMD->GetStableEntryPoint());
}
}
if (!pStubMD->IsDynamicMethod())
{
// We need an entry point that can be called multiple times
pCode = pStubMD->GetMultiCallableAddrOfCode();
}
return pCode;
}
MethodDesc* RestoreNGENedStub(MethodDesc* pStubMD)
{
CONTRACTL
{
STANDARD_VM_CHECK;
PRECONDITION(CheckPointer(pStubMD));
}
CONTRACTL_END;
#ifdef FEATURE_PREJIT
pStubMD->CheckRestore();
PCODE pCode = pStubMD->GetPreImplementedCode();
if (pCode != NULL)
{
TADDR pFixupList = pStubMD->GetFixupList();
if (pFixupList != NULL)
{
Module* pZapModule = pStubMD->GetZapModule();
_ASSERTE(pZapModule != NULL);
if (!pZapModule->FixupDelayList(pFixupList))
{
_ASSERTE(!"FixupDelayList failed");
ThrowHR(COR_E_BADIMAGEFORMAT);
}
}
#if defined(HAVE_GCCOVER)
if (GCStress<cfg_instr_ngen>::IsEnabled())
SetupGcCoverage(pStubMD, (BYTE*) pCode);
#endif // HAVE_GCCOVER
}
else
{
// We only pass a non-NULL pStubMD to GetStubForILStub() below if pStubMD is preimplemeneted.
pStubMD = NULL;
}
#endif // FEATURE_PREJIT
return pStubMD;
}
PCODE GetStubForInteropMethod(MethodDesc* pMD, DWORD dwStubFlags, MethodDesc **ppStubMD)
{
CONTRACT(PCODE)
{
STANDARD_VM_CHECK;
PRECONDITION(CheckPointer(pMD));
PRECONDITION(pMD->IsNDirect() || pMD->IsComPlusCall() || pMD->IsGenericComPlusCall() || pMD->IsEEImpl() || pMD->IsIL());
}
CONTRACT_END;
PCODE pStub = NULL;
MethodDesc* pStubMD = NULL;
pStubMD = GetStubMethodDescFromInteropMethodDesc(pMD, dwStubFlags);
if (pStubMD != NULL)
{
pStubMD = RestoreNGENedStub(pStubMD);
}
if ((NULL == pStubMD) && (SF_IsNGENedStub(dwStubFlags)))
{
// Return NULL -- the caller asked only for an ngened stub and
// one does not exist, so don't do any more work.
CONSISTENCY_CHECK(pStub == NULL);
}
else
if (pMD->IsNDirect())
{
NDirectMethodDesc* pNMD = (NDirectMethodDesc*)pMD;
pStub = NDirect::GetStubForILStub(pNMD, &pStubMD, dwStubFlags);
}
#ifdef FEATURE_COMINTEROP
else
if (pMD->IsComPlusCall() || pMD->IsGenericComPlusCall())
{
pStub = ComPlusCall::GetStubForILStub(pMD, &pStubMD);
}
#endif // FEATURE_COMINTEROP
else
if (pMD->IsEEImpl())
{
CONSISTENCY_CHECK(pMD->GetMethodTable()->IsDelegate());
EEImplMethodDesc* pDelegateMD = (EEImplMethodDesc*)pMD;
pStub = COMDelegate::GetStubForILStub(pDelegateMD, &pStubMD, dwStubFlags);
}
else
if (pMD->IsIL())
{
CONSISTENCY_CHECK(SF_IsReverseStub(dwStubFlags));
pStub = NDirect::GetStubForILStub(pMD, &pStubMD, dwStubFlags);
}
else
{
UNREACHABLE_MSG("unexpected MethodDesc type");
}
if (pStubMD != NULL && pStubMD->IsILStub() && pStubMD->AsDynamicMethodDesc()->IsStubNeedsCOMStarted())
{
// the stub uses COM so make sure that it is started
EnsureComStarted();
}
if (ppStubMD != NULL)
*EnsureWritablePages(ppStubMD) = pStubMD;
RETURN pStub;
}
#ifdef FEATURE_COMINTEROP
void CreateCLRToDispatchCOMStub(
MethodDesc * pMD,
DWORD dwStubFlags) // NDirectStubFlags
{
CONTRACTL
{
STANDARD_VM_CHECK;
PRECONDITION(CheckPointer(pMD));
}
CONTRACTL_END;
_ASSERTE(SF_IsCOMLateBoundStub(dwStubFlags) || SF_IsCOMEventCallStub(dwStubFlags));
// If we are dealing with a COM event call, then we need to initialize the
// COM event call information.
if (SF_IsCOMEventCallStub(dwStubFlags))
{
_ASSERTE(pMD->IsComPlusCall()); // no generic COM eventing
((ComPlusCallMethodDesc *)pMD)->InitComEventCallInfo();
}
// Get the call signature information
StubSigDesc sigDesc(pMD);
int iLCIDArg = 0;
int numArgs = 0;
int numParamTokens = 0;
mdParamDef* pParamTokenArray = NULL;
CreateNDirectStubAccessMetadata(&sigDesc,
(CorPinvokeMap)0,
&dwStubFlags,
&iLCIDArg,
&numArgs);
numParamTokens = numArgs + 1;
pParamTokenArray = (mdParamDef*)_alloca(numParamTokens * sizeof(mdParamDef));
CollateParamTokens(sigDesc.m_pModule->GetMDImport(), sigDesc.m_tkMethodDef, numArgs, pParamTokenArray);
DispatchStubState MyStubState;
CreateNDirectStubWorker(&MyStubState,
&sigDesc,
(CorNativeLinkType)0,
(CorNativeLinkFlags)0,
(CorPinvokeMap)0,
dwStubFlags | NDIRECTSTUB_FL_COM,
pMD,
pParamTokenArray,
iLCIDArg);
_ASSERTE(pMD->IsComPlusCall()); // no generic disp-calls
((ComPlusCallMethodDesc *)pMD)->InitRetThunk();
}
#endif // FEATURE_COMINTEROP
/*static*/
LPVOID NDirect::NDirectGetEntryPoint(NDirectMethodDesc *pMD, HINSTANCE hMod)
{
// GetProcAddress cannot be called while preemptive GC is disabled.
// It requires the OS to take the loader lock.
CONTRACT(LPVOID)
{
STANDARD_VM_CHECK;
PRECONDITION(CheckPointer(pMD));
POSTCONDITION(CheckPointer(RETVAL, NULL_OK));
}
CONTRACT_END;
g_IBCLogger.LogNDirectCodeAccess(pMD);
#ifdef MDA_SUPPORTED
MDA_TRIGGER_ASSISTANT(PInvokeLog, LogPInvoke(pMD, hMod));
#endif
RETURN pMD->FindEntryPoint(hMod);
}
VOID NDirectMethodDesc::SetNDirectTarget(LPVOID pTarget)
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
MODE_ANY;
PRECONDITION(IsNDirect());
PRECONDITION(pTarget != NULL);
}
CONTRACTL_END;
Stub *pInterceptStub = NULL;
BOOL fHook = FALSE;
// Host hooks are not supported for Mac CoreCLR.
if (NDirect::IsHostHookEnabled())
{
#ifdef _WIN64
// we will call CallNeedsHostHook on every invocation for back compat
fHook = TRUE;
#else // _WIN64
fHook = CallNeedsHostHook((size_t)pTarget);
#endif // _WIN64
#ifdef _DEBUG
if (g_pConfig->ShouldGenerateStubForHost())
{
fHook = TRUE;
}
#endif
}
#ifdef _TARGET_X86_
#ifdef MDA_SUPPORTED
if (!IsQCall() && MDA_GET_ASSISTANT(PInvokeStackImbalance))
{
pInterceptStub = GenerateStubForMDA(pTarget, pInterceptStub, fHook);
}
#endif // MDA_SUPPORTED
#endif // _TARGET_X86_
NDirectWriteableData* pWriteableData = GetWriteableData();
EnsureWritablePages(pWriteableData);
g_IBCLogger.LogNDirectCodeAccess(this);
if (pInterceptStub != NULL WIN64_ONLY(|| fHook))
{
ndirect.m_pNativeNDirectTarget = pTarget;
#if defined(_TARGET_X86_)
pTarget = (PVOID)pInterceptStub->GetEntryPoint();
LPVOID oldTarget = GetNDirectImportThunkGlue()->GetEntrypoint();
if (FastInterlockCompareExchangePointer(&pWriteableData->m_pNDirectTarget, pTarget,
oldTarget) != oldTarget)
{
pInterceptStub->DecRef();
}
#else
_ASSERTE(pInterceptStub == NULL); // we don't intercept for anything else than host on !_TARGET_X86_
#endif
}
else
{
pWriteableData->m_pNDirectTarget = pTarget;
}
}
#if defined(_TARGET_X86_) && defined(MDA_SUPPORTED)
EXTERN_C VOID __stdcall PInvokeStackImbalanceWorker(StackImbalanceCookie *pSICookie, DWORD dwPostESP)
{
STATIC_CONTRACT_THROWS;
STATIC_CONTRACT_GC_TRIGGERS;
STATIC_CONTRACT_MODE_PREEMPTIVE; // we've already switched to preemptive
// make sure we restore the original Win32 last error before leaving this function - we are
// called right after returning from the P/Invoke target and the error has not been saved yet
BEGIN_PRESERVE_LAST_ERROR;
MdaPInvokeStackImbalance* pProbe = MDA_GET_ASSISTANT(PInvokeStackImbalance);
// This MDA must be active if we generated a call to PInvokeStackImbalanceHelper
_ASSERTE(pProbe);
pProbe->CheckStack(pSICookie, dwPostESP);
END_PRESERVE_LAST_ERROR;
}
#endif // _TARGET_X86_ && MDA_SUPPORTED
// Preserving good error info from DllImport-driven LoadLibrary is tricky because we keep loading from different places
// if earlier loads fail and those later loads obliterate error codes.
//
// This tracker object will keep track of the error code in accordance to priority:
//
// low-priority: unknown error code (should never happen)
// medium-priority: dll not found
// high-priority: dll found but error during loading
//
// We will overwrite the previous load's error code only if the new error code is higher priority.
//
class LoadLibErrorTracker
{
private:
static const DWORD const_priorityNotFound = 10;
static const DWORD const_priorityAccessDenied = 20;
static const DWORD const_priorityCouldNotLoad = 99999;
public:
LoadLibErrorTracker()
{
LIMITED_METHOD_CONTRACT;
m_hr = E_FAIL;
m_priorityOfLastError = 0;
}
VOID TrackErrorCode()
{
LIMITED_METHOD_CONTRACT;
DWORD priority;
#ifdef FEATURE_PAL
SetMessage(PAL_GetLoadLibraryError());
#else
DWORD dwLastError = GetLastError();
switch (dwLastError)
{
case ERROR_FILE_NOT_FOUND:
case ERROR_PATH_NOT_FOUND:
case ERROR_MOD_NOT_FOUND:
case ERROR_DLL_NOT_FOUND:
priority = const_priorityNotFound;
break;
// If we can't access a location, we can't know if the dll's there or if it's good.
// Still, this is probably more unusual (and thus of more interest) than a dll-not-found
// so give it an intermediate priority.
case ERROR_ACCESS_DENIED:
priority = const_priorityAccessDenied;
// Assume all others are "dll found but couldn't load."
default:
priority = const_priorityCouldNotLoad;
break;
}
UpdateHR(priority, HRESULT_FROM_WIN32(dwLastError));
#endif
}
// Sets the error code to HRESULT as could not load DLL
void TrackHR_CouldNotLoad(HRESULT hr)
{
UpdateHR(const_priorityCouldNotLoad, hr);
}
HRESULT GetHR()
{
return m_hr;
}
SString& GetMessage()
{
return m_message;
}
void DECLSPEC_NORETURN Throw(SString &libraryNameOrPath)
{
STANDARD_VM_CONTRACT;
#if defined(__APPLE__)
COMPlusThrow(kDllNotFoundException, IDS_EE_NDIRECT_LOADLIB_MAC, libraryNameOrPath.GetUnicode(), GetMessage());
#elif defined(FEATURE_PAL)
COMPlusThrow(kDllNotFoundException, IDS_EE_NDIRECT_LOADLIB_LINUX, libraryNameOrPath.GetUnicode(), GetMessage());
#else // __APPLE__
HRESULT theHRESULT = GetHR();
if (theHRESULT == HRESULT_FROM_WIN32(ERROR_BAD_EXE_FORMAT))
{
COMPlusThrow(kBadImageFormatException);
}
else
{
SString hrString;
GetHRMsg(theHRESULT, hrString);
COMPlusThrow(kDllNotFoundException, IDS_EE_NDIRECT_LOADLIB_WIN, libraryNameOrPath.GetUnicode(), hrString);
}
#endif // FEATURE_PAL
__UNREACHABLE();
}
private:
void UpdateHR(DWORD priority, HRESULT hr)
{
if (priority > m_priorityOfLastError)
{
m_hr = hr;
m_priorityOfLastError = priority;
}
}
void SetMessage(LPCSTR message)
{
m_message = SString(SString::Utf8, message);
}
HRESULT m_hr;
DWORD m_priorityOfLastError;
SString m_message;
}; // class LoadLibErrorTracker
// Local helper function for the LoadLibraryModule function below
static HMODULE LocalLoadLibraryHelper( LPCWSTR name, DWORD flags, LoadLibErrorTracker *pErrorTracker )
{
STANDARD_VM_CONTRACT;
HMODULE hmod = NULL;
#ifndef FEATURE_PAL
if ((flags & 0xFFFFFF00) != 0
#ifndef FEATURE_CORESYSTEM
&& NDirect::SecureLoadLibrarySupported()
#endif // !FEATURE_CORESYSTEM
)
{
hmod = CLRLoadLibraryEx(name, NULL, flags & 0xFFFFFF00);
if(hmod != NULL)
{
return hmod;
}
DWORD dwLastError = GetLastError();
if (dwLastError != ERROR_INVALID_PARAMETER)
{
pErrorTracker->TrackErrorCode();
return hmod;
}
}
hmod = CLRLoadLibraryEx(name, NULL, flags & 0xFF);
#else // !FEATURE_PAL
hmod = CLRLoadLibrary(name);
#endif // !FEATURE_PAL
if (hmod == NULL)
{
pErrorTracker->TrackErrorCode();
}
return hmod;
}
// Local helper function for the LoadLibraryFromPath function below
static HMODULE LocalLoadLibraryDirectHelper(LPCWSTR name, DWORD flags, LoadLibErrorTracker *pErrorTracker)
{
STANDARD_VM_CONTRACT;
#ifndef FEATURE_PAL
return LocalLoadLibraryHelper(name, flags, pErrorTracker);
#else // !FEATURE_PAL
// Load the library directly, and don't register it yet with PAL. The system library handle is required here, not the PAL
// handle. The system library handle is registered with PAL to get a PAL handle in LoadLibraryModuleViaHost().
HMODULE hmod = PAL_LoadLibraryDirect(name);
if (hmod == NULL)
{
pErrorTracker->TrackErrorCode();
}
return hmod;
#endif // !FEATURE_PAL
}
#if !defined(FEATURE_PAL)
bool NDirect::s_fSecureLoadLibrarySupported = false;
#endif
#define TOLOWER(a) (((a) >= W('A') && (a) <= W('Z')) ? (W('a') + (a - W('A'))) : (a))
#define TOHEX(a) ((a)>=10 ? W('a')+(a)-10 : W('0')+(a))
#ifdef FEATURE_PAL
#define PLATFORM_SHARED_LIB_SUFFIX_W PAL_SHLIB_SUFFIX_W
#define PLATFORM_SHARED_LIB_PREFIX_W PAL_SHLIB_PREFIX_W
#else // !FEATURE_PAL
#define PLATFORM_SHARED_LIB_SUFFIX_W W(".dll")
#define PLATFORM_SHARED_LIB_PREFIX_W W("")
#endif // !FEATURE_PAL
// static
HMODULE NDirect::LoadLibraryFromPath(LPCWSTR libraryPath)
{
STANDARD_VM_CONTRACT;
LoadLibErrorTracker errorTracker;
const HMODULE systemModuleHandle =
LocalLoadLibraryDirectHelper(libraryPath, GetLoadWithAlteredSearchPathFlag(), &errorTracker);
if (systemModuleHandle == nullptr)
{
SString libraryPathSString(libraryPath);
errorTracker.Throw(libraryPathSString);
}
return systemModuleHandle;
}
/* static */
HMODULE NDirect::LoadLibraryModuleViaHost(NDirectMethodDesc * pMD, AppDomain* pDomain, const wchar_t* wszLibName)
{
STANDARD_VM_CONTRACT;
//Dynamic Pinvoke Support:
//Check if we need to provide the host a chance to provide the unmanaged dll
#ifndef PLATFORM_UNIX
// Prevent Overriding of Windows API sets.
// This is replicating quick check from the OS implementation of api sets.
if (SString::_wcsnicmp(wszLibName, W("api-"), 4) == 0 || SString::_wcsnicmp(wszLibName, W("ext-"), 4) == 0)
{
return NULL;
}
#endif
LPVOID hmod = NULL;
CLRPrivBinderCoreCLR *pTPABinder = pDomain->GetTPABinderContext();
Assembly* pAssembly = pMD->GetMethodTable()->GetAssembly();
PEFile *pManifestFile = pAssembly->GetManifestFile();
PTR_ICLRPrivBinder pBindingContext = pManifestFile->GetBindingContext();
//Step 0: Check if the assembly was bound using TPA.
// The Binding Context can be null or an overridden TPA context
if (pBindingContext == NULL)
{
// If we do not have any binder associated, then return to the default resolution mechanism.
return NULL;
}
UINT_PTR assemblyBinderID = 0;
IfFailThrow(pBindingContext->GetBinderID(&assemblyBinderID));
ICLRPrivBinder *pCurrentBinder = reinterpret_cast<ICLRPrivBinder *>(assemblyBinderID);
// For assemblies bound via TPA binder, we should use the standard mechanism to make the pinvoke call.
if (AreSameBinderInstance(pCurrentBinder, pTPABinder))
{
return NULL;
}
#ifdef FEATURE_COMINTEROP
CLRPrivBinderWinRT *pWinRTBinder = pDomain->GetWinRtBinder();
if (AreSameBinderInstance(pCurrentBinder, pWinRTBinder))
{
// We could be here when a non-WinRT assembly load is triggerred by a winmd (e.g. System.Runtime being loaded due to
// types being referenced from Windows.Foundation.Winmd) or when dealing with a winmd (which is bound using WinRT binder).
//
// For this, we should use the standard mechanism to make pinvoke call as well.
return NULL;
}
#endif // FEATURE_COMINTEROP
//Step 1: If the assembly was not bound using TPA,
// Call System.Runtime.Loader.AssemblyLoadContext.ResolveUnamanagedDll to give
// The custom assembly context a chance to load the unmanaged dll.
GCX_COOP();
STRINGREF pUnmanagedDllName;
pUnmanagedDllName = StringObject::NewString(wszLibName);
GCPROTECT_BEGIN(pUnmanagedDllName);
// Get the pointer to the managed assembly load context
INT_PTR ptrManagedAssemblyLoadContext = ((CLRPrivBinderAssemblyLoadContext *)pCurrentBinder)->GetManagedAssemblyLoadContext();
// Prepare to invoke System.Runtime.Loader.AssemblyLoadContext.ResolveUnamanagedDll method.
PREPARE_NONVIRTUAL_CALLSITE(METHOD__ASSEMBLYLOADCONTEXT__RESOLVEUNMANAGEDDLL);
DECLARE_ARGHOLDER_ARRAY(args, 2);
args[ARGNUM_0] = STRINGREF_TO_ARGHOLDER(pUnmanagedDllName);
args[ARGNUM_1] = PTR_TO_ARGHOLDER(ptrManagedAssemblyLoadContext);
// Make the call
CALL_MANAGED_METHOD(hmod,LPVOID,args);
GCPROTECT_END();
#ifdef FEATURE_PAL
if (hmod != nullptr)
{
// Register the system library handle with PAL and get a PAL library handle
hmod = PAL_RegisterLibraryDirect(hmod, wszLibName);
}
#endif // FEATURE_PAL
return (HMODULE)hmod;
}
// Try to load the module alongside the assembly where the PInvoke was declared.
HMODULE NDirect::LoadFromPInvokeAssemblyDirectory(Assembly *pAssembly, LPCWSTR libName, DWORD flags, LoadLibErrorTracker *pErrorTracker)
{
STANDARD_VM_CONTRACT;
HMODULE hmod = NULL;
SString path = pAssembly->GetManifestFile()->GetPath();
SString::Iterator lastPathSeparatorIter = path.End();
if (PEAssembly::FindLastPathSeparator(path, lastPathSeparatorIter))
{
lastPathSeparatorIter++;
path.Truncate(lastPathSeparatorIter);
path.Append(libName);
hmod = LocalLoadLibraryHelper(path, flags, pErrorTracker);
}
return hmod;
}
// Try to load the module from the native DLL search directories
HMODULE NDirect::LoadFromNativeDllSearchDirectories(AppDomain* pDomain, LPCWSTR libName, DWORD flags, LoadLibErrorTracker *pErrorTracker)
{
STANDARD_VM_CONTRACT;
HMODULE hmod = NULL;
if (pDomain->HasNativeDllSearchDirectories())
{
AppDomain::PathIterator pathIter = pDomain->IterateNativeDllSearchDirectories();
while (hmod == NULL && pathIter.Next())
{
SString qualifiedPath(*(pathIter.GetPath()));
qualifiedPath.Append(libName);
if (!Path::IsRelative(qualifiedPath))
{
hmod = LocalLoadLibraryHelper(qualifiedPath, flags, pErrorTracker);
}
}
}
return hmod;
}
#ifdef FEATURE_PAL
static void DetermineLibNameVariations(const WCHAR* const** libNameVariations, int* numberOfVariations, const SString& libName, bool libNameIsRelativePath)
{
if (libNameIsRelativePath)
{
// We check if the suffix is contained in the name, because on Linux it is common to append
// a version number to the library name (e.g. 'libicuuc.so.57').
bool containsSuffix;
SString::CIterator it = libName.Begin();
if (libName.Find(it, PLATFORM_SHARED_LIB_SUFFIX_W))
{
it += wcslen(PLATFORM_SHARED_LIB_SUFFIX_W);
containsSuffix = it == libName.End() || *it == (WCHAR)'.';
}
else
{
containsSuffix = false;
}
if (containsSuffix)
{
static const WCHAR* const SuffixLast[] =
{
W("%.0s%s"), // name
W("%s%s%.0s"), // prefix+name
W("%.0s%s%s"), // name+suffix
W("%s%s%s") // prefix+name+suffix
};
*libNameVariations = SuffixLast;
*numberOfVariations = COUNTOF(SuffixLast);
}
else
{
static const WCHAR* const SuffixFirst[] =
{
W("%.0s%s%s"), // name+suffix
W("%s%s%s"), // prefix+name+suffix
W("%.0s%s"), // name
W("%s%s%.0s") // prefix+name
};
*libNameVariations = SuffixFirst;
*numberOfVariations = COUNTOF(SuffixFirst);
}
}
else
{
static const WCHAR* const NameOnly[] =
{
W("%.0s%s")
};
*libNameVariations = NameOnly;
*numberOfVariations = COUNTOF(NameOnly);
}
}
#else // FEATURE_PAL
static void DetermineLibNameVariations(const WCHAR* const** libNameVariations, int* numberOfVariations, const SString& libName, bool libNameIsRelativePath)
{
// The purpose of following code is to workaround LoadLibrary limitation:
// LoadLibrary won't append extension if filename itself contains '.'. Thus it will break the following scenario:
// [DllImport("A.B")] // The full name for file is "A.B.dll". This is common code pattern for cross-platform PInvoke
// The workaround for above scenario is to call LoadLibrary with "A.B" first, if it fails, then call LoadLibrary with "A.B.dll"
if (!libNameIsRelativePath ||
!libName.Find(libName.Begin(), W('.')) ||
libName.EndsWith(W(".")) ||
libName.EndsWithCaseInsensitive(W(".dll")) ||
libName.EndsWithCaseInsensitive(W(".exe")))
{
// Follow LoadLibrary rules in MSDN doc: https://msdn.microsoft.com/en-us/library/windows/desktop/ms684175(v=vs.85).aspx
// If the string specifies a full path, the function searches only that path for the module.
// If the string specifies a module name without a path and the file name extension is omitted, the function appends the default library extension .dll to the module name.
// To prevent the function from appending .dll to the module name, include a trailing point character (.) in the module name string.
static const WCHAR* const NameOnly[] =
{
W("%.0s%s")
};
*libNameVariations = NameOnly;
*numberOfVariations = COUNTOF(NameOnly);
}
else
{
static const WCHAR* const SuffixLast[] =
{
W("%.0s%s"), // name
W("%.0s%s%s"), // name+suffix
};
*libNameVariations = SuffixLast;
*numberOfVariations = COUNTOF(SuffixLast);
}
}
#endif // FEATURE_PAL
HINSTANCE NDirect::LoadLibraryModule(NDirectMethodDesc * pMD, LoadLibErrorTracker * pErrorTracker)
{
CONTRACTL
{
STANDARD_VM_CHECK;
PRECONDITION( CheckPointer( pMD ) );
}
CONTRACTL_END;
LPCUTF8 name = pMD->GetLibName();
if ( !name || !*name )
return NULL;
ModuleHandleHolder hmod;
DWORD loadWithAlteredPathFlags = GetLoadWithAlteredSearchPathFlag();
PREFIX_ASSUME( name != NULL );
MAKE_WIDEPTR_FROMUTF8( wszLibName, name );
AppDomain* pDomain = GetAppDomain();
// AssemblyLoadContext is not supported in AppX mode and thus,
// we should not perform PInvoke resolution via it when operating in
// AppX mode.
if (!AppX::IsAppXProcess())
{
hmod = LoadLibraryModuleViaHost(pMD, pDomain, wszLibName);
}
if(hmod == NULL)
{
hmod = pDomain->FindUnmanagedImageInCache(wszLibName);
}
if(hmod != NULL)
{
return hmod.Extract();
}
#ifdef FEATURE_PAL
// In the PAL version of CoreCLR, the CLR module itself exports the functionality
// that the Windows version obtains from kernel32 and friends. In order to avoid
// picking up the wrong instance, we perform this redirection first.
// This is also true for CoreSystem builds, where mscorlib p/invokes are forwarded through coreclr
// itself so we can control CoreSystem library/API name re-mapping from one central location.
if (SString::_wcsicmp(wszLibName, MAIN_CLR_MODULE_NAME_W) == 0)
hmod = GetCLRModule();
#endif // FEATURE_PAL
#if defined(FEATURE_CORESYSTEM) && !defined(PLATFORM_UNIX)
if (hmod == NULL)
{
// Try to go straight to System32 for Windows API sets. This is replicating quick check from
// the OS implementation of api sets.
if (SString::_wcsnicmp(wszLibName, W("api-"), 4) == 0 || SString::_wcsnicmp(wszLibName, W("ext-"), 4) == 0)
{
hmod = LocalLoadLibraryHelper(wszLibName, LOAD_LIBRARY_SEARCH_SYSTEM32, pErrorTracker);
}
}
#endif // FEATURE_CORESYSTEM && !FEATURE_PAL
bool libNameIsRelativePath = Path::IsRelative(wszLibName);
DWORD dllImportSearchPathFlag = 0;
// P/Invokes are often declared with variations on the actual library name.
// For example, it's common to leave off the extension/suffix of the library
// even if it has one, or to leave off a prefix like "lib" even if it has one
// (both of these are typically done to smooth over cross-platform differences).
// We try to dlopen with such variations on the original.
const WCHAR* const* prefixSuffixCombinations = nullptr;
int numberOfVariations = 0;
DetermineLibNameVariations(&prefixSuffixCombinations, &numberOfVariations, wszLibName, libNameIsRelativePath);
for (int i = 0; hmod == NULL && i < numberOfVariations; i++)
{
SString currLibNameVariation;
currLibNameVariation.Printf(prefixSuffixCombinations[i], PLATFORM_SHARED_LIB_PREFIX_W, wszLibName, PLATFORM_SHARED_LIB_SUFFIX_W);
if (hmod == NULL)
{
// NATIVE_DLL_SEARCH_DIRECTORIES set by host is considered well known path
hmod = LoadFromNativeDllSearchDirectories(pDomain, currLibNameVariation, loadWithAlteredPathFlags, pErrorTracker);
}
BOOL searchAssemblyDirectory = TRUE;
if (hmod == NULL)
{
// First checks if the method has DefaultDllImportSearchPathsAttribute. If method has the attribute
// then dllImportSearchPathFlag is set to its value.
// Otherwise checks if the assembly has the attribute.
// If assembly has the attribute then flag ise set to its value.
BOOL attributeIsFound = FALSE;
if (pMD->HasDefaultDllImportSearchPathsAttribute())
{
dllImportSearchPathFlag = pMD->DefaultDllImportSearchPathsAttributeCachedValue();
searchAssemblyDirectory = pMD->DllImportSearchAssemblyDirectory();
attributeIsFound = TRUE;
}
else
{
Module * pModule = pMD->GetModule();
if(pModule->HasDefaultDllImportSearchPathsAttribute())
{
dllImportSearchPathFlag = pModule->DefaultDllImportSearchPathsAttributeCachedValue();
searchAssemblyDirectory = pModule->DllImportSearchAssemblyDirectory();
attributeIsFound = TRUE;
}
}
if (!libNameIsRelativePath)
{
DWORD flags = loadWithAlteredPathFlags;
if ((dllImportSearchPathFlag & LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR) != 0)
{
// LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR is the only flag affecting absolute path. Don't OR the flags
// unconditionally as all absolute path P/Invokes could then lose LOAD_WITH_ALTERED_SEARCH_PATH.
flags |= dllImportSearchPathFlag;
}
hmod = LocalLoadLibraryHelper(currLibNameVariation, flags, pErrorTracker);
}
else if (searchAssemblyDirectory)
{
Assembly* pAssembly = pMD->GetMethodTable()->GetAssembly();
hmod = LoadFromPInvokeAssemblyDirectory(pAssembly, currLibNameVariation, loadWithAlteredPathFlags | dllImportSearchPathFlag, pErrorTracker);
}
}
// This call searches the application directory instead of the location for the library.
if (hmod == NULL)
{
hmod = LocalLoadLibraryHelper(currLibNameVariation, dllImportSearchPathFlag, pErrorTracker);
}
}
// This may be an assembly name
if (!hmod)
{
// Format is "fileName, assemblyDisplayName"
MAKE_UTF8PTR_FROMWIDE(szLibName, wszLibName);
char *szComma = strchr(szLibName, ',');
if (szComma)
{
*szComma = '\0';
while (COMCharacter::nativeIsWhiteSpace(*(++szComma)));
AssemblySpec spec;
if (SUCCEEDED(spec.Init(szComma)))
{
// Need to perform case insensitive hashing.
CQuickBytes qbLC;
{
UTF8_TO_LOWER_CASE(szLibName, qbLC);
szLibName = (LPUTF8) qbLC.Ptr();
}
Assembly *pAssembly = spec.LoadAssembly(FILE_LOADED);
Module *pModule = pAssembly->FindModuleByName(szLibName);
hmod = LocalLoadLibraryHelper(pModule->GetPath(), loadWithAlteredPathFlags | dllImportSearchPathFlag, pErrorTracker);
}
}
}
// After all this, if we have a handle add it to the cache.
if (hmod)
{
pDomain->AddUnmanagedImageToCache(wszLibName, hmod);
}
return hmod.Extract();
}
//---------------------------------------------------------
// Loads the DLL and finds the procaddress for an N/Direct call.
//---------------------------------------------------------
/* static */
VOID NDirect::NDirectLink(NDirectMethodDesc *pMD)
{
CONTRACTL
{
STANDARD_VM_CHECK;
PRECONDITION(CheckPointer(pMD));
}
CONTRACTL_END;
//
// On the phone, we only allow platform assemblies to define pinvokes
// unless the host has asked us otherwise.
//
if (pMD->IsClassConstructorTriggeredAtLinkTime())
{
pMD->GetMethodTable()->CheckRunClassInitThrowing();
}
if (pMD->IsQCall())
{
LPVOID pvTarget = pMD->ndirect.m_pNativeNDirectTarget;
// Do not repeat the lookup if the QCall was hardbound during ngen
if (pvTarget == NULL)
{
pvTarget = ECall::GetQCallImpl(pMD);
}
else
{
_ASSERTE(pvTarget == ECall::GetQCallImpl(pMD));
}
pMD->SetNDirectTarget(pvTarget);
return;
}
// Loading unmanaged dlls can trigger dllmains which certainly count as code execution!
pMD->EnsureActive();
LoadLibErrorTracker errorTracker;
BOOL fSuccess = FALSE;
HINSTANCE hmod = LoadLibraryModule( pMD, &errorTracker );
if ( hmod )
{
LPVOID pvTarget = NDirectGetEntryPoint(pMD, hmod);
if (pvTarget)
{
#ifdef MDA_SUPPORTED
MdaInvalidOverlappedToPinvoke *pOverlapCheck = MDA_GET_ASSISTANT(InvalidOverlappedToPinvoke);
if (pOverlapCheck && pOverlapCheck->ShouldHook(pMD))
{
LPVOID pNewTarget = pOverlapCheck->Register(hmod,pvTarget);
if (pNewTarget)
{
pvTarget = pNewTarget;
}
}
#endif
pMD->SetNDirectTarget(pvTarget);
fSuccess = TRUE;
}
}
if (!fSuccess)
{
if (pMD->GetLibName() == NULL)
COMPlusThrow(kEntryPointNotFoundException, IDS_EE_NDIRECT_GETPROCADDRESS_NONAME);
StackSString ssLibName(SString::Utf8, pMD->GetLibName());
if (!hmod)
{
errorTracker.Throw(ssLibName);
}
WCHAR wszEPName[50];
if(WszMultiByteToWideChar(CP_UTF8, 0, (LPCSTR)pMD->GetEntrypointName(), -1, wszEPName, sizeof(wszEPName)/sizeof(WCHAR)) == 0)
{
wszEPName[0] = W('?');
wszEPName[1] = W('\0');
}
#ifdef FEATURE_PAL
COMPlusThrow(kEntryPointNotFoundException, IDS_EE_NDIRECT_GETPROCADDRESS_UNIX, ssLibName.GetUnicode(), wszEPName);
#else
COMPlusThrow(kEntryPointNotFoundException, IDS_EE_NDIRECT_GETPROCADDRESS_WIN, ssLibName.GetUnicode(), wszEPName);
#endif
}
}
//---------------------------------------------------------
// One-time init
//---------------------------------------------------------
/*static*/ void NDirect::Init()
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
MODE_ANY;
INJECT_FAULT(COMPlusThrowOM());
}
CONTRACTL_END;
#if !defined(FEATURE_PAL)
// Check if the OS supports the new secure LoadLibraryEx flags introduced in KB2533623
HMODULE hMod = CLRGetModuleHandle(WINDOWS_KERNEL32_DLLNAME_W);
_ASSERTE(hMod != NULL);
if (GetProcAddress(hMod, "AddDllDirectory") != NULL)
{
// The AddDllDirectory export was added in KB2533623 together with the new flag support
s_fSecureLoadLibrarySupported = true;
}
#endif // !FEATURE_PAL
}
//==========================================================================
// This function is reached only via NDirectImportThunk. It's purpose
// is to ensure that the target DLL is fully loaded and ready to run.
//
// FUN FACTS: Though this function is actually entered in unmanaged mode,
// it can reenter managed mode and throw a COM+ exception if the DLL linking
// fails.
//==========================================================================
EXTERN_C LPVOID STDCALL NDirectImportWorker(NDirectMethodDesc* pMD)
{
LPVOID ret = NULL;
BEGIN_PRESERVE_LAST_ERROR;
CONTRACTL
{
THROWS;
GC_TRIGGERS;
MODE_PREEMPTIVE;
SO_TOLERANT;
}
CONTRACTL_END;
INSTALL_MANAGED_EXCEPTION_DISPATCHER;
// this function is called by CLR to native assembly stubs which are called by
// managed code as a result, we need an unwind and continue handler to translate
// any of our internal exceptions into managed exceptions.
INSTALL_UNWIND_AND_CONTINUE_HANDLER;
{
//
// Otherwise we're in an inlined pinvoke late bound MD
//
INDEBUG(Thread *pThread = GetThread());
{
_ASSERTE(pThread->GetFrame()->GetVTablePtr() == InlinedCallFrame::GetMethodFrameVPtr());
CONSISTENCY_CHECK(pMD->IsNDirect());
//
// With IL stubs, we don't have to do anything but ensure the DLL is loaded.
//
if (!pMD->IsZapped())
{
PInvokeStaticSigInfo sigInfo;
NDirect::PopulateNDirectMethodDesc(pMD, &sigInfo);
}
else
{
// must have been populated at NGEN time
_ASSERTE(pMD->GetLibName() != NULL);
}
pMD->CheckRestore();
NDirect::NDirectLink(pMD);
}
}
ret = pMD->GetNDirectTarget();
UNINSTALL_UNWIND_AND_CONTINUE_HANDLER;
UNINSTALL_MANAGED_EXCEPTION_DISPATCHER;
END_PRESERVE_LAST_ERROR;
return ret;
}
//===========================================================================
// Support for Pinvoke Calli instruction
//
//===========================================================================
EXTERN_C void STDCALL VarargPInvokeStubWorker(TransitionBlock * pTransitionBlock, VASigCookie *pVASigCookie, MethodDesc *pMD)
{
BEGIN_PRESERVE_LAST_ERROR;
STATIC_CONTRACT_THROWS;
STATIC_CONTRACT_GC_TRIGGERS;
STATIC_CONTRACT_MODE_COOPERATIVE;
STATIC_CONTRACT_ENTRY_POINT;
MAKE_CURRENT_THREAD_AVAILABLE();
#ifdef _DEBUG
Thread::ObjectRefFlush(CURRENT_THREAD);
#endif
FrameWithCookie<PrestubMethodFrame> frame(pTransitionBlock, pMD);
PrestubMethodFrame * pFrame = &frame;
pFrame->Push(CURRENT_THREAD);
_ASSERTE(pVASigCookie == pFrame->GetVASigCookie());
_ASSERTE(pMD == pFrame->GetFunction());
GetILStubForCalli(pVASigCookie, pMD);
pFrame->Pop(CURRENT_THREAD);
END_PRESERVE_LAST_ERROR;
}
EXTERN_C void STDCALL GenericPInvokeCalliStubWorker(TransitionBlock * pTransitionBlock, VASigCookie * pVASigCookie, PCODE pUnmanagedTarget)
{
BEGIN_PRESERVE_LAST_ERROR;
STATIC_CONTRACT_THROWS;
STATIC_CONTRACT_GC_TRIGGERS;
STATIC_CONTRACT_MODE_COOPERATIVE;
STATIC_CONTRACT_ENTRY_POINT;
MAKE_CURRENT_THREAD_AVAILABLE();
#ifdef _DEBUG
Thread::ObjectRefFlush(CURRENT_THREAD);
#endif
FrameWithCookie<PInvokeCalliFrame> frame(pTransitionBlock, pVASigCookie, pUnmanagedTarget);
PInvokeCalliFrame * pFrame = &frame;
pFrame->Push(CURRENT_THREAD);
_ASSERTE(pVASigCookie == pFrame->GetVASigCookie());
GetILStubForCalli(pVASigCookie, NULL);
pFrame->Pop(CURRENT_THREAD);
END_PRESERVE_LAST_ERROR;
}
PCODE GetILStubForCalli(VASigCookie *pVASigCookie, MethodDesc *pMD)
{
CONTRACT(PCODE)
{
THROWS;
GC_TRIGGERS;
ENTRY_POINT;
MODE_ANY;
PRECONDITION(CheckPointer(pVASigCookie));
PRECONDITION(CheckPointer(pMD, NULL_OK));
POSTCONDITION(RETVAL != NULL);
}
CONTRACT_END;
PCODE pTempILStub = NULL;
INSTALL_MANAGED_EXCEPTION_DISPATCHER;
// this function is called by CLR to native assembly stubs which are called by
// managed code as a result, we need an unwind and continue handler to translate
// any of our internal exceptions into managed exceptions.
INSTALL_UNWIND_AND_CONTINUE_HANDLER;
// Force a GC if the stress level is high enough
GCStress<cfg_any>::MaybeTrigger();
GCX_PREEMP();
Signature signature = pVASigCookie->signature;
CorPinvokeMap unmgdCallConv = pmNoMangle;
DWORD dwStubFlags = NDIRECTSTUB_FL_BESTFIT;
// The MethodDesc pointer may in fact be the unmanaged target, see PInvokeStubs.asm.
if (pMD == NULL || (UINT_PTR)pMD & 0x1)
{
pMD = NULL;
dwStubFlags |= NDIRECTSTUB_FL_UNMANAGED_CALLI;
// need to convert the CALLI signature to stub signature with managed calling convention
switch (MetaSig::GetCallingConvention(pVASigCookie->pModule, pVASigCookie->signature))
{
case IMAGE_CEE_CS_CALLCONV_C:
unmgdCallConv = pmCallConvCdecl;
break;
case IMAGE_CEE_CS_CALLCONV_STDCALL:
unmgdCallConv = pmCallConvStdcall;
break;
case IMAGE_CEE_CS_CALLCONV_THISCALL:
unmgdCallConv = pmCallConvThiscall;
break;
case IMAGE_CEE_CS_CALLCONV_FASTCALL:
unmgdCallConv = pmCallConvFastcall;
break;
default:
COMPlusThrow(kTypeLoadException, IDS_INVALID_PINVOKE_CALLCONV);
}
LoaderHeap *pHeap = pVASigCookie->pModule->GetLoaderAllocator()->GetHighFrequencyHeap();
PCOR_SIGNATURE new_sig = (PCOR_SIGNATURE)(void *)pHeap->AllocMem(S_SIZE_T(signature.GetRawSigLen()));
CopyMemory(new_sig, signature.GetRawSig(), signature.GetRawSigLen());
// make the stub IMAGE_CEE_CS_CALLCONV_DEFAULT
*new_sig &= ~IMAGE_CEE_CS_CALLCONV_MASK;
*new_sig |= IMAGE_CEE_CS_CALLCONV_DEFAULT;
signature = Signature(new_sig, signature.GetRawSigLen());
}
else
{
_ASSERTE(pMD->IsNDirect());
dwStubFlags |= NDIRECTSTUB_FL_CONVSIGASVARARG;
// vararg P/Invoke must be cdecl
unmgdCallConv = pmCallConvCdecl;
if (((NDirectMethodDesc *)pMD)->IsClassConstructorTriggeredByILStub())
{
dwStubFlags |= NDIRECTSTUB_FL_TRIGGERCCTOR;
}
}
mdMethodDef md;
CorNativeLinkFlags nlFlags;
CorNativeLinkType nlType;
if (pMD != NULL)
{
PInvokeStaticSigInfo sigInfo(pMD);
md = pMD->GetMemberDef();
nlFlags = sigInfo.GetLinkFlags();
nlType = sigInfo.GetCharSet();
}
else
{
md = mdMethodDefNil;
nlFlags = nlfNone;
nlType = nltAnsi;
}
StubSigDesc sigDesc(pMD, signature, pVASigCookie->pModule);
MethodDesc* pStubMD = NDirect::CreateCLRToNativeILStub(&sigDesc,
nlType,
nlFlags,
unmgdCallConv,
dwStubFlags);
pTempILStub = JitILStub(pStubMD);
InterlockedCompareExchangeT<PCODE>(&pVASigCookie->pNDirectILStub,
pTempILStub,
NULL);
UNINSTALL_UNWIND_AND_CONTINUE_HANDLER;
UNINSTALL_MANAGED_EXCEPTION_DISPATCHER;
RETURN pVASigCookie->pNDirectILStub;
}
#endif // CROSSGEN_COMPILE
#endif // #ifndef DACCESS_COMPILE
//
// Truncates a SString by first converting it to unicode and truncate it
// if it is larger than size. "..." will be appened if it is truncated.
//
void TruncateUnicodeString(SString &string, COUNT_T bufSize)
{
string.Normalize();
if ((string.GetCount() + 1) * sizeof(WCHAR) > bufSize)
{
_ASSERTE(bufSize / sizeof(WCHAR) > 4);
string.Truncate(string.Begin() + bufSize / sizeof(WCHAR) - 4);
string.Append(W("..."));
}
}
|