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
|
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
//*****************************************************************************
// UtilCode.h
//
// Utility functions implemented in UtilCode.lib.
//
//*****************************************************************************
#ifndef __UtilCode_h__
#define __UtilCode_h__
#include "crtwrap.h"
#include "winwrap.h"
#include <wchar.h>
#include <stdio.h>
#include <malloc.h>
#include <ole2.h>
#include <oleauto.h>
#include <limits.h>
#include "clrtypes.h"
#include "safewrap.h"
#include "volatile.h"
#include <daccess.h>
#include "clrhost.h"
#include "debugmacros.h"
#include "corhlprpriv.h"
#include "winnls.h"
#include "check.h"
#include "safemath.h"
#include "clr_std/type_traits"
#include "contract.h"
#include "entrypoints.h"
#include "clrnt.h"
// Values for the names of Watson
const WCHAR kWatsonName1[] = W("drwatson");
const WCHAR kWatsonName2[] = W("drwtsn32");
#include "random.h"
// Windows CoreSystem has a different naming scheme for some dlls, which we must take account of when doing
// LoadLibrary and the like.
#if defined(FEATURE_CORESYSTEM)
#define WINDOWS_KERNEL32_DLLNAME_A "kernelbase"
#define WINDOWS_KERNEL32_DLLNAME_W W("kernelbase")
#elif !defined(FEATURE_CORESYSTEM) || defined(CROSS_COMPILE)
#define WINDOWS_KERNEL32_DLLNAME_A "kernel32"
#define WINDOWS_KERNEL32_DLLNAME_W W("kernel32")
#endif
class StringArrayList;
#if !defined(_DEBUG_IMPL) && defined(_DEBUG) && !defined(DACCESS_COMPILE)
#define _DEBUG_IMPL 1
#endif
#ifdef _TARGET_ARM_
// Under ARM we generate code only with Thumb encoding. In order to ensure we execute such code in the correct
// mode we must ensure the low-order bit is set in any code address we'll call as a sub-routine. In C++ this
// is handled automatically for us by the compiler. When generating and working with code generated
// dynamically we have to be careful to set or mask-out this bit as appropriate.
#ifndef THUMB_CODE
#define THUMB_CODE 1
#endif
// Given a WORD extract the bitfield [lowbit, highbit] (i.e. BitExtract(0xffff, 15, 0) == 0xffff).
inline WORD BitExtract(WORD wValue, DWORD highbit, DWORD lowbit)
{
_ASSERTE((highbit < 16) && (lowbit < 16) && (highbit >= lowbit));
return (wValue >> lowbit) & ((1 << ((highbit - lowbit) + 1)) - 1);
}
// Determine whether an ARM Thumb mode instruction is 32-bit or 16-bit based on the first WORD of the
// instruction.
inline bool Is32BitInstruction(WORD opcode)
{
return BitExtract(opcode, 15, 11) >= 0x1d;
}
template <typename ResultType, typename SourceType>
inline ResultType DataPointerToThumbCode(SourceType pCode)
{
return (ResultType)(((UINT_PTR)pCode) | THUMB_CODE);
}
template <typename ResultType, typename SourceType>
inline ResultType ThumbCodeToDataPointer(SourceType pCode)
{
return (ResultType)(((UINT_PTR)pCode) & ~THUMB_CODE);
}
#endif // _TARGET_ARM_
// Convert from a PCODE to the corresponding PINSTR. On many architectures this will be the identity function;
// on ARM, this will mask off the THUMB bit.
inline TADDR PCODEToPINSTR(PCODE pc)
{
#ifdef _TARGET_ARM_
return ThumbCodeToDataPointer<TADDR,PCODE>(pc);
#else
return dac_cast<PCODE>(pc);
#endif
}
typedef LPCSTR LPCUTF8;
typedef LPSTR LPUTF8;
#include "nsutilpriv.h"
#include "stdmacros.h"
/*
// This is for WinCE
#ifdef VERIFY
#undef VERIFY
#endif
#ifdef _ASSERTE
#undef _ASSERTE
#endif
*/
//********** Macros. **********************************************************
#ifndef FORCEINLINE
#if _MSC_VER < 1200
#define FORCEINLINE inline
#else
#define FORCEINLINE __forceinline
#endif
#endif
#ifndef DEBUG_NOINLINE
#if defined(_DEBUG)
#define DEBUG_NOINLINE __declspec(noinline)
#else
#define DEBUG_NOINLINE
#endif
#endif
#ifndef DBG_NOINLINE_X86__RET_INLINE
#if defined(_DEBUG) && defined(_TARGET_X86_)
// this exists to make scan work on x86.
#define DBG_NOINLINE_X86__RET_INLINE __declspec(noinline)
#else
#define DBG_NOINLINE_X86__RET_INLINE FORCEINLINE
#endif
#endif
#include <stddef.h> // for offsetof
#ifndef NumItems
// Number of elements in a fixed-size array
#define NumItems(s) (sizeof(s) / sizeof(s[0]))
#endif
#ifndef StrLen
// Number of characters in a string literal. Excludes terminating NULL.
#define StrLen(str) (NumItems(str) - 1)
#endif
#define IS_DIGIT(ch) ((ch >= W('0')) && (ch <= W('9')))
#define DIGIT_TO_INT(ch) (ch - W('0'))
#define INT_TO_DIGIT(i) ((WCHAR)(W('0') + i))
#define IS_HEXDIGIT(ch) (((ch >= W('a')) && (ch <= W('f'))) || \
((ch >= W('A')) && (ch <= W('F'))))
#define HEXDIGIT_TO_INT(ch) ((towlower(ch) - W('a')) + 10)
#define INT_TO_HEXDIGIT(i) ((WCHAR)(W('a') + (i - 10)))
// Helper will 4 byte align a value, rounding up.
#define ALIGN4BYTE(val) (((val) + 3) & ~0x3)
#ifdef _DEBUG
#define DEBUGARG(x) , x
#else
#define DEBUGARG(x)
#endif
#ifndef sizeofmember
// Returns the size of a class or struct member.
#define sizeofmember(c,m) (sizeof(((c*)0)->m))
#endif
#if defined(_MSC_VER) && _MSC_VER < 1900
#define NOEXCEPT
#else
#define NOEXCEPT noexcept
#endif
//=--------------------------------------------------------------------------=
// Prefast helpers.
//
#include "safemath.h"
//=--------------------------------------------------------------------------=
// string helpers.
//
// given and ANSI String, copy it into a wide buffer.
// be careful about scoping when using this macro!
//
// how to use the below two macros:
//
// ...
// LPSTR pszA;
// pszA = MyGetAnsiStringRoutine();
// MAKE_WIDEPTR_FROMANSI(pwsz, pszA);
// MyUseWideStringRoutine(pwsz);
// ...
//
// similarily for MAKE_ANSIPTR_FROMWIDE. note that the first param does not
// have to be declared, and no clean up must be done.
//
// We'll define an upper limit that allows multiplication by 4 (the max
// bytes/char in UTF-8) but still remains positive, and allows some room for pad.
// Under normal circumstances, we should never get anywhere near this limit.
#define MAKE_MAX_LENGTH 0x1fffff00
#ifndef MAKE_TOOLONGACTION
#define MAKE_TOOLONGACTION ThrowHR(COR_E_OVERFLOW)
#endif
#ifndef MAKE_TRANSLATIONFAILED
#define MAKE_TRANSLATIONFAILED ThrowWin32(ERROR_NO_UNICODE_TRANSLATION)
#endif
// This version throws on conversion errors (ie, no best fit character
// mapping to characters that look similar, and no use of the default char
// ('?') when printing out unrepresentable characters. Use this method for
// most development in the EE, especially anything like metadata or class
// names. See the BESTFIT version if you're printing out info to the console.
#define MAKE_MULTIBYTE_FROMWIDE(ptrname, widestr, codepage) \
int __l##ptrname = (int)wcslen(widestr); \
if (__l##ptrname > MAKE_MAX_LENGTH) \
MAKE_TOOLONGACTION; \
__l##ptrname = (int)((__l##ptrname + 1) * 2 * sizeof(char)); \
CQuickBytes __CQuickBytes##ptrname; \
__CQuickBytes##ptrname.AllocThrows(__l##ptrname); \
BOOL __b##ptrname; \
DWORD __cBytes##ptrname = WszWideCharToMultiByte(codepage, WC_NO_BEST_FIT_CHARS, widestr, -1, (LPSTR)__CQuickBytes##ptrname.Ptr(), __l##ptrname, NULL, &__b##ptrname); \
if (__b##ptrname || (__cBytes##ptrname == 0 && (widestr[0] != W('\0')))) { \
MAKE_TRANSLATIONFAILED; \
} \
LPSTR ptrname = (LPSTR)__CQuickBytes##ptrname.Ptr()
// This version does best fit character mapping and also allows the use
// of the default char ('?') for any Unicode character that isn't
// representable. This is reasonable for writing to the console, but
// shouldn't be used for most string conversions.
#define MAKE_MULTIBYTE_FROMWIDE_BESTFIT(ptrname, widestr, codepage) \
int __l##ptrname = (int)wcslen(widestr); \
if (__l##ptrname > MAKE_MAX_LENGTH) \
MAKE_TOOLONGACTION; \
__l##ptrname = (int)((__l##ptrname + 1) * 2 * sizeof(char)); \
CQuickBytes __CQuickBytes##ptrname; \
__CQuickBytes##ptrname.AllocThrows(__l##ptrname); \
DWORD __cBytes##ptrname = WszWideCharToMultiByte(codepage, 0, widestr, -1, (LPSTR)__CQuickBytes##ptrname.Ptr(), __l##ptrname, NULL, NULL); \
if (__cBytes##ptrname == 0 && __l##ptrname != 0) { \
MAKE_TRANSLATIONFAILED; \
} \
LPSTR ptrname = (LPSTR)__CQuickBytes##ptrname.Ptr()
// Use for anything critical other than output to console, where weird
// character mappings are unacceptable.
#define MAKE_ANSIPTR_FROMWIDE(ptrname, widestr) MAKE_MULTIBYTE_FROMWIDE(ptrname, widestr, CP_ACP)
// Use for output to the console.
#define MAKE_ANSIPTR_FROMWIDE_BESTFIT(ptrname, widestr) MAKE_MULTIBYTE_FROMWIDE_BESTFIT(ptrname, widestr, CP_ACP)
#define MAKE_WIDEPTR_FROMANSI(ptrname, ansistr) \
CQuickBytes __qb##ptrname; \
int __l##ptrname; \
__l##ptrname = WszMultiByteToWideChar(CP_ACP, 0, ansistr, -1, 0, 0); \
if (__l##ptrname > MAKE_MAX_LENGTH) \
MAKE_TOOLONGACTION; \
LPWSTR ptrname = (LPWSTR) __qb##ptrname.AllocThrows((__l##ptrname+1)*sizeof(WCHAR)); \
if (WszMultiByteToWideChar(CP_ACP, MB_ERR_INVALID_CHARS, ansistr, -1, ptrname, __l##ptrname) == 0) { \
MAKE_TRANSLATIONFAILED; \
}
#define MAKE_WIDEPTR_FROMANSI_NOTHROW(ptrname, ansistr) \
CQuickBytes __qb##ptrname; \
LPWSTR ptrname = 0; \
int __l##ptrname; \
__l##ptrname = WszMultiByteToWideChar(CP_ACP, 0, ansistr, -1, 0, 0); \
if (__l##ptrname <= MAKE_MAX_LENGTH) { \
ptrname = (LPWSTR) __qb##ptrname.AllocNoThrow((__l##ptrname+1)*sizeof(WCHAR)); \
if (ptrname) { \
if (WszMultiByteToWideChar(CP_ACP, MB_ERR_INVALID_CHARS, ansistr, -1, ptrname, __l##ptrname) != 0) { \
ptrname[__l##ptrname] = 0; \
} else { \
ptrname = 0; \
} \
} \
}
#define MAKE_UTF8PTR_FROMWIDE(ptrname, widestr) CQuickBytes _##ptrname; _##ptrname.ConvertUnicode_Utf8(widestr); LPSTR ptrname = (LPSTR) _##ptrname.Ptr();
#define MAKE_UTF8PTR_FROMWIDE_NOTHROW(ptrname, widestr) \
CQuickBytes __qb##ptrname; \
int __l##ptrname = (int)wcslen(widestr); \
LPUTF8 ptrname = 0; \
if (__l##ptrname <= MAKE_MAX_LENGTH) { \
__l##ptrname = (int)((__l##ptrname + 1) * 2 * sizeof(char)); \
ptrname = (LPUTF8) __qb##ptrname.AllocNoThrow(__l##ptrname); \
} \
if (ptrname) { \
INT32 __lresult##ptrname=WszWideCharToMultiByte(CP_UTF8, 0, widestr, -1, ptrname, __l##ptrname-1, NULL, NULL); \
DWORD __dwCaptureLastError##ptrname = ::GetLastError(); \
if ((__lresult##ptrname==0) && (((LPCWSTR)widestr)[0] != W('\0'))) { \
if (__dwCaptureLastError##ptrname==ERROR_INSUFFICIENT_BUFFER) { \
INT32 __lsize##ptrname=WszWideCharToMultiByte(CP_UTF8, 0, widestr, -1, NULL, 0, NULL, NULL); \
ptrname = (LPSTR) __qb##ptrname .AllocNoThrow(__lsize##ptrname); \
if (ptrname) { \
if (WszWideCharToMultiByte(CP_UTF8, 0, widestr, -1, ptrname, __lsize##ptrname, NULL, NULL) != 0) { \
ptrname[__l##ptrname] = 0; \
} else { \
ptrname = 0; \
} \
} \
} \
else { \
ptrname = 0; \
} \
} \
} \
#define MAKE_WIDEPTR_FROMUTF8N(ptrname, utf8str, n8chrs) \
CQuickBytes __qb##ptrname; \
int __l##ptrname; \
__l##ptrname = WszMultiByteToWideChar(CP_UTF8, 0, utf8str, n8chrs, 0, 0); \
if (__l##ptrname > MAKE_MAX_LENGTH) \
MAKE_TOOLONGACTION; \
LPWSTR ptrname = (LPWSTR) __qb##ptrname .AllocThrows((__l##ptrname+1)*sizeof(WCHAR)); \
if (0==WszMultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, utf8str, n8chrs, ptrname, __l##ptrname)) { \
MAKE_TRANSLATIONFAILED; \
} \
ptrname[__l##ptrname] = 0;
#define MAKE_WIDEPTR_FROMUTF8(ptrname, utf8str) CQuickBytes _##ptrname; _##ptrname.ConvertUtf8_Unicode(utf8str); LPCWSTR ptrname = (LPCWSTR) _##ptrname.Ptr();
#define MAKE_WIDEPTR_FROMUTF8N_NOTHROW(ptrname, utf8str, n8chrs) \
CQuickBytes __qb##ptrname; \
int __l##ptrname; \
LPWSTR ptrname = 0; \
__l##ptrname = WszMultiByteToWideChar(CP_UTF8, 0, utf8str, n8chrs, 0, 0); \
if (__l##ptrname <= MAKE_MAX_LENGTH) { \
ptrname = (LPWSTR) __qb##ptrname.AllocNoThrow((__l##ptrname+1)*sizeof(WCHAR)); \
if (ptrname) { \
if (WszMultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, utf8str, n8chrs, ptrname, __l##ptrname) != 0) { \
ptrname[__l##ptrname] = 0; \
} else { \
ptrname = 0; \
} \
} \
}
#define MAKE_WIDEPTR_FROMUTF8_NOTHROW(ptrname, utf8str) MAKE_WIDEPTR_FROMUTF8N_NOTHROW(ptrname, utf8str, -1)
// This method takes the number of characters
#define MAKE_MULTIBYTE_FROMWIDEN(ptrname, widestr, _nCharacters, _pCnt, codepage) \
CQuickBytes __qb##ptrname; \
int __l##ptrname; \
__l##ptrname = WszWideCharToMultiByte(codepage, WC_NO_BEST_FIT_CHARS, widestr, _nCharacters, NULL, 0, NULL, NULL); \
if (__l##ptrname > MAKE_MAX_LENGTH) \
MAKE_TOOLONGACTION; \
ptrname = (LPUTF8) __qb##ptrname .AllocThrows(__l##ptrname+1); \
BOOL __b##ptrname; \
DWORD _pCnt = WszWideCharToMultiByte(codepage, WC_NO_BEST_FIT_CHARS, widestr, _nCharacters, ptrname, __l##ptrname, NULL, &__b##ptrname); \
if (__b##ptrname || (_pCnt == 0 && _nCharacters > 0)) { \
MAKE_TRANSLATIONFAILED; \
} \
ptrname[__l##ptrname] = 0;
#define MAKE_MULTIBYTE_FROMWIDEN_BESTFIT(ptrname, widestr, _nCharacters, _pCnt, codepage) \
CQuickBytes __qb##ptrname; \
int __l##ptrname; \
__l##ptrname = WszWideCharToMultiByte(codepage, 0, widestr, _nCharacters, NULL, 0, NULL, NULL); \
if (__l##ptrname > MAKE_MAX_LENGTH) \
MAKE_TOOLONGACTION; \
ptrname = (LPUTF8) __qb##ptrname .AllocThrows(__l##ptrname+1); \
DWORD _pCnt = WszWideCharToMultiByte(codepage, 0, widestr, _nCharacters, ptrname, __l##ptrname, NULL, NULL); \
if (_pCnt == 0 && _nCharacters > 0) { \
MAKE_TRANSLATIONFAILED; \
} \
ptrname[__l##ptrname] = 0;
#define MAKE_ANSIPTR_FROMWIDEN(ptrname, widestr, _nCharacters, _pCnt) \
MAKE_MULTIBYTE_FROMWIDEN(ptrname, widestr, _nCharacters, _pCnt, CP_ACP)
inline
LPWSTR DuplicateString(
LPCWSTR wszString,
size_t cchString)
{
STATIC_CONTRACT_NOTHROW;
LPWSTR wszDup = NULL;
if (wszString != NULL)
{
wszDup = new (nothrow) WCHAR[cchString + 1];
if (wszDup != NULL)
{
wcscpy_s(wszDup, cchString + 1, wszString);
}
}
return wszDup;
}
inline
LPWSTR DuplicateString(
LPCWSTR wszString)
{
STATIC_CONTRACT_NOTHROW;
if (wszString != NULL)
{
return DuplicateString(wszString, wcslen(wszString));
}
else
{
return NULL;
}
}
void DECLSPEC_NORETURN ThrowOutOfMemory();
inline
LPWSTR DuplicateStringThrowing(
LPCWSTR wszString,
size_t cchString)
{
STATIC_CONTRACT_THROWS;
if (wszString == NULL)
return NULL;
LPWSTR wszDup = DuplicateString(wszString, cchString);
if (wszDup == NULL)
ThrowOutOfMemory();
return wszDup;
}
inline
LPWSTR DuplicateStringThrowing(
LPCWSTR wszString)
{
STATIC_CONTRACT_THROWS;
if (wszString == NULL)
return NULL;
LPWSTR wszDup = DuplicateString(wszString);
if (wszDup == NULL)
ThrowOutOfMemory();
return wszDup;
}
//*****************************************************************************
// Placement new is used to new and object at an exact location. The pointer
// is simply returned to the caller without actually using the heap. The
// advantage here is that you cause the ctor() code for the object to be run.
// This is ideal for heaps of C++ objects that need to get init'd multiple times.
// Example:
// void *pMem = GetMemFromSomePlace();
// Foo *p = new (pMem) Foo;
// DoSomething(p);
// p->~Foo();
//*****************************************************************************
#ifndef __PLACEMENT_NEW_INLINE
#define __PLACEMENT_NEW_INLINE
inline void *__cdecl operator new(size_t, void *_P)
{
LIMITED_METHOD_DAC_CONTRACT;
return (_P);
}
#endif // __PLACEMENT_NEW_INLINE
/********************************************************************************/
/* portability helpers */
#ifdef _WIN64
#define IN_WIN64(x) x
#define IN_WIN32(x)
#else
#define IN_WIN64(x)
#define IN_WIN32(x) x
#endif
void * __cdecl
operator new(size_t n);
_Ret_bytecap_(_Size) void * __cdecl
operator new[](size_t n);
void __cdecl
operator delete(void *p) NOEXCEPT;
void __cdecl
operator delete[](void *p) NOEXCEPT;
#ifdef _DEBUG_IMPL
HRESULT _OutOfMemory(LPCSTR szFile, int iLine);
#define OutOfMemory() _OutOfMemory(__FILE__, __LINE__)
#else
inline HRESULT OutOfMemory()
{
LIMITED_METHOD_CONTRACT;
return (E_OUTOFMEMORY);
}
#endif
//*****************************************************************************
// Handle accessing localizable resource strings
//*****************************************************************************
// NOTE: Should use locale names as much as possible. LCIDs don't support
// custom cultures on Vista+.
// TODO: This should always use the names
#ifdef FEATURE_USE_LCID
typedef LCID LocaleID;
typedef LCID LocaleIDValue;
#else
typedef LPCWSTR LocaleID;
typedef WCHAR LocaleIDValue[LOCALE_NAME_MAX_LENGTH];
#endif
// Notes about the culture callbacks:
// - The language we're operating in can change at *runtime*!
// - A process may operate in *multiple* languages.
// (ex: Each thread may have it's own language)
// - If we don't care what language we're in (or have no way of knowing),
// then return a 0-length name and UICULTUREID_DONTCARE for the culture ID.
// - GetCultureName() and the GetCultureId() must be in sync (refer to the
// same language).
// - We have two functions separate functions for better performance.
// - The name is used to resolve a directory for MsCorRC.dll.
// - The id is used as a key to map to a dll hinstance.
// Callback to obtain both the culture name and the culture's parent culture name
typedef HRESULT (*FPGETTHREADUICULTURENAMES)(__inout StringArrayList* pCultureNames);
#ifdef FEATURE_USE_LCID
// Callback to return the culture ID.
const LCID UICULTUREID_DONTCARE = (LCID)-1;
#else
const LPCWSTR UICULTUREID_DONTCARE = NULL;
#endif
typedef int (*FPGETTHREADUICULTUREID)(LocaleIDValue*);
HMODULE CLRLoadLibrary(LPCWSTR lpLibFileName);
HMODULE CLRLoadLibraryEx(LPCWSTR lpLibFileName, HANDLE hFile, DWORD dwFlags);
BOOL CLRFreeLibrary(HMODULE hModule);
// Prevent people from using LoadStringRC & LoadStringRCEx from inside the product since it
// causes issues with having the wrong version picked up inside the shim.
#define LoadStringRC __error("From inside the CLR, use UtilLoadStringRC; LoadStringRC is only meant to be exported.")
#define LoadStringRCEx __error("From inside the CLR, use UtilLoadStringRCEx; LoadStringRC is only meant to be exported.")
// Load a string using the resources for the current module.
STDAPI UtilLoadStringRC(UINT iResouceID, __out_ecount (iMax) LPWSTR szBuffer, int iMax, int bQuiet=FALSE);
#if ENABLE_DOWNLEVEL_FOR_NLS
STDAPI UtilLoadStringRCEx(LCID lcid, UINT iResourceID, __out_ecount (iMax) LPWSTR szBuffer, int iMax, int bQuiet, int *pcwchUsed);
#endif
// Specify callbacks so that UtilLoadStringRC can find out which language we're in.
// If no callbacks specified (or both parameters are NULL), we default to the
// resource dll in the root (which is probably english).
void SetResourceCultureCallbacks(
FPGETTHREADUICULTURENAMES fpGetThreadUICultureNames,
FPGETTHREADUICULTUREID fpGetThreadUICultureId
);
void GetResourceCultureCallbacks(
FPGETTHREADUICULTURENAMES* fpGetThreadUICultureNames,
FPGETTHREADUICULTUREID* fpGetThreadUICultureId
);
#if !defined(DACCESS_COMPILE)
// Get the MUI ID, on downlevel platforms where MUI is not supported it
// returns the default system ID.
extern int GetMUILanguageID(LocaleIDValue* pResult);
extern HRESULT GetMUILanguageNames(__inout StringArrayList* pCultureNames);
#endif // !defined(DACCESS_COMPILE)
//*****************************************************************************
// Use this class by privately deriving from noncopyable to disallow copying of
// your class.
//*****************************************************************************
class noncopyable
{
protected:
noncopyable()
{}
~noncopyable()
{}
private:
noncopyable(const noncopyable&);
const noncopyable& operator=(const noncopyable&);
};
//*****************************************************************************
// Must associate each handle to an instance of a resource dll with the int
// that it represents
//*****************************************************************************
typedef HINSTANCE HRESOURCEDLL;
class CCulturedHInstance
{
LocaleIDValue m_LangId;
HRESOURCEDLL m_hInst;
BOOL m_fMissing;
public:
CCulturedHInstance()
{
LIMITED_METHOD_CONTRACT;
m_hInst = NULL;
m_fMissing = FALSE;
}
BOOL HasID(LocaleID id)
{
_ASSERTE(m_hInst != NULL || m_fMissing);
if (id == UICULTUREID_DONTCARE)
return FALSE;
#ifdef FEATURE_USE_LCID
return id == m_LangId;
#else
return wcscmp(id, m_LangId) == 0;
#endif
}
HRESOURCEDLL GetLibraryHandle()
{
return m_hInst;
}
BOOL IsSet()
{
return m_hInst != NULL;
}
BOOL IsMissing()
{
return m_fMissing;
}
void SetMissing(LocaleID id)
{
_ASSERTE(m_hInst == NULL);
SetId(id);
m_fMissing = TRUE;
}
void Set(LocaleID id, HRESOURCEDLL hInst)
{
_ASSERTE(m_hInst == NULL);
_ASSERTE(m_fMissing == FALSE);
SetId(id);
m_hInst = hInst;
}
private:
void SetId(LocaleID id)
{
#ifdef FEATURE_USE_LCID
m_LangId = id;
#else
if (id != UICULTUREID_DONTCARE)
{
wcsncpy_s(m_LangId, NumItems(m_LangId), id, NumItems(m_LangId));
m_LangId[NumItems(m_LangId)-1] = W('\0');
}
else
{
m_LangId[0] = W('\0');
}
#endif
}
};
#ifndef DACCESS_COMPILE
void AddThreadPreferredUILanguages(StringArrayList* pArray);
#endif
//*****************************************************************************
// CCompRC manages string Resource access for COM+. This includes loading
// the MsCorRC.dll for resources as well allowing each thread to use a
// a different localized version.
//*****************************************************************************
class CCompRC
{
public:
enum ResourceCategory
{
// must be present
Required,
// present in Desktop CLR and Core CLR + debug pack, an error
// If missing, get a generic error message instead
Error,
// present in Desktop CLR and Core CLR + debug pack, normal operation (e.g tracing)
// if missing, get a generic "resource not found" message instead
Debugging,
// present in Desktop CLR, optional for CoreCLR
DesktopCLR,
// might not be present, non essential
Optional
};
CCompRC()
{
// This constructor will be fired up on startup. Make sure it doesn't
// do anything besides zero-out out values.
m_bUseFallback = FALSE;
m_fpGetThreadUICultureId = NULL;
m_fpGetThreadUICultureNames = NULL;
m_pHash = NULL;
m_nHashSize = 0;
m_csMap = NULL;
m_pResourceFile = NULL;
#ifdef FEATURE_PAL
m_pResourceDomain = NULL;
#endif // FEATURE_PAL
}// CCompRC
HRESULT Init(LPCWSTR pResourceFile, BOOL bUseFallback = FALSE);
void Destroy();
BOOL ShouldUseFallback()
{
LIMITED_METHOD_CONTRACT;
return m_bUseFallback;
};
static void SetIsMscoree() {s_bIsMscoree = TRUE;}
HRESULT LoadString(ResourceCategory eCategory, UINT iResourceID, __out_ecount (iMax) LPWSTR szBuffer, int iMax , int *pcwchUsed=NULL);
HRESULT LoadString(ResourceCategory eCategory, LocaleID langId, UINT iResourceID, __out_ecount (iMax) LPWSTR szBuffer, int iMax, int *pcwchUsed);
void SetResourceCultureCallbacks(
FPGETTHREADUICULTURENAMES fpGetThreadUICultureNames,
FPGETTHREADUICULTUREID fpGetThreadUICultureId
);
void GetResourceCultureCallbacks(
FPGETTHREADUICULTURENAMES* fpGetThreadUICultureNames,
FPGETTHREADUICULTUREID* fpGetThreadUICultureId
);
HRESULT LoadMUILibrary(HRESOURCEDLL * pHInst);
// Get the default resource location (mscorrc.dll for desktop, mscorrc.debug.dll for CoreCLR)
static CCompRC* GetDefaultResourceDll();
#ifdef FEATURE_CORECLR
// Get the generic messages dll (Silverlight only, mscorrc.dll)
static CCompRC* GetFallbackResourceDll();
#endif
static void ShutdownDefaultResourceDll();
static void GetDefaultCallbacks(
FPGETTHREADUICULTURENAMES* fpGetThreadUICultureNames,
FPGETTHREADUICULTUREID* fpGetThreadUICultureId)
{
WRAPPER_NO_CONTRACT;
m_DefaultResourceDll.GetResourceCultureCallbacks(
fpGetThreadUICultureNames,
fpGetThreadUICultureId);
}
static void SetDefaultCallbacks(
FPGETTHREADUICULTURENAMES fpGetThreadUICultureNames,
FPGETTHREADUICULTUREID fpGetThreadUICultureId)
{
WRAPPER_NO_CONTRACT;
// Either both are NULL or neither are NULL
_ASSERTE((fpGetThreadUICultureNames != NULL) ==
(fpGetThreadUICultureId != NULL));
m_DefaultResourceDll.SetResourceCultureCallbacks(
fpGetThreadUICultureNames,
fpGetThreadUICultureId);
#ifdef FEATURE_CORECLR
m_FallbackResourceDll.SetResourceCultureCallbacks(
fpGetThreadUICultureNames,
fpGetThreadUICultureId);
#endif
}
#ifdef USE_FORMATMESSAGE_WRAPPER
DWORD
PALAPI
static
FormatMessage(
IN DWORD dwFlags,
IN LPCVOID lpSource,
IN DWORD dwMessageId,
IN DWORD dwLanguageId,
OUT LPWSTR lpBuffer,
IN DWORD nSize,
IN va_list *Arguments);
#endif // USE_FORMATMESSAGE_WRAPPER
private:
HRESULT GetLibrary(LocaleID langId, HRESOURCEDLL* phInst);
#ifndef DACCESS_COMPILE
HRESULT LoadLibraryHelper(HRESOURCEDLL *pHInst,
__out_ecount(rcPathSize) WCHAR *rcPath, const DWORD rcPathSize);
HRESULT LoadLibrary(HRESOURCEDLL * pHInst);
HRESULT LoadResourceFile(HRESOURCEDLL * pHInst, LPCWSTR lpFileName);
#endif
// We do not have global constructors any more
static LONG m_dwDefaultInitialized;
static CCompRC m_DefaultResourceDll;
static LPCWSTR m_pDefaultResource;
#ifdef FEATURE_CORECLR
// fallback resources if debug pack is not installed
static LONG m_dwFallbackInitialized;
static CCompRC m_FallbackResourceDll;
static LPCWSTR m_pFallbackResource;
#endif
// We must map between a thread's int and a dll instance.
// Since we only expect 1 language almost all of the time, we'll special case
// that and then use a variable size map for everything else.
CCulturedHInstance m_Primary;
CCulturedHInstance * m_pHash;
int m_nHashSize;
CRITSEC_COOKIE m_csMap;
LPCWSTR m_pResourceFile;
#ifdef FEATURE_PAL
// Resource domain is an ANSI string identifying a native resources file
static LPCSTR m_pDefaultResourceDomain;
static LPCSTR m_pFallbackResourceDomain;
LPCSTR m_pResourceDomain;
#endif // FEATURE_PAL
// Main accessors for hash
HRESOURCEDLL LookupNode(LocaleID langId, BOOL &fMissing);
HRESULT AddMapNode(LocaleID langId, HRESOURCEDLL hInst, BOOL fMissing = FALSE);
FPGETTHREADUICULTUREID m_fpGetThreadUICultureId;
FPGETTHREADUICULTURENAMES m_fpGetThreadUICultureNames;
BOOL m_bUseFallback;
static BOOL s_bIsMscoree;
};
HRESULT UtilLoadResourceString(CCompRC::ResourceCategory eCategory, UINT iResouceID, __out_ecount (iMax) LPWSTR szBuffer, int iMax);
int UtilMessageBox(
HWND hWnd, // Handle to Owner Window
UINT uText, // Resource Identifier for Text message
UINT uCaption, // Resource Identifier for Caption
UINT uType, // Style of MessageBox
BOOL displayForNonInteractive, // Display even if the process is running non interactive
BOOL ShowFileNameInTitle, // Flag to show FileName in Caption
...); // Additional Arguments
int UtilMessageBoxNonLocalized(
HWND hWnd, // Handle to Owner Window
LPCWSTR lpText, // Resource Identifier for Text message
LPCWSTR lpTitle, // Resource Identifier for Caption
UINT uType, // Style of MessageBox
BOOL displayForNonInteractive, // Display even if the process is running non interactive
BOOL ShowFileNameInTitle, // Flag to show FileName in Caption
...); // Additional Arguments
int UtilMessageBoxVA(
HWND hWnd, // Handle to Owner Window
UINT uText, // Resource Identifier for Text message
UINT uCaption, // Resource Identifier for Caption
UINT uType, // Style of MessageBox
BOOL displayForNonInteractive, // Display even if the process is running non interactive
BOOL ShowFileNameInTitle, // Flag to show FileName in Caption
va_list args); // Additional Arguments
int UtilMessageBoxNonLocalizedVA(
HWND hWnd, // Handle to Owner Window
LPCWSTR lpText, // Text message
LPCWSTR lpCaption, // Caption
UINT uType, // Style of MessageBox
BOOL displayForNonInteractive, // Display even if the process is running non interactive
BOOL ShowFileNameInTitle, // Flag to show FileName in Caption
BOOL * pInputFromUser, // To distinguish between user pressing abort vs. assuming abort.
va_list args); // Additional Arguments
int UtilMessageBoxNonLocalizedVA(
HWND hWnd, // Handle to Owner Window
LPCWSTR lpText, // Text message
LPCWSTR lpCaption, // Caption
LPCWSTR lpDetails, // Details that may be shown in a collapsed extended area of the dialog (Vista or higher).
UINT uType, // Style of MessageBox
BOOL displayForNonInteractive, // Display even if the process is running non interactive
BOOL ShowFileNameInTitle, // Flag to show FileName in Caption
BOOL * pInputFromUser, // To distinguish between user pressing abort vs. assuming abort.
va_list args); // Additional Arguments
int UtilMessageBoxCatastrophic(
UINT uText, // Text for MessageBox
UINT uTitle, // Title for MessageBox
UINT uType, // Style of MessageBox
BOOL ShowFileNameInTitle, // Flag to show FileName in Caption
...);
int UtilMessageBoxCatastrophicNonLocalized(
LPCWSTR lpText, // Text for MessageBox
LPCWSTR lpTitle, // Title for MessageBox
UINT uType, // Style of MessageBox
BOOL ShowFileNameInTitle, // Flag to show FileName in Caption
...);
int UtilMessageBoxCatastrophicVA(
UINT uText, // Text for MessageBox
UINT uTitle, // Title for MessageBox
UINT uType, // Style of MessageBox
BOOL ShowFileNameInTitle, // Flag to show FileName in Caption
va_list args); // Additional Arguments
int UtilMessageBoxCatastrophicNonLocalizedVA(
LPCWSTR lpText, // Text for MessageBox
LPCWSTR lpTitle, // Title for MessageBox
UINT uType, // Style of MessageBox
BOOL ShowFileNameInTitle, // Flag to show FileName in Caption
va_list args); // Additional Arguments
// The HRESULT_FROM_WIN32 macro evaluates its arguments three times.
// <TODO>TODO: All HRESULT_FROM_WIN32(GetLastError()) should be replaced by calls to
// this helper function avoid code bloat</TODO>
inline HRESULT HRESULT_FROM_GetLastError()
{
WRAPPER_NO_CONTRACT;
DWORD dw = GetLastError();
// Make sure we return a failure
if (dw == ERROR_SUCCESS)
{
_ASSERTE(!"We were expecting to get an error code, but a success code is being returned. Check this code path for Everett!");
return E_FAIL;
}
else
return HRESULT_FROM_WIN32(dw);
}
inline HRESULT HRESULT_FROM_GetLastErrorNA()
{
WRAPPER_NO_CONTRACT;
DWORD dw = GetLastError();
// Make sure we return a failure
if (dw == ERROR_SUCCESS)
return E_FAIL;
else
return HRESULT_FROM_WIN32(dw);
}
inline HRESULT BadError(HRESULT hr)
{
LIMITED_METHOD_CONTRACT;
_ASSERTE(!"Serious Error");
return (hr);
}
#define TESTANDRETURN(test, hrVal) \
{ \
int ___test = (int)(test); \
if (! ___test) \
return hrVal; \
}
#define TESTANDRETURNPOINTER(pointer) \
TESTANDRETURN(pointer!=NULL, E_POINTER)
#define TESTANDRETURNMEMORY(pointer) \
TESTANDRETURN(pointer!=NULL, E_OUTOFMEMORY)
#define TESTANDRETURNHR(hr) \
TESTANDRETURN(SUCCEEDED(hr), hr)
#define TESTANDRETURNARG(argtest) \
TESTANDRETURN(argtest, E_INVALIDARG)
// Quick validity check for HANDLEs that are returned by Win32 APIs that
// use INVALID_HANDLE_VALUE instead of NULL to indicate an error
inline BOOL IsValidHandle(HANDLE h)
{
LIMITED_METHOD_CONTRACT;
return ((h != NULL) && (h != INVALID_HANDLE_VALUE));
}
// Count the bits in a value in order iBits time.
inline int CountBits(int iNum)
{
LIMITED_METHOD_CONTRACT;
int iBits;
for (iBits=0; iNum; iBits++)
iNum = iNum & (iNum - 1);
return (iBits);
}
//------------------------------------------------------------------------
// BitPosition: Return the position of the single bit that is set in 'value'.
//
// Return Value:
// The position (0 is LSB) of bit that is set in 'value'
//
// Notes:
// 'value' must have exactly one bit set.
// The algorithm is as follows:
// - PRIME is a prime bigger than sizeof(unsigned int), which is not of the
// form 2^n-1.
// - Taking the modulo of 'value' with this will produce a unique hash for all
// powers of 2 (which is what "value" is).
// - Entries in hashTable[] which are -1 should never be used. There
// should be PRIME-8*sizeof(value) entries which are -1 .
//
inline
unsigned BitPosition(unsigned value)
{
_ASSERTE((value != 0) && ((value & (value-1)) == 0));
#ifndef _TARGET_AMD64_
const unsigned PRIME = 37;
static const char hashTable[PRIME] =
{
-1, 0, 1, 26, 2, 23, 27, -1, 3, 16,
24, 30, 28, 11, -1, 13, 4, 7, 17, -1,
25, 22, 31, 15, 29, 10, 12, 6, -1, 21,
14, 9, 5, 20, 8, 19, 18
};
_ASSERTE(PRIME >= 8*sizeof(value));
_ASSERTE(sizeof(hashTable) == PRIME);
unsigned hash = value % PRIME;
unsigned index = hashTable[hash];
_ASSERTE(index != (unsigned char)-1);
#else
// not enabled for x86 because BSF is extremely slow on Atom
// (15 clock cycles vs 1-3 on any other Intel CPU post-P4)
DWORD index;
BitScanForward(&index, value);
#endif
return index;
}
// Used to remove trailing zeros from Decimal types.
// NOTE: Assumes hi32 bits are empty (used for conversions from Cy->Dec)
inline HRESULT DecimalCanonicalize(DECIMAL* dec)
{
WRAPPER_NO_CONTRACT;
// Clear the VARENUM field
(*(USHORT*)dec) = 0;
// Remove trailing zeros:
DECIMAL temp;
DECIMAL templast;
temp = templast = *dec;
// Ensure the hi 32 bits are empty (should be if we came from a currency)
if ((DECIMAL_HI32(temp) != 0) || (DECIMAL_SCALE(temp) > 4))
return DISP_E_OVERFLOW;
// Return immediately if dec represents a zero.
if (DECIMAL_LO32(temp) == 0 && DECIMAL_MID32(temp) == 0)
return S_OK;
// Compare to the original to see if we've
// lost non-zero digits (and make sure we don't overflow the scale BYTE)
#ifdef _PREFAST_
#pragma warning(push)
#pragma warning(disable:6219) // "Suppress PREFast warning about Implicit cast between semantically different integer types"
#endif
while ((DECIMAL_SCALE(temp) <= 4) && (VARCMP_EQ == VarDecCmp(dec, &temp)))
{
#ifdef _PREFAST_
#pragma warning(pop)
#endif
templast = temp;
// Remove the last digit and normalize. Ignore temp.Hi32
// as Currency values will have a max of 64 bits of data.
DECIMAL_SCALE(temp)--;
UINT64 temp64 = (((UINT64) DECIMAL_MID32(temp)) << 32) + DECIMAL_LO32(temp);
temp64 /= 10;
DECIMAL_MID32(temp) = (ULONG)(temp64 >> 32);
DECIMAL_LO32(temp) = (ULONG)temp64;
}
*dec = templast;
return S_OK;
}
//*****************************************************************************
//
// Paths functions. Use these instead of the CRT.
//
//*****************************************************************************
// secure version! Specify the size of the each buffer in count of elements
void SplitPath(register const WCHAR *path,
__inout_z __inout_ecount_opt(driveSizeInWords) WCHAR *drive, int driveSizeInWords,
__inout_z __inout_ecount_opt(dirSizeInWords) WCHAR *dir, int dirSizeInWords,
__inout_z __inout_ecount_opt(fnameSizeInWords) WCHAR *fname, size_t fnameSizeInWords,
__inout_z __inout_ecount_opt(extSizeInWords) WCHAR *ext, size_t extSizeInWords);
//*******************************************************************************
// A much more sensible version that just points to each section of the string.
//*******************************************************************************
void SplitPathInterior(
__in LPCWSTR wszPath,
__out_opt LPCWSTR *pwszDrive, __out_opt size_t *pcchDrive,
__out_opt LPCWSTR *pwszDir, __out_opt size_t *pcchDir,
__out_opt LPCWSTR *pwszFileName, __out_opt size_t *pcchFileName,
__out_opt LPCWSTR *pwszExt, __out_opt size_t *pcchExt);
void MakePath(__out_ecount (MAX_PATH) register WCHAR *path,
__in LPCWSTR drive,
__in LPCWSTR dir,
__in LPCWSTR fname,
__in LPCWSTR ext);
WCHAR * FullPath(__out_ecount (maxlen) WCHAR *UserBuf, const WCHAR *path, size_t maxlen);
//*****************************************************************************
//
// SString version of the path functions.
//
//*****************************************************************************
void SplitPath(__in SString const &path,
__inout_opt SString *drive,
__inout_opt SString *dir,
__inout_opt SString *fname,
__inout_opt SString *ext);
//*****************************************************************************
//
// **** REGUTIL - Static helper functions for reading/writing to Windows registry.
//
//*****************************************************************************
class REGUTIL
{
public:
//*****************************************************************************
enum CORConfigLevel
{
COR_CONFIG_ENV = 0x01,
COR_CONFIG_USER = 0x02,
COR_CONFIG_MACHINE = 0x04,
COR_CONFIG_FUSION = 0x08,
COR_CONFIG_REGISTRY = (COR_CONFIG_USER|COR_CONFIG_MACHINE|COR_CONFIG_FUSION),
COR_CONFIG_ALL = (COR_CONFIG_ENV|COR_CONFIG_USER|COR_CONFIG_MACHINE),
};
//
// NOTE: The following function is deprecated; use the CLRConfig class instead.
// To access a configuration value through CLRConfig, add an entry in file:../inc/CLRConfigValues.h.
//
static DWORD GetConfigDWORD_DontUse_(
LPCWSTR name,
DWORD defValue,
CORConfigLevel level = COR_CONFIG_ALL,
BOOL fPrependCOMPLUS = TRUE);
//
// NOTE: The following function is deprecated; use the CLRConfig class instead.
// To access a configuration value through CLRConfig, add an entry in file:../inc/CLRConfigValues.h.
//
static HRESULT GetConfigDWORD_DontUse_(
LPCWSTR name,
DWORD defValue,
__out DWORD * result,
CORConfigLevel level = COR_CONFIG_ALL,
BOOL fPrependCOMPLUS = TRUE);
static ULONGLONG GetConfigULONGLONG_DontUse_(
LPCWSTR name,
ULONGLONG defValue,
CORConfigLevel level = COR_CONFIG_ALL,
BOOL fPrependCOMPLUS = TRUE);
//
// NOTE: The following function is deprecated; use the CLRConfig class instead.
// To access a configuration value through CLRConfig, add an entry in file:../inc/CLRConfigValues.h.
//
static DWORD GetConfigFlag_DontUse_(
LPCWSTR name,
DWORD bitToSet,
BOOL defValue = FALSE);
//
// NOTE: The following function is deprecated; use the CLRConfig class instead.
// To access a configuration value through CLRConfig, add an entry in file:../inc/CLRConfigValues.h.
//
static LPWSTR GetConfigString_DontUse_(
LPCWSTR name,
BOOL fPrependCOMPLUS = TRUE,
CORConfigLevel level = COR_CONFIG_ALL,
BOOL fUsePerfCache = TRUE);
static void FreeConfigString(__in __in_z LPWSTR name);
#ifdef FEATURE_CORECLR
private:
#endif //FEATURE_CORECLR
static LPWSTR EnvGetString(LPCWSTR name, BOOL fPrependCOMPLUS);
#ifdef FEATURE_CORECLR
public:
#endif //FEATURE_CORECLR
static BOOL UseRegistry();
private:
//*****************************************************************************
// Get either a DWORD or ULONGLONG. Always puts the result in a ULONGLONG that
// you can safely cast to a DWORD if fGetDWORD is TRUE.
//*****************************************************************************
static HRESULT GetConfigInteger(
LPCWSTR name,
ULONGLONG defValue,
__out ULONGLONG * result,
BOOL fGetDWORD = TRUE,
CORConfigLevel level = COR_CONFIG_ALL,
BOOL fPrependCOMPLUS = TRUE);
public:
#ifndef FEATURE_CORECLR
static void AllowRegistryUse(BOOL fAllowUse);
//*****************************************************************************
// Open's the given key and returns the value desired. If the key or value is
// not found, then the default is returned.
//*****************************************************************************
static long GetLong( // Return value from registry or default.
LPCTSTR szName, // Name of value to get.
long iDefault, // Default value to return if not found.
LPCTSTR szKey=NULL, // Name of key, NULL==default.
HKEY hKey=HKEY_LOCAL_MACHINE);// What key to work on.
//*****************************************************************************
// Open's the given key and returns the value desired. If the key or value is
// not found, then the default is returned.
//*****************************************************************************
static long SetLong( // Return value from registry or default.
LPCTSTR szName, // Name of value to get.
long iValue, // Value to set.
LPCTSTR szKey=NULL, // Name of key, NULL==default.
HKEY hKey=HKEY_LOCAL_MACHINE);// What key to work on.
//*****************************************************************************
// Open's the given key and returns the value desired. If the key or value is
// not found, then it's created
//*****************************************************************************
static long SetOrCreateLong( // Return value from registry or default.
LPCTSTR szName, // Name of value to get.
long iValue, // Value to set.
LPCTSTR szKey=NULL, // Name of key, NULL==default.
HKEY hKey=HKEY_LOCAL_MACHINE);// What key to work on.
//*****************************************************************************
// Set an entry in the registry of the form:
// HKEY_CLASSES_ROOT\szKey\szSubkey = szValue. If szSubkey or szValue are
// NULL, omit them from the above expression.
//*****************************************************************************
static BOOL SetKeyAndValue( // TRUE or FALSE.
LPCTSTR szKey, // Name of the reg key to set.
LPCTSTR szSubkey, // Optional subkey of szKey.
LPCTSTR szValue); // Optional value for szKey\szSubkey.
//*****************************************************************************
// Delete an entry in the registry of the form:
// HKEY_CLASSES_ROOT\szKey\szSubkey.
//*****************************************************************************
static LONG DeleteKey( // TRUE or FALSE.
LPCTSTR szKey, // Name of the reg key to set.
LPCTSTR szSubkey); // Subkey of szKey.
//*****************************************************************************
// Open the key, create a new keyword and value pair under it.
//*****************************************************************************
static BOOL SetRegValue( // Return status.
LPCTSTR szKeyName, // Name of full key.
LPCTSTR szKeyword, // Name of keyword.
LPCTSTR szValue); // Value of keyword.
//*****************************************************************************
// Does standard registration of a CoClass with a progid.
//*****************************************************************************
static HRESULT RegisterCOMClass( // Return code.
REFCLSID rclsid, // Class ID.
LPCTSTR szDesc, // Description of the class.
LPCTSTR szProgIDPrefix, // Prefix for progid.
int iVersion, // Version # for progid.
LPCTSTR szClassProgID, // Class progid.
LPCTSTR szThreadingModel, // What threading model to use.
LPCTSTR szModule, // Path to class.
HINSTANCE hInst, // Handle to module being registered
LPCTSTR szAssemblyName, // Optional assembly name
LPCTSTR szVersion, // Optional Runtime Version (directry containing runtime)
BOOL fExternal, // flag - External to mscoree.
BOOL fRelativePath); // flag - Relative path in szModule
//*****************************************************************************
// Unregister the basic information in the system registry for a given object
// class.
//*****************************************************************************
static HRESULT UnregisterCOMClass( // Return code.
REFCLSID rclsid, // Class ID we are registering.
LPCTSTR szProgIDPrefix, // Prefix for progid.
int iVersion, // Version # for progid.
LPCTSTR szClassProgID, // Class progid.
BOOL fExternal); // flag - External to mscoree.
//*****************************************************************************
// Does standard registration of a CoClass with a progid.
// NOTE: This is the non-side-by-side execution version.
//*****************************************************************************
static HRESULT RegisterCOMClass( // Return code.
REFCLSID rclsid, // Class ID.
LPCTSTR szDesc, // Description of the class.
LPCTSTR szProgIDPrefix, // Prefix for progid.
int iVersion, // Version # for progid.
LPCTSTR szClassProgID, // Class progid.
LPCTSTR szThreadingModel, // What threading model to use.
LPCTSTR szModule, // Path to class.
BOOL bInprocServer = true); // Whether we register the server as inproc or local
//*****************************************************************************
// Unregister the basic information in the system registry for a given object
// class.
// NOTE: This is the non-side-by-side execution version.
//*****************************************************************************
static HRESULT UnregisterCOMClass( // Return code.
REFCLSID rclsid, // Class ID we are registering.
LPCTSTR szProgIDPrefix, // Prefix for progid.
int iVersion, // Version # for progid.
LPCTSTR szClassProgID); // Class progid.
//*****************************************************************************
// Register a type library.
//*****************************************************************************
static HRESULT RegisterTypeLib( // Return code.
REFGUID rtlbid, // TypeLib ID we are registering.
int iVersion, // Typelib version.
LPCTSTR szDesc, // TypeLib description.
LPCTSTR szModule); // Path to the typelib.
//*****************************************************************************
// Remove the registry keys for a type library.
//*****************************************************************************
static HRESULT UnregisterTypeLib( // Return code.
REFGUID rtlbid, // TypeLib ID we are registering.
int iVersion); // Typelib version.
#endif //#ifndef FEATURE_CORECLR
//*****************************************************************************
// (Optional) Initialize the config registry cache
// (see ConfigCacheValueNameSeenPerhaps, below.)
//*****************************************************************************
static void InitOptionalConfigCache();
private:
#ifndef FEATURE_CORECLR
//*****************************************************************************
// Register the basics for a in proc server.
//*****************************************************************************
static HRESULT RegisterClassBase( // Return code.
REFCLSID rclsid, // Class ID we are registering.
LPCTSTR szDesc, // Class description.
LPCTSTR szProgID, // Class prog ID.
LPCTSTR szIndepProgID, // Class version independant prog ID.
__out_ecount (cchOutCLSID) LPTSTR szOutCLSID, // CLSID formatted in character form.
DWORD cchOutCLSID); // Out CLS ID buffer size in characters
//*****************************************************************************
// Delete the basic settings for an inproc server.
//*****************************************************************************
static HRESULT UnregisterClassBase( // Return code.
REFCLSID rclsid, // Class ID we are registering.
LPCTSTR szProgID, // Class prog ID.
LPCTSTR szIndepProgID, // Class version independant prog ID.
__out_ecount (cchOutCLSID) LPTSTR szOutCLSID, // Return formatted class ID here.
DWORD cchOutCLSID); // Out CLS ID buffer size in characters
#endif //#ifndef FEATURE_CORECLR
//*****************************************************************************
// Return TRUE if the registry value name might have been seen in the registry
// at startup;
// return FALSE if the value was definitely not seen at startup.
//
// Perf Optimization for VSWhidbey:113373.
//*****************************************************************************
static BOOL RegCacheValueNameSeenPerhaps(
LPCWSTR name);
//*****************************************************************************
// Return TRUE if the environment variable name might have been seen at startup;
// return FALSE if the value was definitely not seen at startup.
//*****************************************************************************
static BOOL EnvCacheValueNameSeenPerhaps(
LPCWSTR name);
static BOOL s_fUseRegCache; // Enable registry cache; if FALSE, CCVNSP
// always returns TRUE.
static BOOL s_fUseEnvCache; // Enable env cache.
static BOOL s_fUseRegistry; // Allow lookups in the registry
// Open the .NetFramework keys once and cache the handles
static HKEY s_hMachineFrameworkKey;
static HKEY s_hUserFrameworkKey;
};
// need this here because CLRConfig depends on REGUTIL, and ConfigStringHolder depends on CLRConfig
#include "clrconfig.h"
//-----------------------------------------------------------------------------
// Wrapper for configuration strings.
// This serves as a holder to call FreeConfigString.
class ConfigStringHolder
{
public:
ConfigStringHolder() { m_wszString = NULL; }
~ConfigStringHolder()
{
Clear();
}
//
// NOTE: The following function is deprecated; use the CLRConfig class instead.
// To access a configuration value through CLRConfig, add an entry in file:../inc/CLRConfigValues.h.
//
void Init_DontUse_(LPCWSTR wszName)
{
Clear();
m_wszString = REGUTIL::GetConfigString_DontUse_(wszName);
}
// Free resources.
void Clear()
{
if (m_wszString != NULL)
{
REGUTIL::FreeConfigString(m_wszString);
m_wszString = NULL;
}
}
// Get the string value. NULL if not set.
LPCWSTR Value()
{
return m_wszString;
}
private:
LPWSTR m_wszString;
};
#include "ostype.h"
#define CLRGetTickCount64() GetTickCount64()
//
// Use this function to initialize the s_CodeAllocHint
// during startup. base is runtime .dll base address,
// size is runtime .dll virtual size.
//
void InitCodeAllocHint(SIZE_T base, SIZE_T size, int randomPageOffset);
//
// Use this function to reset the s_CodeAllocHint
// after unloading an AppDomain
//
void ResetCodeAllocHint();
//
// Returns TRUE if p is located in near clr.dll that allows us
// to use rel32 IP-relative addressing modes.
//
BOOL IsPreferredExecutableRange(void * p);
//
// Allocate free memory that will be used for executable code
// Handles the special requirements that we have on 64-bit platforms
// where we want the executable memory to be located near mscorwks
//
BYTE * ClrVirtualAllocExecutable(SIZE_T dwSize,
DWORD flAllocationType,
DWORD flProtect);
//
// Allocate free memory within the range [pMinAddr..pMaxAddr] using
// ClrVirtualQuery to find free memory and ClrVirtualAlloc to allocate it.
//
BYTE * ClrVirtualAllocWithinRange(const BYTE *pMinAddr,
const BYTE *pMaxAddr,
SIZE_T dwSize,
DWORD flAllocationType,
DWORD flProtect);
//
// Allocate free memory with specific alignment
//
LPVOID ClrVirtualAllocAligned(LPVOID lpAddress, SIZE_T dwSize, DWORD flAllocationType, DWORD flProtect, SIZE_T alignment);
//******************************************************************************
// Returns the number of processors that a process has been configured to run on
//******************************************************************************
class NumaNodeInfo
{
private:
static BOOL m_enableGCNumaAware;
static BOOL InitNumaNodeInfoAPI();
public:
static BOOL CanEnableGCNumaAware();
static void InitNumaNodeInfo();
#if !defined(FEATURE_REDHAWK)&& !defined(FEATURE_PAL)
private: // apis types
#if !defined(FEATURE_CORESYSTEM)
//GetNumaProcessorNode()
typedef BOOL
(WINAPI *PGNPN)(UCHAR, PUCHAR);
#endif
//GetNumaHighestNodeNumber()
typedef BOOL
(WINAPI *PGNHNN)(PULONG);
//VirtualAllocExNuma()
typedef LPVOID
(WINAPI *PVAExN)(HANDLE,LPVOID,SIZE_T,DWORD,DWORD,DWORD);
// api pfns and members
#if !defined(FEATURE_CORESYSTEM)
static PGNPN m_pGetNumaProcessorNode;
#endif
static PGNHNN m_pGetNumaHighestNodeNumber;
static PVAExN m_pVirtualAllocExNuma;
public: // functions
#if !defined(FEATURE_CORESYSTEM)
static BOOL GetNumaProcessorNode(UCHAR proc_no, PUCHAR node_no);
#endif
static LPVOID VirtualAllocExNuma(HANDLE hProc, LPVOID lpAddr, SIZE_T size,
DWORD allocType, DWORD prot, DWORD node);
#if !defined(FEATURE_CORECLR) || defined(FEATURE_CORESYSTEM)
private:
//GetNumaProcessorNodeEx()
typedef BOOL
(WINAPI *PGNPNEx)(PPROCESSOR_NUMBER, PUSHORT);
static PGNPNEx m_pGetNumaProcessorNodeEx;
public:
static BOOL GetNumaProcessorNodeEx(PPROCESSOR_NUMBER proc_no, PUSHORT node_no);
#endif
#endif
};
struct CPU_Group_Info
{
WORD nr_active; // at most 64
WORD reserved[1];
WORD begin;
WORD end;
DWORD_PTR active_mask;
DWORD groupWeight;
DWORD activeThreadWeight;
};
class CPUGroupInfo
{
private:
static LONG m_initialization;
static WORD m_nGroups;
static WORD m_nProcessors;
static BOOL m_enableGCCPUGroups;
static BOOL m_threadUseAllCpuGroups;
static WORD m_initialGroup;
static CPU_Group_Info *m_CPUGroupInfoArray;
static BOOL InitCPUGroupInfoAPI();
static BOOL InitCPUGroupInfoArray();
static BOOL InitCPUGroupInfoRange();
static void InitCPUGroupInfo();
static BOOL IsInitialized();
public:
static void EnsureInitialized();
static BOOL CanEnableGCCPUGroups();
static BOOL CanEnableThreadUseAllCpuGroups();
static WORD GetNumActiveProcessors();
static void GetGroupForProcessor(WORD processor_number,
WORD *group_number, WORD *group_processor_number);
static DWORD CalculateCurrentProcessorNumber();
//static void PopulateCPUUsageArray(void * infoBuffer, ULONG infoSize);
#if !defined(FEATURE_REDHAWK) && !defined(FEATURE_PAL)
private:
//GetLogicalProcessorInforomationEx()
typedef BOOL
(WINAPI *PGLPIEx)(DWORD, SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX *, PDWORD);
//SetThreadGroupAffinity()
typedef BOOL
(WINAPI *PSTGA)(HANDLE, GROUP_AFFINITY *, GROUP_AFFINITY *);
//GetThreadGroupAffinity()
typedef BOOL
(WINAPI *PGTGA)(HANDLE, GROUP_AFFINITY *);
#if !defined(FEATURE_CORESYSTEM) && !defined(FEATURE_CORECLR)
//GetCurrentProcessorNumberEx()
typedef void
(WINAPI *PGCPNEx)(PROCESSOR_NUMBER *);
//GetSystemTimes()
typedef BOOL
(WINAPI *PGST)(FILETIME *, FILETIME *, FILETIME *);
//NtQuerySystemInformationEx()
//typedef int
//(WINAPI *PNTQSIEx)(SYSTEM_INFORMATION_CLASS, PULONG, ULONG, PVOID, ULONG, PULONG);
#endif
static PGLPIEx m_pGetLogicalProcessorInformationEx;
static PSTGA m_pSetThreadGroupAffinity;
static PGTGA m_pGetThreadGroupAffinity;
#if !defined(FEATURE_CORESYSTEM) && !defined(FEATURE_CORECLR)
static PGCPNEx m_pGetCurrentProcessorNumberEx;
static PGST m_pGetSystemTimes;
//static PNTQSIEx m_pNtQuerySystemInformationEx;
#endif
public:
static BOOL GetLogicalProcessorInformationEx(DWORD relationship,
SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX *slpiex, PDWORD count);
static BOOL SetThreadGroupAffinity(HANDLE h,
GROUP_AFFINITY *groupAffinity, GROUP_AFFINITY *previousGroupAffinity);
static BOOL GetThreadGroupAffinity(HANDLE h, GROUP_AFFINITY *groupAffinity);
#if !defined(FEATURE_CORESYSTEM) && !defined(FEATURE_CORECLR)
static BOOL GetSystemTimes(FILETIME *idleTime, FILETIME *kernelTime, FILETIME *userTime);
static void ChooseCPUGroupAffinity(GROUP_AFFINITY *gf);
static void ClearCPUGroupAffinity(GROUP_AFFINITY *gf);
#endif
#endif
};
int GetCurrentProcessCpuCount();
DWORD_PTR GetCurrentProcessCpuMask();
//*****************************************************************************
// Return != 0 if the bit at the specified index in the array is on and 0 if
// it is off.
//*****************************************************************************
inline int GetBit(PTR_BYTE pcBits,int iBit)
{
LIMITED_METHOD_CONTRACT;
return (pcBits[iBit>>3] & (1 << (iBit & 0x7)));
}
#ifdef DACCESS_COMPILE
inline int GetBit(BYTE const * pcBits,int iBit)
{
WRAPPER_NO_CONTRACT;
return GetBit(dac_cast<PTR_BYTE>(pcBits), iBit);
}
#endif
//*****************************************************************************
// Set the state of the bit at the specified index based on the value of bOn.
//*****************************************************************************
inline void SetBit(PTR_BYTE pcBits,int iBit,int bOn)
{
LIMITED_METHOD_CONTRACT;
if (bOn)
pcBits[iBit>>3] |= (1 << (iBit & 0x7));
else
pcBits[iBit>>3] &= ~(1 << (iBit & 0x7));
}
#ifdef DACCESS_COMPILE
inline void SetBit(BYTE * pcBits,int iBit,int bOn)
{
WRAPPER_NO_CONTRACT;
SetBit(dac_cast<PTR_BYTE>(pcBits), iBit, bOn);
}
#endif
template<typename T>
class SimpleListNode
{
public:
SimpleListNode<T>(const T& _t)
{
data = _t;
next = 0;
}
T data;
SimpleListNode<T>* next;
};
template<typename T>
class SimpleList
{
public:
typedef SimpleListNode<T> NodeType;
SimpleList<T>()
{
head = NULL;
}
void LinkHead(NodeType* pNode)
{
pNode->next = head;
head = pNode;
}
NodeType* UnlinkHead()
{
NodeType* ret = head;
if (head)
{
head = head->next;
}
return ret;
}
NodeType* Head()
{
return head;
}
protected:
NodeType* head;
};
template < typename T, typename U >
struct Pair
{
public:
typedef Pair< T, U > this_type;
typedef T first_type;
typedef U second_type;
Pair()
{}
Pair( T const & t, U const & u )
: m_first( t )
, m_second( u )
{ SUPPORTS_DAC; }
Pair( this_type const & obj )
: m_first( obj.m_first )
, m_second( obj.m_second )
{}
this_type & operator=( this_type const & obj )
{
m_first = obj.m_first;
m_second = obj.m_second;
return *this;
}
T & First()
{
return m_first;
}
T const & First() const
{
return m_first;
}
U & Second()
{
return m_second;
}
U const & Second() const
{
return m_second;
}
bool operator==(const Pair& rhs) const
{
return ((this->First() == rhs.First()) &&
(this->Second() == rhs.Second()));
}
bool operator!=(const Pair& rhs) const
{
return !(*this == rhs);
}
private:
first_type m_first;
second_type m_second;
};
template < typename T, typename U >
Pair< T, U > MakePair( T const & t, U const & u )
{
SUPPORTS_DAC;
return Pair< T, U >( t, u );
}
//*****************************************************************************
// This class implements a dynamic array of structures for which the order of
// the elements is unimportant. This means that any item placed in the list
// may be swapped to any other location in the list at any time. If the order
// of the items you place in the array is important, then use the CStructArray
// class.
//*****************************************************************************
template <class T,
int iGrowInc,
class ALLOCATOR>
class CUnorderedArrayWithAllocator
{
int m_iCount; // # of elements used in the list.
int m_iSize; // # of elements allocated in the list.
public:
#ifndef DACCESS_COMPILE
T *m_pTable; // Pointer to the list of elements.
#else
TADDR m_pTable; // Pointer to the list of elements.
#endif
public:
#ifndef DACCESS_COMPILE
CUnorderedArrayWithAllocator() :
m_iCount(0),
m_iSize(0),
m_pTable(NULL)
{
LIMITED_METHOD_CONTRACT;
}
~CUnorderedArrayWithAllocator()
{
LIMITED_METHOD_CONTRACT;
// Free the chunk of memory.
if (m_pTable != NULL)
ALLOCATOR::Free(this, m_pTable);
}
void Clear()
{
WRAPPER_NO_CONTRACT;
m_iCount = 0;
if (m_iSize > iGrowInc)
{
T* tmp = ALLOCATOR::AllocNoThrow(this, iGrowInc);
if (tmp) {
ALLOCATOR::Free(this, m_pTable);
m_pTable = tmp;
m_iSize = iGrowInc;
}
}
}
void Clear(int iFirst, int iCount)
{
WRAPPER_NO_CONTRACT;
int iSize;
if (iFirst + iCount < m_iCount)
memmove(&m_pTable[iFirst], &m_pTable[iFirst + iCount], sizeof(T) * (m_iCount - (iFirst + iCount)));
m_iCount -= iCount;
iSize = ((m_iCount / iGrowInc) * iGrowInc) + ((m_iCount % iGrowInc != 0) ? iGrowInc : 0);
if (m_iSize > iGrowInc && iSize < m_iSize)
{
T *tmp = ALLOCATOR::AllocNoThrow(this, iSize);
if (tmp) {
memcpy (tmp, m_pTable, iSize * sizeof(T));
delete [] m_pTable;
m_pTable = tmp;
m_iSize = iSize;
}
}
_ASSERTE(m_iCount <= m_iSize);
}
T *Table()
{
LIMITED_METHOD_CONTRACT;
return (m_pTable);
}
T *Append()
{
CONTRACTL {
NOTHROW;
} CONTRACTL_END;
// The array should grow, if we can't fit one more element into the array.
if (m_iSize <= m_iCount && GrowNoThrow() == NULL)
return (NULL);
return (&m_pTable[m_iCount++]);
}
T *AppendThrowing()
{
CONTRACTL {
THROWS;
} CONTRACTL_END;
// The array should grow, if we can't fit one more element into the array.
if (m_iSize <= m_iCount)
Grow();
return (&m_pTable[m_iCount++]);
}
void Delete(const T &Entry)
{
LIMITED_METHOD_CONTRACT;
--m_iCount;
for (int i=0; i <= m_iCount; ++i)
if (m_pTable[i] == Entry)
{
m_pTable[i] = m_pTable[m_iCount];
return;
}
// Just in case we didn't find it.
++m_iCount;
}
void DeleteByIndex(int i)
{
LIMITED_METHOD_CONTRACT;
--m_iCount;
m_pTable[i] = m_pTable[m_iCount];
}
void Swap(int i,int j)
{
LIMITED_METHOD_CONTRACT;
T tmp;
if (i == j)
return;
tmp = m_pTable[i];
m_pTable[i] = m_pTable[j];
m_pTable[j] = tmp;
}
#else
TADDR Table()
{
LIMITED_METHOD_CONTRACT;
SUPPORTS_DAC;
return (m_pTable);
}
void EnumMemoryRegions(void)
{
SUPPORTS_DAC;
DacEnumMemoryRegion(m_pTable, m_iCount * sizeof(T));
}
#endif // #ifndef DACCESS_COMPILE
USHORT Count()
{
LIMITED_METHOD_CONTRACT;
SUPPORTS_DAC;
_ASSERTE(FitsIn<USHORT>(m_iCount));
return static_cast<USHORT>(m_iCount);
}
private:
T *Grow();
T *GrowNoThrow();
};
#ifndef DACCESS_COMPILE
//*****************************************************************************
// Increase the size of the array.
//*****************************************************************************
template <class T,
int iGrowInc,
class ALLOCATOR>
T *CUnorderedArrayWithAllocator<T,iGrowInc,ALLOCATOR>::GrowNoThrow() // NULL if can't grow.
{
WRAPPER_NO_CONTRACT;
T *pTemp;
// try to allocate memory for reallocation.
if ((pTemp = ALLOCATOR::AllocNoThrow(this, m_iSize+iGrowInc)) == NULL)
return (NULL);
memcpy (pTemp, m_pTable, m_iSize*sizeof(T));
ALLOCATOR::Free(this, m_pTable);
m_pTable = pTemp;
m_iSize += iGrowInc;
_ASSERTE(m_iSize > 0);
return (pTemp);
}
template <class T,
int iGrowInc,
class ALLOCATOR>
T *CUnorderedArrayWithAllocator<T,iGrowInc,ALLOCATOR>::Grow() // exception if can't grow.
{
WRAPPER_NO_CONTRACT;
T *pTemp;
// try to allocate memory for reallocation.
pTemp = ALLOCATOR::AllocThrowing(this, m_iSize+iGrowInc);
memcpy (pTemp, m_pTable, m_iSize*sizeof(T));
ALLOCATOR::Free(this, m_pTable);
m_pTable = pTemp;
m_iSize += iGrowInc;
_ASSERTE(m_iSize > 0);
return (pTemp);
}
#endif // #ifndef DACCESS_COMPILE
template <class T>
class CUnorderedArray__Allocator
{
public:
static T *AllocThrowing (void*, int nElements)
{
return new T[nElements];
}
static T *AllocNoThrow (void*, int nElements)
{
return new (nothrow) T[nElements];
}
static void Free (void*, T *pTable)
{
delete [] pTable;
}
};
template <class T,int iGrowInc>
class CUnorderedArray : public CUnorderedArrayWithAllocator<T, iGrowInc, CUnorderedArray__Allocator<T> >
{
public:
CUnorderedArray ()
{
LIMITED_METHOD_CONTRACT;
}
};
//Used by the debugger. Included here in hopes somebody else might, too
typedef CUnorderedArray<SIZE_T, 17> SIZE_T_UNORDERED_ARRAY;
//*****************************************************************************
// This class implements a dynamic array of structures for which the insert
// order is important. Inserts will slide all elements after the location
// down, deletes slide all values over the deleted item. If the order of the
// items in the array is unimportant to you, then CUnorderedArray may provide
// the same feature set at lower cost.
//*****************************************************************************
class CStructArray
{
BYTE *m_pList; // Pointer to the list of elements.
int m_iCount; // # of elements used in the list.
int m_iSize; // # of elements allocated in the list.
int m_iGrowInc; // Growth increment.
short m_iElemSize; // Size of an array element.
bool m_bFree; // true if data is automatically maintained.
public:
CStructArray(short iElemSize, short iGrowInc = 1) :
m_pList(NULL),
m_iCount(0),
m_iSize(0),
m_iGrowInc(iGrowInc),
m_iElemSize(iElemSize),
m_bFree(true)
{
LIMITED_METHOD_CONTRACT;
}
~CStructArray()
{
WRAPPER_NO_CONTRACT;
Clear();
}
void *Insert(int iIndex);
void *InsertThrowing(int iIndex);
void *Append();
void *AppendThrowing();
int AllocateBlock(int iCount);
void AllocateBlockThrowing(int iCount);
void Delete(int iIndex);
void *Ptr()
{
LIMITED_METHOD_CONTRACT;
return (m_pList);
}
void *Get(int iIndex)
{
WRAPPER_NO_CONTRACT;
_ASSERTE(iIndex < m_iCount);
return ((void *) ((size_t) Ptr() + (iIndex * m_iElemSize)));
}
int Size()
{
LIMITED_METHOD_CONTRACT;
return (m_iCount * m_iElemSize);
}
int Count()
{
LIMITED_METHOD_CONTRACT;
return (m_iCount);
}
void Clear();
void ClearCount()
{
LIMITED_METHOD_CONTRACT;
m_iCount = 0;
}
void InitOnMem(short iElemSize, void *pList, int iCount, int iSize, int iGrowInc=1)
{
LIMITED_METHOD_CONTRACT;
m_iElemSize = iElemSize;
m_iGrowInc = (short) iGrowInc;
m_pList = (BYTE*)pList;
m_iCount = iCount;
m_iSize = iSize;
m_bFree = false;
}
private:
void Grow(int iCount);
};
//*****************************************************************************
// This template simplifies access to a CStructArray by removing void * and
// adding some operator overloads.
//*****************************************************************************
template <class T>
class CDynArray : public CStructArray
{
public:
CDynArray(short iGrowInc=16) :
CStructArray(sizeof(T), iGrowInc)
{
LIMITED_METHOD_CONTRACT;
}
T *Insert(int iIndex)
{
WRAPPER_NO_CONTRACT;
return ((T *)CStructArray::Insert((int)iIndex));
}
T *InsertThrowing(int iIndex)
{
WRAPPER_NO_CONTRACT;
return ((T *)CStructArray::InsertThrowing((int)iIndex));
}
T *Append()
{
WRAPPER_NO_CONTRACT;
return ((T *)CStructArray::Append());
}
T *AppendThrowing()
{
WRAPPER_NO_CONTRACT;
return ((T *)CStructArray::AppendThrowing());
}
T *Ptr()
{
WRAPPER_NO_CONTRACT;
return ((T *)CStructArray::Ptr());
}
T *Get(int iIndex)
{
WRAPPER_NO_CONTRACT;
return (Ptr() + iIndex);
}
T &operator[](int iIndex)
{
WRAPPER_NO_CONTRACT;
return (*(Ptr() + iIndex));
}
int ItemIndex(T *p)
{
WRAPPER_NO_CONTRACT;
return (((int)(LONG_PTR)p - (int)(LONG_PTR)Ptr()) / sizeof(T));
}
void Move(int iFrom, int iTo)
{
WRAPPER_NO_CONTRACT;
T tmp;
_ASSERTE(iFrom >= 0 && iFrom < Count() &&
iTo >= 0 && iTo < Count());
tmp = *(Ptr() + iFrom);
if (iTo > iFrom)
memmove(Ptr() + iFrom, Ptr() + iFrom + 1, (iTo - iFrom) * sizeof(T));
else
memmove(Ptr() + iTo + 1, Ptr() + iTo, (iFrom - iTo) * sizeof(T));
*(Ptr() + iTo) = tmp;
}
};
// Some common arrays.
typedef CDynArray<int> INTARRAY;
typedef CDynArray<short> SHORTARRAY;
typedef CDynArray<int> LONGARRAY;
typedef CDynArray<USHORT> USHORTARRAY;
typedef CDynArray<ULONG> ULONGARRAY;
typedef CDynArray<BYTE> BYTEARRAY;
typedef CDynArray<mdToken> TOKENARRAY;
template <class T> class CStackArray : public CStructArray
{
public:
CStackArray(short iGrowInc=4) :
CStructArray(sizeof(T), iGrowInc),
m_curPos(0)
{
LIMITED_METHOD_CONTRACT;
}
void Push(T p)
{
WRAPPER_NO_CONTRACT;
// We should only inc m_curPos after we grow the array.
T *pT = (T *)CStructArray::InsertThrowing(m_curPos);
m_curPos ++;
*pT = p;
}
T * Pop()
{
WRAPPER_NO_CONTRACT;
T * retPtr;
_ASSERTE(m_curPos > 0);
retPtr = (T *)CStructArray::Get(m_curPos-1);
CStructArray::Delete(m_curPos--);
return (retPtr);
}
int Count()
{
LIMITED_METHOD_CONTRACT;
return(m_curPos);
}
private:
int m_curPos;
};
//*****************************************************************************
// This template manages a list of free entries by their 0 based offset. By
// making it a template, you can use whatever size free chain will match your
// maximum count of items. -1 is reserved.
//*****************************************************************************
template <class T> class TFreeList
{
public:
void Init(
T *rgList,
int iCount)
{
LIMITED_METHOD_CONTRACT;
// Save off values.
m_rgList = rgList;
m_iCount = iCount;
m_iNext = 0;
// Init free list.
int i;
for (i=0; i<iCount - 1; i++)
m_rgList[i] = i + 1;
m_rgList[i] = (T) -1;
}
T GetFreeEntry() // Index of free item, or -1.
{
LIMITED_METHOD_CONTRACT;
T iNext;
if (m_iNext == (T) -1)
return (-1);
iNext = m_iNext;
m_iNext = m_rgList[m_iNext];
return (iNext);
}
void DelFreeEntry(T iEntry)
{
LIMITED_METHOD_CONTRACT;
_ASSERTE(iEntry < m_iCount);
m_rgList[iEntry] = m_iNext;
m_iNext = iEntry;
}
// This function can only be used when it is guaranteed that the free
// array is contigous, for example, right after creation to quickly
// get a range of items from the heap.
void ReserveRange(int iCount)
{
LIMITED_METHOD_CONTRACT;
_ASSERTE(iCount < m_iCount);
_ASSERTE(m_iNext == 0);
m_iNext = iCount;
}
private:
T *m_rgList; // List of free info.
int m_iCount; // How many entries to manage.
T m_iNext; // Next item to get.
};
//*****************************************************************************
//*****************************************************************************
template <class T> class CQuickSort
{
protected:
T *m_pBase; // Base of array to sort.
private:
SSIZE_T m_iCount; // How many items in array.
SSIZE_T m_iElemSize; // Size of one element.
public:
CQuickSort(
T *pBase, // Address of first element.
SSIZE_T iCount) : // How many there are.
m_pBase(pBase),
m_iCount(iCount),
m_iElemSize(sizeof(T))
{
LIMITED_METHOD_DAC_CONTRACT;
}
//*****************************************************************************
// Call to sort the array.
//*****************************************************************************
inline void Sort()
{
WRAPPER_NO_CONTRACT;
SortRange(0, m_iCount - 1);
}
protected:
//*****************************************************************************
// Override this function to do the comparison.
//*****************************************************************************
virtual FORCEINLINE int Compare( // -1, 0, or 1
T *psFirst, // First item to compare.
T *psSecond) // Second item to compare.
{
LIMITED_METHOD_DAC_CONTRACT;
return (memcmp(psFirst, psSecond, sizeof(T)));
// return (::Compare(*psFirst, *psSecond));
}
virtual FORCEINLINE void Swap(
SSIZE_T iFirst,
SSIZE_T iSecond)
{
LIMITED_METHOD_DAC_CONTRACT;
if (iFirst == iSecond) return;
T sTemp( m_pBase[iFirst] );
m_pBase[iFirst] = m_pBase[iSecond];
m_pBase[iSecond] = sTemp;
}
private:
inline void SortRange(
SSIZE_T iLeft,
SSIZE_T iRight)
{
WRAPPER_NO_CONTRACT;
SSIZE_T iLast;
SSIZE_T i; // loop variable.
for (;;)
{
// if less than two elements you're done.
if (iLeft >= iRight)
return;
// ASSERT that we now have valid indicies. This is statically provable
// since this private function is only called with valid indicies,
// and iLeft and iRight only converge towards eachother. However,
// PreFast can't detect this because it doesn't know about our callers.
COMPILER_ASSUME(iLeft >= 0 && iLeft < m_iCount);
COMPILER_ASSUME(iRight >= 0 && iRight < m_iCount);
// The mid-element is the pivot, move it to the left.
Swap(iLeft, (iLeft + iRight) / 2);
iLast = iLeft;
// move everything that is smaller than the pivot to the left.
for (i = iLeft + 1; i <= iRight; i++)
{
if (Compare(&m_pBase[i], &m_pBase[iLeft]) < 0)
{
Swap(i, ++iLast);
}
}
// Put the pivot to the point where it is in between smaller and larger elements.
Swap(iLeft, iLast);
// Sort each partition.
SSIZE_T iLeftLast = iLast - 1;
SSIZE_T iRightFirst = iLast + 1;
if (iLeftLast - iLeft < iRight - iRightFirst)
{ // Left partition is smaller, sort it recursively
SortRange(iLeft, iLeftLast);
// Tail call to sort the right (bigger) partition
iLeft = iRightFirst;
//iRight = iRight;
continue;
}
else
{ // Right partition is smaller, sort it recursively
SortRange(iRightFirst, iRight);
// Tail call to sort the left (bigger) partition
//iLeft = iLeft;
iRight = iLeftLast;
continue;
}
}
}
};
//*****************************************************************************
// Faster and simpler version of the binary search below.
//*****************************************************************************
template <class T>
const T * BinarySearch(const T * pBase, int iCount, const T & find)
{
WRAPPER_NO_CONTRACT;
int iFirst = 0;
int iLast = iCount - 1;
// It is faster to use linear search once we get down to a small number of elements.
while (iLast - iFirst > 10)
{
int iMid = (iLast + iFirst) / 2;
if (find < pBase[iMid])
iLast = iMid - 1;
else
iFirst = iMid;
}
for (int i = iFirst; i <= iLast; i++)
{
if (find == pBase[i])
return &pBase[i];
if (find < pBase[i])
break;
}
return NULL;
}
//*****************************************************************************
// This template encapsulates a binary search algorithm on the given type
// of data.
//*****************************************************************************
template <class T> class CBinarySearch
{
private:
const T *m_pBase; // Base of array to sort.
int m_iCount; // How many items in array.
public:
CBinarySearch(
const T *pBase, // Address of first element.
int iCount) : // Value to find.
m_pBase(pBase),
m_iCount(iCount)
{
LIMITED_METHOD_CONTRACT;
}
//*****************************************************************************
// Searches for the item passed to ctor.
//*****************************************************************************
const T *Find( // Pointer to found item in array.
const T *psFind, // The key to find.
int *piInsert = NULL) // Index to insert at.
{
WRAPPER_NO_CONTRACT;
int iMid, iFirst, iLast; // Loop control.
int iCmp; // Comparison.
iFirst = 0;
iLast = m_iCount - 1;
while (iFirst <= iLast)
{
iMid = (iLast + iFirst) / 2;
iCmp = Compare(psFind, &m_pBase[iMid]);
if (iCmp == 0)
{
if (piInsert != NULL)
*piInsert = iMid;
return (&m_pBase[iMid]);
}
else if (iCmp < 0)
iLast = iMid - 1;
else
iFirst = iMid + 1;
}
if (piInsert != NULL)
*piInsert = iFirst;
return (NULL);
}
//*****************************************************************************
// Override this function to do the comparison if a comparison operator is
// not valid for your data type (such as a struct).
//*****************************************************************************
virtual int Compare( // -1, 0, or 1
const T *psFirst, // Key you are looking for.
const T *psSecond) // Item to compare to.
{
LIMITED_METHOD_CONTRACT;
return (memcmp(psFirst, psSecond, sizeof(T)));
// return (::Compare(*psFirst, *psSecond));
}
};
//*****************************************************************************
// The information that the hash table implementation stores at the beginning
// of every record that can be but in the hash table.
//*****************************************************************************
typedef DPTR(struct HASHENTRY) PTR_HASHENTRY;
struct HASHENTRY
{
ULONG iPrev; // Previous bucket in the chain.
ULONG iNext; // Next bucket in the chain.
};
typedef DPTR(struct FREEHASHENTRY) PTR_FREEHASHENTRY;
struct FREEHASHENTRY : HASHENTRY
{
ULONG iFree;
};
//*****************************************************************************
// Used by the FindFirst/FindNextEntry functions. These api's allow you to
// do a sequential scan of all entries.
//*****************************************************************************
struct HASHFIND
{
ULONG iBucket; // The next bucket to look in.
ULONG iNext;
};
//*****************************************************************************
// IMPORTANT: This data structure is deprecated, please do not add any new uses.
// The hashtable implementation that should be used instead is code:SHash.
// If code:SHash does not work for you, talk to mailto:clrdeag.
//*****************************************************************************
// This is a class that implements a chain and bucket hash table.
//
// The data is actually supplied as an array of structures by the user of this class.
// This allows the buckets to use small indices to point to the chain, instead of pointers.
//
// Each entry in the array contains a HASHENTRY structure immediately
// followed by the key used to hash the structure.
//
// The HASHENTRY part of every structure is used to implement the chain of
// entries in a single bucket.
//
// This implementation does not support rehashing the buckets if the table grows
// to big.
// @TODO: Fix this by adding an abstract function Hash() which must be implemented
// by all clients.
//
//*****************************************************************************
class CHashTable
{
friend class DebuggerRCThread; //RCthread actually needs access to
//fields of derrived class DebuggerPatchTable
protected:
TADDR m_pcEntries; // Pointer to the array of structs.
ULONG m_iEntrySize; // Size of the structs.
ULONG m_iBuckets; // # of chains we are hashing into.
PTR_ULONG m_piBuckets; // Ptr to the array of bucket chains.
INDEBUG(unsigned m_maxSearch;) // For evaluating perf characteristics
HASHENTRY *EntryPtr(ULONG iEntry)
{
LIMITED_METHOD_DAC_CONTRACT;
return (PTR_HASHENTRY(m_pcEntries + (iEntry * m_iEntrySize)));
}
ULONG ItemIndex(HASHENTRY *p)
{
SUPPORTS_DAC;
LIMITED_METHOD_CONTRACT;
return (ULONG)((dac_cast<TADDR>(p) - m_pcEntries) / m_iEntrySize);
}
public:
CHashTable(
ULONG iBuckets) : // # of chains we are hashing into.
m_pcEntries((TADDR)NULL),
m_iBuckets(iBuckets)
{
LIMITED_METHOD_CONTRACT;
m_piBuckets = NULL;
INDEBUG(m_maxSearch = 0;)
}
CHashTable() : // # of chains we are hashing into.
m_pcEntries((TADDR)NULL),
m_iBuckets(5)
{
LIMITED_METHOD_CONTRACT;
m_piBuckets = NULL;
INDEBUG(m_maxSearch = 0;)
}
#ifndef DACCESS_COMPILE
~CHashTable()
{
LIMITED_METHOD_CONTRACT;
if (m_piBuckets != NULL)
{
delete [] m_piBuckets;
m_piBuckets = NULL;
}
}
//*****************************************************************************
// This is the second part of construction where we do all of the work that
// can fail. We also take the array of structs here because the calling class
// presumably needs to allocate it in its NewInit.
//*****************************************************************************
HRESULT NewInit( // Return status.
BYTE *pcEntries, // Array of structs we are managing.
ULONG iEntrySize); // Size of the entries.
//*****************************************************************************
// This can be called to change the pointer to the table that the hash table
// is managing. You might call this if (for example) you realloc the size
// of the table and its pointer is different.
//*****************************************************************************
void SetTable(
BYTE *pcEntries) // Array of structs we are managing.
{
LIMITED_METHOD_CONTRACT;
m_pcEntries = (TADDR)pcEntries;
}
//*****************************************************************************
// Clear the hash table as if there were nothing in it.
//*****************************************************************************
void Clear()
{
LIMITED_METHOD_CONTRACT;
_ASSERTE(m_piBuckets != NULL);
memset(m_piBuckets, 0xff, m_iBuckets * sizeof(ULONG));
}
//*****************************************************************************
// Add the struct at the specified index in m_pcEntries to the hash chains.
//*****************************************************************************
BYTE *Add( // New entry.
ULONG iHash, // Hash value of entry to add.
ULONG iIndex); // Index of struct in m_pcEntries.
//*****************************************************************************
// Delete the struct at the specified index in m_pcEntries from the hash chains.
//*****************************************************************************
void Delete(
ULONG iHash, // Hash value of entry to delete.
ULONG iIndex); // Index of struct in m_pcEntries.
void Delete(
ULONG iHash, // Hash value of entry to delete.
HASHENTRY *psEntry); // The struct to delete.
//*****************************************************************************
// The item at the specified index has been moved, update the previous and
// next item.
//*****************************************************************************
void Move(
ULONG iHash, // Hash value for the item.
ULONG iNew); // New location.
#endif // #ifndef DACCESS_COMPILE
//*****************************************************************************
// Return a boolean indicating whether or not this hash table has been inited.
//*****************************************************************************
int IsInited()
{
LIMITED_METHOD_CONTRACT;
return (m_piBuckets != NULL);
}
//*****************************************************************************
// Search the hash table for an entry with the specified key value.
//*****************************************************************************
BYTE *Find( // Index of struct in m_pcEntries.
ULONG iHash, // Hash value of the item.
SIZE_T key); // The key to match.
//*****************************************************************************
// Search the hash table for the next entry with the specified key value.
//*****************************************************************************
ULONG FindNext( // Index of struct in m_pcEntries.
SIZE_T key, // The key to match.
ULONG iIndex); // Index of previous match.
//*****************************************************************************
// Returns the first entry in the first hash bucket and inits the search
// struct. Use the FindNextEntry function to continue walking the list. The
// return order is not gauranteed.
//*****************************************************************************
BYTE *FindFirstEntry( // First entry found, or 0.
HASHFIND *psSrch) // Search object.
{
WRAPPER_NO_CONTRACT;
if (m_piBuckets == 0)
return (0);
psSrch->iBucket = 1;
psSrch->iNext = m_piBuckets[0];
return (FindNextEntry(psSrch));
}
//*****************************************************************************
// Returns the next entry in the list.
//*****************************************************************************
BYTE *FindNextEntry( // The next entry, or0 for end of list.
HASHFIND *psSrch); // Search object.
#ifdef DACCESS_COMPILE
void EnumMemoryRegions(CLRDataEnumMemoryFlags flags,
ULONG numEntries);
#endif
protected:
virtual BOOL Cmp(SIZE_T key1, const HASHENTRY * pc2) = 0;
};
class CNewData
{
public:
static BYTE *Alloc(int iSize, int iMaxSize)
{
WRAPPER_NO_CONTRACT;
return (new BYTE[iSize]);
}
static void Free(BYTE *pPtr, int iSize)
{
LIMITED_METHOD_CONTRACT;
delete [] pPtr;
}
static BYTE *Grow(BYTE *&pPtr, int iCurSize)
{
WRAPPER_NO_CONTRACT;
BYTE *p;
S_SIZE_T newSize = S_SIZE_T(iCurSize) + S_SIZE_T(GrowSize(iCurSize));
//check for overflow
if(newSize.IsOverflow())
p = NULL;
else
p = new (nothrow) BYTE[newSize.Value()];
if (p == 0) return (0);
memcpy (p, pPtr, iCurSize);
delete [] pPtr;
pPtr = p;
return pPtr;
}
static void Clean(BYTE * pData, int iSize)
{
}
static int RoundSize(int iSize)
{
LIMITED_METHOD_CONTRACT;
return (iSize);
}
static int GrowSize(int iCurSize)
{
LIMITED_METHOD_CONTRACT;
int newSize = (3 * iCurSize) / 2;
return (newSize < 256) ? 256 : newSize;
}
};
class CNewDataNoThrow
{
public:
static BYTE *Alloc(int iSize, int iMaxSize)
{
WRAPPER_NO_CONTRACT;
return (new (nothrow) BYTE[iSize]);
}
static void Free(BYTE *pPtr, int iSize)
{
LIMITED_METHOD_CONTRACT;
delete [] pPtr;
}
static BYTE *Grow(BYTE *&pPtr, int iCurSize)
{
WRAPPER_NO_CONTRACT;
BYTE *p;
S_SIZE_T newSize = S_SIZE_T(iCurSize) + S_SIZE_T(GrowSize(iCurSize));
//check for overflow
if(newSize.IsOverflow())
p = NULL;
else
p = new (nothrow) BYTE[newSize.Value()];
if (p == 0) return (0);
memcpy (p, pPtr, iCurSize);
delete [] pPtr;
pPtr = p;
return pPtr;
}
static void Clean(BYTE * pData, int iSize)
{
}
static int RoundSize(int iSize)
{
LIMITED_METHOD_CONTRACT;
return (iSize);
}
static int GrowSize(int iCurSize)
{
LIMITED_METHOD_CONTRACT;
int newSize = (3 * iCurSize) / 2;
return (newSize < 256) ? 256 : newSize;
}
};
//*****************************************************************************
// IMPORTANT: This data structure is deprecated, please do not add any new uses.
// The hashtable implementation that should be used instead is code:SHash.
// If code:SHash does not work for you, talk to mailto:clrdeag.
//*****************************************************************************
// CHashTable expects the data to be in a single array - this is provided by
// CHashTableAndData.
// The array is allocated using the MemMgr type. CNewData and
// CNewDataNoThrow can be used for this.
//*****************************************************************************
template <class MemMgr>
class CHashTableAndData : public CHashTable
{
public:
ULONG m_iFree; // Index into m_pcEntries[] of next available slot
ULONG m_iEntries; // size of m_pcEntries[]
public:
CHashTableAndData() :
CHashTable()
{
LIMITED_METHOD_CONTRACT;
}
CHashTableAndData(
ULONG iBuckets) : // # of chains we are hashing into.
CHashTable(iBuckets)
{
LIMITED_METHOD_CONTRACT;
}
#ifndef DACCESS_COMPILE
~CHashTableAndData()
{
WRAPPER_NO_CONTRACT;
if (m_pcEntries != NULL)
MemMgr::Free((BYTE*)m_pcEntries, MemMgr::RoundSize(m_iEntries * m_iEntrySize));
}
//*****************************************************************************
// This is the second part of construction where we do all of the work that
// can fail. We also take the array of structs here because the calling class
// presumably needs to allocate it in its NewInit.
//*****************************************************************************
HRESULT NewInit( // Return status.
ULONG iEntries, // # of entries.
ULONG iEntrySize, // Size of the entries.
int iMaxSize); // Max size of data.
//*****************************************************************************
// Clear the hash table as if there were nothing in it.
//*****************************************************************************
void Clear()
{
WRAPPER_NO_CONTRACT;
m_iFree = 0;
InitFreeChain(0, m_iEntries);
CHashTable::Clear();
}
//*****************************************************************************
// Grabs a slot for the new entry to be added.
// The caller should fill in the non-HASHENTRY part of the returned slot
//*****************************************************************************
BYTE *Add(
ULONG iHash) // Hash value of entry to add.
{
WRAPPER_NO_CONTRACT;
FREEHASHENTRY *psEntry;
// Make the table bigger if necessary.
if (m_iFree == UINT32_MAX && !Grow())
return (NULL);
// Add the first entry from the free list to the hash chain.
psEntry = (FREEHASHENTRY *) CHashTable::Add(iHash, m_iFree);
m_iFree = psEntry->iFree;
// If we're recycling memory, give our memory-allocator a chance to re-init it.
// Each entry is prefixed with a header - we don't want to trash that.
SIZE_T cbHeader = sizeof(FREEHASHENTRY);
MemMgr::Clean((BYTE*) psEntry + cbHeader, (int) (m_iEntrySize - cbHeader));
return ((BYTE *) psEntry);
}
//*****************************************************************************
// Delete the struct at the specified index in m_pcEntries from the hash chains.
//*****************************************************************************
void Delete(
ULONG iHash, // Hash value of entry to delete.
ULONG iIndex) // Index of struct in m_pcEntries.
{
WRAPPER_NO_CONTRACT;
CHashTable::Delete(iHash, iIndex);
((FREEHASHENTRY *) EntryPtr(iIndex))->iFree = m_iFree;
m_iFree = iIndex;
}
void Delete(
ULONG iHash, // Hash value of entry to delete.
HASHENTRY *psEntry) // The struct to delete.
{
WRAPPER_NO_CONTRACT;
CHashTable::Delete(iHash, psEntry);
((FREEHASHENTRY *) psEntry)->iFree = m_iFree;
m_iFree = ItemIndex(psEntry);
}
#endif // #ifndef DACCESS_COMPILE
// This is a sad legacy workaround. The debugger's patch table (implemented as this
// class) is shared across process. We publish the runtime offsets of
// some key fields. Since those fields are private, we have to provide
// accessors here. So if you're not using these functions, don't start.
// We can hopefully remove them.
// Note that we can't just make RCThread a friend of this class (we tried
// originally) because the inheritence chain has a private modifier,
// so DebuggerPatchTable::m_pcEntries is illegal.
static SIZE_T helper_GetOffsetOfEntries()
{
LIMITED_METHOD_CONTRACT;
return offsetof(CHashTableAndData, m_pcEntries);
}
static SIZE_T helper_GetOffsetOfCount()
{
LIMITED_METHOD_CONTRACT;
return offsetof(CHashTableAndData, m_iEntries);
}
#ifdef DACCESS_COMPILE
void EnumMemoryRegions(CLRDataEnumMemoryFlags flags)
{
SUPPORTS_DAC;
CHashTable::EnumMemoryRegions(flags, m_iEntries);
}
#endif
private:
void InitFreeChain(ULONG iStart,ULONG iEnd);
int Grow();
};
#ifndef DACCESS_COMPILE
//*****************************************************************************
// This is the second part of construction where we do all of the work that
// can fail. We also take the array of structs here because the calling class
// presumably needs to allocate it in its NewInit.
//*****************************************************************************
template<class MemMgr>
HRESULT CHashTableAndData<MemMgr>::NewInit(// Return status.
ULONG iEntries, // # of entries.
ULONG iEntrySize, // Size of the entries.
int iMaxSize) // Max size of data.
{
WRAPPER_NO_CONTRACT;
BYTE *pcEntries;
HRESULT hr;
// note that this function can throw because it depends on the <M>::Alloc
// Allocate the memory for the entries.
if ((pcEntries = MemMgr::Alloc(MemMgr::RoundSize(iEntries * iEntrySize),
MemMgr::RoundSize(iMaxSize))) == 0)
return (E_OUTOFMEMORY);
m_iEntries = iEntries;
// Init the base table.
if (FAILED(hr = CHashTable::NewInit(pcEntries, iEntrySize)))
MemMgr::Free(pcEntries, MemMgr::RoundSize(iEntries * iEntrySize));
else
{
// Init the free chain.
m_iFree = 0;
InitFreeChain(0, iEntries);
}
return (hr);
}
//*****************************************************************************
// Initialize a range of records such that they are linked together to be put
// on the free chain.
//*****************************************************************************
template<class MemMgr>
void CHashTableAndData<MemMgr>::InitFreeChain(
ULONG iStart, // Index to start initializing.
ULONG iEnd) // Index to stop initializing
{
LIMITED_METHOD_CONTRACT;
BYTE* pcPtr;
_ASSERTE(iEnd > iStart);
pcPtr = (BYTE*)m_pcEntries + iStart * m_iEntrySize;
for (++iStart; iStart < iEnd; ++iStart)
{
((FREEHASHENTRY *) pcPtr)->iFree = iStart;
pcPtr += m_iEntrySize;
}
((FREEHASHENTRY *) pcPtr)->iFree = UINT32_MAX;
}
//*****************************************************************************
// Attempt to increase the amount of space available for the record heap.
//*****************************************************************************
template<class MemMgr>
int CHashTableAndData<MemMgr>::Grow() // 1 if successful, 0 if not.
{
WRAPPER_NO_CONTRACT;
int iCurSize; // Current size in bytes.
int iEntries; // New # of entries.
_ASSERTE(m_pcEntries != NULL);
_ASSERTE(m_iFree == UINT32_MAX);
// Compute the current size and new # of entries.
S_UINT32 iTotEntrySize = S_UINT32(m_iEntries) * S_UINT32(m_iEntrySize);
if( iTotEntrySize.IsOverflow() )
{
_ASSERTE( !"CHashTableAndData overflow!" );
return (0);
}
iCurSize = MemMgr::RoundSize( iTotEntrySize.Value() );
iEntries = (iCurSize + MemMgr::GrowSize(iCurSize)) / m_iEntrySize;
if ( (iEntries < 0) || ((ULONG)iEntries <= m_iEntries) )
{
_ASSERTE( !"CHashTableAndData overflow!" );
return (0);
}
// Try to expand the array.
if (MemMgr::Grow(*(BYTE**)&m_pcEntries, iCurSize) == 0)
return (0);
// Init the newly allocated space.
InitFreeChain(m_iEntries, iEntries);
m_iFree = m_iEntries;
m_iEntries = iEntries;
return (1);
}
#endif // #ifndef DACCESS_COMPILE
//*****************************************************************************
//*****************************************************************************
inline COUNT_T HashCOUNT_T(COUNT_T currentHash, COUNT_T data)
{
LIMITED_METHOD_DAC_CONTRACT;
return ((currentHash << 5) + currentHash) ^ data;
}
inline COUNT_T HashPtr(COUNT_T currentHash, PTR_VOID ptr)
{
WRAPPER_NO_CONTRACT;
SUPPORTS_DAC;
return HashCOUNT_T(currentHash, COUNT_T(SIZE_T(dac_cast<TADDR>(ptr))));
}
inline DWORD HashThreeToOne(DWORD a, DWORD b, DWORD c)
{
LIMITED_METHOD_DAC_CONTRACT;
// Current implementation taken from lookup3.c, by Bob Jenkins, May 2006
#define rot32(x,k) (((x)<<(k)) | ((x)>>(32-(k))))
c ^= b; c -= rot32(b,14);
a ^= c; a -= rot32(c,11);
b ^= a; b -= rot32(a,25);
c ^= b; c -= rot32(b,16);
a ^= c; a -= rot32(c,4);
b ^= a; b -= rot32(a,14);
c ^= b; c -= rot32(b,24);
return c;
}
inline ULONG HashBytes(BYTE const *pbData, size_t iSize)
{
LIMITED_METHOD_CONTRACT;
ULONG hash = 5381;
BYTE const *pbDataEnd = pbData + iSize;
for (/**/ ; pbData < pbDataEnd; pbData++)
{
hash = ((hash << 5) + hash) ^ *pbData;
}
return hash;
}
// Helper function for hashing a string char by char.
inline ULONG HashStringA(LPCSTR szStr)
{
LIMITED_METHOD_CONTRACT;
ULONG hash = 5381;
int c;
while ((c = *szStr) != 0)
{
hash = ((hash << 5) + hash) ^ c;
++szStr;
}
return hash;
}
inline ULONG HashString(LPCWSTR szStr)
{
LIMITED_METHOD_CONTRACT;
ULONG hash = 5381;
int c;
while ((c = *szStr) != 0)
{
hash = ((hash << 5) + hash) ^ c;
++szStr;
}
return hash;
}
inline ULONG HashStringN(LPCWSTR szStr, SIZE_T cchStr)
{
LIMITED_METHOD_CONTRACT;
ULONG hash = 5381;
// hash the string two characters at a time
ULONG *ptr = (ULONG *)szStr;
// we assume that szStr is null-terminated
_ASSERTE(cchStr <= wcslen(szStr));
SIZE_T cDwordCount = (cchStr + 1) / 2;
for (SIZE_T i = 0; i < cDwordCount; i++)
{
hash = ((hash << 5) + hash) ^ ptr[i];
}
return hash;
}
// Case-insensitive string hash function.
inline ULONG HashiStringA(LPCSTR szStr)
{
LIMITED_METHOD_CONTRACT;
ULONG hash = 5381;
while (*szStr != 0)
{
hash = ((hash << 5) + hash) ^ toupper(*szStr);
szStr++;
}
return hash;
}
// Case-insensitive string hash function.
inline ULONG HashiString(LPCWSTR szStr)
{
LIMITED_METHOD_CONTRACT;
ULONG hash = 5381;
while (*szStr != 0)
{
hash = ((hash << 5) + hash) ^ towupper(*szStr);
szStr++;
}
return hash;
}
// Case-insensitive string hash function.
inline ULONG HashiStringN(LPCWSTR szStr, DWORD count)
{
LIMITED_METHOD_CONTRACT;
ULONG hash = 5381;
while (*szStr != 0 && count--)
{
hash = ((hash << 5) + hash) ^ towupper(*szStr);
szStr++;
}
return hash;
}
// Case-insensitive string hash function when all of the
// characters in the string are known to be below 0x80.
// Knowing this is much more efficient than calling
// towupper above.
inline ULONG HashiStringKnownLower80(LPCWSTR szStr) {
LIMITED_METHOD_CONTRACT;
ULONG hash = 5381;
int c;
int mask = ~0x20;
while ((c = *szStr)!=0) {
//If we have a lowercase character, ANDing off 0x20
//(mask) will make it an uppercase character.
if (c>='a' && c<='z') {
c&=mask;
}
hash = ((hash << 5) + hash) ^ c;
++szStr;
}
return hash;
}
inline ULONG HashiStringNKnownLower80(LPCWSTR szStr, DWORD count) {
LIMITED_METHOD_CONTRACT;
ULONG hash = 5381;
int c;
int mask = ~0x20;
while ((c = *szStr) !=0 && count--) {
//If we have a lowercase character, ANDing off 0x20
//(mask) will make it an uppercase character.
if (c>='a' && c<='z') {
c&=mask;
}
hash = ((hash << 5) + hash) ^ c;
++szStr;
}
return hash;
}
// // //
// // // See $\src\utilcode\Debug.cpp for "Binomial (K, M, N)", which
// // // computes the binomial distribution, with which to compare your
// // // hash-table statistics.
// // //
//*****************************************************************************
// IMPORTANT: This data structure is deprecated, please do not add any new uses.
// The hashtable implementation that should be used instead is code:SHash.
// If code:SHash does not work for you, talk to mailto:clrdeag.
//*****************************************************************************
// This class implements a closed hashing table. Values are hashed to a bucket,
// and if that bucket is full already, then the value is placed in the next
// free bucket starting after the desired target (with wrap around). If the
// table becomes 75% full, it is grown and rehashed to reduce lookups. This
// class is best used in a reltively small lookup table where hashing is
// not going to cause many collisions. By not having the collision chain
// logic, a lot of memory is saved.
//
// The user of the template is required to supply several methods which decide
// how each element can be marked as free, deleted, or used. It would have
// been possible to write this with more internal logic, but that would require
// either (a) more overhead to add status on top of elements, or (b) hard
// coded types like one for strings, one for ints, etc... This gives you the
// flexibility of adding logic to your type.
//*****************************************************************************
class CClosedHashBase
{
BYTE *EntryPtr(int iEntry)
{
LIMITED_METHOD_CONTRACT;
return (m_rgData + (iEntry * m_iEntrySize));
}
BYTE *EntryPtr(int iEntry, BYTE *rgData)
{
LIMITED_METHOD_CONTRACT;
return (rgData + (iEntry * m_iEntrySize));
}
public:
enum ELEMENTSTATUS
{
FREE, // Item is not in use right now.
DELETED, // Item is deleted.
USED // Item is in use.
};
CClosedHashBase(
int iBuckets, // How many buckets should we start with.
int iEntrySize, // Size of an entry.
bool bPerfect) : // true if bucket size will hash with no collisions.
m_bPerfect(bPerfect),
m_iBuckets(iBuckets),
m_iEntrySize(iEntrySize),
m_iCount(0),
m_iCollisions(0),
m_rgData(0)
{
LIMITED_METHOD_CONTRACT;
m_iSize = iBuckets + 7;
}
~CClosedHashBase()
{
WRAPPER_NO_CONTRACT;
Clear();
}
virtual void Clear()
{
LIMITED_METHOD_CONTRACT;
delete [] m_rgData;
m_iCount = 0;
m_iCollisions = 0;
m_rgData = 0;
}
//*****************************************************************************
// Accessors for getting at the underlying data. Be careful to use Count()
// only when you want the number of buckets actually used.
//*****************************************************************************
int Count()
{
LIMITED_METHOD_CONTRACT;
return (m_iCount);
}
int Collisions()
{
LIMITED_METHOD_CONTRACT;
return (m_iCollisions);
}
int Buckets()
{
LIMITED_METHOD_CONTRACT;
return (m_iBuckets);
}
void SetBuckets(int iBuckets, bool bPerfect=false)
{
LIMITED_METHOD_CONTRACT;
_ASSERTE(m_rgData == 0);
m_iBuckets = iBuckets;
m_iSize = m_iBuckets + 7;
m_bPerfect = bPerfect;
}
BYTE *Data()
{
LIMITED_METHOD_CONTRACT;
return (m_rgData);
}
//*****************************************************************************
// Add a new item to hash table given the key value. If this new entry
// exceeds maximum size, then the table will grow and be re-hashed, which
// may cause a memory error.
//*****************************************************************************
BYTE *Add( // New item to fill out on success.
void *pData) // The value to hash on.
{
WRAPPER_NO_CONTRACT;
// If we haven't allocated any memory, or it is too small, fix it.
if (!m_rgData || ((m_iCount + 1) > (m_iSize * 3 / 4) && !m_bPerfect))
{
if (!ReHash())
return (0);
}
return (DoAdd(pData, m_rgData, m_iBuckets, m_iSize, m_iCollisions, m_iCount));
}
//*****************************************************************************
// Delete the given value. This will simply mark the entry as deleted (in
// order to keep the collision chain intact). There is an optimization that
// consecutive deleted entries leading up to a free entry are themselves freed
// to reduce collisions later on.
//*****************************************************************************
void Delete(
void *pData); // Key value to delete.
//*****************************************************************************
// Callback function passed to DeleteLoop.
//*****************************************************************************
typedef BOOL (* DELETELOOPFUNC)( // Delete current item?
BYTE *pEntry, // Bucket entry to evaluate
void *pCustomizer); // User-defined value
//*****************************************************************************
// Iterates over all active values, passing each one to pDeleteLoopFunc.
// If pDeleteLoopFunc returns TRUE, the entry is deleted. This is safer
// and faster than using FindNext() and Delete().
//*****************************************************************************
void DeleteLoop(
DELETELOOPFUNC pDeleteLoopFunc, // Decides whether to delete item
void *pCustomizer); // Extra value passed to deletefunc.
//*****************************************************************************
// Lookup a key value and return a pointer to the element if found.
//*****************************************************************************
BYTE *Find( // The item if found, 0 if not.
void *pData); // The key to lookup.
//*****************************************************************************
// Look for an item in the table. If it isn't found, then create a new one and
// return that.
//*****************************************************************************
BYTE *FindOrAdd( // The item if found, 0 if not.
void *pData, // The key to lookup.
bool &bNew); // true if created.
//*****************************************************************************
// The following functions are used to traverse each used entry. This code
// will skip over deleted and free entries freeing the caller up from such
// logic.
//*****************************************************************************
BYTE *GetFirst() // The first entry, 0 if none.
{
WRAPPER_NO_CONTRACT;
int i; // Loop control.
// If we've never allocated the table there can't be any to get.
if (m_rgData == 0)
return (0);
// Find the first one.
for (i=0; i<m_iSize; i++)
{
if (Status(EntryPtr(i)) != FREE && Status(EntryPtr(i)) != DELETED)
return (EntryPtr(i));
}
return (0);
}
BYTE *GetNext(BYTE *Prev) // The next entry, 0 if done.
{
WRAPPER_NO_CONTRACT;
int i; // Loop control.
for (i = (int)(((size_t) Prev - (size_t) &m_rgData[0]) / m_iEntrySize) + 1; i<m_iSize; i++)
{
if (Status(EntryPtr(i)) != FREE && Status(EntryPtr(i)) != DELETED)
return (EntryPtr(i));
}
return (0);
}
private:
//*****************************************************************************
// Hash is called with a pointer to an element in the table. You must override
// this method and provide a hash algorithm for your element type.
//*****************************************************************************
virtual unsigned int Hash( // The key value.
void const *pData)=0; // Raw data to hash.
//*****************************************************************************
// Compare is used in the typical memcmp way, 0 is eqaulity, -1/1 indicate
// direction of miscompare. In this system everything is always equal or not.
//*****************************************************************************
virtual unsigned int Compare( // 0, -1, or 1.
void const *pData, // Raw key data on lookup.
BYTE *pElement)=0; // The element to compare data against.
//*****************************************************************************
// Return true if the element is free to be used.
//*****************************************************************************
virtual ELEMENTSTATUS Status( // The status of the entry.
BYTE *pElement)=0; // The element to check.
//*****************************************************************************
// Sets the status of the given element.
//*****************************************************************************
virtual void SetStatus(
BYTE *pElement, // The element to set status for.
ELEMENTSTATUS eStatus)=0; // New status.
//*****************************************************************************
// Returns the internal key value for an element.
//*****************************************************************************
virtual void *GetKey( // The data to hash on.
BYTE *pElement)=0; // The element to return data ptr for.
//*****************************************************************************
// This helper actually does the add for you.
//*****************************************************************************
BYTE *DoAdd(void *pData, BYTE *rgData, int &iBuckets, int iSize,
int &iCollisions, int &iCount);
//*****************************************************************************
// This function is called either to init the table in the first place, or
// to rehash the table if we ran out of room.
//*****************************************************************************
bool ReHash(); // true if successful.
//*****************************************************************************
// Walk each item in the table and mark it free.
//*****************************************************************************
void InitFree(BYTE *ptr, int iSize)
{
WRAPPER_NO_CONTRACT;
int i;
for (i=0; i<iSize; i++, ptr += m_iEntrySize)
SetStatus(ptr, FREE);
}
private:
bool m_bPerfect; // true if the table size guarantees
// no collisions.
int m_iBuckets; // How many buckets do we have.
int m_iEntrySize; // Size of an entry.
int m_iSize; // How many elements can we have.
int m_iCount; // How many items cannot be used (NON free, i.e. USED+DELETED).
int m_iCollisions; // How many have we had.
BYTE *m_rgData; // Data element list.
};
//*****************************************************************************
// IMPORTANT: This data structure is deprecated, please do not add any new uses.
// The hashtable implementation that should be used instead is code:SHash.
// If code:SHash does not work for you, talk to mailto:clrdeag.
//*****************************************************************************
template <class T> class CClosedHash : public CClosedHashBase
{
public:
CClosedHash(
int iBuckets, // How many buckets should we start with.
bool bPerfect=false) : // true if bucket size will hash with no collisions.
CClosedHashBase(iBuckets, sizeof(T), bPerfect)
{
WRAPPER_NO_CONTRACT;
}
T &operator[](int iIndex)
{
WRAPPER_NO_CONTRACT;
return ((T &) *(Data() + (iIndex * sizeof(T))));
}
//*****************************************************************************
// Add a new item to hash table given the key value. If this new entry
// exceeds maximum size, then the table will grow and be re-hashed, which
// may cause a memory error.
//*****************************************************************************
T *Add( // New item to fill out on success.
void *pData) // The value to hash on.
{
WRAPPER_NO_CONTRACT;
return ((T *) CClosedHashBase::Add(pData));
}
//*****************************************************************************
// Lookup a key value and return a pointer to the element if found.
//*****************************************************************************
T *Find( // The item if found, 0 if not.
void *pData) // The key to lookup.
{
WRAPPER_NO_CONTRACT;
return ((T *) CClosedHashBase::Find(pData));
}
//*****************************************************************************
// Look for an item in the table. If it isn't found, then create a new one and
// return that.
//*****************************************************************************
T *FindOrAdd( // The item if found, 0 if not.
void *pData, // The key to lookup.
bool &bNew) // true if created.
{
WRAPPER_NO_CONTRACT;
return ((T *) CClosedHashBase::FindOrAdd(pData, bNew));
}
//*****************************************************************************
// The following functions are used to traverse each used entry. This code
// will skip over deleted and free entries freeing the caller up from such
// logic.
//*****************************************************************************
T *GetFirst() // The first entry, 0 if none.
{
WRAPPER_NO_CONTRACT;
return ((T *) CClosedHashBase::GetFirst());
}
T *GetNext(T *Prev) // The next entry, 0 if done.
{
WRAPPER_NO_CONTRACT;
return ((T *) CClosedHashBase::GetNext((BYTE *) Prev));
}
};
//*****************************************************************************
// IMPORTANT: This data structure is deprecated, please do not add any new uses.
// The hashtable implementation that should be used instead is code:SHash.
// If code:SHash does not work for you, talk to mailto:clrdeag.
//*****************************************************************************
// Closed hash with typed parameters. The derived class is the second
// parameter to the template. The derived class must implement:
// unsigned long Hash(const T *pData);
// unsigned long Compare(const T *p1, T *p2);
// ELEMENTSTATUS Status(T *pEntry);
// void SetStatus(T *pEntry, ELEMENTSTATUS s);
// void* GetKey(T *pEntry);
//*****************************************************************************
template<class T, class H>class CClosedHashEx : public CClosedHash<T>
{
public:
CClosedHashEx(
int iBuckets, // How many buckets should we start with.
bool bPerfect=false) : // true if bucket size will hash with no collisions.
CClosedHash<T> (iBuckets, bPerfect)
{
WRAPPER_NO_CONTRACT;
}
unsigned int Hash(const void *pData)
{
WRAPPER_NO_CONTRACT;
return static_cast<H*>(this)->Hash((const T*)pData);
}
unsigned int Compare(const void *p1, BYTE *p2)
{
WRAPPER_NO_CONTRACT;
return static_cast<H*>(this)->Compare((const T*)p1, (T*)p2);
}
typename CClosedHash<T>::ELEMENTSTATUS Status(BYTE *p)
{
WRAPPER_NO_CONTRACT;
return static_cast<H*>(this)->Status((T*)p);
}
void SetStatus(BYTE *p, typename CClosedHash<T>::ELEMENTSTATUS s)
{
WRAPPER_NO_CONTRACT;
static_cast<H*>(this)->SetStatus((T*)p, s);
}
void* GetKey(BYTE *p)
{
WRAPPER_NO_CONTRACT;
return static_cast<H*>(this)->GetKey((T*)p);
}
};
//*****************************************************************************
// IMPORTANT: This data structure is deprecated, please do not add any new uses.
// The hashtable implementation that should be used instead is code:SHash.
// If code:SHash does not work for you, talk to mailto:clrdeag.
//*****************************************************************************
// This template is another form of a closed hash table. It handles collisions
// through a linked chain. To use it, derive your hashed item from HASHLINK
// and implement the virtual functions required. 1.5 * ibuckets will be
// allocated, with the extra .5 used for collisions. If you add to the point
// where no free nodes are available, the entire table is grown to make room.
// The advantage to this system is that collisions are always directly known,
// there either is one or there isn't.
//*****************************************************************************
struct HASHLINK
{
ULONG iNext; // Offset for next entry.
};
template <class T> class CChainedHash
{
friend class VerifyLayoutsMD;
public:
CChainedHash(int iBuckets=32) :
m_rgData(0),
m_iBuckets(iBuckets),
m_iCount(0),
m_iMaxChain(0),
m_iFree(0)
{
LIMITED_METHOD_CONTRACT;
m_iSize = iBuckets + (iBuckets / 2);
}
~CChainedHash()
{
LIMITED_METHOD_CONTRACT;
if (m_rgData)
delete [] m_rgData;
}
void SetBuckets(int iBuckets)
{
LIMITED_METHOD_CONTRACT;
_ASSERTE(m_rgData == 0);
// if iBuckets==0, then we'll allocate a zero size array and AV on dereference.
_ASSERTE(iBuckets > 0);
m_iBuckets = iBuckets;
m_iSize = iBuckets + (iBuckets / 2);
}
T *Add(void const *pData)
{
WRAPPER_NO_CONTRACT;
ULONG iHash;
int iBucket;
T *pItem;
// Build the list if required.
if (m_rgData == 0 || m_iFree == 0xffffffff)
{
if (!ReHash())
return (0);
}
// Hash the item and pick a bucket.
iHash = Hash(pData);
iBucket = iHash % m_iBuckets;
// Use the bucket if it is free.
if (InUse(&m_rgData[iBucket]) == false)
{
pItem = &m_rgData[iBucket];
pItem->iNext = 0xffffffff;
}
// Else take one off of the free list for use.
else
{
ULONG iEntry;
// Pull an item from the free list.
iEntry = m_iFree;
pItem = &m_rgData[m_iFree];
m_iFree = pItem->iNext;
// Link the new node in after the bucket.
pItem->iNext = m_rgData[iBucket].iNext;
m_rgData[iBucket].iNext = iEntry;
}
++m_iCount;
return (pItem);
}
T *Find(void const *pData, bool bAddIfNew=false)
{
WRAPPER_NO_CONTRACT;
ULONG iHash;
int iBucket;
T *pItem;
// Check states for lookup.
if (m_rgData == 0)
{
// If we won't be adding, then we are through.
if (bAddIfNew == false)
return (0);
// Otherwise, create the table.
if (!ReHash())
return (0);
}
// Hash the item and pick a bucket.
iHash = Hash(pData);
iBucket = iHash % m_iBuckets;
// If it isn't in use, then there it wasn't found.
if (!InUse(&m_rgData[iBucket]))
{
if (bAddIfNew == false)
pItem = 0;
else
{
pItem = &m_rgData[iBucket];
pItem->iNext = 0xffffffff;
++m_iCount;
}
}
// Scan the list for the one we want.
else
{
ULONG iChain = 0;
for (pItem=(T *) &m_rgData[iBucket]; pItem; pItem=GetNext(pItem))
{
if (Cmp(pData, pItem) == 0)
break;
++iChain;
}
if (!pItem && bAddIfNew)
{
ULONG iEntry;
// Record maximum chain length.
if (iChain > m_iMaxChain)
m_iMaxChain = iChain;
// Now need more room.
if (m_iFree == 0xffffffff)
{
if (!ReHash())
return (0);
}
// Pull an item from the free list.
iEntry = m_iFree;
pItem = &m_rgData[m_iFree];
m_iFree = pItem->iNext;
// Link the new node in after the bucket.
pItem->iNext = m_rgData[iBucket].iNext;
m_rgData[iBucket].iNext = iEntry;
++m_iCount;
}
}
return (pItem);
}
int Count()
{
LIMITED_METHOD_CONTRACT;
return (m_iCount);
}
int Buckets()
{
LIMITED_METHOD_CONTRACT;
return (m_iBuckets);
}
ULONG MaxChainLength()
{
LIMITED_METHOD_CONTRACT;
return (m_iMaxChain);
}
virtual void Clear()
{
LIMITED_METHOD_CONTRACT;
// Free up the memory.
if (m_rgData)
{
delete [] m_rgData;
m_rgData = 0;
}
m_rgData = 0;
m_iFree = 0;
m_iCount = 0;
m_iMaxChain = 0;
}
virtual bool InUse(T *pItem)=0;
virtual void SetFree(T *pItem)=0;
virtual ULONG Hash(void const *pData)=0;
virtual int Cmp(void const *pData, void *pItem)=0;
private:
inline T *GetNext(T *pItem)
{
LIMITED_METHOD_CONTRACT;
if (pItem->iNext != 0xffffffff)
return ((T *) &m_rgData[pItem->iNext]);
return (0);
}
bool ReHash()
{
WRAPPER_NO_CONTRACT;
T *rgTemp;
int iNewSize;
// If this is a first time allocation, then just malloc it.
if (!m_rgData)
{
if ((m_rgData = new (nothrow) T[m_iSize]) == 0)
return (false);
int i;
for (i=0; i<m_iSize; i++)
SetFree(&m_rgData[i]);
m_iFree = m_iBuckets;
for (i=m_iBuckets; i<m_iSize; i++)
((T *) &m_rgData[i])->iNext = i + 1;
((T *) &m_rgData[m_iSize - 1])->iNext = 0xffffffff;
return (true);
}
// Otherwise we need more room on the free chain, so allocate some.
iNewSize = m_iSize + (m_iSize / 2);
// Allocate/realloc memory.
if ((rgTemp = new (nothrow) T[iNewSize]) == 0)
return (false);
memcpy (rgTemp,m_rgData,m_iSize*sizeof(T));
delete [] m_rgData;
// Init new entries, save the new free chain, and reset internals.
m_iFree = m_iSize;
for (int i=m_iFree; i<iNewSize; i++)
{
SetFree(&rgTemp[i]);
((T *) &rgTemp[i])->iNext = i + 1;
}
((T *) &rgTemp[iNewSize - 1])->iNext = 0xffffffff;
m_rgData = rgTemp;
m_iSize = iNewSize;
return (true);
}
private:
T *m_rgData; // Data to store items in.
int m_iBuckets; // How many buckets we want.
int m_iSize; // How many are allocated.
int m_iCount; // How many are we using.
ULONG m_iMaxChain; // Max chain length.
ULONG m_iFree; // Free chain.
};
//*****************************************************************************
//
//********** String helper functions.
//
//*****************************************************************************
//*****************************************************************************
// Checks if string length exceeds the specified limit
//*****************************************************************************
inline BOOL IsStrLongerThan(__in __in_z char* pstr, unsigned N)
{
LIMITED_METHOD_CONTRACT;
unsigned i = 0;
if(pstr)
{
for(i=0; (i < N)&&(pstr[i]); i++);
}
return (i >= N);
}
//*****************************************************************************
// Class to parse a list of simple assembly names and then find a match
//*****************************************************************************
class AssemblyNamesList
{
struct AssemblyName
{
LPUTF8 m_assemblyName;
AssemblyName *m_next; // Next name
};
AssemblyName *m_pNames; // List of names
public:
bool IsInList(LPCUTF8 assemblyName);
bool IsEmpty()
{
LIMITED_METHOD_CONTRACT;
return m_pNames == 0;
}
AssemblyNamesList(__in LPWSTR list);
~AssemblyNamesList();
};
//*****************************************************************************
// Class to parse a list of method names and then find a match
//*****************************************************************************
class MethodNamesListBase
{
struct MethodName
{
LPUTF8 methodName; // NULL means wildcard
LPUTF8 className; // NULL means wildcard
int numArgs; // number of args for the method, -1 is wildcard
MethodName *next; // Next name
};
MethodName *pNames; // List of names
public:
void Init()
{
LIMITED_METHOD_CONTRACT;
pNames = 0;
}
void Init(__in __in_z LPWSTR list)
{
WRAPPER_NO_CONTRACT;
pNames = 0;
Insert(list);
}
void Destroy();
void Insert(__in __in_z LPWSTR list);
bool IsInList(LPCUTF8 methodName, LPCUTF8 className, PCCOR_SIGNATURE sig);
bool IsEmpty()
{
LIMITED_METHOD_CONTRACT;
return pNames == 0;
}
};
class MethodNamesList : public MethodNamesListBase
{
public:
MethodNamesList()
{
WRAPPER_NO_CONTRACT;
Init();
}
MethodNamesList(__in LPWSTR list)
{
WRAPPER_NO_CONTRACT;
Init(list);
}
~MethodNamesList()
{
WRAPPER_NO_CONTRACT;
Destroy();
}
};
/**************************************************************************/
/* simple wrappers around the REGUTIL and MethodNameList routines that make
the lookup lazy */
/* to be used as static variable - no constructor/destructor, assumes zero
initialized memory */
class ConfigDWORD
{
public:
//
// NOTE: The following function is deprecated; use the CLRConfig class instead.
// To access a configuration value through CLRConfig, add an entry in file:../inc/CLRConfigValues.h.
//
inline DWORD val_DontUse_(__in __in_z LPCWSTR keyName, DWORD defaultVal=0)
{
WRAPPER_NO_CONTRACT;
// make sure that the memory was zero initialized
_ASSERTE(m_inited == 0 || m_inited == 1);
if (!m_inited) init_DontUse_(keyName, defaultVal);
return m_value;
}
inline DWORD val(const CLRConfig::ConfigDWORDInfo & info)
{
WRAPPER_NO_CONTRACT;
// make sure that the memory was zero initialized
_ASSERTE(m_inited == 0 || m_inited == 1);
if (!m_inited) init(info);
return m_value;
}
private:
void init_DontUse_(__in __in_z LPCWSTR keyName, DWORD defaultVal=0);
void init(const CLRConfig::ConfigDWORDInfo & info);
private:
DWORD m_value;
BYTE m_inited;
};
/**************************************************************************/
class ConfigString
{
public:
inline LPWSTR val(const CLRConfig::ConfigStringInfo & info)
{
WRAPPER_NO_CONTRACT;
// make sure that the memory was zero initialized
_ASSERTE(m_inited == 0 || m_inited == 1);
if (!m_inited) init(info);
return m_value;
}
bool isInitialized()
{
WRAPPER_NO_CONTRACT;
// make sure that the memory was zero initialized
_ASSERTE(m_inited == 0 || m_inited == 1);
return m_inited == 1;
}
private:
void init(const CLRConfig::ConfigStringInfo & info);
private:
LPWSTR m_value;
BYTE m_inited;
};
/**************************************************************************/
class ConfigMethodSet
{
public:
bool isEmpty()
{
WRAPPER_NO_CONTRACT;
_ASSERTE(m_inited == 1);
return m_list.IsEmpty();
}
bool contains(LPCUTF8 methodName, LPCUTF8 className, PCCOR_SIGNATURE sig);
inline void ensureInit(const CLRConfig::ConfigStringInfo & info)
{
WRAPPER_NO_CONTRACT;
// make sure that the memory was zero initialized
_ASSERTE(m_inited == 0 || m_inited == 1);
if (!m_inited) init(info);
}
private:
void init(const CLRConfig::ConfigStringInfo & info);
private:
MethodNamesListBase m_list;
BYTE m_inited;
};
//*****************************************************************************
// Convert a pointer to a string into a GUID.
//*****************************************************************************
HRESULT LPCSTRToGuid( // Return status.
LPCSTR szGuid, // String to convert.
GUID *psGuid); // Buffer for converted GUID.
//*****************************************************************************
// Convert a GUID into a pointer to a string
//*****************************************************************************
int GuidToLPWSTR( // Return status.
GUID Guid, // [IN] The GUID to convert.
__out_ecount (cchGuid) LPWSTR szGuid, // [OUT] String into which the GUID is stored
DWORD cchGuid); // [IN] Size in wide chars of szGuid
//*****************************************************************************
// Parse a Wide char string into a GUID
//*****************************************************************************
BOOL LPWSTRToGuid(
GUID * Guid, // [OUT] The GUID to fill in
__in_ecount(cchGuid) LPCWSTR szGuid, // [IN] String to parse
DWORD cchGuid); // [IN] Count in wchars in string
typedef VPTR(class RangeList) PTR_RangeList;
class RangeList
{
public:
VPTR_BASE_CONCRETE_VTABLE_CLASS(RangeList)
#ifndef DACCESS_COMPILE
RangeList();
~RangeList();
#else
RangeList()
{
LIMITED_METHOD_CONTRACT;
}
#endif
// Wrappers to make the virtual calls DAC-safe.
BOOL AddRange(const BYTE *start, const BYTE *end, void *id)
{
return this->AddRangeWorker(start, end, id);
}
void RemoveRanges(void *id, const BYTE *start = NULL, const BYTE *end = NULL)
{
return this->RemoveRangesWorker(id, start, end);
}
BOOL IsInRange(TADDR address, TADDR *pID = NULL)
{
SUPPORTS_DAC;
return this->IsInRangeWorker(address, pID);
}
#ifndef DACCESS_COMPILE
// You can overload these two for synchronization (as LockedRangeList does)
virtual BOOL AddRangeWorker(const BYTE *start, const BYTE *end, void *id);
// If both "start" and "end" are NULL, then this method deletes all ranges with
// the given id (i.e. the original behaviour). Otherwise, it ignores the given
// id and deletes all ranges falling in the region [start, end).
virtual void RemoveRangesWorker(void *id, const BYTE *start = NULL, const BYTE *end = NULL);
#else
virtual BOOL AddRangeWorker(const BYTE *start, const BYTE *end, void *id)
{
return TRUE;
}
virtual void RemoveRangesWorker(void *id, const BYTE *start = NULL, const BYTE *end = NULL) { }
#endif // !DACCESS_COMPILE
virtual BOOL IsInRangeWorker(TADDR address, TADDR *pID = NULL);
#ifdef DACCESS_COMPILE
void EnumMemoryRegions(enum CLRDataEnumMemoryFlags flags);
#endif
enum
{
RANGE_COUNT = 10
};
private:
struct Range
{
TADDR start;
TADDR end;
TADDR id;
};
struct RangeListBlock
{
Range ranges[RANGE_COUNT];
DPTR(RangeListBlock) next;
#ifdef DACCESS_COMPILE
void EnumMemoryRegions(enum CLRDataEnumMemoryFlags flags);
#endif
};
void InitBlock(RangeListBlock *block);
RangeListBlock m_starterBlock;
DPTR(RangeListBlock) m_firstEmptyBlock;
TADDR m_firstEmptyRange;
};
//
// A private function to do the equavilent of a CoCreateInstance in
// cases where we can't make the real call. Use this when, for
// instance, you need to create a symbol reader in the Runtime but
// we're not CoInitialized. Obviously, this is only good for COM
// objects for which CoCreateInstance is just a glorified
// find-and-load-me operation.
//
HRESULT FakeCoCreateInstanceEx(REFCLSID rclsid,
LPCWSTR wszDllPath,
REFIID riid,
void ** ppv,
HMODULE * phmodDll);
// Provided for backward compatibility and for code that doesn't need the HMODULE of the
// DLL that was loaded to create the COM object. See comment at implementation of
// code:FakeCoCreateInstanceEx for more details.
inline HRESULT FakeCoCreateInstance(REFCLSID rclsid,
REFIID riid,
void ** ppv)
{
CONTRACTL
{
NOTHROW;
}
CONTRACTL_END;
return FakeCoCreateInstanceEx(rclsid, NULL, riid, ppv, NULL);
};
HRESULT FakeCoCallDllGetClassObject(REFCLSID rclsid,
LPCWSTR wszDllPath,
REFIID riid,
void ** ppv,
HMODULE * phmodDll);
//*****************************************************************************
// Gets the directory based on the location of the module. This routine
// is called at COR setup time. Set is called during EEStartup and by the
// MetaData dispenser.
//*****************************************************************************
HRESULT GetInternalSystemDirectory(__out_ecount_part_opt(*pdwLength,*pdwLength) LPWSTR buffer, __inout DWORD* pdwLength);
LPCWSTR GetInternalSystemDirectory(__out_opt DWORD * pdwLength = NULL);
//*****************************************************************************
// This function validates the given Method/Field/Standalone signature. (util.cpp)
//*****************************************************************************
struct IMDInternalImport;
HRESULT validateTokenSig(
mdToken tk, // [IN] Token whose signature needs to be validated.
PCCOR_SIGNATURE pbSig, // [IN] Signature.
ULONG cbSig, // [IN] Size in bytes of the signature.
DWORD dwFlags, // [IN] Method flags.
IMDInternalImport* pImport); // [IN] Internal MD Import interface ptr
//*****************************************************************************
// Determine the version number of the runtime that was used to build the
// specified image. The pMetadata pointer passed in is the pointer to the
// metadata contained in the image.
//*****************************************************************************
HRESULT GetImageRuntimeVersionString(PVOID pMetaData, LPCSTR* pString);
void AdjustImageRuntimeVersion (SString* pVersion);
//*****************************************************************************
// The registry keys and values that contain the information regarding
// the default registered unmanaged debugger.
//*****************************************************************************
SELECTANY const WCHAR kDebugApplicationsPoliciesKey[] = W("SOFTWARE\\Policies\\Microsoft\\Windows\\Windows Error Reporting\\DebugApplications");
SELECTANY const WCHAR kDebugApplicationsKey[] = W("SOFTWARE\\Microsoft\\Windows\\Windows Error Reporting\\DebugApplications");
SELECTANY const WCHAR kUnmanagedDebuggerKey[] = W("SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\AeDebug");
SELECTANY const WCHAR kUnmanagedDebuggerValue[] = W("Debugger");
SELECTANY const WCHAR kUnmanagedDebuggerAutoValue[] = W("Auto");
SELECTANY const WCHAR kUnmanagedDebuggerAutoExclusionListKey[] = W("SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\AeDebug\\AutoExclusionList");
BOOL GetRegistryLongValue(HKEY hKeyParent, // Parent key.
LPCWSTR szKey, // Key name to look at.
LPCWSTR szName, // Name of value to get.
long *pValue, // Put value here, if found.
BOOL fReadNonVirtualizedKey); // Whether to read 64-bit hive on WOW64
HRESULT GetCurrentModuleFileName(__out_ecount(*pcchBuffer) LPWSTR pBuffer, __inout DWORD *pcchBuffer);
//*****************************************************************************
// Retrieve information regarding what registered default debugger
//*****************************************************************************
void GetDebuggerSettingInfo(SString &debuggerKeyValue, BOOL *pfAuto);
HRESULT GetDebuggerSettingInfoWorker(__out_ecount_part_opt(*pcchDebuggerString, *pcchDebuggerString) LPWSTR wszDebuggerString, DWORD * pcchDebuggerString, BOOL * pfAuto);
void TrimWhiteSpace(__deref_inout_ecount(*pcch) LPCWSTR *pwsz, __inout LPDWORD pcch);
//*****************************************************************************
// Convert a UTF8 string to Unicode, into a CQuickArray<WCHAR>.
//*****************************************************************************
HRESULT Utf2Quick(
LPCUTF8 pStr, // The string to convert.
CQuickArray<WCHAR> &rStr, // The QuickArray<WCHAR> to convert it into.
int iCurLen); // Inital characters in the array to leave (default 0).
//*****************************************************************************
// Extract the movl 64-bit unsigned immediate from an IA64 bundle
// (Format X2)
//*****************************************************************************
UINT64 GetIA64Imm64(UINT64 * pBundle);
UINT64 GetIA64Imm64(UINT64 qword0, UINT64 qword1);
//*****************************************************************************
// Deposit the movl 64-bit unsigned immediate into an IA64 bundle
// (Format X2)
//*****************************************************************************
void PutIA64Imm64(UINT64 * pBundle, UINT64 imm64);
//*****************************************************************************
// Extract the IP-Relative signed 25-bit immediate from an IA64 bundle
// (Formats B1, B2 or B3)
// Note that due to branch target alignment requirements
// the lowest four bits in the result will always be zero.
//*****************************************************************************
INT32 GetIA64Rel25(UINT64 * pBundle, UINT32 slot);
INT32 GetIA64Rel25(UINT64 qword0, UINT64 qword1, UINT32 slot);
//*****************************************************************************
// Deposit the IP-Relative signed 25-bit immediate into an IA64 bundle
// (Formats B1, B2 or B3)
// Note that due to branch target alignment requirements
// the lowest four bits are required to be zero.
//*****************************************************************************
void PutIA64Rel25(UINT64 * pBundle, UINT32 slot, INT32 imm25);
//*****************************************************************************
// Extract the IP-Relative signed 64-bit immediate from an IA64 bundle
// (Formats X3 or X4)
//*****************************************************************************
INT64 GetIA64Rel64(UINT64 * pBundle);
INT64 GetIA64Rel64(UINT64 qword0, UINT64 qword1);
//*****************************************************************************
// Deposit the IP-Relative signed 64-bit immediate into a IA64 bundle
// (Formats X3 or X4)
//*****************************************************************************
void PutIA64Rel64(UINT64 * pBundle, INT64 imm64);
//*****************************************************************************
// Extract the 32-bit immediate from movw/movt Thumb2 sequence
//*****************************************************************************
UINT32 GetThumb2Mov32(UINT16 * p);
//*****************************************************************************
// Deposit the 32-bit immediate into movw/movt Thumb2 sequence
//*****************************************************************************
void PutThumb2Mov32(UINT16 * p, UINT32 imm32);
//*****************************************************************************
// Extract the 24-bit rel offset from bl instruction
//*****************************************************************************
INT32 GetThumb2BlRel24(UINT16 * p);
//*****************************************************************************
// Extract the 24-bit rel offset from bl instruction
//*****************************************************************************
void PutThumb2BlRel24(UINT16 * p, INT32 imm24);
//*****************************************************************************
// Extract the PC-Relative offset from a b or bl instruction
//*****************************************************************************
INT32 GetArm64Rel28(UINT32 * pCode);
//*****************************************************************************
// Deposit the PC-Relative offset 'imm28' into a b or bl instruction
//*****************************************************************************
void PutArm64Rel28(UINT32 * pCode, INT32 imm28);
//*****************************************************************************
// Returns whether the offset fits into bl instruction
//*****************************************************************************
inline bool FitsInThumb2BlRel24(INT32 imm24)
{
return ((imm24 << 7) >> 7) == imm24;
}
//*****************************************************************************
// Returns whether the offset fits into an Arm64 b or bl instruction
//*****************************************************************************
inline bool FitsInRel28(INT32 val32)
{
return (val32 >= -0x08000000) && (val32 < 0x08000000);
}
//*****************************************************************************
// Returns whether the offset fits into an Arm64 b or bl instruction
//*****************************************************************************
inline bool FitsInRel28(INT64 val64)
{
return (val64 >= -0x08000000LL) && (val64 < 0x08000000LL);
}
//*****************************************************************************
// Splits a command line into argc/argv lists, using the VC7 parsing rules.
// This functions interface mimics the CommandLineToArgvW api.
// If function fails, returns NULL.
// If function suceeds, call delete [] on return pointer when done.
//*****************************************************************************
LPWSTR *SegmentCommandLine(LPCWSTR lpCmdLine, DWORD *pNumArgs);
//
// TEB access can be dangerous when using fibers because a fiber may
// run on multiple threads. If the TEB pointer is retrieved and saved
// and then a fiber is moved to a different thread, when it accesses
// the saved TEB pointer, it will be looking at the TEB state for a
// different fiber.
//
// These accessors serve the purpose of retrieving information from the
// TEB in a manner that ensures that the current fiber will not switch
// threads while the access is occuring.
//
class ClrTeb
{
public:
#if defined(FEATURE_PAL)
// returns pointer that uniquely identifies the fiber
static void* GetFiberPtrId()
{
LIMITED_METHOD_CONTRACT;
// not fiber for FEATURE_PAL - use the regular thread ID
return (void *)(size_t)GetCurrentThreadId();
}
static void* InvalidFiberPtrId()
{
return NULL;
}
static void* GetStackBase()
{
return PAL_GetStackBase();
}
static void* GetStackLimit()
{
return PAL_GetStackLimit();
}
#else // !FEATURE_PAL
// returns pointer that uniquely identifies the fiber
static void* GetFiberPtrId()
{
LIMITED_METHOD_CONTRACT;
// stackbase is the unique fiber identifier
return NtCurrentTeb()->NtTib.StackBase;
}
static void* GetStackBase()
{
LIMITED_METHOD_CONTRACT;
return NtCurrentTeb()->NtTib.StackBase;
}
static void* GetStackLimit()
{
LIMITED_METHOD_CONTRACT;
return NtCurrentTeb()->NtTib.StackLimit;
}
// Please don't start to use this method unless you absolutely have to.
// The reason why this is added is for WIN64 to support LEGACY PE-style TLS
// variables. On X86 it is supported by the JIT compilers themselves. On
// WIN64 we build more logic into the JIT helper for accessing fields.
static void* GetLegacyThreadLocalStoragePointer()
{
LIMITED_METHOD_CONTRACT;
return NtCurrentTeb()->ThreadLocalStoragePointer;
}
static void* GetOleReservedPtr()
{
LIMITED_METHOD_CONTRACT;
return NtCurrentTeb()->ReservedForOle;
}
static void* GetProcessEnvironmentBlock()
{
LIMITED_METHOD_CONTRACT;
return NtCurrentTeb()->ProcessEnvironmentBlock;
}
#ifndef FEATURE_CORECLR
static void* GetFiberDataPtr()
{
LIMITED_METHOD_CONTRACT;
return ClrTeb::IsCurrentThreadAFiber()? GetCurrentFiber() : NULL;
}
static BOOL IsCurrentThreadAFiber()
{
return IsThreadAFiber();
}
#endif
static void* InvalidFiberPtrId()
{
return (void*) 1;
}
#endif // !FEATURE_PAL
};
#if !defined(DACCESS_COMPILE) && !defined(CLR_STANDALONE_BINDER)
// check if current thread is a GC thread (concurrent or server)
inline BOOL IsGCSpecialThread ()
{
STATIC_CONTRACT_NOTHROW;
STATIC_CONTRACT_GC_NOTRIGGER;
STATIC_CONTRACT_MODE_ANY;
STATIC_CONTRACT_CANNOT_TAKE_LOCK;
return !!(((size_t)ClrFlsGetValue (TlsIdx_ThreadType)) & ThreadType_GC);
}
// check if current thread is a Gate thread
inline BOOL IsGateSpecialThread ()
{
STATIC_CONTRACT_NOTHROW;
STATIC_CONTRACT_GC_NOTRIGGER;
STATIC_CONTRACT_MODE_ANY;
return !!(((size_t)ClrFlsGetValue (TlsIdx_ThreadType)) & ThreadType_Gate);
}
// check if current thread is a Timer thread
inline BOOL IsTimerSpecialThread ()
{
STATIC_CONTRACT_NOTHROW;
STATIC_CONTRACT_GC_NOTRIGGER;
STATIC_CONTRACT_MODE_ANY;
return !!(((size_t)ClrFlsGetValue (TlsIdx_ThreadType)) & ThreadType_Timer);
}
// check if current thread is a debugger helper thread
inline BOOL IsDbgHelperSpecialThread ()
{
STATIC_CONTRACT_NOTHROW;
STATIC_CONTRACT_GC_NOTRIGGER;
STATIC_CONTRACT_MODE_ANY;
return !!(((size_t)ClrFlsGetValue (TlsIdx_ThreadType)) & ThreadType_DbgHelper);
}
// check if current thread is a debugger helper thread
inline BOOL IsETWRundownSpecialThread ()
{
STATIC_CONTRACT_NOTHROW;
STATIC_CONTRACT_GC_NOTRIGGER;
STATIC_CONTRACT_MODE_ANY;
return !!(((size_t)ClrFlsGetValue (TlsIdx_ThreadType)) & ThreadType_ETWRundownThread);
}
// check if current thread is a generic instantiation lookup compare thread
inline BOOL IsGenericInstantiationLookupCompareThread ()
{
STATIC_CONTRACT_NOTHROW;
STATIC_CONTRACT_GC_NOTRIGGER;
STATIC_CONTRACT_MODE_ANY;
return !!(((size_t)ClrFlsGetValue (TlsIdx_ThreadType)) & ThreadType_GenericInstantiationCompare);
}
// check if current thread is a thread which is performing shutdown
inline BOOL IsShutdownSpecialThread ()
{
STATIC_CONTRACT_NOTHROW;
STATIC_CONTRACT_GC_NOTRIGGER;
STATIC_CONTRACT_MODE_ANY;
return !!(((size_t)ClrFlsGetValue (TlsIdx_ThreadType)) & ThreadType_Shutdown);
}
inline BOOL IsThreadPoolIOCompletionSpecialThread ()
{
STATIC_CONTRACT_NOTHROW;
STATIC_CONTRACT_GC_NOTRIGGER;
STATIC_CONTRACT_MODE_ANY;
return !!(((size_t)ClrFlsGetValue (TlsIdx_ThreadType)) & ThreadType_Threadpool_IOCompletion);
}
inline BOOL IsThreadPoolWorkerSpecialThread ()
{
STATIC_CONTRACT_NOTHROW;
STATIC_CONTRACT_GC_NOTRIGGER;
STATIC_CONTRACT_MODE_ANY;
return !!(((size_t)ClrFlsGetValue (TlsIdx_ThreadType)) & ThreadType_Threadpool_Worker);
}
inline BOOL IsWaitSpecialThread ()
{
STATIC_CONTRACT_NOTHROW;
STATIC_CONTRACT_GC_NOTRIGGER;
STATIC_CONTRACT_MODE_ANY;
return !!(((size_t)ClrFlsGetValue (TlsIdx_ThreadType)) & ThreadType_Wait);
}
// check if current thread is a thread which is performing shutdown
inline BOOL IsSuspendEEThread ()
{
STATIC_CONTRACT_NOTHROW;
STATIC_CONTRACT_GC_NOTRIGGER;
STATIC_CONTRACT_MODE_ANY;
return !!(((size_t)ClrFlsGetValue (TlsIdx_ThreadType)) & ThreadType_DynamicSuspendEE);
}
inline BOOL IsFinalizerThread ()
{
STATIC_CONTRACT_NOTHROW;
STATIC_CONTRACT_GC_NOTRIGGER;
STATIC_CONTRACT_MODE_ANY;
return !!(((size_t)ClrFlsGetValue (TlsIdx_ThreadType)) & ThreadType_Finalizer);
}
inline BOOL IsADUnloadHelperThread ()
{
STATIC_CONTRACT_NOTHROW;
STATIC_CONTRACT_GC_NOTRIGGER;
STATIC_CONTRACT_MODE_ANY;
return !!(((size_t)ClrFlsGetValue (TlsIdx_ThreadType)) & ThreadType_ADUnloadHelper);
}
inline BOOL IsShutdownHelperThread ()
{
STATIC_CONTRACT_NOTHROW;
STATIC_CONTRACT_GC_NOTRIGGER;
STATIC_CONTRACT_MODE_ANY;
return !!(((size_t)ClrFlsGetValue (TlsIdx_ThreadType)) & ThreadType_ShutdownHelper);
}
inline BOOL IsProfilerAttachThread ()
{
STATIC_CONTRACT_NOTHROW;
STATIC_CONTRACT_GC_NOTRIGGER;
STATIC_CONTRACT_MODE_ANY;
return !!(((size_t)ClrFlsGetValue (TlsIdx_ThreadType)) & ThreadType_ProfAPI_Attach);
}
// set specical type for current thread
inline void ClrFlsSetThreadType (TlsThreadTypeFlag flag)
{
STATIC_CONTRACT_NOTHROW;
STATIC_CONTRACT_GC_NOTRIGGER;
STATIC_CONTRACT_MODE_ANY;
STATIC_CONTRACT_SO_TOLERANT;
ClrFlsSetValue (TlsIdx_ThreadType, (LPVOID)(((size_t)ClrFlsGetValue (TlsIdx_ThreadType)) |flag));
}
// clear specical type for current thread
inline void ClrFlsClearThreadType (TlsThreadTypeFlag flag)
{
STATIC_CONTRACT_NOTHROW;
STATIC_CONTRACT_GC_NOTRIGGER;
STATIC_CONTRACT_MODE_ANY;
ClrFlsSetValue (TlsIdx_ThreadType, (LPVOID)(((size_t)ClrFlsGetValue (TlsIdx_ThreadType)) & ~flag));
}
#endif //!DACCESS_COMPILE
#ifdef DACCESS_COMPILE
#define SET_THREAD_TYPE_STACKWALKER(pThread)
#define CLEAR_THREAD_TYPE_STACKWALKER()
#else // DACCESS_COMPILE
#define SET_THREAD_TYPE_STACKWALKER(pThread) ClrFlsSetValue(TlsIdx_StackWalkerWalkingThread, pThread)
#define CLEAR_THREAD_TYPE_STACKWALKER() ClrFlsSetValue(TlsIdx_StackWalkerWalkingThread, NULL)
#endif // DACCESS_COMPILE
inline BOOL IsStackWalkerThread()
{
STATIC_CONTRACT_NOTHROW;
STATIC_CONTRACT_GC_NOTRIGGER;
STATIC_CONTRACT_MODE_ANY;
STATIC_CONTRACT_CANNOT_TAKE_LOCK;
#if defined(DACCESS_COMPILE) || defined(CLR_STANDALONE_BINDER)
return FALSE;
#else
return ClrFlsGetValue (TlsIdx_StackWalkerWalkingThread) != NULL;
#endif
}
inline BOOL IsGCThread ()
{
STATIC_CONTRACT_NOTHROW;
STATIC_CONTRACT_GC_NOTRIGGER;
STATIC_CONTRACT_MODE_ANY;
STATIC_CONTRACT_SUPPORTS_DAC;
STATIC_CONTRACT_SO_TOLERANT;
#if !defined(DACCESS_COMPILE) && !defined(CLR_STANDALONE_BINDER)
return IsGCSpecialThread () || IsSuspendEEThread ();
#else
return FALSE;
#endif
}
#ifndef CLR_STANDALONE_BINDER
class ClrFlsThreadTypeSwitch
{
public:
ClrFlsThreadTypeSwitch (TlsThreadTypeFlag flag)
{
STATIC_CONTRACT_NOTHROW;
STATIC_CONTRACT_GC_NOTRIGGER;
STATIC_CONTRACT_MODE_ANY;
#ifndef DACCESS_COMPILE
m_flag = flag;
m_fPreviouslySet = (((size_t)ClrFlsGetValue (TlsIdx_ThreadType)) & flag);
// In debug builds, remember the full group of flags that were set at the time
// the constructor was called. This will be used in ASSERTs in the destructor
INDEBUG(m_nPreviousFlagGroup = (size_t)ClrFlsGetValue (TlsIdx_ThreadType));
if (!m_fPreviouslySet)
{
ClrFlsSetThreadType(flag);
}
#endif // DACCESS_COMPILE
}
~ClrFlsThreadTypeSwitch ()
{
STATIC_CONTRACT_NOTHROW;
STATIC_CONTRACT_GC_NOTRIGGER;
STATIC_CONTRACT_MODE_ANY;
#ifndef DACCESS_COMPILE
// This holder should only be used to set (and thus restore) ONE thread type flag
// at a time. If more than that one flag was modified since this holder was
// instantiated, then this holder still restores only the flag it knows about. To
// prevent confusion, assert if some other flag was modified, so the user doesn't
// expect the holder to restore the entire original set of flags.
//
// The expression below says that the only difference between the previous flag
// group and the current flag group should be m_flag (or no difference at all, if
// m_flag's state didn't actually change).
_ASSERTE(((m_nPreviousFlagGroup ^ (size_t) ClrFlsGetValue(TlsIdx_ThreadType)) | (size_t) m_flag) == (size_t) m_flag);
if (m_fPreviouslySet)
{
ClrFlsSetThreadType(m_flag);
}
else
{
ClrFlsClearThreadType(m_flag);
}
#endif // DACCESS_COMPILE
}
private:
TlsThreadTypeFlag m_flag;
BOOL m_fPreviouslySet;
INDEBUG(size_t m_nPreviousFlagGroup);
};
class ClrFlsValueSwitch
{
public:
ClrFlsValueSwitch (PredefinedTlsSlots slot, PVOID value)
{
STATIC_CONTRACT_NOTHROW;
STATIC_CONTRACT_GC_NOTRIGGER;
STATIC_CONTRACT_MODE_ANY;
#ifndef DACCESS_COMPILE
m_slot = slot;
m_PreviousValue = ClrFlsGetValue(slot);
ClrFlsSetValue(slot, value);
#endif // DACCESS_COMPILE
}
~ClrFlsValueSwitch ()
{
STATIC_CONTRACT_NOTHROW;
STATIC_CONTRACT_GC_NOTRIGGER;
STATIC_CONTRACT_MODE_ANY;
#ifndef DACCESS_COMPILE
ClrFlsSetValue(m_slot, m_PreviousValue);
#endif // DACCESS_COMPILE
}
private:
PVOID m_PreviousValue;
PredefinedTlsSlots m_slot;
};
#endif // !CLR_STANDALONE_BINDER
//*********************************************************************************
// When we're hosted, operations called by the host (such as Thread::YieldTask)
// may not cause calls back into the host, as the host needs not be reentrant.
// Use the following holder for code in which calls into the host are forbidden.
// (If a call into the host is attempted nevertheless, an assert will fire.)
class ForbidCallsIntoHostOnThisThread
{
private:
static Volatile<PVOID> s_pvOwningFiber;
FORCEINLINE static BOOL Enter(BOOL)
{
WRAPPER_NO_CONTRACT;
return InterlockedCompareExchangePointer(
&s_pvOwningFiber, ClrTeb::GetFiberPtrId(), NULL) == NULL;
}
FORCEINLINE static void Leave(BOOL)
{
LIMITED_METHOD_CONTRACT;
s_pvOwningFiber = NULL;
}
public:
typedef ConditionalStateHolder<BOOL, ForbidCallsIntoHostOnThisThread::Enter, ForbidCallsIntoHostOnThisThread::Leave> Holder;
FORCEINLINE static BOOL CanThisThreadCallIntoHost()
{
WRAPPER_NO_CONTRACT;
return s_pvOwningFiber != ClrTeb::GetFiberPtrId();
}
};
typedef ForbidCallsIntoHostOnThisThread::Holder ForbidCallsIntoHostOnThisThreadHolder;
FORCEINLINE BOOL CanThisThreadCallIntoHost()
{
WRAPPER_NO_CONTRACT;
return ForbidCallsIntoHostOnThisThread::CanThisThreadCallIntoHost();
}
//*********************************************************************************
#include "contract.inl"
namespace util
{
// compare adapters
//
template < typename T >
struct less
{
bool operator()( T const & first, T const & second ) const
{
return first < second;
}
};
template < typename T >
struct greater
{
bool operator()( T const & first, T const & second ) const
{
return first > second;
}
};
// sort adapters
//
template< typename Iter, typename Pred >
void sort( Iter begin, Iter end, Pred pred );
template< typename T, typename Pred >
void sort( T * begin, T * end, Pred pred )
{
struct sort_helper : CQuickSort< T >
{
sort_helper( T * begin, T * end, Pred pred )
: CQuickSort< T >( begin, end - begin )
, m_pred( pred )
{}
virtual int Compare( T * first, T * second )
{
return m_pred( *first, *second ) ? -1
: ( m_pred( *second, *first ) ? 1 : 0 );
}
Pred m_pred;
};
sort_helper sort_obj( begin, end, pred );
sort_obj.Sort();
}
template < typename Iter >
void sort( Iter begin, Iter end );
template < typename T >
void sort( T * begin, T * end )
{
util::sort( begin, end, util::less< T >() );
}
// binary search adapters
//
template < typename Iter, typename T, typename Pred >
Iter lower_bound( Iter begin, Iter end, T const & val, Pred pred );
template < typename T, typename Pred >
T * lower_bound( T * begin, T * end, T const & val, Pred pred )
{
for (; begin != end; )
{
T * mid = begin + ( end - begin ) / 2;
if ( pred( *mid, val ) )
begin = ++mid;
else
end = mid;
}
return begin;
}
template < typename Iter, typename T >
Iter lower_bound( Iter begin, Iter end, T const & val );
template < typename T >
T * lower_bound( T * begin, T * end, T const & val )
{
return util::lower_bound( begin, end, val, util::less< T >() );
}
}
/* ------------------------------------------------------------------------ *
* Overloaded operators for the executable heap
* ------------------------------------------------------------------------ */
#ifndef FEATURE_PAL
struct CExecutable { int x; };
extern const CExecutable executable;
void * __cdecl operator new(size_t n, const CExecutable&);
void * __cdecl operator new[](size_t n, const CExecutable&);
void * __cdecl operator new(size_t n, const CExecutable&, const NoThrow&);
void * __cdecl operator new[](size_t n, const CExecutable&, const NoThrow&);
//
// Executable heap delete to match the executable heap new above.
//
template<class T> void DeleteExecutable(T *p)
{
if (p != NULL)
{
p->T::~T();
ClrHeapFree(ClrGetProcessExecutableHeap(), 0, p);
}
}
#endif // FEATURE_PAL
INDEBUG(BOOL DbgIsExecutable(LPVOID lpMem, SIZE_T length);)
class HighCharHelper {
public:
static inline BOOL IsHighChar(int c) {
return (BOOL)HighCharTable[c];
}
private:
static const BYTE HighCharTable[];
};
BOOL ThreadWillCreateGuardPage(SIZE_T sizeReservedStack, SIZE_T sizeCommitedStack);
FORCEINLINE void HolderSysFreeString(BSTR str) { CONTRACT_VIOLATION(ThrowsViolation); SysFreeString(str); }
typedef Wrapper<BSTR, DoNothing, HolderSysFreeString> BSTRHolder;
BOOL FileExists(LPCWSTR filename);
#ifndef FEATURE_CORECLR
class FileLockHolder
{
public:
FileLockHolder();
~FileLockHolder();
virtual void Acquire(LPCWSTR lockName, HANDLE hInterrupt = 0, BOOL* pInterrupted = NULL);
HRESULT AcquireNoThrow(LPCWSTR lockName, HANDLE hInterrupt = 0, BOOL* pInterrupted = NULL);
static BOOL IsTaken(LPCWSTR lockName);
void Release();
private:
HANDLE _hLock;
};
#endif // FEATURE_CORECLR
// a class for general x.x version info
class MajorMinorVersionInfo
{
protected:
WORD version[2];
BOOL bInitialized;
public:
//cctors
MajorMinorVersionInfo()
{
LIMITED_METHOD_CONTRACT;
bInitialized = FALSE;
ZeroMemory(version,sizeof(version));
};
MajorMinorVersionInfo(WORD wMajor, WORD wMinor)
{
WRAPPER_NO_CONTRACT;
Init(wMajor,wMinor);
};
// getters
BOOL IsInitialized() const
{
LIMITED_METHOD_CONTRACT;
return bInitialized;
};
WORD Major() const
{
LIMITED_METHOD_CONTRACT;
return version[0];
};
WORD Minor() const
{
LIMITED_METHOD_CONTRACT;
return version[1];
};
// setters
void Init(WORD wMajor, WORD wMinor)
{
LIMITED_METHOD_CONTRACT;
version[0]=wMajor;
version[1]=wMinor;
bInitialized=TRUE;
};
};
// CLR runtime version info in Major/Minor form
class RUNTIMEVERSIONINFO : public MajorMinorVersionInfo
{
static RUNTIMEVERSIONINFO notDefined;
public:
// cctors
RUNTIMEVERSIONINFO() {};
RUNTIMEVERSIONINFO(WORD wMajor, WORD wMinor) :
MajorMinorVersionInfo(wMajor,wMinor){};
// CLR version specific helpers
BOOL IsPreWhidbey() const
{
WRAPPER_NO_CONTRACT;
return (Major() == 1) && (Minor() <= 1);
}
static const RUNTIMEVERSIONINFO& NotApplicable()
{
LIMITED_METHOD_CONTRACT;
return notDefined;
}
};
// HMODULE_TGT represents a handle to a module in the target process. In non-DAC builds this is identical
// to HMODULE (HINSTANCE), which is the base address of the module. In DAC builds this must be a target address,
// and so is represented by TADDR.
#ifdef DACCESS_COMPILE
typedef TADDR HMODULE_TGT;
#else
typedef HMODULE HMODULE_TGT;
#endif
BOOL IsIPInModule(HMODULE_TGT hModule, PCODE ip);
//----------------------------------------------------------------------------------------
// The runtime invokes InitUtilcode() in its dllmain and passes along all of the critical
// callback pointers. For the desktop CLR, all DLLs loaded by the runtime must also call
// InitUtilcode with the same callbacks as the runtime used. To achieve this, the runtime
// calls a special initialization routine exposed by the loaded module with the callbacks,
// which in turn calls InitUtilcode.
//
// This structure collects all of the critical callback info passed in InitUtilcode().
// Note that one of them is GetCLRFunction() which is itself a gofer for many other
// callbacks. If a callback fetch be safely deferred until we have TLS and stack probe
// functionality running, it should be added to that function rather than this structure.
// Things like IEE are here because that callback has to be set up before GetCLRFunction()
// can be safely called.
//----------------------------------------------------------------------------------------
struct CoreClrCallbacks
{
typedef IExecutionEngine* (__stdcall * pfnIEE_t)();
typedef HRESULT (__stdcall * pfnGetCORSystemDirectory_t)(LPWSTR pbuffer, DWORD cchBuffer, DWORD* pdwlength);
typedef void* (__stdcall * pfnGetCLRFunction_t)(LPCSTR functionName);
HINSTANCE m_hmodCoreCLR;
pfnIEE_t m_pfnIEE;
pfnGetCORSystemDirectory_t m_pfnGetCORSystemDirectory;
pfnGetCLRFunction_t m_pfnGetCLRFunction;
};
#if defined(FEATURE_CORECLR) || !defined(SELF_NO_HOST) || defined(DACCESS_COMPILE)
// For DAC, we include this functionality only when EH SxS is enabled.
//----------------------------------------------------------------------------------------
// CoreCLR must invoke this before CRT initialization to ensure utilcode has all the callback
// pointers it needs.
//----------------------------------------------------------------------------------------
VOID InitUtilcode(const CoreClrCallbacks &cccallbacks);
CoreClrCallbacks const & GetClrCallbacks();
//----------------------------------------------------------------------------------------
// Stuff below is for utilcode.lib eyes only.
//----------------------------------------------------------------------------------------
// Stores callback pointers provided by InitUtilcode().
extern CoreClrCallbacks g_CoreClrCallbacks;
// Throws up a helpful dialog if InitUtilcode() wasn't called.
#ifdef _DEBUG
void OnUninitializedCoreClrCallbacks();
#define VALIDATECORECLRCALLBACKS() if (g_CoreClrCallbacks.m_hmodCoreCLR == NULL) OnUninitializedCoreClrCallbacks()
#else //_DEBUG
#define VALIDATECORECLRCALLBACKS()
#endif //_DEBUG
#endif // defined(FEATURE_CORECLR) || !defined(SELF_NO_HOST) || defined(DACCESS_COMPILE)
#ifdef FEATURE_CORRUPTING_EXCEPTIONS
// Corrupting Exception limited support for outside the VM folder
BOOL IsProcessCorruptedStateException(DWORD dwExceptionCode, BOOL fCheckForSO = TRUE);
#endif // FEATURE_CORRUPTING_EXCEPTIONS
BOOL IsV2RuntimeLoaded(void);
namespace UtilCode
{
// These are type-safe versions of Interlocked[Compare]Exchange
// They avoid invoking struct cast operations via reinterpreting
// the struct's address as a LONG* or LONGLONG* and dereferencing it.
//
// If we had a global ::operator & (unary), we would love to use that
// to ensure we were not also accidentally getting a structs's provided
// operator &. TODO: probe with a static_assert?
template <typename T, int SIZE = sizeof(T)>
struct InterlockedCompareExchangeHelper;
template <typename T>
struct InterlockedCompareExchangeHelper<T, sizeof(LONG)>
{
static inline T InterlockedExchange(
T volatile * target,
T value)
{
static_assert_no_msg(sizeof(T) == sizeof(LONG));
LONG res = ::InterlockedExchange(
reinterpret_cast<LONG volatile *>(target),
*reinterpret_cast<LONG *>(/*::operator*/&(value)));
return *reinterpret_cast<T*>(&res);
}
static inline T InterlockedCompareExchange(
T volatile * destination,
T exchange,
T comparand)
{
static_assert_no_msg(sizeof(T) == sizeof(LONG));
LONG res = ::InterlockedCompareExchange(
reinterpret_cast<LONG volatile *>(destination),
*reinterpret_cast<LONG*>(/*::operator*/&(exchange)),
*reinterpret_cast<LONG*>(/*::operator*/&(comparand)));
return *reinterpret_cast<T*>(&res);
}
};
template <typename T>
struct InterlockedCompareExchangeHelper<T, sizeof(LONGLONG)>
{
static inline T InterlockedExchange(
T volatile * target,
T value)
{
static_assert_no_msg(sizeof(T) == sizeof(LONGLONG));
LONGLONG res = ::InterlockedExchange64(
reinterpret_cast<LONGLONG volatile *>(target),
*reinterpret_cast<LONGLONG *>(/*::operator*/&(value)));
return *reinterpret_cast<T*>(&res);
}
static inline T InterlockedCompareExchange(
T volatile * destination,
T exchange,
T comparand)
{
static_assert_no_msg(sizeof(T) == sizeof(LONGLONG));
LONGLONG res = ::InterlockedCompareExchange64(
reinterpret_cast<LONGLONG volatile *>(destination),
*reinterpret_cast<LONGLONG*>(/*::operator*/&(exchange)),
*reinterpret_cast<LONGLONG*>(/*::operator*/&(comparand)));
return *reinterpret_cast<T*>(&res);
}
};
}
template <typename T>
inline T InterlockedExchangeT(
T volatile * target,
T value)
{
return ::UtilCode::InterlockedCompareExchangeHelper<T>::InterlockedExchange(
target, value);
}
template <typename T>
inline T InterlockedCompareExchangeT(
T volatile * destination,
T exchange,
T comparand)
{
return ::UtilCode::InterlockedCompareExchangeHelper<T>::InterlockedCompareExchange(
destination, exchange, comparand);
}
// Pointer variants for Interlocked[Compare]ExchangePointer
// If the underlying type is a const type, we have to remove its constness
// since Interlocked[Compare]ExchangePointer doesn't take const void * arguments.
template <typename T>
inline T* InterlockedExchangeT(
T* volatile * target,
T* value)
{
//STATIC_ASSERT(value == 0);
typedef typename std::remove_const<T>::type * non_const_ptr_t;
return reinterpret_cast<T*>(InterlockedExchangePointer(
reinterpret_cast<PVOID volatile *>(const_cast<non_const_ptr_t volatile *>(target)),
reinterpret_cast<PVOID>(const_cast<non_const_ptr_t>(value))));
}
template <typename T>
inline T* InterlockedCompareExchangeT(
T* volatile * destination,
T* exchange,
T* comparand)
{
//STATIC_ASSERT(exchange == 0);
typedef typename std::remove_const<T>::type * non_const_ptr_t;
return reinterpret_cast<T*>(InterlockedCompareExchangePointer(
reinterpret_cast<PVOID volatile *>(const_cast<non_const_ptr_t volatile *>(destination)),
reinterpret_cast<PVOID>(const_cast<non_const_ptr_t>(exchange)),
reinterpret_cast<PVOID>(const_cast<non_const_ptr_t>(comparand))));
}
// NULL pointer variants of the above to avoid having to cast NULL
// to the appropriate pointer type.
template <typename T>
inline T* InterlockedExchangeT(
T* volatile * target,
int value) // When NULL is provided as argument.
{
//STATIC_ASSERT(value == 0);
return InterlockedExchangeT(target, reinterpret_cast<T*>(value));
}
template <typename T>
inline T* InterlockedCompareExchangeT(
T* volatile * destination,
int exchange, // When NULL is provided as argument.
T* comparand)
{
//STATIC_ASSERT(exchange == 0);
return InterlockedCompareExchangeT(destination, reinterpret_cast<T*>(exchange), comparand);
}
template <typename T>
inline T* InterlockedCompareExchangeT(
T* volatile * destination,
T* exchange,
int comparand) // When NULL is provided as argument.
{
//STATIC_ASSERT(comparand == 0);
return InterlockedCompareExchangeT(destination, exchange, reinterpret_cast<T*>(comparand));
}
// NULL pointer variants of the above to avoid having to cast NULL
// to the appropriate pointer type.
template <typename T>
inline T* InterlockedExchangeT(
T* volatile * target,
std::nullptr_t value) // When nullptr is provided as argument.
{
//STATIC_ASSERT(value == 0);
return InterlockedExchangeT(target, reinterpret_cast<T*>(value));
}
template <typename T>
inline T* InterlockedCompareExchangeT(
T* volatile * destination,
std::nullptr_t exchange, // When nullptr is provided as argument.
T* comparand)
{
//STATIC_ASSERT(exchange == 0);
return InterlockedCompareExchangeT(destination, reinterpret_cast<T*>(exchange), comparand);
}
template <typename T>
inline T* InterlockedCompareExchangeT(
T* volatile * destination,
T* exchange,
std::nullptr_t comparand) // When nullptr is provided as argument.
{
//STATIC_ASSERT(comparand == 0);
return InterlockedCompareExchangeT(destination, exchange, reinterpret_cast<T*>(comparand));
}
#undef InterlockedExchangePointer
#define InterlockedExchangePointer Use_InterlockedExchangeT
#undef InterlockedCompareExchangePointer
#define InterlockedCompareExchangePointer Use_InterlockedCompareExchangeT
// Returns the directory for HMODULE. So, if HMODULE was for "C:\Dir1\Dir2\Filename.DLL",
// then this would return "C:\Dir1\Dir2\" (note the trailing backslash).
HRESULT GetHModuleDirectory(HMODULE hMod, __out_z __out_ecount(cchPath) LPWSTR wszPath, size_t cchPath);
SString & GetHModuleDirectory(HMODULE hMod, SString &ssDir);
HMODULE LoadLocalizedResourceDLLForSDK(_In_z_ LPCWSTR wzResourceDllName, _In_opt_z_ LPCWSTR modulePath=NULL, bool trySelf=true);
// This is a slight variation that can be used for anything else
typedef void* (__cdecl *LocalizedFileHandler)(LPCWSTR);
void* FindLocalizedFile(_In_z_ LPCWSTR wzResourceDllName, LocalizedFileHandler lfh, _In_opt_z_ LPCWSTR modulePath=NULL);
BOOL IsClrHostedLegacyComObject(REFCLSID rclsid);
#if !defined(FEATURE_CORECLR) && !defined(CROSSGEN_COMPILE)
// No utilcode code should use the global LoadLibraryShim anymore. UtilCode::LoadLibraryShim will do
// the right thing based on whether the hosted or non-hosted utilcode is linked to. Using the global
// LoadLibraryShim will result in a deprecated use warning.
#ifdef SELF_NO_HOST
#define LEGACY_ACTIVATION_SHIM_LOAD_LIBRARY WszLoadLibrary
#include "legacyactivationshim.h"
#include "mscoreepriv.h"
namespace UtilCode
{
inline HRESULT LoadLibraryShim(LPCWSTR szDllName, LPCWSTR szVersion, LPVOID pvReserved, HMODULE *phModDll)
{
return LegacyActivationShim::LoadLibraryShim(szDllName, szVersion, pvReserved, phModDll);
}
};
#else // SELF_NO_HOST
namespace UtilCode
{
// Hosted environment
HRESULT LoadLibraryShim(LPCWSTR szDllName, LPCWSTR szVersion, LPVOID pvReserved, HMODULE *phModDll);
};
#endif // SELF_NO_HOST
#endif // !FEATURE_CORECLR && !CROSSGEN_COMPILE
// Helper to support termination due to heap corruption
// It's not supported on Win2K, so we have to manually delay load it
void EnableTerminationOnHeapCorruption();
#if !defined(FEATURE_CORECLR)
// On success, sets pwszProcessExePath (required) to full path to process EXE.
HRESULT GetProcessExePath(LPCWSTR *pwszProcessExePath);
#endif
namespace Clr { namespace Util
{
// This api returns a pointer to a null-terminated string that contains the local appdata directory
// or it returns NULL in the case that the directory could not be found. The return value from this function
// is not actually checked for existence.
HRESULT GetLocalAppDataDirectory(LPCWSTR *ppwzLocalAppDataDirectory);
HRESULT SetLocalAppDataDirectory(LPCWSTR pwzLocalAppDataDirectory);
namespace Reg
{
HRESULT ReadStringValue(HKEY hKey, LPCWSTR wszSubKey, LPCWSTR wszName, SString & ssValue);
HRESULT ReadStringValue(HKEY hKey, LPCWSTR wszSubKey, LPCWSTR wszName, __deref_out __deref_out_z LPWSTR* pwszValue);
}
#ifdef FEATURE_COMINTEROP
namespace Com
{
HRESULT FindServerUsingCLSID(REFCLSID rclsid, SString & ssServerName);
HRESULT FindServerUsingCLSID(REFCLSID rclsid, __deref_out __deref_out_z LPWSTR* pwszServerName);
HRESULT FindInprocServer32UsingCLSID(REFCLSID rclsid, SString & ssInprocServer32Name);
HRESULT FindInprocServer32UsingCLSID(REFCLSID rclsid, __deref_out __deref_out_z LPWSTR* pwszInprocServer32Name);
BOOL IsMscoreeInprocServer32(const SString & ssInprocServer32Name);
BOOL CLSIDHasMscoreeAsInprocServer32(REFCLSID rclsid);
}
#endif // FEATURE_COMINTEROP
namespace Win32
{
static const WCHAR LONG_FILENAME_PREFIX_W[] = W("\\\\?\\");
static const CHAR LONG_FILENAME_PREFIX_A[] = "\\\\?\\";
void GetModuleFileName(
HMODULE hModule,
SString & ssFileName,
bool fAllowLongFileNames = false);
HRESULT GetModuleFileName(
HMODULE hModule,
__deref_out_z LPWSTR * pwszFileName,
bool fAllowLongFileNames = false);
void GetFullPathName(
SString const & ssFileName,
SString & ssPathName,
DWORD * pdwFilePartIdx,
bool fAllowLongFileNames = false);
}
}}
#if defined(FEATURE_APPX) && !defined(DACCESS_COMPILE)
// Forward declaration of AppX::IsAppXProcess
namespace AppX { bool IsAppXProcess(); }
// LOAD_WITH_ALTERED_SEARCH_PATH is unsupported in AppX processes.
inline DWORD GetLoadWithAlteredSearchPathFlag()
{
WRAPPER_NO_CONTRACT;
return AppX::IsAppXProcess() ? 0 : LOAD_WITH_ALTERED_SEARCH_PATH;
}
#else // FEATURE_APPX && !DACCESS_COMPILE
// LOAD_WITH_ALTERED_SEARCH_PATH can be used unconditionally.
inline DWORD GetLoadWithAlteredSearchPathFlag()
{
LIMITED_METHOD_CONTRACT;
#ifdef LOAD_WITH_ALTERED_SEARCH_PATH
return LOAD_WITH_ALTERED_SEARCH_PATH;
#else
return 0;
#endif
}
#endif // FEATURE_APPX && !DACCESS_COMPILE
// clr::SafeAddRef and clr::SafeRelease helpers.
namespace clr
{
//=================================================================================================================
template <typename ItfT>
static inline
typename std::enable_if< std::is_pointer<ItfT>::value, ItfT >::type
SafeAddRef(ItfT pItf)
{
STATIC_CONTRACT_LIMITED_METHOD;
if (pItf != nullptr)
{
pItf->AddRef();
}
return pItf;
}
//=================================================================================================================
template <typename ItfT>
typename std::enable_if< std::is_pointer<ItfT>::value && std::is_reference<ItfT>::value, ULONG >::type
SafeRelease(ItfT pItf)
{
STATIC_CONTRACT_LIMITED_METHOD;
ULONG res = 0;
if (pItf != nullptr)
{
res = pItf->Release();
pItf = nullptr;
}
return res;
}
//=================================================================================================================
template <typename ItfT>
typename std::enable_if< std::is_pointer<ItfT>::value && !std::is_reference<ItfT>::value, ULONG >::type
SafeRelease(ItfT pItf)
{
STATIC_CONTRACT_LIMITED_METHOD;
ULONG res = 0;
if (pItf != nullptr)
{
res = pItf->Release();
}
return res;
}
}
// clr::SafeDelete
namespace clr
{
//=================================================================================================================
template <typename PtrT>
static inline
typename std::enable_if< std::is_pointer<PtrT>::value, PtrT >::type
SafeDelete(PtrT & ptr)
{
STATIC_CONTRACT_LIMITED_METHOD;
if (ptr != nullptr)
{
delete ptr;
ptr = nullptr;
}
}
}
// ======================================================================================
// Spinning support (used by VM and by MetaData via file:..\Utilcode\UTSem.cpp)
struct SpinConstants
{
DWORD dwInitialDuration;
DWORD dwMaximumDuration;
DWORD dwBackoffFactor;
DWORD dwRepetitions;
};
extern SpinConstants g_SpinConstants;
// ======================================================================================
#endif // __UtilCode_h__
|