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
|
// 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: UTIL.CPP
//
// ===========================================================================
#include "common.h"
#include "excep.h"
#include "corhost.h"
#include "eventtrace.h"
#include "posterror.h"
#include "eemessagebox.h"
#include <shlobj.h>
#include "dlwrap.h"
#ifndef DACCESS_COMPILE
// Helper function that encapsulates the parsing rules.
//
// Called first with *pdstout == NULL to figure out how many args there are
// and the size of the required destination buffer.
//
// Called again with a nonnull *pdstout to fill in the actual buffer.
//
// Returns the # of arguments.
static UINT ParseCommandLine(LPCWSTR psrc, __inout LPWSTR *pdstout)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
FORBID_FAULT;
}
CONTRACTL_END
UINT argcount = 1; // discovery of arg0 is unconditional, below
LPWSTR pdst = *pdstout;
BOOL fDoWrite = (pdst != NULL);
BOOL fInQuotes;
int iSlash;
/* A quoted program name is handled here. The handling is much
simpler than for other arguments. Basically, whatever lies
between the leading double-quote and next one, or a terminal null
character is simply accepted. Fancier handling is not required
because the program name must be a legal NTFS/HPFS file name.
Note that the double-quote characters are not copied, nor do they
contribute to numchars.
This "simplification" is necessary for compatibility reasons even
though it leads to mishandling of certain cases. For example,
"c:\tests\"test.exe will result in an arg0 of c:\tests\ and an
arg1 of test.exe. In any rational world this is incorrect, but
we need to preserve compatibility.
*/
LPCWSTR pStart = psrc;
BOOL skipQuote = FALSE;
if (*psrc == W('\"'))
{
// scan from just past the first double-quote through the next
// double-quote, or up to a null, whichever comes first
while ((*(++psrc) != W('\"')) && (*psrc != W('\0')))
continue;
skipQuote = TRUE;
}
else
{
/* Not a quoted program name */
while (!ISWWHITE(*psrc) && *psrc != W('\0'))
psrc++;
}
// We have now identified arg0 as pStart (or pStart+1 if we have a leading
// quote) through psrc-1 inclusive
if (skipQuote)
pStart++;
while (pStart < psrc)
{
if (fDoWrite)
*pdst = *pStart;
pStart++;
pdst++;
}
// And terminate it.
if (fDoWrite)
*pdst = W('\0');
pdst++;
// if we stopped on a double-quote when arg0 is quoted, skip over it
if (skipQuote && *psrc == W('\"'))
psrc++;
while ( *psrc != W('\0'))
{
LEADINGWHITE:
// The outofarg state.
while (ISWWHITE(*psrc))
psrc++;
if (*psrc == W('\0'))
break;
else
if (*psrc == W('#'))
{
while (*psrc != W('\0') && *psrc != W('\n'))
psrc++; // skip to end of line
goto LEADINGWHITE;
}
argcount++;
fInQuotes = FALSE;
while ((!ISWWHITE(*psrc) || fInQuotes) && *psrc != W('\0'))
{
switch (*psrc)
{
case W('\\'):
iSlash = 0;
while (*psrc == W('\\'))
{
iSlash++;
psrc++;
}
if (*psrc == W('\"'))
{
for ( ; iSlash >= 2; iSlash -= 2)
{
if (fDoWrite)
*pdst = W('\\');
pdst++;
}
if (iSlash & 1)
{
if (fDoWrite)
*pdst = *psrc;
psrc++;
pdst++;
}
else
{
fInQuotes = !fInQuotes;
psrc++;
}
}
else
for ( ; iSlash > 0; iSlash--)
{
if (fDoWrite)
*pdst = W('\\');
pdst++;
}
break;
case W('\"'):
fInQuotes = !fInQuotes;
psrc++;
break;
default:
if (fDoWrite)
*pdst = *psrc;
psrc++;
pdst++;
}
}
if (fDoWrite)
*pdst = W('\0');
pdst++;
}
_ASSERTE(*psrc == W('\0'));
*pdstout = pdst;
return argcount;
}
// Function to parse apart a command line and return the
// arguments just like argv and argc
// This function is a little funky because of the pointer work
// but it is neat because it allows the recipient of the char**
// to only have to do a single delete []
LPWSTR* CommandLineToArgvW(__in LPWSTR lpCmdLine, DWORD *pNumArgs)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
INJECT_FAULT(return NULL;);
}
CONTRACTL_END
DWORD argcount = 0;
LPWSTR retval = NULL;
LPWSTR *pslot;
// First we need to find out how many strings there are in the command line
_ASSERTE(lpCmdLine);
_ASSERTE(pNumArgs);
LPWSTR pdst = NULL;
argcount = ParseCommandLine(lpCmdLine, &pdst);
// This check is because on WinCE the Application Name is not passed in as an argument to the app!
if (argcount == 0)
{
*pNumArgs = 0;
return NULL;
}
// Now we need alloc a buffer the size of the command line + the number of strings * DWORD
retval = new (nothrow) WCHAR[(argcount*sizeof(WCHAR*))/sizeof(WCHAR) + (pdst - (LPWSTR)NULL)];
if(!retval)
return NULL;
pdst = (LPWSTR)( argcount*sizeof(LPWSTR*) + (BYTE*)retval );
ParseCommandLine(lpCmdLine, &pdst);
pdst = (LPWSTR)( argcount*sizeof(LPWSTR*) + (BYTE*)retval );
pslot = (LPWSTR*)retval;
for (DWORD i = 0; i < argcount; i++)
{
*(pslot++) = pdst;
while (*pdst != W('\0'))
{
pdst++;
}
pdst++;
}
*pNumArgs = argcount;
return (LPWSTR*)retval;
}
//************************************************************************
// CQuickHeap
//
// A fast non-multithread-safe heap for short term use.
// Destroying the heap frees all blocks allocated from the heap.
// Blocks cannot be freed individually.
//
// The heap uses COM+ exceptions to report errors.
//
// The heap does not use any internal synchronization so it is not
// multithreadsafe.
//************************************************************************
CQuickHeap::CQuickHeap()
{
LIMITED_METHOD_CONTRACT;
m_pFirstQuickBlock = NULL;
m_pFirstBigQuickBlock = NULL;
m_pNextFree = NULL;
}
CQuickHeap::~CQuickHeap()
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
FORBID_FAULT;
}
CONTRACTL_END
QuickBlock *pQuickBlock = m_pFirstQuickBlock;
while (pQuickBlock) {
QuickBlock *ptmp = pQuickBlock;
pQuickBlock = pQuickBlock->m_next;
delete [] (BYTE*)ptmp;
}
pQuickBlock = m_pFirstBigQuickBlock;
while (pQuickBlock) {
QuickBlock *ptmp = pQuickBlock;
pQuickBlock = pQuickBlock->m_next;
delete [] (BYTE*)ptmp;
}
}
LPVOID CQuickHeap::Alloc(UINT sz)
{
CONTRACTL
{
THROWS;
GC_NOTRIGGER;
INJECT_FAULT(COMPlusThrowOM(););
} CONTRACTL_END;
sz = (sz+7) & ~7;
if ( sz > kBlockSize ) {
QuickBlock *pQuickBigBlock = (QuickBlock*) new BYTE[sz + sizeof(QuickBlock) - 1];
pQuickBigBlock->m_next = m_pFirstBigQuickBlock;
m_pFirstBigQuickBlock = pQuickBigBlock;
return pQuickBigBlock->m_bytes;
} else {
if (m_pNextFree == NULL || sz > (UINT)( &(m_pFirstQuickBlock->m_bytes[kBlockSize]) - m_pNextFree )) {
QuickBlock *pQuickBlock = (QuickBlock*) new BYTE[kBlockSize + sizeof(QuickBlock) - 1];
pQuickBlock->m_next = m_pFirstQuickBlock;
m_pFirstQuickBlock = pQuickBlock;
m_pNextFree = pQuickBlock->m_bytes;
}
LPVOID pv = m_pNextFree;
m_pNextFree += sz;
return pv;
}
}
//----------------------------------------------------------------------------
// Output functions that avoid the crt's.
//----------------------------------------------------------------------------
static
void NPrintToHandleA(HANDLE Handle, const char *pszString, size_t BytesToWrite)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
FORBID_FAULT;
}
CONTRACTL_END
if (Handle == INVALID_HANDLE_VALUE || Handle == NULL)
return;
BOOL success;
DWORD dwBytesWritten;
const size_t maxWriteFileSize = 32767; // This is somewhat arbitrary limit, but 2**16-1 doesn't work
while (BytesToWrite > 0) {
DWORD dwChunkToWrite = (DWORD) min(BytesToWrite, maxWriteFileSize);
// No CharNextExA on CoreSystem, we just assume no multi-byte characters (this code path shouldn't be
// used in the production codepath for currently supported CoreSystem based products anyway).
#ifndef FEATURE_CORESYSTEM
if (dwChunkToWrite < BytesToWrite) {
break;
// must go by char to find biggest string that will fit, taking DBCS chars into account
//dwChunkToWrite = 0;
//const char *charNext = pszString;
//while (dwChunkToWrite < maxWriteFileSize-2 && charNext) {
// charNext = CharNextExA(0, pszString+dwChunkToWrite, 0);
// dwChunkToWrite = (DWORD)(charNext - pszString);
//}
//if (dwChunkToWrite == 0)
// break;
}
#endif // !FEATURE_CORESYSTEM
// Try to write to handle. If this is not a CUI app, then this is probably
// not going to work unless the dev took special pains to set their own console
// handle during CreateProcess. So try it, but don't yell if it doesn't work in
// that case. Also, if we redirect stdout to a pipe then the pipe breaks (ie, we
// write to something like the UNIX head command), don't complain.
success = WriteFile(Handle, pszString, dwChunkToWrite, &dwBytesWritten, NULL);
if (!success)
{
#if defined(_DEBUG)
// This can happen if stdout is a closed pipe. This might not help
// much, but we'll have half a chance of seeing this.
OutputDebugStringA("CLR: Writing out an unhandled exception to stdout failed!\n");
OutputDebugStringA(pszString);
#endif //_DEBUG
break;
}
else {
_ASSERTE(dwBytesWritten == dwChunkToWrite);
}
pszString = pszString + dwChunkToWrite;
BytesToWrite -= dwChunkToWrite;
}
}
static
void PrintToHandleA(HANDLE Handle, const char *pszString)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
FORBID_FAULT;
}
CONTRACTL_END
size_t len = strlen(pszString);
NPrintToHandleA(Handle, pszString, len);
}
void PrintToStdOutA(const char *pszString) {
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
FORBID_FAULT;
}
CONTRACTL_END
HANDLE Handle = GetStdHandle(STD_OUTPUT_HANDLE);
PrintToHandleA(Handle, pszString);
}
void PrintToStdOutW(const WCHAR *pwzString)
{
CONTRACTL
{
THROWS;
GC_NOTRIGGER;
INJECT_FAULT(COMPlusThrowOM(););
}
CONTRACTL_END
MAKE_MULTIBYTE_FROMWIDE_BESTFIT(pStr, pwzString, GetConsoleOutputCP());
PrintToStdOutA(pStr);
}
void PrintToStdErrA(const char *pszString) {
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
FORBID_FAULT;
}
CONTRACTL_END
HANDLE Handle = GetStdHandle(STD_ERROR_HANDLE);
PrintToHandleA(Handle, pszString);
}
void PrintToStdErrW(const WCHAR *pwzString)
{
CONTRACTL
{
THROWS;
GC_NOTRIGGER;
INJECT_FAULT(COMPlusThrowOM(););
}
CONTRACTL_END
MAKE_MULTIBYTE_FROMWIDE_BESTFIT(pStr, pwzString, GetConsoleOutputCP());
PrintToStdErrA(pStr);
}
void NPrintToStdOutA(const char *pszString, size_t nbytes) {
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
FORBID_FAULT;
}
CONTRACTL_END
HANDLE Handle = GetStdHandle(STD_OUTPUT_HANDLE);
NPrintToHandleA(Handle, pszString, nbytes);
}
void NPrintToStdOutW(const WCHAR *pwzString, size_t nchars)
{
CONTRACTL
{
THROWS;
GC_NOTRIGGER;
INJECT_FAULT(COMPlusThrowOM(););
}
CONTRACTL_END
LPSTR pStr;
MAKE_MULTIBYTE_FROMWIDEN_BESTFIT(pStr, pwzString, (int)nchars, nbytes, GetConsoleOutputCP());
NPrintToStdOutA(pStr, nbytes);
}
void NPrintToStdErrA(const char *pszString, size_t nbytes) {
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
FORBID_FAULT;
}
CONTRACTL_END
HANDLE Handle = GetStdHandle(STD_ERROR_HANDLE);
NPrintToHandleA(Handle, pszString, nbytes);
}
void NPrintToStdErrW(const WCHAR *pwzString, size_t nchars)
{
CONTRACTL
{
THROWS;
GC_NOTRIGGER;
INJECT_FAULT(COMPlusThrowOM(););
}
CONTRACTL_END
LPSTR pStr;
MAKE_MULTIBYTE_FROMWIDEN_BESTFIT(pStr, pwzString, (int)nchars, nbytes, GetConsoleOutputCP());
NPrintToStdErrA(pStr, nbytes);
}
//----------------------------------------------------------------------------
//*****************************************************************************
// Compare VarLoc's
//*****************************************************************************
bool operator ==(const ICorDebugInfo::VarLoc &varLoc1,
const ICorDebugInfo::VarLoc &varLoc2)
{
STATIC_CONTRACT_NOTHROW;
STATIC_CONTRACT_GC_NOTRIGGER;
STATIC_CONTRACT_FORBID_FAULT;
if (varLoc1.vlType != varLoc2.vlType)
return false;
switch(varLoc1.vlType)
{
case ICorDebugInfo::VLT_REG:
case ICorDebugInfo::VLT_REG_BYREF:
return varLoc1.vlReg.vlrReg == varLoc2.vlReg.vlrReg;
case ICorDebugInfo::VLT_STK:
case ICorDebugInfo::VLT_STK_BYREF:
return varLoc1.vlStk.vlsBaseReg == varLoc2.vlStk.vlsBaseReg &&
varLoc1.vlStk.vlsOffset == varLoc2.vlStk.vlsOffset;
case ICorDebugInfo::VLT_REG_REG:
return varLoc1.vlRegReg.vlrrReg1 == varLoc2.vlRegReg.vlrrReg1 &&
varLoc1.vlRegReg.vlrrReg2 == varLoc2.vlRegReg.vlrrReg2;
case ICorDebugInfo::VLT_REG_STK:
return varLoc1.vlRegStk.vlrsReg == varLoc2.vlRegStk.vlrsReg &&
varLoc1.vlRegStk.vlrsStk.vlrssBaseReg == varLoc2.vlRegStk.vlrsStk.vlrssBaseReg &&
varLoc1.vlRegStk.vlrsStk.vlrssOffset == varLoc2.vlRegStk.vlrsStk.vlrssOffset;
case ICorDebugInfo::VLT_STK_REG:
return varLoc1.vlStkReg.vlsrStk.vlsrsBaseReg == varLoc2.vlStkReg.vlsrStk.vlsrsBaseReg &&
varLoc1.vlStkReg.vlsrStk.vlsrsOffset == varLoc2.vlStkReg.vlsrStk.vlsrsBaseReg &&
varLoc1.vlStkReg.vlsrReg == varLoc2.vlStkReg.vlsrReg;
case ICorDebugInfo::VLT_STK2:
return varLoc1.vlStk2.vls2BaseReg == varLoc2.vlStk2.vls2BaseReg &&
varLoc1.vlStk2.vls2Offset == varLoc2.vlStk2.vls2Offset;
case ICorDebugInfo::VLT_FPSTK:
return varLoc1.vlFPstk.vlfReg == varLoc2.vlFPstk.vlfReg;
default:
_ASSERTE(!"Bad vlType"); return false;
}
}
#endif // #ifndef DACCESS_COMPILE
//*****************************************************************************
// The following are used to read and write data given NativeVarInfo
// for primitive types. For ValueClasses, FALSE will be returned.
//*****************************************************************************
SIZE_T GetRegOffsInCONTEXT(ICorDebugInfo::RegNum regNum)
{
STATIC_CONTRACT_NOTHROW;
STATIC_CONTRACT_GC_NOTRIGGER;
STATIC_CONTRACT_FORBID_FAULT;
#ifdef _TARGET_X86_
switch(regNum)
{
case ICorDebugInfo::REGNUM_EAX: return offsetof(T_CONTEXT,Eax);
case ICorDebugInfo::REGNUM_ECX: return offsetof(T_CONTEXT,Ecx);
case ICorDebugInfo::REGNUM_EDX: return offsetof(T_CONTEXT,Edx);
case ICorDebugInfo::REGNUM_EBX: return offsetof(T_CONTEXT,Ebx);
// TODO: Fix AMBIENT_SP handling.
// AMBIENT_SP It isn't necessarily the same value as ESP. We probably shouldn't try
// and handle REGNUM_AMBIENT_SP here, and instead update our callers (eg.
// GetNativeVarVal) to handle this case explicitly. This logic should also be
// merged with the parallel (but correct in this case) logic in mscordbi.
case ICorDebugInfo::REGNUM_ESP:
case ICorDebugInfo::REGNUM_AMBIENT_SP:
return offsetof(T_CONTEXT,Esp);
case ICorDebugInfo::REGNUM_EBP: return offsetof(T_CONTEXT,Ebp);
case ICorDebugInfo::REGNUM_ESI: return offsetof(T_CONTEXT,Esi);
case ICorDebugInfo::REGNUM_EDI: return offsetof(T_CONTEXT,Edi);
default: _ASSERTE(!"Bad regNum"); return (SIZE_T) -1;
}
#elif defined(_TARGET_AMD64_)
switch(regNum)
{
case ICorDebugInfo::REGNUM_RAX: return offsetof(CONTEXT, Rax);
case ICorDebugInfo::REGNUM_RCX: return offsetof(CONTEXT, Rcx);
case ICorDebugInfo::REGNUM_RDX: return offsetof(CONTEXT, Rdx);
case ICorDebugInfo::REGNUM_RBX: return offsetof(CONTEXT, Rbx);
case ICorDebugInfo::REGNUM_RSP: return offsetof(CONTEXT, Rsp);
case ICorDebugInfo::REGNUM_RBP: return offsetof(CONTEXT, Rbp);
case ICorDebugInfo::REGNUM_RSI: return offsetof(CONTEXT, Rsi);
case ICorDebugInfo::REGNUM_RDI: return offsetof(CONTEXT, Rdi);
case ICorDebugInfo::REGNUM_R8: return offsetof(CONTEXT, R8);
case ICorDebugInfo::REGNUM_R9: return offsetof(CONTEXT, R9);
case ICorDebugInfo::REGNUM_R10: return offsetof(CONTEXT, R10);
case ICorDebugInfo::REGNUM_R11: return offsetof(CONTEXT, R11);
case ICorDebugInfo::REGNUM_R12: return offsetof(CONTEXT, R12);
case ICorDebugInfo::REGNUM_R13: return offsetof(CONTEXT, R13);
case ICorDebugInfo::REGNUM_R14: return offsetof(CONTEXT, R14);
case ICorDebugInfo::REGNUM_R15: return offsetof(CONTEXT, R15);
default: _ASSERTE(!"Bad regNum"); return (SIZE_T)(-1);
}
#elif defined(_TARGET_ARM_)
switch(regNum)
{
case ICorDebugInfo::REGNUM_R0: return offsetof(T_CONTEXT, R0);
case ICorDebugInfo::REGNUM_R1: return offsetof(T_CONTEXT, R1);
case ICorDebugInfo::REGNUM_R2: return offsetof(T_CONTEXT, R2);
case ICorDebugInfo::REGNUM_R3: return offsetof(T_CONTEXT, R3);
case ICorDebugInfo::REGNUM_R4: return offsetof(T_CONTEXT, R4);
case ICorDebugInfo::REGNUM_R5: return offsetof(T_CONTEXT, R5);
case ICorDebugInfo::REGNUM_R6: return offsetof(T_CONTEXT, R6);
case ICorDebugInfo::REGNUM_R7: return offsetof(T_CONTEXT, R7);
case ICorDebugInfo::REGNUM_R8: return offsetof(T_CONTEXT, R8);
case ICorDebugInfo::REGNUM_R9: return offsetof(T_CONTEXT, R9);
case ICorDebugInfo::REGNUM_R10: return offsetof(T_CONTEXT, R10);
case ICorDebugInfo::REGNUM_R11: return offsetof(T_CONTEXT, R11);
case ICorDebugInfo::REGNUM_R12: return offsetof(T_CONTEXT, R12);
case ICorDebugInfo::REGNUM_SP: return offsetof(T_CONTEXT, Sp);
case ICorDebugInfo::REGNUM_PC: return offsetof(T_CONTEXT, Pc);
case ICorDebugInfo::REGNUM_LR: return offsetof(T_CONTEXT, Lr);
case ICorDebugInfo::REGNUM_AMBIENT_SP: return offsetof(T_CONTEXT, Sp);
default: _ASSERTE(!"Bad regNum"); return (SIZE_T)(-1);
}
#elif defined(_TARGET_ARM64_)
switch(regNum)
{
case ICorDebugInfo::REGNUM_X0: return offsetof(T_CONTEXT, X0);
case ICorDebugInfo::REGNUM_X1: return offsetof(T_CONTEXT, X1);
case ICorDebugInfo::REGNUM_X2: return offsetof(T_CONTEXT, X2);
case ICorDebugInfo::REGNUM_X3: return offsetof(T_CONTEXT, X3);
case ICorDebugInfo::REGNUM_X4: return offsetof(T_CONTEXT, X4);
case ICorDebugInfo::REGNUM_X5: return offsetof(T_CONTEXT, X5);
case ICorDebugInfo::REGNUM_X6: return offsetof(T_CONTEXT, X6);
case ICorDebugInfo::REGNUM_X7: return offsetof(T_CONTEXT, X7);
case ICorDebugInfo::REGNUM_X8: return offsetof(T_CONTEXT, X8);
case ICorDebugInfo::REGNUM_X9: return offsetof(T_CONTEXT, X9);
case ICorDebugInfo::REGNUM_X10: return offsetof(T_CONTEXT, X10);
case ICorDebugInfo::REGNUM_X11: return offsetof(T_CONTEXT, X11);
case ICorDebugInfo::REGNUM_X12: return offsetof(T_CONTEXT, X12);
case ICorDebugInfo::REGNUM_X13: return offsetof(T_CONTEXT, X13);
case ICorDebugInfo::REGNUM_X14: return offsetof(T_CONTEXT, X14);
case ICorDebugInfo::REGNUM_X15: return offsetof(T_CONTEXT, X15);
case ICorDebugInfo::REGNUM_X16: return offsetof(T_CONTEXT, X16);
case ICorDebugInfo::REGNUM_X17: return offsetof(T_CONTEXT, X17);
case ICorDebugInfo::REGNUM_X18: return offsetof(T_CONTEXT, X18);
case ICorDebugInfo::REGNUM_X19: return offsetof(T_CONTEXT, X19);
case ICorDebugInfo::REGNUM_X20: return offsetof(T_CONTEXT, X20);
case ICorDebugInfo::REGNUM_X21: return offsetof(T_CONTEXT, X21);
case ICorDebugInfo::REGNUM_X22: return offsetof(T_CONTEXT, X22);
case ICorDebugInfo::REGNUM_X23: return offsetof(T_CONTEXT, X23);
case ICorDebugInfo::REGNUM_X24: return offsetof(T_CONTEXT, X24);
case ICorDebugInfo::REGNUM_X25: return offsetof(T_CONTEXT, X25);
case ICorDebugInfo::REGNUM_X26: return offsetof(T_CONTEXT, X26);
case ICorDebugInfo::REGNUM_X27: return offsetof(T_CONTEXT, X27);
case ICorDebugInfo::REGNUM_X28: return offsetof(T_CONTEXT, X28);
case ICorDebugInfo::REGNUM_FP: return offsetof(T_CONTEXT, Fp);
case ICorDebugInfo::REGNUM_LR: return offsetof(T_CONTEXT, Lr);
case ICorDebugInfo::REGNUM_SP: return offsetof(T_CONTEXT, Sp);
case ICorDebugInfo::REGNUM_PC: return offsetof(T_CONTEXT, Pc);
case ICorDebugInfo::REGNUM_AMBIENT_SP: return offsetof(T_CONTEXT, Sp);
default: _ASSERTE(!"Bad regNum"); return (SIZE_T)(-1);
}
#else
PORTABILITY_ASSERT("GetRegOffsInCONTEXT is not implemented on this platform.");
return (SIZE_T) -1;
#endif // _TARGET_X86_
}
SIZE_T DereferenceByRefVar(SIZE_T addr)
{
STATIC_CONTRACT_WRAPPER;
SIZE_T result = NULL;
#if defined(DACCESS_COMPILE)
HRESULT hr = DacReadAll(addr, &result, sizeof(result), false);
if (FAILED(hr))
{
result = NULL;
}
#else // !DACCESS_COMPILE
EX_TRY
{
AVInRuntimeImplOkayHolder AVOkay;
result = *(SIZE_T*)addr;
}
EX_CATCH
{
}
EX_END_CATCH(SwallowAllExceptions);
#endif // !DACCESS_COMPILE
return result;
}
// How are errors communicated to the caller?
ULONG NativeVarLocations(const ICorDebugInfo::VarLoc & varLoc,
PT_CONTEXT pCtx,
ULONG numLocs,
NativeVarLocation* locs)
{
STATIC_CONTRACT_NOTHROW;
STATIC_CONTRACT_GC_NOTRIGGER;
STATIC_CONTRACT_FORBID_FAULT;
_ASSERTE(numLocs >= MAX_NATIVE_VAR_LOCS);
bool fByRef = false;
switch(varLoc.vlType)
{
SIZE_T regOffs;
TADDR baseReg;
case ICorDebugInfo::VLT_REG_BYREF:
fByRef = true; // fall through
case ICorDebugInfo::VLT_REG:
regOffs = GetRegOffsInCONTEXT(varLoc.vlReg.vlrReg);
locs->addr = (ULONG64)(ULONG_PTR)pCtx + regOffs;
if (fByRef)
{
locs->addr = (ULONG64)DereferenceByRefVar((SIZE_T)locs->addr);
}
locs->size = sizeof(SIZE_T);
{
locs->contextReg = true;
}
return 1;
case ICorDebugInfo::VLT_STK_BYREF:
fByRef = true; // fall through
case ICorDebugInfo::VLT_STK:
regOffs = GetRegOffsInCONTEXT(varLoc.vlStk.vlsBaseReg);
baseReg = *(TADDR *)(regOffs + (BYTE*)pCtx);
locs->addr = baseReg + varLoc.vlStk.vlsOffset;
if (fByRef)
{
locs->addr = (ULONG64)DereferenceByRefVar((SIZE_T)locs->addr);
}
locs->size = sizeof(SIZE_T);
locs->contextReg = false;
return 1;
case ICorDebugInfo::VLT_REG_REG:
regOffs = GetRegOffsInCONTEXT(varLoc.vlRegReg.vlrrReg1);
locs->addr = (ULONG64)(ULONG_PTR)pCtx + regOffs;
locs->size = sizeof(SIZE_T);
locs->contextReg = true;
locs++;
regOffs = GetRegOffsInCONTEXT(varLoc.vlRegReg.vlrrReg2);
locs->addr = (ULONG64)(ULONG_PTR)pCtx + regOffs;
locs->size = sizeof(SIZE_T);
locs->contextReg = true;
return 2;
case ICorDebugInfo::VLT_REG_STK:
regOffs = GetRegOffsInCONTEXT(varLoc.vlRegStk.vlrsReg);
locs->addr = (ULONG64)(ULONG_PTR)pCtx + regOffs;
locs->size = sizeof(SIZE_T);
locs->contextReg = true;
locs++;
regOffs = GetRegOffsInCONTEXT(varLoc.vlRegStk.vlrsStk.vlrssBaseReg);
baseReg = *(TADDR *)(regOffs + (BYTE*)pCtx);
locs->addr = baseReg + varLoc.vlRegStk.vlrsStk.vlrssOffset;
locs->size = sizeof(SIZE_T);
locs->contextReg = false;
return 2;
case ICorDebugInfo::VLT_STK_REG:
regOffs = GetRegOffsInCONTEXT(varLoc.vlStkReg.vlsrStk.vlsrsBaseReg);
baseReg = *(TADDR *)(regOffs + (BYTE*)pCtx);
locs->addr = baseReg + varLoc.vlStkReg.vlsrStk.vlsrsOffset;
locs->size = sizeof(SIZE_T);
locs->contextReg = false;
locs++;
regOffs = GetRegOffsInCONTEXT(varLoc.vlStkReg.vlsrReg);
locs->addr = (ULONG64)(ULONG_PTR)pCtx + regOffs;
locs->size = sizeof(SIZE_T);
locs->contextReg = true;
return 2;
case ICorDebugInfo::VLT_STK2:
regOffs = GetRegOffsInCONTEXT(varLoc.vlStk2.vls2BaseReg);
baseReg = *(TADDR *)(regOffs + (BYTE*)pCtx);
locs->addr = baseReg + varLoc.vlStk2.vls2Offset;
locs->size = 2 * sizeof(SIZE_T);
locs->contextReg = false;
return 1;
case ICorDebugInfo::VLT_FPSTK:
_ASSERTE(!"NYI");
return 0;
default:
_ASSERTE(!"Bad locType");
return 0;
}
}
BOOL CompareFiles(HANDLE hFile1,HANDLE hFile2)
{
STATIC_CONTRACT_THROWS;
STATIC_CONTRACT_GC_NOTRIGGER;
BY_HANDLE_FILE_INFORMATION fileinfo1;
BY_HANDLE_FILE_INFORMATION fileinfo2;
if (!GetFileInformationByHandle(hFile1,&fileinfo1) ||
!GetFileInformationByHandle(hFile2,&fileinfo2))
ThrowLastError();
return fileinfo1.nFileIndexLow == fileinfo2.nFileIndexLow &&
fileinfo1.nFileIndexHigh == fileinfo2.nFileIndexHigh &&
fileinfo1.dwVolumeSerialNumber==fileinfo2.dwVolumeSerialNumber;
}
#ifndef DACCESS_COMPILE
// Returns the location at which the variable
// begins. Returns NULL for register vars. For reg-stack
// split, it'll return the addr of the stack part.
// This also works for VLT_REG (a single register).
SIZE_T *NativeVarStackAddr(const ICorDebugInfo::VarLoc & varLoc,
PCONTEXT pCtx)
{
STATIC_CONTRACT_NOTHROW;
STATIC_CONTRACT_GC_NOTRIGGER;
STATIC_CONTRACT_FORBID_FAULT;
SIZE_T *dwAddr = NULL;
bool fByRef = false;
switch(varLoc.vlType)
{
SIZE_T regOffs;
const BYTE * baseReg;
case ICorDebugInfo::VLT_REG_BYREF:
fByRef = true; // fall through
case ICorDebugInfo::VLT_REG:
regOffs = GetRegOffsInCONTEXT(varLoc.vlReg.vlrReg);
dwAddr = (SIZE_T *)(regOffs + (BYTE*)pCtx);
if (fByRef)
{
dwAddr = (SIZE_T*)(*dwAddr);
}
LOG((LF_CORDB, LL_INFO100, "NVSA: VLT_REG @ 0x%x (by ref = %d)\n", dwAddr, fByRef));
break;
case ICorDebugInfo::VLT_STK_BYREF:
fByRef = true; // fall through
case ICorDebugInfo::VLT_STK:
regOffs = GetRegOffsInCONTEXT(varLoc.vlStk.vlsBaseReg);
baseReg = (const BYTE *)*(SIZE_T *)(regOffs + (BYTE*)pCtx);
dwAddr = (SIZE_T *)(baseReg + varLoc.vlStk.vlsOffset);
if (fByRef)
{
dwAddr = (SIZE_T*)(*dwAddr);
}
LOG((LF_CORDB, LL_INFO100, "NVSA: VLT_STK @ 0x%x (by ref = %d)\n", dwAddr, fByRef));
break;
case ICorDebugInfo::VLT_STK2:
// <TODO>@TODO : VLT_STK2 is overloaded to also mean VLT_STK_n.
// return FALSE if n > 2;</TODO>
regOffs = GetRegOffsInCONTEXT(varLoc.vlStk2.vls2BaseReg);
baseReg = (const BYTE *)*(SIZE_T *)(regOffs + (BYTE*)pCtx);
dwAddr = (SIZE_T *)(baseReg + varLoc.vlStk2.vls2Offset);
LOG((LF_CORDB, LL_INFO100, "NVSA: VLT_STK_2 @ 0x%x\n",dwAddr));
break;
case ICorDebugInfo::VLT_REG_STK:
regOffs = GetRegOffsInCONTEXT(varLoc.vlRegStk.vlrsStk.vlrssBaseReg);
baseReg = (const BYTE *)*(SIZE_T *)(regOffs + (BYTE*)pCtx);
dwAddr = (SIZE_T *)(baseReg + varLoc.vlRegStk.vlrsStk.vlrssOffset);
LOG((LF_CORDB, LL_INFO100, "NVSA: REG_STK @ 0x%x\n",dwAddr));
break;
case ICorDebugInfo::VLT_STK_REG:
regOffs = GetRegOffsInCONTEXT(varLoc.vlStkReg.vlsrStk.vlsrsBaseReg);
baseReg = (const BYTE *)*(SIZE_T *)(regOffs + (BYTE*)pCtx);
dwAddr = (SIZE_T *)(baseReg + varLoc.vlStkReg.vlsrStk.vlsrsOffset);
LOG((LF_CORDB, LL_INFO100, "NVSA: STK_REG @ 0x%x\n",dwAddr));
break;
case ICorDebugInfo::VLT_REG_REG:
case ICorDebugInfo::VLT_FPSTK:
_ASSERTE(!"NYI"); break;
default:
_ASSERTE(!"Bad locType"); break;
}
return dwAddr;
}
#if defined(_WIN64)
void GetNativeVarValHelper(SIZE_T* dstAddrLow, SIZE_T* dstAddrHigh, SIZE_T* srcAddr, SIZE_T size)
{
if (size == 1)
*(BYTE*)dstAddrLow = *(BYTE*)srcAddr;
else if (size == 2)
*(USHORT*)dstAddrLow = *(USHORT*)srcAddr;
else if (size == 4)
*(ULONG*)dstAddrLow = *(ULONG*)srcAddr;
else if (size == 8)
*dstAddrLow = *srcAddr;
else if (size == 16)
{
*dstAddrLow = *srcAddr;
*dstAddrHigh = *(srcAddr+1);
}
else
{
_ASSERTE(!"util.cpp - unreachable code.\n");
UNREACHABLE();
}
}
#endif // _WIN64
bool GetNativeVarVal(const ICorDebugInfo::VarLoc & varLoc,
PCONTEXT pCtx,
SIZE_T * pVal1,
SIZE_T * pVal2
WIN64_ARG(SIZE_T cbSize))
{
STATIC_CONTRACT_NOTHROW;
STATIC_CONTRACT_GC_NOTRIGGER;
STATIC_CONTRACT_FORBID_FAULT;
switch(varLoc.vlType)
{
#if !defined(_WIN64)
SIZE_T regOffs;
case ICorDebugInfo::VLT_REG:
*pVal1 = *NativeVarStackAddr(varLoc,pCtx);
break;
case ICorDebugInfo::VLT_STK:
*pVal1 = *NativeVarStackAddr(varLoc,pCtx);
break;
case ICorDebugInfo::VLT_STK2:
*pVal1 = *NativeVarStackAddr(varLoc,pCtx);
*pVal2 = *(NativeVarStackAddr(varLoc,pCtx)+ 1);
break;
case ICorDebugInfo::VLT_REG_REG:
regOffs = GetRegOffsInCONTEXT(varLoc.vlRegReg.vlrrReg1);
*pVal1 = *(SIZE_T *)(regOffs + (BYTE*)pCtx);
LOG((LF_CORDB, LL_INFO100, "GNVV: STK_REG_REG 1 @ 0x%x\n",
(SIZE_T *)(regOffs + (BYTE*)pCtx)));
regOffs = GetRegOffsInCONTEXT(varLoc.vlRegReg.vlrrReg2);
*pVal2 = *(SIZE_T *)(regOffs + (BYTE*)pCtx);
LOG((LF_CORDB, LL_INFO100, "GNVV: STK_REG_REG 2 @ 0x%x\n",
(SIZE_T *)(regOffs + (BYTE*)pCtx)));
break;
case ICorDebugInfo::VLT_REG_STK:
regOffs = GetRegOffsInCONTEXT(varLoc.vlRegStk.vlrsReg);
*pVal1 = *(SIZE_T *)(regOffs + (BYTE*)pCtx);
LOG((LF_CORDB, LL_INFO100, "GNVV: STK_REG_STK reg @ 0x%x\n",
(SIZE_T *)(regOffs + (BYTE*)pCtx)));
*pVal2 = *NativeVarStackAddr(varLoc,pCtx);
break;
case ICorDebugInfo::VLT_STK_REG:
*pVal1 = *NativeVarStackAddr(varLoc,pCtx);
regOffs = GetRegOffsInCONTEXT(varLoc.vlStkReg.vlsrReg);
*pVal2 = *(SIZE_T *)(regOffs + (BYTE*)pCtx);
LOG((LF_CORDB, LL_INFO100, "GNVV: STK_STK_REG reg @ 0x%x\n",
(SIZE_T *)(regOffs + (BYTE*)pCtx)));
break;
case ICorDebugInfo::VLT_FPSTK:
_ASSERTE(!"NYI"); break;
#else // _WIN64
case ICorDebugInfo::VLT_REG:
case ICorDebugInfo::VLT_REG_FP:
case ICorDebugInfo::VLT_STK:
GetNativeVarValHelper(pVal1, pVal2, NativeVarStackAddr(varLoc, pCtx), cbSize);
break;
case ICorDebugInfo::VLT_REG_BYREF: // fall through
case ICorDebugInfo::VLT_STK_BYREF:
_ASSERTE(!"GNVV: This function should not be called for value types");
break;
#endif // _WIN64
default:
_ASSERTE(!"Bad locType"); break;
}
return true;
}
#if defined(_WIN64)
void SetNativeVarValHelper(SIZE_T* dstAddr, SIZE_T valueLow, SIZE_T valueHigh, SIZE_T size)
{
if (size == 1)
*(BYTE*)dstAddr = (BYTE)valueLow;
else if (size == 2)
*(USHORT*)dstAddr = (USHORT)valueLow;
else if (size == 4)
*(ULONG*)dstAddr = (ULONG)valueLow;
else if (size == 8)
*dstAddr = valueLow;
else if (size == 16)
{
*dstAddr = valueLow;
*(dstAddr+1) = valueHigh;
}
else
{
_ASSERTE(!"util.cpp - unreachable code.\n");
UNREACHABLE();
}
}
#endif // _WIN64
bool SetNativeVarVal(const ICorDebugInfo::VarLoc & varLoc,
PCONTEXT pCtx,
SIZE_T val1,
SIZE_T val2
WIN64_ARG(SIZE_T cbSize))
{
STATIC_CONTRACT_NOTHROW;
STATIC_CONTRACT_GC_NOTRIGGER;
STATIC_CONTRACT_FORBID_FAULT;
switch(varLoc.vlType)
{
#if !defined(_WIN64)
SIZE_T regOffs;
case ICorDebugInfo::VLT_REG:
*NativeVarStackAddr(varLoc,pCtx) = val1;
break;
case ICorDebugInfo::VLT_STK:
*NativeVarStackAddr(varLoc,pCtx) = val1;
break;
case ICorDebugInfo::VLT_STK2:
*NativeVarStackAddr(varLoc,pCtx) = val1;
*(NativeVarStackAddr(varLoc,pCtx)+ 1) = val2;
break;
case ICorDebugInfo::VLT_REG_REG:
regOffs = GetRegOffsInCONTEXT(varLoc.vlRegReg.vlrrReg1);
*(SIZE_T *)(regOffs + (BYTE*)pCtx) = val1;
LOG((LF_CORDB, LL_INFO100, "SNVV: STK_REG_REG 1 @ 0x%x\n",
(SIZE_T *)(regOffs + (BYTE*)pCtx)));
regOffs = GetRegOffsInCONTEXT(varLoc.vlRegReg.vlrrReg2);
*(SIZE_T *)(regOffs + (BYTE*)pCtx) = val2;
LOG((LF_CORDB, LL_INFO100, "SNVV: STK_REG_REG 2 @ 0x%x\n",
(SIZE_T *)(regOffs + (BYTE*)pCtx)));
break;
case ICorDebugInfo::VLT_REG_STK:
regOffs = GetRegOffsInCONTEXT(varLoc.vlRegStk.vlrsReg);
*(SIZE_T *)(regOffs + (BYTE*)pCtx) = val1;
LOG((LF_CORDB, LL_INFO100, "SNVV: STK_REG_STK reg @ 0x%x\n",
(SIZE_T *)(regOffs + (BYTE*)pCtx)));
*NativeVarStackAddr(varLoc,pCtx) = val2;
break;
case ICorDebugInfo::VLT_STK_REG:
*NativeVarStackAddr(varLoc,pCtx) = val1;
regOffs = GetRegOffsInCONTEXT(varLoc.vlStkReg.vlsrReg);
*(SIZE_T *)(regOffs + (BYTE*)pCtx) = val2;
LOG((LF_CORDB, LL_INFO100, "SNVV: STK_STK_REG reg @ 0x%x\n",
(SIZE_T *)(regOffs + (BYTE*)pCtx)));
break;
case ICorDebugInfo::VLT_FPSTK:
_ASSERTE(!"NYI"); break;
#else // _WIN64
case ICorDebugInfo::VLT_REG:
case ICorDebugInfo::VLT_REG_FP:
case ICorDebugInfo::VLT_STK:
SetNativeVarValHelper(NativeVarStackAddr(varLoc, pCtx), val1, val2, cbSize);
break;
case ICorDebugInfo::VLT_REG_BYREF: // fall through
case ICorDebugInfo::VLT_STK_BYREF:
_ASSERTE(!"GNVV: This function should not be called for value types");
break;
#endif // _WIN64
default:
_ASSERTE(!"Bad locType"); break;
}
return true;
}
HRESULT VMPostError( // Returned error.
HRESULT hrRpt, // Reported error.
...) // Error arguments.
{
CONTRACTL
{
NOTHROW;
GC_TRIGGERS;
MODE_ANY;
}
CONTRACTL_END;
GCX_PREEMP();
va_list marker; // User text.
va_start(marker, hrRpt);
hrRpt = PostErrorVA(hrRpt, marker);
va_end(marker);
return hrRpt;
}
#ifndef CROSSGEN_COMPILE
//-----------------------------------------------------------------------------
#ifndef FEATURE_PAL
// This function checks to see if GetLogicalProcessorInformation API is supported.
// On success, this function allocates a SLPI array, sets nEntries to number
// of elements in the SLPI array and returns a pointer to the SLPI array after filling it with information.
//
// Note: If successful, IsGLPISupported allocates memory for the SLPI array and expects the caller to
// free the memory once the caller is done using the information in the SLPI array.
//
// If the API is not supported or any failure, returns NULL
//
SYSTEM_LOGICAL_PROCESSOR_INFORMATION *IsGLPISupported( PDWORD nEntries )
{
DWORD cbslpi = 0;
DWORD dwNumElements = 0;
SYSTEM_LOGICAL_PROCESSOR_INFORMATION *pslpi = NULL;
// We setup the first call to GetLogicalProcessorInformation to fail so that we can obtain
// the size of the buffer required to allocate for the SLPI array that is returned
if (!GetLogicalProcessorInformation(pslpi, &cbslpi) &&
GetLastError() != ERROR_INSUFFICIENT_BUFFER)
{
// If we fail with anything other than an ERROR_INSUFFICIENT_BUFFER here, we punt with failure.
return NULL;
}
_ASSERTE(cbslpi);
// compute the number of SLPI entries required to hold the information returned from GLPI
dwNumElements = cbslpi / sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION);
// allocate a buffer in the free heap to hold an array of SLPI entries from GLPI, number of elements in the array is dwNumElements
pslpi = new (nothrow) SYSTEM_LOGICAL_PROCESSOR_INFORMATION[ dwNumElements ];
if(pslpi == NULL)
{
// the memory allocation failed
return NULL;
}
// Make call to GetLogicalProcessorInformation. Returns array of SLPI structures
if (!GetLogicalProcessorInformation(pslpi, &cbslpi))
{
// GetLogicalProcessorInformation failed
delete[] pslpi ; //Allocation was fine but the API call itself failed and so we are releasing the memory before the return NULL.
return NULL ;
}
// GetLogicalProcessorInformation successful, set nEntries to number of entries in the SLPI array
*nEntries = dwNumElements;
return pslpi; // return pointer to SLPI array
}//IsGLPISupported
// This function returns the size of highest level cache on the physical chip. If it cannot
// determine the cachesize this function returns 0.
size_t GetLogicalProcessorCacheSizeFromOS()
{
size_t cache_size = 0;
DWORD nEntries = 0;
// Try to use GetLogicalProcessorInformation API and get a valid pointer to the SLPI array if successful. Returns NULL
// if API not present or on failure.
SYSTEM_LOGICAL_PROCESSOR_INFORMATION *pslpi = IsGLPISupported(&nEntries) ;
if (pslpi == NULL)
{
// GetLogicalProcessorInformation not supported or failed.
goto Exit;
}
// Crack the information. Iterate through all the SLPI array entries for all processors in system.
// Will return the greatest of all the processor cache sizes or zero
{
size_t last_cache_size = 0;
for (DWORD i=0; i < nEntries; i++)
{
if (pslpi[i].Relationship == RelationCache)
{
last_cache_size = max(last_cache_size, pslpi[i].Cache.Size);
}
}
cache_size = last_cache_size;
}
Exit:
if(pslpi)
delete[] pslpi; // release the memory allocated for the SLPI array.
return cache_size;
}
#endif // !FEATURE_PAL
// This function returns the number of logical processors on a given physical chip. If it cannot
// determine the number of logical cpus, or the machine is not populated uniformly with the same
// type of processors, this function returns 0.
DWORD GetLogicalCpuCountFromOS()
{
// No CONTRACT possible because GetLogicalCpuCount uses SEH
STATIC_CONTRACT_THROWS;
STATIC_CONTRACT_GC_NOTRIGGER;
static DWORD val = 0;
DWORD retVal = 0;
#ifdef FEATURE_PAL
retVal = PAL_GetLogicalCpuCountFromOS();
#else // FEATURE_PAL
DWORD nEntries = 0;
DWORD prevcount = 0;
DWORD count = 1;
// Try to use GetLogicalProcessorInformation API and get a valid pointer to the SLPI array if successful. Returns NULL
// if API not present or on failure.
SYSTEM_LOGICAL_PROCESSOR_INFORMATION *pslpi = IsGLPISupported(&nEntries) ;
if (pslpi == NULL)
{
// GetLogicalProcessorInformation no supported
goto lDone;
}
for (DWORD j = 0; j < nEntries; j++)
{
if (pslpi[j].Relationship == RelationProcessorCore)
{
// LTP_PC_SMT indicates HT or SMT
if (pslpi[j].ProcessorCore.Flags == LTP_PC_SMT)
{
SIZE_T pmask = pslpi[j].ProcessorMask;
// Count the processors in the mask
//
// These are not the fastest bit counters. There may be processor intrinsics
// (which would be best), but there are variants faster than these:
// See http://en.wikipedia.org/wiki/Hamming_weight.
// This is the naive implementation.
#if !_WIN64
count = (pmask & 0x55555555) + ((pmask >> 1) & 0x55555555);
count = (count & 0x33333333) + ((count >> 2) & 0x33333333);
count = (count & 0x0F0F0F0F) + ((count >> 4) & 0x0F0F0F0F);
count = (count & 0x00FF00FF) + ((count >> 8) & 0x00FF00FF);
count = (count & 0x0000FFFF) + ((count >> 16)& 0x0000FFFF);
#else
pmask = (pmask & 0x5555555555555555ull) + ((pmask >> 1) & 0x5555555555555555ull);
pmask = (pmask & 0x3333333333333333ull) + ((pmask >> 2) & 0x3333333333333333ull);
pmask = (pmask & 0x0f0f0f0f0f0f0f0full) + ((pmask >> 4) & 0x0f0f0f0f0f0f0f0full);
pmask = (pmask & 0x00ff00ff00ff00ffull) + ((pmask >> 8) & 0x00ff00ff00ff00ffull);
pmask = (pmask & 0x0000ffff0000ffffull) + ((pmask >> 16) & 0x0000ffff0000ffffull);
pmask = (pmask & 0x00000000ffffffffull) + ((pmask >> 32) & 0x00000000ffffffffull);
count = static_cast<DWORD>(pmask);
#endif // !_WIN64 else
assert (count > 0);
if (prevcount)
{
if (count != prevcount)
{
retVal = 1; // masks are not symmetric
goto lDone;
}
}
prevcount = count;
}
}
}
retVal = count;
lDone:
if(pslpi)
{
delete[] pslpi; // release the memory allocated for the SLPI array
}
#endif // FEATURE_PAL
return retVal;
}
#if defined(_TARGET_X86_) || defined(_TARGET_AMD64_)
#define CACHE_WAY_BITS 0xFFC00000 // number of cache WAYS-Associativity is returned in EBX[31:22] (10 bits) using cpuid function 4
#define CACHE_PARTITION_BITS 0x003FF000 // number of cache Physical Partitions is returned in EBX[21:12] (10 bits) using cpuid function 4
#define CACHE_LINESIZE_BITS 0x00000FFF // Linesize returned in EBX[11:0] (12 bits) using cpuid function 4
// these are defined in src\VM\AMD64\asmhelpers.asm / cgenx86.cpp
extern "C" DWORD __stdcall getcpuid(DWORD arg1, unsigned char result[16]);
extern "C" DWORD __stdcall getextcpuid(DWORD arg1, DWORD arg2, unsigned char result[16]);
// The following function uses a deterministic mechanism for enumerating/calculating the details of the cache hierarychy at runtime
// by using deterministic cache parameter leafs on Prescott and higher processors.
// If successful, this function returns the cache size in bytes of the highest level on-die cache. Returns 0 on failure.
size_t GetIntelDeterministicCacheEnum()
{
LIMITED_METHOD_CONTRACT;
size_t retVal = 0;
unsigned char buffer[16];
size_t buflen = ARRAYSIZE(buffer);
DWORD maxCpuid = getextcpuid(0,0,buffer);
DWORD dwBuffer[4];
memcpy(dwBuffer, buffer, buflen);
if( (maxCpuid > 3) && (maxCpuid < 0x80000000) ) // Deterministic Cache Enum is Supported
{
DWORD dwCacheWays, dwCachePartitions, dwLineSize, dwSets;
DWORD retEAX = 0;
DWORD loopECX = 0;
size_t maxSize = 0;
size_t curSize = 0;
// Make First call to getextcpuid with loopECX=0. loopECX provides an index indicating which level to return information about.
// The second parameter is input EAX=4, to specify we want deterministic cache parameter leaf information.
// getextcpuid with EAX=4 should be executed with loopECX = 0,1, ... until retEAX [4:0] contains 00000b, indicating no more
// cache levels are supported.
getextcpuid(loopECX, 4, buffer);
memcpy(dwBuffer, buffer, buflen);
retEAX = dwBuffer[0]; // get EAX
int i = 0;
while(retEAX & 0x1f) // Crack cache enums and loop while EAX > 0
{
dwCacheWays = (dwBuffer[1] & CACHE_WAY_BITS) >> 22;
dwCachePartitions = (dwBuffer[1] & CACHE_PARTITION_BITS) >> 12;
dwLineSize = dwBuffer[1] & CACHE_LINESIZE_BITS;
dwSets = dwBuffer[2]; // ECX
curSize = (dwCacheWays+1)*(dwCachePartitions+1)*(dwLineSize+1)*(dwSets+1);
if (maxSize < curSize)
maxSize = curSize;
loopECX++;
getextcpuid(loopECX, 4, buffer);
memcpy(dwBuffer, buffer, buflen);
retEAX = dwBuffer[0] ; // get EAX[4:0];
i++;
if (i > 16) { // prevent infinite looping
return 0;
}
}
retVal = maxSize;
}
return retVal ;
}
// The following function uses CPUID function 2 with descriptor values to determine the cache size. This requires a-priori
// knowledge of the descriptor values. This works on gallatin and prior processors (already released processors).
// If successful, this function returns the cache size in bytes of the highest level on-die cache. Returns 0 on failure.
size_t GetIntelDescriptorValuesCache()
{
LIMITED_METHOD_CONTRACT;
size_t size = 0;
size_t maxSize = 0;
unsigned char buffer[16];
getextcpuid(0,2, buffer); // call CPUID with EAX function 2H to obtain cache descriptor values
for (int i = buffer[0]; --i >= 0; )
{
int j;
for (j = 3; j < 16; j += 4)
{
// if the information in a register is marked invalid, set to null descriptors
if (buffer[j] & 0x80)
{
buffer[j-3] = 0;
buffer[j-2] = 0;
buffer[j-1] = 0;
buffer[j-0] = 0;
}
}
for (j = 1; j < 16; j++)
{
switch (buffer[j]) // need to add descriptor values for 8M and 12M when they become known
{
case 0x41:
case 0x79:
size = 128*1024;
break;
case 0x42:
case 0x7A:
case 0x82:
size = 256*1024;
break;
case 0x22:
case 0x43:
case 0x7B:
case 0x83:
case 0x86:
size = 512*1024;
break;
case 0x23:
case 0x44:
case 0x7C:
case 0x84:
case 0x87:
size = 1024*1024;
break;
case 0x25:
case 0x45:
case 0x85:
size = 2*1024*1024;
break;
case 0x29:
size = 4*1024*1024;
break;
}
if (maxSize < size)
maxSize = size;
}
if (i > 0)
getextcpuid(0,2, buffer);
}
return maxSize;
}
#define NUM_LOGICAL_BITS 0x00FF0000 // EBX[23:16] Bit 16-23 in ebx contains the number of logical
// processors per physical processor (using cpuid function 1)
#define INITIAL_APIC_ID_BITS 0xFF000000 // EBX[31:24] Bits 24-31 (8 bits) return the 8-bit unique
// initial APIC ID for the processor this code is running on.
// Default value = 0xff if HT is not supported
// This function uses CPUID function 1 to return the number of logical processors on a given physical chip.
// It returns the number of logicals processors on a physical chip.
DWORD GetLogicalCpuCountFallback()
{
BYTE LogicalNum = 0;
BYTE PhysicalNum = 0;
DWORD lProcCounter = 0;
unsigned char buffer[16];
DWORD* dwBuffer = (DWORD*)buffer;
DWORD retVal = 1;
getextcpuid(0,1, buffer); //call CPUID with EAX=1
if (dwBuffer[3] & (1<<28)) // edx:bit 28 is HT bit
{
PhysicalNum = (BYTE) g_SystemInfo.dwNumberOfProcessors ; // total # of processors
LogicalNum = (BYTE) ((dwBuffer[1] & NUM_LOGICAL_BITS) >> 16); // # of logical per physical
if(LogicalNum > 1)
{
#ifdef FEATURE_CORESYSTEM
// CoreSystem doesn't expose GetProcessAffinityMask or SetProcessAffinityMask or anything
// functionally equivalent. Just assume 1:1 mapping if we get here (in reality we shouldn't since
// all CoreSystems support GetLogicalProcessorInformation so GetLogicalCpuCountFromOS should have
// taken care of everything.
goto fDone;
#else // FEATURE_CORESYSTEM
HANDLE hCurrentProcessHandle;
DWORD_PTR dwProcessAffinity;
DWORD_PTR dwSystemAffinity;
DWORD_PTR dwAffinityMask;
// Calculate the appropriate shifts and mask based on the
// number of logical processors.
BYTE i = 1, PHY_ID_MASK = 0xFF, PHY_ID_SHIFT = 0;
while (i < LogicalNum)
{
i *= 2;
PHY_ID_MASK <<= 1;
PHY_ID_SHIFT++;
}
hCurrentProcessHandle = GetCurrentProcess();
GetProcessAffinityMask(hCurrentProcessHandle, &dwProcessAffinity, &dwSystemAffinity);
// Check if available process affinity mask is equal to the available system affinity mask
// If the masks are equal, then all the processors the OS utilizes are available to the
// application.
if (dwProcessAffinity != dwSystemAffinity)
{
retVal = 0;
goto fDone;
}
dwAffinityMask = 1;
// loop over all processors, running APIC ID retrieval code starting
// with the first one by setting process affinity.
while (dwAffinityMask != 0 && dwAffinityMask <= dwProcessAffinity)
{
// Check if this CPU is available
if (dwAffinityMask & dwProcessAffinity)
{
if (SetProcessAffinityMask(hCurrentProcessHandle, dwAffinityMask))
{
BYTE APIC_ID, LOG_ID, PHY_ID;
__SwitchToThread(0, CALLER_LIMITS_SPINNING); // Give OS time to switch CPU
getextcpuid(0,1, buffer); //call cpuid with EAX=1
APIC_ID = (dwBuffer[1] & INITIAL_APIC_ID_BITS) >> 24;
LOG_ID = APIC_ID & ~PHY_ID_MASK;
PHY_ID = APIC_ID >> PHY_ID_SHIFT;
if (LOG_ID != 0)
lProcCounter++;
}
}
dwAffinityMask = dwAffinityMask << 1;
}
// Reset the processor affinity
SetProcessAffinityMask(hCurrentProcessHandle, dwProcessAffinity);
// Check if HT is enabled on all the processors
if(lProcCounter > 0 && (lProcCounter == (DWORD)(PhysicalNum / LogicalNum)))
{
retVal = lProcCounter;
goto fDone;
}
#endif // FEATURE_CORESYSTEM
}
}
fDone:
return retVal;
}
#endif // _TARGET_X86_ || _TARGET_AMD64_
// fix this if/when AMD does multicore or SMT
size_t GetCacheSizePerLogicalCpu(BOOL bTrueSize)
{
// No CONTRACT possible because GetCacheSizePerLogicalCpu uses SEH
STATIC_CONTRACT_NOTHROW;
STATIC_CONTRACT_GC_NOTRIGGER;
static size_t maxSize;
static size_t maxTrueSize;
if (maxSize)
{
// maxSize and maxTrueSize cached
if (bTrueSize)
{
return maxTrueSize;
}
else
{
return maxSize;
}
}
#if defined (_TARGET_X86_)
DefaultCatchFilterParam param;
param.pv = COMPLUS_EXCEPTION_EXECUTE_HANDLER;
PAL_TRY(DefaultCatchFilterParam *, pParam, ¶m)
{
unsigned char buffer[16];
DWORD* dwBuffer = (DWORD*)buffer;
DWORD maxCpuId = getcpuid(0, buffer);
if (dwBuffer[1] == 'uneG')
{
if (dwBuffer[3] == 'Ieni')
{
if (dwBuffer[2] == 'letn')
{
/*
//The following lines are commented because the OS API on Windows 2003 SP1 is not returning the Cache Relation information on x86.
//Once the OS API (LH and above) is updated with this information, we should start using the OS API to get the cache enumeration by
//uncommenting the lines below.
tempSize = GetLogicalProcessorCacheSizeFromOS(); //use OS API for cache enumeration on LH and above
*/
size_t tempSize = 0;
if (maxCpuId >= 2) // cpuid support for cache size determination is available
{
tempSize = GetIntelDeterministicCacheEnum(); // try to use use deterministic cache size enumeration
if (!tempSize)
{ // deterministic enumeration failed, fallback to legacy enumeration using descriptor values
tempSize = GetIntelDescriptorValuesCache();
}
}
// TODO: Currently GetLogicalCpuCountFromOS() and GetLogicalCpuCountFallback() are broken on
// multi-core processor, but we never call into those two functions since we don't halve the
// gen0size when it's prescott and above processor. We keep the old version here for earlier
// generation system(Northwood based), perf data suggests on those systems, halve gen0 size
// still boost the performance(ex:Biztalk boosts about 17%). So on earlier systems(Northwood)
// based, we still go ahead and halve gen0 size. The logic in GetLogicalCpuCountFromOS()
// and GetLogicalCpuCountFallback() works fine for those earlier generation systems.
// If it's a Prescott and above processor or Multi-core, perf data suggests not to halve gen0
// size at all gives us overall better performance.
// This is going to be fixed with a new version in orcas time frame.
if (maxCpuId >= 2 && !((maxCpuId > 3) && (maxCpuId < 0x80000000)))
{
DWORD logicalProcessorCount = GetLogicalCpuCountFromOS(); //try to obtain HT enumeration from OS API
if (!logicalProcessorCount)
{
logicalProcessorCount = GetLogicalCpuCountFallback(); // OS API failed, Fallback to HT enumeration using CPUID
}
if (logicalProcessorCount)
{
tempSize = tempSize / logicalProcessorCount;
}
}
// update maxSize once with final value
maxTrueSize = tempSize;
#ifdef _WIN64
if (maxCpuId >= 2)
{
// If we're running on a Prescott or greater core, EM64T tests
// show that starting with a gen0 larger than LLC improves performance.
// Thus, start with a gen0 size that is larger than the cache. The value of
// 3 is a reasonable tradeoff between workingset and performance.
maxSize = maxTrueSize * 3;
}
else
#endif
{
maxSize = maxTrueSize;
}
}
}
}
if (dwBuffer[1] == 'htuA') {
if (dwBuffer[3] == 'itne') {
if (dwBuffer[2] == 'DMAc') {
if (getcpuid(0x80000000, buffer) >= 0x80000006)
{
getcpuid(0x80000006, buffer);
DWORD dwL2CacheBits = dwBuffer[2];
DWORD dwL3CacheBits = dwBuffer[3];
maxTrueSize = (size_t)((dwL2CacheBits >> 16) * 1024); // L2 cache size in ECX bits 31-16
getcpuid(0x1, buffer);
DWORD dwBaseFamily = (dwBuffer[0] & (0xF << 8)) >> 8;
DWORD dwExtFamily = (dwBuffer[0] & (0xFF << 20)) >> 20;
DWORD dwFamily = dwBaseFamily >= 0xF ? dwBaseFamily + dwExtFamily : dwBaseFamily;
if (dwFamily >= 0x10)
{
BOOL bSkipAMDL3 = FALSE;
if (dwFamily == 0x10) // are we running on a Barcelona (Family 10h) processor?
{
// check model
DWORD dwBaseModel = (dwBuffer[0] & (0xF << 4)) >> 4 ;
DWORD dwExtModel = (dwBuffer[0] & (0xF << 16)) >> 16;
DWORD dwModel = dwBaseFamily >= 0xF ? (dwExtModel << 4) | dwBaseModel : dwBaseModel;
switch (dwModel)
{
case 0x2:
// 65nm parts do not benefit from larger Gen0
bSkipAMDL3 = TRUE;
break;
case 0x4:
default:
bSkipAMDL3 = FALSE;
}
}
if (!bSkipAMDL3)
{
// 45nm Greyhound parts (and future parts based on newer northbridge) benefit
// from increased gen0 size, taking L3 into account
getcpuid(0x80000008, buffer);
DWORD dwNumberOfCores = (dwBuffer[2] & (0xFF)) + 1; // NC is in ECX bits 7-0
DWORD dwL3CacheSize = (size_t)((dwL3CacheBits >> 18) * 512 * 1024); // L3 size in EDX bits 31-18 * 512KB
// L3 is shared between cores
dwL3CacheSize = dwL3CacheSize / dwNumberOfCores;
maxTrueSize += dwL3CacheSize; // due to exclusive caches, add L3 size (possibly zero) to L2
// L1 is too small to worry about, so ignore it
}
}
maxSize = maxTrueSize;
}
}
}
}
}
PAL_EXCEPT_FILTER(DefaultCatchFilter)
{
}
PAL_ENDTRY
#else
maxSize = maxTrueSize = GetLogicalProcessorCacheSizeFromOS() ; // Returns the size of the highest level processor cache
#endif
#if defined(_TARGET_ARM64_)
// Bigger gen0 size helps arm64 targets
maxSize = maxTrueSize * 3;
#endif
// printf("GetCacheSizePerLogicalCpu returns %d, adjusted size %d\n", maxSize, maxTrueSize);
if (bTrueSize)
return maxTrueSize;
else
return maxSize;
}
//---------------------------------------------------------------------
#ifndef FEATURE_PAL
HMODULE CLRGetModuleHandle(LPCWSTR lpModuleFileName)
{
// Don't use dynamic contract: will override GetLastError value
STATIC_CONTRACT_NOTHROW;
STATIC_CONTRACT_GC_NOTRIGGER;
STATIC_CONTRACT_FORBID_FAULT;
HMODULE hMod = WszGetModuleHandle(lpModuleFileName);
return hMod;
}
#endif // !FEATURE_PAL
LPVOID EEHeapAllocInProcessHeap(DWORD dwFlags, SIZE_T dwBytes);
BOOL EEHeapFreeInProcessHeap(DWORD dwFlags, LPVOID lpMem);
BOOL IsRuntimeStarted(DWORD *pdwStartupFlags);
void *GetCLRFunction(LPCSTR FunctionName)
{
void* func = NULL;
BEGIN_ENTRYPOINT_VOIDRET;
LIMITED_METHOD_CONTRACT;
if (strcmp(FunctionName, "EEHeapAllocInProcessHeap") == 0)
{
func = (void*)EEHeapAllocInProcessHeap;
}
else if (strcmp(FunctionName, "EEHeapFreeInProcessHeap") == 0)
{
func = (void*)EEHeapFreeInProcessHeap;
}
else if (strcmp(FunctionName, "IsRuntimeStarted") == 0)
{
func = (void*)IsRuntimeStarted;
}
else {
_ASSERTE ("Unknown function name");
func = NULL;
}
END_ENTRYPOINT_VOIDRET;
return func;
}
#endif // CROSSGEN_COMPILE
LPVOID
CLRMapViewOfFile(
IN HANDLE hFileMappingObject,
IN DWORD dwDesiredAccess,
IN DWORD dwFileOffsetHigh,
IN DWORD dwFileOffsetLow,
IN SIZE_T dwNumberOfBytesToMap,
IN LPVOID lpBaseAddress
)
{
#ifdef _DEBUG
#ifdef _TARGET_X86_
char *tmp = new (nothrow) char;
if (!tmp)
{
SetLastError(ERROR_OUTOFMEMORY);
return NULL;
}
delete tmp;
#endif // _TARGET_X86_
#endif // _DEBUG
LPVOID pv = MapViewOfFileEx(hFileMappingObject,dwDesiredAccess,dwFileOffsetHigh,dwFileOffsetLow,dwNumberOfBytesToMap,lpBaseAddress);
if (!pv)
{
if(GetLastError()==ERROR_SUCCESS)
SetLastError(ERROR_OUTOFMEMORY);
return NULL;
}
#ifdef _DEBUG
#ifdef _TARGET_X86_
if (pv && g_pConfig && g_pConfig->ShouldInjectFault(INJECTFAULT_MAPVIEWOFFILE))
{
MEMORY_BASIC_INFORMATION mbi;
memset(&mbi, 0, sizeof(mbi));
if (!ClrVirtualQuery(pv, &mbi, sizeof(mbi)))
{
if(GetLastError()==ERROR_SUCCESS)
SetLastError(ERROR_OUTOFMEMORY);
return NULL;
}
UnmapViewOfFile(pv);
pv = ClrVirtualAlloc(lpBaseAddress, mbi.RegionSize, MEM_RESERVE, PAGE_NOACCESS);
}
else
#endif // _TARGET_X86_
#endif // _DEBUG
{
}
if (!pv && GetLastError()==ERROR_SUCCESS)
SetLastError(ERROR_OUTOFMEMORY);
return pv;
}
BOOL
CLRUnmapViewOfFile(
IN LPVOID lpBaseAddress
)
{
STATIC_CONTRACT_ENTRY_POINT;
#ifdef _DEBUG
#ifdef _TARGET_X86_
if (g_pConfig && g_pConfig->ShouldInjectFault(INJECTFAULT_MAPVIEWOFFILE))
{
return ClrVirtualFree((LPVOID)lpBaseAddress, 0, MEM_RELEASE);
}
else
#endif // _TARGET_X86_
#endif // _DEBUG
{
BOOL result = UnmapViewOfFile(lpBaseAddress);
if (result)
{
}
return result;
}
}
#ifndef CROSSGEN_COMPILE
static HMODULE CLRLoadLibraryWorker(LPCWSTR lpLibFileName, DWORD *pLastError)
{
// Don't use dynamic contract: will override GetLastError value
STATIC_CONTRACT_NOTHROW;
STATIC_CONTRACT_GC_TRIGGERS;
STATIC_CONTRACT_FAULT;
HMODULE hMod;
UINT last = SetErrorMode(SEM_NOOPENFILEERRORBOX|SEM_FAILCRITICALERRORS);
{
INDEBUG(PEDecoder::ForceRelocForDLL(lpLibFileName));
hMod = WszLoadLibrary(lpLibFileName);
*pLastError = GetLastError();
}
SetErrorMode(last);
return hMod;
}
HMODULE CLRLoadLibrary(LPCWSTR lpLibFileName)
{
// Don't use dynamic contract: will override GetLastError value
STATIC_CONTRACT_NOTHROW;
STATIC_CONTRACT_GC_TRIGGERS;
STATIC_CONTRACT_FAULT;
DWORD dwLastError = 0;
HMODULE hmod = 0;
hmod = CLRLoadLibraryWorker(lpLibFileName, &dwLastError);
SetLastError(dwLastError);
return hmod;
}
#ifndef FEATURE_PAL
static HMODULE CLRLoadLibraryExWorker(LPCWSTR lpLibFileName, HANDLE hFile, DWORD dwFlags, DWORD *pLastError)
{
// Don't use dynamic contract: will override GetLastError value
STATIC_CONTRACT_NOTHROW;
STATIC_CONTRACT_GC_TRIGGERS;
STATIC_CONTRACT_FAULT;
HMODULE hMod;
UINT last = SetErrorMode(SEM_NOOPENFILEERRORBOX|SEM_FAILCRITICALERRORS);
{
INDEBUG(PEDecoder::ForceRelocForDLL(lpLibFileName));
hMod = WszLoadLibraryEx(lpLibFileName, hFile, dwFlags);
*pLastError = GetLastError();
}
SetErrorMode(last);
return hMod;
}
HMODULE CLRLoadLibraryEx(LPCWSTR lpLibFileName, HANDLE hFile, DWORD dwFlags)
{
// Don't use dynamic contract: will override GetLastError value
// This will throw in the case of SO
//STATIC_CONTRACT_NOTHROW;
STATIC_CONTRACT_GC_TRIGGERS;
STATIC_CONTRACT_FAULT;
DWORD lastError = ERROR_SUCCESS;
HMODULE hmod = NULL;
hmod = CLRLoadLibraryExWorker(lpLibFileName, hFile, dwFlags, &lastError);
SetLastError(lastError);
return hmod;
}
#endif // !FEATURE_PAL
BOOL CLRFreeLibrary(HMODULE hModule)
{
// Don't use dynamic contract: will override GetLastError value
STATIC_CONTRACT_NOTHROW;
STATIC_CONTRACT_GC_TRIGGERS;
STATIC_CONTRACT_FORBID_FAULT;
return FreeLibrary(hModule);
}
#endif // CROSSGEN_COMPILE
#endif // #ifndef DACCESS_COMPILE
GPTR_IMPL(JITNotification, g_pNotificationTable);
GVAL_IMPL(ULONG32, g_dacNotificationFlags);
BOOL IsValidMethodCodeNotification(USHORT Notification)
{
// If any bit is on other than that given by a valid combination of flags, no good.
if (Notification & ~(
CLRDATA_METHNOTIFY_NONE |
CLRDATA_METHNOTIFY_GENERATED |
CLRDATA_METHNOTIFY_DISCARDED))
{
return FALSE;
}
return TRUE;
}
JITNotifications::JITNotifications(JITNotification *jitTable)
{
LIMITED_METHOD_CONTRACT;
if (jitTable)
{
// Bookkeeping info is held in the first slot
m_jitTable = jitTable + 1;
}
else
{
m_jitTable = NULL;
}
}
BOOL JITNotifications::FindItem(TADDR clrModule, mdToken token, UINT *indexOut)
{
LIMITED_METHOD_CONTRACT;
if (m_jitTable == NULL)
{
return FALSE;
}
if (indexOut == NULL)
{
return FALSE;
}
UINT Length = GetLength();
for(UINT i=0; i < Length; i++)
{
JITNotification *pCurrent = m_jitTable + i;
if (!pCurrent->IsFree() &&
pCurrent->clrModule == clrModule &&
pCurrent->methodToken == token)
{
*indexOut = i;
return TRUE;
}
}
return FALSE;
}
// if clrModule is NULL, all active notifications are changed to NType
BOOL JITNotifications::SetAllNotifications(TADDR clrModule,USHORT NType,BOOL *changedOut)
{
if (m_jitTable == NULL)
{
return FALSE;
}
if (changedOut == NULL)
{
return FALSE;
}
*changedOut = FALSE;
UINT Length = GetLength();
for(UINT i=0; i < Length; i++)
{
JITNotification *pCurrent = m_jitTable + i;
if (!pCurrent->IsFree() &&
((clrModule == NULL) || (pCurrent->clrModule == clrModule))&&
pCurrent->state != NType)
{
pCurrent->state = NType;
*changedOut = TRUE;
}
}
if (*changedOut && NType == CLRDATA_METHNOTIFY_NONE)
{
// Need to recompute length if we removed notifications
for (UINT iCurrent=Length; iCurrent > 0; iCurrent--)
{
JITNotification *pCurrent = m_jitTable + (iCurrent - 1);
if (pCurrent->IsFree())
{
DecrementLength();
}
}
}
return TRUE;
}
BOOL JITNotifications::SetNotification(TADDR clrModule, mdToken token, USHORT NType)
{
UINT iIndex;
if (!IsActive())
{
return FALSE;
}
if (clrModule == NULL)
{
return FALSE;
}
if (NType == CLRDATA_METHNOTIFY_NONE)
{
// Remove an item if it exists
if (FindItem(clrModule, token, &iIndex))
{
JITNotification *pItem = m_jitTable + iIndex;
pItem->SetFree();
_ASSERTE(iIndex < GetLength());
// Update highest?
if (iIndex == (GetLength()-1))
{
DecrementLength();
}
}
return TRUE;
}
if (FindItem(clrModule, token, &iIndex))
{
JITNotification *pItem = m_jitTable + iIndex;
_ASSERTE(pItem->IsFree() == FALSE);
pItem->state = NType;
return TRUE;
}
// Find first free item
UINT iFirstFree = GetLength();
for (UINT i = 0; i < iFirstFree; i++)
{
JITNotification *pCurrent = m_jitTable + i;
if (pCurrent->state == CLRDATA_METHNOTIFY_NONE)
{
iFirstFree = i;
break;
}
}
if (iFirstFree == GetLength() &&
iFirstFree == GetTableSize())
{
// No more room
return FALSE;
}
JITNotification *pCurrent = m_jitTable + iFirstFree;
pCurrent->SetState(clrModule, token, NType);
if (iFirstFree == GetLength())
{
IncrementLength();
}
return TRUE;
}
UINT JITNotifications::GetLength()
{
LIMITED_METHOD_CONTRACT;
_ASSERTE(IsActive());
if (!IsActive())
{
return 0;
}
return (UINT) (m_jitTable - 1)->methodToken;
}
void JITNotifications::IncrementLength()
{
_ASSERTE(IsActive());
if (!IsActive())
{
return;
}
UINT *pShort = (UINT *) &((m_jitTable - 1)->methodToken);
(*pShort)++;
}
void JITNotifications::DecrementLength()
{
_ASSERTE(IsActive());
if (!IsActive())
{
return;
}
UINT *pShort = (UINT *) &((m_jitTable - 1)->methodToken);
(*pShort)--;
}
UINT JITNotifications::GetTableSize()
{
_ASSERTE(IsActive());
if (!IsActive())
{
return 0;
}
return ((UINT) (m_jitTable - 1)->clrModule);
}
USHORT JITNotifications::Requested(TADDR clrModule, mdToken token)
{
LIMITED_METHOD_CONTRACT;
UINT iIndex;
if (FindItem(clrModule, token, &iIndex))
{
JITNotification *pItem = m_jitTable + iIndex;
_ASSERTE(pItem->IsFree() == FALSE);
return pItem->state;
}
return CLRDATA_METHNOTIFY_NONE;
}
#ifdef DACCESS_COMPILE
JITNotification *JITNotifications::InitializeNotificationTable(UINT TableSize)
{
// We use the first entry in the table for recordkeeping info.
JITNotification *retTable = new (nothrow) JITNotification[TableSize+1];
if (retTable)
{
// Set the length
UINT *pUint = (UINT *) &(retTable->methodToken);
*pUint = 0;
// Set the table size
pUint = (UINT *) &(retTable->clrModule);
*pUint = TableSize;
}
return retTable;
}
template <class NotificationClass>
BOOL UpdateOutOfProcTable(__GlobalPtr<NotificationClass*, DPTR(NotificationClass)> pHostTable, NotificationClass* copyFrom, UINT tableSize)
{
ClrSafeInt<ULONG32> allocSize = S_SIZE_T(sizeof(NotificationClass)) * ClrSafeInt<UINT>(tableSize);
if (allocSize.IsOverflow())
{
return FALSE;
}
if (dac_cast<TADDR>(pHostTable) == NULL)
{
// The table has not been initialized in the target. Allocate space for it and update the pointer
// in the target so that we'll use this allocated memory from now on. Note that we never free this
// memory, but this isn't a big deal because it's only a single allocation.
TADDR Location;
if (DacAllocVirtual(0, allocSize.Value(),
MEM_COMMIT, PAGE_READWRITE, false,
&Location) != S_OK)
{
return FALSE;
}
DPTR(DPTR(NotificationClass)) ppTable = &pHostTable;
*ppTable = DPTR(NotificationClass)(Location);
if (DacWriteHostInstance(ppTable,false) != S_OK)
{
return FALSE;
}
}
// We store recordkeeping info right before the m_jitTable pointer, that must be written as well.
if (DacWriteAll(dac_cast<TADDR>(pHostTable), copyFrom,
allocSize.Value(), false) != S_OK)
{
return FALSE;
}
return TRUE;
}
BOOL JITNotifications::UpdateOutOfProcTable()
{
return ::UpdateOutOfProcTable<JITNotification>(g_pNotificationTable, m_jitTable - 1, GetTableSize() + 1);
}
#endif // DACCESS_COMPILE
GPTR_IMPL(GcNotification, g_pGcNotificationTable);
GcNotifications::GcNotifications(GcNotification *gcTable)
{
LIMITED_METHOD_CONTRACT;
if (gcTable)
{
// Bookkeeping info is held in the first slot
m_gcTable = gcTable + 1;
}
else
{
m_gcTable = NULL;
}
}
BOOL GcNotifications::FindItem(GcEvtArgs ev_, UINT *indexOut)
{
LIMITED_METHOD_CONTRACT;
if (m_gcTable == NULL)
{
return FALSE;
}
if (indexOut == NULL)
{
return FALSE;
}
UINT length = Length();
for (UINT i = 0; i < length; i++)
{
if (m_gcTable[i].IsMatch(ev_))
{
*indexOut = i;
return TRUE;
}
}
return FALSE;
}
BOOL GcNotifications::SetNotification(GcEvtArgs ev)
{
if (!IsActive())
{
return FALSE;
}
if (ev.typ < 0 || ev.typ >= GC_EVENT_TYPE_MAX)
{
return FALSE;
}
// build the "match" event
GcEvtArgs evStar = { ev.typ };
switch (ev.typ)
{
case GC_MARK_END:
// specify mark event matching all generations
evStar.condemnedGeneration = -1;
break;
default:
break;
}
// look for the entry that matches the evStar argument
UINT idx;
if (!FindItem(evStar, &idx))
{
// Find first free item
UINT iFirstFree = Length();
for (UINT i = 0; i < iFirstFree; i++)
{
GcNotification *pCurrent = m_gcTable + i;
if (pCurrent->IsFree())
{
iFirstFree = i;
break;
}
}
if (iFirstFree == Length() &&
iFirstFree == GetTableSize())
{
// No more room
return FALSE;
}
// guarantee the free cell is zeroed out
m_gcTable[iFirstFree].SetFree();
idx = iFirstFree;
}
// Now update the state
m_gcTable[idx].ev.typ = ev.typ;
switch (ev.typ)
{
case GC_MARK_END:
if (ev.condemnedGeneration == 0)
{
m_gcTable[idx].SetFree();
}
else
{
m_gcTable[idx].ev.condemnedGeneration |= ev.condemnedGeneration;
}
break;
default:
break;
}
// and if needed, update the array's length
if (idx == Length())
{
IncrementLength();
}
return TRUE;
}
GARY_IMPL(size_t, g_clrNotificationArguments, MAX_CLR_NOTIFICATION_ARGS);
#ifdef DACCESS_COMPILE
GcNotification *GcNotifications::InitializeNotificationTable(UINT TableSize)
{
// We use the first entry in the table for recordkeeping info.
GcNotification *retTable = new (nothrow) GcNotification[TableSize+1];
if (retTable)
{
// Set the length
UINT *pUint = (UINT *) &(retTable[0].ev.typ);
*pUint = 0;
// Set the table size
++pUint;
*pUint = TableSize;
}
return retTable;
}
BOOL GcNotifications::UpdateOutOfProcTable()
{
return ::UpdateOutOfProcTable<GcNotification>(g_pGcNotificationTable, m_gcTable - 1, GetTableSize() + 1);
}
#else // DACCESS_COMPILE
static CrstStatic g_clrNotificationCrst;
void DACRaiseException(TADDR *args, UINT argCount)
{
STATIC_CONTRACT_NOTHROW;
STATIC_CONTRACT_GC_NOTRIGGER;
STATIC_CONTRACT_MODE_ANY;
struct Param
{
TADDR *args;
UINT argCount;
} param;
param.args = args;
param.argCount = argCount;
PAL_TRY(Param *, pParam, ¶m)
{
RaiseException(CLRDATA_NOTIFY_EXCEPTION, 0, pParam->argCount, (ULONG_PTR *)pParam->args);
}
PAL_EXCEPT(EXCEPTION_EXECUTE_HANDLER)
{
}
PAL_ENDTRY
}
void DACNotifyExceptionHelper(TADDR *args, UINT argCount)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
}
CONTRACTL_END;
_ASSERTE(argCount <= MAX_CLR_NOTIFICATION_ARGS);
if (IsDebuggerPresent() && !CORDebuggerAttached())
{
CrstHolder lh(&g_clrNotificationCrst);
for (UINT i = 0; i < argCount; i++)
{
g_clrNotificationArguments[i] = args[i];
}
DACRaiseException(args, argCount);
g_clrNotificationArguments[0] = NULL;
}
}
void InitializeClrNotifications()
{
g_clrNotificationCrst.Init(CrstClrNotification, CRST_UNSAFE_ANYMODE);
g_clrNotificationArguments[0] = NULL;
}
// <TODO> FIX IN BETA 2
//
// g_dacNotificationFlags is only modified by the DAC and therefore the
// optmizer can assume that it will always be its default value and has
// been seen to eliminate the code in DoModuleLoadNotification,
// etc... such that DAC notifications are no longer sent.
//
// TODO: fix this in Beta 2
// the RIGHT fix is to make g_dacNotificationFlags volatile, but currently
// we don't have DAC macros to do that. Additionally, there are a number
// of other places we should look at DAC definitions to determine if they
// should be also declared volatile.
//
// for now we just turn off optimization for these guys
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable: 4748)
#pragma optimize("", off)
#endif // _MSC_VER
#if defined(FEATURE_GDBJIT)
#include "gdbjit.h"
#endif // FEATURE_GDBJIT
// called from the runtime
void DACNotify::DoJITNotification(MethodDesc *MethodDescPtr, TADDR NativeCodeLocation)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_PREEMPTIVE;
}
CONTRACTL_END;
TADDR Args[3] = { JIT_NOTIFICATION2, (TADDR) MethodDescPtr, NativeCodeLocation };
DACNotifyExceptionHelper(Args, 3);
}
void DACNotify::DoJITPitchingNotification(MethodDesc *MethodDescPtr)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_PREEMPTIVE;
}
CONTRACTL_END;
#if defined(FEATURE_GDBJIT) && defined(FEATURE_PAL) && !defined(CROSSGEN_COMPILE)
NotifyGdb::MethodPitched(MethodDescPtr);
#endif
TADDR Args[2] = { JIT_PITCHING_NOTIFICATION, (TADDR) MethodDescPtr };
DACNotifyExceptionHelper(Args, 2);
}
void DACNotify::DoModuleLoadNotification(Module *ModulePtr)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_PREEMPTIVE;
}
CONTRACTL_END;
if ((g_dacNotificationFlags & CLRDATA_NOTIFY_ON_MODULE_LOAD) != 0)
{
TADDR Args[2] = { MODULE_LOAD_NOTIFICATION, (TADDR) ModulePtr};
DACNotifyExceptionHelper(Args, 2);
}
}
void DACNotify::DoModuleUnloadNotification(Module *ModulePtr)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_PREEMPTIVE;
}
CONTRACTL_END;
if ((g_dacNotificationFlags & CLRDATA_NOTIFY_ON_MODULE_UNLOAD) != 0)
{
TADDR Args[2] = { MODULE_UNLOAD_NOTIFICATION, (TADDR) ModulePtr};
DACNotifyExceptionHelper(Args, 2);
}
}
void DACNotify::DoExceptionNotification(Thread* ThreadPtr)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_PREEMPTIVE;
}
CONTRACTL_END;
if ((g_dacNotificationFlags & CLRDATA_NOTIFY_ON_EXCEPTION) != 0)
{
TADDR Args[2] = { EXCEPTION_NOTIFICATION, (TADDR) ThreadPtr};
DACNotifyExceptionHelper(Args, 2);
}
}
void DACNotify::DoGCNotification(const GcEvtArgs& args)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_COOPERATIVE;
}
CONTRACTL_END;
if (args.typ == GC_MARK_END)
{
TADDR Args[3] = { GC_NOTIFICATION, (TADDR) args.typ, (TADDR) args.condemnedGeneration };
DACNotifyExceptionHelper(Args, 3);
}
}
void DACNotify::DoExceptionCatcherEnterNotification(MethodDesc *MethodDescPtr, DWORD nativeOffset)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_COOPERATIVE;
}
CONTRACTL_END;
if ((g_dacNotificationFlags & CLRDATA_NOTIFY_ON_EXCEPTION_CATCH_ENTER) != 0)
{
TADDR Args[3] = { CATCH_ENTER_NOTIFICATION, (TADDR) MethodDescPtr, (TADDR)nativeOffset };
DACNotifyExceptionHelper(Args, 3);
}
}
#ifdef _MSC_VER
#pragma optimize("", on)
#pragma warning(pop)
#endif // _MSC_VER
// </TODO>
#endif // DACCESS_COMPILE
// called from the DAC
int DACNotify::GetType(TADDR Args[])
{
// Type is an enum, and will thus fit into an int.
return static_cast<int>(Args[0]);
}
BOOL DACNotify::ParseJITNotification(TADDR Args[], TADDR& MethodDescPtr, TADDR& NativeCodeLocation)
{
_ASSERTE(Args[0] == JIT_NOTIFICATION2);
if (Args[0] != JIT_NOTIFICATION2)
{
return FALSE;
}
MethodDescPtr = Args[1];
NativeCodeLocation = Args[2];
return TRUE;
}
BOOL DACNotify::ParseJITPitchingNotification(TADDR Args[], TADDR& MethodDescPtr)
{
_ASSERTE(Args[0] == JIT_PITCHING_NOTIFICATION);
if (Args[0] != JIT_PITCHING_NOTIFICATION)
{
return FALSE;
}
MethodDescPtr = Args[1];
return TRUE;
}
BOOL DACNotify::ParseModuleLoadNotification(TADDR Args[], TADDR& Module)
{
_ASSERTE(Args[0] == MODULE_LOAD_NOTIFICATION);
if (Args[0] != MODULE_LOAD_NOTIFICATION)
{
return FALSE;
}
Module = Args[1];
return TRUE;
}
BOOL DACNotify::ParseModuleUnloadNotification(TADDR Args[], TADDR& Module)
{
_ASSERTE(Args[0] == MODULE_UNLOAD_NOTIFICATION);
if (Args[0] != MODULE_UNLOAD_NOTIFICATION)
{
return FALSE;
}
Module = Args[1];
return TRUE;
}
BOOL DACNotify::ParseExceptionNotification(TADDR Args[], TADDR& ThreadPtr)
{
_ASSERTE(Args[0] == EXCEPTION_NOTIFICATION);
if (Args[0] != EXCEPTION_NOTIFICATION)
{
return FALSE;
}
ThreadPtr = Args[1];
return TRUE;
}
BOOL DACNotify::ParseGCNotification(TADDR Args[], GcEvtArgs& args)
{
_ASSERTE(Args[0] == GC_NOTIFICATION);
if (Args[0] != GC_NOTIFICATION)
{
return FALSE;
}
BOOL bRet = FALSE;
args.typ = (GcEvt_t) Args[1];
switch (args.typ)
{
case GC_MARK_END:
{
// The condemnedGeneration is an int.
args.condemnedGeneration = static_cast<int>(Args[2]);
bRet = TRUE;
break;
}
default:
bRet = FALSE;
break;
}
return bRet;
}
BOOL DACNotify::ParseExceptionCatcherEnterNotification(TADDR Args[], TADDR& MethodDescPtr, DWORD& nativeOffset)
{
_ASSERTE(Args[0] == CATCH_ENTER_NOTIFICATION);
if (Args[0] != CATCH_ENTER_NOTIFICATION)
{
return FALSE;
}
MethodDescPtr = Args[1];
nativeOffset = (DWORD) Args[2];
return TRUE;
}
static BOOL TrustMeIAmSafe(void *pLock)
{
LIMITED_METHOD_CONTRACT;
return TRUE;
}
LockOwner g_lockTrustMeIAmThreadSafe = { NULL, TrustMeIAmSafe };
static DangerousNonHostedSpinLock g_randomLock;
static CLRRandom g_random;
int GetRandomInt(int maxVal)
{
#ifndef CROSSGEN_COMPILE
// Use the thread-local Random instance if possible
Thread* pThread = GetThread();
if (pThread)
return pThread->GetRandom()->Next(maxVal);
#endif
// No Thread object - need to fall back to the global generator.
// In DAC builds we don't need the lock (DAC is single-threaded) and can't get it anyway (DNHSL isn't supported)
#ifndef DACCESS_COMPILE
DangerousNonHostedSpinLockHolder lh(&g_randomLock);
#endif
if (!g_random.IsInitialized())
g_random.Init();
return g_random.Next(maxVal);
}
// These wrap the SString:L:CompareCaseInsenstive function in a way that makes it
// easy to fix code that uses _stricmp. _stricmp should be avoided as it uses the current
// C-runtime locale rather than the invariance culture.
//
// Note that unlike the real _stricmp, these functions unavoidably have a throws/gc_triggers/inject_fault
// contract. So if need a case-insensitive comparison in a place where you can't tolerate this contract,
// you've got a problem.
int __cdecl stricmpUTF8(const char* szStr1, const char* szStr2)
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
INJECT_FAULT(COMPlusThrowOM());
}
CONTRACTL_END
SString sStr1 (SString::Utf8, szStr1);
SString sStr2 (SString::Utf8, szStr2);
return sStr1.CompareCaseInsensitive(sStr2);
}
#ifndef DACCESS_COMPILE
//
//
// COMCharacter and Helper functions
//
//
#ifndef FEATURE_PAL
/*============================GetCharacterInfoHelper============================
**Determines character type info (digit, whitespace, etc) for the given char.
**Args: c is the character on which to operate.
** CharInfoType is one of CT_CTYPE1, CT_CTYPE2, CT_CTYPE3 and specifies the type
** of information being requested.
**Returns: The bitmask returned by GetStringTypeEx. The caller needs to know
** how to interpret this.
**Exceptions: ArgumentException if GetStringTypeEx fails.
==============================================================================*/
INT32 GetCharacterInfoHelper(WCHAR c, INT32 CharInfoType)
{
WRAPPER_NO_CONTRACT;
unsigned short result=0;
if (!GetStringTypeEx(LOCALE_USER_DEFAULT, CharInfoType, &(c), 1, &result)) {
_ASSERTE(!"This should not happen, verify the arguments passed to GetStringTypeEx()");
}
return(INT32)result;
}
#endif // !FEATURE_PAL
/*==============================nativeIsWhiteSpace==============================
**The locally available version of IsWhiteSpace. Designed to be called by other
**native methods. The work is mostly done by GetCharacterInfoHelper
**Args: c -- the character to check.
**Returns: true if c is whitespace, false otherwise.
**Exceptions: Only those thrown by GetCharacterInfoHelper.
==============================================================================*/
BOOL COMCharacter::nativeIsWhiteSpace(WCHAR c)
{
WRAPPER_NO_CONTRACT;
#ifndef FEATURE_PAL
if (c <= (WCHAR) 0x7F) // common case
{
BOOL result = (c == ' ') || (c == '\r') || (c == '\n') || (c == '\t') || (c == '\f') || (c == (WCHAR) 0x0B);
ASSERT(result == ((GetCharacterInfoHelper(c, CT_CTYPE1) & C1_SPACE)!=0));
return result;
}
// GetCharacterInfoHelper costs around 160 instructions
return((GetCharacterInfoHelper(c, CT_CTYPE1) & C1_SPACE)!=0);
#else // !FEATURE_PAL
return iswspace(c);
#endif // !FEATURE_PAL
}
/*================================nativeIsDigit=================================
**The locally available version of IsDigit. Designed to be called by other
**native methods. The work is mostly done by GetCharacterInfoHelper
**Args: c -- the character to check.
**Returns: true if c is whitespace, false otherwise.
**Exceptions: Only those thrown by GetCharacterInfoHelper.
==============================================================================*/
BOOL COMCharacter::nativeIsDigit(WCHAR c)
{
WRAPPER_NO_CONTRACT;
#ifndef FEATURE_PAL
return((GetCharacterInfoHelper(c, CT_CTYPE1) & C1_DIGIT)!=0);
#else // !FEATURE_PAL
return iswdigit(c);
#endif // !FEATURE_PAL
}
BOOL RuntimeFileNotFound(HRESULT hr)
{
LIMITED_METHOD_CONTRACT;
return Assembly::FileNotFound(hr);
}
#ifndef FEATURE_PAL
HRESULT GetFileVersion( // S_OK or error
LPCWSTR wszFilePath, // Path to the executable.
ULARGE_INTEGER* pFileVersion) // Put file version here.
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
}
CONTRACTL_END;
//
// Note that this code is equivalent to FusionGetFileVersionInfo, found in fusion\asmcache\asmcache.cpp
//
// Avoid confusion.
pFileVersion->QuadPart = 0;
DWORD ret;
DWORD dwHandle = 0;
DWORD bufSize = GetFileVersionInfoSizeW(wszFilePath, &dwHandle);
if (!bufSize)
{
return HRESULT_FROM_GetLastErrorNA();
}
// Allocate the buffer for the version info structure
// _alloca() can't return NULL -- raises STATUS_STACK_OVERFLOW.
BYTE* pVersionInfoBuffer = reinterpret_cast< BYTE* >(_alloca(bufSize));
ret = GetFileVersionInfoW(wszFilePath, dwHandle, bufSize, pVersionInfoBuffer);
if (!ret)
{
return HRESULT_FROM_GetLastErrorNA();
}
// Extract the actual File Version number that we care about.
UINT versionInfoSize = 0;
VS_FIXEDFILEINFO* pVSFileInfo;
ret = VerQueryValueW(pVersionInfoBuffer, W("\\"),
reinterpret_cast< void **>(&pVSFileInfo), &versionInfoSize);
if (!ret || versionInfoSize == 0)
{
return HRESULT_FROM_GetLastErrorNA();
}
pFileVersion->HighPart = pVSFileInfo->dwFileVersionMS;
pFileVersion->LowPart = pVSFileInfo->dwFileVersionLS;
return S_OK;
}
#endif // !FEATURE_PAL
#endif // !DACCESS_COMPILE
|