1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
// THREADS.H -
//
//
//
// Currently represents a logical and physical COM+ thread. Later, these concepts will be separated.
//
//
// #RuntimeThreadLocals.
//
// Windows has a feature call Thread Local Storage (TLS, which is data that the OS allocates every time it
// creates a thread). Programs access this storage by using the Windows TlsAlloc, TlsGetValue, TlsSetValue
// APIs (see http://msdn2.microsoft.com/en-us/library/ms686812.aspx). The runtime allocates two such slots
// for its use
//
// * A slot that holds a pointer to the runtime thread object code:Thread (see code:#ThreadClass). The
// runtime has a special optimized version of this helper code:GetThread (we actually emit assembly
// code on the fly so it is as fast as possible). These code:Thread objects live in the
// code:ThreadStore.
//
// * The other slot holds the current code:AppDomain (a managed equivalent of a process). The
// runtime thread object also has a pointer to the thread's AppDomain (see code:Thread.m_pDomain,
// so in theory this TLS is redundant. It is there for speed (one less pointer indirection). The
// optimized helper for this is code:GetAppDomain (we emit assembly code on the fly for this one
// too).
//
// Initially these TLS slots are empty (when the OS starts up), however before we run managed code, we must
// set them properly so that managed code knows what AppDomain it is in and we can suspend threads properly
// for a GC (see code:#SuspendingTheRuntime)
//
// #SuspendingTheRuntime
//
// One of the primary differences between runtime code (managed code), and traditional (unmanaged code) is
// the existence of the GC heap (see file:gc.cpp#Overview). For the GC to do its job, it must be able to
// traverse all references to the GC heap, including ones on the stack of every thread, as well as any in
// hardware registers. While it is simple to state this requirement, it has long reaching effects, because
// properly accounting for all GC heap references ALL the time turns out to be quite hard. When we make a
// bookkeeping mistake, a GC reference is not reported at GC time, which means it will not be updated when the
// GC happens. Since memory in the GC heap can move, this can cause the pointer to point at 'random' places
// in the GC heap, causing data corruption. This is a 'GC Hole', and is very bad. We have special modes (see
// code:EEConfig.GetGCStressLevel) called GCStress to help find such issues.
//
// In order to find all GC references on the stacks we need insure that no thread is manipulating a GC
// reference at the time of the scan. This is the job of code:Thread.SuspendRuntime. Logically it suspends
// every thread in the process. Unfortunately it can not literally simply call the OS SuspendThread API on
// all threads. The reason is that the other threads MIGHT hold important locks (for example there is a lock
// that is taken when unmanaged heap memory is requested, or when a DLL is loaded). In general process
// global structures in the OS will be protected by locks, and if you suspend a thread it might hold that
// lock. If you happen to need that OS service (eg you might need to allocated unmanaged memory), then
// deadlock will occur (as you wait on the suspended thread, that never wakes up).
//
// Luckily, we don't need to actually suspend the threads, we just need to insure that all GC references on
// the stack are stable. This is where the concept of cooperative mode and preemptive mode (a bad name) come
// from.
//
// #CooperativeMode
//
// The runtime keeps a table of all threads that have ever run managed code in the code:ThreadStore table.
// The ThreadStore table holds a list of Thread objects (see code:#ThreadClass). This object holds all
// infomation about managed threads. Cooperative mode is defined as the mode the thread is in when the field
// code:Thread.m_fPreemptiveGCDisabled is non-zero. When this field is zero the thread is said to be in
// Preemptive mode (named because if you preempt the thread in this mode, it is guaranteed to be in a place
// where a GC can occur).
//
// When a thread is in cooperative mode, it is basically saying that it is potentially modifying GC
// references, and so the runtime must Cooperate with it to get to a 'GC Safe' location where the GC
// references can be enumerated. This is the mode that a thread is in MOST times when it is running managed
// code (in fact if the EIP is in JIT compiled code, there is only one place where you are NOT in cooperative
// mode (Inlined PINVOKE transition code)). Conversely, any time non-runtime unmanaged code is running, the
// thread MUST NOT be in cooperative mode (you risk deadlock otherwise). Only code in mscorwks.dll might be
// running in either cooperative or preemptive mode.
//
// It is easier to describe the invariant associated with being in Preemptive mode. When the thread is in
// preemptive mode (when code:Thread.m_fPreemptiveGCDisabled is zero), the thread guarantees two things
//
// * That it not currently running code that manipulates GC references.
// * That it has set the code:Thread.m_pFrame pointer in the code:Thread to be a subclass of the class
// code:Frame which marks the location on the stack where the last managed method frame is. This
// allows the GC to start crawling the stack from there (essentially skip over the unmanaged frames).
// * That the thread will not reenter managed code if the global variable code:g_TrapReturningThreads is
// set (it will call code:Thread.RareDisablePreemptiveGC first which will block if a a suspension is
// in progress)
//
// The basic idea is that the suspension logic in code:Thread.SuspendRuntime first sets the global variable
// code:g_TrapReturningThreads and then checks if each thread in the ThreadStore is in Cooperative mode. If a
// thread is NOT in cooperative mode, the logic simply skips the thread, because it knows that the thread
// will stop itself before reentering managed code (because code:g_TrapReturningThreads is set). This avoids
// the deadlock problem mentioned earlier, because threads that are running unmanaged code are allowed to
// run. Enumeration of GC references starts at the first managed frame (pointed at by code:Thread.m_pFrame).
//
// When a thread is in cooperative mode, it means that GC references might be being manipulated. There are
// two important possibilities
//
// * The CPU is running JIT compiled code
// * The CPU is running code elsewhere (which should only be in mscorwks.dll, because everywhere else a
// transition to preemptive mode should have happened first)
//
// * #PartiallyInteruptibleCode
// * #FullyInteruptibleCode
//
// If the Instruction pointer (x86/x64: EIP, ARM: R15/PC) is in JIT compiled code, we can detect this because we have tables that
// map the ranges of every method back to their code:MethodDesc (this the code:ICodeManager interface). In
// addition to knowing the method, these tables also point at 'GCInfo' that tell for that method which stack
// locations and which registers hold GC references at any particular instruction pointer. If the method is
// what is called FullyInterruptible, then we have information for any possible instruction pointer in the
// method and we can simply stop the thread (however we have to do this carefully TODO explain).
//
// However for most methods, we only keep GC information for paticular EIP's, in particular we keep track of
// GC reference liveness only at call sites. Thus not every location is 'GC Safe' (that is we can enumerate
// all references, but must be 'driven' to a GC safe location).
//
// We drive threads to GC safe locations by hijacking. This is a term for updating the return address on the
// stack so that we gain control when a method returns. If we find that we are in JITTed code but NOT at a GC
// safe location, then we find the return address for the method and modfiy it to cause the runtime to stop.
// We then let the method run. Hopefully the method quickly returns, and hits our hijack, and we are now at a
// GC-safe location (all call sites are GC-safe). If not we repeat the procedure (possibly moving the
// hijack). At some point a method returns, and we get control. For methods that have loops that don't make
// calls, we are forced to make the method FullyInterruptible, so we can be sure to stop the mehod.
//
// This leaves only the case where we are in cooperative modes, but not in JIT compiled code (we should be in
// clr.dll). In this case we simply let the thread run. The idea is that code in clr.dll makes the
// promise that it will not do ANYTHING that will block (which includes taking a lock), while in cooperative
// mode, or do anything that might take a long time without polling to see if a GC is needed. Thus this code
// 'cooperates' to insure that GCs can happen in a timely fashion.
//
// If you need to switch the GC mode of the current thread, look for the GCX_COOP() and GCX_PREEMP() macros.
//
#ifndef __threads_h__
#define __threads_h__
#include "vars.hpp"
#include "util.hpp"
#include "eventstore.hpp"
#include "argslot.h"
#include "context.h"
#include "regdisp.h"
#include "mscoree.h"
#include "gcheaputilities.h"
#include "gchandleutilities.h"
#include "gcinfotypes.h"
#include <clrhost.h>
class Thread;
class ThreadStore;
class MethodDesc;
struct PendingSync;
class AppDomain;
class NDirect;
class Frame;
class ThreadBaseObject;
class AppDomainStack;
class LoadLevelLimiter;
class DomainFile;
class DeadlockAwareLock;
struct HelperMethodFrameCallerList;
class ThreadLocalIBCInfo;
class EECodeInfo;
class DebuggerPatchSkip;
class MethodCallGraphPreparer;
class FaultingExceptionFrame;
class ContextTransitionFrame;
enum BinderMethodID : int;
class CRWLock;
struct LockEntry;
class PendingTypeLoadHolder;
struct ThreadLocalBlock;
typedef DPTR(struct ThreadLocalBlock) PTR_ThreadLocalBlock;
typedef DPTR(PTR_ThreadLocalBlock) PTR_PTR_ThreadLocalBlock;
#include "stackwalktypes.h"
#include "log.h"
#include "stackingallocator.h"
#include "excep.h"
#include "synch.h"
#include "exstate.h"
#include "threaddebugblockinginfo.h"
#include "interoputil.h"
#include "eventtrace.h"
#ifdef FEATURE_PERFTRACING
class EventPipeBufferList;
#endif // FEATURE_PERFTRACING
#ifdef CROSSGEN_COMPILE
#include "asmconstants.h"
class Thread
{
friend class ThreadStatics;
PTR_ThreadLocalBlock m_pThreadLocalBlock;
PTR_PTR_ThreadLocalBlock m_pTLBTable;
SIZE_T m_TLBTableSize;
public:
BOOL IsAddressInStack (PTR_VOID addr) const { return TRUE; }
static BOOL IsAddressInCurrentStack (PTR_VOID addr) { return TRUE; }
Frame *IsRunningIn(AppDomain* pDomain, int *count) { return NULL; }
StackingAllocator m_MarshalAlloc;
private:
MethodCallGraphPreparer * m_pCerPreparationState;
public:
MethodCallGraphPreparer * GetCerPreparationState()
{
LIMITED_METHOD_CONTRACT;
return m_pCerPreparationState;
}
void SetCerPreparationState(MethodCallGraphPreparer * pCerPreparationState)
{
LIMITED_METHOD_CONTRACT;
m_pCerPreparationState = pCerPreparationState;
}
private:
LoadLevelLimiter *m_pLoadLimiter;
public:
LoadLevelLimiter *GetLoadLevelLimiter()
{
LIMITED_METHOD_CONTRACT;
return m_pLoadLimiter;
}
void SetLoadLevelLimiter(LoadLevelLimiter *limiter)
{
LIMITED_METHOD_CONTRACT;
m_pLoadLimiter = limiter;
}
PTR_Frame GetFrame() { return NULL; }
void SetFrame(Frame *pFrame) { }
DWORD CatchAtSafePoint() { return 0; }
DWORD CatchAtSafePointOpportunistic() { return 0; }
static void ObjectRefProtected(const OBJECTREF* ref) { }
static void ObjectRefNew(const OBJECTREF* ref) { }
void EnablePreemptiveGC() { }
void DisablePreemptiveGC() { }
inline void IncLockCount() { }
inline void DecLockCount() { }
void EnterContextRestricted(Context* c, ContextTransitionFrame* pFrame) { }
static LPVOID GetStaticFieldAddress(FieldDesc *pFD) { return NULL; }
PTR_AppDomain GetDomain() { return ::GetAppDomain(); }
DWORD GetThreadId() { return 0; }
inline DWORD GetOverridesCount() { return 0; }
inline BOOL CheckThreadWideSpecialFlag(DWORD flags) { return 0; }
BOOL PreemptiveGCDisabled() { return false; }
void PulseGCMode() { }
OBJECTREF GetThrowable() { return NULL; }
OBJECTREF LastThrownObject() { return NULL; }
static BOOL Debug_AllowCallout() { return TRUE; }
static void IncForbidSuspendThread() { }
static void DecForbidSuspendThread() { }
// The ForbidSuspendThreadHolder is used during the initialization of the stack marker infrastructure so
// it can't do any backout stack validation (which is why we pass in VALIDATION_TYPE=HSV_NoValidation).
typedef StateHolder<Thread::IncForbidSuspendThread, Thread::DecForbidSuspendThread, HSV_NoValidation> ForbidSuspendThreadHolder;
static BYTE GetOffsetOfCurrentFrame()
{
LIMITED_METHOD_CONTRACT;
size_t ofs = Thread_m_pFrame;
_ASSERTE(FitsInI1(ofs));
return (BYTE)ofs;
}
static BYTE GetOffsetOfGCFlag()
{
LIMITED_METHOD_CONTRACT;
size_t ofs = Thread_m_fPreemptiveGCDisabled;
_ASSERTE(FitsInI1(ofs));
return (BYTE)ofs;
}
void SetLoadingFile(DomainFile *pFile)
{
}
typedef Holder<Thread *, DoNothing, DoNothing> LoadingFileHolder;
enum ThreadState
{
};
BOOL HasThreadState(ThreadState ts)
{
LIMITED_METHOD_CONTRACT;
return ((DWORD)m_State & ts);
}
BOOL HasThreadStateOpportunistic(ThreadState ts)
{
LIMITED_METHOD_CONTRACT;
return m_State.LoadWithoutBarrier() & ts;
}
Volatile<ThreadState> m_State;
enum ThreadStateNoConcurrency
{
TSNC_OwnsSpinLock = 0x00000400, // The thread owns a spinlock.
TSNC_DisableOleaut32Check = 0x00040000, // Disable oleaut32 delay load check. Oleaut32 has
// been loaded
TSNC_LoadsTypeViolation = 0x40000000, // Use by type loader to break deadlocks caused by type load level ordering violations
};
ThreadStateNoConcurrency m_StateNC;
void SetThreadStateNC(ThreadStateNoConcurrency tsnc)
{
LIMITED_METHOD_CONTRACT;
m_StateNC = (ThreadStateNoConcurrency)((DWORD)m_StateNC | tsnc);
}
void ResetThreadStateNC(ThreadStateNoConcurrency tsnc)
{
LIMITED_METHOD_CONTRACT;
m_StateNC = (ThreadStateNoConcurrency)((DWORD)m_StateNC & ~tsnc);
}
BOOL HasThreadStateNC(ThreadStateNoConcurrency tsnc)
{
LIMITED_METHOD_DAC_CONTRACT;
return ((DWORD)m_StateNC & tsnc);
}
PendingTypeLoadHolder* m_pPendingTypeLoad;
#ifndef DACCESS_COMPILE
PendingTypeLoadHolder* GetPendingTypeLoad()
{
LIMITED_METHOD_CONTRACT;
return m_pPendingTypeLoad;
}
void SetPendingTypeLoad(PendingTypeLoadHolder* pPendingTypeLoad)
{
LIMITED_METHOD_CONTRACT;
m_pPendingTypeLoad = pPendingTypeLoad;
}
#endif
#ifdef FEATURE_COMINTEROP_APARTMENT_SUPPORT
enum ApartmentState { AS_Unknown };
#endif
#if defined(FEATURE_COMINTEROP) && defined(MDA_SUPPORTED)
void RegisterRCW(RCW *pRCW)
{
}
BOOL RegisterRCWNoThrow(RCW *pRCW)
{
return FALSE;
}
RCW *UnregisterRCW(INDEBUG(SyncBlock *pSB))
{
return NULL;
}
#endif
DWORD m_dwLastError;
};
inline void DoReleaseCheckpoint(void *checkPointMarker)
{
WRAPPER_NO_CONTRACT;
GetThread()->m_MarshalAlloc.Collapse(checkPointMarker);
}
// CheckPointHolder : Back out to a checkpoint on the thread allocator.
typedef Holder<void*, DoNothing,DoReleaseCheckpoint> CheckPointHolder;
class AVInRuntimeImplOkayHolder
{
public:
AVInRuntimeImplOkayHolder()
{
LIMITED_METHOD_CONTRACT;
}
AVInRuntimeImplOkayHolder(Thread * pThread)
{
LIMITED_METHOD_CONTRACT;
}
~AVInRuntimeImplOkayHolder()
{
LIMITED_METHOD_CONTRACT;
}
};
inline BOOL dbgOnly_IsSpecialEEThread() { return FALSE; }
#define INCTHREADLOCKCOUNT() { }
#define DECTHREADLOCKCOUNT() { }
#define INCTHREADLOCKCOUNTTHREAD(thread) { }
#define DECTHREADLOCKCOUNTTHREAD(thread) { }
#define FORBIDGC_LOADER_USE_ENABLED() false
#define ENABLE_FORBID_GC_LOADER_USE_IN_THIS_SCOPE() ;
#define BEGIN_FORBID_TYPELOAD()
#define END_FORBID_TYPELOAD()
#define TRIGGERS_TYPELOAD()
#define TRIGGERSGC() ANNOTATION_GC_TRIGGERS
inline void CommonTripThread() { }
//current ad, always safe
#define ADV_CURRENTAD 0
//default ad, never unloaded
#define ADV_DEFAULTAD 1
// held by iterator, iterator holds a ref
#define ADV_ITERATOR 2
// the appdomain is on the stack
#define ADV_RUNNINGIN 4
// we're in process of creating the appdomain, refcount guaranteed to be >0
#define ADV_CREATING 8
// compilation domain - ngen guarantees it won't be unloaded until everyone left
#define ADV_COMPILATION 0x10
// finalizer thread - synchronized with ADU
#define ADV_FINALIZER 0x40
// adu thread - cannot race with itself
#define ADV_ADUTHREAD 0x80
// held by AppDomainRefTaker
#define ADV_REFTAKER 0x100
#define CheckADValidity(pDomain,ADValidityKind) { }
#define ENTER_DOMAIN_PTR(_pDestDomain,ADValidityKind) {
#define END_DOMAIN_TRANSITION }
class DeadlockAwareLock
{
public:
DeadlockAwareLock(const char *description = NULL) { }
~DeadlockAwareLock() { }
BOOL CanEnterLock() { return TRUE; }
BOOL TryBeginEnterLock() { return TRUE; }
void BeginEnterLock() { }
void EndEnterLock() { }
void LeaveLock() { }
public:
typedef StateHolder<DoNothing,DoNothing> BlockingLockHolder;
};
// Do not include threads.inl
#define _THREADS_INL
typedef Thread::ForbidSuspendThreadHolder ForbidSuspendThreadHolder;
#else // CROSSGEN_COMPILE
#ifdef _TARGET_ARM_
#include "armsinglestepper.h"
#endif
#if !defined(PLATFORM_SUPPORTS_SAFE_THREADSUSPEND)
// DISABLE_THREADSUSPEND controls whether Thread::SuspendThread will be used at all.
// This API is dangerous on non-Windows platforms, as it can lead to deadlocks,
// due to low level OS resources that the PAL is not aware of, or due to the fact that
// PAL-unaware code in the process may hold onto some OS resources.
#define DISABLE_THREADSUSPEND
#endif
// NT thread priorities range from -15 to +15.
#define INVALID_THREAD_PRIORITY ((DWORD)0x80000000)
// For a fiber which switched out, we set its OSID to a special number
// Note: there's a copy of this macro in strike.cpp
#define SWITCHED_OUT_FIBER_OSID 0xbaadf00d;
#ifdef _DEBUG
// A thread doesn't recieve its id until fully constructed.
#define UNINITIALIZED_THREADID 0xbaadf00d
#endif //_DEBUG
// Capture all the synchronization requests, for debugging purposes
#if defined(_DEBUG) && defined(TRACK_SYNC)
// Each thread has a stack that tracks all enter and leave requests
struct Dbg_TrackSync
{
virtual ~Dbg_TrackSync() = default;
virtual void EnterSync (UINT_PTR caller, void *pAwareLock) = 0;
virtual void LeaveSync (UINT_PTR caller, void *pAwareLock) = 0;
};
EXTERN_C void EnterSyncHelper (UINT_PTR caller, void *pAwareLock);
EXTERN_C void LeaveSyncHelper (UINT_PTR caller, void *pAwareLock);
#endif // TRACK_SYNC
//***************************************************************************
#ifdef FEATURE_HIJACK
// Used to capture information about the state of execution of a *SUSPENDED* thread.
struct ExecutionState;
#ifndef PLATFORM_UNIX
// This is the type of the start function of a redirected thread pulled from
// a HandledJITCase during runtime suspension
typedef void (__stdcall *PFN_REDIRECTTARGET)();
// Describes the weird argument sets during hijacking
struct HijackArgs;
#endif // !PLATFORM_UNIX
#endif // FEATURE_HIJACK
//***************************************************************************
#ifdef ENABLE_CONTRACTS_IMPL
inline Thread* GetThreadNULLOk()
{
LIMITED_METHOD_CONTRACT;
Thread * pThread;
BEGIN_GETTHREAD_ALLOWED_IN_NO_THROW_REGION;
pThread = GetThread();
END_GETTHREAD_ALLOWED_IN_NO_THROW_REGION;
return pThread;
}
#else
#define GetThreadNULLOk() GetThread()
#endif
// manifest constant for waiting in the exposed classlibs
const INT32 INFINITE_TIMEOUT = -1;
/***************************************************************************/
// Public enum shared between thread and threadpool
// These are two kinds of threadpool thread that the threadpool mgr needs
// to keep track of
enum ThreadpoolThreadType
{
WorkerThread,
CompletionPortThread,
WaitThread,
TimerMgrThread
};
//***************************************************************************
// Public functions
//
// Thread* GetThread() - returns current Thread
// Thread* SetupThread() - creates new Thread.
// Thread* SetupUnstartedThread() - creates new unstarted Thread which
// (obviously) isn't in a TLS.
// void DestroyThread() - the underlying logical thread is going
// away.
// void DetachThread() - the underlying logical thread is going
// away but we don't want to destroy it yet.
//
// Public functions for ASM code generators
//
// Thread* __stdcall CreateThreadBlockThrow() - creates new Thread on reverse p-invoke
//
// Public functions for one-time init/cleanup
//
// void InitThreadManager() - onetime init
// void TerminateThreadManager() - onetime cleanup
//
// Public functions for taking control of a thread at a safe point
//
// VOID OnHijackTripThread() - we've hijacked a JIT method
// VOID OnHijackFPTripThread() - we've hijacked a JIT method,
// and need to save the x87 FP stack.
//
//***************************************************************************
//***************************************************************************
// Public functions
//***************************************************************************
//---------------------------------------------------------------------------
//
//---------------------------------------------------------------------------
Thread* SetupThread(BOOL fInternal);
inline Thread* SetupThread()
{
WRAPPER_NO_CONTRACT;
return SetupThread(FALSE);
}
// A host can deny a thread entering runtime by returning a NULL IHostTask.
// But we do want threads used by threadpool.
inline Thread* SetupInternalThread()
{
WRAPPER_NO_CONTRACT;
return SetupThread(TRUE);
}
Thread* SetupThreadNoThrow(HRESULT *phresult = NULL);
// WARNING : only GC calls this with bRequiresTSL set to FALSE.
Thread* SetupUnstartedThread(BOOL bRequiresTSL=TRUE);
void DestroyThread(Thread *th);
DWORD GetRuntimeId();
EXTERN_C Thread* WINAPI CreateThreadBlockThrow();
//---------------------------------------------------------------------------
// One-time initialization. Called during Dll initialization.
//---------------------------------------------------------------------------
void InitThreadManager();
// When we want to take control of a thread at a safe point, the thread will
// eventually come back to us in one of the following trip functions:
#ifdef FEATURE_HIJACK
EXTERN_C void WINAPI OnHijackTripThread();
#ifdef _TARGET_X86_
EXTERN_C void WINAPI OnHijackFPTripThread(); // hijacked JIT code is returning an FP value
#endif // _TARGET_X86_
#endif // FEATURE_HIJACK
void CommonTripThread();
// When we resume a thread at a new location, to get an exception thrown, we have to
// pretend the exception originated elsewhere.
EXTERN_C void ThrowControlForThread(
#ifdef WIN64EXCEPTIONS
FaultingExceptionFrame *pfef
#endif // WIN64EXCEPTIONS
);
// RWLock state inside TLS
struct LockEntry
{
LockEntry *pNext; // next entry
LockEntry *pPrev; // prev entry
LONG dwULockID;
LONG dwLLockID; // owning lock
WORD wReaderLevel; // reader nesting level
};
#if defined(_DEBUG)
BOOL MatchThreadHandleToOsId ( HANDLE h, DWORD osId );
#endif
#ifdef FEATURE_COMINTEROP
#define RCW_STACK_SIZE 64
class RCWStack
{
public:
inline RCWStack()
{
LIMITED_METHOD_CONTRACT;
memset(this, 0, sizeof(RCWStack));
}
inline VOID SetEntry(unsigned int index, RCW* pRCW)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
PRECONDITION(index < RCW_STACK_SIZE);
PRECONDITION(CheckPointer(pRCW, NULL_OK));
}
CONTRACTL_END;
m_pList[index] = pRCW;
}
inline RCW* GetEntry(unsigned int index)
{
CONTRACT (RCW*)
{
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
PRECONDITION(index < RCW_STACK_SIZE);
}
CONTRACT_END;
RETURN m_pList[index];
}
inline VOID SetNextStack(RCWStack* pStack)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
PRECONDITION(CheckPointer(pStack));
PRECONDITION(m_pNext == NULL);
}
CONTRACTL_END;
m_pNext = pStack;
}
inline RCWStack* GetNextStack()
{
CONTRACT (RCWStack*)
{
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
POSTCONDITION(CheckPointer(RETVAL, NULL_OK));
}
CONTRACT_END;
RETURN m_pNext;
}
private:
RCWStack* m_pNext;
RCW* m_pList[RCW_STACK_SIZE];
};
class RCWStackHeader
{
public:
RCWStackHeader()
{
CONTRACTL
{
THROWS;
GC_NOTRIGGER;
MODE_ANY;
}
CONTRACTL_END;
m_iIndex = 0;
m_iSize = RCW_STACK_SIZE;
m_pHead = new RCWStack();
}
~RCWStackHeader()
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
}
CONTRACTL_END;
RCWStack* pStack = m_pHead;
RCWStack* pNextStack = NULL;
while (pStack)
{
pNextStack = pStack->GetNextStack();
delete pStack;
pStack = pNextStack;
}
}
bool Push(RCW* pRCW)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
PRECONDITION(CheckPointer(pRCW, NULL_OK));
}
CONTRACTL_END;
if (!GrowListIfNeeded())
return false;
// Fast Path
if (m_iIndex < RCW_STACK_SIZE)
{
m_pHead->SetEntry(m_iIndex, pRCW);
m_iIndex++;
return true;
}
// Slow Path
unsigned int count = m_iIndex;
RCWStack* pStack = m_pHead;
while (count >= RCW_STACK_SIZE)
{
pStack = pStack->GetNextStack();
_ASSERTE(pStack);
count -= RCW_STACK_SIZE;
}
pStack->SetEntry(count, pRCW);
m_iIndex++;
return true;
}
RCW* Pop()
{
CONTRACT (RCW*)
{
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
PRECONDITION(m_iIndex > 0);
POSTCONDITION(CheckPointer(RETVAL, NULL_OK));
}
CONTRACT_END;
RCW* pRCW = NULL;
m_iIndex--;
// Fast Path
if (m_iIndex < RCW_STACK_SIZE)
{
pRCW = m_pHead->GetEntry(m_iIndex);
m_pHead->SetEntry(m_iIndex, NULL);
RETURN pRCW;
}
// Slow Path
unsigned int count = m_iIndex;
RCWStack* pStack = m_pHead;
while (count >= RCW_STACK_SIZE)
{
pStack = pStack->GetNextStack();
_ASSERTE(pStack);
count -= RCW_STACK_SIZE;
}
pRCW = pStack->GetEntry(count);
pStack->SetEntry(count, NULL);
RETURN pRCW;
}
BOOL IsInStack(RCW* pRCW)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
PRECONDITION(CheckPointer(pRCW));
}
CONTRACTL_END;
if (m_iIndex == 0)
return FALSE;
// Fast Path
if (m_iIndex <= RCW_STACK_SIZE)
{
for (int i = 0; i < (int)m_iIndex; i++)
{
if (pRCW == m_pHead->GetEntry(i))
return TRUE;
}
return FALSE;
}
// Slow Path
RCWStack* pStack = m_pHead;
int totalcount = 0;
while (pStack != NULL)
{
for (int i = 0; (i < RCW_STACK_SIZE) && (totalcount < m_iIndex); i++, totalcount++)
{
if (pRCW == pStack->GetEntry(i))
return TRUE;
}
pStack = pStack->GetNextStack();
}
return FALSE;
}
private:
bool GrowListIfNeeded()
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
INJECT_FAULT(COMPlusThrowOM());
PRECONDITION(CheckPointer(m_pHead));
}
CONTRACTL_END;
if (m_iIndex == m_iSize)
{
RCWStack* pStack = m_pHead;
RCWStack* pNextStack = NULL;
while ( (pNextStack = pStack->GetNextStack()) != NULL)
pStack = pNextStack;
RCWStack* pNewStack = new (nothrow) RCWStack();
if (NULL == pNewStack)
return false;
pStack->SetNextStack(pNewStack);
m_iSize += RCW_STACK_SIZE;
}
return true;
}
// Zero-based index to the first free element in the list.
int m_iIndex;
// Total size of the list, including all stacks.
int m_iSize;
// Pointer to the first stack.
RCWStack* m_pHead;
};
#endif // FEATURE_COMINTEROP
typedef DWORD (*AppropriateWaitFunc) (void *args, DWORD timeout, DWORD option);
// The Thread class represents a managed thread. This thread could be internal
// or external (i.e. it wandered in from outside the runtime). For internal
// threads, it could correspond to an exposed System.Thread object or it
// could correspond to an internal worker thread of the runtime.
//
// If there's a physical Win32 thread underneath this object (i.e. it isn't an
// unstarted System.Thread), then this instance can be found in the TLS
// of that physical thread.
// FEATURE_MULTIREG_RETURN is set for platforms where a struct return value
// [GcInfo v2 only] can be returned in multiple registers
// ex: Windows/Unix ARM/ARM64, Unix-AMD64.
//
//
// UNIX_AMD64_ABI is a specific kind of FEATURE_MULTIREG_RETURN
// [GcInfo v1 and v2] specified by SystemV ABI for AMD64
//
#ifdef FEATURE_HIJACK // Hijack function returning
EXTERN_C void STDCALL OnHijackWorker(HijackArgs * pArgs);
#endif // FEATURE_HIJACK
// This is the code we pass around for Thread.Interrupt, mainly for assertions
#define APC_Code 0xEECEECEE
#ifdef DACCESS_COMPILE
class BaseStackGuard;
#endif
// #ThreadClass
//
// A code:Thread contains all the per-thread information needed by the runtime. You can get at this
// structure throught the and OS TLS slot see code:#RuntimeThreadLocals for more
// Implementing IUnknown would prevent the field (e.g. m_Context) layout from being rearranged (which will need to be fixed in
// "asmconstants.h" for the respective architecture). As it is, ICLRTask derives from IUnknown and would have got IUnknown implemented
// here - so doing this explicitly and maintaining layout sanity should be just fine.
class Thread: public IUnknown
{
friend struct ThreadQueue; // used to enqueue & dequeue threads onto SyncBlocks
friend class ThreadStore;
friend class ThreadSuspend;
friend class SyncBlock;
friend class Context;
friend struct PendingSync;
friend class AppDomain;
friend class ThreadNative;
friend class DeadlockAwareLock;
#ifdef _DEBUG
friend class EEContract;
#endif
#ifdef DACCESS_COMPILE
friend class ClrDataAccess;
friend class ClrDataTask;
#endif
friend BOOL NTGetThreadContext(Thread *pThread, T_CONTEXT *pContext);
friend BOOL NTSetThreadContext(Thread *pThread, const T_CONTEXT *pContext);
friend void CommonTripThread();
#ifdef FEATURE_HIJACK
// MapWin32FaultToCOMPlusException needs access to Thread::IsAddrOfRedirectFunc()
friend DWORD MapWin32FaultToCOMPlusException(EXCEPTION_RECORD *pExceptionRecord);
friend void STDCALL OnHijackWorker(HijackArgs * pArgs);
#ifdef PLATFORM_UNIX
friend void HandleGCSuspensionForInterruptedThread(CONTEXT *interruptedContext);
#endif // PLATFORM_UNIX
#endif // FEATURE_HIJACK
friend void InitThreadManager();
friend void ThreadBaseObject::SetDelegate(OBJECTREF delegate);
friend void CallFinalizerOnThreadObject(Object *obj);
friend class ContextTransitionFrame; // To set m_dwBeginLockCount
// Debug and Profiler caches ThreadHandle.
friend class Debugger; // void Debugger::ThreadStarted(Thread* pRuntimeThread, BOOL fAttaching);
#if defined(DACCESS_COMPILE)
friend class DacDbiInterfaceImpl; // DacDbiInterfaceImpl::GetThreadHandle(HANDLE * phThread);
#endif // DACCESS_COMPILE
friend class ProfToEEInterfaceImpl; // HRESULT ProfToEEInterfaceImpl::GetHandleFromThread(ThreadID threadId, HANDLE *phThread);
friend class CExecutionEngine;
friend class UnC;
friend class CheckAsmOffsets;
friend class ExceptionTracker;
friend class ThreadExceptionState;
friend class StackFrameIterator;
friend class ThreadStatics;
VPTR_BASE_CONCRETE_VTABLE_CLASS(Thread)
public:
enum SetThreadStackGuaranteeScope { STSGuarantee_Force, STSGuarantee_OnlyIfEnabled };
static BOOL IsSetThreadStackGuaranteeInUse(SetThreadStackGuaranteeScope fScope = STSGuarantee_OnlyIfEnabled)
{
WRAPPER_NO_CONTRACT;
if(STSGuarantee_Force == fScope)
return TRUE;
//The runtime must be hosted to have escalation policy
//If escalation policy is enabled but StackOverflow is not part of the policy
// then we don't use SetThreadStackGuarantee
if(!CLRHosted() ||
GetEEPolicy()->GetActionOnFailure(FAIL_StackOverflow) == eRudeExitProcess)
{
//FAIL_StackOverflow is ProcessExit so don't use SetThreadStackGuarantee
return FALSE;
}
return TRUE;
}
public:
// If we are trying to suspend a thread, we set the appropriate pending bit to
// indicate why we want to suspend it (TS_GCSuspendPending, TS_UserSuspendPending,
// TS_DebugSuspendPending).
//
// If instead the thread has blocked itself, via WaitSuspendEvent, we indicate
// this with TS_SyncSuspended. However, we need to know whether the synchronous
// suspension is for a user request, or for an internal one (GC & Debug). That's
// because a user request is not allowed to resume a thread suspended for
// debugging or GC. -- That's not stricly true. It is allowed to resume such a
// thread so long as it was ALSO suspended by the user. In other words, this
// ensures that user resumptions aren't unbalanced from user suspensions.
//
enum ThreadState
{
TS_Unknown = 0x00000000, // threads are initialized this way
TS_AbortRequested = 0x00000001, // Abort the thread
TS_GCSuspendPending = 0x00000002, // waiting to get to safe spot for GC
TS_UserSuspendPending = 0x00000004, // user suspension at next opportunity
TS_DebugSuspendPending = 0x00000008, // Is the debugger suspending threads?
TS_GCOnTransitions = 0x00000010, // Force a GC on stub transitions (GCStress only)
TS_LegalToJoin = 0x00000020, // Is it now legal to attempt a Join()
// unused = 0x00000040,
#ifdef FEATURE_HIJACK
TS_Hijacked = 0x00000080, // Return address has been hijacked
#endif // FEATURE_HIJACK
TS_BlockGCForSO = 0x00000100, // If a thread does not have enough stack, WaitUntilGCComplete may fail.
// Either GC suspension will wait until the thread has cleared this bit,
// Or the current thread is going to spin if GC has suspended all threads.
TS_Background = 0x00000200, // Thread is a background thread
TS_Unstarted = 0x00000400, // Thread has never been started
TS_Dead = 0x00000800, // Thread is dead
TS_WeOwn = 0x00001000, // Exposed object initiated this thread
#ifdef FEATURE_COMINTEROP_APARTMENT_SUPPORT
TS_CoInitialized = 0x00002000, // CoInitialize has been called for this thread
TS_InSTA = 0x00004000, // Thread hosts an STA
TS_InMTA = 0x00008000, // Thread is part of the MTA
#endif // FEATURE_COMINTEROP_APARTMENT_SUPPORT
// Some bits that only have meaning for reporting the state to clients.
TS_ReportDead = 0x00010000, // in WaitForOtherThreads()
TS_FullyInitialized = 0x00020000, // Thread is fully initialized and we are ready to broadcast its existence to external clients
TS_TaskReset = 0x00040000, // The task is reset
TS_SyncSuspended = 0x00080000, // Suspended via WaitSuspendEvent
TS_DebugWillSync = 0x00100000, // Debugger will wait for this thread to sync
TS_StackCrawlNeeded = 0x00200000, // A stackcrawl is needed on this thread, such as for thread abort
// See comment for s_pWaitForStackCrawlEvent for reason.
TS_SuspendUnstarted = 0x00400000, // latch a user suspension on an unstarted thread
TS_Aborted = 0x00800000, // is the thread aborted?
TS_TPWorkerThread = 0x01000000, // is this a threadpool worker thread?
TS_Interruptible = 0x02000000, // sitting in a Sleep(), Wait(), Join()
TS_Interrupted = 0x04000000, // was awakened by an interrupt APC. !!! This can be moved to TSNC
TS_CompletionPortThread = 0x08000000, // Completion port thread
TS_AbortInitiated = 0x10000000, // set when abort is begun
TS_Finalized = 0x20000000, // The associated managed Thread object has been finalized.
// We can clean up the unmanaged part now.
TS_FailStarted = 0x40000000, // The thread fails during startup.
TS_Detached = 0x80000000, // Thread was detached by DllMain
// <TODO> @TODO: We need to reclaim the bits that have no concurrency issues (i.e. they are only
// manipulated by the owning thread) and move them off to a different DWORD. Note if this
// enum is changed, we also need to update SOS to reflect this.</TODO>
// We require (and assert) that the following bits are less than 0x100.
TS_CatchAtSafePoint = (TS_UserSuspendPending | TS_AbortRequested |
TS_GCSuspendPending | TS_DebugSuspendPending | TS_GCOnTransitions),
};
// Thread flags that aren't really states in themselves but rather things the thread
// has to do.
enum ThreadTasks
{
TT_CleanupSyncBlock = 0x00000001, // The synch block needs to be cleaned up.
#ifdef FEATURE_COMINTEROP_APARTMENT_SUPPORT
TT_CallCoInitialize = 0x00000002, // CoInitialize needs to be called.
#endif // FEATURE_COMINTEROP_APARTMENT_SUPPORT
};
// Thread flags that have no concurrency issues (i.e., they are only manipulated by the owning thread). Use these
// state flags when you have a new thread state that doesn't belong in the ThreadState enum above.
//
// <TODO>@TODO: its possible that the ThreadTasks from above and these flags should be merged.</TODO>
enum ThreadStateNoConcurrency
{
TSNC_Unknown = 0x00000000, // threads are initialized this way
TSNC_DebuggerUserSuspend = 0x00000001, // marked "suspended" by the debugger
TSNC_DebuggerReAbort = 0x00000002, // thread needs to re-abort itself when resumed by the debugger
TSNC_DebuggerIsStepping = 0x00000004, // debugger is stepping this thread
TSNC_DebuggerIsManagedException = 0x00000008, // EH is re-raising a managed exception.
TSNC_WaitUntilGCFinished = 0x00000010, // The current thread is waiting for GC. If host returns
// SO during wait, we will either spin or make GC wait.
TSNC_BlockedForShutdown = 0x00000020, // Thread is blocked in WaitForEndOfShutdown. We should not hit WaitForEndOfShutdown again.
TSNC_SOWorkNeeded = 0x00000040, // The thread needs to wake up AD unload helper thread to finish SO work
TSNC_CLRCreatedThread = 0x00000080, // The thread was created through Thread::CreateNewThread
TSNC_ExistInThreadStore = 0x00000100, // For dtor to know if it needs to be removed from ThreadStore
TSNC_UnsafeSkipEnterCooperative = 0x00000200, // This is a "fix" for deadlocks caused when cleaning up COM
TSNC_OwnsSpinLock = 0x00000400, // The thread owns a spinlock.
TSNC_PreparingAbort = 0x00000800, // Preparing abort. This avoids recursive HandleThreadAbort call.
TSNC_OSAlertableWait = 0x00001000, // Preparing abort. This avoids recursive HandleThreadAbort call.
TSNC_ADUnloadHelper = 0x00002000, // This thread is AD Unload helper.
TSNC_CreatingTypeInitException = 0x00004000, // Thread is trying to create a TypeInitException
TSNC_InTaskSwitch = 0x00008000, // A task is switching
TSNC_AppDomainContainUnhandled = 0x00010000, // Used to control how unhandled exception reporting occurs.
// See detailed explanation for this bit in threads.cpp
TSNC_InRestoringSyncBlock = 0x00020000, // The thread is restoring its SyncBlock for Object.Wait.
// After the thread is interrupted once, we turn off interruption
// at the beginning of wait.
TSNC_DisableOleaut32Check = 0x00040000, // Disable oleaut32 delay load check. Oleaut32 has
// been loaded
TSNC_CannotRecycle = 0x00080000, // A host can not recycle this Thread object. When a thread
// has orphaned lock, we will apply this.
TSNC_RaiseUnloadEvent = 0x00100000, // Finalize thread is raising managed unload event which
// may call AppDomain.Unload.
TSNC_UnbalancedLocks = 0x00200000, // Do not rely on lock accounting for this thread:
// we left an app domain with a lock count different from
// when we entered it
TSNC_DisableSOCheckInHCALL = 0x00400000, // Some HCALL method may be called directly from VM.
// We can not assert they are called in SOTolerant
// region.
TSNC_IgnoreUnhandledExceptions = 0x00800000, // Set for a managed thread born inside an appdomain created with the APPDOMAIN_IGNORE_UNHANDLED_EXCEPTIONS flag.
TSNC_ProcessedUnhandledException = 0x01000000,// Set on a thread on which we have done unhandled exception processing so that
// we dont perform it again when OS invokes our UEF. Currently, applicable threads include:
// 1) entry point thread of a managed app
// 2) new managed thread created in default domain
//
// For such threads, we will return to the OS after our UE processing is done
// and the OS will start invoking the UEFs. If our UEF gets invoked, it will try to
// perform the UE processing again. We will use this flag to prevent the duplicated
// effort.
//
// Once we are completely independent of the OS UEF, we could remove this.
TSNC_InsideSyncContextWait = 0x02000000, // Whether we are inside DoSyncContextWait
TSNC_DebuggerSleepWaitJoin = 0x04000000, // Indicates to the debugger that this thread is in a sleep wait or join state
// This almost mirrors the TS_Interruptible state however that flag can change
// during GC-preemptive mode whereas this one cannot.
#ifdef FEATURE_COMINTEROP
TSNC_WinRTInitialized = 0x08000000, // the thread has initialized WinRT
#endif // FEATURE_COMINTEROP
TSNC_ForceStackCommit = 0x10000000, // Commit the whole stack, even if disableCommitThreadStack is set
TSNC_CallingManagedCodeDisabled = 0x20000000, // Use by multicore JIT feature to asert on calling managed code/loading module in background thread
// Exception, system module is allowed, security demand is allowed
TSNC_LoadsTypeViolation = 0x40000000, // Use by type loader to break deadlocks caused by type load level ordering violations
TSNC_EtwStackWalkInProgress = 0x80000000, // Set on the thread so that ETW can know that stackwalking is in progress
// and does not proceed with a stackwalk on the same thread
// There are cases during managed debugging when we can run into this situation
};
// Functions called by host
STDMETHODIMP QueryInterface(REFIID riid, void** ppv)
DAC_EMPTY_RET(E_NOINTERFACE);
STDMETHODIMP_(ULONG) AddRef(void)
DAC_EMPTY_RET(0);
STDMETHODIMP_(ULONG) Release(void)
DAC_EMPTY_RET(0);
STDMETHODIMP SwitchIn(HANDLE threadHandle)
DAC_EMPTY_RET(E_FAIL);
STDMETHODIMP SwitchOut()
DAC_EMPTY_RET(E_FAIL);
STDMETHODIMP Reset (BOOL fFull)
DAC_EMPTY_RET(E_FAIL);
STDMETHODIMP ExitTask()
DAC_EMPTY_RET(E_FAIL);
STDMETHODIMP Abort()
DAC_EMPTY_RET(E_FAIL);
STDMETHODIMP RudeAbort()
DAC_EMPTY_RET(E_FAIL);
STDMETHODIMP NeedsPriorityScheduling(BOOL *pbNeedsPriorityScheduling)
DAC_EMPTY_RET(E_FAIL);
STDMETHODIMP YieldTask()
DAC_EMPTY_RET(E_FAIL);
STDMETHODIMP LocksHeld(SIZE_T *pLockCount)
DAC_EMPTY_RET(E_FAIL);
STDMETHODIMP SetTaskIdentifier(TASKID asked)
DAC_EMPTY_RET(E_FAIL);
STDMETHODIMP BeginPreventAsyncAbort()
DAC_EMPTY_RET(E_FAIL);
STDMETHODIMP EndPreventAsyncAbort()
DAC_EMPTY_RET(E_FAIL);
STDMETHODIMP SetLocale(LCID lcid);
STDMETHODIMP SetUILocale(LCID lcid);
void InternalReset (BOOL fFull, BOOL fNotFinalizerThread=FALSE, BOOL fThreadObjectResetNeeded=TRUE, BOOL fResetAbort=TRUE);
INT32 ResetManagedThreadObject(INT32 nPriority);
INT32 ResetManagedThreadObjectInCoopMode(INT32 nPriority);
BOOL IsRealThreadPoolResetNeeded();
private:
//Helpers for reset...
void FullResetThread();
public:
void InternalSwitchOut();
HRESULT DetachThread(BOOL fDLLThreadDetach);
void SetThreadState(ThreadState ts)
{
LIMITED_METHOD_CONTRACT;
FastInterlockOr((DWORD*)&m_State, ts);
}
void ResetThreadState(ThreadState ts)
{
LIMITED_METHOD_CONTRACT;
FastInterlockAnd((DWORD*)&m_State, ~ts);
}
BOOL HasThreadState(ThreadState ts)
{
LIMITED_METHOD_CONTRACT;
return ((DWORD)m_State & ts);
}
//
// This is meant to be used for quick opportunistic checks for thread abort and similar conditions. This method
// does not erect memory barrier and so it may return wrong result sometime that the caller has to handle.
//
BOOL HasThreadStateOpportunistic(ThreadState ts)
{
LIMITED_METHOD_CONTRACT;
return m_State.LoadWithoutBarrier() & ts;
}
void SetThreadStateNC(ThreadStateNoConcurrency tsnc)
{
LIMITED_METHOD_CONTRACT;
m_StateNC = (ThreadStateNoConcurrency)((DWORD)m_StateNC | tsnc);
}
void ResetThreadStateNC(ThreadStateNoConcurrency tsnc)
{
LIMITED_METHOD_CONTRACT;
m_StateNC = (ThreadStateNoConcurrency)((DWORD)m_StateNC & ~tsnc);
}
BOOL HasThreadStateNC(ThreadStateNoConcurrency tsnc)
{
LIMITED_METHOD_DAC_CONTRACT;
return ((DWORD)m_StateNC & tsnc);
}
void MarkEtwStackWalkInProgress()
{
WRAPPER_NO_CONTRACT;
SetThreadStateNC(Thread::TSNC_EtwStackWalkInProgress);
}
void MarkEtwStackWalkCompleted()
{
WRAPPER_NO_CONTRACT;
ResetThreadStateNC(Thread::TSNC_EtwStackWalkInProgress);
}
BOOL IsEtwStackWalkInProgress()
{
WRAPPER_NO_CONTRACT;
return HasThreadStateNC(Thread::TSNC_EtwStackWalkInProgress);
}
DWORD RequireSyncBlockCleanup()
{
LIMITED_METHOD_CONTRACT;
return (m_ThreadTasks & TT_CleanupSyncBlock);
}
void SetSyncBlockCleanup()
{
LIMITED_METHOD_CONTRACT;
FastInterlockOr((ULONG *)&m_ThreadTasks, TT_CleanupSyncBlock);
}
void ResetSyncBlockCleanup()
{
LIMITED_METHOD_CONTRACT;
FastInterlockAnd((ULONG *)&m_ThreadTasks, ~TT_CleanupSyncBlock);
}
#ifdef FEATURE_COMINTEROP_APARTMENT_SUPPORT
DWORD IsCoInitialized()
{
LIMITED_METHOD_CONTRACT;
return (m_State & TS_CoInitialized);
}
void SetCoInitialized()
{
LIMITED_METHOD_CONTRACT;
FastInterlockOr((ULONG *)&m_State, TS_CoInitialized);
FastInterlockAnd((ULONG*)&m_ThreadTasks, ~TT_CallCoInitialize);
}
void ResetCoInitialized()
{
LIMITED_METHOD_CONTRACT;
FastInterlockAnd((ULONG *)&m_State,~TS_CoInitialized);
}
#ifdef FEATURE_COMINTEROP
BOOL IsWinRTInitialized()
{
LIMITED_METHOD_CONTRACT;
return HasThreadStateNC(TSNC_WinRTInitialized);
}
void ResetWinRTInitialized()
{
LIMITED_METHOD_CONTRACT;
ResetThreadStateNC(TSNC_WinRTInitialized);
}
#endif // FEATURE_COMINTEROP
DWORD RequiresCoInitialize()
{
LIMITED_METHOD_CONTRACT;
return (m_ThreadTasks & TT_CallCoInitialize);
}
void SetRequiresCoInitialize()
{
LIMITED_METHOD_CONTRACT;
FastInterlockOr((ULONG *)&m_ThreadTasks, TT_CallCoInitialize);
}
void ResetRequiresCoInitialize()
{
LIMITED_METHOD_CONTRACT;
FastInterlockAnd((ULONG *)&m_ThreadTasks,~TT_CallCoInitialize);
}
void CleanupCOMState();
#endif // FEATURE_COMINTEROP_APARTMENT_SUPPORT
#ifdef FEATURE_COMINTEROP
bool IsDisableComObjectEagerCleanup()
{
LIMITED_METHOD_CONTRACT;
return m_fDisableComObjectEagerCleanup;
}
void SetDisableComObjectEagerCleanup()
{
LIMITED_METHOD_CONTRACT;
m_fDisableComObjectEagerCleanup = true;
}
#endif //FEATURE_COMINTEROP
#ifndef DACCESS_COMPILE
bool HasDeadThreadBeenConsideredForGCTrigger()
{
LIMITED_METHOD_CONTRACT;
_ASSERTE(IsDead());
return m_fHasDeadThreadBeenConsideredForGCTrigger;
}
void SetHasDeadThreadBeenConsideredForGCTrigger()
{
LIMITED_METHOD_CONTRACT;
_ASSERTE(IsDead());
m_fHasDeadThreadBeenConsideredForGCTrigger = true;
}
#endif // !DACCESS_COMPILE
// returns if there is some extra work for the finalizer thread.
BOOL HaveExtraWorkForFinalizer();
// do the extra finalizer work.
void DoExtraWorkForFinalizer();
#ifndef DACCESS_COMPILE
DWORD CatchAtSafePoint()
{
LIMITED_METHOD_CONTRACT;
return (m_State & TS_CatchAtSafePoint);
}
DWORD CatchAtSafePointOpportunistic()
{
LIMITED_METHOD_CONTRACT;
return HasThreadStateOpportunistic(TS_CatchAtSafePoint);
}
#endif // DACCESS_COMPILE
DWORD IsBackground()
{
LIMITED_METHOD_CONTRACT;
return (m_State & TS_Background);
}
DWORD IsUnstarted()
{
LIMITED_METHOD_CONTRACT;
SUPPORTS_DAC;
return (m_State & TS_Unstarted);
}
DWORD IsDead()
{
LIMITED_METHOD_CONTRACT;
return (m_State & TS_Dead);
}
DWORD IsAborted()
{
LIMITED_METHOD_CONTRACT;
return (m_State & TS_Aborted);
}
void SetAborted()
{
FastInterlockOr((ULONG *) &m_State, TS_Aborted);
}
void ClearAborted()
{
FastInterlockAnd((ULONG *) &m_State, ~TS_Aborted);
}
DWORD DoWeOwn()
{
LIMITED_METHOD_CONTRACT;
return (m_State & TS_WeOwn);
}
// For reporting purposes, grab a consistent snapshot of the thread's state
ThreadState GetSnapshotState();
// For delayed destruction of threads
DWORD IsDetached()
{
LIMITED_METHOD_CONTRACT;
return (m_State & TS_Detached);
}
#ifdef FEATURE_STACK_PROBE
//---------------------------------------------------------------------------------------
//
// IsSOTolerant - Is the current thread in SO Tolerant region?
//
// Arguments:
// pLimitFrame: the limit of search for frames
//
// Return Value:
// TRUE if in SO tolerant region.
// FALSE if in SO intolerant region.
//
// Note:
// We walk our frame chain to decide. If HelperMethodFrame is seen first, we are in tolerant
// region. If EnterSOIntolerantCodeFrame is seen first, we are in intolerant region.
//
BOOL IsSOTolerant(void * pLimitFrame);
#endif
#ifdef _DEBUG
class DisableSOCheckInHCALL
{
private:
Thread *m_pThread;
public:
DisableSOCheckInHCALL()
{
m_pThread = GetThread();
m_pThread->SetThreadStateNC(TSNC_DisableSOCheckInHCALL);
}
~DisableSOCheckInHCALL()
{
LIMITED_METHOD_CONTRACT;
m_pThread->ResetThreadStateNC(TSNC_DisableSOCheckInHCALL);
}
};
#endif
static LONG m_DetachCount;
static LONG m_ActiveDetachCount; // Count how many non-background detached
static Volatile<LONG> m_threadsAtUnsafePlaces;
// Offsets for the following variables need to fit in 1 byte, so keep near
// the top of the object. Also, we want cache line filling to work for us
// so the critical stuff is ordered based on frequency of use.
Volatile<ThreadState> m_State; // Bits for the state of the thread
// If TRUE, GC is scheduled cooperatively with this thread.
// NOTE: This "byte" is actually a boolean - we don't allow
// recursive disables.
Volatile<ULONG> m_fPreemptiveGCDisabled;
PTR_Frame m_pFrame; // The Current Frame
PTR_Frame m_pUnloadBoundaryFrame;
//-----------------------------------------------------------
// If the thread has wandered in from the outside this is
// its Domain.
//-----------------------------------------------------------
PTR_AppDomain m_pDomain;
// Track the number of locks (critical section, spin lock, syncblock lock,
// EE Crst, GC lock) held by the current thread.
DWORD m_dwLockCount;
// Unique thread id used for thin locks - kept as small as possible, as we have limited space
// in the object header to store it.
DWORD m_ThreadId;
// RWLock state
LockEntry *m_pHead;
LockEntry m_embeddedEntry;
#ifndef DACCESS_COMPILE
Frame* NotifyFrameChainOfExceptionUnwind(Frame* pStartFrame, LPVOID pvLimitSP);
#endif // DACCESS_COMPILE
#if defined(FEATURE_COMINTEROP) && !defined(DACCESS_COMPILE)
void RegisterRCW(RCW *pRCW)
{
CONTRACTL
{
THROWS;
GC_NOTRIGGER;
MODE_ANY;
PRECONDITION(CheckPointer(pRCW));
}
CONTRACTL_END;
if (!m_pRCWStack->Push(pRCW))
{
ThrowOutOfMemory();
}
}
// Returns false on OOM.
BOOL RegisterRCWNoThrow(RCW *pRCW)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
PRECONDITION(CheckPointer(pRCW, NULL_OK));
}
CONTRACTL_END;
return m_pRCWStack->Push(pRCW);
}
RCW *UnregisterRCW(INDEBUG(SyncBlock *pSB))
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
PRECONDITION(CheckPointer(pSB));
}
CONTRACTL_END;
RCW* pPoppedRCW = m_pRCWStack->Pop();
#ifdef _DEBUG
// The RCW we popped must be the one pointed to by pSB if pSB still points to an RCW.
RCW* pCurrentRCW = pSB->GetInteropInfoNoCreate()->GetRawRCW();
_ASSERTE(pCurrentRCW == NULL || pPoppedRCW == NULL || pCurrentRCW == pPoppedRCW);
#endif // _DEBUG
return pPoppedRCW;
}
BOOL RCWIsInUse(RCW* pRCW)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
PRECONDITION(CheckPointer(pRCW));
}
CONTRACTL_END;
return m_pRCWStack->IsInStack(pRCW);
}
#endif // FEATURE_COMINTEROP && !DACCESS_COMPILE
// The context within which this thread is executing. As the thread crosses
// context boundaries, the context mechanism adjusts this so it's always
// current.
// <TODO>@TODO cwb: When we add COM+ 1.0 Context Interop, this should get moved out
// of the Thread object and into its own slot in the TLS.</TODO>
// The address of the context object is also used as the ContextID!
PTR_Context m_Context;
public:
// on MP systems, each thread has its own allocation chunk so we can avoid
// lock prefixes and expensive MP cache snooping stuff
gc_alloc_context m_alloc_context;
inline gc_alloc_context *GetAllocContext() { LIMITED_METHOD_CONTRACT; return &m_alloc_context; }
// This is the type handle of the first object in the alloc context at the time
// we fire the AllocationTick event. It's only for tooling purpose.
TypeHandle m_thAllocContextObj;
#ifndef FEATURE_PAL
private:
_NT_TIB *m_pTEB;
public:
_NT_TIB *GetTEB() {
LIMITED_METHOD_CONTRACT;
return m_pTEB;
}
PEXCEPTION_REGISTRATION_RECORD *GetExceptionListPtr() {
WRAPPER_NO_CONTRACT;
return &GetTEB()->ExceptionList;
}
#endif // !FEATURE_PAL
inline void SetTHAllocContextObj(TypeHandle th) {LIMITED_METHOD_CONTRACT; m_thAllocContextObj = th; }
inline TypeHandle GetTHAllocContextObj() {LIMITED_METHOD_CONTRACT; return m_thAllocContextObj; }
#ifdef FEATURE_COMINTEROP
// The header for the per-thread in-use RCW stack.
RCWStackHeader* m_pRCWStack;
#endif // FEATURE_COMINTEROP
// Allocator used during marshaling for temporary buffers, much faster than
// heap allocation.
//
// Uses of this allocator should be effectively statically scoped, i.e. a "region"
// is started using a CheckPointHolder and GetCheckpoint, and this region can then be used for allocations
// from that point onwards, and then all memory is reclaimed when the static scope for the
// checkpoint is exited by the running thread.
StackingAllocator m_MarshalAlloc;
// Flags used to indicate tasks the thread has to do.
ThreadTasks m_ThreadTasks;
// Flags for thread states that have no concurrency issues.
ThreadStateNoConcurrency m_StateNC;
inline void IncLockCount();
inline void DecLockCount();
private:
DWORD m_dwBeginLockCount; // lock count when the thread enters current domain
#ifdef _DEBUG
DWORD dbg_m_cSuspendedThreads;
// Count of suspended threads that we know are not in native code (and therefore cannot hold OS lock which prevents us calling out to host)
DWORD dbg_m_cSuspendedThreadsWithoutOSLock;
EEThreadId m_Creater;
#endif
// After we suspend a thread, we may need to call EEJitManager::JitCodeToMethodInfo
// or StressLog which may waits on a spinlock. It is unsafe to suspend a thread while it
// is in this state.
Volatile<LONG> m_dwForbidSuspendThread;
public:
static void IncForbidSuspendThread()
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
SO_TOLERANT;
MODE_ANY;
SUPPORTS_DAC;
}
CONTRACTL_END;
#ifndef DACCESS_COMPILE
Thread * pThread = GetThreadNULLOk();
if (pThread)
{
_ASSERTE (pThread->m_dwForbidSuspendThread != (LONG)MAXLONG);
#ifdef _DEBUG
{
//DEBUG_ONLY;
STRESS_LOG2(LF_SYNC, LL_INFO100000, "Set forbid suspend [%d] for thread %p.\n", pThread->m_dwForbidSuspendThread.Load(), pThread);
}
#endif
FastInterlockIncrement(&pThread->m_dwForbidSuspendThread);
}
#endif //!DACCESS_COMPILE
}
static void DecForbidSuspendThread()
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
SO_TOLERANT;
MODE_ANY;
SUPPORTS_DAC;
}
CONTRACTL_END;
#ifndef DACCESS_COMPILE
Thread * pThread = GetThreadNULLOk();
if (pThread)
{
_ASSERTE (pThread->m_dwForbidSuspendThread != (LONG)0);
FastInterlockDecrement(&pThread->m_dwForbidSuspendThread);
#ifdef _DEBUG
{
//DEBUG_ONLY;
STRESS_LOG2(LF_SYNC, LL_INFO100000, "Reset forbid suspend [%d] for thread %p.\n", pThread->m_dwForbidSuspendThread.Load(), pThread);
}
#endif
}
#endif //!DACCESS_COMPILE
}
bool IsInForbidSuspendRegion()
{
return m_dwForbidSuspendThread != (LONG)0;
}
// The ForbidSuspendThreadHolder is used during the initialization of the stack marker infrastructure so
// it can't do any backout stack validation (which is why we pass in VALIDATION_TYPE=HSV_NoValidation).
typedef StateHolder<Thread::IncForbidSuspendThread, Thread::DecForbidSuspendThread, HSV_NoValidation> ForbidSuspendThreadHolder;
private:
// Per thread counter to dispense hash code - kept in the thread so we don't need a lock
// or interlocked operations to get a new hash code;
DWORD m_dwHashCodeSeed;
// Lock thread is trying to acquire
VolatilePtr<DeadlockAwareLock> m_pBlockingLock;
public:
inline BOOL HasLockInCurrentDomain()
{
LIMITED_METHOD_CONTRACT;
_ASSERTE(m_dwLockCount >= m_dwBeginLockCount);
// Equivalent to (m_dwLockCount != m_dwBeginLockCount ||
// m_dwCriticalRegionCount ! m_dwBeginCriticalRegionCount),
// but without branching instructions
BOOL fHasLock = (m_dwLockCount ^ m_dwBeginLockCount);
return fHasLock;
}
inline BOOL HasCriticalRegion()
{
LIMITED_METHOD_CONTRACT;
return FALSE;
}
inline DWORD GetNewHashCode()
{
LIMITED_METHOD_CONTRACT;
// Every thread has its own generator for hash codes so that we won't get into a situation
// where two threads consistently give out the same hash codes.
// Choice of multiplier guarantees period of 2**32 - see Knuth Vol 2 p16 (3.2.1.2 Theorem A).
DWORD multiplier = GetThreadId()*4 + 5;
m_dwHashCodeSeed = m_dwHashCodeSeed*multiplier + 1;
return m_dwHashCodeSeed;
}
#ifdef _DEBUG
// If the current thread suspends other threads, we need to make sure that the thread
// only allocates memory if the suspended threads do not have OS Heap lock.
static BOOL Debug_AllowCallout()
{
LIMITED_METHOD_CONTRACT;
Thread * pThread = GetThreadNULLOk();
return ((pThread == NULL) || (pThread->dbg_m_cSuspendedThreads == pThread->dbg_m_cSuspendedThreadsWithoutOSLock));
}
// Returns number of threads that are currently suspended by the current thread and that can potentially hold OS lock
BOOL Debug_GetUnsafeSuspendeeCount()
{
LIMITED_METHOD_CONTRACT;
return (dbg_m_cSuspendedThreads - dbg_m_cSuspendedThreadsWithoutOSLock);
}
#endif
public:
BOOL HasThreadAffinity()
{
LIMITED_METHOD_CONTRACT;
return FALSE;
}
private:
LoadLevelLimiter *m_pLoadLimiter;
public:
LoadLevelLimiter *GetLoadLevelLimiter()
{
LIMITED_METHOD_CONTRACT;
return m_pLoadLimiter;
}
void SetLoadLevelLimiter(LoadLevelLimiter *limiter)
{
LIMITED_METHOD_CONTRACT;
m_pLoadLimiter = limiter;
}
public:
//--------------------------------------------------------------
// Constructor.
//--------------------------------------------------------------
#ifndef DACCESS_COMPILE
Thread();
#endif
//--------------------------------------------------------------
// Failable initialization occurs here.
//--------------------------------------------------------------
BOOL InitThread(BOOL fInternal);
BOOL AllocHandles();
void SetupThreadForHost();
//--------------------------------------------------------------
// If the thread was setup through SetupUnstartedThread, rather
// than SetupThread, complete the setup here when the thread is
// actually running.
// WARNING : only GC calls this with bRequiresTSL set to FALSE.
//--------------------------------------------------------------
BOOL HasStarted(BOOL bRequiresTSL=TRUE);
// We don't want ::CreateThread() calls scattered throughout the source.
// Create all new threads here. The thread is created as suspended, so
// you must ::ResumeThread to kick it off. It is guaranteed to create the
// thread, or throw.
BOOL CreateNewThread(SIZE_T stackSize, LPTHREAD_START_ROUTINE start, void *args, LPCWSTR pName=NULL);
enum StackSizeBucket
{
StackSize_Small,
StackSize_Medium,
StackSize_Large
};
//
// Creates a raw OS thread; use this only for CLR-internal threads that never execute user code.
// StackSizeBucket determines how large the stack should be.
//
static HANDLE CreateUtilityThread(StackSizeBucket stackSizeBucket, LPTHREAD_START_ROUTINE start, void *args, DWORD flags = 0, DWORD* pThreadId = NULL);
//--------------------------------------------------------------
// Destructor
//--------------------------------------------------------------
#ifndef DACCESS_COMPILE
virtual ~Thread();
#else
virtual ~Thread() {}
#endif
#ifdef FEATURE_COMINTEROP_APARTMENT_SUPPORT
void CoUninitialize();
void BaseCoUninitialize();
void BaseWinRTUninitialize();
#endif // FEATURE_COMINTEROP_APARTMENT_SUPPORT
void OnThreadTerminate(BOOL holdingLock);
static void CleanupDetachedThreads();
//--------------------------------------------------------------
// Returns innermost active Frame.
//--------------------------------------------------------------
PTR_Frame GetFrame()
{
SUPPORTS_DAC;
#ifndef DACCESS_COMPILE
#ifdef _DEBUG_IMPL
WRAPPER_NO_CONTRACT;
if (this == GetThreadNULLOk())
{
void* curSP;
curSP = (void *)GetCurrentSP();
_ASSERTE((curSP <= m_pFrame && m_pFrame < m_CacheStackBase) || m_pFrame == (Frame*) -1);
}
#else
LIMITED_METHOD_CONTRACT;
_ASSERTE(!"NYI");
#endif
#endif // #ifndef DACCESS_COMPILE
return m_pFrame;
}
//--------------------------------------------------------------
// Replaces innermost active Frames.
//--------------------------------------------------------------
#ifndef DACCESS_COMPILE
void SetFrame(Frame *pFrame)
#ifdef _DEBUG
;
#else
{
LIMITED_METHOD_CONTRACT;
m_pFrame = pFrame;
}
#endif
;
#endif
inline Frame* FindFrame(SIZE_T StackPointer);
bool DetectHandleILStubsForDebugger();
#ifndef DACCESS_COMPILE
void SetUnloadBoundaryFrame(Frame *pFrame);
void ResetUnloadBoundaryFrame();
#endif
PTR_Frame GetUnloadBoundaryFrame()
{
LIMITED_METHOD_CONTRACT;
return m_pUnloadBoundaryFrame;
}
void SetWin32FaultAddress(DWORD eip)
{
LIMITED_METHOD_CONTRACT;
m_Win32FaultAddress = eip;
}
void SetWin32FaultCode(DWORD code)
{
LIMITED_METHOD_CONTRACT;
m_Win32FaultCode = code;
}
DWORD GetWin32FaultAddress()
{
LIMITED_METHOD_CONTRACT;
return m_Win32FaultAddress;
}
DWORD GetWin32FaultCode()
{
LIMITED_METHOD_CONTRACT;
return m_Win32FaultCode;
}
#ifdef ENABLE_CONTRACTS
ClrDebugState *GetClrDebugState()
{
LIMITED_METHOD_CONTRACT;
return m_pClrDebugState;
}
#endif
//**************************************************************
// GC interaction
//**************************************************************
//--------------------------------------------------------------
// Enter cooperative GC mode. NOT NESTABLE.
//--------------------------------------------------------------
FORCEINLINE_NONDEBUG void DisablePreemptiveGC()
{
#ifndef DACCESS_COMPILE
WRAPPER_NO_CONTRACT;
_ASSERTE(this == GetThread());
_ASSERTE(!m_fPreemptiveGCDisabled);
// holding a spin lock in preemp mode and transit to coop mode will cause other threads
// spinning waiting for GC
_ASSERTE ((m_StateNC & Thread::TSNC_OwnsSpinLock) == 0);
#ifdef ENABLE_CONTRACTS_IMPL
TriggersGC(this);
#endif
// Logically, we just want to check whether a GC is in progress and halt
// at the boundary if it is -- before we disable preemptive GC. However
// this opens up a race condition where the GC starts after we make the
// check. SuspendRuntime will ignore such a thread because it saw it as
// outside the EE. So the thread would run wild during the GC.
//
// Instead, enter cooperative mode and then check if a GC is in progress.
// If so, go back out and try again. The reason we go back out before we
// try again, is that SuspendRuntime might have seen us as being in
// cooperative mode if it checks us between the next two statements.
// In that case, it will be trying to move us to a safe spot. If
// we don't let it see us leave, it will keep waiting on us indefinitely.
// ------------------------------------------------------------------------
// ** WARNING ** WARNING ** WARNING ** WARNING ** WARNING ** WARNING ** |
// ------------------------------------------------------------------------
//
// DO NOT CHANGE THIS METHOD WITHOUT VISITING ALL THE STUB GENERATORS
// THAT EFFECTIVELY INLINE IT INTO THEIR STUBS
//
// ------------------------------------------------------------------------
// ** WARNING ** WARNING ** WARNING ** WARNING ** WARNING ** WARNING ** |
// ------------------------------------------------------------------------
m_fPreemptiveGCDisabled.StoreWithoutBarrier(1);
if (g_TrapReturningThreads.LoadWithoutBarrier())
{
RareDisablePreemptiveGC();
}
#else
LIMITED_METHOD_CONTRACT;
#endif
}
NOINLINE void RareDisablePreemptiveGC();
void HandleThreadAbort()
{
HandleThreadAbort(FALSE);
}
void HandleThreadAbort(BOOL fForce); // fForce=TRUE only for a thread waiting to start AD unload
void PreWorkForThreadAbort();
private:
void HandleThreadAbortTimeout();
public:
//--------------------------------------------------------------
// Leave cooperative GC mode. NOT NESTABLE.
//--------------------------------------------------------------
FORCEINLINE_NONDEBUG void EnablePreemptiveGC()
{
LIMITED_METHOD_CONTRACT;
#ifndef DACCESS_COMPILE
_ASSERTE(this == GetThread());
_ASSERTE(m_fPreemptiveGCDisabled);
// holding a spin lock in coop mode and transit to preemp mode will cause deadlock on GC
_ASSERTE ((m_StateNC & Thread::TSNC_OwnsSpinLock) == 0);
#ifdef ENABLE_CONTRACTS_IMPL
_ASSERTE(!GCForbidden());
TriggersGC(this);
#endif
// ------------------------------------------------------------------------
// ** WARNING ** WARNING ** WARNING ** WARNING ** WARNING ** WARNING ** |
// ------------------------------------------------------------------------
//
// DO NOT CHANGE THIS METHOD WITHOUT VISITING ALL THE STUB GENERATORS
// THAT EFFECTIVELY INLINE IT INTO THEIR STUBS
//
// ------------------------------------------------------------------------
// ** WARNING ** WARNING ** WARNING ** WARNING ** WARNING ** WARNING ** |
// ------------------------------------------------------------------------
m_fPreemptiveGCDisabled.StoreWithoutBarrier(0);
#ifdef ENABLE_CONTRACTS
m_ulEnablePreemptiveGCCount ++;
#endif // _DEBUG
if (CatchAtSafePoint())
RareEnablePreemptiveGC();
#endif
}
#if defined(STRESS_HEAP) && defined(_DEBUG)
void PerformPreemptiveGC();
#endif
void RareEnablePreemptiveGC();
void PulseGCMode();
//--------------------------------------------------------------
// Query mode
//--------------------------------------------------------------
BOOL PreemptiveGCDisabled()
{
WRAPPER_NO_CONTRACT;
_ASSERTE(this == GetThread());
//
// m_fPreemptiveGCDisabled is always modified by the thread itself, and so the thread itself
// can read it without memory barrier.
//
return m_fPreemptiveGCDisabled.LoadWithoutBarrier();
}
BOOL PreemptiveGCDisabledOther()
{
LIMITED_METHOD_CONTRACT;
return (m_fPreemptiveGCDisabled);
}
#ifdef ENABLE_CONTRACTS_IMPL
void BeginNoTriggerGC(const char *szFile, int lineNum)
{
WRAPPER_NO_CONTRACT;
m_pClrDebugState->IncrementGCNoTriggerCount();
if (PreemptiveGCDisabled())
{
m_pClrDebugState->IncrementGCForbidCount();
}
}
void EndNoTriggerGC()
{
WRAPPER_NO_CONTRACT;
_ASSERTE(m_pClrDebugState->GetGCNoTriggerCount() != 0 || (m_pClrDebugState->ViolationMask() & BadDebugState));
m_pClrDebugState->DecrementGCNoTriggerCount();
if (m_pClrDebugState->GetGCForbidCount())
{
m_pClrDebugState->DecrementGCForbidCount();
}
}
void BeginForbidGC(const char *szFile, int lineNum)
{
WRAPPER_NO_CONTRACT;
_ASSERTE(this == GetThread());
#ifdef PROFILING_SUPPORTED
_ASSERTE(PreemptiveGCDisabled()
|| CORProfilerPresent() || // This added to allow profiler to use GetILToNativeMapping
// while in preemptive GC mode
(g_fEEShutDown & (ShutDown_Finalize2 | ShutDown_Profiler)) == ShutDown_Finalize2);
#else // PROFILING_SUPPORTED
_ASSERTE(PreemptiveGCDisabled());
#endif // PROFILING_SUPPORTED
BeginNoTriggerGC(szFile, lineNum);
}
void EndForbidGC()
{
WRAPPER_NO_CONTRACT;
_ASSERTE(this == GetThread());
#ifdef PROFILING_SUPPORTED
_ASSERTE(PreemptiveGCDisabled() ||
CORProfilerPresent() || // This added to allow profiler to use GetILToNativeMapping
// while in preemptive GC mode
(g_fEEShutDown & (ShutDown_Finalize2 | ShutDown_Profiler)) == ShutDown_Finalize2);
#else // PROFILING_SUPPORTED
_ASSERTE(PreemptiveGCDisabled());
#endif // PROFILING_SUPPORTED
EndNoTriggerGC();
}
BOOL GCNoTrigger()
{
WRAPPER_NO_CONTRACT;
_ASSERTE(this == GetThread());
if ( (GCViolation|BadDebugState) & m_pClrDebugState->ViolationMask() )
{
return FALSE;
}
return m_pClrDebugState->GetGCNoTriggerCount();
}
BOOL GCForbidden()
{
WRAPPER_NO_CONTRACT;
_ASSERTE(this == GetThread());
if ( (GCViolation|BadDebugState) & m_pClrDebugState->ViolationMask())
{
return FALSE;
}
return m_pClrDebugState->GetGCForbidCount();
}
BOOL RawGCNoTrigger()
{
LIMITED_METHOD_CONTRACT;
if (m_pClrDebugState->ViolationMask() & BadDebugState)
{
return 0;
}
return m_pClrDebugState->GetGCNoTriggerCount();
}
BOOL RawGCForbidden()
{
LIMITED_METHOD_CONTRACT;
if (m_pClrDebugState->ViolationMask() & BadDebugState)
{
return 0;
}
return m_pClrDebugState->GetGCForbidCount();
}
#endif // ENABLE_CONTRACTS_IMPL
//---------------------------------------------------------------
// Expose key offsets and values for stub generation.
//---------------------------------------------------------------
static BYTE GetOffsetOfCurrentFrame()
{
LIMITED_METHOD_CONTRACT;
size_t ofs = offsetof(class Thread, m_pFrame);
_ASSERTE(FitsInI1(ofs));
return (BYTE)ofs;
}
static BYTE GetOffsetOfState()
{
LIMITED_METHOD_CONTRACT;
size_t ofs = offsetof(class Thread, m_State);
_ASSERTE(FitsInI1(ofs));
return (BYTE)ofs;
}
static BYTE GetOffsetOfGCFlag()
{
LIMITED_METHOD_CONTRACT;
size_t ofs = offsetof(class Thread, m_fPreemptiveGCDisabled);
_ASSERTE(FitsInI1(ofs));
return (BYTE)ofs;
}
static void StaticDisablePreemptiveGC( Thread *pThread)
{
WRAPPER_NO_CONTRACT;
_ASSERTE(pThread != NULL);
pThread->DisablePreemptiveGC();
}
static void StaticEnablePreemptiveGC( Thread *pThread)
{
WRAPPER_NO_CONTRACT;
_ASSERTE(pThread != NULL);
pThread->EnablePreemptiveGC();
}
//---------------------------------------------------------------
// Expose offset of the app domain word for the interop and delegate callback
//---------------------------------------------------------------
static SIZE_T GetOffsetOfAppDomain()
{
LIMITED_METHOD_CONTRACT;
return (SIZE_T)(offsetof(class Thread, m_pDomain));
}
//---------------------------------------------------------------
// Expose offset of the place for storing the filter context for the debugger.
//---------------------------------------------------------------
static SIZE_T GetOffsetOfDebuggerFilterContext()
{
LIMITED_METHOD_CONTRACT;
return (SIZE_T)(offsetof(class Thread, m_debuggerFilterContext));
}
//---------------------------------------------------------------
// Expose offset of the debugger cant stop count for the debugger
//---------------------------------------------------------------
static SIZE_T GetOffsetOfCantStop()
{
LIMITED_METHOD_CONTRACT;
return (SIZE_T)(offsetof(class Thread, m_debuggerCantStop));
}
//---------------------------------------------------------------
// Expose offset of m_StateNC
//---------------------------------------------------------------
static SIZE_T GetOffsetOfStateNC()
{
LIMITED_METHOD_CONTRACT;
return (SIZE_T)(offsetof(class Thread, m_StateNC));
}
//---------------------------------------------------------------
// Last exception to be thrown
//---------------------------------------------------------------
inline void SetThrowable(OBJECTREF pThrowable
DEBUG_ARG(ThreadExceptionState::SetThrowableErrorChecking stecFlags = ThreadExceptionState::STEC_All));
OBJECTREF GetThrowable()
{
WRAPPER_NO_CONTRACT;
return m_ExceptionState.GetThrowable();
}
// An unmnaged thread can check if a managed is processing an exception
BOOL HasException()
{
LIMITED_METHOD_CONTRACT;
OBJECTHANDLE pThrowable = m_ExceptionState.GetThrowableAsHandle();
return pThrowable && *PTR_UNCHECKED_OBJECTREF(pThrowable);
}
OBJECTHANDLE GetThrowableAsHandle()
{
LIMITED_METHOD_CONTRACT;
return m_ExceptionState.GetThrowableAsHandle();
}
// special null test (for use when we're in the wrong GC mode)
BOOL IsThrowableNull()
{
WRAPPER_NO_CONTRACT;
return IsHandleNullUnchecked(m_ExceptionState.GetThrowableAsHandle());
}
BOOL IsExceptionInProgress()
{
SUPPORTS_DAC;
LIMITED_METHOD_CONTRACT;
return m_ExceptionState.IsExceptionInProgress();
}
void SyncManagedExceptionState(bool fIsDebuggerThread);
//---------------------------------------------------------------
// Per-thread information used by handler
//---------------------------------------------------------------
// exception handling info stored in thread
// can't allocate this as needed because can't make exception-handling depend upon memory allocation
PTR_ThreadExceptionState GetExceptionState()
{
LIMITED_METHOD_CONTRACT;
SUPPORTS_DAC;
return PTR_ThreadExceptionState(PTR_HOST_MEMBER_TADDR(Thread, this, m_ExceptionState));
}
// Access to the Context this thread is executing in.
Context *GetContext()
{
LIMITED_METHOD_CONTRACT;
SUPPORTS_DAC;
#ifndef DACCESS_COMPILE
// if another thread is asking about our thread, we could be in the middle of an AD transition so
// the context and AD may not match if have set one but not the other. Can live without checking when
// another thread is asking it as this method is mostly called on our own thread so will mostly get the
// checking. If are int the middle of a transition, this could return either the old or the new AD.
// But no matter what we do, such as lock on the transition, by the time are done could still have
// changed right after we asked, so really no point.
_ASSERTE((this != GetThreadNULLOk()) || (m_Context == NULL && m_pDomain == NULL) || (m_Context->GetDomain() == m_pDomain) || g_fEEShutDown);
#endif // DACCESS_COMPILE
return m_Context;
}
// This callback is used when we are executing in the EE and discover that we need
// to switch appdomains.
//
// Set the last parameter to FALSE if you want to perform the AD transition *without*
// EH (this can affect marshalling of exceptions).
void DoADCallBack(ADID appDomain , Context::ADCallBackFcnType pTarget, LPVOID args, BOOL fSetupEHAtTransition = TRUE);
void DoADCallBack(AppDomain* pDomain , Context::ADCallBackFcnType pTarget, LPVOID args, DWORD dwADV, BOOL fSetupEHAtTransition = TRUE);
void DoContextCallBack(ADID appDomain, Context* c , Context::ADCallBackFcnType pTarget, LPVOID args);
// Except for security and the call in from the remoting code in mscorlib, you should never do an
// AppDomain transition directly through these functions. Rather, you should use DoADCallBack above
// to call into managed code to perform the transition for you so that the correct policy code etc
// is run on the transition,
void EnterContextRestricted(Context* c, ContextTransitionFrame* pFrame);
void ReturnToContext(ContextTransitionFrame *pFrame);
private:
typedef enum {
RaiseCrossContextSuccess,
RaiseCrossContextRetry,
RaiseCrossContextClassInit
} RaiseCrossContextResult;
// The "orBlob" stores the serialized image of a managed Exception object as it gets marshaled
// across AD boundaries.
//
// In Telesto, we don't support true appdomain marshaling so the "orBlob" is in fact an
// agile wrapper object whose ToString() echoes the original exception's ToString().
typedef OBJECTREF ORBLOBREF;
RaiseCrossContextResult TryRaiseCrossContextException(Exception **ppExOrig,
Exception *pException,
RuntimeExceptionKind *pKind,
OBJECTREF *ppThrowable,
ORBLOBREF *pOrBlob);
public:
void DECLSPEC_NORETURN RaiseCrossContextException(Exception* pEx, ContextTransitionFrame* pFrame);
void RaiseCrossContextExceptionHelper(Exception* pEx,ContextTransitionFrame* pFrame);
// ClearContext are to be called only during shutdown
void ClearContext();
// Used by security to prevent recursive stackwalking.
BOOL IsSecurityStackwalkInProgess()
{
LIMITED_METHOD_CONTRACT;
return m_fSecurityStackwalk;
}
void SetSecurityStackwalkInProgress(BOOL fSecurityStackwalk)
{
LIMITED_METHOD_CONTRACT;
m_fSecurityStackwalk = fSecurityStackwalk;
}
private:
void ReturnToContextAndThrow(ContextTransitionFrame* pFrame, EEException* pEx, BOOL* pContextSwitched);
void ReturnToContextAndOOM(ContextTransitionFrame* pFrame);
private:
// don't ever call these except when creating thread!!!!!
void InitContext();
BOOL m_fSecurityStackwalk;
public:
PTR_AppDomain GetDomain(INDEBUG(BOOL fMidContextTransitionOK = FALSE))
{
LIMITED_METHOD_DAC_CONTRACT;
// if another thread is asking about our thread, we could be in the middle of an AD transition so
// the context and AD may not match if have set one but not the other. Can live without checking when
// another thread is asking it as this method is mostly called on our own thread so will mostly get the
// checking. If are int the middle of a transition, this could return either the old or the new AD.
// But no matter what we do, such as lock on the transition, by the time are done could still have
// changed right after we asked, so really no point.
#ifdef _DEBUG_IMPL
BEGIN_GETTHREAD_ALLOWED_IN_NO_THROW_REGION;
if (!g_fEEShutDown && this == GetThread())
{
if (!fMidContextTransitionOK)
{
// We also want to suppress the "domain on context == domain on thread" check if this might
// be called during a context or AD transition (in which case fMidContextTransitionOK is nonzero).
// A profiler stackwalk can occur at arbitrary times, including during these transitions, but
// the stackwalk is still safe to do at this point, so we don't want to trigger this assert.
_ASSERTE((m_Context == NULL && m_pDomain == NULL) || m_Context->GetDomain() == m_pDomain);
}
AppDomain* valueInTLSSlot = GetAppDomain();
_ASSERTE(valueInTLSSlot == 0 || valueInTLSSlot == m_pDomain);
}
END_GETTHREAD_ALLOWED_IN_NO_THROW_REGION;
#endif
return m_pDomain;
}
Frame *IsRunningIn(AppDomain* pDomain, int *count);
Frame *GetFirstTransitionInto(AppDomain *pDomain, int *count);
BOOL ShouldChangeAbortToUnload(Frame *pFrame, Frame *pUnloadBoundaryFrame=NULL);
// Get outermost (oldest) AppDomain for this thread.
AppDomain *GetInitialDomain();
//---------------------------------------------------------------
// Track use of the thread block. See the general comments on
// thread destruction in threads.cpp, for details.
//---------------------------------------------------------------
int IncExternalCount();
int DecExternalCount(BOOL holdingLock);
//---------------------------------------------------------------
// !!!! THESE ARE NOT SAFE FOR GENERAL USE !!!!
// IncExternalCountDANGEROUSProfilerOnly()
// DecExternalCountDANGEROUSProfilerOnly()
// Currently only the profiler API should be using these
// functions, because the profiler is responsible for ensuring
// that the thread exists, undestroyed, before operating on it.
// All other clients should use IncExternalCount/DecExternalCount
// instead
//---------------------------------------------------------------
int IncExternalCountDANGEROUSProfilerOnly()
{
LIMITED_METHOD_CONTRACT;
#ifdef _DEBUG
int cRefs =
#else // _DEBUG
return
#endif //_DEBUG
FastInterlockIncrement((LONG*)&m_ExternalRefCount);
#ifdef _DEBUG
// This should never be called on a thread being destroyed
_ASSERTE(cRefs != 1);
return cRefs;
#endif //_DEBUG
}
int DecExternalCountDANGEROUSProfilerOnly()
{
LIMITED_METHOD_CONTRACT;
#ifdef _DEBUG
int cRefs =
#else // _DEBUG
return
#endif //_DEBUG
FastInterlockDecrement((LONG*)&m_ExternalRefCount);
#ifdef _DEBUG
// This should never cause the last reference on the thread to be released
_ASSERTE(cRefs != 0);
return cRefs;
#endif //_DEBUG
}
// Get and Set the exposed System.Thread object which corresponds to
// this thread. Also the thread handle and Id.
OBJECTREF GetExposedObject();
OBJECTREF GetExposedObjectRaw();
void SetExposedObject(OBJECTREF exposed);
OBJECTHANDLE GetExposedObjectHandleForDebugger()
{
LIMITED_METHOD_CONTRACT;
return m_ExposedObject;
}
// Query whether the exposed object exists
BOOL IsExposedObjectSet()
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
SO_TOLERANT;
MODE_COOPERATIVE;
}
CONTRACTL_END;
return (ObjectFromHandle(m_ExposedObject) != NULL) ;
}
void GetSynchronizationContext(OBJECTREF *pSyncContextObj)
{
CONTRACTL
{
MODE_COOPERATIVE;
GC_NOTRIGGER;
NOTHROW;
PRECONDITION(CheckPointer(pSyncContextObj));
}
CONTRACTL_END;
*pSyncContextObj = NULL;
THREADBASEREF ExposedThreadObj = (THREADBASEREF)GetExposedObjectRaw();
if (ExposedThreadObj != NULL)
*pSyncContextObj = ExposedThreadObj->GetSynchronizationContext();
}
// When we create a managed thread, the thread is suspended. We call StartThread to get
// the thread start.
DWORD StartThread();
// The result of attempting to OS-suspend an EE thread.
enum SuspendThreadResult
{
// We successfully suspended the thread. This is the only
// case where the caller should subsequently call ResumeThread.
STR_Success,
// The underlying call to the operating system's SuspendThread
// or GetThreadContext failed. This is usually taken to mean
// that the OS thread has exited. (This can possibly also mean
//
// that the suspension count exceeded the allowed maximum, but
// Thread::SuspendThread asserts that does not happen.)
STR_Failure,
// The thread handle is invalid. This means that the thread
// is dead (or dying), or that the object has been created for
// an exposed System.Thread that has not been started yet.
STR_UnstartedOrDead,
// The fOneTryOnly flag was set, and we managed to OS suspend the
// thread, but we found that it had its m_dwForbidSuspendThread
// flag set. If fOneTryOnly is not set, Thread::Suspend will
// retry in this case.
STR_Forbidden,
// Stress logging is turned on, but no stress log had been created
// for the thread yet, and we failed to create one. This can mean
// that either we are not allowed to call into the host, or we ran
// out of memory.
STR_NoStressLog,
// The EE thread is currently switched out. This can only happen
// if we are hosted and the host schedules EE threads on fibers.
STR_SwitchedOut,
};
#if defined(FEATURE_HIJACK) && defined(PLATFORM_UNIX)
bool InjectGcSuspension();
#endif // FEATURE_HIJACK && PLATFORM_UNIX
#ifndef DISABLE_THREADSUSPEND
// SuspendThread
// Attempts to OS-suspend the thread, whichever GC mode it is in.
// Arguments:
// fOneTryOnly - If TRUE, report failure if the thread has its
// m_dwForbidSuspendThread flag set. If FALSE, retry.
// pdwSuspendCount - If non-NULL, will contain the return code
// of the underlying OS SuspendThread call on success,
// undefined on any kind of failure.
// Return value:
// A SuspendThreadResult value indicating success or failure.
SuspendThreadResult SuspendThread(BOOL fOneTryOnly = FALSE, DWORD *pdwSuspendCount = NULL);
DWORD ResumeThread();
#endif // DISABLE_THREADSUSPEND
int GetThreadPriority();
BOOL SetThreadPriority(
int nPriority // thread priority level
);
BOOL Alert ();
DWORD Join(DWORD timeout, BOOL alertable);
DWORD JoinEx(DWORD timeout, WaitMode mode);
BOOL GetThreadContext(
LPCONTEXT lpContext // context structure
)
{
WRAPPER_NO_CONTRACT;
return ::GetThreadContext (GetThreadHandle(), lpContext);
}
#ifndef DACCESS_COMPILE
BOOL SetThreadContext(
CONST CONTEXT *lpContext // context structure
)
{
WRAPPER_NO_CONTRACT;
return ::SetThreadContext (GetThreadHandle(), lpContext);
}
#endif
BOOL HasValidThreadHandle ()
{
WRAPPER_NO_CONTRACT;
return GetThreadHandle() != INVALID_HANDLE_VALUE;
}
DWORD GetThreadId()
{
STATIC_CONTRACT_SO_TOLERANT;
LIMITED_METHOD_DAC_CONTRACT;
_ASSERTE(m_ThreadId != UNINITIALIZED_THREADID);
return m_ThreadId;
}
DWORD GetOSThreadId()
{
LIMITED_METHOD_CONTRACT;
SUPPORTS_DAC;
#ifndef DACCESS_COMPILE
_ASSERTE (m_OSThreadId != 0xbaadf00d);
#endif // !DACCESS_COMPILE
return m_OSThreadId;
}
// This API is to be used for Debugger only.
// We need to be able to return the true value of m_OSThreadId.
//
DWORD GetOSThreadIdForDebugger()
{
SUPPORTS_DAC;
LIMITED_METHOD_CONTRACT;
return m_OSThreadId;
}
TASKID GetTaskId()
{
LIMITED_METHOD_CONTRACT;
return m_TaskId;
}
CONNID GetConnectionId()
{
LIMITED_METHOD_CONTRACT;
return m_dwConnectionId;
}
void SetConnectionId(CONNID dwConnectionId)
{
LIMITED_METHOD_CONTRACT;
m_dwConnectionId = dwConnectionId;
}
BOOL IsThreadPoolThread()
{
LIMITED_METHOD_CONTRACT;
return m_State & (Thread::TS_TPWorkerThread | Thread::TS_CompletionPortThread);
}
// public suspend functions. System ones are internal, like for GC. User ones
// correspond to suspend/resume calls on the exposed System.Thread object.
static bool SysStartSuspendForDebug(AppDomain *pAppDomain);
static bool SysSweepThreadsForDebug(bool forceSync);
static void SysResumeFromDebug(AppDomain *pAppDomain);
void UserSleep(INT32 time);
// AD unload uses ThreadAbort support. We need to distinguish pure ThreadAbort and AD unload
// cases.
enum ThreadAbortRequester
{
TAR_Thread = 0x00000001, // Request by Thread
TAR_ADUnload = 0x00000002, // Request by AD unload
TAR_FuncEval = 0x00000004, // Request by Func-Eval
TAR_StackOverflow = 0x00000008, // Request by StackOverflow. TAR_THREAD should be set at the same time.
TAR_ALL = 0xFFFFFFFF,
};
private:
//
// Bit mask for tracking which aborts came in and why.
//
enum ThreadAbortInfo
{
TAI_ThreadAbort = 0x00000001,
TAI_ThreadV1Abort = 0x00000002,
TAI_ThreadRudeAbort = 0x00000004,
TAI_ADUnloadAbort = 0x00000008,
TAI_ADUnloadV1Abort = 0x00000010,
TAI_ADUnloadRudeAbort = 0x00000020,
TAI_FuncEvalAbort = 0x00000040,
TAI_FuncEvalV1Abort = 0x00000080,
TAI_FuncEvalRudeAbort = 0x00000100,
TAI_ForADUnloadThread = 0x10000000, // AD unload thread is working on the thread
};
static const DWORD TAI_AnySafeAbort = (TAI_ThreadAbort |
TAI_ADUnloadAbort |
TAI_FuncEvalAbort
);
static const DWORD TAI_AnyV1Abort = (TAI_ThreadV1Abort |
TAI_ADUnloadV1Abort |
TAI_FuncEvalV1Abort
);
static const DWORD TAI_AnyRudeAbort = (TAI_ThreadRudeAbort |
TAI_ADUnloadRudeAbort |
TAI_FuncEvalRudeAbort
);
static const DWORD TAI_AnyFuncEvalAbort = (TAI_FuncEvalAbort |
TAI_FuncEvalV1Abort |
TAI_FuncEvalRudeAbort
);
// Specifies type of thread abort.
DWORD m_AbortInfo;
DWORD m_AbortType;
ULONGLONG m_AbortEndTime;
ULONGLONG m_RudeAbortEndTime;
BOOL m_fRudeAbortInitiated;
LONG m_AbortController;
static ULONGLONG s_NextSelfAbortEndTime;
void SetRudeAbortEndTimeFromEEPolicy();
// This is a spin lock to serialize setting/resetting of AbortType and AbortRequest.
LONG m_AbortRequestLock;
static void LockAbortRequest(Thread *pThread);
static void UnlockAbortRequest(Thread *pThread);
typedef Holder<Thread*, Thread::LockAbortRequest, Thread::UnlockAbortRequest> AbortRequestLockHolder;
static void AcquireAbortControl(Thread *pThread)
{
LIMITED_METHOD_CONTRACT;
FastInterlockIncrement (&pThread->m_AbortController);
}
static void ReleaseAbortControl(Thread *pThread)
{
LIMITED_METHOD_CONTRACT;
_ASSERTE (pThread->m_AbortController > 0);
FastInterlockDecrement (&pThread->m_AbortController);
}
typedef Holder<Thread*, Thread::AcquireAbortControl, Thread::ReleaseAbortControl> AbortControlHolder;
BOOL IsBeingAbortedForADUnload()
{
LIMITED_METHOD_CONTRACT;
return (m_AbortInfo & TAI_ForADUnloadThread) != 0;
}
void ResetBeginAbortedForADUnload();
public:
#ifdef _DEBUG
BOOL m_fRudeAborted;
DWORD m_dwAbortPoint;
#endif
public:
enum UserAbort_Client
{
UAC_Normal,
UAC_Host, // Called by host through IClrTask::Abort
UAC_WatchDog, // Called by ADUnload helper thread
UAC_FinalizerTimeout,
};
HRESULT UserAbort(ThreadAbortRequester requester,
EEPolicy::ThreadAbortTypes abortType,
DWORD timeout,
UserAbort_Client client
);
BOOL HandleJITCaseForAbort();
void UserResetAbort(ThreadAbortRequester requester)
{
InternalResetAbort(requester, FALSE);
}
void EEResetAbort(ThreadAbortRequester requester)
{
InternalResetAbort(requester, TRUE);
}
private:
void InternalResetAbort(ThreadAbortRequester requester, BOOL fResetRudeAbort);
void SetAbortEndTime(ULONGLONG endTime, BOOL fRudeAbort);
public:
ULONGLONG GetAbortEndTime()
{
WRAPPER_NO_CONTRACT;
return IsRudeAbort()?m_RudeAbortEndTime:m_AbortEndTime;
}
// We distinguish interrupting a thread between Thread.Interrupt and other usage.
// For Thread.Interrupt usage, we will interrupt an alertable wait using the same
// rule as ReadyForAbort. Wait in EH clause or CER region is not interrupted.
// For other usage, we will try to Abort the thread.
// If we can not do the operation, we will delay until next wait.
enum ThreadInterruptMode
{
TI_Interrupt = 0x00000001, // Requested by Thread.Interrupt
TI_Abort = 0x00000002, // Requested by Thread.Abort or AppDomain.Unload
};
private:
BOOL ReadyForAsyncException();
public:
void UserInterrupt(ThreadInterruptMode mode);
void SetAbortRequest(EEPolicy::ThreadAbortTypes abortType); // Should only be called by ADUnload
BOOL ReadyForAbort()
{
return ReadyForAsyncException();
}
BOOL IsRudeAbort();
BOOL IsRudeAbortOnlyForADUnload();
BOOL IsRudeUnload();
BOOL IsFuncEvalAbort();
#if defined(_TARGET_AMD64_) && defined(FEATURE_HIJACK)
BOOL IsSafeToInjectThreadAbort(PTR_CONTEXT pContextToCheck);
#endif // defined(_TARGET_AMD64_) && defined(FEATURE_HIJACK)
inline BOOL IsAbortRequested()
{
LIMITED_METHOD_CONTRACT;
return (m_State & TS_AbortRequested);
}
inline BOOL IsAbortInitiated()
{
LIMITED_METHOD_CONTRACT;
return (m_State & TS_AbortInitiated);
}
inline BOOL IsRudeAbortInitiated()
{
LIMITED_METHOD_CONTRACT;
return IsAbortRequested() && m_fRudeAbortInitiated;
}
inline void SetAbortInitiated()
{
WRAPPER_NO_CONTRACT;
if (IsRudeAbort()) {
m_fRudeAbortInitiated = TRUE;
}
FastInterlockOr((ULONG *)&m_State, TS_AbortInitiated);
// The following should be factored better, but I'm looking for a minimal V1 change.
ResetUserInterrupted();
}
inline void ResetAbortInitiated()
{
LIMITED_METHOD_CONTRACT;
FastInterlockAnd((ULONG *)&m_State, ~TS_AbortInitiated);
m_fRudeAbortInitiated = FALSE;
}
inline void SetPreparingAbort()
{
WRAPPER_NO_CONTRACT;
SetThreadStateNC(TSNC_PreparingAbort);
}
inline void ResetPreparingAbort()
{
WRAPPER_NO_CONTRACT;
ResetThreadStateNC(TSNC_PreparingAbort);
}
private:
inline static void SetPreparingAbortForHolder()
{
GetThread()->SetPreparingAbort();
}
inline static void ResetPreparingAbortForHolder()
{
GetThread()->ResetPreparingAbort();
}
typedef StateHolder<Thread::SetPreparingAbortForHolder, Thread::ResetPreparingAbortForHolder> PreparingAbortHolder;
public:
inline void SetIsCreatingTypeInitException()
{
WRAPPER_NO_CONTRACT;
SetThreadStateNC(TSNC_CreatingTypeInitException);
}
inline void ResetIsCreatingTypeInitException()
{
WRAPPER_NO_CONTRACT;
ResetThreadStateNC(TSNC_CreatingTypeInitException);
}
inline BOOL IsCreatingTypeInitException()
{
WRAPPER_NO_CONTRACT;
return HasThreadStateNC(TSNC_CreatingTypeInitException);
}
private:
void SetAbortRequestBit();
void RemoveAbortRequestBit();
public:
void MarkThreadForAbort(ThreadAbortRequester requester, EEPolicy::ThreadAbortTypes abortType, BOOL fTentative = FALSE);
void UnmarkThreadForAbort(ThreadAbortRequester requester, BOOL fForce = TRUE);
private:
static void ThreadAbortWatchDogAbort(Thread *pThread);
static void ThreadAbortWatchDogEscalate(Thread *pThread);
public:
static void ThreadAbortWatchDog();
static ULONGLONG GetNextSelfAbortEndTime()
{
LIMITED_METHOD_CONTRACT;
return s_NextSelfAbortEndTime;
}
#if defined(FEATURE_HIJACK) && !defined(PLATFORM_UNIX)
// Tricks for resuming threads from fully interruptible code with a ThreadStop.
BOOL ResumeUnderControl(T_CONTEXT *pCtx);
#endif // FEATURE_HIJACK && !PLATFORM_UNIX
enum InducedThrowReason {
InducedThreadStop = 1,
InducedThreadRedirect = 2,
InducedThreadRedirectAtEndOfCatch = 3,
};
DWORD m_ThrewControlForThread; // flag that is set when the thread deliberately raises an exception for stop/abort
inline DWORD ThrewControlForThread()
{
LIMITED_METHOD_CONTRACT;
return m_ThrewControlForThread;
}
inline void SetThrowControlForThread(InducedThrowReason reason)
{
LIMITED_METHOD_CONTRACT;
m_ThrewControlForThread = reason;
}
inline void ResetThrowControlForThread()
{
LIMITED_METHOD_CONTRACT;
m_ThrewControlForThread = 0;
}
PTR_CONTEXT m_OSContext; // ptr to a Context structure used to record the OS specific ThreadContext for a thread
// this is used for thread stop/abort and is intialized on demand
PT_CONTEXT GetAbortContext ();
// These will only ever be called from the debugger's helper
// thread.
//
// When a thread is being created after a debug suspension has
// started, we get the event on the debugger helper thread. It
// will turn around and call this to set the debug suspend pending
// flag on the newly created flag, since it was missed by
// SysStartSuspendForGC as it didn't exist when that function was
// run.
void MarkForDebugSuspend();
// When the debugger uses the trace flag to single step a thread,
// it also calls this function to mark this info in the thread's
// state. The out-of-process portion of the debugger will read the
// thread's state for a variety of reasons, including looking for
// this flag.
void MarkDebuggerIsStepping(bool onOff)
{
WRAPPER_NO_CONTRACT;
if (onOff)
SetThreadStateNC(Thread::TSNC_DebuggerIsStepping);
else
ResetThreadStateNC(Thread::TSNC_DebuggerIsStepping);
}
#ifdef _TARGET_ARM_
// ARM doesn't currently support any reliable hardware mechanism for single-stepping. Instead we emulate
// this in software. This support is used only by the debugger.
private:
ArmSingleStepper m_singleStepper;
public:
#ifndef DACCESS_COMPILE
// Given the context with which this thread shall be resumed and the first WORD of the instruction that
// should be executed next (this is not always the WORD under PC since the debugger uses this mechanism to
// skip breakpoints written into the code), set the thread up to execute one instruction and then throw an
// EXCEPTION_SINGLE_STEP. (In fact an EXCEPTION_BREAKPOINT will be thrown, but this is fixed up in our
// first chance exception handler, see IsDebuggerFault in excep.cpp).
void EnableSingleStep()
{
m_singleStepper.Enable();
}
void BypassWithSingleStep(DWORD ip, WORD opcode1, WORD opcode2)
{
m_singleStepper.Bypass(ip, opcode1, opcode2);
}
void DisableSingleStep()
{
m_singleStepper.Disable();
}
void ApplySingleStep(T_CONTEXT *pCtx)
{
m_singleStepper.Apply(pCtx);
}
bool IsSingleStepEnabled() const
{
return m_singleStepper.IsEnabled();
}
// Fixup code called by our vectored exception handler to complete the emulation of single stepping
// initiated by EnableSingleStep above. Returns true if the exception was indeed encountered during
// stepping.
bool HandleSingleStep(T_CONTEXT *pCtx, DWORD dwExceptionCode)
{
return m_singleStepper.Fixup(pCtx, dwExceptionCode);
}
#endif // !DACCESS_COMPILE
#endif // _TARGET_ARM_
private:
PendingTypeLoadHolder* m_pPendingTypeLoad;
public:
#ifndef DACCESS_COMPILE
PendingTypeLoadHolder* GetPendingTypeLoad()
{
LIMITED_METHOD_CONTRACT;
return m_pPendingTypeLoad;
}
void SetPendingTypeLoad(PendingTypeLoadHolder* pPendingTypeLoad)
{
LIMITED_METHOD_CONTRACT;
m_pPendingTypeLoad = pPendingTypeLoad;
}
#endif
#ifdef FEATURE_PREJIT
private:
ThreadLocalIBCInfo* m_pIBCInfo;
public:
#ifndef DACCESS_COMPILE
ThreadLocalIBCInfo* GetIBCInfo()
{
LIMITED_METHOD_CONTRACT;
_ASSERTE(g_IBCLogger.InstrEnabled());
return m_pIBCInfo;
}
void SetIBCInfo(ThreadLocalIBCInfo* pInfo)
{
LIMITED_METHOD_CONTRACT;
_ASSERTE(g_IBCLogger.InstrEnabled());
m_pIBCInfo = pInfo;
}
void FlushIBCInfo()
{
WRAPPER_NO_CONTRACT;
if (m_pIBCInfo != NULL)
m_pIBCInfo->FlushDelayedCallbacks();
}
#endif // #ifndef DACCESS_COMPILE
#endif // #ifdef FEATURE_PREJIT
// Indicate whether this thread should run in the background. Background threads
// don't interfere with the EE shutting down. Whereas a running non-background
// thread prevents us from shutting down (except through System.Exit(), of course)
// WARNING : only GC calls this with bRequiresTSL set to FALSE.
void SetBackground(BOOL isBack, BOOL bRequiresTSL=TRUE);
// When the thread starts running, make sure it is running in the correct apartment
// and context.
BOOL PrepareApartmentAndContext();
#ifdef FEATURE_COMINTEROP_APARTMENT_SUPPORT
// Retrieve the apartment state of the current thread. There are three possible
// states: thread hosts an STA, thread is part of the MTA or thread state is
// undecided. The last state may indicate that the apartment has not been set at
// all (nobody has called CoInitializeEx) or that the EE does not know the
// current state (EE has not called CoInitializeEx).
enum ApartmentState { AS_InSTA, AS_InMTA, AS_Unknown };
ApartmentState GetApartment();
ApartmentState GetApartmentRare(Thread::ApartmentState as);
ApartmentState GetExplicitApartment();
// Sets the apartment state if it has not already been set and
// returns the state.
ApartmentState GetFinalApartment();
// Attempt to set current thread's apartment state. The actual apartment state
// achieved is returned and may differ from the input state if someone managed to
// call CoInitializeEx on this thread first (note that calls to SetApartment made
// before the thread has started are guaranteed to succeed).
// The fFireMDAOnMismatch indicates if we should fire the apartment state probe
// on an apartment state mismatch.
ApartmentState SetApartment(ApartmentState state, BOOL fFireMDAOnMismatch);
// when we get apartment tear-down notification,
// we want reset the apartment state we cache on the thread
VOID ResetApartment();
#endif // FEATURE_COMINTEROP_APARTMENT_SUPPORT
// Either perform WaitForSingleObject or MsgWaitForSingleObject as appropriate.
DWORD DoAppropriateWait(int countHandles, HANDLE *handles, BOOL waitAll,
DWORD millis, WaitMode mode,
PendingSync *syncInfo = 0);
DWORD DoAppropriateWait(AppropriateWaitFunc func, void *args, DWORD millis,
WaitMode mode, PendingSync *syncInfo = 0);
DWORD DoSignalAndWait(HANDLE *handles, DWORD millis, BOOL alertable,
PendingSync *syncState = 0);
private:
void DoAppropriateWaitWorkerAlertableHelper(WaitMode mode);
DWORD DoAppropriateWaitWorker(int countHandles, HANDLE *handles, BOOL waitAll,
DWORD millis, WaitMode mode);
DWORD DoAppropriateWaitWorker(AppropriateWaitFunc func, void *args,
DWORD millis, WaitMode mode);
DWORD DoSignalAndWaitWorker(HANDLE* pHandles, DWORD millis,BOOL alertable);
DWORD DoAppropriateAptStateWait(int numWaiters, HANDLE* pHandles, BOOL bWaitAll, DWORD timeout, WaitMode mode);
DWORD DoSyncContextWait(OBJECTREF *pSyncCtxObj, int countHandles, HANDLE *handles, BOOL waitAll, DWORD millis);
public:
//************************************************************************
// Enumerate all frames.
//************************************************************************
/* Flags used for StackWalkFramesEx */
// FUNCTIONSONLY excludes all functionless frames and all funclets
#define FUNCTIONSONLY 0x0001
// SKIPFUNCLETS includes functionless frames but excludes all funclets and everything between funclets and their parent methods
#define SKIPFUNCLETS 0x0002
#define POPFRAMES 0x0004
/* use the following flag only if you REALLY know what you are doing !!! */
#define QUICKUNWIND 0x0008 // do not restore all registers during unwind
#define HANDLESKIPPEDFRAMES 0x0010 // temporary to handle skipped frames for appdomain unload
// stack crawl. Eventually need to always do this but it
// breaks the debugger right now.
#define LIGHTUNWIND 0x0020 // allow using cache schema (see StackwalkCache class)
#define NOTIFY_ON_U2M_TRANSITIONS 0x0040 // Provide a callback for native transitions.
// This is only useful to a debugger trying to find native code
// in the stack.
#define DISABLE_MISSING_FRAME_DETECTION 0x0080 // disable detection of missing TransitionFrames
// One thread may be walking the stack of another thread
// If you need to use this, you may also need to put a call to CrawlFrame::CheckGSCookies
// in your callback routine if it does any potentially time-consuming activity.
#define ALLOW_ASYNC_STACK_WALK 0x0100
#define THREAD_IS_SUSPENDED 0x0200 // Be careful not to cause deadlocks, this thread is suspended
// Stackwalk tries to verify some objects, but it could be called in relocate phase of GC,
// where objects could be in invalid state, this flag is to tell stackwalk to skip the validation
#define ALLOW_INVALID_OBJECTS 0x0400
// Caller has verified that the thread to be walked is in the middle of executing
// JITd or NGENd code, according to the thread's current context (or seeded
// context if one was provided). The caller ensures this when the stackwalk
// is initiated by a profiler.
#define THREAD_EXECUTING_MANAGED_CODE 0x0800
// This stackwalk is due to the DoStackSnapshot profiler API
#define PROFILER_DO_STACK_SNAPSHOT 0x1000
// When this flag is set, the stackwalker does not automatically advance to the
// faulting managed stack frame when it encounters an ExInfo. This should only be
// necessary for native debuggers doing mixed-mode stackwalking.
#define NOTIFY_ON_NO_FRAME_TRANSITIONS 0x2000
// Normally, the stackwalker does not stop at the initial CONTEXT if the IP is in native code.
// This flag changes the stackwalker behaviour. Currently this is only used in the debugger stackwalking
// API.
#define NOTIFY_ON_INITIAL_NATIVE_CONTEXT 0x4000
// Indicates that we are enumerating GC references and should follow appropriate
// callback rules for parent methods vs funclets. Only supported on non-x86 platforms.
//
// Refer to StackFrameIterator::Filter for detailed comments on this flag.
#define GC_FUNCLET_REFERENCE_REPORTING 0x8000
StackWalkAction StackWalkFramesEx(
PREGDISPLAY pRD, // virtual register set at crawl start
PSTACKWALKFRAMESCALLBACK pCallback,
VOID *pData,
unsigned flags,
PTR_Frame pStartFrame = PTR_NULL);
private:
// private helpers used by StackWalkFramesEx and StackFrameIterator
StackWalkAction MakeStackwalkerCallback(CrawlFrame* pCF, PSTACKWALKFRAMESCALLBACK pCallback, VOID* pData DEBUG_ARG(UINT32 uLoopIteration));
#ifdef _DEBUG
void DebugLogStackWalkInfo(CrawlFrame* pCF, __in_z LPCSTR pszTag, UINT32 uLoopIteration);
#endif // _DEBUG
public:
StackWalkAction StackWalkFrames(
PSTACKWALKFRAMESCALLBACK pCallback,
VOID *pData,
unsigned flags = 0,
PTR_Frame pStartFrame = PTR_NULL);
bool InitRegDisplay(const PREGDISPLAY, const PT_CONTEXT, bool validContext);
void FillRegDisplay(const PREGDISPLAY pRD, PT_CONTEXT pctx);
#ifdef WIN64EXCEPTIONS
static PCODE VirtualUnwindCallFrame(T_CONTEXT* pContext, T_KNONVOLATILE_CONTEXT_POINTERS* pContextPointers = NULL,
EECodeInfo * pCodeInfo = NULL);
static UINT_PTR VirtualUnwindCallFrame(PREGDISPLAY pRD, EECodeInfo * pCodeInfo = NULL);
#ifndef DACCESS_COMPILE
static PCODE VirtualUnwindLeafCallFrame(T_CONTEXT* pContext);
static PCODE VirtualUnwindNonLeafCallFrame(T_CONTEXT* pContext, T_KNONVOLATILE_CONTEXT_POINTERS* pContextPointers = NULL,
PT_RUNTIME_FUNCTION pFunctionEntry = NULL, UINT_PTR uImageBase = NULL);
static UINT_PTR VirtualUnwindToFirstManagedCallFrame(T_CONTEXT* pContext);
#endif // DACCESS_COMPILE
#endif // WIN64EXCEPTIONS
// During a <clinit>, this thread must not be asynchronously
// stopped or interrupted. That would leave the class unavailable
// and is therefore a security hole.
static void IncPreventAsync()
{
WRAPPER_NO_CONTRACT;
Thread *pThread = GetThread();
FastInterlockIncrement((LONG*)&pThread->m_PreventAsync);
}
static void DecPreventAsync()
{
WRAPPER_NO_CONTRACT;
Thread *pThread = GetThread();
FastInterlockDecrement((LONG*)&pThread->m_PreventAsync);
}
bool IsAsyncPrevented()
{
return m_PreventAsync != 0;
}
typedef StateHolder<Thread::IncPreventAsync, Thread::DecPreventAsync> ThreadPreventAsyncHolder;
// During a <clinit>, this thread must not be asynchronously
// stopped or interrupted. That would leave the class unavailable
// and is therefore a security hole.
static void IncPreventAbort()
{
WRAPPER_NO_CONTRACT;
Thread *pThread = GetThread();
FastInterlockIncrement((LONG*)&pThread->m_PreventAbort);
}
static void DecPreventAbort()
{
WRAPPER_NO_CONTRACT;
Thread *pThread = GetThread();
FastInterlockDecrement((LONG*)&pThread->m_PreventAbort);
}
BOOL IsAbortPrevented()
{
return m_PreventAbort != 0;
}
typedef StateHolder<Thread::IncPreventAbort, Thread::DecPreventAbort> ThreadPreventAbortHolder;
// The ThreadStore manages a list of all the threads in the system. I
// can't figure out how to expand the ThreadList template type without
// making m_Link public.
SLink m_Link;
// For N/Direct calls with the "setLastError" bit, this field stores
// the errorcode from that call.
DWORD m_dwLastError;
#ifdef FEATURE_INTERPRETER
// When we're interpreting IL stubs for N/Direct calls with the "setLastError" bit,
// the interpretation will trash the last error before we get to the call to "SetLastError".
// Therefore, we record it here immediately after the calli, and treat "SetLastError" as an
// intrinsic that transfers the value stored here into the field above.
DWORD m_dwLastErrorInterp;
#endif
// Debugger per-thread flag for enabling notification on "manual"
// method calls, for stepping logic
void IncrementTraceCallCount();
void DecrementTraceCallCount();
FORCEINLINE int IsTraceCall()
{
LIMITED_METHOD_CONTRACT;
return m_TraceCallCount;
}
// Functions to get culture information for thread.
int GetParentCultureName(__out_ecount(length) LPWSTR szBuffer, int length, BOOL bUICulture);
int GetCultureName(__out_ecount(length) LPWSTR szBuffer, int length, BOOL bUICulture);
LCID GetCultureId(BOOL bUICulture);
OBJECTREF GetCulture(BOOL bUICulture);
// Release user cultures that can't survive appdomain unload
// Functions to set the culture on the thread.
void SetCultureId(LCID lcid, BOOL bUICulture);
void SetCulture(OBJECTREF *CultureObj, BOOL bUICulture);
private:
// Used by the culture accesors.
ARG_SLOT CallPropertyGet(BinderMethodID id, OBJECTREF pObject);
ARG_SLOT CallPropertySet(BinderMethodID id, OBJECTREF pObject, OBJECTREF pValue);
#if defined(FEATURE_HIJACK) && !defined(PLATFORM_UNIX)
// Used in suspension code to redirect a thread at a HandledJITCase
BOOL RedirectThreadAtHandledJITCase(PFN_REDIRECTTARGET pTgt);
BOOL RedirectCurrentThreadAtHandledJITCase(PFN_REDIRECTTARGET pTgt, T_CONTEXT *pCurrentThreadCtx);
// Will Redirect the thread using RedirectThreadAtHandledJITCase if necessary
BOOL CheckForAndDoRedirect(PFN_REDIRECTTARGET pRedirectTarget);
BOOL CheckForAndDoRedirectForDbg();
BOOL CheckForAndDoRedirectForGC();
BOOL CheckForAndDoRedirectForUserSuspend();
// Exception handling must be very aware of redirection, so we provide a helper
// to identifying redirection targets
static BOOL IsAddrOfRedirectFunc(void * pFuncAddr);
#if defined(HAVE_GCCOVER) && defined(USE_REDIRECT_FOR_GCSTRESS)
public:
BOOL CheckForAndDoRedirectForGCStress (T_CONTEXT *pCurrentThreadCtx);
private:
bool m_fPreemptiveGCDisabledForGCStress;
#endif // HAVE_GCCOVER && USE_REDIRECT_FOR_GCSTRESS
#endif // FEATURE_HIJACK && !PLATFORM_UNIX
public:
#ifndef DACCESS_COMPILE
// These re-calculate the proper value on each call for the currently executing thread. Use GetCachedStackLimit
// and GetCachedStackBase for the cached values on this Thread.
static void * GetStackLowerBound();
static void * GetStackUpperBound();
#endif
enum SetStackLimitScope { fAll, fAllowableOnly };
BOOL SetStackLimits(SetStackLimitScope scope);
// These access the stack base and limit values for this thread. (They are cached during InitThread.) The
// "stack base" is the "upper bound", i.e., where the stack starts growing from. (Main's call frame is at the
// upper bound.) The "stack limit" is the "lower bound", i.e., how far the stack can grow down to.
// The "stack sufficient execution limit" is used by EnsureSufficientExecutionStack() to limit how much stack
// should remain to execute the average Framework method.
PTR_VOID GetCachedStackBase() {LIMITED_METHOD_DAC_CONTRACT; return m_CacheStackBase; }
PTR_VOID GetCachedStackLimit() {LIMITED_METHOD_DAC_CONTRACT; return m_CacheStackLimit;}
UINT_PTR GetCachedStackSufficientExecutionLimit() {LIMITED_METHOD_DAC_CONTRACT; return m_CacheStackSufficientExecutionLimit;}
private:
// Access the base and limit of the stack. (I.e. the memory ranges that the thread has reserved for its stack).
//
// Note that the base is at a higher address than the limit, since the stack grows downwards.
//
// Note that we generally access the stack of the thread we are crawling, which is cached in the ScanContext.
PTR_VOID m_CacheStackBase;
PTR_VOID m_CacheStackLimit;
UINT_PTR m_CacheStackSufficientExecutionLimit;
#define HARD_GUARD_REGION_SIZE GetOsPageSize()
private:
//
static HRESULT CLRSetThreadStackGuarantee(SetThreadStackGuaranteeScope fScope = STSGuarantee_OnlyIfEnabled);
// try to turn a page into a guard page
static BOOL MarkPageAsGuard(UINT_PTR uGuardPageBase);
// scan a region for a guard page
static BOOL DoesRegionContainGuardPage(UINT_PTR uLowAddress, UINT_PTR uHighAddress);
// Every stack has a single reserved page at its limit that we call the 'hard guard page'. This page is never
// committed, and access to it after a stack overflow will terminate the thread.
#define HARD_GUARD_REGION_SIZE GetOsPageSize()
#define SIZEOF_DEFAULT_STACK_GUARANTEE 1 * GetOsPageSize()
public:
// This will return the last stack address that one could write to before a stack overflow.
static UINT_PTR GetLastNormalStackAddress(UINT_PTR stackBase);
UINT_PTR GetLastNormalStackAddress();
UINT_PTR GetLastAllowableStackAddress()
{
return m_LastAllowableStackAddress;
}
UINT_PTR GetProbeLimit()
{
return m_ProbeLimit;
}
void ResetStackLimits()
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
SO_TOLERANT;
MODE_ANY;
}
CONTRACTL_END;
if (!IsSetThreadStackGuaranteeInUse())
{
return;
}
SetStackLimits(fAllowableOnly);
}
BOOL IsSPBeyondLimit();
INDEBUG(static void DebugLogStackMBIs());
#if defined(_DEBUG_IMPL) && !defined(DACCESS_COMPILE)
// Verify that the cached stack base is for the current thread.
BOOL HasRightCacheStackBase()
{
WRAPPER_NO_CONTRACT;
return m_CacheStackBase == GetStackUpperBound();
}
#endif
public:
static BOOL UniqueStack(void* startLoc = 0);
BOOL IsAddressInStack (PTR_VOID addr) const
{
LIMITED_METHOD_DAC_CONTRACT;
_ASSERTE(m_CacheStackBase != NULL);
_ASSERTE(m_CacheStackLimit != NULL);
_ASSERTE(m_CacheStackLimit < m_CacheStackBase);
return m_CacheStackLimit < addr && addr <= m_CacheStackBase;
}
static BOOL IsAddressInCurrentStack (PTR_VOID addr)
{
LIMITED_METHOD_DAC_CONTRACT;
Thread* currentThread = GetThread();
if (currentThread == NULL)
{
return FALSE;
}
PTR_VOID sp = dac_cast<PTR_VOID>(GetCurrentSP());
_ASSERTE(currentThread->m_CacheStackBase != NULL);
_ASSERTE(sp < currentThread->m_CacheStackBase);
return sp < addr && addr <= currentThread->m_CacheStackBase;
}
// DetermineIfGuardPagePresent returns TRUE if the thread's stack contains a proper guard page. This function
// makes a physical check of the stack, rather than relying on whether or not the CLR is currently processing a
// stack overflow exception.
BOOL DetermineIfGuardPagePresent();
#ifdef FEATURE_STACK_PROBE
// CanResetStackTo will return TRUE if the given stack pointer is far enough away from the guard page to proper
// restore the guard page with RestoreGuardPage.
BOOL CanResetStackTo(LPCVOID stackPointer);
// IsStackSpaceAvailable will return true if there are the given number of stack pages available on the stack.
BOOL IsStackSpaceAvailable(float numPages);
#endif
// Returns the amount of stack available after an SO but before the OS rips the process.
static UINT_PTR GetStackGuarantee();
// RestoreGuardPage will replace the guard page on this thread's stack. The assumption is that it was removed
// by the OS due to a stack overflow exception. This function requires that you know that you have enough stack
// space to restore the guard page, so make sure you know what you're doing when you decide to call this.
VOID RestoreGuardPage();
// Commit the thread's entire stack. Note: this works on managed or unmanaged threads, and pLowerBoundMemInfo
// is optional.
static BOOL CommitThreadStack(Thread* pThreadOptional);
#if defined(FEATURE_HIJACK) && !defined(PLATFORM_UNIX)
private:
// Redirecting of threads in managed code at suspension
enum RedirectReason {
RedirectReason_GCSuspension,
RedirectReason_DebugSuspension,
RedirectReason_UserSuspension,
#if defined(HAVE_GCCOVER) && defined(USE_REDIRECT_FOR_GCSTRESS) // GCCOVER
RedirectReason_GCStress,
#endif // HAVE_GCCOVER && USE_REDIRECT_FOR_GCSTRESS
};
static void __stdcall RedirectedHandledJITCase(RedirectReason reason);
static void __stdcall RedirectedHandledJITCaseForDbgThreadControl();
static void __stdcall RedirectedHandledJITCaseForGCThreadControl();
static void __stdcall RedirectedHandledJITCaseForUserSuspend();
#if defined(HAVE_GCCOVER) && defined(USE_REDIRECT_FOR_GCSTRESS) // GCCOVER
static void __stdcall Thread::RedirectedHandledJITCaseForGCStress();
#endif // defined(HAVE_GCCOVER) && USE_REDIRECT_FOR_GCSTRESS
friend void CPFH_AdjustContextForThreadSuspensionRace(T_CONTEXT *pContext, Thread *pThread);
#endif // FEATURE_HIJACK && !PLATFORM_UNIX
private:
//-------------------------------------------------------------
// Waiting & Synchronization
//-------------------------------------------------------------
// For suspends. The thread waits on this event. A client sets the event to cause
// the thread to resume.
void WaitSuspendEvents(BOOL fDoWait = TRUE);
BOOL WaitSuspendEventsHelper(void);
// Helpers to ensure that the bits for suspension and the number of active
// traps remain coordinated.
void MarkForSuspension(ULONG bit);
void UnmarkForSuspension(ULONG bit);
void SetupForSuspension(ULONG bit)
{
WRAPPER_NO_CONTRACT;
// CoreCLR does not support user-requested thread suspension
_ASSERTE(!(bit & TS_UserSuspendPending));
if (bit & TS_DebugSuspendPending) {
m_DebugSuspendEvent.Reset();
}
}
void ReleaseFromSuspension(ULONG bit)
{
WRAPPER_NO_CONTRACT;
UnmarkForSuspension(~bit);
//
// If the thread is set free, mark it as not-suspended now
//
ThreadState oldState = m_State;
// CoreCLR does not support user-requested thread suspension
_ASSERTE(!(oldState & TS_UserSuspendPending));
while ((oldState & (TS_UserSuspendPending | TS_DebugSuspendPending)) == 0)
{
// CoreCLR does not support user-requested thread suspension
_ASSERTE(!(oldState & TS_UserSuspendPending));
//
// Construct the destination state we desire - all suspension bits turned off.
//
ThreadState newState = (ThreadState)(oldState & ~(TS_UserSuspendPending |
TS_DebugSuspendPending |
TS_SyncSuspended));
if (FastInterlockCompareExchange((LONG *)&m_State, newState, oldState) == (LONG)oldState)
{
break;
}
//
// The state changed underneath us, refresh it and try again.
//
oldState = m_State;
}
// CoreCLR does not support user-requested thread suspension
_ASSERTE(!(bit & TS_UserSuspendPending));
if (bit & TS_DebugSuspendPending) {
m_DebugSuspendEvent.Set();
}
}
public:
FORCEINLINE void UnhijackThreadNoAlloc()
{
#if defined(FEATURE_HIJACK) && !defined(DACCESS_COMPILE)
if (m_State & TS_Hijacked)
{
*m_ppvHJRetAddrPtr = m_pvHJRetAddr;
FastInterlockAnd((ULONG *) &m_State, ~TS_Hijacked);
}
#endif
}
void UnhijackThread();
// Flags that may be passed to GetSafelyRedirectableThreadContext, to customize
// which checks it should perform. This allows a subset of the context verification
// logic used by HandledJITCase to be shared with other callers, such as profiler
// stackwalking
enum GetSafelyRedirectableThreadContextOptions
{
// Perform the default thread context checks
kDefaultChecks = 0x00000000,
// Compares the thread context's IP against m_LastRedirectIP, and potentially
// updates m_LastRedirectIP, when determining the safeness of the thread's
// context. HandledJITCase will always set this flag.
// This flag is ignored on non-x86 platforms, and also on x86 if the OS supports
// trap frame reporting.
kPerfomLastRedirectIPCheck = 0x00000001,
// Use g_pDebugInterface->IsThreadContextInvalid() to see if breakpoints might
// confuse the stack walker. HandledJITCase will always set this flag.
kCheckDebuggerBreakpoints = 0x00000002,
};
// Helper used by HandledJITCase and others who need an absolutely reliable
// register context.
BOOL GetSafelyRedirectableThreadContext(DWORD dwOptions, T_CONTEXT * pCtx, REGDISPLAY * pRD);
private:
#ifdef FEATURE_HIJACK
void HijackThread(VOID *pvHijackAddr, ExecutionState *esb);
VOID *m_pvHJRetAddr; // original return address (before hijack)
VOID **m_ppvHJRetAddrPtr; // place we bashed a new return address
MethodDesc *m_HijackedFunction; // remember what we hijacked
#ifndef PLATFORM_UNIX
BOOL HandledJITCase(BOOL ForTaskSwitchIn = FALSE);
#ifdef _TARGET_X86_
PCODE m_LastRedirectIP;
ULONG m_SpinCount;
#endif // _TARGET_X86_
#endif // !PLATFORM_UNIX
#endif // FEATURE_HIJACK
DWORD m_Win32FaultAddress;
DWORD m_Win32FaultCode;
// Support for Wait/Notify
BOOL Block(INT32 timeOut, PendingSync *syncInfo);
void Wake(SyncBlock *psb);
DWORD Wait(HANDLE *objs, int cntObjs, INT32 timeOut, PendingSync *syncInfo);
DWORD Wait(CLREvent* pEvent, INT32 timeOut, PendingSync *syncInfo);
// support for Thread.Interrupt() which breaks out of Waits, Sleeps, Joins
LONG m_UserInterrupt;
DWORD IsUserInterrupted()
{
LIMITED_METHOD_CONTRACT;
return m_UserInterrupt;
}
void ResetUserInterrupted()
{
LIMITED_METHOD_CONTRACT;
FastInterlockExchange(&m_UserInterrupt, 0);
}
void HandleThreadInterrupt(BOOL fWaitForADUnload);
public:
static void WINAPI UserInterruptAPC(ULONG_PTR ignore);
#if defined(_DEBUG) && defined(TRACK_SYNC)
// Each thread has a stack that tracks all enter and leave requests
public:
Dbg_TrackSync *m_pTrackSync;
#endif // TRACK_SYNC
private:
#ifdef ENABLE_CONTRACTS_DATA
struct ClrDebugState *m_pClrDebugState; // Pointer to ClrDebugState for quick access
ULONG m_ulEnablePreemptiveGCCount;
#endif // _DEBUG
private:
// For suspends:
CLREvent m_DebugSuspendEvent;
// For Object::Wait, Notify and NotifyAll, we use an Event inside the
// thread and we queue the threads onto the SyncBlock of the object they
// are waiting for.
CLREvent m_EventWait;
WaitEventLink m_WaitEventLink;
WaitEventLink* WaitEventLinkForSyncBlock (SyncBlock *psb)
{
LIMITED_METHOD_CONTRACT;
WaitEventLink *walk = &m_WaitEventLink;
while (walk->m_Next) {
_ASSERTE (walk->m_Next->m_Thread == this);
if ((SyncBlock*)(((DWORD_PTR)walk->m_Next->m_WaitSB) & ~1)== psb) {
break;
}
walk = walk->m_Next;
}
return walk;
}
// Access to thread handle and ThreadId.
HANDLE GetThreadHandle()
{
LIMITED_METHOD_CONTRACT;
#if defined(_DEBUG) && !defined(DACCESS_COMPILE)
{
CounterHolder handleHolder(&m_dwThreadHandleBeingUsed);
HANDLE handle = m_ThreadHandle;
_ASSERTE ( handle == INVALID_HANDLE_VALUE
|| handle == SWITCHOUT_HANDLE_VALUE
|| m_OSThreadId == 0
|| m_OSThreadId == 0xbaadf00d
|| ::MatchThreadHandleToOsId(handle, m_OSThreadId) );
}
#endif
DACCOP_IGNORE(FieldAccess, "Treated as raw address, no marshaling is necessary");
return m_ThreadHandle;
}
void SetThreadHandle(HANDLE h)
{
LIMITED_METHOD_CONTRACT;
#if defined(_DEBUG)
_ASSERTE ( h == INVALID_HANDLE_VALUE
|| h == SWITCHOUT_HANDLE_VALUE
|| m_OSThreadId == 0
|| m_OSThreadId == 0xbaadf00d
|| ::MatchThreadHandleToOsId(h, m_OSThreadId) );
#endif
FastInterlockExchangePointer(&m_ThreadHandle, h);
}
// We maintain a correspondence between this object, the ThreadId and ThreadHandle
// in Win32, and the exposed Thread object.
HANDLE m_ThreadHandle;
// <TODO> It would be nice to remove m_ThreadHandleForClose to simplify Thread.Join,
// but at the moment that isn't possible without extensive work.
// This handle is used by SwitchOut to store the old handle which may need to be closed
// if we are the owner. The handle can't be closed before checking the external count
// which we can't do in SwitchOut since that may require locking or switching threads.</TODO>
HANDLE m_ThreadHandleForClose;
HANDLE m_ThreadHandleForResume;
BOOL m_WeOwnThreadHandle;
DWORD m_OSThreadId;
BOOL CreateNewOSThread(SIZE_T stackSize, LPTHREAD_START_ROUTINE start, void *args);
OBJECTHANDLE m_ExposedObject;
OBJECTHANDLE m_StrongHndToExposedObject;
DWORD m_Priority; // initialized to INVALID_THREAD_PRIORITY, set to actual priority when a
// thread does a busy wait for GC, reset to INVALID_THREAD_PRIORITY after wait is over
friend class NDirect; // Quick access to thread stub creation
#ifdef HAVE_GCCOVER
friend void DoGcStress (PT_CONTEXT regs, MethodDesc *pMD); // Needs to call UnhijackThread
#endif // HAVE_GCCOVER
ULONG m_ExternalRefCount;
ULONG m_UnmanagedRefCount;
LONG m_TraceCallCount;
//-----------------------------------------------------------
// Bytes promoted on this thread since the last GC?
//-----------------------------------------------------------
DWORD m_fPromoted;
public:
void SetHasPromotedBytes ();
DWORD GetHasPromotedBytes ()
{
LIMITED_METHOD_CONTRACT;
return m_fPromoted;
}
private:
//-----------------------------------------------------------
// Last exception to be thrown.
//-----------------------------------------------------------
friend class EEDbgInterfaceImpl;
private:
// Stores the most recently thrown exception. We need to have a handle in case a GC occurs before
// we catch so we don't lose the object. Having a static allows others to catch outside of COM+ w/o leaking
// a handler and allows rethrow outside of COM+ too.
// Differs from m_pThrowable in that it doesn't stack on nested exceptions.
OBJECTHANDLE m_LastThrownObjectHandle; // Unsafe to use directly. Use accessors instead.
// Indicates that the throwable in m_lastThrownObjectHandle should be treated as
// unhandled. This occurs during fatal error and a few other early error conditions
// before EH is fully set up.
BOOL m_ltoIsUnhandled;
friend void DECLSPEC_NORETURN EEPolicy::HandleFatalStackOverflow(EXCEPTION_POINTERS *pExceptionInfo, BOOL fSkipDebugger);
public:
BOOL IsLastThrownObjectNull() { WRAPPER_NO_CONTRACT; return (m_LastThrownObjectHandle == NULL); }
OBJECTREF LastThrownObject()
{
WRAPPER_NO_CONTRACT;
if (m_LastThrownObjectHandle == NULL)
{
return NULL;
}
else
{
// We only have a handle if we have an object to keep in it.
_ASSERTE(ObjectFromHandle(m_LastThrownObjectHandle) != NULL);
return ObjectFromHandle(m_LastThrownObjectHandle);
}
}
OBJECTHANDLE LastThrownObjectHandle()
{
LIMITED_METHOD_DAC_CONTRACT;
return m_LastThrownObjectHandle;
}
void SetLastThrownObject(OBJECTREF throwable, BOOL isUnhandled = FALSE);
void SetSOForLastThrownObject();
OBJECTREF SafeSetLastThrownObject(OBJECTREF throwable);
// Inidcates that the last thrown object is now treated as unhandled
void MarkLastThrownObjectUnhandled()
{
LIMITED_METHOD_CONTRACT;
m_ltoIsUnhandled = TRUE;
}
// TRUE if the throwable in LTO should be treated as unhandled
BOOL IsLastThrownObjectUnhandled()
{
LIMITED_METHOD_DAC_CONTRACT;
return m_ltoIsUnhandled;
}
void SafeUpdateLastThrownObject(void);
OBJECTREF SafeSetThrowables(OBJECTREF pThrowable
DEBUG_ARG(ThreadExceptionState::SetThrowableErrorChecking stecFlags = ThreadExceptionState::STEC_All),
BOOL isUnhandled = FALSE);
bool IsLastThrownObjectStackOverflowException()
{
LIMITED_METHOD_CONTRACT;
CONSISTENCY_CHECK(NULL != g_pPreallocatedStackOverflowException);
return (m_LastThrownObjectHandle == g_pPreallocatedStackOverflowException);
}
void SetKickOffDomainId(ADID ad);
ADID GetKickOffDomainId();
// get the current notification (if any) from this thread
OBJECTHANDLE GetThreadCurrNotification();
// set the current notification on this thread
void SetThreadCurrNotification(OBJECTHANDLE handle);
// clear the current notification (if any) from this thread
void ClearThreadCurrNotification();
private:
void SetLastThrownObjectHandle(OBJECTHANDLE h);
ADID m_pKickOffDomainId;
ThreadExceptionState m_ExceptionState;
//-----------------------------------------------------------
// For stack probing. These are the last allowable addresses that a thread
// can touch. Going beyond is a stack overflow. The ProbeLimit will be
// set based on whether SO probing is enabled. The LastAllowableAddress
// will always represent the true stack limit.
//-----------------------------------------------------------
UINT_PTR m_ProbeLimit;
UINT_PTR m_LastAllowableStackAddress;
private:
// Save the domain when a task is switched out, and restore it when
// the task is switched in.
PTR_AppDomain m_pDomainAtTaskSwitch;
//---------------------------------------------------------------
// m_debuggerFilterContext holds the thread's "filter context" for the
// debugger. This filter context is used by the debugger to seed
// stack walks on the thread.
//---------------------------------------------------------------
PTR_CONTEXT m_debuggerFilterContext;
//---------------------------------------------------------------
// m_profilerFilterContext holds an additional context for the
// case when a (sampling) profiler wishes to hijack the thread
// and do a stack walk on the same thread.
//---------------------------------------------------------------
T_CONTEXT *m_pProfilerFilterContext;
//---------------------------------------------------------------
// m_hijackLock holds a BOOL that is used for mutual exclusion
// between profiler stack walks and thread hijacks (bashing
// return addresses on the stack)
//---------------------------------------------------------------
Volatile<LONG> m_hijackLock;
//---------------------------------------------------------------
// m_debuggerCantStop holds a count of entries into "can't stop"
// areas that the Interop Debugging Services must know about.
//---------------------------------------------------------------
DWORD m_debuggerCantStop;
//---------------------------------------------------------------
// The current custom notification data object (or NULL if none
// pending)
//---------------------------------------------------------------
OBJECTHANDLE m_hCurrNotification;
//---------------------------------------------------------------
// For Interop-Debugging; track if a thread is hijacked.
//---------------------------------------------------------------
BOOL m_fInteropDebuggingHijacked;
//---------------------------------------------------------------
// Bitmask to remember per-thread state useful for the profiler API. See
// COR_PRF_CALLBACKSTATE_* flags in clr\src\inc\ProfilePriv.h for bit values.
//---------------------------------------------------------------
DWORD m_profilerCallbackState;
#if defined(FEATURE_PROFAPI_ATTACH_DETACH) || defined(DATA_PROFAPI_ATTACH_DETACH)
//---------------------------------------------------------------
// m_dwProfilerEvacuationCounter keeps track of how many profiler
// callback calls remain on the stack
//---------------------------------------------------------------
// Why volatile?
// See code:ProfilingAPIUtility::InitializeProfiling#LoadUnloadCallbackSynchronization.
Volatile<DWORD> m_dwProfilerEvacuationCounter;
#endif // defined(FEATURE_PROFAPI_ATTACH_DETACH) || defined(DATA_PROFAPI_ATTACH_DETACH)
private:
Volatile<LONG> m_threadPoolCompletionCount;
static Volatile<LONG> s_threadPoolCompletionCountOverflow; //counts completions for threads that have been destroyed.
public:
static void IncrementThreadPoolCompletionCount()
{
LIMITED_METHOD_CONTRACT;
Thread* pThread = GetThread();
if (pThread)
pThread->m_threadPoolCompletionCount++;
else
FastInterlockIncrement(&s_threadPoolCompletionCountOverflow);
}
static LONG GetTotalThreadPoolCompletionCount();
private:
//-------------------------------------------------------------------------
// Support creation of assemblies in DllMain (see ceemain.cpp)
//-------------------------------------------------------------------------
DomainFile* m_pLoadingFile;
// The ThreadAbort reason (Get/Set/ClearExceptionStateInfo on the managed thread) is
// held here as an OBJECTHANDLE and the ADID of the AppDomain in which it is valid.
// Atomic updates of this state use the Thread's Crst.
OBJECTHANDLE m_AbortReason;
ADID m_AbortReasonDomainID;
void ClearAbortReason(BOOL pNoLock = FALSE);
public:
void SetInteropDebuggingHijacked(BOOL f)
{
LIMITED_METHOD_CONTRACT;
m_fInteropDebuggingHijacked = f;
}
BOOL GetInteropDebuggingHijacked()
{
LIMITED_METHOD_CONTRACT;
return m_fInteropDebuggingHijacked;
}
void SetFilterContext(T_CONTEXT *pContext);
T_CONTEXT *GetFilterContext(void);
void SetProfilerFilterContext(T_CONTEXT *pContext)
{
LIMITED_METHOD_CONTRACT;
m_pProfilerFilterContext = pContext;
}
// Used by the profiler API to find which flags have been set on the Thread object,
// in order to authorize a profiler's call into ICorProfilerInfo(2).
DWORD GetProfilerCallbackFullState()
{
LIMITED_METHOD_CONTRACT;
_ASSERTE(GetThread() == this);
return m_profilerCallbackState;
}
// Used by profiler API to set at once all callback flag bits stored on the Thread object.
// Used to reinstate the previous state that had been modified by a previous call to
// SetProfilerCallbackStateFlags
void SetProfilerCallbackFullState(DWORD dwFullState)
{
LIMITED_METHOD_CONTRACT;
_ASSERTE(GetThread() == this);
m_profilerCallbackState = dwFullState;
}
// Used by profiler API to set individual callback flags on the Thread object.
// Returns the previous state of all flags.
DWORD SetProfilerCallbackStateFlags(DWORD dwFlags)
{
LIMITED_METHOD_CONTRACT;
_ASSERTE(GetThread() == this);
DWORD dwRet = m_profilerCallbackState;
m_profilerCallbackState |= dwFlags;
return dwRet;
}
T_CONTEXT *GetProfilerFilterContext(void)
{
LIMITED_METHOD_CONTRACT;
return m_pProfilerFilterContext;
}
#ifdef FEATURE_PROFAPI_ATTACH_DETACH
FORCEINLINE DWORD GetProfilerEvacuationCounter(void)
{
LIMITED_METHOD_CONTRACT;
return m_dwProfilerEvacuationCounter;
}
FORCEINLINE void IncProfilerEvacuationCounter(void)
{
LIMITED_METHOD_CONTRACT;
m_dwProfilerEvacuationCounter++;
_ASSERTE(m_dwProfilerEvacuationCounter != 0U);
}
FORCEINLINE void DecProfilerEvacuationCounter(void)
{
LIMITED_METHOD_CONTRACT;
_ASSERTE(m_dwProfilerEvacuationCounter != 0U);
m_dwProfilerEvacuationCounter--;
}
#endif // FEATURE_PROFAPI_ATTACH_DETACH
//-------------------------------------------------------------------------
// The hijack lock enforces that a thread on which a profiler is currently
// performing a stack walk cannot be hijacked.
//
// Note that the hijack lock cannot be managed by the host (i.e., this
// cannot be a Crst), because this could lead to a deadlock: YieldTask,
// which is called by the host, may need to hijack, for which it would
// need to take this lock - but since the host needs not be reentrant,
// taking the lock cannot cause a call back into the host.
//-------------------------------------------------------------------------
static BOOL EnterHijackLock(Thread *pThread)
{
LIMITED_METHOD_CONTRACT;
return ::InterlockedCompareExchange(&(pThread->m_hijackLock), TRUE, FALSE) == FALSE;
}
static void LeaveHijackLock(Thread *pThread)
{
LIMITED_METHOD_CONTRACT;
pThread->m_hijackLock = FALSE;
}
typedef ConditionalStateHolder<Thread *, Thread::EnterHijackLock, Thread::LeaveHijackLock> HijackLockHolder;
//-------------------------------------------------------------------------
static bool ThreadsAtUnsafePlaces(void)
{
LIMITED_METHOD_CONTRACT;
return (m_threadsAtUnsafePlaces != (LONG)0);
}
static void IncThreadsAtUnsafePlaces(void)
{
LIMITED_METHOD_CONTRACT;
InterlockedIncrement(&m_threadsAtUnsafePlaces);
}
static void DecThreadsAtUnsafePlaces(void)
{
LIMITED_METHOD_CONTRACT;
InterlockedDecrement(&m_threadsAtUnsafePlaces);
}
void PrepareForEERestart(BOOL SuspendSucceeded)
{
WRAPPER_NO_CONTRACT;
#ifdef FEATURE_HIJACK
// Only unhijack the thread if the suspend succeeded. If it failed,
// the target thread may currently be using the original stack
// location of the return address for something else.
if (SuspendSucceeded)
UnhijackThread();
#endif // FEATURE_HIJACK
ResetThreadState(TS_GCSuspendPending);
}
void SetDebugCantStop(bool fCantStop);
bool GetDebugCantStop(void);
static LPVOID GetStaticFieldAddress(FieldDesc *pFD);
TADDR GetStaticFieldAddrNoCreate(FieldDesc *pFD, PTR_AppDomain pDomain);
void SetLoadingFile(DomainFile *pFile)
{
LIMITED_METHOD_CONTRACT;
CONSISTENCY_CHECK(m_pLoadingFile == NULL);
m_pLoadingFile = pFile;
}
void ClearLoadingFile()
{
LIMITED_METHOD_CONTRACT;
m_pLoadingFile = NULL;
}
DomainFile *GetLoadingFile()
{
LIMITED_METHOD_CONTRACT;
return m_pLoadingFile;
}
private:
static void LoadingFileRelease(Thread *pThread)
{
WRAPPER_NO_CONTRACT;
pThread->ClearLoadingFile();
}
public:
typedef Holder<Thread *, DoNothing, Thread::LoadingFileRelease> LoadingFileHolder;
void InitCultureAccessors();
FieldDesc *managedThreadCurrentCulture;
FieldDesc *managedThreadCurrentUICulture;
private:
// Don't allow a thread to be asynchronously stopped or interrupted (e.g. because
// it is performing a <clinit>)
int m_PreventAsync;
int m_PreventAbort;
int m_nNestedMarshalingExceptions;
BOOL IsMarshalingException()
{
LIMITED_METHOD_CONTRACT;
return (m_nNestedMarshalingExceptions != 0);
}
int StartedMarshalingException()
{
LIMITED_METHOD_CONTRACT;
return m_nNestedMarshalingExceptions++;
}
void FinishedMarshalingException()
{
LIMITED_METHOD_CONTRACT;
_ASSERTE(m_nNestedMarshalingExceptions > 0);
m_nNestedMarshalingExceptions--;
}
static LONG m_DebugWillSyncCount;
// IP cache used by QueueCleanupIP.
#define CLEANUP_IPS_PER_CHUNK 4
struct CleanupIPs {
IUnknown *m_Slots[CLEANUP_IPS_PER_CHUNK];
CleanupIPs *m_Next;
CleanupIPs() {LIMITED_METHOD_CONTRACT; memset(this, 0, sizeof(*this)); }
};
CleanupIPs m_CleanupIPs;
#define BEGIN_FORBID_TYPELOAD() _ASSERTE_IMPL((GetThreadNULLOk() == 0) || ++GetThreadNULLOk()->m_ulForbidTypeLoad)
#define END_FORBID_TYPELOAD() _ASSERTE_IMPL((GetThreadNULLOk() == 0) || GetThreadNULLOk()->m_ulForbidTypeLoad--)
#define TRIGGERS_TYPELOAD() _ASSERTE_IMPL((GetThreadNULLOk() == 0) || !GetThreadNULLOk()->m_ulForbidTypeLoad)
#ifdef _DEBUG
public:
DWORD m_GCOnTransitionsOK;
ULONG m_ulForbidTypeLoad;
/****************************************************************************/
/* The code below an attempt to catch people who don't protect GC pointers that
they should be protecting. Basically, OBJECTREF's constructor, adds the slot
to a table. When we protect a slot, we remove it from the table. When GC
could happen, all entries in the table are marked as bad. When access to
an OBJECTREF happens (the -> operator) we assert the slot is not bad. To make
this fast, the table is not perfect (there can be collisions), but this should
not cause false positives, but it may allow errors to go undetected */
#ifdef _WIN64
#define OBJREF_HASH_SHIFT_AMOUNT 3
#else // _WIN64
#define OBJREF_HASH_SHIFT_AMOUNT 2
#endif // _WIN64
// For debugging, you may want to make this number very large, (8K)
// should basically insure that no collisions happen
#define OBJREF_TABSIZE 256
DWORD_PTR dangerousObjRefs[OBJREF_TABSIZE]; // Really objectRefs with lower bit stolen
// m_allObjRefEntriesBad is TRUE iff dangerousObjRefs are all marked as GC happened
// It's purely a perf optimization for debug builds that'll help for the cases where we make 2 successive calls
// to Thread::TriggersGC. In that case, the entire array doesn't need to be walked and marked, since we just did
// that.
BOOL m_allObjRefEntriesBad;
static DWORD_PTR OBJREF_HASH;
// Remembers that this object ref pointer is 'alive' and unprotected (Bad if GC happens)
static void ObjectRefNew(const OBJECTREF* ref) {
WRAPPER_NO_CONTRACT;
Thread * curThread = GetThreadNULLOk();
if (curThread == 0) return;
curThread->dangerousObjRefs[((size_t)ref >> OBJREF_HASH_SHIFT_AMOUNT) % OBJREF_HASH] = (size_t)ref;
curThread->m_allObjRefEntriesBad = FALSE;
}
static void ObjectRefAssign(const OBJECTREF* ref) {
WRAPPER_NO_CONTRACT;
Thread * curThread = GetThreadNULLOk();
if (curThread == 0) return;
curThread->m_allObjRefEntriesBad = FALSE;
DWORD_PTR* slot = &curThread->dangerousObjRefs[((DWORD_PTR) ref >> OBJREF_HASH_SHIFT_AMOUNT) % OBJREF_HASH];
if ((*slot & ~3) == (size_t) ref)
*slot = *slot & ~1; // Don't care about GC's that have happened
}
// If an object is protected, it can be removed from the 'dangerous table'
static void ObjectRefProtected(const OBJECTREF* ref) {
#ifdef USE_CHECKED_OBJECTREFS
WRAPPER_NO_CONTRACT;
_ASSERTE(IsObjRefValid(ref));
Thread * curThread = GetThreadNULLOk();
if (curThread == 0) return;
curThread->m_allObjRefEntriesBad = FALSE;
DWORD_PTR* slot = &curThread->dangerousObjRefs[((DWORD_PTR) ref >> OBJREF_HASH_SHIFT_AMOUNT) % OBJREF_HASH];
if ((*slot & ~3) == (DWORD_PTR) ref)
*slot = (size_t) ref | 2; // mark has being protected
#else
LIMITED_METHOD_CONTRACT;
#endif
}
static bool IsObjRefValid(const OBJECTREF* ref) {
WRAPPER_NO_CONTRACT;
Thread * curThread = GetThreadNULLOk();
if (curThread == 0) return(true);
// If the object ref is NULL, we'll let it pass.
if (*((DWORD_PTR*) ref) == 0)
return(true);
DWORD_PTR val = curThread->dangerousObjRefs[((DWORD_PTR) ref >> OBJREF_HASH_SHIFT_AMOUNT) % OBJREF_HASH];
// if not in the table, or not the case that it was unprotected and GC happened, return true.
if((val & ~3) != (size_t) ref || (val & 3) != 1)
return(true);
// If the pointer lives in the GC heap, than it is protected, and thus valid.
if (dac_cast<TADDR>(g_lowest_address) <= val && val < dac_cast<TADDR>(g_highest_address))
return(true);
return(false);
}
// Clears the table. Useful to do when crossing the managed-code - EE boundary
// as you ususally only care about OBJECTREFS that have been created after that
static void STDCALL ObjectRefFlush(Thread* thread);
#ifdef ENABLE_CONTRACTS_IMPL
// Marks all Objrefs in the table as bad (since they are unprotected)
static void TriggersGC(Thread* thread) {
WRAPPER_NO_CONTRACT;
if ((GCViolation|BadDebugState) & (UINT_PTR)(GetViolationMask()))
{
return;
}
if (!thread->m_allObjRefEntriesBad)
{
thread->m_allObjRefEntriesBad = TRUE;
for(unsigned i = 0; i < OBJREF_TABSIZE; i++)
thread->dangerousObjRefs[i] |= 1; // mark all slots as GC happened
}
}
#endif // ENABLE_CONTRACTS_IMPL
#endif // _DEBUG
private:
PTR_CONTEXT m_pSavedRedirectContext;
BOOL IsContextSafeToRedirect(T_CONTEXT* pContext);
public:
PT_CONTEXT GetSavedRedirectContext()
{
LIMITED_METHOD_CONTRACT;
return (m_pSavedRedirectContext);
}
#ifndef DACCESS_COMPILE
void SetSavedRedirectContext(PT_CONTEXT pCtx)
{
LIMITED_METHOD_CONTRACT;
m_pSavedRedirectContext = pCtx;
}
#endif
void EnsurePreallocatedContext();
// m_pThreadLocalBLock points to the ThreadLocalBlock that corresponds to the
// AppDomain that the Thread is currently in
// m_pTLBTable points to the this Thread's table of ThreadLocalBlocks, indexed by
// ADIndex. It's important to note that ADIndexes get recycled when AppDomains are
// torn down. m_TLBTableSize holds to current size the size of this Thread's TLB table.
// See "ThreadStatics.h" for more information.
PTR_ThreadLocalBlock m_pThreadLocalBlock;
PTR_PTR_ThreadLocalBlock m_pTLBTable;
SIZE_T m_TLBTableSize;
// This getter is used by SOS; if m_pThreadLocalBlock is NULL, it's
// important that we look in the TLB table as well
/*
PTR_ThreadLocalBlock GetThreadLocalBlock()
{
// If the current TLB pointer is NULL, search the TLB table
if (m_pThreadLocalBlock != NULL)
return m_pThreadLocalBlock;
ADIndex index = GetDomain()->GetIndex();
// Check to see if we have a ThreadLocalBlock for the the current AppDomain,
if (index.m_dwIndex < m_TLBTableSize)
{
// Update the current ThreadLocalBlock pointer,
// but only on non-DAC builds
#ifndef DACCESS_COMPILE
m_pThreadLocalBlock = m_pTLBTable[index.m_dwIndex];
#endif
return m_pTLBTable[index.m_dwIndex];
}
return NULL;
}
*/
protected:
// Called during AD teardown to clean up any references this
// thread may have to the AppDomain
void DeleteThreadStaticData(AppDomain *pDomain);
private:
// Called during Thread death to clean up all structures
// associated with thread statics
void DeleteThreadStaticData();
#ifdef _DEBUG
private:
// When we create an object, or create an OBJECTREF, or create an Interior Pointer, or enter EE from managed
// code, we will set this flag.
// Inside GCHeapUtilities::StressHeap, we only do GC if this flag is TRUE. Then we reset it to zero.
BOOL m_fStressHeapCount;
public:
void EnableStressHeap()
{
LIMITED_METHOD_CONTRACT;
m_fStressHeapCount = TRUE;
}
void DisableStressHeap()
{
LIMITED_METHOD_CONTRACT;
m_fStressHeapCount = FALSE;
}
BOOL StressHeapIsEnabled()
{
LIMITED_METHOD_CONTRACT;
return m_fStressHeapCount;
}
size_t *m_pCleanedStackBase;
#endif
private:
PVOID m_pFiberData;
TASKID m_TaskId;
CONNID m_dwConnectionId;
public:
void SetupFiberData();
#ifdef _DEBUG
public:
void AddFiberInfo(DWORD type);
enum {
ThreadTrackInfo_Lifetime=0x1, // creation, destruction, ref-count
ThreadTrackInfo_Schedule=0x2, // switch in/out
ThreadTrackInfo_UM_M=0x4, // Unmanaged <-> managed transtion
ThreadTrackInfo_Abort=0x8, // Thread abort
ThreadTrackInfo_Affinity=0x10, // Thread's affinity
ThreadTrackInfo_GCMode=0x20,
ThreadTrackInfo_Escalation=0x40,// escalation point
ThreadTrackInfo_SO=0x80,
ThreadTrackInfo_Max=8
};
private:
static int MaxThreadRecord;
static int MaxStackDepth;
static const int MaxThreadTrackInfo;
struct FiberSwitchInfo
{
unsigned __int64 timeStamp;
DWORD threadID;
size_t callStack[1];
};
FiberSwitchInfo *m_pFiberInfo[ThreadTrackInfo_Max];
DWORD m_FiberInfoIndex[ThreadTrackInfo_Max];
#endif
#ifdef DACCESS_COMPILE
public:
void EnumMemoryRegions(CLRDataEnumMemoryFlags flags);
void EnumMemoryRegionsWorker(CLRDataEnumMemoryFlags flags);
#endif
private:
// Head of a linked list of opaque records that record if and how the thread is currently preparing a
// graph of methods for CER usage. This is used to determine if a re-entrant preparation request should
// complete immediately as a no-op (because it would lead to an infinite recursion) or should proceed
// recursively.
MethodCallGraphPreparer * m_pCerPreparationState;
public:
MethodCallGraphPreparer * GetCerPreparationState()
{
LIMITED_METHOD_CONTRACT;
return m_pCerPreparationState;
}
void SetCerPreparationState(MethodCallGraphPreparer * pCerPreparationState)
{
LIMITED_METHOD_CONTRACT;
m_pCerPreparationState = pCerPreparationState;
}
// Is the current thread currently executing within a constrained execution region?
static BOOL IsExecutingWithinCer();
// Determine whether the method at the given frame in the thread's execution stack is executing within a CER.
BOOL IsWithinCer(CrawlFrame *pCf);
private:
// used to pad stack on thread creation to avoid aliasing penalty in P4 HyperThread scenarios
static DWORD WINAPI intermediateThreadProc(PVOID arg);
static int m_offset_counter;
static const int offset_multiplier = 128;
typedef struct {
LPTHREAD_START_ROUTINE lpThreadFunction;
PVOID lpArg;
} intermediateThreadParam;
#ifdef _DEBUG
// when the thread is doing a stressing GC, some Crst violation could be ignored, by a non-elegant solution.
private:
BOOL m_bGCStressing; // the flag to indicate if the thread is doing a stressing GC
BOOL m_bUniqueStacking; // the flag to indicate if the thread is doing a UniqueStack
public:
BOOL GetGCStressing ()
{
return m_bGCStressing;
}
BOOL GetUniqueStacking ()
{
return m_bUniqueStacking;
}
#endif
private:
//-----------------------------------------------------------------------------
// AVInRuntimeImplOkay : its okay to have an AV in Runtime implemetation while
// this holder is in effect.
//
// {
// AVInRuntimeImplOkayHolder foo();
// } // make AV's in the Runtime illegal on out of scope.
//-----------------------------------------------------------------------------
DWORD m_dwAVInRuntimeImplOkayCount;
static void AVInRuntimeImplOkayAcquire(Thread * pThread)
{
LIMITED_METHOD_CONTRACT;
if (pThread)
{
_ASSERTE(pThread->m_dwAVInRuntimeImplOkayCount != (DWORD)-1);
pThread->m_dwAVInRuntimeImplOkayCount++;
}
}
static void AVInRuntimeImplOkayRelease(Thread * pThread)
{
LIMITED_METHOD_CONTRACT;
if (pThread)
{
_ASSERTE(pThread->m_dwAVInRuntimeImplOkayCount > 0);
pThread->m_dwAVInRuntimeImplOkayCount--;
}
}
public:
static BOOL AVInRuntimeImplOkay(void)
{
LIMITED_METHOD_CONTRACT;
Thread * pThread = GetThreadNULLOk();
if (pThread)
{
return (pThread->m_dwAVInRuntimeImplOkayCount > 0);
}
else
{
return FALSE;
}
}
class AVInRuntimeImplOkayHolder
{
Thread * const m_pThread;
public:
AVInRuntimeImplOkayHolder() :
m_pThread(GetThread())
{
LIMITED_METHOD_CONTRACT;
AVInRuntimeImplOkayAcquire(m_pThread);
}
AVInRuntimeImplOkayHolder(Thread * pThread) :
m_pThread(pThread)
{
LIMITED_METHOD_CONTRACT;
AVInRuntimeImplOkayAcquire(m_pThread);
}
~AVInRuntimeImplOkayHolder()
{
LIMITED_METHOD_CONTRACT;
AVInRuntimeImplOkayRelease(m_pThread);
}
};
#ifdef _DEBUG
private:
DWORD m_dwUnbreakableLockCount;
public:
void IncUnbreakableLockCount()
{
LIMITED_METHOD_CONTRACT;
_ASSERTE (m_dwUnbreakableLockCount != (DWORD)-1);
m_dwUnbreakableLockCount ++;
}
void DecUnbreakableLockCount()
{
LIMITED_METHOD_CONTRACT;
_ASSERTE (m_dwUnbreakableLockCount > 0);
m_dwUnbreakableLockCount --;
}
BOOL HasUnbreakableLock() const
{
LIMITED_METHOD_CONTRACT;
return m_dwUnbreakableLockCount != 0;
}
DWORD GetUnbreakableLockCount() const
{
LIMITED_METHOD_CONTRACT;
return m_dwUnbreakableLockCount;
}
#endif // _DEBUG
#ifdef _DEBUG
private:
friend class FCallTransitionState;
friend class PermitHelperMethodFrameState;
friend class CompletedFCallTransitionState;
HelperMethodFrameCallerList *m_pHelperMethodFrameCallerList;
#endif // _DEBUG
private:
LONG m_dwHostTaskRefCount;
private:
// If HasStarted fails, we cache the exception here, and rethrow on the thread which
// calls Thread.Start.
Exception* m_pExceptionDuringStartup;
public:
void HandleThreadStartupFailure();
#ifdef HAVE_GCCOVER
private:
BYTE* m_pbDestCode;
BYTE* m_pbSrcCode;
#if defined(GCCOVER_TOLERATE_SPURIOUS_AV)
LPVOID m_pLastAVAddress;
#endif // defined(GCCOVER_TOLERATE_SPURIOUS_AV)
public:
void CommitGCStressInstructionUpdate();
void PostGCStressInstructionUpdate(BYTE* pbDestCode, BYTE* pbSrcCode)
{
LIMITED_METHOD_CONTRACT;
PRECONDITION(!HasPendingGCStressInstructionUpdate());
m_pbDestCode = pbDestCode;
m_pbSrcCode = pbSrcCode;
}
bool HasPendingGCStressInstructionUpdate()
{
LIMITED_METHOD_CONTRACT;
CONSISTENCY_CHECK((NULL == m_pbDestCode) == (NULL == m_pbSrcCode));
return m_pbDestCode != NULL;
}
void ClearGCStressInstructionUpdate()
{
LIMITED_METHOD_CONTRACT;
PRECONDITION(HasPendingGCStressInstructionUpdate());
m_pbDestCode = NULL;
m_pbSrcCode = NULL;
}
#if defined(GCCOVER_TOLERATE_SPURIOUS_AV)
void SetLastAVAddress(LPVOID address)
{
LIMITED_METHOD_CONTRACT;
m_pLastAVAddress = address;
}
LPVOID GetLastAVAddress()
{
LIMITED_METHOD_CONTRACT;
return m_pLastAVAddress;
}
#endif // defined(GCCOVER_TOLERATE_SPURIOUS_AV)
#endif // HAVE_GCCOVER
#if defined(_DEBUG) && defined(FEATURE_STACK_PROBE)
class ::BaseStackGuard;
private:
// This field is used for debugging purposes to allow easy access to the stack guard
// chain and also in SO-tolerance checking to quickly determine if a guard is in place.
BaseStackGuard *m_pCurrentStackGuard;
public:
BaseStackGuard *GetCurrentStackGuard()
{
LIMITED_METHOD_CONTRACT;
return m_pCurrentStackGuard;
}
void SetCurrentStackGuard(BaseStackGuard *pGuard)
{
LIMITED_METHOD_CONTRACT;
m_pCurrentStackGuard = pGuard;
}
#endif
private:
BOOL m_fCompletionPortDrained;
public:
void MarkCompletionPortDrained()
{
LIMITED_METHOD_CONTRACT;
FastInterlockExchange ((LONG*)&m_fCompletionPortDrained, TRUE);
}
void UnmarkCompletionPortDrained()
{
LIMITED_METHOD_CONTRACT;
FastInterlockExchange ((LONG*)&m_fCompletionPortDrained, FALSE);
}
BOOL IsCompletionPortDrained()
{
LIMITED_METHOD_CONTRACT;
return m_fCompletionPortDrained;
}
// --------------------------------
// Store the maxReservedStackSize
// This is passed in from managed code in the thread constructor
// ---------------------------------
private:
SIZE_T m_RequestedStackSize;
public:
// Get the MaxStackSize
SIZE_T RequestedThreadStackSize()
{
LIMITED_METHOD_CONTRACT;
return (m_RequestedStackSize);
}
// Set the MaxStackSize
void RequestedThreadStackSize(SIZE_T requestedStackSize)
{
LIMITED_METHOD_CONTRACT;
m_RequestedStackSize = requestedStackSize;
}
static BOOL CheckThreadStackSize(SIZE_T *SizeToCommitOrReserve,
BOOL isSizeToReserve // When TRUE, the previous argument is the stack size to reserve.
// Otherwise, it is the size to commit.
);
static BOOL GetProcessDefaultStackSize(SIZE_T* reserveSize, SIZE_T* commitSize);
private:
// Although this is a pointer, it is used as a flag to indicate the current context is unsafe
// to inspect. When NULL the context is safe to use, otherwise it points to the active patch skipper
// and the context is unsafe to use. When running a patch skipper we could be in one of two
// debug-only situations that the context inspecting/modifying code isn't generally prepared
// to deal with.
// a) We have set the IP to point somewhere in the patch skip table but have not yet run the
// instruction
// b) We executed the instruction in the patch skip table and now the IP could be anywhere
// The debugger may need to fix up the IP to compensate for the instruction being run
// from a different address.
VolatilePtr<DebuggerPatchSkip> m_debuggerActivePatchSkipper;
public:
VOID BeginDebuggerPatchSkip(DebuggerPatchSkip* patchSkipper)
{
LIMITED_METHOD_CONTRACT;
_ASSERTE(!m_debuggerActivePatchSkipper.Load());
FastInterlockExchangePointer(m_debuggerActivePatchSkipper.GetPointer(), patchSkipper);
_ASSERTE(m_debuggerActivePatchSkipper.Load());
}
VOID EndDebuggerPatchSkip()
{
LIMITED_METHOD_CONTRACT;
_ASSERTE(m_debuggerActivePatchSkipper.Load());
FastInterlockExchangePointer(m_debuggerActivePatchSkipper.GetPointer(), NULL);
_ASSERTE(!m_debuggerActivePatchSkipper.Load());
}
private:
static BOOL EnterWorkingOnThreadContext(Thread *pThread)
{
LIMITED_METHOD_CONTRACT;
if(pThread->m_debuggerActivePatchSkipper.Load() != NULL)
{
return FALSE;
}
return TRUE;
}
static void LeaveWorkingOnThreadContext(Thread *pThread)
{
LIMITED_METHOD_CONTRACT;
}
typedef ConditionalStateHolder<Thread *, Thread::EnterWorkingOnThreadContext, Thread::LeaveWorkingOnThreadContext> WorkingOnThreadContextHolder;
public:
void PrepareThreadForSOWork()
{
WRAPPER_NO_CONTRACT;
#ifdef FEATURE_HIJACK
UnhijackThread();
#endif // FEATURE_HIJACK
ResetThrowControlForThread();
// Since this Thread has taken an SO, there may be state left-over after we
// short-circuited exception or other error handling, and so we don't want
// to risk recycling it.
SetThreadStateNC(TSNC_CannotRecycle);
}
void SetSOWorkNeeded()
{
SetThreadStateNC(TSNC_SOWorkNeeded);
}
BOOL IsSOWorkNeeded()
{
return HasThreadStateNC(TSNC_SOWorkNeeded);
}
void FinishSOWork();
void ClearExceptionStateAfterSO(void* pStackFrameSP)
{
WRAPPER_NO_CONTRACT;
// Clear any stale exception state.
m_ExceptionState.ClearExceptionStateAfterSO(pStackFrameSP);
}
private:
BOOL m_fAllowProfilerCallbacks;
public:
//
// These two methods are for profiler support. The profiler clears the allowed
// value once it has delivered a ThreadDestroyed callback, so that it does not
// deliver any notifications to the profiler afterwards which reference this
// thread. Callbacks on this thread which do not reference this thread are
// allowable.
//
BOOL ProfilerCallbacksAllowed(void)
{
return m_fAllowProfilerCallbacks;
}
void SetProfilerCallbacksAllowed(BOOL fValue)
{
m_fAllowProfilerCallbacks = fValue;
}
private:
//
//This context is used for optimizations on I/O thread pool thread. In case the
//overlapped structure is from a different appdomain, it is stored in this structure
//to be processed later correctly by entering the right domain.
PVOID m_pIOCompletionContext;
BOOL AllocateIOCompletionContext();
VOID FreeIOCompletionContext();
public:
inline PVOID GetIOCompletionContext()
{
return m_pIOCompletionContext;
}
private:
// Inside a host, we don't own a thread handle, and we avoid DuplicateHandle call.
// If a thread is dying after we obtain the thread handle, our SuspendThread may fail
// because the handle may be closed and reused for a completely different type of handle.
// To solve this problem, we have a counter m_dwThreadHandleBeingUsed. Before we grab
// the thread handle, we increment the counter. Before we return a thread back to SQL
// in Reset and ExitTask, we wait until the counter drops to 0.
Volatile<LONG> m_dwThreadHandleBeingUsed;
private:
static BOOL s_fCleanFinalizedThread;
public:
#ifndef DACCESS_COMPILE
static void SetCleanupNeededForFinalizedThread()
{
LIMITED_METHOD_CONTRACT;
_ASSERTE (IsFinalizerThread());
s_fCleanFinalizedThread = TRUE;
}
#endif //!DACCESS_COMPILE
static BOOL CleanupNeededForFinalizedThread()
{
LIMITED_METHOD_CONTRACT;
return s_fCleanFinalizedThread;
}
private:
// When we create throwable for an exception, we need to run managed code.
// If the same type of exception is thrown while creating managed object, like InvalidProgramException,
// we may be in an infinite recursive case.
Exception *m_pCreatingThrowableForException;
friend OBJECTREF CLRException::GetThrowable();
#ifdef _DEBUG
private:
int m_dwDisableAbortCheckCount; // Disable check before calling managed code.
// !!! Use this very carefully. If managed code runs user code
// !!! or blocks on locks, the thread may not be aborted.
public:
static void DisableAbortCheck()
{
WRAPPER_NO_CONTRACT;
Thread *pThread = GetThread();
FastInterlockIncrement((LONG*)&pThread->m_dwDisableAbortCheckCount);
}
static void EnableAbortCheck()
{
WRAPPER_NO_CONTRACT;
Thread *pThread = GetThread();
_ASSERTE (pThread->m_dwDisableAbortCheckCount > 0);
FastInterlockDecrement((LONG*)&pThread->m_dwDisableAbortCheckCount);
}
BOOL IsAbortCheckDisabled()
{
return m_dwDisableAbortCheckCount > 0;
}
typedef StateHolder<Thread::DisableAbortCheck, Thread::EnableAbortCheck> DisableAbortCheckHolder;
#endif
private:
// At the end of a catch, we may raise ThreadAbortException. If catch clause set IP to resume in the
// corresponding try block, our exception system will execute the same catch clause again and again.
// So we save reference to the clause post which TA was reraised, which is used in ExceptionTracker::ProcessManagedCallFrame
// to make ThreadAbort proceed ahead instead of going in a loop.
// This problem only happens on Win64 due to JIT64. The common scenario is VB's "On error resume next"
#ifdef WIN64EXCEPTIONS
DWORD m_dwIndexClauseForCatch;
StackFrame m_sfEstablisherOfActualHandlerFrame;
#endif // WIN64EXCEPTIONS
public:
// Holds per-thread information the debugger uses to expose locking information
// See ThreadDebugBlockingInfo.h for more details
ThreadDebugBlockingInfo DebugBlockingInfo;
#ifdef FEATURE_APPDOMAIN_RESOURCE_MONITORING
// For the purposes of tracking resource usage we implement a simple cpu resource usage counter on each
// thread. Every time QueryThreadProcessorUsage() is invoked it returns the amount of cpu time (a
// combination of user and kernel mode time) used since the last call to QueryThreadProcessorUsage(). The
// result is in 100 nanosecond units.
ULONGLONG QueryThreadProcessorUsage();
private:
// The amount of processor time (both user and kernel) in 100ns units used by this thread at the time of
// the last call to QueryThreadProcessorUsage().
ULONGLONG m_ullProcessorUsageBaseline;
#endif // FEATURE_APPDOMAIN_RESOURCE_MONITORING
// Disables pumping and thread join in RCW creation
bool m_fDisableComObjectEagerCleanup;
// See ThreadStore::TriggerGCForDeadThreadsIfNecessary()
bool m_fHasDeadThreadBeenConsideredForGCTrigger;
private:
CLRRandom m_random;
public:
CLRRandom* GetRandom() {return &m_random;}
#ifdef FEATURE_COMINTEROP
private:
// Cookie returned from CoRegisterInitializeSpy
ULARGE_INTEGER m_uliInitializeSpyCookie;
// True if m_uliInitializeSpyCookie is valid
bool m_fInitializeSpyRegistered;
// The last STA COM context we saw - used to speed up RCW creation
LPVOID m_pLastSTACtxCookie;
public:
inline void RevokeApartmentSpy();
inline LPVOID GetLastSTACtxCookie(BOOL *pfNAContext);
inline void SetLastSTACtxCookie(LPVOID pCtxCookie, BOOL fNAContext);
#endif // FEATURE_COMINTEROP
private:
// This duplicates the ThreadType_GC bit stored in TLS (TlsIdx_ThreadType). It exists
// so that any thread can query whether any other thread is a "GC Special" thread.
// (In contrast, ::IsGCSpecialThread() only gives this info about the currently
// executing thread.) The Profiling API uses this to determine whether it should
// "hide" the thread from profilers. GC Special threads (in particular the bgc
// thread) need to be hidden from profilers because the bgc thread creation path
// occurs while the EE is suspended, and while the thread that's suspending the
// runtime is waiting for the bgc thread to signal an event. The bgc thread cannot
// switch to preemptive mode and call into a profiler at this time, or else a
// deadlock will result when toggling back to cooperative mode (bgc thread toggling
// to coop will block due to the suspension, and the thread suspending the runtime
// continues to block waiting for the bgc thread to signal its creation events).
// Furthermore, profilers have no need to be aware of GC special threads anyway,
// since managed code never runs on them.
bool m_fGCSpecial;
public:
// Profiling API uses this to determine whether it should hide this thread from the
// profiler.
bool IsGCSpecial();
// GC calls this when creating special threads that also happen to have an EE Thread
// object associated with them (e.g., the bgc thread).
void SetGCSpecial(bool fGCSpecial);
private:
WORD m_wCPUGroup;
DWORD_PTR m_pAffinityMask;
public:
void ChooseThreadCPUGroupAffinity();
void ClearThreadCPUGroupAffinity();
private:
// Per thread table used to implement allocation sampling.
AllLoggedTypes * m_pAllLoggedTypes;
public:
AllLoggedTypes * GetAllocationSamplingTable()
{
LIMITED_METHOD_CONTRACT;
return m_pAllLoggedTypes;
}
void SetAllocationSamplingTable(AllLoggedTypes * pAllLoggedTypes)
{
LIMITED_METHOD_CONTRACT;
// Assert if we try to set the m_pAllLoggedTypes to a non NULL value if it is already non-NULL.
// This implies a memory leak.
_ASSERTE(pAllLoggedTypes != NULL ? m_pAllLoggedTypes == NULL : TRUE);
m_pAllLoggedTypes = pAllLoggedTypes;
}
#ifdef FEATURE_PERFTRACING
private:
// The object that contains the list write buffers used by this thread.
Volatile<EventPipeBufferList*> m_pEventPipeBufferList;
// Whether or not the thread is currently writing an event.
Volatile<bool> m_eventWriteInProgress;
// SampleProfiler thread state. This is set on suspension and cleared before restart.
// True if the thread was in cooperative mode. False if it was in preemptive when the suspension started.
Volatile<ULONG> m_gcModeOnSuspension;
// The activity ID for the current thread.
// An activity ID of zero means the thread is not executing in the context of an activity.
GUID m_activityId;
public:
EventPipeBufferList* GetEventPipeBufferList()
{
LIMITED_METHOD_CONTRACT;
return m_pEventPipeBufferList;
}
void SetEventPipeBufferList(EventPipeBufferList *pList)
{
LIMITED_METHOD_CONTRACT;
m_pEventPipeBufferList = pList;
}
bool GetEventWriteInProgress() const
{
LIMITED_METHOD_CONTRACT;
return m_eventWriteInProgress;
}
void SetEventWriteInProgress(bool value)
{
LIMITED_METHOD_CONTRACT;
m_eventWriteInProgress = value;
}
bool GetGCModeOnSuspension()
{
LIMITED_METHOD_CONTRACT;
return m_gcModeOnSuspension != 0;
}
void SaveGCModeOnSuspension()
{
LIMITED_METHOD_CONTRACT;
m_gcModeOnSuspension = m_fPreemptiveGCDisabled;
}
void ClearGCModeOnSuspension()
{
m_gcModeOnSuspension = 0;
}
LPCGUID GetActivityId() const
{
LIMITED_METHOD_CONTRACT;
return &m_activityId;
}
void SetActivityId(LPCGUID pActivityId)
{
LIMITED_METHOD_CONTRACT;
_ASSERTE(pActivityId != NULL);
m_activityId = *pActivityId;
}
#endif // FEATURE_PERFTRACING
#ifdef FEATURE_HIJACK
private:
// By the time a frame is scanned by the runtime, m_pHijackReturnKind always
// identifies the gc-ness of the return register(s)
// If the ReturnKind information is not available from the GcInfo, the runtime
// computes it using the return types's class handle.
ReturnKind m_HijackReturnKind;
public:
ReturnKind GetHijackReturnKind()
{
LIMITED_METHOD_CONTRACT;
return m_HijackReturnKind;
}
void SetHijackReturnKind(ReturnKind returnKind)
{
LIMITED_METHOD_CONTRACT;
m_HijackReturnKind = returnKind;
}
#endif // FEATURE_HIJACK
};
// End of class Thread
LCID GetThreadCultureIdNoThrow(Thread *pThread, BOOL bUICulture);
typedef Thread::ForbidSuspendThreadHolder ForbidSuspendThreadHolder;
typedef Thread::ThreadPreventAsyncHolder ThreadPreventAsyncHolder;
typedef Thread::ThreadPreventAbortHolder ThreadPreventAbortHolder;
// Combines ForBindSuspendThreadHolder and CrstHolder into one.
class ForbidSuspendThreadCrstHolder
{
public:
// Note: member initialization is intentionally ordered.
ForbidSuspendThreadCrstHolder(CrstBase * pCrst)
: m_forbid_suspend_holder()
, m_lock_holder(pCrst)
{ WRAPPER_NO_CONTRACT; }
private:
ForbidSuspendThreadHolder m_forbid_suspend_holder;
CrstHolder m_lock_holder;
};
ETaskType GetCurrentTaskType();
typedef Thread::AVInRuntimeImplOkayHolder AVInRuntimeImplOkayHolder;
BOOL RevertIfImpersonated(BOOL *bReverted, HANDLE *phToken);
void UndoRevert(BOOL bReverted, HANDLE hToken);
// ---------------------------------------------------------------------------
//
// The ThreadStore manages all the threads in the system.
//
// There is one ThreadStore in the system, available through
// ThreadStore::m_pThreadStore.
// ---------------------------------------------------------------------------
typedef SList<Thread, false, PTR_Thread> ThreadList;
// The ThreadStore is a singleton class
#define CHECK_ONE_STORE() _ASSERTE(this == ThreadStore::s_pThreadStore);
typedef DPTR(class ThreadStore) PTR_ThreadStore;
typedef DPTR(class ExceptionTracker) PTR_ExceptionTracker;
class ThreadStore
{
friend class Thread;
friend class ThreadSuspend;
friend Thread* SetupThread(BOOL);
friend class AppDomain;
#ifdef DACCESS_COMPILE
friend class ClrDataAccess;
friend Thread* __stdcall DacGetThread(ULONG32 osThreadID);
#endif
public:
ThreadStore();
static void InitThreadStore();
static void LockThreadStore();
static void UnlockThreadStore();
// Add a Thread to the ThreadStore
// WARNING : only GC calls this with bRequiresTSL set to FALSE.
static void AddThread(Thread *newThread, BOOL bRequiresTSL=TRUE);
// RemoveThread finds the thread in the ThreadStore and discards it.
static BOOL RemoveThread(Thread *target);
static BOOL CanAcquireLock();
// Transfer a thread from the unstarted to the started list.
// WARNING : only GC calls this with bRequiresTSL set to FALSE.
static void TransferStartedThread(Thread *target, BOOL bRequiresTSL=TRUE);
// Before using the thread list, be sure to take the critical section. Otherwise
// it can change underneath you, perhaps leading to an exception after Remove.
// Prev==NULL to get the first entry in the list.
static Thread *GetAllThreadList(Thread *Prev, ULONG mask, ULONG bits);
static Thread *GetThreadList(Thread *Prev);
// Every EE process can lazily create a GUID that uniquely identifies it (for
// purposes of remoting).
const GUID &GetUniqueEEId();
// We shut down the EE when the last non-background thread terminates. This event
// is used to signal the main thread when this condition occurs.
void WaitForOtherThreads();
static void CheckForEEShutdown();
CLREvent m_TerminationEvent;
// Have all the foreground threads completed? In other words, can we release
// the main thread?
BOOL OtherThreadsComplete()
{
LIMITED_METHOD_CONTRACT;
_ASSERTE(m_ThreadCount - m_UnstartedThreadCount - m_DeadThreadCount - Thread::m_ActiveDetachCount + m_PendingThreadCount >= m_BackgroundThreadCount);
return (m_ThreadCount - m_UnstartedThreadCount - m_DeadThreadCount
- Thread::m_ActiveDetachCount + m_PendingThreadCount
== m_BackgroundThreadCount);
}
// If you want to trap threads re-entering the EE (be this for GC, or debugging,
// or Thread.Suspend() or whatever, you need to TrapReturningThreads(TRUE). When
// you are finished snagging threads, call TrapReturningThreads(FALSE). This
// counts internally.
//
// Of course, you must also fix RareDisablePreemptiveGC to do the right thing
// when the trap occurs.
static void TrapReturningThreads(BOOL yes);
private:
// Enter and leave the critical section around the thread store. Clients should
// use LockThreadStore and UnlockThreadStore.
void Enter();
void Leave();
// Critical section for adding and removing threads to the store
Crst m_Crst;
// List of all the threads known to the ThreadStore (started & unstarted).
ThreadList m_ThreadList;
// m_ThreadCount is the count of all threads in m_ThreadList. This includes
// background threads / unstarted threads / whatever.
//
// m_UnstartedThreadCount is the subset of m_ThreadCount that have not yet been
// started.
//
// m_BackgroundThreadCount is the subset of m_ThreadCount that have been started
// but which are running in the background. So this is a misnomer in the sense
// that unstarted background threads are not reflected in this count.
//
// m_PendingThreadCount is used to solve a race condition. The main thread could
// start another thread running and then exit. The main thread might then start
// tearing down the EE before the new thread moves itself out of m_UnstartedThread-
// Count in TransferUnstartedThread. This count is atomically bumped in
// CreateNewThread, and atomically reduced within a locked thread store.
//
// m_DeadThreadCount is the subset of m_ThreadCount which have died. The Win32
// thread has disappeared, but something (like the exposed object) has kept the
// refcount non-zero so we can't destruct yet.
//
// m_MaxThreadCount is the maximum value of m_ThreadCount. ie. the largest number
// of simultaneously active threads
protected:
LONG m_ThreadCount;
LONG m_MaxThreadCount;
public:
LONG ThreadCountInEE ()
{
LIMITED_METHOD_CONTRACT;
return m_ThreadCount;
}
#if defined(_DEBUG) || defined(DACCESS_COMPILE)
LONG MaxThreadCountInEE ()
{
LIMITED_METHOD_CONTRACT;
return m_MaxThreadCount;
}
#endif
private:
LONG m_UnstartedThreadCount;
LONG m_BackgroundThreadCount;
LONG m_PendingThreadCount;
LONG m_DeadThreadCount;
LONG m_DeadThreadCountForGCTrigger;
bool m_TriggerGCForDeadThreads;
private:
// Space for the lazily-created GUID.
GUID m_EEGuid;
BOOL m_GuidCreated;
// Even in the release product, we need to know what thread holds the lock on
// the ThreadStore. This is so we never deadlock when the GC thread halts a
// thread that holds this lock.
Thread *m_HoldingThread;
EEThreadId m_holderthreadid; // current holder (or NULL)
private:
static LONG s_DeadThreadCountThresholdForGCTrigger;
static DWORD s_DeadThreadGCTriggerPeriodMilliseconds;
static SIZE_T *s_DeadThreadGenerationCounts;
public:
static BOOL HoldingThreadStore()
{
WRAPPER_NO_CONTRACT;
// Note that GetThread() may be 0 if it is the debugger thread
// or perhaps a concurrent GC thread.
return HoldingThreadStore(GetThread());
}
static BOOL HoldingThreadStore(Thread *pThread);
#ifdef DACCESS_COMPILE
static void EnumMemoryRegions(CLRDataEnumMemoryFlags flags);
#endif
SPTR_DECL(ThreadStore, s_pThreadStore);
#ifdef _DEBUG
public:
BOOL DbgFindThread(Thread *target);
LONG DbgBackgroundThreadCount()
{
LIMITED_METHOD_CONTRACT;
return m_BackgroundThreadCount;
}
BOOL IsCrstForThreadStore (const CrstBase* const pCrstBase)
{
LIMITED_METHOD_CONTRACT;
return (void *)pCrstBase == (void*)&m_Crst;
}
#endif
private:
static CONTEXT *s_pOSContext;
public:
// We can not do any memory allocation after we suspend a thread in order ot
// avoid deadlock situation.
static void AllocateOSContext();
static CONTEXT *GrabOSContext();
private:
// Thread abort needs to walk stack to decide if thread abort can proceed.
// It is unsafe to crawl a stack of thread if the thread is OS-suspended which we do during
// thread abort. For example, Thread T1 aborts thread T2. T2 is suspended by T1. Inside SQL
// this means that no thread sharing the same scheduler with T2 can run. If T1 needs a lock which
// is owned by one thread on the scheduler, T1 will wait forever.
// Our solution is to move T2 to a safe point, resume it, and then do stack crawl.
static CLREvent *s_pWaitForStackCrawlEvent;
public:
static void WaitForStackCrawlEvent()
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
CAN_TAKE_LOCK;
}
CONTRACTL_END;
s_pWaitForStackCrawlEvent->Wait(INFINITE,FALSE);
}
static void SetStackCrawlEvent()
{
LIMITED_METHOD_CONTRACT;
s_pWaitForStackCrawlEvent->Set();
}
static void ResetStackCrawlEvent()
{
LIMITED_METHOD_CONTRACT;
s_pWaitForStackCrawlEvent->Reset();
}
private:
void IncrementDeadThreadCountForGCTrigger();
void DecrementDeadThreadCountForGCTrigger();
public:
void OnMaxGenerationGCStarted();
bool ShouldTriggerGCForDeadThreads();
void TriggerGCForDeadThreadsIfNecessary();
};
struct TSSuspendHelper {
static void SetTrap() { ThreadStore::TrapReturningThreads(TRUE); }
static void UnsetTrap() { ThreadStore::TrapReturningThreads(FALSE); }
};
typedef StateHolder<TSSuspendHelper::SetTrap, TSSuspendHelper::UnsetTrap> TSSuspendHolder;
typedef StateHolder<ThreadStore::LockThreadStore,ThreadStore::UnlockThreadStore> ThreadStoreLockHolder;
#endif
// This class dispenses small thread ids for the thin lock mechanism.
// Recently we started using this class to dispense domain neutral module IDs as well.
class IdDispenser
{
private:
DWORD m_highestId; // highest id given out so far
SIZE_T m_recycleBin; // link list to chain all ids returning to us
Crst m_Crst; // lock to protect our data structures
DPTR(PTR_Thread) m_idToThread; // map thread ids to threads
DWORD m_idToThreadCapacity; // capacity of the map
#ifndef DACCESS_COMPILE
void GrowIdToThread()
{
CONTRACTL
{
THROWS;
GC_NOTRIGGER;
SO_TOLERANT;
MODE_ANY;
}
CONTRACTL_END;
DWORD newCapacity = m_idToThreadCapacity == 0 ? 16 : m_idToThreadCapacity*2;
Thread **newIdToThread = new Thread*[newCapacity];
newIdToThread[0] = NULL;
for (DWORD i = 1; i < m_idToThreadCapacity; i++)
{
newIdToThread[i] = m_idToThread[i];
}
for (DWORD j = m_idToThreadCapacity; j < newCapacity; j++)
{
newIdToThread[j] = NULL;
}
delete[] m_idToThread;
m_idToThread = newIdToThread;
m_idToThreadCapacity = newCapacity;
}
#endif // !DACCESS_COMPILE
public:
IdDispenser() :
// NOTE: CRST_UNSAFE_ANYMODE prevents a GC mode switch when entering this crst.
// If you remove this flag, we will switch to preemptive mode when entering
// m_Crst, which means all functions that enter it will become
// GC_TRIGGERS. (This includes all uses of CrstHolder.) So be sure
// to update the contracts if you remove this flag.
m_Crst(CrstThreadIdDispenser, CRST_UNSAFE_ANYMODE)
{
WRAPPER_NO_CONTRACT;
m_highestId = 0;
m_recycleBin = 0;
m_idToThreadCapacity = 0;
m_idToThread = NULL;
}
~IdDispenser()
{
LIMITED_METHOD_CONTRACT;
delete[] m_idToThread;
}
bool IsValidId(DWORD id)
{
LIMITED_METHOD_CONTRACT;
return (id > 0) && (id <= m_highestId);
}
#ifndef DACCESS_COMPILE
void NewId(Thread *pThread, DWORD & newId)
{
WRAPPER_NO_CONTRACT;
DWORD result;
CrstHolder ch(&m_Crst);
if (m_recycleBin != 0)
{
_ASSERTE(FitsIn<DWORD>(m_recycleBin));
result = static_cast<DWORD>(m_recycleBin);
m_recycleBin = reinterpret_cast<SIZE_T>(m_idToThread[m_recycleBin]);
}
else
{
// we make sure ids don't wrap around - before they do, we always return the highest possible
// one and rely on our caller to detect this situation
if (m_highestId + 1 > m_highestId)
m_highestId = m_highestId + 1;
result = m_highestId;
if (result >= m_idToThreadCapacity)
GrowIdToThread();
}
_ASSERTE(result < m_idToThreadCapacity);
newId = result;
if (result < m_idToThreadCapacity)
m_idToThread[result] = pThread;
}
#endif // !DACCESS_COMPILE
#ifndef DACCESS_COMPILE
void DisposeId(DWORD id)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
CAN_TAKE_LOCK;
}
CONTRACTL_END;
CrstHolder ch(&m_Crst);
_ASSERTE(IsValidId(id));
if (id == m_highestId)
{
m_highestId--;
}
else
{
m_idToThread[id] = reinterpret_cast<PTR_Thread>(m_recycleBin);
m_recycleBin = id;
#ifdef _DEBUG
size_t index = (size_t)m_idToThread[id];
while (index != 0)
{
_ASSERTE(index != id);
index = (size_t)m_idToThread[index];
}
#endif
}
}
#endif // !DACCESS_COMPILE
Thread *IdToThread(DWORD id)
{
LIMITED_METHOD_CONTRACT;
CrstHolder ch(&m_Crst);
Thread *result = NULL;
if (id <= m_highestId)
result = m_idToThread[id];
// m_idToThread may have Thread*, or the next free slot
_ASSERTE ((size_t)result > m_idToThreadCapacity);
return result;
}
Thread *IdToThreadWithValidation(DWORD id)
{
WRAPPER_NO_CONTRACT;
CrstHolder ch(&m_Crst);
Thread *result = NULL;
if (id <= m_highestId)
result = m_idToThread[id];
// m_idToThread may have Thread*, or the next free slot
if ((size_t)result <= m_idToThreadCapacity)
result = NULL;
_ASSERTE(result == NULL || ((size_t)result & 0x3) == 0 || ((Thread*)result)->GetThreadId() == id);
return result;
}
};
typedef DPTR(IdDispenser) PTR_IdDispenser;
#ifndef CROSSGEN_COMPILE
// Dispenser of small thread ids for thin lock mechanism
GPTR_DECL(IdDispenser,g_pThinLockThreadIdDispenser);
// forward declaration
DWORD MsgWaitHelper(int numWaiters, HANDLE* phEvent, BOOL bWaitAll, DWORD millis, BOOL alertable = FALSE);
// When a thread is being created after a debug suspension has started, it sends an event up to the
// debugger. Afterwards, with the Debugger Lock still held, it will check to see if we had already asked to suspend the
// Runtime. If we have, then it will turn around and call this to set the debug suspend pending flag on the newly
// created thread, since it was missed by SysStartSuspendForDebug as it didn't exist when that function was run.
//
inline void Thread::MarkForDebugSuspend(void)
{
WRAPPER_NO_CONTRACT;
if (!(m_State & TS_DebugSuspendPending))
{
FastInterlockOr((ULONG *) &m_State, TS_DebugSuspendPending);
ThreadStore::TrapReturningThreads(TRUE);
}
}
// Debugger per-thread flag for enabling notification on "manual"
// method calls, for stepping logic.
inline void Thread::IncrementTraceCallCount()
{
WRAPPER_NO_CONTRACT;
FastInterlockIncrement(&m_TraceCallCount);
ThreadStore::TrapReturningThreads(TRUE);
}
inline void Thread::DecrementTraceCallCount()
{
WRAPPER_NO_CONTRACT;
ThreadStore::TrapReturningThreads(FALSE);
FastInterlockDecrement(&m_TraceCallCount);
}
// When we enter an Object.Wait() we are logically inside the synchronized
// region of that object. Of course, we've actually completely left the region,
// or else nobody could Notify us. But if we throw ThreadInterruptedException to
// break out of the Wait, all the catchers are going to expect the synchronized
// state to be correct. So we carry it around in case we need to restore it.
struct PendingSync
{
LONG m_EnterCount;
WaitEventLink *m_WaitEventLink;
#ifdef _DEBUG
Thread *m_OwnerThread;
#endif
PendingSync(WaitEventLink *s) : m_WaitEventLink(s)
{
WRAPPER_NO_CONTRACT;
#ifdef _DEBUG
m_OwnerThread = GetThread();
#endif
}
void Restore(BOOL bRemoveFromSB);
};
#define INCTHREADLOCKCOUNT() { }
#define DECTHREADLOCKCOUNT() { }
#define INCTHREADLOCKCOUNTTHREAD(thread) { }
#define DECTHREADLOCKCOUNTTHREAD(thread) { }
// --------------------------------------------------------------------------------
// GCHolder is used to implement the normal GCX_ macros.
//
// GCHolder is normally used indirectly through GCX_ convenience macros, but can be used
// directly if needed (e.g. due to multiple holders in one scope, or to use
// in class definitions).
//
// GCHolder (or derived types) should only be instantiated as automatic variables
// --------------------------------------------------------------------------------
#ifdef ENABLE_CONTRACTS_IMPL
#define GCHOLDER_CONTRACT_ARGS_NoDtor , false, szConstruct, szFunction, szFile, lineNum
#define GCHOLDER_CONTRACT_ARGS_HasDtor , true, szConstruct, szFunction, szFile, lineNum
#define GCHOLDER_DECLARE_CONTRACT_ARGS_BARE \
const char * szConstruct = "Unknown" \
, const char * szFunction = "Unknown" \
, const char * szFile = "Unknown" \
, int lineNum = 0
#define GCHOLDER_DECLARE_CONTRACT_ARGS , GCHOLDER_DECLARE_CONTRACT_ARGS_BARE
#define GCHOLDER_DECLARE_CONTRACT_ARGS_INTERNAL , bool fPushStackRecord = true, GCHOLDER_DECLARE_CONTRACT_ARGS_BARE
#define GCHOLDER_SETUP_CONTRACT_STACK_RECORD(mode) \
m_fPushedRecord = false; \
\
if (fPushStackRecord && conditional) \
{ \
m_pClrDebugState = GetClrDebugState(); \
m_oldClrDebugState = *m_pClrDebugState; \
\
m_pClrDebugState->ViolationMaskReset( ModeViolation ); \
\
m_ContractStackRecord.m_szFunction = szFunction; \
m_ContractStackRecord.m_szFile = szFile; \
m_ContractStackRecord.m_lineNum = lineNum; \
m_ContractStackRecord.m_testmask = \
(Contract::ALL_Disabled & ~((UINT)(Contract::MODE_Mask))) \
| (mode); \
m_ContractStackRecord.m_construct = szConstruct; \
m_pClrDebugState->LinkContractStackTrace( &m_ContractStackRecord ); \
m_fPushedRecord = true; \
}
#define GCHOLDER_CHECK_FOR_PREEMP_IN_NOTRIGGER(pThread) \
if (pThread->GCNoTrigger()) \
{ \
CONTRACT_ASSERT("Coop->preemp->coop switch attempted in a GC_NOTRIGGER scope", \
Contract::GC_NoTrigger, \
Contract::GC_Mask, \
szFunction, \
szFile, \
lineNum \
); \
}
#else
#define GCHOLDER_CONTRACT_ARGS_NoDtor
#define GCHOLDER_CONTRACT_ARGS_HasDtor
#define GCHOLDER_DECLARE_CONTRACT_ARGS_BARE
#define GCHOLDER_DECLARE_CONTRACT_ARGS
#define GCHOLDER_DECLARE_CONTRACT_ARGS_INTERNAL
#define GCHOLDER_SETUP_CONTRACT_STACK_RECORD(mode)
#define GCHOLDER_CHECK_FOR_PREEMP_IN_NOTRIGGER(pThread)
#endif // ENABLE_CONTRACTS_IMPL
#ifndef DACCESS_COMPILE
class GCHolderBase
{
protected:
// NOTE: This method is FORCEINLINE'ed into its callers, but the callers are just the
// corresponding methods in the derived types, not all sites that use GC holders. This
// is done so that the #pragma optimize will take affect since the optimize settings
// are taken from the template instantiation site, not the template definition site.
template <BOOL THREAD_EXISTS>
FORCEINLINE_NONDEBUG
void PopInternal()
{
SCAN_SCOPE_END;
WRAPPER_NO_CONTRACT;
#ifdef ENABLE_CONTRACTS_IMPL
if (m_fPushedRecord)
{
*m_pClrDebugState = m_oldClrDebugState;
}
// Make sure that we're using the version of this template that matches the
// invariant setup in EnterInternal{Coop|Preemp}{_HackNoThread}
_ASSERTE(!!THREAD_EXISTS == m_fThreadMustExist);
#endif
if (m_WasCoop)
{
// m_WasCoop is only TRUE if we've already verified there's an EE thread.
BEGIN_GETTHREAD_ALLOWED;
_ASSERTE(m_Thread != NULL); // Cannot switch to cooperative with no thread
if (!m_Thread->PreemptiveGCDisabled())
m_Thread->DisablePreemptiveGC();
END_GETTHREAD_ALLOWED;
}
else
{
// Either we initialized m_Thread explicitly with GetThread() in the
// constructor, or our caller (instantiator of GCHolder) called our constructor
// with GetThread() (which we already asserted in the constuctor)
// (i.e., m_Thread == GetThread()). Also, note that if THREAD_EXISTS,
// then m_Thread must be non-null (as it's == GetThread()). So the
// "if" below looks a little hokey since we're checking for either condition.
// But the template param THREAD_EXISTS allows us to statically early-out
// when it's TRUE, so we check it for perf.
if (THREAD_EXISTS || m_Thread != NULL)
{
BEGIN_GETTHREAD_ALLOWED;
if (m_Thread->PreemptiveGCDisabled())
m_Thread->EnablePreemptiveGC();
END_GETTHREAD_ALLOWED;
}
}
// If we have a thread then we assert that we ended up in the same state
// which we started in.
if (THREAD_EXISTS || m_Thread != NULL)
{
_ASSERTE(!!m_WasCoop == !!(m_Thread->PreemptiveGCDisabled()));
}
}
// NOTE: The rest of these methods are all FORCEINLINE so that the uses where 'conditional==true'
// can have the if-checks removed by the compiler. The callers are just the corresponding methods
// in the derived types, not all sites that use GC holders.
// This is broken - there is a potential race with the GC thread. It is currently
// used for a few cases where (a) we potentially haven't started up the EE yet, or
// (b) we are on a "special thread". We need a real solution here though.
FORCEINLINE_NONDEBUG
void EnterInternalCoop_HackNoThread(bool conditional GCHOLDER_DECLARE_CONTRACT_ARGS_INTERNAL)
{
GCHOLDER_SETUP_CONTRACT_STACK_RECORD(Contract::MODE_Coop);
m_Thread = GetThreadNULLOk();
#ifdef ENABLE_CONTRACTS_IMPL
m_fThreadMustExist = false;
#endif // ENABLE_CONTRACTS_IMPL
if (m_Thread != NULL)
{
BEGIN_GETTHREAD_ALLOWED;
m_WasCoop = m_Thread->PreemptiveGCDisabled();
if (conditional && !m_WasCoop)
{
m_Thread->DisablePreemptiveGC();
_ASSERTE(m_Thread->PreemptiveGCDisabled());
}
END_GETTHREAD_ALLOWED;
}
else
{
m_WasCoop = FALSE;
}
}
FORCEINLINE_NONDEBUG
void EnterInternalPreemp(bool conditional GCHOLDER_DECLARE_CONTRACT_ARGS_INTERNAL)
{
GCHOLDER_SETUP_CONTRACT_STACK_RECORD(Contract::MODE_Preempt);
m_Thread = GetThreadNULLOk();
#ifdef ENABLE_CONTRACTS_IMPL
m_fThreadMustExist = false;
if (m_Thread != NULL && conditional)
{
BEGIN_GETTHREAD_ALLOWED;
GCHOLDER_CHECK_FOR_PREEMP_IN_NOTRIGGER(m_Thread);
END_GETTHREAD_ALLOWED;
}
#endif // ENABLE_CONTRACTS_IMPL
if (m_Thread != NULL)
{
BEGIN_GETTHREAD_ALLOWED;
m_WasCoop = m_Thread->PreemptiveGCDisabled();
if (conditional && m_WasCoop)
{
m_Thread->EnablePreemptiveGC();
_ASSERTE(!m_Thread->PreemptiveGCDisabled());
}
END_GETTHREAD_ALLOWED;
}
else
{
m_WasCoop = FALSE;
}
}
FORCEINLINE_NONDEBUG
void EnterInternalCoop(Thread *pThread, bool conditional GCHOLDER_DECLARE_CONTRACT_ARGS_INTERNAL)
{
// This is the perf version. So we deliberately restrict the calls
// to already setup threads to avoid the null checks and GetThread call
_ASSERTE(pThread && (pThread == GetThread()));
#ifdef ENABLE_CONTRACTS_IMPL
m_fThreadMustExist = true;
#endif // ENABLE_CONTRACTS_IMPL
GCHOLDER_SETUP_CONTRACT_STACK_RECORD(Contract::MODE_Coop);
m_Thread = pThread;
m_WasCoop = m_Thread->PreemptiveGCDisabled();
if (conditional && !m_WasCoop)
{
m_Thread->DisablePreemptiveGC();
_ASSERTE(m_Thread->PreemptiveGCDisabled());
}
}
template <BOOL THREAD_EXISTS>
FORCEINLINE_NONDEBUG
void EnterInternalPreemp(Thread *pThread, bool conditional GCHOLDER_DECLARE_CONTRACT_ARGS_INTERNAL)
{
// This is the perf version. So we deliberately restrict the calls
// to already setup threads to avoid the null checks and GetThread call
_ASSERTE(!THREAD_EXISTS || (pThread && (pThread == GetThread())));
#ifdef ENABLE_CONTRACTS_IMPL
m_fThreadMustExist = !!THREAD_EXISTS;
#endif // ENABLE_CONTRACTS_IMPL
GCHOLDER_SETUP_CONTRACT_STACK_RECORD(Contract::MODE_Preempt);
m_Thread = pThread;
if (THREAD_EXISTS || (m_Thread != NULL))
{
GCHOLDER_CHECK_FOR_PREEMP_IN_NOTRIGGER(m_Thread);
m_WasCoop = m_Thread->PreemptiveGCDisabled();
if (conditional && m_WasCoop)
{
m_Thread->EnablePreemptiveGC();
_ASSERTE(!m_Thread->PreemptiveGCDisabled());
}
}
else
{
m_WasCoop = FALSE;
}
}
private:
Thread * m_Thread;
BOOL m_WasCoop; // This is BOOL and not 'bool' because PreemptiveGCDisabled returns BOOL,
// so the codegen is better if we don't have to convert to 'bool'.
#ifdef ENABLE_CONTRACTS_IMPL
bool m_fThreadMustExist; // used to validate that the proper Pop<THREAD_EXISTS> method is used
bool m_fPushedRecord;
ClrDebugState m_oldClrDebugState;
ClrDebugState *m_pClrDebugState;
ContractStackRecord m_ContractStackRecord;
#endif
};
class GCCoopNoDtor : public GCHolderBase
{
public:
DEBUG_NOINLINE
void Enter(bool conditional GCHOLDER_DECLARE_CONTRACT_ARGS)
{
WRAPPER_NO_CONTRACT;
SCAN_SCOPE_BEGIN;
if (conditional)
{
STATIC_CONTRACT_MODE_COOPERATIVE;
}
// The thread must be non-null to enter MODE_COOP
this->EnterInternalCoop(GetThread(), conditional GCHOLDER_CONTRACT_ARGS_NoDtor);
}
DEBUG_NOINLINE
void Leave()
{
WRAPPER_NO_CONTRACT;
SCAN_SCOPE_BEGIN;
this->PopInternal<TRUE>(); // Thread must be non-NULL
}
};
class GCPreempNoDtor : public GCHolderBase
{
public:
DEBUG_NOINLINE
void Enter(bool conditional GCHOLDER_DECLARE_CONTRACT_ARGS)
{
SCAN_SCOPE_BEGIN;
if (conditional)
{
STATIC_CONTRACT_MODE_PREEMPTIVE;
}
this->EnterInternalPreemp(conditional GCHOLDER_CONTRACT_ARGS_NoDtor);
}
DEBUG_NOINLINE
void Enter(Thread * pThreadNullOk, bool conditional GCHOLDER_DECLARE_CONTRACT_ARGS)
{
SCAN_SCOPE_BEGIN;
if (conditional)
{
STATIC_CONTRACT_MODE_PREEMPTIVE;
}
this->EnterInternalPreemp<FALSE>( // Thread may be NULL
pThreadNullOk, conditional GCHOLDER_CONTRACT_ARGS_NoDtor);
}
DEBUG_NOINLINE
void Leave()
{
SCAN_SCOPE_END;
this->PopInternal<FALSE>(); // Thread may be NULL
}
};
class GCCoop : public GCHolderBase
{
public:
DEBUG_NOINLINE
GCCoop(GCHOLDER_DECLARE_CONTRACT_ARGS_BARE)
{
SCAN_SCOPE_BEGIN;
STATIC_CONTRACT_MODE_COOPERATIVE;
// The thread must be non-null to enter MODE_COOP
this->EnterInternalCoop(GetThread(), true GCHOLDER_CONTRACT_ARGS_HasDtor);
}
DEBUG_NOINLINE
GCCoop(bool conditional GCHOLDER_DECLARE_CONTRACT_ARGS)
{
SCAN_SCOPE_BEGIN;
if (conditional)
{
STATIC_CONTRACT_MODE_COOPERATIVE;
}
// The thread must be non-null to enter MODE_COOP
this->EnterInternalCoop(GetThread(), conditional GCHOLDER_CONTRACT_ARGS_HasDtor);
}
DEBUG_NOINLINE
~GCCoop()
{
SCAN_SCOPE_END;
this->PopInternal<TRUE>(); // Thread must be non-NULL
}
};
// This is broken - there is a potential race with the GC thread. It is currently
// used for a few cases where (a) we potentially haven't started up the EE yet, or
// (b) we are on a "special thread". We need a real solution here though.
class GCCoopHackNoThread : public GCHolderBase
{
public:
DEBUG_NOINLINE
GCCoopHackNoThread(GCHOLDER_DECLARE_CONTRACT_ARGS_BARE)
{
SCAN_SCOPE_BEGIN;
STATIC_CONTRACT_MODE_COOPERATIVE;
this->EnterInternalCoop_HackNoThread(true GCHOLDER_CONTRACT_ARGS_HasDtor);
}
DEBUG_NOINLINE
GCCoopHackNoThread(bool conditional GCHOLDER_DECLARE_CONTRACT_ARGS)
{
SCAN_SCOPE_BEGIN;
if (conditional)
{
STATIC_CONTRACT_MODE_COOPERATIVE;
}
this->EnterInternalCoop_HackNoThread(conditional GCHOLDER_CONTRACT_ARGS_HasDtor);
}
DEBUG_NOINLINE
~GCCoopHackNoThread()
{
SCAN_SCOPE_END;
this->PopInternal<FALSE>(); // Thread might be NULL
}
};
class GCCoopThreadExists : public GCHolderBase
{
public:
DEBUG_NOINLINE
GCCoopThreadExists(Thread * pThread GCHOLDER_DECLARE_CONTRACT_ARGS)
{
SCAN_SCOPE_BEGIN;
STATIC_CONTRACT_MODE_COOPERATIVE;
this->EnterInternalCoop(pThread, true GCHOLDER_CONTRACT_ARGS_HasDtor);
}
DEBUG_NOINLINE
GCCoopThreadExists(Thread * pThread, bool conditional GCHOLDER_DECLARE_CONTRACT_ARGS)
{
SCAN_SCOPE_BEGIN;
if (conditional)
{
STATIC_CONTRACT_MODE_COOPERATIVE;
}
this->EnterInternalCoop(pThread, conditional GCHOLDER_CONTRACT_ARGS_HasDtor);
}
DEBUG_NOINLINE
~GCCoopThreadExists()
{
SCAN_SCOPE_END;
this->PopInternal<TRUE>(); // Thread must be non-NULL
}
};
class GCPreemp : public GCHolderBase
{
public:
DEBUG_NOINLINE
GCPreemp(GCHOLDER_DECLARE_CONTRACT_ARGS_BARE)
{
SCAN_SCOPE_BEGIN;
STATIC_CONTRACT_MODE_PREEMPTIVE;
this->EnterInternalPreemp(true GCHOLDER_CONTRACT_ARGS_HasDtor);
}
DEBUG_NOINLINE
GCPreemp(bool conditional GCHOLDER_DECLARE_CONTRACT_ARGS)
{
SCAN_SCOPE_BEGIN;
if (conditional)
{
STATIC_CONTRACT_MODE_PREEMPTIVE;
}
this->EnterInternalPreemp(conditional GCHOLDER_CONTRACT_ARGS_HasDtor);
}
DEBUG_NOINLINE
~GCPreemp()
{
SCAN_SCOPE_END;
this->PopInternal<FALSE>(); // Thread may be NULL
}
};
class GCPreempThreadExists : public GCHolderBase
{
public:
DEBUG_NOINLINE
GCPreempThreadExists(Thread * pThread GCHOLDER_DECLARE_CONTRACT_ARGS)
{
SCAN_SCOPE_BEGIN;
STATIC_CONTRACT_MODE_PREEMPTIVE;
this->EnterInternalPreemp<TRUE>( // Thread must be non-NULL
pThread, true GCHOLDER_CONTRACT_ARGS_HasDtor);
}
DEBUG_NOINLINE
GCPreempThreadExists(Thread * pThread, bool conditional GCHOLDER_DECLARE_CONTRACT_ARGS)
{
SCAN_SCOPE_BEGIN;
if (conditional)
{
STATIC_CONTRACT_MODE_PREEMPTIVE;
}
this->EnterInternalPreemp<TRUE>( // Thread must be non-NULL
pThread, conditional GCHOLDER_CONTRACT_ARGS_HasDtor);
}
DEBUG_NOINLINE
~GCPreempThreadExists()
{
SCAN_SCOPE_END;
this->PopInternal<TRUE>(); // Thread must be non-NULL
}
};
#endif // DACCESS_COMPILE
// --------------------------------------------------------------------------------
// GCAssert is used to implement the assert GCX_ macros. Usage is similar to GCHolder.
//
// GCAsserting for preemptive mode automatically passes on unmanaged threads.
//
// Note that the assert is "2 sided"; it happens on entering and on leaving scope, to
// help ensure mode integrity.
//
// GCAssert is a noop in a free build
// --------------------------------------------------------------------------------
template<BOOL COOPERATIVE>
class GCAssert
{
public:
DEBUG_NOINLINE void BeginGCAssert();
DEBUG_NOINLINE void EndGCAssert()
{
SCAN_SCOPE_END;
}
};
template<BOOL COOPERATIVE>
class AutoCleanupGCAssert
{
#ifdef _DEBUG_IMPL
public:
DEBUG_NOINLINE AutoCleanupGCAssert();
DEBUG_NOINLINE ~AutoCleanupGCAssert()
{
SCAN_SCOPE_END;
WRAPPER_NO_CONTRACT;
// This is currently disabled; we currently have a lot of code which doesn't
// back out the GC mode properly (instead relying on the EX_TRY macros.)
//
// @todo enable this when we remove raw GC mode switching.
#if 0
DoCheck();
#endif
}
private:
FORCEINLINE void DoCheck()
{
WRAPPER_NO_CONTRACT;
Thread *pThread = GetThread();
if (COOPERATIVE)
{
_ASSERTE(pThread != NULL);
_ASSERTE(pThread->PreemptiveGCDisabled());
}
else
{
_ASSERTE(pThread == NULL || !(pThread->PreemptiveGCDisabled()));
}
}
#endif
};
// --------------------------------------------------------------------------------
// GCForbid is used to add ForbidGC semantics to the current GC mode. Note that
// it requires the thread to be in cooperative mode already.
//
// GCForbid is a noop in a free build
// --------------------------------------------------------------------------------
#ifndef DACCESS_COMPILE
class GCForbid : AutoCleanupGCAssert<TRUE>
{
#ifdef ENABLE_CONTRACTS_IMPL
public:
DEBUG_NOINLINE GCForbid(BOOL fConditional, const char *szFunction, const char *szFile, int lineNum)
{
SCAN_SCOPE_BEGIN;
if (fConditional)
{
STATIC_CONTRACT_MODE_COOPERATIVE;
STATIC_CONTRACT_GC_NOTRIGGER;
}
m_fConditional = fConditional;
if (m_fConditional)
{
Thread *pThread = GetThread();
m_pClrDebugState = pThread ? pThread->GetClrDebugState() : ::GetClrDebugState();
m_oldClrDebugState = *m_pClrDebugState;
m_pClrDebugState->ViolationMaskReset( GCViolation );
GetThread()->BeginForbidGC(szFile, lineNum);
m_ContractStackRecord.m_szFunction = szFunction;
m_ContractStackRecord.m_szFile = (char*)szFile;
m_ContractStackRecord.m_lineNum = lineNum;
m_ContractStackRecord.m_testmask = (Contract::ALL_Disabled & ~((UINT)(Contract::GC_Mask))) | Contract::GC_NoTrigger;
m_ContractStackRecord.m_construct = "GCX_FORBID";
m_pClrDebugState->LinkContractStackTrace( &m_ContractStackRecord );
}
}
DEBUG_NOINLINE GCForbid(const char *szFunction, const char *szFile, int lineNum)
{
SCAN_SCOPE_BEGIN;
STATIC_CONTRACT_MODE_COOPERATIVE;
STATIC_CONTRACT_GC_NOTRIGGER;
m_fConditional = TRUE;
Thread *pThread = GetThread();
m_pClrDebugState = pThread ? pThread->GetClrDebugState() : ::GetClrDebugState();
m_oldClrDebugState = *m_pClrDebugState;
m_pClrDebugState->ViolationMaskReset( GCViolation );
GetThread()->BeginForbidGC(szFile, lineNum);
m_ContractStackRecord.m_szFunction = szFunction;
m_ContractStackRecord.m_szFile = (char*)szFile;
m_ContractStackRecord.m_lineNum = lineNum;
m_ContractStackRecord.m_testmask = (Contract::ALL_Disabled & ~((UINT)(Contract::GC_Mask))) | Contract::GC_NoTrigger;
m_ContractStackRecord.m_construct = "GCX_FORBID";
m_pClrDebugState->LinkContractStackTrace( &m_ContractStackRecord );
}
DEBUG_NOINLINE ~GCForbid()
{
SCAN_SCOPE_END;
if (m_fConditional)
{
GetThread()->EndForbidGC();
*m_pClrDebugState = m_oldClrDebugState;
}
}
private:
BOOL m_fConditional;
ClrDebugState *m_pClrDebugState;
ClrDebugState m_oldClrDebugState;
ContractStackRecord m_ContractStackRecord;
#endif // _DEBUG_IMPL
};
#endif // !DACCESS_COMPILE
// --------------------------------------------------------------------------------
// GCNoTrigger is used to add NoTriggerGC semantics to the current GC mode. Unlike
// GCForbid, it does not require a thread to be in cooperative mode.
//
// GCNoTrigger is a noop in a free build
// --------------------------------------------------------------------------------
#ifndef DACCESS_COMPILE
class GCNoTrigger
{
#ifdef ENABLE_CONTRACTS_IMPL
public:
DEBUG_NOINLINE GCNoTrigger(BOOL fConditional, const char *szFunction, const char *szFile, int lineNum)
{
SCAN_SCOPE_BEGIN;
if (fConditional)
{
STATIC_CONTRACT_GC_NOTRIGGER;
}
m_fConditional = fConditional;
if (m_fConditional)
{
Thread * pThread = GetThreadNULLOk();
m_pClrDebugState = pThread ? pThread->GetClrDebugState() : ::GetClrDebugState();
m_oldClrDebugState = *m_pClrDebugState;
m_pClrDebugState->ViolationMaskReset( GCViolation );
if (pThread != NULL)
{
pThread->BeginNoTriggerGC(szFile, lineNum);
}
m_ContractStackRecord.m_szFunction = szFunction;
m_ContractStackRecord.m_szFile = (char*)szFile;
m_ContractStackRecord.m_lineNum = lineNum;
m_ContractStackRecord.m_testmask = (Contract::ALL_Disabled & ~((UINT)(Contract::GC_Mask))) | Contract::GC_NoTrigger;
m_ContractStackRecord.m_construct = "GCX_NOTRIGGER";
m_pClrDebugState->LinkContractStackTrace( &m_ContractStackRecord );
}
}
DEBUG_NOINLINE GCNoTrigger(const char *szFunction, const char *szFile, int lineNum)
{
SCAN_SCOPE_BEGIN;
STATIC_CONTRACT_GC_NOTRIGGER;
m_fConditional = TRUE;
Thread * pThread = GetThreadNULLOk();
m_pClrDebugState = pThread ? pThread->GetClrDebugState() : ::GetClrDebugState();
m_oldClrDebugState = *m_pClrDebugState;
m_pClrDebugState->ViolationMaskReset( GCViolation );
if (pThread != NULL)
{
pThread->BeginNoTriggerGC(szFile, lineNum);
}
m_ContractStackRecord.m_szFunction = szFunction;
m_ContractStackRecord.m_szFile = (char*)szFile;
m_ContractStackRecord.m_lineNum = lineNum;
m_ContractStackRecord.m_testmask = (Contract::ALL_Disabled & ~((UINT)(Contract::GC_Mask))) | Contract::GC_NoTrigger;
m_ContractStackRecord.m_construct = "GCX_NOTRIGGER";
m_pClrDebugState->LinkContractStackTrace( &m_ContractStackRecord );
}
DEBUG_NOINLINE ~GCNoTrigger()
{
SCAN_SCOPE_END;
if (m_fConditional)
{
Thread * pThread = GetThreadNULLOk();
if (pThread)
{
pThread->EndNoTriggerGC();
}
*m_pClrDebugState = m_oldClrDebugState;
}
}
private:
BOOL m_fConditional;
ClrDebugState *m_pClrDebugState;
ClrDebugState m_oldClrDebugState;
ContractStackRecord m_ContractStackRecord;
#endif // _DEBUG_IMPL
};
#endif //!DACCESS_COMPILE
class CoopTransitionHolder
{
Frame * m_pFrame;
public:
CoopTransitionHolder(Thread * pThread)
: m_pFrame(pThread->m_pFrame)
{
LIMITED_METHOD_CONTRACT;
}
~CoopTransitionHolder()
{
WRAPPER_NO_CONTRACT;
if (m_pFrame != NULL)
COMPlusCooperativeTransitionHandler(m_pFrame);
}
void SuppressRelease()
{
LIMITED_METHOD_CONTRACT;
// FRAME_TOP and NULL must be distinct values.
// static_assert_no_msg(FRAME_TOP_VALUE != NULL);
m_pFrame = NULL;
}
};
// --------------------------------------------------------------------------------
// GCX macros - see util.hpp
// --------------------------------------------------------------------------------
#ifdef _DEBUG_IMPL
// Normally, any thread we operate on has a Thread block in its TLS. But there are
// a few special threads we don't normally execute managed code on.
BOOL dbgOnly_IsSpecialEEThread();
void dbgOnly_IdentifySpecialEEThread();
#ifdef USE_CHECKED_OBJECTREFS
#define ASSERT_PROTECTED(objRef) Thread::ObjectRefProtected(objRef)
#else
#define ASSERT_PROTECTED(objRef)
#endif
#else
#define ASSERT_PROTECTED(objRef)
#endif
#ifdef ENABLE_CONTRACTS_IMPL
#define BEGINFORBIDGC() {if (GetThreadNULLOk() != NULL) GetThreadNULLOk()->BeginForbidGC(__FILE__, __LINE__);}
#define ENDFORBIDGC() {if (GetThreadNULLOk() != NULL) GetThreadNULLOk()->EndForbidGC();}
class FCallGCCanTrigger
{
public:
static DEBUG_NOINLINE void Enter()
{
SCAN_SCOPE_BEGIN;
STATIC_CONTRACT_GC_TRIGGERS;
Thread * pThread = GetThreadNULLOk();
if (pThread != NULL)
{
Enter(pThread);
}
}
static DEBUG_NOINLINE void Enter(Thread* pThread)
{
SCAN_SCOPE_BEGIN;
STATIC_CONTRACT_GC_TRIGGERS;
pThread->EndForbidGC();
}
static DEBUG_NOINLINE void Leave(const char *szFunction, const char *szFile, int lineNum)
{
SCAN_SCOPE_END;
Thread * pThread = GetThreadNULLOk();
if (pThread != NULL)
{
Leave(pThread, szFunction, szFile, lineNum);
}
}
static DEBUG_NOINLINE void Leave(Thread* pThread, const char *szFunction, const char *szFile, int lineNum)
{
SCAN_SCOPE_END;
pThread->BeginForbidGC(szFile, lineNum);
}
};
#define TRIGGERSGC_NOSTOMP() do { \
ANNOTATION_GC_TRIGGERS; \
Thread* curThread = GetThread(); \
if(curThread->GCNoTrigger()) \
{ \
CONTRACT_ASSERT("TRIGGERSGC found in a GC_NOTRIGGER region.", Contract::GC_NoTrigger, Contract::GC_Mask, __FUNCTION__, __FILE__, __LINE__); \
} \
} while(0)
#define TRIGGERSGC() do { \
TRIGGERSGC_NOSTOMP(); \
Thread::TriggersGC(GetThread()); \
} while(0)
#else // ENABLE_CONTRACTS_IMPL
#define BEGINFORBIDGC()
#define ENDFORBIDGC()
#define TRIGGERSGC_NOSTOMP() ANNOTATION_GC_TRIGGERS
#define TRIGGERSGC() ANNOTATION_GC_TRIGGERS
#endif // ENABLE_CONTRACTS_IMPL
inline BOOL GC_ON_TRANSITIONS(BOOL val) {
WRAPPER_NO_CONTRACT;
#ifdef _DEBUG
Thread* thread = GetThread();
if (thread == 0)
return(FALSE);
BOOL ret = thread->m_GCOnTransitionsOK;
thread->m_GCOnTransitionsOK = val;
return(ret);
#else // _DEBUG
return FALSE;
#endif // !_DEBUG
}
#ifdef _DEBUG
inline void ENABLESTRESSHEAP() {
WRAPPER_NO_CONTRACT;
Thread * thread = GetThreadNULLOk();
if (thread) {
thread->EnableStressHeap();
}
}
void CleanStackForFastGCStress ();
#define CLEANSTACKFORFASTGCSTRESS() \
if (g_pConfig->GetGCStressLevel() && g_pConfig->FastGCStressLevel() > 1) { \
CleanStackForFastGCStress (); \
}
#else // _DEBUG
#define CLEANSTACKFORFASTGCSTRESS()
#endif // _DEBUG
inline void DoReleaseCheckpoint(void *checkPointMarker)
{
WRAPPER_NO_CONTRACT;
GetThread()->m_MarshalAlloc.Collapse(checkPointMarker);
}
// CheckPointHolder : Back out to a checkpoint on the thread allocator.
typedef Holder<void*, DoNothing, DoReleaseCheckpoint> CheckPointHolder;
#ifdef _DEBUG_IMPL
// Holder for incrementing the ForbidGCLoaderUse counter.
class GCForbidLoaderUseHolder
{
public:
GCForbidLoaderUseHolder()
{
WRAPPER_NO_CONTRACT;
ClrFlsIncrementValue(TlsIdx_ForbidGCLoaderUseCount, 1);
}
~GCForbidLoaderUseHolder()
{
WRAPPER_NO_CONTRACT;
ClrFlsIncrementValue(TlsIdx_ForbidGCLoaderUseCount, -1);
}
};
#endif
// Declaring this macro turns off the GC_TRIGGERS/THROWS/INJECT_FAULT contract in LoadTypeHandle.
// If you do this, you must restrict your use of the loader only to retrieve TypeHandles
// for types that have already been loaded and resolved. If you fail to observe this restriction, you will
// reach a GC_TRIGGERS point somewhere in the loader and assert. If you're lucky, that is.
// (If you're not lucky, you will introduce a GC hole.)
//
// The main user of this workaround is the GC stack crawl. It must parse signatures and retrieve
// type handles for valuetypes in method parameters. Some other uses have creeped into the codebase -
// some justified, others not.
//
// ENABLE_FORBID_GC_LOADER is *not* the same as using tokenNotToLoad to suppress loading.
// You should use tokenNotToLoad in preference to ENABLE_FORBID. ENABLE_FORBID is a fragile
// workaround and places enormous responsibilities on the caller. The only reason it exists at all
// is that the GC stack crawl simply cannot tolerate exceptions or new GC's - that's an immovable
// rock we're faced with.
//
// The key differences are:
//
// ENABLE_FORBID tokenNotToLoad
// -------------------------------------------- ------------------------------------------------------
// caller must guarantee the type is already caller does not have to guarantee the type
// loaded - otherwise, we will crash badly. is already loaded.
//
// loader will not throw, trigger gc or OOM loader may throw, trigger GC or OOM.
//
//
//
#ifdef ENABLE_CONTRACTS_IMPL
#define ENABLE_FORBID_GC_LOADER_USE_IN_THIS_SCOPE() GCForbidLoaderUseHolder __gcfluh; \
CANNOTTHROWCOMPLUSEXCEPTION(); \
GCX_NOTRIGGER(); \
FAULT_FORBID();
#else // _DEBUG_IMPL
#define ENABLE_FORBID_GC_LOADER_USE_IN_THIS_SCOPE() ;
#endif // _DEBUG_IMPL
// This macro lets us define a conditional CONTRACT for the GC_TRIGGERS behavior.
// This is for the benefit of a select group of callers that use the loader
// in ForbidGC mode strictly to retrieve existing TypeHandles. The reason
// we use a threadstate rather than an extra parameter is that these annoying
// callers call the loader through intermediaries (MetaSig) and it proved to be too
// cumbersome to pass this state down through all those callers.
//
// Don't make GC_TRIGGERS conditional just because your function ends up calling
// LoadTypeHandle indirectly. We don't want to proliferate conditonal contracts more
// than necessary so declare such functions as GC_TRIGGERS until the need
// for the conditional contract is actually proven through code inspection or
// coverage.
#if defined(DACCESS_COMPILE)
// Disable (<non-zero constant> || <expression>) is always a non-zero constant.
// <expression> is never evaluated and might have side effects, because
// FORBIDGC_LOADER_USE_ENABLED is used in that pattern and additionally the rule
// has little value.
#ifdef _PREFAST_
#pragma warning(disable:6286)
#endif
#define FORBIDGC_LOADER_USE_ENABLED() true
#else // DACCESS_COMPILE
#if defined (_DEBUG_IMPL) || defined(_PREFAST_)
#ifndef DACCESS_COMPILE
#define FORBIDGC_LOADER_USE_ENABLED() (ClrFlsGetValue(TlsIdx_ForbidGCLoaderUseCount))
#else
#define FORBIDGC_LOADER_USE_ENABLED() TRUE
#endif
#else // _DEBUG_IMPL
// If you got an error about FORBIDGC_LOADER_USE_ENABLED being undefined, it's because you tried
// to use this predicate in a free build outside of a CONTRACT or ASSERT.
//
#define FORBIDGC_LOADER_USE_ENABLED() (sizeof(YouCannotUseThisHere) != 0)
#endif // _DEBUG_IMPL
#endif // DACCESS_COMPILE
#ifdef FEATURE_STACK_PROBE
#ifdef _DEBUG_IMPL
inline void NO_FORBIDGC_LOADER_USE_ThrowSO()
{
WRAPPER_NO_CONTRACT;
if (FORBIDGC_LOADER_USE_ENABLED())
{
//if you hitting this assert maybe a failure was injected at the place
// it won't occur in a real-world scenario, see VSW 397871
// then again maybe it 's a bug at the place FORBIDGC_LOADER_USE_ENABLED was set
_ASSERTE(!"Unexpected SO, please read the comment");
}
else
COMPlusThrowSO();
}
#else
inline void NO_FORBIDGC_LOADER_USE_ThrowSO()
{
COMPlusThrowSO();
}
#endif
#endif
// There is an MDA which can detect illegal reentrancy into the CLR. For instance, if you call managed
// code from a native vectored exception handler, this might cause a reverse PInvoke to occur. But if the
// exception was triggered from code that was executing in cooperative GC mode, we now have GC holes and
// general corruption.
BOOL HasIllegalReentrancy();
// This class can be used to "schedule" a culture setting,
// kicking in when leaving scope or during exception unwinding.
// Note: during destruction, this can throw. You have been warned.
class ReturnCultureHolder
{
public:
ReturnCultureHolder(Thread* pThread, OBJECTREF* culture, BOOL bUICulture)
{
CONTRACTL
{
WRAPPER(NOTHROW);
WRAPPER(GC_NOTRIGGER);
MODE_COOPERATIVE;
PRECONDITION(CheckPointer(pThread));
}
CONTRACTL_END;
m_pThread = pThread;
m_culture = culture;
m_bUICulture = bUICulture;
m_acquired = TRUE;
}
FORCEINLINE void SuppressRelease()
{
m_acquired = FALSE;
}
~ReturnCultureHolder()
{
CONTRACTL
{
WRAPPER(THROWS);
WRAPPER(GC_TRIGGERS);
MODE_COOPERATIVE;
}
CONTRACTL_END;
if (m_acquired)
m_pThread->SetCulture(m_culture, m_bUICulture);
}
private:
ReturnCultureHolder()
{
LIMITED_METHOD_CONTRACT;
}
Thread* m_pThread;
OBJECTREF* m_culture;
BOOL m_bUICulture;
BOOL m_acquired;
};
//
// _pThread: (Thread*) current Thread
// _pCurrDomain: (AppDomain*) current AppDomain
// _pDestDomain: (AppDomain*) AppDomain to transition to
// _predicate_expr: (bool) Expression to predicate the transition. If this is true, we transition,
// otherwise we don't. WARNING : if you change this macro, be sure you
// guarantee that this macro argument is only evaluated once.
//
//
// @TODO: can't we take the transition with a holder?
//
#define ENTER_DOMAIN_SETUPVARS(_pThread, _predicate_expr) \
{ \
DEBUG_ASSURE_NO_RETURN_BEGIN(DOMAIN) \
\
Thread* _ctx_trans_pThread = (_pThread); \
bool _ctx_trans_fTransitioned = false; \
bool _ctx_trans_fPredicate = (_predicate_expr); \
bool _ctx_trans_fRaiseNeeded = false; \
Exception* _ctx_trans_pTargetDomainException=NULL; \
ADID _ctx_trans_pDestDomainId=ADID(0); \
FrameWithCookie<ContextTransitionFrame> _ctx_trans_Frame; \
ContextTransitionFrame* _ctx_trans_pFrame = &_ctx_trans_Frame; \
#define ENTER_DOMAIN_SWITCH_CTX_BY_ADID(_pCurrDomainPtr,_pDestDomainId,_bUnsafePoint) \
AppDomain* _ctx_trans_pCurrDomain=_pCurrDomainPtr; \
_ctx_trans_pDestDomainId=(ADID)_pDestDomainId; \
BOOL _ctx_trans_bUnsafePoint=_bUnsafePoint; \
if (_ctx_trans_fPredicate && \
(_ctx_trans_pCurrDomain==NULL || \
(_ctx_trans_pCurrDomain->GetId() != _ctx_trans_pDestDomainId))) \
{ \
AppDomainFromIDHolder _ctx_trans_ad(_ctx_trans_pDestDomainId,_ctx_trans_bUnsafePoint); \
_ctx_trans_ad.ThrowIfUnloaded(); \
\
_ctx_trans_ad->EnterContext(_ctx_trans_pThread, \
_ctx_trans_ad->GetDefaultContext(), \
_ctx_trans_pFrame); \
\
_ctx_trans_ad.Release(); \
_ctx_trans_fTransitioned = true; \
}
#define ENTER_DOMAIN_SWITCH_CTX_BY_ADPTR(_pCurrDomain,_pDestDomain) \
AppDomain* _ctx_trans_pCurrDomain=_pCurrDomain; \
AppDomain* _ctx_trans_pDestDomain=_pDestDomain; \
_ctx_trans_pDestDomainId=_ctx_trans_pDestDomain->GetId(); \
\
if (_ctx_trans_fPredicate && (_ctx_trans_pCurrDomain != _ctx_trans_pDestDomain)) \
{ \
TESTHOOKCALL(AppDomainCanBeUnloaded(_ctx_trans_pDestDomain->GetId().m_dwId,FALSE)); \
GCX_FORBID(); \
if (!_ctx_trans_pDestDomain->CanThreadEnter(_ctx_trans_pThread)) \
COMPlusThrow(kAppDomainUnloadedException); \
\
_ctx_trans_pThread->EnterContextRestricted( \
_ctx_trans_pDestDomain->GetDefaultContext(), \
_ctx_trans_pFrame); \
\
_ctx_trans_fTransitioned = true; \
}
#define ENTER_DOMAIN_SETUP_EH \
/* work around unreachable code warning */ \
SCAN_BLOCKMARKER_N(DOMAIN); \
if (true) EX_TRY \
{ \
SCAN_BLOCKMARKER_MARK_N(DOMAIN); \
LOG((LF_APPDOMAIN, LL_INFO1000, "ENTER_DOMAIN(%s, %s, %d): %s\n", \
__FUNCTION__, __FILE__, __LINE__, \
_ctx_trans_fTransitioned ? "ENTERED" : "NOP"));
// Note: we go to preemptive mode before the EX_RETHROW Going preemp here is safe, since there are many other paths in
// this macro that toggle the GC mode, too.
#define END_DOMAIN_TRANSITION \
TESTHOOKCALL(LeavingAppDomain(::GetAppDomain()->GetId().m_dwId)); \
} \
EX_CATCH \
{ \
SCAN_BLOCKMARKER_USE_N(DOMAIN); \
LOG((LF_EH|LF_APPDOMAIN, LL_INFO1000, "ENTER_DOMAIN(%s, %s, %d): exception in flight\n", \
__FUNCTION__, __FILE__, __LINE__)); \
\
if (!_ctx_trans_fTransitioned) \
{ \
if (_ctx_trans_pThread->PreemptiveGCDisabled()) \
{ \
_ctx_trans_pThread->EnablePreemptiveGC(); \
} \
\
EX_RETHROW; \
} \
\
\
_ctx_trans_pTargetDomainException=EXTRACT_EXCEPTION(); \
\
/* Save Watson buckets before the exception object is changed */ \
CAPTURE_BUCKETS_AT_TRANSITION(_ctx_trans_pThread, GET_THROWABLE()); \
\
_ctx_trans_fRaiseNeeded = true; \
SCAN_BLOCKMARKER_END_USE_N(DOMAIN); \
} \
/* SwallowAllExceptions is fine because we don't get to this point */ \
/* unless fRaiseNeeded = true or no exception was thrown */ \
EX_END_CATCH(SwallowAllExceptions); \
\
if (_ctx_trans_fRaiseNeeded) \
{ \
SCAN_BLOCKMARKER_USE_N(DOMAIN); \
LOG((LF_EH, LL_INFO1000, "RaiseCrossContextException(%s, %s, %d)\n", \
__FUNCTION__, __FILE__, __LINE__)); \
_ctx_trans_pThread->RaiseCrossContextException(_ctx_trans_pTargetDomainException, _ctx_trans_pFrame); \
} \
\
LOG((LF_APPDOMAIN, LL_INFO1000, "LEAVE_DOMAIN(%s, %s, %d)\n", \
__FUNCTION__, __FILE__, __LINE__)); \
\
if (_ctx_trans_fTransitioned) \
{ \
GCX_FORBID(); \
_ctx_trans_pThread->ReturnToContext(_ctx_trans_pFrame); \
} \
TESTHOOKCALL(LeftAppDomain(_ctx_trans_pDestDomainId.m_dwId)); \
DEBUG_ASSURE_NO_RETURN_END(DOMAIN) \
}
//current ad, always safe
#define ADV_CURRENTAD 0
//default ad, never unloaded
#define ADV_DEFAULTAD 1
// held by iterator, iterator holds a ref
#define ADV_ITERATOR 2
// the appdomain is on the stack
#define ADV_RUNNINGIN 4
// we're in process of creating the appdomain, refcount guaranteed to be >0
#define ADV_CREATING 8
// compilation domain - ngen guarantees it won't be unloaded until everyone left
#define ADV_COMPILATION 0x10
// finalizer thread - synchronized with ADU
#define ADV_FINALIZER 0x40
// adu thread - cannot race with itself
#define ADV_ADUTHREAD 0x80
// held by AppDomainRefTaker
#define ADV_REFTAKER 0x100
#ifdef _DEBUG
void CheckADValidity(AppDomain* pDomain, DWORD ADValidityKind);
#else
#define CheckADValidity(pDomain,ADValidityKind)
#endif
// Please keep these macros in sync with the NO_EH_AT_TRANSITION macros below.
#define ENTER_DOMAIN_ID_PREDICATED(_pDestDomain,_predicate_expr) \
TESTHOOKCALL(EnteringAppDomain(_pDestDomain.m_dwId)) ; \
ENTER_DOMAIN_SETUPVARS(GetThread(), _predicate_expr) \
ENTER_DOMAIN_SWITCH_CTX_BY_ADID(_ctx_trans_pThread->GetDomain(), _pDestDomain, FALSE) \
ENTER_DOMAIN_SETUP_EH \
TESTHOOKCALL(EnteredAppDomain(_pDestDomain.m_dwId));
#define ENTER_DOMAIN_PTR_PREDICATED(_pDestDomain,ADValidityKind,_predicate_expr) \
TESTHOOKCALL(EnteringAppDomain((_pDestDomain)->GetId().m_dwId)); \
ENTER_DOMAIN_SETUPVARS(GetThread(), _predicate_expr) \
CheckADValidity(_ctx_trans_fPredicate?(_pDestDomain):GetAppDomain(),ADValidityKind); \
ENTER_DOMAIN_SWITCH_CTX_BY_ADPTR(_ctx_trans_pThread->GetDomain(), _pDestDomain) \
ENTER_DOMAIN_SETUP_EH \
TESTHOOKCALL(EnteredAppDomain((_pDestDomain)->GetId().m_dwId));
#define ENTER_DOMAIN_PTR(_pDestDomain,ADValidityKind) \
TESTHOOKCALL(EnteringAppDomain((_pDestDomain)->GetId().m_dwId)); \
CheckADValidity(_pDestDomain,ADValidityKind); \
ENTER_DOMAIN_SETUPVARS(GetThread(), true) \
ENTER_DOMAIN_SWITCH_CTX_BY_ADPTR(_ctx_trans_pThread->GetDomain(), _pDestDomain) \
ENTER_DOMAIN_SETUP_EH \
TESTHOOKCALL(EnteredAppDomain((_pDestDomain)->GetId().m_dwId));
#define ENTER_DOMAIN_ID(_pDestDomain) \
ENTER_DOMAIN_ID_PREDICATED(_pDestDomain,true)
// <EnableADTransitionWithoutEH>
// The following macros support the AD transition *without* using EH at transition boundary.
// Please keep them in sync with the macros above.
#define ENTER_DOMAIN_PTR_NO_EH_AT_TRANSITION(_pDestDomain,ADValidityKind) \
TESTHOOKCALL(EnteringAppDomain((_pDestDomain)->GetId().m_dwId)); \
CheckADValidity(_pDestDomain,ADValidityKind); \
ENTER_DOMAIN_SETUPVARS(GetThread(), true) \
ENTER_DOMAIN_SWITCH_CTX_BY_ADPTR(_ctx_trans_pThread->GetDomain(), _pDestDomain) \
TESTHOOKCALL(EnteredAppDomain((_pDestDomain)->GetId().m_dwId)); \
ReturnToPreviousAppDomainHolder __returnToPreviousAppDomainHolder;
#define ENTER_DOMAIN_ID_NO_EH_AT_TRANSITION_PREDICATED(_pDestDomain,_predicate_expr) \
TESTHOOKCALL(EnteringAppDomain(_pDestDomain.m_dwId)) ; \
ENTER_DOMAIN_SETUPVARS(GetThread(), _predicate_expr) \
ENTER_DOMAIN_SWITCH_CTX_BY_ADID(_ctx_trans_pThread->GetDomain(), _pDestDomain, FALSE) \
TESTHOOKCALL(EnteredAppDomain(_pDestDomain.m_dwId)); \
ReturnToPreviousAppDomainHolder __returnToPreviousAppDomainHolder;
#define ENTER_DOMAIN_ID_NO_EH_AT_TRANSITION(_pDestDomain) \
ENTER_DOMAIN_ID_NO_EH_AT_TRANSITION_PREDICATED(_pDestDomain,true)
#define END_DOMAIN_TRANSITION_NO_EH_AT_TRANSITION \
TESTHOOKCALL(LeavingAppDomain(::GetAppDomain()->GetId().m_dwId)); \
LOG((LF_APPDOMAIN, LL_INFO1000, "LEAVE_DOMAIN(%s, %s, %d)\n", \
__FUNCTION__, __FILE__, __LINE__)); \
\
if (_ctx_trans_fTransitioned) \
{ \
GCX_FORBID(); \
_ctx_trans_pThread->ReturnToContext(_ctx_trans_pFrame); \
} \
__returnToPreviousAppDomainHolder.SuppressRelease(); \
TESTHOOKCALL(LeftAppDomain(_ctx_trans_pDestDomainId.m_dwId)); \
DEBUG_ASSURE_NO_RETURN_END(DOMAIN) \
} // Close scope setup by ENTER_DOMAIN_SETUPVARS
// </EnableADTransitionWithoutEH>
#define GET_CTX_TRANSITION_FRAME() \
(_ctx_trans_pFrame)
//-----------------------------------------------------------------------------
// System to make Cross-Appdomain calls.
//
// Cross-AppDomain calls are made via a callback + args. This gives us the flexibility
// to check if a transition is needed, and take fast vs. slow paths for the debugger.
//
// Example usage:
// struct FooArgs : public CtxTransitionBaseArgs { ... } args (...); // load up args
// MakeCallWithPossibleAppDomainTransition(pNewDomain, MyFooFunc, &args);
//
// MyFooFunc is always executed in pNewDomain.
// If we're already in pNewDomain, then that just becomes MyFooFunc(&args);
// else we'll switch ADs, and do the proper Try/Catch/Rethrow.
//-----------------------------------------------------------------------------
// All Arg structs should derive from this. This makes certain standard args
// are available (such as the context-transition frame).
// The ADCallback helpers will fill in these base args.
struct CtxTransitionBaseArgs;
// Pointer type for the AppDomain callback function.
typedef void (*FPAPPDOMAINCALLBACK)(
CtxTransitionBaseArgs* pData // Caller's private data
);
//-----------------------------------------------------------------------------
// Call w/a wrapper.
// We've already transitioned AppDomains here. This just places a 1st-pass filter to sniff
// for catch-handler found callbacks for the debugger.
//-----------------------------------------------------------------------------
void MakeADCallDebuggerWrapper(
FPAPPDOMAINCALLBACK fpCallback,
CtxTransitionBaseArgs * args,
ContextTransitionFrame* pFrame);
// Invoke a callback in another appdomain.
// Caller should have checked that we're actually transitioning domains here.
void MakeCallWithAppDomainTransition(
ADID pTargetDomain,
FPAPPDOMAINCALLBACK fpCallback,
CtxTransitionBaseArgs * args);
// Invoke the callback in the AppDomain.
// Ensure that predicate only gets evaluted once!!
#define MakePredicatedCallWithPossibleAppDomainTransition(pTargetDomain, fPredicate, fpCallback, args) \
{ \
Thread* _ctx_trans_pThread = GetThread(); \
_ASSERTE(_ctx_trans_pThread != NULL); \
ADID _ctx_trans_pCurrDomain = _ctx_trans_pThread->GetDomain()->GetId(); \
ADID _ctx_trans_pDestDomain = (pTargetDomain); \
\
if (fPredicate && (_ctx_trans_pCurrDomain != _ctx_trans_pDestDomain)) \
{ \
/* Transition domains and make the call */ \
MakeCallWithAppDomainTransition(pTargetDomain, (FPAPPDOMAINCALLBACK) fpCallback, args); \
} \
else \
{ \
/* No transition needed. Just call directly. */ \
(fpCallback)(args); \
}\
}
// Invoke the callback in the AppDomain.
#define MakeCallWithPossibleAppDomainTransition(pTargetDomain, fpCallback, args) \
MakePredicatedCallWithPossibleAppDomainTransition(pTargetDomain, true, fpCallback, args)
struct CtxTransitionBaseArgs
{
// This function fills out the private base args.
friend void MakeCallWithAppDomainTransition(
ADID pTargetDomain,
FPAPPDOMAINCALLBACK fpCallback,
CtxTransitionBaseArgs * args);
public:
CtxTransitionBaseArgs() { pCtxFrame = NULL; }
// This will be NULL if we didn't actually transition.
ContextTransitionFrame* GetCtxTransitionFrame() { return pCtxFrame; }
private:
ContextTransitionFrame* pCtxFrame;
};
// We have numerous places where we start up a managed thread. This includes several places in the
// ThreadPool, the 'new Thread(...).Start()' case, and the Finalizer. Try to factor the code so our
// base exception handling behavior is consistent across those places. The resulting code is convoluted,
// but it's better than the prior situation of each thread being on a different plan.
// If you add a new kind of managed thread (i.e. thread proc) to the system, you must:
//
// 1) Call HasStarted() before calling any ManagedThreadBase_* routine.
// 2) Define a ManagedThreadBase_* routine for your scenario and declare it below.
// 3) Always perform any AD transitions through the ManagedThreadBase_* mechanism.
// 4) Allow the ManagedThreadBase_* mechanism to perform all your exception handling, including
// dispatching of unhandled exception events, deciding what to swallow, etc.
// 5) If you must separate your base thread proc behavior from your AD transitioning behavior,
// define a second ManagedThreadADCall_* helper and declare it below.
// 6) Never decide this is too much work and that you will roll your own thread proc code.
// intentionally opaque.
struct ManagedThreadCallState;
struct ManagedThreadBase
{
// The 'new Thread(...).Start()' case from COMSynchronizable kickoff thread worker
static void KickOff(ADID pAppDomain,
Context::ADCallBackFcnType pTarget,
LPVOID args);
// The IOCompletion, QueueUserWorkItem, AddTimer, RegisterWaitForSingleObject cases in
// the ThreadPool
static void ThreadPool(ADID pAppDomain, Context::ADCallBackFcnType pTarget, LPVOID args);
// The Finalizer thread separates the tasks of establishing exception handling at its
// base and transitioning into AppDomains. The turnaround structure that ties the 2 calls together
// is the ManagedThreadCallState.
// For the case (like Finalization) where the base transition and the AppDomain transition are
// separated, an opaque structure is used to tie together the two calls.
static void FinalizerBase(Context::ADCallBackFcnType pTarget);
static void FinalizerAppDomain(AppDomain* pAppDomain,
Context::ADCallBackFcnType pTarget,
LPVOID args,
ManagedThreadCallState *pTurnAround);
};
// DeadlockAwareLock is a base for building deadlock-aware locks.
// Note that DeadlockAwareLock only works if ALL locks involved in the deadlock are deadlock aware.
class DeadlockAwareLock
{
private:
VolatilePtr<Thread> m_pHoldingThread;
#ifdef _DEBUG
const char *m_description;
#endif
public:
DeadlockAwareLock(const char *description = NULL);
~DeadlockAwareLock();
// Test for deadlock
BOOL CanEnterLock();
// Call BeginEnterLock before attempting to acquire the lock
BOOL TryBeginEnterLock(); // returns FALSE if deadlock
void BeginEnterLock(); // Asserts if deadlock
// Call EndEnterLock after acquiring the lock
void EndEnterLock();
// Call LeaveLock after releasing the lock
void LeaveLock();
const char *GetDescription();
private:
CHECK CheckDeadlock(Thread *pThread);
static void ReleaseBlockingLock()
{
Thread *pThread = GetThread();
_ASSERTE (pThread);
pThread->m_pBlockingLock = NULL;
}
public:
typedef StateHolder<DoNothing,DeadlockAwareLock::ReleaseBlockingLock> BlockingLockHolder;
};
inline Context* GetCurrentContext()
{
CONTRACTL {
SO_TOLERANT;
NOTHROW;
GC_NOTRIGGER;
}
CONTRACTL_END;
return GetThread()->GetContext();
}
inline void SetTypeHandleOnThreadForAlloc(TypeHandle th)
{
// We are doing this unconditionally even though th is only used by ETW events in GC. When the ETW
// event is not enabled we still need to set it because it may not be enabled here but by the
// time we are checking in GC, the event is enabled - we don't want GC to read a random value
// from before in this case.
GetThread()->SetTHAllocContextObj(th);
}
#endif // CROSSGEN_COMPILE
class Compiler;
// users of OFFSETOF__TLS__tls_CurrentThread macro expect the offset of these variables wrt to _tls_start to be stable.
// Defining each of the following thread local variable separately without the struct causes the offsets to change in
// different flavors of build. Eg. in chk build the offset of m_pThread is 0x4 while in ret build it becomes 0x8 as 0x4 is
// occupied by m_pAddDomain. Packing all thread local variables in a struct and making struct instance to be thread local
// ensures that the offsets of the variables are stable in all build flavors.
struct ThreadLocalInfo
{
Thread* m_pThread;
AppDomain* m_pAppDomain;
void** m_EETlsData; // ClrTlsInfo::data
};
class ThreadStateHolder
{
public:
ThreadStateHolder (BOOL fNeed, DWORD state)
{
LIMITED_METHOD_CONTRACT;
_ASSERTE (GetThread());
m_fNeed = fNeed;
m_state = state;
}
~ThreadStateHolder ()
{
LIMITED_METHOD_CONTRACT;
if (m_fNeed)
{
Thread *pThread = GetThread();
_ASSERTE (pThread);
FastInterlockAnd((ULONG *) &pThread->m_State, ~m_state);
}
}
private:
BOOL m_fNeed;
DWORD m_state;
};
// Sets an NC threadstate if not already set, and restores the old state
// of that bit upon destruction
// fNeed > 0, make sure state is set, restored in destructor
// fNeed = 0, no change
// fNeed < 0, make sure state is reset, restored in destructor
class ThreadStateNCStackHolder
{
public:
ThreadStateNCStackHolder (BOOL fNeed, Thread::ThreadStateNoConcurrency state)
{
LIMITED_METHOD_CONTRACT;
_ASSERTE (GetThread());
m_fNeed = fNeed;
m_state = state;
if (fNeed)
{
Thread *pThread = GetThread();
_ASSERTE (pThread);
if (fNeed < 0)
{
// if the state is set, reset it
if (pThread->HasThreadStateNC(state))
{
pThread->ResetThreadStateNC(m_state);
}
else
{
m_fNeed = FALSE;
}
}
else
{
// if the state is already set then no change is
// necessary during the back out
if(pThread->HasThreadStateNC(state))
{
m_fNeed = FALSE;
}
else
{
pThread->SetThreadStateNC(state);
}
}
}
}
~ThreadStateNCStackHolder()
{
LIMITED_METHOD_CONTRACT;
if (m_fNeed)
{
Thread *pThread = GetThread();
_ASSERTE (pThread);
if (m_fNeed < 0)
{
pThread->SetThreadStateNC(m_state); // set it
}
else
{
pThread->ResetThreadStateNC(m_state);
}
}
}
private:
BOOL m_fNeed;
Thread::ThreadStateNoConcurrency m_state;
};
BOOL Debug_IsLockedViaThreadSuspension();
#endif //__threads_h__
|