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
|
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
//
//
#include "common.h"
#ifndef FEATURE_PAL
#include "securityprincipal.h"
#endif // !FEATURE_PAL
#ifdef WIN64EXCEPTIONS
#include "exceptionhandling.h"
#include "dbginterface.h"
#include "asmconstants.h"
#include "eetoprofinterfacewrapper.inl"
#include "eedbginterfaceimpl.inl"
#include "perfcounters.h"
#include "eventtrace.h"
#ifndef DACCESS_COMPILE
// o Functions and funclets are tightly associated. In fact, they are laid out in contiguous memory.
// They also present some interesting issues with respect to EH because we will see callstacks with
// both functions and funclets, but need to logically treat them as the original single IL function
// described them.
//
// o All funclets are ripped out of line from the main function. Finally clause are pulled out of
// line and replaced by calls to the funclets. Catch clauses, however, are simply pulled out of
// line. !!!This causes a loss of nesting information in clause offsets.!!! A canonical example of
// two different functions which look identical due to clause removal is as shown in the code
// snippets below. The reason they look identical in the face of out-of-line funclets is that the
// region bounds for the "try A" region collapse and become identical to the region bounds for
// region "try B". This will look identical to the region information for Bar because Bar must
// have a separate entry for each catch clause, both of which will have the same try-region bounds.
//
// void Foo() void Bar()
// { {
// try A try C
// { {
// try B BAR_BLK_1
// { }
// FOO_BLK_1 catch C
// } {
// catch B BAR_BLK_2
// { }
// FOO_BLK_2 catch D
// } {
// } BAR_BLK_3
// catch A }
// { }
// FOO_BLK_3
// }
// }
//
// O The solution is to duplicate all clauses that logically cover the funclet in its parent
// method, but with the try-region covering the entire out-of-line funclet code range. This will
// differentiate the canonical example above because the CatchB funclet will have a try-clause
// covering it whose associated handler is CatchA. In Bar, there is no such duplication of any clauses.
//
// o The behavior of the personality routine depends upon the JIT to properly order the clauses from
// inside-out. This allows us to properly handle a situation where our control PC is covered by clauses
// that should not be considered because a more nested clause will catch the exception and resume within
// the scope of the outer clauses.
//
// o This sort of clause duplication for funclets should be done for all clause types, not just catches.
// Unfortunately, I cannot articulate why at the moment.
//
#ifdef _DEBUG
void DumpClauses(IJitManager* pJitMan, const METHODTOKEN& MethToken, UINT_PTR uMethodStartPC, UINT_PTR dwControlPc);
static void DoEHLog(DWORD lvl, __in_z char *fmt, ...);
#define EH_LOG(expr) { DoEHLog expr ; }
#else
#define EH_LOG(expr)
#endif
TrackerAllocator g_theTrackerAllocator;
void __declspec(noinline)
ClrUnwindEx(EXCEPTION_RECORD* pExceptionRecord,
UINT_PTR ReturnValue,
UINT_PTR TargetIP,
UINT_PTR TargetFrameSp);
bool FixNonvolatileRegisters(UINT_PTR uOriginalSP,
Thread* pThread,
CONTEXT* pContextRecord,
bool fAborting
);
MethodDesc * GetUserMethodForILStub(Thread * pThread, UINT_PTR uStubSP, MethodDesc * pILStubMD, Frame ** ppFrameOut);
static ExceptionTracker* GetTrackerMemory()
{
CONTRACTL
{
GC_TRIGGERS;
NOTHROW;
MODE_ANY;
}
CONTRACTL_END;
return g_theTrackerAllocator.GetTrackerMemory();
}
static void FreeTrackerMemory(ExceptionTracker* pTracker, TrackerMemoryType mem)
{
CONTRACTL
{
GC_NOTRIGGER;
NOTHROW;
MODE_ANY;
}
CONTRACTL_END;
if (mem & memManaged)
{
pTracker->ReleaseResources();
}
if (mem & memUnmanaged)
{
g_theTrackerAllocator.FreeTrackerMemory(pTracker);
}
}
static inline void UpdatePerformanceMetrics(CrawlFrame *pcfThisFrame, BOOL bIsRethrownException, BOOL bIsNewException)
{
WRAPPER_NO_CONTRACT;
COUNTER_ONLY(GetPerfCounters().m_Excep.cThrown++);
// Fire an exception thrown ETW event when an exception occurs
ETW::ExceptionLog::ExceptionThrown(pcfThisFrame, bIsRethrownException, bIsNewException);
}
void InitializeExceptionHandling()
{
EH_LOG((LL_INFO100, "InitializeExceptionHandling(): ExceptionTracker size: 0x%x bytes\n", sizeof(ExceptionTracker)));
InitSavedExceptionInfo();
CLRAddVectoredHandlers();
g_theTrackerAllocator.Init();
// Initialize the lock used for synchronizing access to the stacktrace in the exception object
g_StackTraceArrayLock.Init(LOCK_TYPE_DEFAULT, TRUE);
}
struct UpdateObjectRefInResumeContextCallbackState
{
UINT_PTR uResumeSP;
Frame *pHighestFrameWithRegisters;
TADDR uResumeFrameFP;
TADDR uICFCalleeSavedFP;
#ifdef _DEBUG
UINT nFrames;
bool fFound;
#endif
};
// Stack unwind callback for UpdateObjectRefInResumeContext().
StackWalkAction UpdateObjectRefInResumeContextCallback(CrawlFrame* pCF, LPVOID pData)
{
CONTRACTL
{
MODE_ANY;
NOTHROW;
GC_NOTRIGGER;
}
CONTRACTL_END;
UpdateObjectRefInResumeContextCallbackState *pState = (UpdateObjectRefInResumeContextCallbackState*)pData;
CONTEXT* pSrcContext = pCF->GetRegisterSet()->pCurrentContext;
INDEBUG(pState->nFrames++);
// Check to see if we have reached the resume frame.
if (pCF->IsFrameless())
{
// At this point, we are trying to find the managed frame containing the catch handler to be invoked.
// This is done by comparing the SP of the managed frame for which this callback was invoked with the
// SP the OS passed to our personality routine for the current managed frame. If they match, then we have
// reached the target frame.
//
// It is possible that a managed frame may execute a PInvoke after performing a stackalloc:
//
// 1) The Evanesco JIT will always inline the PInvoke in the managed frame, whether or not the frame
// contains EH. As a result, the ICF will live in the same frame which performs stackalloc.
//
// 2) JIT64 will only inline the PInvoke in the managed frame if the frame *does not* contain EH. If it does,
// then pinvoke will be performed via an ILStub and thus, stackalloc will be performed in a frame different
// from the one (ILStub) that contains the ICF.
//
// Thus, for the scenario where the catch handler lives in the frame that performed stackalloc, in case of
// Evanesco JIT, the SP returned by the OS will be the SP *after* the stackalloc has happened. However,
// the stackwalker will invoke this callback with the CrawlFrameSP that was initialized at the time ICF was setup, i.e.,
// it will be the SP after the prolog has executed (refer to InlinedCallFrame::UpdateRegDisplay).
//
// Thus, checking only the SP will not work for this scenario when using the Evanesco JIT.
//
// To address this case, the callback data also contains the frame pointer (FP) passed by the OS. This will
// be the value that is saved in the "CalleeSavedFP" field of the InlinedCallFrame during ICF
// initialization. When the stackwalker sees an ICF and invokes this callback, we copy the value of "CalleeSavedFP" in the data
// structure passed to this callback.
//
// Later, when the stackwalker invokes the callback for the managed frame containing the ICF, and the check
// for SP comaprison fails, we will compare the FP value we got from the ICF with the FP value the OS passed
// to us. If they match, then we have reached the resume frame.
//
// Note: This problem/scenario is not applicable to JIT64 since it does not perform pinvoke inlining if the
// method containing pinvoke also contains EH. Thus, the SP check will never fail for it.
if (pState->uResumeSP == GetSP(pSrcContext))
{
INDEBUG(pState->fFound = true);
return SWA_ABORT;
}
// Perform the FP check, as explained above.
if ((pState->uICFCalleeSavedFP !=0) && (pState->uICFCalleeSavedFP == pState->uResumeFrameFP))
{
// FP from ICF is the one that was also copied to the FP register in InlinedCallFrame::UpdateRegDisplay.
_ASSERTE(pState->uICFCalleeSavedFP == GetFP(pSrcContext));
INDEBUG(pState->fFound = true);
return SWA_ABORT;
}
// Reset the ICF FP in callback data
pState->uICFCalleeSavedFP = 0;
}
else
{
Frame *pFrame = pCF->GetFrame();
if (pFrame->NeedsUpdateRegDisplay())
{
CONSISTENCY_CHECK(pFrame >= pState->pHighestFrameWithRegisters);
pState->pHighestFrameWithRegisters = pFrame;
// Is this an InlinedCallFrame?
if (pFrame->GetVTablePtr() == InlinedCallFrame::GetMethodFrameVPtr())
{
// If we are here, then ICF is expected to be active.
_ASSERTE(InlinedCallFrame::FrameHasActiveCall(pFrame));
// Copy the CalleeSavedFP to the data structure that is passed this callback
// by the stackwalker. This is the value of frame pointer when ICF is setup
// in a managed frame.
//
// Setting this value here is based upon the assumption (which holds true on X64 and ARM) that
// the stackwalker invokes the callback for explicit frames before their
// container/corresponding managed frame.
pState->uICFCalleeSavedFP = ((PTR_InlinedCallFrame)pFrame)->GetCalleeSavedFP();
}
else
{
// For any other frame, simply reset uICFCalleeSavedFP field
pState->uICFCalleeSavedFP = 0;
}
}
}
return SWA_CONTINUE;
}
//
// Locates the locations of the nonvolatile registers. This will be used to
// retrive the latest values of the object references before we resume
// execution from an exception.
//
//static
bool ExceptionTracker::FindNonvolatileRegisterPointers(Thread* pThread, UINT_PTR uOriginalSP, REGDISPLAY* pRegDisplay, TADDR uResumeFrameFP)
{
CONTRACTL
{
MODE_ANY;
NOTHROW;
GC_NOTRIGGER;
}
CONTRACTL_END;
//
// Find the highest frame below the resume frame that will update the
// REGDISPLAY. A normal StackWalkFrames will RtlVirtualUnwind through all
// managed frames on the stack, so this avoids some unnecessary work. The
// frame we find will have all of the nonvolatile registers/other state
// needed to start a managed unwind from that point.
//
Frame *pHighestFrameWithRegisters = NULL;
Frame *pFrame = pThread->GetFrame();
while ((UINT_PTR)pFrame < uOriginalSP)
{
if (pFrame->NeedsUpdateRegDisplay())
pHighestFrameWithRegisters = pFrame;
pFrame = pFrame->Next();
}
//
// Do a stack walk from this frame. This may find a higher frame within
// the resume frame (ex. inlined pinvoke frame). This will also update
// the REGDISPLAY pointers if any intervening managed frames saved
// nonvolatile registers.
//
UpdateObjectRefInResumeContextCallbackState state;
state.uResumeSP = uOriginalSP;
state.uResumeFrameFP = uResumeFrameFP;
state.uICFCalleeSavedFP = 0;
state.pHighestFrameWithRegisters = pHighestFrameWithRegisters;
INDEBUG(state.nFrames = 0);
INDEBUG(state.fFound = false);
pThread->StackWalkFramesEx(pRegDisplay, &UpdateObjectRefInResumeContextCallback, &state, 0, pHighestFrameWithRegisters);
// For managed exceptions, we should at least find a HelperMethodFrame (the one we put in IL_Throw()).
// For native exceptions such as AV's, we should at least find the FaultingExceptionFrame.
// If we don't find anything, then we must have hit an SO when we are trying to erect an HMF.
// Bail out in such situations.
//
// Note that pinvoke frames may be inlined in a managed method, so we cannot use the child SP (a.k.a. the current SP)
// to check for explicit frames "higher" on the stack ("higher" here means closer to the leaf frame). The stackwalker
// knows how to deal with inlined pinvoke frames, and it issues callbacks for them before issuing the callback for the
// containing managed method. So we have to do this check after we are done with the stackwalk.
pHighestFrameWithRegisters = state.pHighestFrameWithRegisters;
if (pHighestFrameWithRegisters == NULL)
{
return false;
}
CONSISTENCY_CHECK(state.nFrames);
CONSISTENCY_CHECK(state.fFound);
CONSISTENCY_CHECK(NULL != pHighestFrameWithRegisters);
//
// Now the REGDISPLAY has been unwound to the resume frame. The
// nonvolatile registers will either point into pHighestFrameWithRegisters,
// an inlined pinvoke frame, or into calling managed frames.
//
return true;
}
//static
void ExceptionTracker::UpdateNonvolatileRegisters(CONTEXT *pContextRecord, REGDISPLAY *pRegDisplay, bool fAborting)
{
CONTEXT* pAbortContext = NULL;
if (fAborting)
{
pAbortContext = GetThread()->GetAbortContext();
}
#define UPDATEREG(reg) \
do { \
_ASSERTE(pRegDisplay->pCurrentContextPointers->reg != NULL); \
STRESS_LOG3(LF_GCROOTS, LL_INFO100, "Updating reg %p to %p from %p\n", \
pContextRecord->reg, \
*pRegDisplay->pCurrentContextPointers->reg, \
pRegDisplay->pCurrentContextPointers->reg); \
pContextRecord->reg = *pRegDisplay->pCurrentContextPointers->reg; \
if (pAbortContext) \
{ \
pAbortContext->reg = pContextRecord->reg; \
} \
} while (0)
#if defined(_TARGET_AMD64_)
UPDATEREG(Rbx);
UPDATEREG(Rbp);
UPDATEREG(Rsi);
UPDATEREG(Rdi);
UPDATEREG(R12);
UPDATEREG(R13);
UPDATEREG(R14);
UPDATEREG(R15);
#elif defined(_TARGET_ARM_)
UPDATEREG(R4);
UPDATEREG(R5);
UPDATEREG(R6);
UPDATEREG(R7);
UPDATEREG(R8);
UPDATEREG(R9);
UPDATEREG(R10);
UPDATEREG(R11);
#elif defined(_TARGET_ARM64_)
UPDATEREG(X19);
UPDATEREG(X20);
UPDATEREG(X21);
UPDATEREG(X22);
UPDATEREG(X23);
UPDATEREG(X24);
UPDATEREG(X25);
UPDATEREG(X26);
UPDATEREG(X27);
UPDATEREG(X28);
// Obtain value of Fp from CurrentContext instead of from CurrentContextPointers
// It should not matter. CurrentContextPointers does not have value of FP as this will
// require changes in MachState to also store pointer of FP which it does not do currently.
pContextRecord->Fp = pRegDisplay->pCurrentContext->Fp;
if (pAbortContext)
{
pAbortContext->Fp = pContextRecord->Fp;
}
#else
PORTABILITY_ASSERT("ExceptionTracker::UpdateNonvolatileRegisters");
#endif
#undef UPDATEREG
}
#ifndef _DEBUG
#define DebugLogExceptionRecord(pExceptionRecord)
#else // _DEBUG
#define LOG_FLAG(name) \
if (flags & name) \
{ \
LOG((LF_EH, LL_INFO100, "" #name " ")); \
} \
void DebugLogExceptionRecord(EXCEPTION_RECORD* pExceptionRecord)
{
ULONG flags = pExceptionRecord->ExceptionFlags;
EH_LOG((LL_INFO100, ">>exr: %p, code: %08x, addr: %p, flags: 0x%02x ", pExceptionRecord, pExceptionRecord->ExceptionCode, pExceptionRecord->ExceptionAddress, flags));
LOG_FLAG(EXCEPTION_NONCONTINUABLE);
LOG_FLAG(EXCEPTION_UNWINDING);
LOG_FLAG(EXCEPTION_EXIT_UNWIND);
LOG_FLAG(EXCEPTION_STACK_INVALID);
LOG_FLAG(EXCEPTION_NESTED_CALL);
LOG_FLAG(EXCEPTION_TARGET_UNWIND);
LOG_FLAG(EXCEPTION_COLLIDED_UNWIND);
LOG((LF_EH, LL_INFO100, "\n"));
}
LPCSTR DebugGetExceptionDispositionName(EXCEPTION_DISPOSITION disp)
{
switch (disp)
{
case ExceptionContinueExecution: return "ExceptionContinueExecution";
case ExceptionContinueSearch: return "ExceptionContinueSearch";
case ExceptionNestedException: return "ExceptionNestedException";
case ExceptionCollidedUnwind: return "ExceptionCollidedUnwind";
default:
UNREACHABLE_MSG("Invalid EXCEPTION_DISPOSITION!");
}
}
#endif // _DEBUG
bool ExceptionTracker::IsStackOverflowException()
{
if (m_pThread->GetThrowableAsHandle() == g_pPreallocatedStackOverflowException)
{
return true;
}
return false;
}
UINT_PTR ExceptionTracker::CallCatchHandler(CONTEXT* pContextRecord, bool* pfAborting /*= NULL*/)
{
CONTRACTL
{
MODE_COOPERATIVE;
GC_TRIGGERS;
THROWS;
PRECONDITION(CheckPointer(pContextRecord, NULL_OK));
}
CONTRACTL_END;
UINT_PTR uResumePC = 0;
ULONG_PTR ulRelOffset;
StackFrame sfStackFp = m_sfResumeStackFrame;
Thread* pThread = m_pThread;
MethodDesc* pMD = m_pMethodDescOfCatcher;
bool fIntercepted = false;
ThreadExceptionState* pExState = pThread->GetExceptionState();
#if defined(DEBUGGING_SUPPORTED)
// If the exception is intercepted, use the information stored in the DebuggerExState to resume the
// exception instead of calling the catch clause (there may not even be one).
if (pExState->GetFlags()->DebuggerInterceptInfo())
{
_ASSERTE(pMD != NULL);
// retrieve the interception information
pExState->GetDebuggerState()->GetDebuggerInterceptInfo(NULL, NULL, (PBYTE*)&(sfStackFp.SP), &ulRelOffset, NULL);
PCODE pStartAddress = pMD->GetNativeCode();
EECodeInfo codeInfo(pStartAddress);
_ASSERTE(codeInfo.IsValid());
// Note that the value returned for ulRelOffset is actually the offset,
// so we need to adjust it to get the actual IP.
_ASSERTE(FitsIn<DWORD>(ulRelOffset));
uResumePC = codeInfo.GetJitManager()->GetCodeAddressForRelOffset(codeInfo.GetMethodToken(), static_cast<DWORD>(ulRelOffset));
// Either we haven't set m_uResumeStackFrame (for unhandled managed exceptions), or we have set it
// and it equals to MemoryStackFp.
_ASSERTE(m_sfResumeStackFrame.IsNull() || m_sfResumeStackFrame == sfStackFp);
fIntercepted = true;
}
#endif // DEBUGGING_SUPPORTED
_ASSERTE(!sfStackFp.IsNull());
m_sfResumeStackFrame.Clear();
m_pMethodDescOfCatcher = NULL;
_ASSERTE(pContextRecord);
//
// call the handler
//
EH_LOG((LL_INFO100, " calling catch at 0x%p\n", m_uCatchToCallPC));
// do not call the catch clause if the exception is intercepted
if (!fIntercepted)
{
_ASSERTE(m_uCatchToCallPC != 0 && m_pClauseForCatchToken != NULL);
uResumePC = CallHandler(m_uCatchToCallPC, sfStackFp, &m_ClauseForCatch, pMD, Catch ARM_ARG(pContextRecord) ARM64_ARG(pContextRecord));
}
else
{
// Since the exception has been intercepted and we could resuming execution at any
// user-specified arbitary location, reset the EH clause index and EstablisherFrame
// we may have saved for addressing any potential ThreadAbort raise.
//
// This is done since the saved EH clause index is related to the catch block executed,
// which does not happen in interception. As user specifies where we resume execution,
// we let that behaviour override the index and pretend as if we have no index available.
m_dwIndexClauseForCatch = 0;
m_sfEstablisherOfActualHandlerFrame.Clear();
m_sfCallerOfActualHandlerFrame.Clear();
}
EH_LOG((LL_INFO100, " resume address should be 0x%p\n", uResumePC));
//
// Our tracker may have gone away at this point, don't reference it.
//
return FinishSecondPass(pThread, uResumePC, sfStackFp, pContextRecord, this, pfAborting);
}
// static
UINT_PTR ExceptionTracker::FinishSecondPass(
Thread* pThread,
UINT_PTR uResumePC,
StackFrame sf,
CONTEXT* pContextRecord,
ExceptionTracker* pTracker,
bool* pfAborting /*= NULL*/)
{
CONTRACTL
{
MODE_COOPERATIVE;
GC_NOTRIGGER;
NOTHROW;
PRECONDITION(CheckPointer(pThread, NULL_NOT_OK));
PRECONDITION(CheckPointer((void*)uResumePC, NULL_NOT_OK));
PRECONDITION(CheckPointer(pContextRecord, NULL_OK));
}
CONTRACTL_END;
// Between the time when we pop the ExceptionTracker for the current exception and the time
// when we actually resume execution, it is unsafe to start a funclet-skipping stackwalk.
// So we set a flag here to indicate that we are in this time window. The only user of this
// information right now is the profiler.
ThreadExceptionFlagHolder tefHolder(ThreadExceptionState::TEF_InconsistentExceptionState);
#ifdef DEBUGGING_SUPPORTED
// This must be done before we pop the trackers.
BOOL fIntercepted = pThread->GetExceptionState()->GetFlags()->DebuggerInterceptInfo();
#endif // DEBUGGING_SUPPORTED
// Since we may [re]raise ThreadAbort post the catch block execution,
// save the index, and Establisher, of the EH clause corresponding to the handler
// we just executed before we release the tracker. This will be used to ensure that reraise
// proceeds forward and not get stuck in a loop. Refer to
// ExceptionTracker::ProcessManagedCallFrame for details.
DWORD ehClauseCurrentHandlerIndex = pTracker->GetCatchHandlerExceptionClauseIndex();
StackFrame sfEstablisherOfActualHandlerFrame = pTracker->GetEstablisherOfActualHandlingFrame();
EH_LOG((LL_INFO100, "second pass finished\n"));
EH_LOG((LL_INFO100, "cleaning up ExceptionTracker state\n"));
// Release the exception trackers till the current (specified) frame.
ExceptionTracker::PopTrackers(sf, true);
// This will set the last thrown to be either null if we have handled all the exceptions in the nested chain or
// to whatever the current exception is.
//
// In a case when we're nested inside another catch block, the domain in which we're executing may not be the
// same as the one the domain of the throwable that was just made the current throwable above. Therefore, we
// make a special effort to preserve the domain of the throwable as we update the the last thrown object.
//
// If an exception is active, we dont want to reset the LastThrownObject to NULL as the active exception
// might be represented by a tracker created in the second pass (refer to
// CEHelper::SetupCorruptionSeverityForActiveExceptionInUnwindPass to understand how exception trackers can be
// created in the 2nd pass on 64bit) that does not have a throwable attached to it. Thus, if this exception
// is caught in the VM and it attempts to get the LastThrownObject using GET_THROWABLE macro, then it should be available.
//
// But, if the active exception tracker remains consistent in the 2nd pass (which will happen if the exception is caught
// in managed code), then the call to SafeUpdateLastThrownObject below will automatically update the LTO as per the
// active exception.
if (!pThread->GetExceptionState()->IsExceptionInProgress())
{
pThread->SafeSetLastThrownObject(NULL);
}
pThread->SafeUpdateLastThrownObject();
#ifdef FEATURE_CORRUPTING_EXCEPTIONS
// Since the catch clause has successfully executed and we are exiting it, reset the corruption severity
// in the ThreadExceptionState for the last active exception. This will ensure that when the next exception
// gets thrown/raised, EH tracker wont pick up an invalid value.
CEHelper::ResetLastActiveCorruptionSeverityPostCatchHandler();
#endif // FEATURE_CORRUPTING_EXCEPTIONS
//
// If we are aborting, we should not resume execution. Instead, we raise another
// exception. However, we do this by resuming execution at our thread redirecter
// function (RedirectForThrowControl), which is the same process we use for async
// thread stops. This redirecter function will cover the stack frame and register
// stack frame and then throw an exception. When we first see the exception thrown
// by this redirecter, we fixup the context for the thread stackwalk by copying
// pThread->m_OSContext into the dispatcher context and restarting the exception
// dispatch. As a result, we need to save off the "correct" resume context before
// we resume so the exception processing can work properly after redirect. A side
// benefit of this mechanism is that it makes synchronous and async thread abort
// use exactly the same codepaths.
//
UINT_PTR uAbortAddr = 0;
#if defined(DEBUGGING_SUPPORTED)
// Don't honour thread abort requests at this time for intercepted exceptions.
if (fIntercepted)
{
uAbortAddr = 0;
}
else
#endif // !DEBUGGING_SUPPORTED
{
CopyOSContext(pThread->m_OSContext, pContextRecord);
SetIP(pThread->m_OSContext, (PCODE)uResumePC);
uAbortAddr = (UINT_PTR)COMPlusCheckForAbort(uResumePC);
}
if (uAbortAddr)
{
if (pfAborting != NULL)
{
*pfAborting = true;
}
EH_LOG((LL_INFO100, "thread abort in progress, resuming thread under control...\n"));
// We are aborting, so keep the reference to the current EH clause index.
// We will use this when the exception is reraised and we begin commencing
// exception dispatch. This is done in ExceptionTracker::ProcessOSExceptionNotification.
//
// The "if" condition below can be false if the exception has been intercepted (refer to
// ExceptionTracker::CallCatchHandler for details)
if ((ehClauseCurrentHandlerIndex > 0) && (!sfEstablisherOfActualHandlerFrame.IsNull()))
{
pThread->m_dwIndexClauseForCatch = ehClauseCurrentHandlerIndex;
pThread->m_sfEstablisherOfActualHandlerFrame = sfEstablisherOfActualHandlerFrame;
}
CONSISTENCY_CHECK(CheckPointer(pContextRecord));
STRESS_LOG1(LF_EH, LL_INFO10, "resume under control: ip: %p\n", uResumePC);
#ifdef _TARGET_AMD64_
pContextRecord->Rcx = uResumePC;
#elif defined(_TARGET_ARM_) || defined(_TARGET_ARM64_)
// On ARM & ARM64, we save off the original PC in Lr. This is the same as done
// in HandleManagedFault for H/W generated exceptions.
pContextRecord->Lr = uResumePC;
#endif
uResumePC = uAbortAddr;
}
CONSISTENCY_CHECK(pThread->DetermineIfGuardPagePresent());
EH_LOG((LL_INFO100, "FinishSecondPass complete, uResumePC = %p, current SP = %p\n", uResumePC, GetCurrentSP()));
return uResumePC;
}
// On CoreARM, the MemoryStackFp is ULONG when passed by RtlDispatchException,
// unlike its 64bit counterparts.
EXTERN_C EXCEPTION_DISPOSITION
ProcessCLRException(IN PEXCEPTION_RECORD pExceptionRecord
WIN64_ARG(IN ULONG64 MemoryStackFp)
NOT_WIN64_ARG(IN ULONG MemoryStackFp),
IN OUT PCONTEXT pContextRecord,
IN OUT PDISPATCHER_CONTEXT pDispatcherContext
)
{
//
// This method doesn't always return, so it will leave its
// state on the thread if using dynamic contracts.
//
STATIC_CONTRACT_MODE_ANY;
STATIC_CONTRACT_GC_TRIGGERS;
STATIC_CONTRACT_THROWS;
// We must preserve this so that GCStress=4 eh processing doesnt kill last error.
DWORD dwLastError = GetLastError();
EXCEPTION_DISPOSITION returnDisposition = ExceptionContinueSearch;
STRESS_LOG5(LF_EH, LL_INFO10, "Processing exception at establisher=%p, ip=%p disp->cxr: %p, sp: %p, cxr @ exception: %p\n",
MemoryStackFp, pDispatcherContext->ControlPc,
pDispatcherContext->ContextRecord,
GetSP(pDispatcherContext->ContextRecord), pContextRecord);
AMD64_ONLY(STRESS_LOG3(LF_EH, LL_INFO10, " rbx=%p, rsi=%p, rdi=%p\n", pContextRecord->Rbx, pContextRecord->Rsi, pContextRecord->Rdi));
// sample flags early on because we may change pExceptionRecord below
// if we are seeing a STATUS_UNWIND_CONSOLIDATE
DWORD dwExceptionFlags = pExceptionRecord->ExceptionFlags;
Thread* pThread = GetThread();
// Stack Overflow is handled specially by the CLR EH mechanism. In fact
// there are cases where we aren't in managed code, but aren't quite in
// known unmanaged code yet either...
//
// These "boundary code" cases include:
// - in JIT helper methods which don't have a frame
// - in JIT helper methods before/during frame setup
// - in FCALL before/during frame setup
//
// In those cases on x86 we take special care to start our unwind looking
// for a handler which is below the last explicit frame which has been
// established on the stack as it can't reliably crawl the stack frames
// above that.
// NOTE: see code in the CLRVectoredExceptionHandler() routine.
//
// From the perspective of the EH subsystem, we can handle unwind correctly
// even without erecting a transition frame on WIN64. However, since the GC
// uses the stackwalker to update object references, and since the stackwalker
// relies on transition frame, we still cannot let an exception be handled
// by an unprotected managed frame.
//
// This code below checks to see if a SO has occured outside of managed code.
// If it has, and if we don't have a transition frame higher up the stack, then
// we don't handle the SO.
if (!(dwExceptionFlags & EXCEPTION_UNWINDING))
{
if (IsSOExceptionCode(pExceptionRecord->ExceptionCode))
{
// We don't need to unwind the frame chain here because we have backstop
// personality routines at the U2M boundary to handle do that. They are
// the personality routines of CallDescrWorker() and UMThunkStubCommon().
//
// See VSW 471619 for more information.
// We should be in cooperative mode if we are going to handle the SO.
// We track SO state for the thread.
EEPolicy::HandleStackOverflow(SOD_ManagedFrameHandler, (void*)MemoryStackFp);
FastInterlockAnd (&pThread->m_fPreemptiveGCDisabled, 0);
return ExceptionContinueSearch;
}
else
{
#ifdef FEATURE_STACK_PROBE
if (GetEEPolicy()->GetActionOnFailure(FAIL_StackOverflow) == eRudeUnloadAppDomain)
{
RetailStackProbe(static_cast<unsigned int>(ADJUST_PROBE(BACKOUT_CODE_STACK_LIMIT)), pThread);
}
#endif
}
}
else
{
DWORD exceptionCode = pExceptionRecord->ExceptionCode;
if (exceptionCode == STATUS_UNWIND)
// If exceptionCode is STATUS_UNWIND, RtlUnwind is called with a NULL ExceptionRecord,
// therefore OS uses a faked ExceptionRecord with STATUS_UNWIND code. Then we need to
// look at our saved exception code.
exceptionCode = GetCurrentExceptionCode();
if (IsSOExceptionCode(exceptionCode))
{
return ExceptionContinueSearch;
}
}
BEGIN_CONTRACT_VIOLATION(SOToleranceViolation);
StackFrame sf((UINT_PTR)MemoryStackFp);
{
GCX_COOP();
// Update the current establisher frame
if (dwExceptionFlags & EXCEPTION_UNWINDING)
{
ExceptionTracker *pCurrentTracker = pThread->GetExceptionState()->GetCurrentExceptionTracker();
if (pCurrentTracker != NULL)
{
pCurrentTracker->SetCurrentEstablisherFrame(sf);
}
}
#ifdef _DEBUG
Thread::ObjectRefFlush(pThread);
#endif // _DEBUG
}
//
// begin Early Processing
//
{
#ifndef USE_REDIRECT_FOR_GCSTRESS
if (IsGcMarker(pExceptionRecord->ExceptionCode, pContextRecord))
{
returnDisposition = ExceptionContinueExecution;
goto lExit;
}
#endif // !USE_REDIRECT_FOR_GCSTRESS
EH_LOG((LL_INFO100, "..................................................................................\n"));
EH_LOG((LL_INFO100, "ProcessCLRException enter, sp = 0x%p, ControlPc = 0x%p\n", MemoryStackFp, pDispatcherContext->ControlPc));
DebugLogExceptionRecord(pExceptionRecord);
if (STATUS_UNWIND_CONSOLIDATE == pExceptionRecord->ExceptionCode)
{
EH_LOG((LL_INFO100, "STATUS_UNWIND_CONSOLIDATE, retrieving stored exception record\n"));
_ASSERTE(pExceptionRecord->NumberParameters >= 7);
pExceptionRecord = (EXCEPTION_RECORD*)pExceptionRecord->ExceptionInformation[6];
DebugLogExceptionRecord(pExceptionRecord);
}
CONSISTENCY_CHECK_MSG(!DebugIsEECxxException(pExceptionRecord), "EE C++ Exception leaked into managed code!!\n");
}
//
// end Early Processing (tm) -- we're now into really processing an exception for managed code
//
if (!(dwExceptionFlags & EXCEPTION_UNWINDING))
{
// If the exception is a breakpoint, but outside of the runtime or managed code,
// let it go. It is not ours, so someone else will handle it, or we'll see
// it again as an unhandled exception.
if ((pExceptionRecord->ExceptionCode == STATUS_BREAKPOINT) ||
(pExceptionRecord->ExceptionCode == STATUS_SINGLE_STEP))
{
// It is a breakpoint; is it from the runtime or managed code?
PCODE ip = GetIP(pContextRecord); // IP of the fault.
BOOL fExternalException = FALSE;
BEGIN_SO_INTOLERANT_CODE_NOPROBE;
fExternalException = (!ExecutionManager::IsManagedCode(ip) &&
!IsIPInModule(g_pMSCorEE, ip));
END_SO_INTOLERANT_CODE_NOPROBE;
if (fExternalException)
{
// The breakpoint was not ours. Someone else can handle it. (Or if not, we'll get it again as
// an unhandled exception.)
returnDisposition = ExceptionContinueSearch;
goto lExit;
}
}
}
{
BOOL bAsynchronousThreadStop = IsThreadHijackedForThreadStop(pThread, pExceptionRecord);
// we already fixed the context in HijackHandler, so let's
// just clear the thread state.
pThread->ResetThrowControlForThread();
ExceptionTracker::StackTraceState STState;
ExceptionTracker* pTracker = ExceptionTracker::GetOrCreateTracker(
pDispatcherContext->ControlPc,
sf,
pExceptionRecord,
pContextRecord,
bAsynchronousThreadStop,
!(dwExceptionFlags & EXCEPTION_UNWINDING),
&STState);
#ifdef FEATURE_CORRUPTING_EXCEPTIONS
// Only setup the Corruption Severity in the first pass
if (!(dwExceptionFlags & EXCEPTION_UNWINDING))
{
// Switch to COOP mode
GCX_COOP();
if (pTracker && pTracker->GetThrowable() != NULL)
{
// Setup the state in current exception tracker indicating the corruption severity
// of the active exception.
CEHelper::SetupCorruptionSeverityForActiveException((STState == ExceptionTracker::STS_FirstRethrowFrame), (pTracker->GetPreviousExceptionTracker() != NULL),
CEHelper::ShouldTreatActiveExceptionAsNonCorrupting());
}
}
#endif // FEATURE_CORRUPTING_EXCEPTIONS
#ifdef FEATURE_CORECLR
{
// Switch to COOP mode since we are going to work
// with throwable
GCX_COOP();
if (pTracker->GetThrowable() != NULL)
{
BOOL fIsThrownExceptionAV = FALSE;
OBJECTREF oThrowable = NULL;
GCPROTECT_BEGIN(oThrowable);
oThrowable = pTracker->GetThrowable();
// Check if we are dealing with AV or not and if we are,
// ensure that this is a real AV and not managed AV exception
if ((pExceptionRecord->ExceptionCode == STATUS_ACCESS_VIOLATION) &&
(MscorlibBinder::GetException(kAccessViolationException) == oThrowable->GetMethodTable()))
{
// Its an AV - set the flag
fIsThrownExceptionAV = TRUE;
}
GCPROTECT_END();
// Did we get an AV?
if (fIsThrownExceptionAV == TRUE)
{
// Get the escalation policy action for handling AV
EPolicyAction actionAV = GetEEPolicy()->GetActionOnFailure(FAIL_AccessViolation);
// Valid actions are: eNoAction (default behviour) or eRudeExitProcess
_ASSERTE(((actionAV == eNoAction) || (actionAV == eRudeExitProcess)));
if (actionAV == eRudeExitProcess)
{
LOG((LF_EH, LL_INFO100, "ProcessCLRException: AccessViolation handler found and doing RudeExitProcess due to escalation policy (eRudeExitProcess)\n"));
// EEPolicy::HandleFatalError will help us RudeExit the process.
// RudeExitProcess due to AV is to prevent a security risk - we are ripping
// at the boundary, without looking for the handlers.
EEPOLICY_HANDLE_FATAL_ERROR(COR_E_SECURITY);
}
}
}
}
#endif // FEATURE_CORECLR
#ifndef FEATURE_PAL // Watson is on Windows only
// Setup bucketing details for nested exceptions (rethrow and non-rethrow) only if we are in the first pass
if (!(dwExceptionFlags & EXCEPTION_UNWINDING))
{
ExceptionTracker *pPrevEHTracker = pTracker->GetPreviousExceptionTracker();
if (pPrevEHTracker != NULL)
{
SetStateForWatsonBucketing((STState == ExceptionTracker::STS_FirstRethrowFrame), pPrevEHTracker->GetThrowableAsHandle());
}
}
#endif //!FEATURE_PAL
CLRUnwindStatus status;
// Refer to comment in ProcessOSExceptionNotification about ICF and codegen difference.
ARM_ONLY(InlinedCallFrame *pICFSetAsLimitFrame = NULL;)
status = pTracker->ProcessOSExceptionNotification(
pExceptionRecord,
pContextRecord,
pDispatcherContext,
dwExceptionFlags,
sf,
pThread,
STState ARM_ARG((PVOID)pICFSetAsLimitFrame));
if (FirstPassComplete == status)
{
EH_LOG((LL_INFO100, "first pass finished, found handler, TargetFrameSp = %p\n",
pDispatcherContext->EstablisherFrame));
SetLastError(dwLastError);
//
// At this point (the end of the 1st pass) we don't know where
// we are going to resume to. So, we pass in an address, which
// lies in NULL pointer partition of the memory, as the target IP.
//
// Once we reach the target frame in the second pass unwind, we call
// the catch funclet that caused us to resume execution and it
// tells us where we are resuming to. At that point, we patch
// the context record with the resume IP and RtlUnwind2 finishes
// by restoring our context at the right spot.
//
// If we are unable to set the resume PC for some reason, then
// the OS will try to resume at the NULL partition address and the
// attempt will fail due to AV, resulting in failfast, helping us
// isolate problems in patching the IP.
ClrUnwindEx(pExceptionRecord,
(UINT_PTR)pThread,
INVALID_RESUME_ADDRESS,
pDispatcherContext->EstablisherFrame);
UNREACHABLE();
//
// doesn't return
//
}
else if (SecondPassComplete == status)
{
bool fAborting = false;
UINT_PTR uResumePC = (UINT_PTR)-1;
UINT_PTR uOriginalSP = GetSP(pContextRecord);
Frame* pLimitFrame = pTracker->GetLimitFrame();
pDispatcherContext->ContextRecord = pContextRecord;
// We maybe in COOP mode at this point - the indefinite switch was done
// in ExceptionTracker::ProcessManagedCallFrame.
//
// However, if a finally was invoked non-exceptionally and raised an exception
// that was caught in its parent method, unwind will result in invoking any applicable termination
// handlers in the finally funclet and thus, also switching the mode to COOP indefinitely.
//
// Since the catch block to be executed will lie in the parent method,
// we will skip frames till we reach the parent and in the process, switch back to PREEMP mode
// as control goes back to the OS.
//
// Upon reaching the target of unwind, we wont call ExceptionTracker::ProcessManagedCallFrame (since any
// handlers in finally or surrounding it will be invoked when we unwind finally funclet). Thus,
// we may not be in COOP mode.
//
// Since CallCatchHandler expects to be in COOP mode, perform the switch here.
GCX_COOP_NO_DTOR();
uResumePC = pTracker->CallCatchHandler(pContextRecord, &fAborting);
{
//
// GC must NOT occur after the handler has returned until
// we resume at the new address because the stackwalker
// EnumGcRefs would try and report things as live from the
// try body, that were probably reported dead from the
// handler body.
//
// GC must NOT occur once the frames have been popped because
// the values in the unwound CONTEXT are not GC-protected.
//
GCX_FORBID();
CONSISTENCY_CHECK((UINT_PTR)-1 != uResumePC);
// Ensure we are not resuming to the invalid target IP we had set at the end of
// first pass
_ASSERTE_MSG(INVALID_RESUME_ADDRESS != uResumePC, "CallCatchHandler returned invalid resume PC!");
//
// CallCatchHandler freed the tracker.
//
INDEBUG(pTracker = (ExceptionTracker*)POISONC);
// Note that we should only fail to fix up for SO.
bool fFixedUp = FixNonvolatileRegisters(uOriginalSP, pThread, pContextRecord, fAborting);
_ASSERTE(fFixedUp || (pExceptionRecord->ExceptionCode == STATUS_STACK_OVERFLOW));
CONSISTENCY_CHECK(pLimitFrame > dac_cast<PTR_VOID>(GetSP(pContextRecord)));
#if defined(_TARGET_ARM_)
if (pICFSetAsLimitFrame != NULL)
{
_ASSERTE(pICFSetAsLimitFrame == pLimitFrame);
// Mark the ICF as inactive (by setting the return address as NULL).
// It will be marked as active at the next PInvoke callsite.
//
// This ensures that any stackwalk post the catch handler but before
// the next pinvoke callsite does not see the frame as active.
pICFSetAsLimitFrame->Reset();
}
#endif // defined(_TARGET_ARM_)
pThread->SetFrame(pLimitFrame);
SetIP(pContextRecord, (PCODE)uResumePC);
}
#ifdef STACK_GUARDS_DEBUG
// We are transitioning back to managed code, so ensure that we are in
// SO-tolerant mode before we do so.
RestoreSOToleranceState();
#endif
RESET_CONTRACT_VIOLATION();
ExceptionTracker::ResumeExecution(pContextRecord,
NULL
);
UNREACHABLE();
}
}
lExit: ;
EH_LOG((LL_INFO100, "returning %s\n", DebugGetExceptionDispositionName(returnDisposition)));
CONSISTENCY_CHECK( !((dwExceptionFlags & EXCEPTION_TARGET_UNWIND) && (ExceptionContinueSearch == returnDisposition)));
if ((ExceptionContinueSearch == returnDisposition))
{
GCX_PREEMP_NO_DTOR();
}
END_CONTRACT_VIOLATION;
SetLastError(dwLastError);
return returnDisposition;
}
// When we hit a native exception such as an AV in managed code, we put up a FaultingExceptionFrame which saves all the
// non-volatile registers. The GC may update these registers if they contain object references. However, the CONTEXT
// with which we are going to resume execution doesn't have these updated values. Thus, we need to fix up the non-volatile
// registers in the CONTEXT with the updated ones stored in the FaultingExceptionFrame. To do so properly, we need
// to perform a full stackwalk.
bool FixNonvolatileRegisters(UINT_PTR uOriginalSP,
Thread* pThread,
CONTEXT* pContextRecord,
bool fAborting
)
{
CONTRACTL
{
MODE_COOPERATIVE;
NOTHROW;
GC_NOTRIGGER;
SO_TOLERANT;
}
CONTRACTL_END;
CONTEXT _ctx = {0};
#if defined(_TARGET_AMD64_)
REGDISPLAY regdisp = {0};
#else
// Ctor will initialize it to NULL
REGDISPLAY regdisp;
#endif // _TARGET_AMD64_
pThread->FillRegDisplay(®disp, &_ctx);
bool fFound = ExceptionTracker::FindNonvolatileRegisterPointers(pThread, uOriginalSP, ®disp, GetFP(pContextRecord));
if (!fFound)
{
return false;
}
{
//
// GC must NOT occur once the frames have been popped because
// the values in the unwound CONTEXT are not GC-protected.
//
GCX_FORBID();
ExceptionTracker::UpdateNonvolatileRegisters(pContextRecord, ®disp, fAborting);
}
return true;
}
// static
void ExceptionTracker::InitializeCrawlFrameForExplicitFrame(CrawlFrame* pcfThisFrame, Frame* pFrame, MethodDesc *pMD)
{
CONTRACTL
{
MODE_ANY;
NOTHROW;
GC_NOTRIGGER;
PRECONDITION(pFrame != FRAME_TOP);
}
CONTRACTL_END;
INDEBUG(memset(pcfThisFrame, 0xCC, sizeof(*pcfThisFrame)));
pcfThisFrame->isFrameless = false;
pcfThisFrame->pFrame = pFrame;
pcfThisFrame->pFunc = pFrame->GetFunction();
if (pFrame->GetVTablePtr() == InlinedCallFrame::GetMethodFrameVPtr() &&
!InlinedCallFrame::FrameHasActiveCall(pFrame))
{
// Inactive ICFs in IL stubs contain the true interop MethodDesc which must be
// reported in the stack trace.
if (pMD->IsILStub() && pMD->AsDynamicMethodDesc()->HasMDContextArg())
{
// Report interop MethodDesc
pcfThisFrame->pFunc = ((InlinedCallFrame *)pFrame)->GetActualInteropMethodDesc();
_ASSERTE(pcfThisFrame->pFunc != NULL);
_ASSERTE(pcfThisFrame->pFunc->SanityCheck());
}
}
pcfThisFrame->pFirstGSCookie = NULL;
pcfThisFrame->pCurGSCookie = NULL;
}
// static
void ExceptionTracker::InitializeCrawlFrame(CrawlFrame* pcfThisFrame, Thread* pThread, StackFrame sf, REGDISPLAY* pRD,
PDISPATCHER_CONTEXT pDispatcherContext, DWORD_PTR ControlPCForEHSearch,
UINT_PTR* puMethodStartPC
ARM_ARG(ExceptionTracker *pCurrentTracker)
ARM64_ARG(ExceptionTracker *pCurrentTracker))
{
CONTRACTL
{
MODE_ANY;
NOTHROW;
GC_NOTRIGGER;
}
CONTRACTL_END;
INDEBUG(memset(pcfThisFrame, 0xCC, sizeof(*pcfThisFrame)));
pcfThisFrame->pRD = pRD;
#ifdef FEATURE_INTERPRETER
pcfThisFrame->pFrame = NULL;
#endif // FEATURE_INTERPRETER
#if defined(_TARGET_AMD64_)
pThread->InitRegDisplay(pcfThisFrame->pRD, pDispatcherContext->ContextRecord, true);
if (pDispatcherContext->ControlPc != (UINT_PTR)GetIP(pDispatcherContext->ContextRecord))
{
INDEBUG(memset(pRD->pCurrentContext, 0xCC, sizeof(*(pRD->pCurrentContext))));
// Ensure that clients can tell the current context isn't valid.
SetIP(pRD->pCurrentContext, 0);
*(pRD->pCallerContext) = *(pDispatcherContext->ContextRecord);
pRD->IsCallerContextValid = TRUE;
pcfThisFrame->pRD->SP = sf.SP;
pcfThisFrame->pRD->ControlPC = pDispatcherContext->ControlPc;
}
#elif defined(_TARGET_ARM_) || defined(_TARGET_ARM64_)
pThread->InitRegDisplay(pcfThisFrame->pRD, pDispatcherContext->ContextRecord, true);
if (pCurrentTracker->IsInFirstPass())
{
// In the first pass on ARM & ARM64:
//
// 1) EstablisherFrame (passed as 'sf' to this method) represents the SP at the time
// the current managed method was invoked and thus, is the SP of the caller. This is
// the value of DispatcherContext->EstablisherFrame as well.
// 2) DispatcherContext->ControlPC is the pc in the current managed method for which personality
// routine has been invoked.
// 3) DispatcherContext->ContextRecord contains the context record of the caller (and thus, IP
// in the caller). Most of the times, these values will be distinct. However, recursion
// may result in them being the same (case "run2" of baseservices\Regression\V1\Threads\functional\CS_TryFinally.exe
// is an example). In such a case, we ensure that EstablisherFrame value is the same as
// the SP in DispatcherContext->ContextRecord (which is (1) above).
// Based upon this, ensure that clients can tell the current context isn't valid.
INDEBUG(memset(pRD->pCurrentContext, 0xCC, sizeof(*(pRD->pCurrentContext))));
SetIP(pRD->pCurrentContext, 0);
// Assert that our assumption (1) above is true
_ASSERTE(sf.SP == GetSP(pDispatcherContext->ContextRecord));
// Setup the caller context
*(pRD->pCallerContext) = *(pDispatcherContext->ContextRecord);
pRD->IsCallerContextValid = TRUE;
pcfThisFrame->pRD->SP = sf.SP;
pcfThisFrame->pRD->IsCallerSPValid = TRUE;
EH_LOG((LL_INFO100, "ExceptionTracker::InitializeCrawlFrame: DispatcherContext->ControlPC = %p; IP in DispatcherContext->ContextRecord = %p.\n",
pDispatcherContext->ControlPc, GetIP(pDispatcherContext->ContextRecord)));
pcfThisFrame->pRD->ControlPC = pDispatcherContext->ControlPc;
}
else
{
// In second pass on ARM & ARM64:
//
// 1) EstablisherFrame (passed as 'sf' to this method) represents the SP at the time
// the current managed method was invoked and thus, is the SP of the caller. This is
// the value of DispatcherContext->EstablisherFrame as well.
// 2) DispatcherContext->ControlPC is the pc in the current managed method for which personality
// routine has been invoked.
// 3) DispatcherContext->ContextRecord contains the context record of the current managed method
// for which the personality routine is invoked.
// Assert that our assumption (3) above is true
_ASSERTE(pDispatcherContext->ControlPc == GetIP(pDispatcherContext->ContextRecord));
// Simply setup the callerSP during the second pass in the caller context.
// This is used in setting up the "EnclosingClauseCallerSP" in ExceptionTracker::ProcessManagedCallFrame
// when the termination handlers are invoked.
::SetSP(pcfThisFrame->pRD->pCallerContext, sf.SP);
pcfThisFrame->pRD->IsCallerSPValid = TRUE;
}
// Further below, we will adjust the ControlPC based upon whether we are at a callsite or not.
// We need to do this for "RegDisplay.ControlPC" field as well so that when data structures like
// EECodeInfo initialize themselves using this field, they will have the correct absolute value
// that is in sync with the "relOffset" we calculate below.
//
// However, we do this *only* when "ControlPCForEHSearch" is the same as "DispatcherContext->ControlPC",
// indicating we are not using the thread-abort reraise loop prevention logic.
//
bool fAdjustRegdisplayControlPC = false;
if (pDispatcherContext->ControlPc == ControlPCForEHSearch)
{
// Since DispatcherContext->ControlPc is used to initialize the
// RegDisplay.ControlPC field, assert that it is the same
// as the ControlPC we are going to use to initialize the CrawlFrame
// with as well.
_ASSERTE(pcfThisFrame->pRD->ControlPC == ControlPCForEHSearch);
fAdjustRegdisplayControlPC = true;
}
#if defined(_TARGET_ARM_)
// Remove the Thumb bit
ControlPCForEHSearch = ThumbCodeToDataPointer<DWORD_PTR, DWORD_PTR>(ControlPCForEHSearch);
#endif
// If the OS indicated that the IP is a callsite, then adjust the ControlPC by decrementing it
// by two. This is done because unwinding at callsite will make ControlPC point to the
// instruction post the callsite. If a protected region ends "at" the callsite, then
// not doing this adjustment will result in a one-off error that can result in us not finding
// a handler.
//
// For async exceptions (e.g. AV), this will be false.
//
// We decrement by two to be in accordance with how the kernel does as well.
if (pDispatcherContext->ControlPcIsUnwound)
{
ControlPCForEHSearch -= STACKWALK_CONTROLPC_ADJUST_OFFSET;
if (fAdjustRegdisplayControlPC == true)
{
// Once the check above is removed, the assignment below should
// be done unconditionally.
pcfThisFrame->pRD->ControlPC = ControlPCForEHSearch;
// On ARM & ARM64, the IP is either at the callsite (post the adjustment above)
// or at the instruction at which async exception took place.
pcfThisFrame->isIPadjusted = true;
}
}
#endif // _TARGET_AMD64_ || _TARGET_ARM_ || _TARGET_ARM64_
pcfThisFrame->codeInfo.Init(ControlPCForEHSearch);
if (pcfThisFrame->codeInfo.IsValid())
{
pcfThisFrame->isFrameless = true;
pcfThisFrame->pFunc = pcfThisFrame->codeInfo.GetMethodDesc();
*puMethodStartPC = pcfThisFrame->codeInfo.GetStartAddress();
}
else
{
pcfThisFrame->isFrameless = false;
pcfThisFrame->pFunc = NULL;
*puMethodStartPC = NULL;
}
pcfThisFrame->pThread = pThread;
pcfThisFrame->hasFaulted = false;
Frame* pTopFrame = pThread->GetFrame();
pcfThisFrame->isIPadjusted = (FRAME_TOP != pTopFrame) && (pTopFrame->GetVTablePtr() != FaultingExceptionFrame::GetMethodFrameVPtr());
if (pcfThisFrame->isFrameless && (pcfThisFrame->isIPadjusted == false) && (pcfThisFrame->GetRelOffset() == 0))
{
// If we are here, then either a hardware generated exception happened at the first instruction
// of a managed method an exception was thrown at that location.
//
// Adjusting IP in such a case will lead us into unknown code - it could be native code or some
// other JITted code.
//
// Hence, we will flag that the IP is already adjusted.
pcfThisFrame->isIPadjusted = true;
EH_LOG((LL_INFO100, "ExceptionTracker::InitializeCrawlFrame: Exception at offset zero of the method (MethodDesc %p); setting IP as adjusted.\n",
pcfThisFrame->pFunc));
}
pcfThisFrame->pFirstGSCookie = NULL;
pcfThisFrame->pCurGSCookie = NULL;
pcfThisFrame->isFilterFuncletCached = FALSE;
}
bool ExceptionTracker::UpdateScannedStackRange(StackFrame sf, bool fIsFirstPass)
{
CONTRACTL
{
// Since this function will modify the scanned stack range, which is also accessed during the GC stackwalk,
// we invoke it in COOP mode so that that access to the range is synchronized.
MODE_COOPERATIVE;
GC_TRIGGERS;
THROWS;
}
CONTRACTL_END;
//
// collapse trackers if a nested exception passes a previous exception
//
HandleNestedExceptionEscape(sf, fIsFirstPass);
//
// update stack bounds
//
BOOL fUnwindingToFindResumeFrame = m_ExceptionFlags.UnwindingToFindResumeFrame();
if (m_ScannedStackRange.Contains(sf))
{
// If we're unwinding to find the resume frame and we're examining the topmost previously scanned frame,
// then we can't ignore it because we could resume here due to an escaped nested exception.
if (!fUnwindingToFindResumeFrame || (m_ScannedStackRange.GetUpperBound() != sf))
{
// been there, done that.
EH_LOG((LL_INFO100, " IGNOREFRAME: This frame has been processed already\n"));
return false;
}
}
else
{
if (sf < m_ScannedStackRange.GetLowerBound())
{
m_ScannedStackRange.ExtendLowerBound(sf);
}
if (sf > m_ScannedStackRange.GetUpperBound())
{
m_ScannedStackRange.ExtendUpperBound(sf);
}
DebugLogTrackerRanges(" C");
}
return true;
}
void CheckForRudeAbort(Thread* pThread, bool fIsFirstPass)
{
if (fIsFirstPass && pThread->IsRudeAbort())
{
GCX_COOP();
OBJECTREF rudeAbortThrowable = CLRException::GetPreallocatedRudeThreadAbortException();
if (pThread->GetThrowable() != rudeAbortThrowable)
{
pThread->SafeSetThrowables(rudeAbortThrowable);
}
if (!pThread->IsRudeAbortInitiated())
{
pThread->PreWorkForThreadAbort();
}
}
}
void ExceptionTracker::FirstPassIsComplete()
{
m_ExceptionFlags.ResetUnwindingToFindResumeFrame();
m_pSkipToParentFunctionMD = NULL;
}
void ExceptionTracker::SecondPassIsComplete(MethodDesc* pMD, StackFrame sfResumeStackFrame)
{
EH_LOG((LL_INFO100, " second pass unwind completed\n"));
m_pMethodDescOfCatcher = pMD;
m_sfResumeStackFrame = sfResumeStackFrame;
}
CLRUnwindStatus ExceptionTracker::ProcessOSExceptionNotification(
PEXCEPTION_RECORD pExceptionRecord,
PCONTEXT pContextRecord,
PDISPATCHER_CONTEXT pDispatcherContext,
DWORD dwExceptionFlags,
StackFrame sf,
Thread* pThread,
StackTraceState STState ARM_ARG(PVOID pICFSetAsLimitFrame))
{
CONTRACTL
{
MODE_ANY;
GC_TRIGGERS;
THROWS;
}
CONTRACTL_END;
CLRUnwindStatus status = UnwindPending;
CrawlFrame cfThisFrame;
REGDISPLAY regdisp;
UINT_PTR uMethodStartPC;
UINT_PTR uCallerSP;
DWORD_PTR ControlPc = pDispatcherContext->ControlPc;
ExceptionTracker::InitializeCrawlFrame(&cfThisFrame, pThread, sf, ®disp, pDispatcherContext, ControlPc, &uMethodStartPC
ARM_ARG(this)
ARM64_ARG(this));
#ifdef _TARGET_AMD64_
uCallerSP = EECodeManager::GetCallerSp(cfThisFrame.pRD);
#elif defined(_TARGET_ARM_) || defined(_TARGET_ARM64_)
// On ARM & ARM64, the EstablisherFrame is the value of SP at the time a function was called and before it's prolog
// executed. Effectively, it is the SP of the caller. This has been confirmed by AaronGi from the kernel
// team.
uCallerSP = sf.SP;
#else
PORTABILITY_ASSERT("ExceptionTracker::ProcessOSExceptionNotification");
uCallerSP = NULL;
#endif // _TARGET_AMD64_
EH_LOG((LL_INFO100, "ProcessCrawlFrame: PSP: " FMT_ADDR " EstablisherFrame: " FMT_ADDR "\n", DBG_ADDR(uCallerSP), DBG_ADDR(sf.SP)));
bool fIsFirstPass = !(dwExceptionFlags & EXCEPTION_UNWINDING);
bool fTargetUnwind = !!(dwExceptionFlags & EXCEPTION_TARGET_UNWIND);
// If a thread abort was raised after a catch block's execution, we would have saved
// the index and EstablisherFrame of the EH clause corresponding to the handler that executed.
// Fetch that locally and reset the state against the thread if we are in the unwind pass.
//
// It should be kept in mind that by the virtue of copying the information below, we will
// have it available for the first frame seen during the unwind pass (which will be the
// frame where ThreadAbort was raised after the catch block) for us to skip any termination
// handlers that maybe present prior to the EH clause whose index we saved.
DWORD dwTACatchHandlerClauseIndex = pThread->m_dwIndexClauseForCatch;
StackFrame sfEstablisherOfActualHandlerFrame = pThread->m_sfEstablisherOfActualHandlerFrame;
if (!fIsFirstPass)
{
pThread->m_dwIndexClauseForCatch = 0;
pThread->m_sfEstablisherOfActualHandlerFrame.Clear();
}
bool fProcessThisFrame = false;
bool fCrawlFrameIsDirty = false;
// <GC_FUNCLET_REFERENCE_REPORTING>
//
// Refer to the detailed comment in ExceptionTracker::ProcessManagedCallFrame for more context.
// In summary, if we have reached the target of the unwind, then we need to fix CallerSP (for
// GC reference reporting) if we have been asked to.
//
// This will be done only when we reach the frame that is handling the exception.
//
// </GC_FUNCLET_REFERENCE_REPORTING>
if (fTargetUnwind && (m_fFixupCallerSPForGCReporting == true))
{
m_fFixupCallerSPForGCReporting = false;
this->m_EnclosingClauseInfoForGCReporting.SetEnclosingClauseCallerSP(uCallerSP);
}
#if defined(_TARGET_ARM_)
// Refer to detailed comment below.
PTR_Frame pICFForUnwindTarget = NULL;
#endif // defined(_TARGET_ARM_)
CheckForRudeAbort(pThread, fIsFirstPass);
bool fIsFrameLess = cfThisFrame.IsFrameless();
GSCookie* pGSCookie = NULL;
bool fSetLastUnwoundEstablisherFrame = false;
//
// process any frame since the last frame we've seen
//
{
GCX_COOP_THREAD_EXISTS(pThread);
// UpdateScannedStackRange needs to be invoked in COOP mode since
// the stack range can also be accessed during GC stackwalk.
fProcessThisFrame = UpdateScannedStackRange(sf, fIsFirstPass);
MethodDesc *pMD = cfThisFrame.GetFunction();
Frame* pFrame = GetLimitFrame(); // next frame to process
if (pFrame != FRAME_TOP)
{
// The following function call sets the GS cookie pointers and checks the cookie.
cfThisFrame.SetCurGSCookie(Frame::SafeGetGSCookiePtr(pFrame));
}
while (((UINT_PTR)pFrame) < uCallerSP)
{
#if defined(_TARGET_ARM_)
// InlinedCallFrames (ICF) are allocated, initialized and linked to the Frame chain
// by the code generated by the JIT for a method containing a PInvoke.
//
// On X64, JIT generates code to dynamically link and unlink the ICF around
// each PInvoke call. On ARM, on the other hand, JIT's codegen, in context of ICF,
// is more inline with X86 and thus, it links in the ICF at the start of the method
// and unlinks it towards the method end. Thus, ICF is present on the Frame chain
// at any given point so long as the method containing the PInvoke is on the stack.
//
// Now, if the method containing ICF catches an exception, we will reset the Frame chain
// with the LimitFrame, that is computed below, after the catch handler returns. Since this
// computation is done relative to the CallerSP (on both X64 and ARM), we will end up
// removing the ICF from the Frame chain as that will always be below (stack growing down)
// the CallerSP since it lives in the stack space of the current managed frame.
//
// As a result, if there is another PInvoke call after the catch block, it will expect
// the ICF to be present and without one, execution will go south.
//
// To account for this ICF codegen difference, in the EH system we check if the current
// Frame is an ICF or not. If it is and lies inside the current managed method, we
// keep a reference to it and reset the LimitFrame to this saved reference before we
// return back to invoke the catc handler.
//
// Thus, if there is another PInvoke call post the catch handler, it will find ICF as expected.
//
// This is based upon the following assumptions:
//
// 1) There will be no other explicit Frame inserted above the ICF inside the
// managed method containing ICF. That is, ICF is the top-most explicit frame
// in the managed method (and thus, lies in the current managed frame).
//
// 2) There is only one ICF per managed method containing one (or more) PInvoke(s).
//
// 3) We only do this if the current frame is the one handling the exception. This is to
// address the scenario of keeping any ICF from frames lower in the stack active.
//
// 4) The ExceptionUnwind method of the ICF is a no-op. As noted above, we save a reference
// to the ICF and yet continue to process the frame chain. During unwind, this implies
// that we will end up invoking the ExceptionUnwind methods of all frames that lie
// below the caller SP of the managed frame handling the exception. And since the handling
// managed frame contains an ICF, it will be the topmost frame that will lie
// below the callerSP for which we will invoke ExceptionUnwind.
//
// Thus, ICF::ExceptionUnwind should not do anything significant. If any of these assumptions
// break, then the next best thing will be to make the JIT link/unlink the frame dynamically.
if (fTargetUnwind && (pFrame->GetVTablePtr() == InlinedCallFrame::GetMethodFrameVPtr()))
{
PTR_InlinedCallFrame pICF = (PTR_InlinedCallFrame)pFrame;
// Does it live inside the current managed method? It will iff:
//
// 1) ICF address is higher than the current frame's SP (which we get from DispatcherContext), AND
// 2) ICF address is below callerSP.
if ((GetSP(pDispatcherContext->ContextRecord) < (TADDR)pICF) &&
((UINT_PTR)pICF < uCallerSP))
{
pICFForUnwindTarget = pFrame;
}
}
#endif // defined(_TARGET_ARM)
cfThisFrame.CheckGSCookies();
if (fProcessThisFrame)
{
ExceptionTracker::InitializeCrawlFrameForExplicitFrame(&cfThisFrame, pFrame, pMD);
fCrawlFrameIsDirty = true;
status = ProcessExplicitFrame(
&cfThisFrame,
sf,
fIsFirstPass,
STState);
cfThisFrame.CheckGSCookies();
}
if (!fIsFirstPass)
{
//
// notify Frame of unwind
//
pFrame->ExceptionUnwind();
// If we have not yet set the initial explicit frame processed by this tracker, then
// set it now.
if (m_pInitialExplicitFrame == NULL)
{
m_pInitialExplicitFrame = pFrame;
}
}
pFrame = pFrame->Next();
m_pLimitFrame = pFrame;
if (UnwindPending != status)
{
goto lExit;
}
}
if (fCrawlFrameIsDirty)
{
// If crawlframe is dirty, it implies that it got modified as part of explicit frame processing. Thus, we shall
// reinitialize it here.
ExceptionTracker::InitializeCrawlFrame(&cfThisFrame, pThread, sf, ®disp, pDispatcherContext, ControlPc, &uMethodStartPC
ARM_ARG(this)
ARM64_ARG(this));
}
if (fIsFrameLess)
{
pGSCookie = (GSCookie*)cfThisFrame.GetCodeManager()->GetGSCookieAddr(cfThisFrame.pRD,
&cfThisFrame.codeInfo,
&cfThisFrame.codeManState);
if (pGSCookie)
{
// The following function call sets the GS cookie pointers and checks the cookie.
cfThisFrame.SetCurGSCookie(pGSCookie);
}
status = HandleFunclets(&fProcessThisFrame, fIsFirstPass,
cfThisFrame.GetFunction(), cfThisFrame.IsFunclet(), sf);
}
if ((!fIsFirstPass) && (!fProcessThisFrame))
{
// If we are unwinding and not processing the current frame, it implies that
// this frame has been unwound for one of the following reasons:
//
// 1) We have already seen it due to nested exception processing, OR
// 2) We are skipping frames to find a funclet's parent and thus, its been already
// unwound.
//
// If the current frame is NOT the target of unwind, update the last unwound
// establisher frame. We dont do this for "target of unwind" since it has the catch handler, for a
// dupilcate EH clause reported in the funclet, that needs to be invoked and thus, may have valid
// references to report for GC reporting.
//
// If we are not skipping the managed frame, then LastUnwoundEstablisherFrame will be updated later in this method,
// just before we return back to our caller.
if (!fTargetUnwind)
{
SetLastUnwoundEstablisherFrame(sf);
fSetLastUnwoundEstablisherFrame = true;
}
}
// GCX_COOP_THREAD_EXISTS ends here and we may switch to preemp mode now (if applicable).
}
//
// now process managed call frame if needed
//
if (fIsFrameLess)
{
if (fProcessThisFrame)
{
status = ProcessManagedCallFrame(
&cfThisFrame,
sf,
StackFrame::FromEstablisherFrame(pDispatcherContext->EstablisherFrame),
pExceptionRecord,
STState,
uMethodStartPC,
dwExceptionFlags,
dwTACatchHandlerClauseIndex,
sfEstablisherOfActualHandlerFrame);
if (pGSCookie)
{
cfThisFrame.CheckGSCookies();
}
}
if (fTargetUnwind && (UnwindPending == status))
{
SecondPassIsComplete(cfThisFrame.GetFunction(), sf);
status = SecondPassComplete;
}
}
lExit:
// If we are unwinding and have returned successfully from unwinding the frame, then mark it as the last unwound frame for the current
// exception. We dont do this if the frame is target of unwind(i.e. handling the exception) since catch block invocation may have references to be
// reported (if a GC happens during catch block invocation).
//
// If an exception escapes out of a funclet (this is only possible for fault/finally/catch clauses), then we will not return here.
// Since this implies that the funclet no longer has any valid references to report, we will need to set the LastUnwoundEstablisherFrame
// close to the point we detect the exception has escaped the funclet. This is done in ExceptionTracker::CallHandler and marks the
// frame that invoked (and thus, contained) the funclet as the LastUnwoundEstablisherFrame.
//
// Note: Do no add any GC triggering code between the return from ProcessManagedCallFrame and setting of the LastUnwoundEstablisherFrame
if ((!fIsFirstPass) && (!fTargetUnwind) && (!fSetLastUnwoundEstablisherFrame))
{
GCX_COOP();
SetLastUnwoundEstablisherFrame(sf);
}
if (FirstPassComplete == status)
{
FirstPassIsComplete();
}
if (fTargetUnwind && (status == SecondPassComplete))
{
#if defined(_TARGET_ARM_)
// If we have got a ICF to set as the LimitFrame, do that now.
// The Frame chain is still intact and would be updated using
// the LimitFrame (done after the catch handler returns).
//
// NOTE: This should be done as the last thing before we return
// back to invoke the catch handler.
if (pICFForUnwindTarget != NULL)
{
m_pLimitFrame = pICFForUnwindTarget;
pICFSetAsLimitFrame = (PVOID)pICFForUnwindTarget;
}
#endif // _TARGET_ARM_
// Since second pass is complete and we have reached
// the frame containing the catch funclet, reset the enclosing
// clause SP for the catch funclet, if applicable, to be the CallerSP of the
// current frame.
//
// Refer to the detailed comment about this code
// in ExceptionTracker::ProcessManagedCallFrame.
if (m_fResetEnclosingClauseSPForCatchFunclet)
{
#if defined(_TARGET_ARM_) || defined(_TARGET_ARM64_)
// DispatcherContext->EstablisherFrame's value
// represents the CallerSP of the current frame.
UINT_PTR EnclosingClauseCallerSP = (UINT_PTR)pDispatcherContext->EstablisherFrame;
#elif defined(_TARGET_AMD64_)
// Extract the CallerSP from RegDisplay on AMD64
REGDISPLAY *pRD = cfThisFrame.GetRegisterSet();
_ASSERTE(pRD->IsCallerContextValid || pRD->IsCallerSPValid);
UINT_PTR EnclosingClauseCallerSP = (UINT_PTR)GetSP(pRD->pCallerContext);
#else // !_ARM_ && !_AMD64_ && !_ARM64_
PORTABILITY_ASSERT("ExceptionTracker::ProcessOSExceptionNotification");
UINT_PTR EnclosingClauseCallerSP = NULL;
#endif // defined(_TARGET_ARM_) || defined(_TARGET_ARM64_)
m_EnclosingClauseInfo = EnclosingClauseInfo(false, cfThisFrame.GetRelOffset(), EnclosingClauseCallerSP);
}
m_fResetEnclosingClauseSPForCatchFunclet = FALSE;
}
// If we are unwinding and the exception was not caught in managed code and we have reached the
// topmost frame we saw in the first pass, then reset thread abort state if this is the last managed
// code personality routine on the stack.
if ((fIsFirstPass == false) && (this->GetTopmostStackFrameFromFirstPass() == sf) && (GetCatchToCallPC() == NULL))
{
ExceptionTracker::ResetThreadAbortStatus(pThread, &cfThisFrame, sf);
}
//
// fill in the out parameter
//
return status;
}
// static
void ExceptionTracker::DebugLogTrackerRanges(__in_z char *pszTag)
{
#ifdef _DEBUG
CONTRACTL
{
MODE_ANY;
GC_NOTRIGGER;
NOTHROW;
}
CONTRACTL_END;
Thread* pThread = GetThread();
ExceptionTracker* pTracker = pThread ? pThread->GetExceptionState()->m_pCurrentTracker : NULL;
int i = 0;
while (pTracker)
{
EH_LOG((LL_INFO100, "%s:|%02d| %p: (%p %p) %s\n", pszTag, i, pTracker, pTracker->m_ScannedStackRange.GetLowerBound().SP, pTracker->m_ScannedStackRange.GetUpperBound().SP,
pTracker->IsInFirstPass() ? "1st pass" : "2nd pass"
));
pTracker = pTracker->m_pPrevNestedInfo;
i++;
}
#endif // _DEBUG
}
bool ExceptionTracker::HandleNestedExceptionEscape(StackFrame sf, bool fIsFirstPass)
{
CONTRACTL
{
// Since this function can modify the scanned stack range, which is also accessed during the GC stackwalk,
// we invoke it in COOP mode so that that access to the range is synchronized.
MODE_COOPERATIVE;
GC_NOTRIGGER;
NOTHROW;
}
CONTRACTL_END;
bool fResult = false;
DebugLogTrackerRanges(" A");
ExceptionTracker* pPreviousTracker = m_pPrevNestedInfo;
while (pPreviousTracker && pPreviousTracker->m_ScannedStackRange.IsSupersededBy(sf))
{
//
// If the previous tracker (representing exception E1 and whose scanned stack range is superseded by the current frame)
// is in the first pass AND current tracker (representing exceptio E2) has not seen the current frame AND we are here,
// it implies that we had a nested exception while the previous tracker was in the first pass.
//
// This can happen in the following scenarios:
//
// 1) An exception escapes a managed filter (which are invoked in the first pass). However,
// that is not possible since any exception escaping them is swallowed by the runtime.
// If someone does longjmp from within the filter, then that is illegal and unsupported.
//
// 2) While processing an exception (E1), either us or native code caught it, triggering unwind. However, before the
// first managed frame was processed for unwind, another native frame (below the first managed frame on the stack)
// did a longjmp to go past us or raised another exception from one of their termination handlers.
//
// Thus, we will never get a chance to switch our tracker for E1 to 2nd pass (which would be done when
// ExceptionTracker::GetOrCreateTracker will be invoked for the first managed frame) since the longjmp, or the
// new-exception would result in a new tracker being setup.
//
// Below is an example of such a case that does longjmp
// ----------------------------------------------------
//
// NativeA (does setjmp) -> ManagedFunc -> NativeB
//
//
// NativeB could be implemented as:
//
// __try { // raise exception } __finally { longjmp(jmp1, 1); }
//
// "jmp1" is the jmp_buf setup by NativeA by calling setjmp.
//
// ManagedFunc could be implemented as:
//
// try {
// try { NativeB(); }
// finally { Console.WriteLine("Finally in ManagedFunc"); }
// }
// catch(Exception ex} { Console.WriteLine("Caught"); }
//
//
// In case of nested exception, we combine the stack range (see below) since we have already seen those frames
// in the specified pass for the previous tracker. However, in the example above, the current tracker (in 2nd pass)
// has not see the frames which the previous tracker (which is in the first pass) has seen.
//
// On a similar note, the __finally in the example above could also do a "throw 1;". In such a case, we would expect
// that the catch in ManagedFunc would catch the exception (since "throw 1;" would be represented as SEHException in
// the runtime). However, during first pass, when the exception enters ManagedFunc, the current tracker would not have
// processed the ManagedFunc frame, while the previous tracker (for E1) would have. If we proceed to combine the stack
// ranges, we will omit examining the catch clause in ManagedFunc.
//
// Thus, we cannot combine the stack range yet and must let each frame, already scanned by the previous
// tracker, be also processed by the current (longjmp) tracker if not already done.
//
// Note: This is not a concern if the previous tracker (for exception E1) is in the second pass since any escaping exception (E2)
// would come out of a finally/fault funclet and the runtime's funclet skipping logic will deal with it correctly.
if (pPreviousTracker->IsInFirstPass() && (!this->m_ScannedStackRange.Contains(sf)))
{
// Allow all stackframes seen by previous tracker to be seen by the current
// tracker as well.
if (sf <= pPreviousTracker->m_ScannedStackRange.GetUpperBound())
{
EH_LOG((LL_INFO100, " - not updating current tracker bounds for escaped exception since\n"));
EH_LOG((LL_INFO100, " - active tracker (%p; %s) has not seen the current frame [", this, this->IsInFirstPass()?"FirstPass":"SecondPass"));
EH_LOG((LL_INFO100, " - SP = %p", sf.SP));
EH_LOG((LL_INFO100, "]\n"));
EH_LOG((LL_INFO100, " - which the previous (%p) tracker has processed.\n", pPreviousTracker));
return fResult;
}
}
EH_LOG((LL_INFO100, " nested exception ESCAPED\n"));
EH_LOG((LL_INFO100, " - updating current tracker stack bounds\n"));
m_ScannedStackRange.CombineWith(sf, &pPreviousTracker->m_ScannedStackRange);
//
// Only the topmost tracker can be in the first pass.
//
// (Except in the case where we have an exception thrown in a filter,
// which should never escape the filter, and thus, will never supersede
// the previous exception. This is why we cannot walk the entire list
// of trackers to assert that they're all in the right mode.)
//
// CONSISTENCY_CHECK(!pPreviousTracker->IsInFirstPass());
// If our modes don't match, don't actually delete the supersceded exception.
// If we did, we would lose valueable state on which frames have been scanned
// on the second pass if an exception is thrown during the 2nd pass.
// Advance the current tracker pointer now, since it may be deleted below.
pPreviousTracker = pPreviousTracker->m_pPrevNestedInfo;
if (!fIsFirstPass)
{
EH_LOG((LL_INFO100, " - removing previous tracker\n"));
ExceptionTracker* pTrackerToFree = m_pPrevNestedInfo;
m_pPrevNestedInfo = pTrackerToFree->m_pPrevNestedInfo;
#if defined(DEBUGGING_SUPPORTED)
if (g_pDebugInterface != NULL)
{
g_pDebugInterface->DeleteInterceptContext(pTrackerToFree->m_DebuggerExState.GetDebuggerInterceptContext());
}
#endif // DEBUGGING_SUPPORTED
CONSISTENCY_CHECK(pTrackerToFree->IsValid());
FreeTrackerMemory(pTrackerToFree, memBoth);
}
DebugLogTrackerRanges(" B");
}
return fResult;
}
CLRUnwindStatus ExceptionTracker::ProcessExplicitFrame(
CrawlFrame* pcfThisFrame,
StackFrame sf,
BOOL fIsFirstPass,
StackTraceState& STState
)
{
CONTRACTL
{
MODE_COOPERATIVE;
GC_TRIGGERS;
THROWS;
PRECONDITION(!pcfThisFrame->IsFrameless());
PRECONDITION(pcfThisFrame->GetFrame() != FRAME_TOP);
}
CONTRACTL_END;
Frame* pFrame = pcfThisFrame->GetFrame();
EH_LOG((LL_INFO100, " [ ProcessExplicitFrame: pFrame: " FMT_ADDR " pMD: " FMT_ADDR " %s PASS ]\n", DBG_ADDR(pFrame), DBG_ADDR(pFrame->GetFunction()), fIsFirstPass ? "FIRST" : "SECOND"));
if (FRAME_TOP == pFrame)
{
goto lExit;
}
if (!m_ExceptionFlags.UnwindingToFindResumeFrame())
{
//
// update our exception stacktrace
//
BOOL bReplaceStack = FALSE;
BOOL bSkipLastElement = FALSE;
if (STS_FirstRethrowFrame == STState)
{
bSkipLastElement = TRUE;
}
else
if (STS_NewException == STState)
{
bReplaceStack = TRUE;
}
// Normally, we need to notify the profiler in two cases:
// 1) a brand new exception is thrown, and
// 2) an exception is rethrown.
// However, in this case, if the explicit frame doesn't correspond to a MD, we don't set STState to STS_Append,
// so the next managed call frame we process will give another ExceptionThrown() callback to the profiler.
// So we give the callback below, only in the case when we append to the stack trace.
MethodDesc* pMD = pcfThisFrame->GetFunction();
if (pMD)
{
Thread* pThread = m_pThread;
if (fIsFirstPass)
{
//
// notify profiler of new/rethrown exception
//
if (bSkipLastElement || bReplaceStack)
{
GCX_COOP();
EEToProfilerExceptionInterfaceWrapper::ExceptionThrown(pThread);
UpdatePerformanceMetrics(pcfThisFrame, bSkipLastElement, bReplaceStack);
}
//
// Update stack trace
//
m_StackTraceInfo.AppendElement(CanAllocateMemory(), NULL, sf.SP, pMD, pcfThisFrame);
m_StackTraceInfo.SaveStackTrace(CanAllocateMemory(), m_hThrowable, bReplaceStack, bSkipLastElement);
//
// make callback to debugger and/or profiler
//
#if defined(DEBUGGING_SUPPORTED)
if (ExceptionTracker::NotifyDebuggerOfStub(pThread, sf, pFrame))
{
#ifdef FEATURE_EXCEPTION_NOTIFICATIONS
// Deliver the FirstChanceNotification after the debugger, if not already delivered.
if (!this->DeliveredFirstChanceNotification())
{
ExceptionNotifications::DeliverFirstChanceNotification();
}
#endif // FEATURE_EXCEPTION_NOTIFICATIONS
}
#endif // DEBUGGING_SUPPORTED
STState = STS_Append;
}
}
}
lExit:
return UnwindPending;
}
CLRUnwindStatus ExceptionTracker::HandleFunclets(bool* pfProcessThisFrame, bool fIsFirstPass,
MethodDesc * pMD, bool fFunclet, StackFrame sf)
{
CONTRACTL
{
MODE_ANY;
GC_NOTRIGGER;
NOTHROW;
}
CONTRACTL_END;
#ifdef WIN64EXCEPTIONS // funclets
BOOL fUnwindingToFindResumeFrame = m_ExceptionFlags.UnwindingToFindResumeFrame();
//
// handle out-of-line finallys
//
// In the second pass, we always want to execute this code.
// In the first pass, we only execute this code if we are not unwinding to find the resume frame.
// We do this to avoid calling the same filter more than once. Search for "UnwindingToFindResumeFrame"
// to find a more elaborate comment in ProcessManagedCallFrame().
// If we are in the first pass and we are unwinding to find the resume frame, then make sure the flag is cleared.
if (fIsFirstPass && fUnwindingToFindResumeFrame)
{
m_pSkipToParentFunctionMD = NULL;
}
else
{
// <TODO>
// this 'skip to parent function MD' code only seems to be needed
// in the case where we call a finally funclet from the normal
// execution codepath. Is there a better way to achieve the same
// goal? Also, will recursion break us in any corner cases?
// [ThrowInFinallyNestedInTryTest]
// [GoryManagedPresentTest]
// </TODO>
// <TODO>
// this was done for AMD64, but i don't understand why AMD64 needed the workaround..
// (the workaround is the "double call on parent method" part.)
// </TODO>
//
// If we encounter a funclet, we need to skip all call frames up
// to and including its parent method call frame. The reason
// behind this is that a funclet is logically part of the parent
// method has all the clauses that covered its logical location
// in the parent covering its body.
//
if (((UINT_PTR)m_pSkipToParentFunctionMD) & 1)
{
EH_LOG((LL_INFO100, " IGNOREFRAME: SKIPTOPARENT: skipping to parent\n"));
*pfProcessThisFrame = false;
if ((((UINT_PTR)pMD) == (((UINT_PTR)m_pSkipToParentFunctionMD) & ~((UINT_PTR)1))) && !fFunclet)
{
EH_LOG((LL_INFO100, " SKIPTOPARENT: found parent for funclet pMD = %p, sf.SP = %p, will stop skipping frames\n", pMD, sf.SP));
_ASSERTE(0 == (((UINT_PTR)sf.SP) & 1));
m_pSkipToParentFunctionMD = (MethodDesc*)sf.SP;
_ASSERTE(!fUnwindingToFindResumeFrame);
}
}
else if (fFunclet)
{
EH_LOG((LL_INFO100, " SKIPTOPARENT: found funclet pMD = %p, will start skipping frames\n", pMD));
_ASSERTE(0 == (((UINT_PTR)pMD) & 1));
m_pSkipToParentFunctionMD = (MethodDesc*)(((UINT_PTR)pMD) | 1);
}
else
{
if (sf.SP == ((UINT_PTR)m_pSkipToParentFunctionMD))
{
EH_LOG((LL_INFO100, " IGNOREFRAME: SKIPTOPARENT: got double call on parent method\n"));
*pfProcessThisFrame = false;
}
else if (m_pSkipToParentFunctionMD && (sf.SP > ((UINT_PTR)m_pSkipToParentFunctionMD)))
{
EH_LOG((LL_INFO100, " SKIPTOPARENT: went past parent method\n"));
m_pSkipToParentFunctionMD = NULL;
}
}
}
#endif // WIN64EXCEPTIONS
return UnwindPending;
}
CLRUnwindStatus ExceptionTracker::ProcessManagedCallFrame(
CrawlFrame* pcfThisFrame,
StackFrame sf,
StackFrame sfEstablisherFrame,
EXCEPTION_RECORD* pExceptionRecord,
StackTraceState STState,
UINT_PTR uMethodStartPC,
DWORD dwExceptionFlags,
DWORD dwTACatchHandlerClauseIndex,
StackFrame sfEstablisherOfActualHandlerFrame
)
{
CONTRACTL
{
MODE_ANY;
GC_TRIGGERS;
THROWS;
PRECONDITION(pcfThisFrame->IsFrameless());
}
CONTRACTL_END;
UINT_PTR uControlPC = (UINT_PTR)GetControlPC(pcfThisFrame->GetRegisterSet());
CLRUnwindStatus ReturnStatus = UnwindPending;
MethodDesc* pMD = pcfThisFrame->GetFunction();
bool fIsFirstPass = !(dwExceptionFlags & EXCEPTION_UNWINDING);
bool fIsFunclet = pcfThisFrame->IsFunclet();
CONSISTENCY_CHECK(IsValid());
CONSISTENCY_CHECK(ThrowableIsValid() || !fIsFirstPass);
CONSISTENCY_CHECK(pMD != 0);
EH_LOG((LL_INFO100, " [ ProcessManagedCallFrame this=%p, %s PASS ]\n", this, (fIsFirstPass ? "FIRST" : "SECOND")));
#ifdef WIN64EXCEPTIONS // funclets
EH_LOG((LL_INFO100, " [ method: %s%s, %s ]\n",
(fIsFunclet ? "FUNCLET of " : ""),
pMD->m_pszDebugMethodName, pMD->m_pszDebugClassName));
#else // !WIN64EXCEPTIONS
EH_LOG((LL_INFO100, " [ method: %s, %s ]\n",
pMD->m_pszDebugMethodName, pMD->m_pszDebugClassName));
#endif // WIN64EXCEPTIONS
Thread *pThread = GetThread();
_ASSERTE (pThread);
INDEBUG( DumpClauses(pcfThisFrame->GetJitManager(), pcfThisFrame->GetMethodToken(), uMethodStartPC, uControlPC) );
bool fIsILStub = pMD->IsILStub();
bool fGiveDebuggerAndProfilerNotification = !fIsILStub;
BOOL fUnwindingToFindResumeFrame = m_ExceptionFlags.UnwindingToFindResumeFrame();
bool fIgnoreThisFrame = false;
bool fProcessThisFrameToFindResumeFrameOnly = false;
MethodDesc * pUserMDForILStub = NULL;
Frame * pILStubFrame = NULL;
if (fIsILStub && !fIsFunclet) // only make this callback on the main method body of IL stubs
pUserMDForILStub = GetUserMethodForILStub(pThread, sf.SP, pMD, &pILStubFrame);
#ifdef FEATURE_CORRUPTING_EXCEPTIONS
BOOL fCanMethodHandleException = TRUE;
CorruptionSeverity currentSeverity = NotCorrupting;
{
// Switch to COOP mode since we are going to request throwable
GCX_COOP();
// We must defer to the MethodDesc of the user method instead of the IL stub
// itself because the user can specify the policy on a per-method basis and
// that won't be reflected via the IL stub's MethodDesc.
MethodDesc * pMDWithCEAttribute = (pUserMDForILStub != NULL) ? pUserMDForILStub : pMD;
// Check if the exception can be delivered to the method? It will check if the exception
// is a CE or not. If it is, it will check if the method can process it or not.
currentSeverity = pThread->GetExceptionState()->GetCurrentExceptionTracker()->GetCorruptionSeverity();
fCanMethodHandleException = CEHelper::CanMethodHandleException(currentSeverity, pMDWithCEAttribute);
}
#endif // FEATURE_CORRUPTING_EXCEPTIONS
// Doing rude abort. Skip all non-constrained execution region code.
// When rude abort is initiated, we cannot intercept any exceptions.
if ((pThread->IsRudeAbortInitiated() && !pThread->IsWithinCer(pcfThisFrame)))
{
// If we are unwinding to find the real resume frame, then we cannot ignore frames yet.
// We need to make sure we find the correct resume frame before starting to ignore frames.
if (fUnwindingToFindResumeFrame)
{
fProcessThisFrameToFindResumeFrameOnly = true;
}
else
{
EH_LOG((LL_INFO100, " IGNOREFRAME: rude abort/CE\n"));
fIgnoreThisFrame = true;
}
}
//
// BEGIN resume frame processing code
//
// Often times, we'll run into the situation where the actual resume call frame
// is not the same call frame that we see the catch clause in. The reason for this
// is that catch clauses get duplicated down to cover funclet code ranges. When we
// see a catch clause covering our control PC, but it is marked as a duplicate, we
// need to continue to unwind until we find the same clause that isn't marked as a
// duplicate. This will be the correct resume frame.
//
// We actually achieve this skipping by observing that if we are catching at a
// duplicated clause, all the call frames we should be skipping have already been
// processed by a previous exception dispatch. So if we allow the unwind to
// continue, we will immediately bump into the ExceptionTracker for the previous
// dispatch, and our resume frame will be the last frame seen by that Tracker.
//
// Note that we will have visited all the EH clauses for a particular method when we
// see its first funclet (the funclet which is closest to the leaf). We need to make
// sure we don't process any EH clause again when we see other funclets or the parent
// method until we get to the real resume frame. The real resume frame may be another
// funclet, which is why we can't blindly skip all funclets until we see the parent
// method frame.
//
// If the exception is handled by the method, then UnwindingToFindResumeFrame takes
// care of the skipping. We basically skip everything when we are unwinding to find
// the resume frame. If the exception is not handled by the method, then we skip all the
// funclets until we get to the parent method. The logic to handle this is in
// HandleFunclets(). In the first pass, HandleFunclets() only kicks
// in if we are not unwinding to find the resume frame.
//
// Then on the second pass, we need to process frames up to the initial place where
// we saw the catch clause, which means upto and including part of the resume stack
// frame. Then we need to skip the call frames up to the real resume stack frame
// and resume.
//
// In the second pass, we have the same problem with skipping funclets as in the first
// pass. However, in this case, we know exactly which frame is our target unwind frame
// (EXCEPTION_TARGET_UNWIND will be set). So we blindly unwind until we see the parent
// method, or until the target unwind frame.
PTR_EXCEPTION_CLAUSE_TOKEN pLimitClauseToken = NULL;
if (!fIgnoreThisFrame && !fIsFirstPass && !m_sfResumeStackFrame.IsNull() && (sf >= m_sfResumeStackFrame))
{
CONSISTENCY_CHECK_MSG(sf == m_sfResumeStackFrame, "Passed initial resume frame and fIgnoreThisFrame wasn't set!");
EH_LOG((LL_INFO100, " RESUMEFRAME: %s initial resume frame: %p\n", (sf == m_sfResumeStackFrame) ? "REACHED" : "PASSED" , m_sfResumeStackFrame.SP));
// process this frame to call handlers
EH_LOG((LL_INFO100, " RESUMEFRAME: Found last frame to process finallys in, need to process only part of call frame\n"));
EH_LOG((LL_INFO100, " RESUMEFRAME: Limit clause token: %p\n", m_pClauseForCatchToken));
pLimitClauseToken = m_pClauseForCatchToken;
// The limit clause is the same as the clause we're catching at. It is used
// as the last clause we process in the "inital resume frame". Anything further
// down the list of clauses is skipped along with all call frames up to the actual
// resume frame.
}
//
// END resume frame code
//
if (!fIgnoreThisFrame)
{
BOOL fFoundHandler = FALSE;
DWORD_PTR dwHandlerStartPC = NULL;
BOOL bReplaceStack = FALSE;
BOOL bSkipLastElement = FALSE;
bool fUnwindFinished = false;
if (STS_FirstRethrowFrame == STState)
{
bSkipLastElement = TRUE;
}
else
if (STS_NewException == STState)
{
bReplaceStack = TRUE;
}
// We need to notify the profiler on the first pass in two cases:
// 1) a brand new exception is thrown, and
// 2) an exception is rethrown.
if (fIsFirstPass && (bSkipLastElement || bReplaceStack))
{
GCX_COOP();
EEToProfilerExceptionInterfaceWrapper::ExceptionThrown(pThread);
UpdatePerformanceMetrics(pcfThisFrame, bSkipLastElement, bReplaceStack);
}
if (!fUnwindingToFindResumeFrame)
{
//
// update our exception stacktrace, ignoring IL stubs
//
if (fIsFirstPass && !pMD->IsILStub())
{
GCX_COOP();
m_StackTraceInfo.AppendElement(CanAllocateMemory(), uControlPC, sf.SP, pMD, pcfThisFrame);
m_StackTraceInfo.SaveStackTrace(CanAllocateMemory(), m_hThrowable, bReplaceStack, bSkipLastElement);
}
//
// make callback to debugger and/or profiler
//
if (fGiveDebuggerAndProfilerNotification)
{
if (fIsFirstPass)
{
EEToProfilerExceptionInterfaceWrapper::ExceptionSearchFunctionEnter(pMD);
// Notfiy the debugger that we are on the first pass for a managed exception.
// Note that this callback is made for every managed frame.
EEToDebuggerExceptionInterfaceWrapper::FirstChanceManagedException(pThread, uControlPC, sf.SP);
#if defined(DEBUGGING_SUPPORTED)
_ASSERTE(this == pThread->GetExceptionState()->m_pCurrentTracker);
// check if the current exception has been intercepted.
if (m_ExceptionFlags.DebuggerInterceptInfo())
{
// According to the x86 implementation, we don't need to call the ExceptionSearchFunctionLeave()
// profiler callback.
StackFrame sfInterceptStackFrame;
m_DebuggerExState.GetDebuggerInterceptInfo(NULL, NULL,
reinterpret_cast<PBYTE *>(&(sfInterceptStackFrame.SP)),
NULL, NULL);
// Save the target unwind frame just like we do when we find a catch clause.
m_sfResumeStackFrame = sfInterceptStackFrame;
ReturnStatus = FirstPassComplete;
goto lExit;
}
#endif // DEBUGGING_SUPPORTED
#ifdef FEATURE_EXCEPTION_NOTIFICATIONS
// Attempt to deliver the first chance notification to the AD only *AFTER* the debugger
// has done that, provided we have not already delivered it.
if (!this->DeliveredFirstChanceNotification())
{
ExceptionNotifications::DeliverFirstChanceNotification();
}
#endif // FEATURE_EXCEPTION_NOTIFICATIONS
}
else
{
#if defined(DEBUGGING_SUPPORTED)
_ASSERTE(this == pThread->GetExceptionState()->m_pCurrentTracker);
// check if the exception is intercepted.
if (m_ExceptionFlags.DebuggerInterceptInfo())
{
MethodDesc* pInterceptMD = NULL;
StackFrame sfInterceptStackFrame;
// check if we have reached the interception point yet
m_DebuggerExState.GetDebuggerInterceptInfo(&pInterceptMD, NULL,
reinterpret_cast<PBYTE *>(&(sfInterceptStackFrame.SP)),
NULL, NULL);
// If the exception has gone unhandled in the first pass, we wouldn't have a chance
// to set the target unwind frame. Check for this case now.
if (m_sfResumeStackFrame.IsNull())
{
m_sfResumeStackFrame = sfInterceptStackFrame;
}
_ASSERTE(m_sfResumeStackFrame == sfInterceptStackFrame);
if ((pInterceptMD == pMD) &&
(sfInterceptStackFrame == sf))
{
// If we have reached the stack frame at which the exception is intercepted,
// then finish the second pass prematurely.
SecondPassIsComplete(pMD, sf);
ReturnStatus = SecondPassComplete;
goto lExit;
}
}
#endif // DEBUGGING_SUPPORTED
// According to the x86 implementation, we don't need to call the ExceptionUnwindFunctionEnter()
// profiler callback when an exception is intercepted.
EEToProfilerExceptionInterfaceWrapper::ExceptionUnwindFunctionEnter(pMD);
}
}
}
#ifdef FEATURE_STACK_PROBE
// Don't call a handler if we're within a certain distance of the end of the stack. Could end up here via probe, in
// which case guard page is intact, or via hard SO, in which case guard page won't be. So don't check for presence of
// guard page, just check for sufficient space on stack.
if ( IsStackOverflowException()
&& !pThread->CanResetStackTo((void*)sf.SP))
{
EH_LOG((LL_INFO100, " STACKOVERFLOW: IGNOREFRAME: stack frame too close to guard page: sf.SP: %p\n", sf.SP));
}
else
#endif // FEATURE_STACK_PROBE
{
IJitManager* pJitMan = pcfThisFrame->GetJitManager();
const METHODTOKEN& MethToken = pcfThisFrame->GetMethodToken();
EH_CLAUSE_ENUMERATOR EnumState;
unsigned EHCount;
#ifdef FEATURE_CORRUPTING_EXCEPTIONS
// The method cannot handle the exception (e.g. cannot handle the CE), then simply bail out
// without examining the EH clauses in it.
if (!fCanMethodHandleException)
{
LOG((LF_EH, LL_INFO100, "ProcessManagedCallFrame - CEHelper decided not to look for exception handlers in the method(MD:%p).\n", pMD));
// Set the flag to skip this frame since the CE cannot be delivered
_ASSERTE(currentSeverity == ProcessCorrupting);
// Force EHClause count to be zero
EHCount = 0;
}
else
#endif // FEATURE_CORRUPTING_EXCEPTIONS
{
EHCount = pJitMan->InitializeEHEnumeration(MethToken, &EnumState);
}
if (!fIsFirstPass)
{
// For a method that may have nested funclets, it is possible that a reference maybe
// dead at the point where control flow left the method but may become active once
// a funclet is executed.
//
// Upon returning from the funclet but before the next funclet is invoked, a GC
// may happen if we are in preemptive mode. Since the GC stackwalk will commence
// at the original IP at which control left the method, it can result in the reference
// not being updated (since it was dead at the point control left the method) if the object
// is moved during GC.
//
// To address this, we will indefinitely switch to COOP mode while enumerating, and invoking,
// funclets.
//
// This switch is also required for another scenario: we maybe in unwind phase and the current frame
// may not have any termination handlers to be invoked (i.e. it may have zero EH clauses applicable to
// the unwind phase). If we do not switch to COOP mode for such a frame, we could remain in preemp mode.
// Upon returning back from ProcessOSExceptionNotification in ProcessCLRException, when we attempt to
// switch to COOP mode to update the LastUnwoundEstablisherFrame, we could get blocked due to an
// active GC, prior to peforming the update.
//
// In this case, if the GC stackwalk encounters the current frame and attempts to check if it has been
// unwound by an exception, then while it has been unwound (especially since it had no termination handlers)
// logically, it will not figure out as unwound and thus, GC stackwalk would attempt to report references from
// it, which is incorrect.
//
// Thus, when unwinding, we will always switch to COOP mode indefinitely, irrespective of whether
// the frame has EH clauses to be processed or not.
GCX_COOP_NO_DTOR();
// We will also forbid any GC to happen between successive funclet invocations.
// This will be automatically undone when the contract goes off the stack as the method
// returns back to its caller.
BEGINFORBIDGC();
}
for (unsigned i = 0; i < EHCount; i++)
{
EE_ILEXCEPTION_CLAUSE EHClause;
PTR_EXCEPTION_CLAUSE_TOKEN pEHClauseToken = pJitMan->GetNextEHClause(&EnumState, &EHClause);
EH_LOG((LL_INFO100, " considering %s clause [%x,%x], ControlPc is %s clause (offset %x)",
(IsFault(&EHClause) ? "fault" :
(IsFinally(&EHClause) ? "finally" :
(IsFilterHandler(&EHClause) ? "filter" :
(IsTypedHandler(&EHClause) ? "typed" : "unknown")))),
EHClause.TryStartPC,
EHClause.TryEndPC,
(ClauseCoversPC(&EHClause, pcfThisFrame->GetRelOffset()) ? "inside" : "outside"),
pcfThisFrame->GetRelOffset()
));
LOG((LF_EH, LL_INFO100, "\n"));
// If we have a valid EstablisherFrame for the managed frame where
// ThreadAbort was raised after the catch block, then see if we
// have reached that frame during the exception dispatch. If we
// have, then proceed to skip applicable EH clauses.
if ((!sfEstablisherOfActualHandlerFrame.IsNull()) && (sfEstablisherFrame == sfEstablisherOfActualHandlerFrame))
{
// We should have a valid index of the EH clause (corresponding to a catch block) after
// which thread abort was raised?
_ASSERTE(dwTACatchHandlerClauseIndex > 0);
{
// Since we have the index, check if the current EH clause index
// is less then saved index. If it is, then it implies that
// we are evaluating clauses that lie "before" the EH clause
// for the catch block "after" which thread abort was raised.
//
// Since ThreadAbort has to make forward progress, we will
// skip evaluating any such EH clauses. Two things can happen:
//
// 1) We will find clauses representing handlers beyond the
// catch block after which ThreadAbort was raised. Since this is
// what we want, we evaluate them.
//
// 2) There wont be any more clauses implying that the catch block
// after which the exception was raised was the outermost
// handler in the method. Thus, the exception will escape out,
// which is semantically the correct thing to happen.
//
// The premise of this check is based upon a JIT compiler's implementation
// detail: when it generates EH clauses, JIT compiler will order them from
// top->bottom (when reading a method) and inside->out when reading nested
// clauses.
//
// This assumption is not new since the basic EH type-matching is reliant
// on this very assumption. However, now we have one more candidate that
// gets to rely on it.
//
// Eventually, this enables forward progress of thread abort exception.
if (i <= (dwTACatchHandlerClauseIndex -1))
{
EH_LOG((LL_INFO100, " skipping the evaluation of EH clause (index=%d) since we cannot process an exception in a handler\n", i));
EH_LOG((LL_INFO100, " that exists prior to the one (index=%d) after which ThreadAbort was [re]raised.\n", dwTACatchHandlerClauseIndex));
continue;
}
}
}
// see comment above where we set pLimitClauseToken
if (pEHClauseToken == pLimitClauseToken)
{
EH_LOG((LL_INFO100, " found limit clause, stopping clause enumeration\n"));
// <GC_FUNCLET_REFERENCE_REPORTING>
//
// If we are here, the exception has been identified to be handled by a duplicate catch clause
// that is protecting the current funclet. The call to SetEnclosingClauseInfo (below)
// will setup the CallerSP (for GC reference reporting) to be the SP of the
// of the caller of current funclet (where the exception has happened, or is escaping from).
//
// However, we need the CallerSP to be set as the SP of the caller of the
// actual frame that will contain (and invoke) the catch handler corresponding to
// the duplicate clause. But that isn't available right now and we can only know
// once we unwind upstack to reach the target frame.
//
// Thus, upon reaching the target frame and before invoking the catch handler,
// we will fix up the CallerSP (for GC reporting) to be that of the caller of the
// target frame that will be invoking the actual catch handler.
//
// </GC_FUNCLET_REFERENCE_REPORTING>
//
// for catch clauses
SetEnclosingClauseInfo(fIsFunclet,
pcfThisFrame->GetRelOffset(),
GetSP(pcfThisFrame->GetRegisterSet()->pCallerContext));
fUnwindFinished = true;
m_fFixupCallerSPForGCReporting = true;
break;
}
BOOL fTermHandler = IsFaultOrFinally(&EHClause);
fFoundHandler = FALSE;
if (( fIsFirstPass && fTermHandler) ||
(!fIsFirstPass && !fTermHandler))
{
continue;
}
if (ClauseCoversPC(&EHClause, pcfThisFrame->GetRelOffset()))
{
EH_LOG((LL_INFO100, " clause covers ControlPC\n"));
dwHandlerStartPC = pJitMan->GetCodeAddressForRelOffset(MethToken, EHClause.HandlerStartPC);
if (fUnwindingToFindResumeFrame)
{
CONSISTENCY_CHECK(fIsFirstPass);
if (!fTermHandler)
{
// m_pClauseForCatchToken can only be NULL for continuable exceptions, but we should never
// get here if we are handling continuable exceptions. fUnwindingToFindResumeFrame is
// only true at the end of the first pass.
_ASSERTE(m_pClauseForCatchToken != NULL);
// handlers match and not duplicate?
EH_LOG((LL_INFO100, " RESUMEFRAME: catch handler: [%x,%x], this handler: [%x,%x] %s\n",
m_ClauseForCatch.HandlerStartPC,
m_ClauseForCatch.HandlerEndPC,
EHClause.HandlerStartPC,
EHClause.HandlerEndPC,
IsDuplicateClause(&EHClause) ? "[duplicate]" : ""));
if ((m_ClauseForCatch.HandlerStartPC == EHClause.HandlerStartPC) &&
(m_ClauseForCatch.HandlerEndPC == EHClause.HandlerEndPC))
{
EH_LOG((LL_INFO100, " RESUMEFRAME: found clause with same handler as catch\n"));
if (!IsDuplicateClause(&EHClause))
{
CONSISTENCY_CHECK(fIsFirstPass);
if (fProcessThisFrameToFindResumeFrameOnly)
{
EH_LOG((LL_INFO100, " RESUMEFRAME: identified real resume frame, \
but rude thread abort is initiated: %p\n", sf.SP));
// We have found the real resume frame. However, rude thread abort
// has been initiated. Thus, we need to continue the first pass
// as if we have not found a handler yet. To do so, we need to
// reset all the information we have saved when we find the handler.
m_ExceptionFlags.ResetUnwindingToFindResumeFrame();
m_uCatchToCallPC = NULL;
m_pClauseForCatchToken = NULL;
m_sfResumeStackFrame.Clear();
ReturnStatus = UnwindPending;
}
else
{
EH_LOG((LL_INFO100, " RESUMEFRAME: identified real resume frame: %p\n", sf.SP));
// Save off the index and the EstablisherFrame of the EH clause of the non-duplicate handler
// that decided to handle the exception. We may need it
// if a ThreadAbort is raised after the catch block
// executes.
m_dwIndexClauseForCatch = i + 1;
m_sfEstablisherOfActualHandlerFrame = sfEstablisherFrame;
#ifdef _TARGET_AMD64_
m_sfCallerOfActualHandlerFrame = EECodeManager::GetCallerSp(pcfThisFrame->pRD);
#else
// On ARM & ARM64, the EstablisherFrame is the value of SP at the time a function was called and before it's prolog
// executed. Effectively, it is the SP of the caller.
m_sfCallerOfActualHandlerFrame = sfEstablisherFrame.SP;
#endif
ReturnStatus = FirstPassComplete;
}
}
break;
}
}
}
else if (IsFilterHandler(&EHClause))
{
DWORD_PTR dwResult = EXCEPTION_CONTINUE_SEARCH;
DWORD_PTR dwFilterStartPC;
dwFilterStartPC = pJitMan->GetCodeAddressForRelOffset(MethToken, EHClause.FilterOffset);
EH_LOG((LL_INFO100, " calling filter\n"));
// @todo : If user code throws a StackOveflowException and we have plenty of stack,
// we probably don't want to be so strict in not calling handlers.
if (! IsStackOverflowException())
{
#ifndef FEATURE_PAL
// Check for any impersonation on the frame and save that for use during EH filter callbacks
OBJECTREF* pRefSecDesc = pcfThisFrame->GetAddrOfSecurityObject();
if (pRefSecDesc != NULL && *pRefSecDesc != NULL)
{
GCX_COOP();
FRAMESECDESCREF fsdRef = (FRAMESECDESCREF)*pRefSecDesc;
if (fsdRef->GetCallerToken() != NULL)
{
m_hCallerToken = fsdRef->GetCallerToken();
STRESS_LOG1(LF_EH, LL_INFO100, "In COMPlusThrowCallback. Found non-NULL callertoken on FSD:%d\n",m_hCallerToken);
if (!m_ExceptionFlags.ImpersonationTokenSet())
{
m_hImpersonationToken = fsdRef->GetImpersonationToken();
STRESS_LOG1(LF_EH, LL_INFO100, "In COMPlusThrowCallback. Found non-NULL impersonationtoken on FSD:%d\n",m_hImpersonationToken);
m_ExceptionFlags.SetImpersonationTokenSet();
}
}
}
BOOL impersonating = FALSE;
#endif // !FEATURE_PAL
// Save the current EHClause Index and Establisher of the clause post which
// ThreadAbort was raised. This is done an exception handled inside a filter
// reset the state that was setup before the filter was invoked.
//
// We dont have to do this for finally/fault clauses since they execute
// in the second pass and by that time, we have already skipped the required
// EH clauses in the applicable stackframe.
DWORD dwPreFilterTACatchHandlerClauseIndex = dwTACatchHandlerClauseIndex;
StackFrame sfPreFilterEstablisherOfActualHandlerFrame = sfEstablisherOfActualHandlerFrame;
EX_TRY
{
#ifndef FEATURE_PAL
if (m_hCallerToken != NULL)
{
STRESS_LOG1(LF_EH, LL_INFO100, "About to call filter with hCallerToken = %d\n",m_hCallerToken);
// CLR_ImpersonateLoggedOnUser fails fast on error
COMPrincipal::CLR_ImpersonateLoggedOnUser(m_hCallerToken);
impersonating = TRUE;
}
#endif // !FEATURE_PAL
// We want to call filters even if the thread is aborting, so suppress abort
// checks while the filter runs.
ThreadPreventAsyncHolder preventAbort(TRUE);
// for filter clauses
SetEnclosingClauseInfo(fIsFunclet,
pcfThisFrame->GetRelOffset(),
GetSP(pcfThisFrame->GetRegisterSet()->pCallerContext));
#if defined(_TARGET_ARM_) || defined(_TARGET_ARM64_)
// On ARM & ARM64, the OS passes us the CallerSP for the frame for which personality routine has been invoked.
// Since IL filters are invoked in the first pass, we pass this CallerSP to the filter funclet which will
// then lookup the actual frame pointer value using it since we dont have a frame pointer to pass to it
// directly.
//
// Assert our invariants (we had set them up in InitializeCrawlFrame):
REGDISPLAY *pCurRegDisplay = pcfThisFrame->GetRegisterSet();
// 1) In first pass, we dont have a valid current context IP
_ASSERTE(GetIP(pCurRegDisplay->pCurrentContext) == 0);
// 2) Our caller context and caller SP are valid
_ASSERTE(pCurRegDisplay->IsCallerContextValid && pCurRegDisplay->IsCallerSPValid);
// 3) CallerSP is intact
_ASSERTE(GetSP(pCurRegDisplay->pCallerContext) == GetRegdisplaySP(pCurRegDisplay));
#endif // _TARGET_ARM_ || _TARGET_ARM64_
{
// CallHandler expects to be in COOP mode.
GCX_COOP();
dwResult = CallHandler(dwFilterStartPC, sf, &EHClause, pMD, Filter ARM_ARG(pCurRegDisplay->pCallerContext) ARM64_ARG(pCurRegDisplay->pCallerContext));
}
#ifndef FEATURE_PAL
if (impersonating)
{
STRESS_LOG1(LF_EH, LL_INFO100, "After calling filter, resetting to hImpersonationToken = %d\n",m_hImpersonationToken);
// CLR_ImpersonateLoggedOnUser fails fast on error
COMPrincipal::CLR_ImpersonateLoggedOnUser(m_hImpersonationToken);
impersonating = FALSE;
}
#endif // !FEATURE_PAL
}
EX_CATCH
{
#ifndef FEATURE_PAL
if (impersonating)
{
STRESS_LOG1(LF_EH, LL_INFO100, "Filter threw exception. In Catch. Resetting to hImpersonationToken = %d\n",m_hImpersonationToken);
// CLR_ImpersonateLoggedOnUser fails fast on error
COMPrincipal::CLR_ImpersonateLoggedOnUser(m_hImpersonationToken);
impersonating = FALSE;
}
#endif // !FEATURE_PAL
// we've returned from the filter abruptly, now out of managed code
m_EHClauseInfo.SetManagedCodeEntered(FALSE);
EH_LOG((LL_INFO100, " filter threw an exception\n"));
// notify profiler
EEToProfilerExceptionInterfaceWrapper::ExceptionSearchFilterLeave();
m_EHClauseInfo.ResetInfo();
// continue search
}
EX_END_CATCH(SwallowAllExceptions);
// Reset the EH clause Index and Establisher of the TA reraise clause
pThread->m_dwIndexClauseForCatch = dwPreFilterTACatchHandlerClauseIndex;
pThread->m_sfEstablisherOfActualHandlerFrame = sfPreFilterEstablisherOfActualHandlerFrame;
if (pThread->IsRudeAbortInitiated() && !pThread->IsWithinCer(pcfThisFrame))
{
EH_LOG((LL_INFO100, " IGNOREFRAME: rude abort\n"));
goto lExit;
}
}
else
{
EH_LOG((LL_INFO100, " STACKOVERFLOW: filter not called due to lack of guard page\n"));
// continue search
}
if (EXCEPTION_EXECUTE_HANDLER == dwResult)
{
fFoundHandler = TRUE;
}
else if (EXCEPTION_CONTINUE_SEARCH != dwResult)
{
//
// Behavior is undefined according to the spec. Let's not execute the handler.
//
}
EH_LOG((LL_INFO100, " filter returned %s\n", (fFoundHandler ? "EXCEPTION_EXECUTE_HANDLER" : "EXCEPTION_CONTINUE_SEARCH")));
}
else if (IsTypedHandler(&EHClause))
{
GCX_COOP();
TypeHandle thrownType = TypeHandle();
OBJECTREF oThrowable = m_pThread->GetThrowable();
if (oThrowable != NULL)
{
oThrowable = PossiblyUnwrapThrowable(oThrowable, pcfThisFrame->GetAssembly());
thrownType = oThrowable->GetTrueTypeHandle();
}
if (!thrownType.IsNull())
{
if (EHClause.ClassToken == mdTypeRefNil)
{
// this is a catch(...)
fFoundHandler = TRUE;
}
else
{
TypeHandle typeHnd = pJitMan->ResolveEHClause(&EHClause, pcfThisFrame);
EH_LOG((LL_INFO100,
" clause type = %s\n",
(!typeHnd.IsNull() ? typeHnd.GetMethodTable()->GetDebugClassName()
: "<couldn't resolve>")));
EH_LOG((LL_INFO100,
" thrown type = %s\n",
thrownType.GetMethodTable()->GetDebugClassName()));
fFoundHandler = !typeHnd.IsNull() && ExceptionIsOfRightType(typeHnd, thrownType);
}
}
}
else
{
_ASSERTE(fTermHandler);
fFoundHandler = TRUE;
}
if (fFoundHandler)
{
if (fIsFirstPass)
{
_ASSERTE(IsFilterHandler(&EHClause) || IsTypedHandler(&EHClause));
EH_LOG((LL_INFO100, " found catch at 0x%p, sp = 0x%p\n", dwHandlerStartPC, sf.SP));
m_uCatchToCallPC = dwHandlerStartPC;
m_pClauseForCatchToken = pEHClauseToken;
m_ClauseForCatch = EHClause;
m_sfResumeStackFrame = sf;
#if defined(DEBUGGING_SUPPORTED) || defined(PROFILING_SUPPORTED)
//
// notify the debugger and profiler
//
if (fGiveDebuggerAndProfilerNotification)
{
EEToProfilerExceptionInterfaceWrapper::ExceptionSearchCatcherFound(pMD);
}
if (fIsILStub)
{
//
// NotifyOfCHFFilter has two behaviors
// * Notifify debugger, get interception info and unwind (function will not return)
// In this case, m_sfResumeStackFrame is expected to be NULL or the frame of interception.
// We NULL it out because we get the interception event after this point.
// * Notifify debugger and return.
// In this case the normal EH proceeds and we need to reset m_sfResumeStackFrame to the sf catch handler.
// TODO: remove this call and try to report the IL catch handler in the IL stub itself.
m_sfResumeStackFrame.Clear();
EEToDebuggerExceptionInterfaceWrapper::NotifyOfCHFFilter((EXCEPTION_POINTERS*)&m_ptrs, pILStubFrame);
m_sfResumeStackFrame = sf;
}
else
{
// We don't need to do anything special for continuable exceptions after calling
// this callback. We are going to start unwinding anyway.
EEToDebuggerExceptionInterfaceWrapper::FirstChanceManagedExceptionCatcherFound(pThread, pMD, (TADDR) uMethodStartPC, sf.SP,
&EHClause);
}
// If the exception is intercepted, then the target unwind frame may not be the
// stack frame we are currently processing, so clear it now. We'll set it
// later in second pass.
if (pThread->GetExceptionState()->GetFlags()->DebuggerInterceptInfo())
{
m_sfResumeStackFrame.Clear();
}
#endif //defined(DEBUGGING_SUPPORTED) || defined(PROFILING_SUPPORTED)
//
// BEGIN resume frame code
//
EH_LOG((LL_INFO100, " RESUMEFRAME: initial resume stack frame: %p\n", sf.SP));
if (IsDuplicateClause(&EHClause))
{
EH_LOG((LL_INFO100, " RESUMEFRAME: need to unwind to find real resume frame\n"));
m_ExceptionFlags.SetUnwindingToFindResumeFrame();
// This is a duplicate catch funclet. As a result, we will continue to let the
// exception dispatch proceed upstack to find the actual frame where the
// funclet lives.
//
// At the same time, we also need to save the CallerSP of the frame containing
// the catch funclet (like we do for other funclets). If the current frame
// represents a funclet that was invoked by JITted code, then we will save
// the caller SP of the current frame when we see it during the 2nd pass -
// refer to the use of "pLimitClauseToken" in the code above.
//
// However, that is not the callerSP of the frame containing the catch funclet
// as the actual frame containing the funclet (and where it will be executed)
// is the one that will be the target of unwind during the first pass.
//
// To correctly get that, we will determine if the current frame is a funclet
// and if it was invoked from JITted code. If this is true, then current frame
// represents a finally funclet invoked non-exceptionally (from its parent frame
// or yet another funclet). In such a case, we will set a flag indicating that
// we need to reset the enclosing clause SP for the catch funclet and later,
// when 2nd pass reaches the actual frame containing the catch funclet to be
// executed, we will update the enclosing clause SP if the
// "m_fResetEnclosingClauseSPForCatchFunclet" flag is set, just prior to
// invoking the catch funclet.
if (fIsFunclet)
{
REGDISPLAY* pCurRegDisplay = pcfThisFrame->GetRegisterSet();
_ASSERTE(pCurRegDisplay->IsCallerContextValid);
TADDR adrReturnAddressFromFunclet = PCODEToPINSTR(GetIP(pCurRegDisplay->pCallerContext)) - STACKWALK_CONTROLPC_ADJUST_OFFSET;
m_fResetEnclosingClauseSPForCatchFunclet = ExecutionManager::IsManagedCode(adrReturnAddressFromFunclet);
}
ReturnStatus = UnwindPending;
break;
}
EH_LOG((LL_INFO100, " RESUMEFRAME: no extra unwinding required, real resume frame: %p\n", sf.SP));
// Save off the index and the EstablisherFrame of the EH clause of the non-duplicate handler
// that decided to handle the exception. We may need it
// if a ThreadAbort is raised after the catch block
// executes.
m_dwIndexClauseForCatch = i + 1;
m_sfEstablisherOfActualHandlerFrame = sfEstablisherFrame;
#ifdef _TARGET_AMD64_
m_sfCallerOfActualHandlerFrame = EECodeManager::GetCallerSp(pcfThisFrame->pRD);
#else
// On ARM & ARM64, the EstablisherFrame is the value of SP at the time a function was called and before it's prolog
// executed. Effectively, it is the SP of the caller.
m_sfCallerOfActualHandlerFrame = sfEstablisherFrame.SP;
#endif
//
// END resume frame code
//
ReturnStatus = FirstPassComplete;
break;
}
else
{
EH_LOG((LL_INFO100, " found finally/fault at 0x%p\n", dwHandlerStartPC));
_ASSERTE(fTermHandler);
// @todo : If user code throws a StackOveflowException and we have plenty of stack,
// we probably don't want to be so strict in not calling handlers.
if (!IsStackOverflowException())
{
DWORD_PTR dwStatus;
// for finally clauses
SetEnclosingClauseInfo(fIsFunclet,
pcfThisFrame->GetRelOffset(),
GetSP(pcfThisFrame->GetRegisterSet()->pCallerContext));
// We have switched to indefinite COOP mode just before this loop started.
// Since we also forbid GC during second pass, disable it now since
// invocation of managed code can result in a GC.
ENDFORBIDGC();
dwStatus = CallHandler(dwHandlerStartPC, sf, &EHClause, pMD, FaultFinally ARM_ARG(pcfThisFrame->GetRegisterSet()->pCurrentContext) ARM64_ARG(pcfThisFrame->GetRegisterSet()->pCurrentContext));
// Once we return from a funclet, forbid GC again (refer to comment before start of the loop for details)
BEGINFORBIDGC();
}
else
{
EH_LOG((LL_INFO100, " STACKOVERFLOW: finally not called due to lack of guard page\n"));
// continue search
}
//
// will continue to find next fault/finally in this call frame
//
}
} // if fFoundHandler
} // if clause covers PC
} // foreach eh clause
} // if stack frame is far enough away from guard page
//
// notify the profiler
//
if (fGiveDebuggerAndProfilerNotification)
{
if (fIsFirstPass)
{
if (!fUnwindingToFindResumeFrame)
{
EEToProfilerExceptionInterfaceWrapper::ExceptionSearchFunctionLeave(pMD);
}
}
else
{
if (!fUnwindFinished)
{
EEToProfilerExceptionInterfaceWrapper::ExceptionUnwindFunctionLeave(pMD);
}
}
}
} // fIgnoreThisFrame
lExit:
return ReturnStatus;
}
// <64bit_And_Arm_Specific>
// For funclets, add support for unwinding frame chain during SO. These definitions will be automatically picked up by
// BEGIN_SO_TOLERANT_CODE/END_SO_TOLERANT_CODE usage in ExceptionTracker::CallHandler below.
//
// This is required since funclet invocation is the only case of calling managed code from VM that is not wrapped by
// assembly helper with associated personality routine. The personality routine will invoke CleanupForSecondPass to
// release exception trackers and unwind frame chain.
//
// We need to do the same work as CleanupForSecondPass for funclet invocation in the face of SO. Thus, we redefine OPTIONAL_SO_CLEANUP_UNWIND
// below. This will perform frame chain unwind inside the "__finally" block that is part of the END_SO_TOLERANT_CODE macro only in the face
// of an SO.
//
// The second part of work, releasing exception trackers, is done inside the "__except" block also part of the END_SO_TOLERANT_CODE by invoking
// ClearExceptionStateAfterSO.
//
// </64bit_And_Arm_Specific>
#undef OPTIONAL_SO_CLEANUP_UNWIND
#define OPTIONAL_SO_CLEANUP_UNWIND(pThread, pFrame) if (pThread->GetFrame() < pFrame) { UnwindFrameChain(pThread, pFrame); }
#if defined(_TARGET_ARM_) || defined(_TARGET_ARM64_)
// This is an assembly helper that enables us to call into EH funclets.
EXTERN_C DWORD_PTR STDCALL CallEHFunclet(Object *pThrowable, UINT_PTR pFuncletToInvoke, UINT_PTR *pFirstNonVolReg, UINT_PTR *pFuncletCallerSP);
// This is an assembly helper that enables us to call into EH filter funclets.
EXTERN_C DWORD_PTR STDCALL CallEHFilterFunclet(Object *pThrowable, TADDR CallerSP, UINT_PTR pFuncletToInvoke, UINT_PTR *pFuncletCallerSP);
#endif // _TARGET_ARM_ || _TARGET_ARM64_
DWORD_PTR ExceptionTracker::CallHandler(
UINT_PTR uHandlerStartPC,
StackFrame sf,
EE_ILEXCEPTION_CLAUSE* pEHClause,
MethodDesc* pMD,
EHFuncletType funcletType
ARM_ARG(PCONTEXT pContextRecord)
ARM64_ARG(PCONTEXT pContextRecord)
)
{
STATIC_CONTRACT_THROWS;
STATIC_CONTRACT_GC_TRIGGERS;
STATIC_CONTRACT_MODE_COOPERATIVE;
DWORD_PTR dwResumePC;
OBJECTREF throwable;
HandlerFn* pfnHandler = (HandlerFn*)uHandlerStartPC;
EH_LOG((LL_INFO100, " calling handler at 0x%p, sp = 0x%p\n", uHandlerStartPC, sf.SP));
Thread* pThread = GetThread();
// The first parameter specifies whether we want to make callbacks before (true) or after (false)
// calling the handler.
MakeCallbacksRelatedToHandler(true, pThread, pMD, pEHClause, uHandlerStartPC, sf);
_ASSERTE(pThread->DetermineIfGuardPagePresent());
throwable = PossiblyUnwrapThrowable(pThread->GetThrowable(), pMD->GetAssembly());
// We probe for stack space before attempting to call a filter, finally, or catch clause. The path from
// here to the actual managed code is very short. We must probe, however, because the JIT does not generate a
// probe for us upon entry to the handler. This probe ensures we have enough stack space to actually make it
// into the managed code.
//
// Incase a SO happens, this macro will also unwind the frame chain before continuing to dispatch the SO
// upstack (look at the macro implementation for details).
BEGIN_SO_TOLERANT_CODE(pThread);
// Stores the current SP and BSP, which will be the caller SP and BSP for the funclet.
// Note that we are making the assumption here that the SP and BSP don't change from this point
// forward until we actually make the call to the funclet. If it's not the case then we will need
// some sort of assembly wrappers to help us out.
CallerStackFrame csfFunclet = CallerStackFrame((UINT_PTR)GetCurrentSP());
this->m_EHClauseInfo.SetManagedCodeEntered(TRUE);
this->m_EHClauseInfo.SetCallerStackFrame(csfFunclet);
#if defined(_TARGET_ARM_) || defined(_TARGET_ARM64_)
// Invoke the funclet. We pass throwable only when invoking the catch block.
// Since the actual caller of the funclet is the assembly helper, pass the reference
// to the CallerStackFrame instance so that it can be updated.
CallerStackFrame* pCallerStackFrame = this->m_EHClauseInfo.GetCallerStackFrameForEHClauseReference();
UINT_PTR *pFuncletCallerSP = &(pCallerStackFrame->SP);
if (funcletType != EHFuncletType::Filter)
{
dwResumePC = CallEHFunclet((funcletType == EHFuncletType::Catch)?OBJECTREFToObject(throwable):(Object *)NULL,
#ifdef _TARGET_ARM_
DataPointerToThumbCode<UINT_PTR, HandlerFn *>(pfnHandler),
(UINT_PTR*)&(pContextRecord->R4),
#else
(UINT_PTR)pfnHandler,
&(pContextRecord->X19),
#endif // _TARGET_ARM_
pFuncletCallerSP);
}
else
{
// For invoking IL filter funclet, we pass the CallerSP to the funclet using which
// it will retrieve the framepointer for accessing the locals in the parent
// method.
dwResumePC = CallEHFilterFunclet(OBJECTREFToObject(throwable),
GetSP(pContextRecord),
#ifdef _TARGET_ARM_
DataPointerToThumbCode<UINT_PTR, HandlerFn *>(pfnHandler),
#else
(UINT_PTR)pfnHandler,
#endif // _TARGET_ARM_
pFuncletCallerSP);
}
#else // defined(_TARGET_ARM_) || defined(_TARGET_ARM64_)
//
// Invoke the funclet.
//
dwResumePC = pfnHandler(sf.SP, OBJECTREFToObject(throwable));
#endif // _TARGET_ARM_
this->m_EHClauseInfo.SetManagedCodeEntered(FALSE);
END_SO_TOLERANT_CODE;
// The first parameter specifies whether we want to make callbacks before (true) or after (false)
// calling the handler.
MakeCallbacksRelatedToHandler(false, pThread, pMD, pEHClause, uHandlerStartPC, sf);
return dwResumePC;
}
#undef OPTIONAL_SO_CLEANUP_UNWIND
#define OPTIONAL_SO_CLEANUP_UNWIND(pThread, pFrame)
//
// this must be done after the second pass has run, it does not
// reference anything on the stack, so it is safe to run in an
// SEH __except clause as well as a C++ catch clause.
//
// static
void ExceptionTracker::PopTrackers(
void* pStackFrameSP
)
{
CONTRACTL
{
MODE_ANY;
GC_NOTRIGGER;
NOTHROW;
}
CONTRACTL_END;
StackFrame sf((UINT_PTR)pStackFrameSP);
// Only call into PopTrackers if we have a managed thread and we have an exception progress.
// Otherwise, the call below (to PopTrackers) is a noop. If this ever changes, then this short-circuit needs to be fixed.
Thread *pCurThread = GetThread();
if ((pCurThread != NULL) && (pCurThread->GetExceptionState()->IsExceptionInProgress()))
{
// Refer to the comment around ExceptionTracker::HasFrameBeenUnwoundByAnyActiveException
// for details on the usage of this COOP switch.
GCX_COOP();
PopTrackers(sf, false);
}
}
//
// during the second pass, an exception might escape out to
// unmanaged code where it is swallowed (or potentially rethrown).
// The current tracker is abandoned in this case, and if a rethrow
// does happen in unmanaged code, this is unfortunately treated as
// a brand new exception. This is unavoidable because if two
// exceptions escape out to unmanaged code in this manner, a subsequent
// rethrow cannot be disambiguated as corresponding to the nested vs.
// the original exception.
void ExceptionTracker::PopTrackerIfEscaping(
void* pStackPointer
)
{
CONTRACTL
{
MODE_ANY;
GC_NOTRIGGER;
NOTHROW;
}
CONTRACTL_END;
Thread* pThread = GetThread();
ThreadExceptionState* pExState = pThread->GetExceptionState();
ExceptionTracker* pTracker = pExState->m_pCurrentTracker;
CONSISTENCY_CHECK((NULL == pTracker) || pTracker->IsValid());
// If we are resuming in managed code (albeit further up the stack) we will still need this
// tracker. Otherwise we are either propagating into unmanaged code -- with the rethrow
// issues mentioned above -- or we are going unhandled.
//
// Note that we don't distinguish unmanaged code in the EE vs. unmanaged code outside the
// EE. We could use the types of the Frames above us to make this distinction. Without
// this, the technique of EX_TRY/EX_CATCH/EX_RETHROW inside the EE will lose its tracker
// and have to rely on LastThrownObject in the rethrow. Along the same lines, unhandled
// exceptions only have access to LastThrownObject.
//
// There may not be a current tracker if, for instance, UMThunk has dispatched into managed
// code via CallDescr. In that case, CallDescr may pop the tracker, leaving UMThunk with
// nothing to do.
if (pTracker && pTracker->m_sfResumeStackFrame.IsNull())
{
StackFrame sf((UINT_PTR)pStackPointer);
StackFrame sfTopMostStackFrameFromFirstPass = pTracker->GetTopmostStackFrameFromFirstPass();
// Refer to the comment around ExceptionTracker::HasFrameBeenUnwoundByAnyActiveException
// for details on the usage of this COOP switch.
GCX_COOP();
ExceptionTracker::PopTrackers(sf, true);
}
}
//
// static
void ExceptionTracker::PopTrackers(
StackFrame sfResumeFrame,
bool fPopWhenEqual
)
{
CONTRACTL
{
// Refer to the comment around ExceptionTracker::HasFrameBeenUnwoundByAnyActiveException
// for details on the mode being COOP here.
MODE_COOPERATIVE;
GC_NOTRIGGER;
NOTHROW;
}
CONTRACTL_END;
Thread* pThread = GetThread();
ExceptionTracker* pTracker = (pThread ? pThread->GetExceptionState()->m_pCurrentTracker : NULL);
// NOTE:
//
// This method is a no-op when there is no managed Thread object. We detect such a case and short circuit out in ExceptionTrackers::PopTrackers.
// If this ever changes, then please revisit that method and fix it up appropriately.
// If this tracker does not have valid stack ranges,
// then we came here likely when the tracker was being setup
// and an exception took place.
//
// In such a case, we will not pop off the tracker
if (pTracker && pTracker->m_ScannedStackRange.IsEmpty())
{
// skip any others with empty ranges...
do
{
pTracker = pTracker->m_pPrevNestedInfo;
}
while (pTracker && pTracker->m_ScannedStackRange.IsEmpty());
// pTracker is now the first non-empty one, make sure it doesn't need popping
// if it does, then someone let an exception propagate out of the exception dispatch code
_ASSERTE(!pTracker || (pTracker->m_ScannedStackRange.GetUpperBound() > sfResumeFrame));
return;
}
#if defined(DEBUGGING_SUPPORTED)
DWORD_PTR dwInterceptStackFrame = 0;
// This method may be called on an unmanaged thread, in which case no interception can be done.
if (pTracker)
{
ThreadExceptionState* pExState = pThread->GetExceptionState();
// If the exception is intercepted, then pop trackers according to the stack frame at which
// the exception is intercepted. We must retrieve the frame pointer before we start popping trackers.
if (pExState->GetFlags()->DebuggerInterceptInfo())
{
pExState->GetDebuggerState()->GetDebuggerInterceptInfo(NULL, NULL, (PBYTE*)&dwInterceptStackFrame,
NULL, NULL);
}
}
#endif // DEBUGGING_SUPPORTED
while (pTracker)
{
// When we are about to pop off a tracker, it should
// have a stack range setup.
_ASSERTE(!pTracker->m_ScannedStackRange.IsEmpty());
ExceptionTracker* pPrev = pTracker->m_pPrevNestedInfo;
// <TODO>
// with new tracker collapsing code, we will only ever pop one of these at a time
// at the end of the 2nd pass. However, CLRException::HandlerState::SetupCatch
// still uses this function and we still need to revisit how it interacts with
// ExceptionTrackers
// </TODO>
if ((fPopWhenEqual && (pTracker->m_ScannedStackRange.GetUpperBound() == sfResumeFrame)) ||
(pTracker->m_ScannedStackRange.GetUpperBound() < sfResumeFrame))
{
#if defined(DEBUGGING_SUPPORTED)
if (g_pDebugInterface != NULL)
{
if (pTracker->m_ScannedStackRange.GetUpperBound().SP < dwInterceptStackFrame)
{
g_pDebugInterface->DeleteInterceptContext(pTracker->m_DebuggerExState.GetDebuggerInterceptContext());
}
else
{
_ASSERTE(dwInterceptStackFrame == 0 ||
( dwInterceptStackFrame == sfResumeFrame.SP &&
dwInterceptStackFrame == pTracker->m_ScannedStackRange.GetUpperBound().SP ));
}
}
#endif // DEBUGGING_SUPPORTED
ExceptionTracker* pTrackerToFree = pTracker;
EH_LOG((LL_INFO100, "Unlinking ExceptionTracker object 0x%p, thread = 0x%p\n", pTrackerToFree, pTrackerToFree->m_pThread));
CONSISTENCY_CHECK(pTracker->IsValid());
pTracker = pPrev;
// free managed tracker resources causing notification -- do this before unlinking the tracker
// this is necessary so that we know an exception is still in flight while we give the notification
FreeTrackerMemory(pTrackerToFree, memManaged);
// unlink the tracker from the thread
pThread->GetExceptionState()->m_pCurrentTracker = pTracker;
CONSISTENCY_CHECK((NULL == pTracker) || pTracker->IsValid());
// free unmanaged tracker resources
FreeTrackerMemory(pTrackerToFree, memUnmanaged);
}
else
{
break;
}
}
}
//
// static
ExceptionTracker* ExceptionTracker::GetOrCreateTracker(
UINT_PTR ControlPc,
StackFrame sf,
EXCEPTION_RECORD* pExceptionRecord,
CONTEXT* pContextRecord,
BOOL bAsynchronousThreadStop,
bool fIsFirstPass,
StackTraceState* pStackTraceState
)
{
CONTRACT(ExceptionTracker*)
{
MODE_ANY;
GC_TRIGGERS;
NOTHROW;
PRECONDITION(CheckPointer(pStackTraceState));
POSTCONDITION(CheckPointer(RETVAL));
}
CONTRACT_END;
Thread* pThread = GetThread();
ThreadExceptionState* pExState = pThread->GetExceptionState();
ExceptionTracker* pTracker = pExState->m_pCurrentTracker;
CONSISTENCY_CHECK((NULL == pTracker) || (pTracker->IsValid()));
bool fCreateNewTracker = false;
bool fIsRethrow = false;
// Initialize the out parameter.
*pStackTraceState = STS_Append;
if (NULL != pTracker)
{
CONSISTENCY_CHECK(!pTracker->m_ScannedStackRange.IsEmpty());
if (pTracker->m_ExceptionFlags.IsRethrown())
{
EH_LOG((LL_INFO100, ">>continued processing of RETHROWN exception\n"));
// this is the first time we've seen a rethrown exception, reuse the tracker and reset some state
fCreateNewTracker = true;
fIsRethrow = true;
}
else
if (pTracker->m_ptrs.ExceptionRecord != pExceptionRecord)
{
EH_LOG((LL_INFO100, ">>NEW exception (exception records do not match)\n"));
fCreateNewTracker = true;
}
else
if (sf >= pTracker->m_ScannedStackRange.GetUpperBound())
{
// We can't have a transition from 1st pass to 2nd pass in this case.
_ASSERTE( ( sf == pTracker->m_ScannedStackRange.GetUpperBound() ) ||
( fIsFirstPass || !pTracker->IsInFirstPass() ) );
if (fIsFirstPass && !pTracker->IsInFirstPass())
{
// We just transition from 2nd pass to 1st pass without knowing it.
// This means that some unmanaged frame outside of the EE catches the previous exception,
// so we should trash the current tracker and create a new one.
EH_LOG((LL_INFO100, ">>NEW exception (the previous second pass finishes at some unmanaged frame outside of the EE)\n"));
{
GCX_COOP();
ExceptionTracker::PopTrackers(sf, false);
}
fCreateNewTracker = true;
}
else
{
EH_LOG((LL_INFO100, ">>continued processing of PREVIOUS exception\n"));
// previously seen exception, reuse the tracker
*pStackTraceState = STS_Append;
}
}
else
if (pTracker->m_ScannedStackRange.Contains(sf))
{
EH_LOG((LL_INFO100, ">>continued processing of PREVIOUS exception (revisiting previously processed frames)\n"));
}
else
{
// nested exception
EH_LOG((LL_INFO100, ">>new NESTED exception\n"));
fCreateNewTracker = true;
}
}
else
{
EH_LOG((LL_INFO100, ">>NEW exception\n"));
fCreateNewTracker = true;
}
if (fCreateNewTracker)
{
#ifdef _DEBUG
if (STATUS_STACK_OVERFLOW == pExceptionRecord->ExceptionCode)
{
CONSISTENCY_CHECK(pExceptionRecord->NumberParameters >= 2);
UINT_PTR uFaultAddress = pExceptionRecord->ExceptionInformation[1];
UINT_PTR uStackLimit = (UINT_PTR)pThread->GetCachedStackLimit();
EH_LOG((LL_INFO100, "STATUS_STACK_OVERFLOW accessing address %p %s\n",
uFaultAddress));
UINT_PTR uDispatchStackAvailable;
uDispatchStackAvailable = uFaultAddress - uStackLimit - HARD_GUARD_REGION_SIZE;
EH_LOG((LL_INFO100, "%x bytes available for SO processing\n", uDispatchStackAvailable));
}
else if ((IsComPlusException(pExceptionRecord)) &&
(pThread->GetThrowableAsHandle() == g_pPreallocatedStackOverflowException))
{
EH_LOG((LL_INFO100, "STACKOVERFLOW: StackOverflowException manually thrown\n"));
}
#endif // _DEBUG
ExceptionTracker* pNewTracker;
pNewTracker = GetTrackerMemory();
if (!pNewTracker)
{
if (NULL != pExState->m_OOMTracker.m_pThread)
{
// Fatal error: we spun and could not allocate another tracker
// and our existing emergency tracker is in use.
EEPOLICY_HANDLE_FATAL_ERROR(COR_E_EXECUTIONENGINE);
}
pNewTracker = &pExState->m_OOMTracker;
}
new (pNewTracker) ExceptionTracker(ControlPc,
pExceptionRecord,
pContextRecord);
CONSISTENCY_CHECK(pNewTracker->IsValid());
CONSISTENCY_CHECK(pThread == pNewTracker->m_pThread);
EH_LOG((LL_INFO100, "___________________________________________\n"));
EH_LOG((LL_INFO100, "creating new tracker object 0x%p, thread = 0x%p\n", pNewTracker, pThread));
GCX_COOP();
// We always create a throwable in the first pass when we first see an exception.
//
// On 64bit, everytime the exception passes beyond a boundary (e.g. RPInvoke call, or CallDescrWorker call),
// the exception trackers that were created below (stack growing down) that boundary are released, during the 2nd pass,
// if the exception was not caught in managed code. This is because the catcher is in native code and managed exception
// data structures are for use of VM only when the exception is caught in managed code. Also, passing by such
// boundaries is our only oppurtunity to release such internal structures and not leak the memory.
//
// However, in certain case, release of exception trackers at each boundary can prove to be a bit aggressive.
// Take the example below where "VM" prefix refers to a VM frame and "M" prefix refers to a managed frame on the stack.
//
// VM1 -> M1 - VM2 - (via RPinvoke) -> M2
//
// Let M2 throw E2 that remains unhandled in managed code (i.e. M1 also does not catch it) but is caught in VM1.
// Note that the acting of throwing an exception also sets it as the LastThrownObject (LTO) against the thread.
//
// Since this is native code (as mentioned in the comments above, there is no distinction made between VM native
// code and external native code) that caught the exception, when the unwind goes past the "Reverse Pinvoke" boundary,
// its personality routine will release the tracker for E2. Thus, only the LTO (which is off the Thread object and not
// the exception tracker) is indicative of type of the last exception thrown.
//
// As the unwind goes up the stack, we come across M1 and, since the original tracker was released, we create a new
// tracker in the 2nd pass that does not contain details like the active exception object. A managed finally executes in M1
// that throws and catches E1 inside the finally block. Thus, LTO is updated to indicate E1 as the last exception thrown.
// When the exception is caught in VM1 and VM attempts to get LTO, it gets E1, which is incorrect as it was handled within the finally.
// Semantically, it should have got E2 as the LTO.
//
// To address, this we will *also* create a throwable during second pass for most exceptions
// since most of them have had the corresponding first pass. If we are processing
// an exception's second pass, we would have processed its first pass as well and thus, already
// created a throwable that would be setup as the LastThrownObject (LTO) against the Thread.
//
// The only exception to this rule is the longjump - this exception only has second pass
// Thus, if we are in second pass and exception in question is longjump, then do not create a throwable.
//
// In the case of the scenario above, when we attempt to create a new exception tracker, during the unwind,
// for M1, we will also setup E2 as the throwable in the tracker. As a result, when the finally in M1 throws
// and catches the exception, the LTO is correctly updated against the thread (see SafeUpdateLastThrownObject)
// and thus, when VM requests for the LTO, it gets E2 as expected.
bool fCreateThrowableForCurrentPass = true;
if (pExceptionRecord->ExceptionCode == STATUS_LONGJUMP)
{
// Long jump is only in second pass of exception dispatch
_ASSERTE(!fIsFirstPass);
fCreateThrowableForCurrentPass = false;
}
// When dealing with SQL Hosting like scenario, a real SO
// maybe caught in native code. As a result, CRT will perform
// STATUS_UNWIND_CONSOLIDATE that will result in replacing
// the exception record in ProcessCLRException. This replaced
// exception record will point to the exception record for original
// SO for which we will not have created a throwable in the first pass
// due to the SO-specific early exit code in ProcessCLRException.
// //
// Thus, if we see that we are here for SO in the 2nd pass, then
// we shouldn't attempt to create a throwable.
if ((!fIsFirstPass) && (IsSOExceptionCode(pExceptionRecord->ExceptionCode)))
{
fCreateThrowableForCurrentPass = false;
}
#ifdef _DEBUG
if ((!fIsFirstPass) && (fCreateThrowableForCurrentPass == true))
{
// We should have a LTO available if we are creating
// a throwable during second pass.
_ASSERTE(pThread->LastThrownObjectHandle() != NULL);
}
#endif // _DEBUG
bool fCreateThrowable = (fCreateThrowableForCurrentPass || (bAsynchronousThreadStop && !pThread->IsAsyncPrevented()));
OBJECTREF oThrowable = NULL;
if (fCreateThrowable)
{
if (fIsRethrow)
{
oThrowable = ObjectFromHandle(pTracker->m_hThrowable);
}
else
{
// this can take a nested exception
oThrowable = CreateThrowable(pExceptionRecord, bAsynchronousThreadStop);
}
}
GCX_FORBID(); // we haven't protected oThrowable
if (pExState->m_pCurrentTracker != pNewTracker) // OOM can make this false
{
pNewTracker->m_pPrevNestedInfo = pExState->m_pCurrentTracker;
pTracker = pNewTracker;
pThread->GetExceptionState()->m_pCurrentTracker = pTracker;
}
if (fCreateThrowable)
{
CONSISTENCY_CHECK(oThrowable != NULL);
CONSISTENCY_CHECK(NULL == pTracker->m_hThrowable);
pThread->SafeSetThrowables(oThrowable);
if (pTracker->CanAllocateMemory())
{
pTracker->m_StackTraceInfo.AllocateStackTrace();
}
}
INDEBUG(oThrowable = NULL);
if (fIsRethrow)
{
*pStackTraceState = STS_FirstRethrowFrame;
}
else
{
*pStackTraceState = STS_NewException;
}
_ASSERTE(pTracker->m_pLimitFrame == NULL);
pTracker->ResetLimitFrame();
}
if (!fIsFirstPass)
{
{
// Refer to the comment around ExceptionTracker::HasFrameBeenUnwoundByAnyActiveException
// for details on the usage of this COOP switch.
GCX_COOP();
if (pTracker->IsInFirstPass())
{
CONSISTENCY_CHECK_MSG(fCreateNewTracker || pTracker->m_ScannedStackRange.Contains(sf),
"Tracker did not receive a first pass!");
// Save the topmost StackFrame the tracker saw in the first pass before we reset the
// scanned stack range.
pTracker->m_sfFirstPassTopmostFrame = pTracker->m_ScannedStackRange.GetUpperBound();
// We have to detect this transition becuase otherwise we break when unmanaged code
// catches our exceptions.
EH_LOG((LL_INFO100, ">>tracker transitioned to second pass\n"));
pTracker->m_ScannedStackRange.Reset();
pTracker->m_ExceptionFlags.SetUnwindHasStarted();
if (pTracker->m_ExceptionFlags.UnwindingToFindResumeFrame())
{
// UnwindingToFindResumeFrame means that in the first pass, we determine that a method
// catches the exception, but the method frame we are inspecting is a funclet method frame
// and is not the correct frame to resume execution. We need to resume to the correct
// method frame before starting the second pass. The correct method frame is most likely
// the parent method frame, but it can also be another funclet method frame.
//
// If the exception transitions from first pass to second pass before we find the parent
// method frame, there is only one possibility: some other thread has initiated a rude
// abort on the current thread, causing us to skip processing of all method frames.
_ASSERTE(pThread->IsRudeAbortInitiated());
}
// Lean on the safe side and just reset everything unconditionally.
pTracker->FirstPassIsComplete();
EEToDebuggerExceptionInterfaceWrapper::ManagedExceptionUnwindBegin(pThread);
pTracker->ResetLimitFrame();
}
else
{
// In the second pass, there's a possibility that UMThunkUnwindFrameChainHandler() has
// popped some frames off the frame chain underneath us. Check for this case here.
if (pTracker->m_pLimitFrame < pThread->GetFrame())
{
pTracker->ResetLimitFrame();
}
}
}
#ifdef FEATURE_CORRUPTING_EXCEPTIONS
if (fCreateNewTracker)
{
// Exception tracker should be in the 2nd pass right now
_ASSERTE(!pTracker->IsInFirstPass());
// The corruption severity of a newly created tracker is NotSet
_ASSERTE(pTracker->GetCorruptionSeverity() == NotSet);
// See comment in CEHelper::SetupCorruptionSeverityForActiveExceptionInUnwindPass for details
CEHelper::SetupCorruptionSeverityForActiveExceptionInUnwindPass(pThread, pTracker, FALSE, pExceptionRecord->ExceptionCode);
}
#endif // FEATURE_CORRUPTING_EXCEPTIONS
}
_ASSERTE(pTracker->m_pLimitFrame >= pThread->GetFrame());
RETURN pTracker;
}
void ExceptionTracker::ResetLimitFrame()
{
WRAPPER_NO_CONTRACT;
m_pLimitFrame = m_pThread->GetFrame();
}
//
// static
void ExceptionTracker::ResumeExecution(
CONTEXT* pContextRecord,
EXCEPTION_RECORD* pExceptionRecord
)
{
//
// This method never returns, so it will leave its
// state on the thread if useing dynamic contracts.
//
STATIC_CONTRACT_MODE_COOPERATIVE;
STATIC_CONTRACT_GC_NOTRIGGER;
STATIC_CONTRACT_NOTHROW;
AMD64_ONLY(STRESS_LOG4(LF_GCROOTS, LL_INFO100, "Resuming after exception at %p, rbx=%p, rsi=%p, rdi=%p\n",
GetIP(pContextRecord),
pContextRecord->Rbx,
pContextRecord->Rsi,
pContextRecord->Rdi));
EH_LOG((LL_INFO100, "resuming execution at 0x%p\n", GetIP(pContextRecord)));
EH_LOG((LL_INFO100, "^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n"));
RtlRestoreContext(pContextRecord, pExceptionRecord);
UNREACHABLE();
//
// doesn't return
//
}
//
// static
OBJECTREF ExceptionTracker::CreateThrowable(
PEXCEPTION_RECORD pExceptionRecord,
BOOL bAsynchronousThreadStop
)
{
CONTRACTL
{
MODE_COOPERATIVE;
GC_TRIGGERS;
NOTHROW;
}
CONTRACTL_END;
OBJECTREF oThrowable = NULL;
Thread* pThread = GetThread();
if ((!bAsynchronousThreadStop) && IsComPlusException(pExceptionRecord))
{
oThrowable = pThread->LastThrownObject();
}
else
{
oThrowable = CreateCOMPlusExceptionObject(pThread, pExceptionRecord, bAsynchronousThreadStop);
}
return oThrowable;
}
//
//static
BOOL ExceptionTracker::ClauseCoversPC(
EE_ILEXCEPTION_CLAUSE* pEHClause,
DWORD dwOffset
)
{
// TryStartPC and TryEndPC are offsets relative to the start
// of the method so we can just compare them to the offset returned
// by JitCodeToMethodInfo.
//
return ((pEHClause->TryStartPC <= dwOffset) && (dwOffset < pEHClause->TryEndPC));
}
#if defined(DEBUGGING_SUPPORTED)
BOOL ExceptionTracker::NotifyDebuggerOfStub(Thread* pThread, StackFrame sf, Frame* pCurrentFrame)
{
LIMITED_METHOD_CONTRACT;
BOOL fDeliveredFirstChanceNotification = FALSE;
// <TODO>
// Remove this once SIS is fully enabled.
// </TODO>
extern bool g_EnableSIS;
if (g_EnableSIS)
{
_ASSERTE(GetThread() == pThread);
GCX_COOP();
// For debugger, we may want to notify 1st chance exceptions if they're coming out of a stub.
// We recognize stubs as Frames with a M2U transition type. The debugger's stackwalker also
// recognizes these frames and publishes ICorDebugInternalFrames in the stackwalk. It's
// important to use pFrame as the stack address so that the Exception callback matches up
// w/ the ICorDebugInternlFrame stack range.
if (CORDebuggerAttached())
{
if (pCurrentFrame->GetTransitionType() == Frame::TT_M2U)
{
// Use -1 for the backing store pointer whenever we use the address of a frame as the stack pointer.
EEToDebuggerExceptionInterfaceWrapper::FirstChanceManagedException(pThread,
(SIZE_T)0,
(SIZE_T)pCurrentFrame);
fDeliveredFirstChanceNotification = TRUE;
}
}
}
return fDeliveredFirstChanceNotification;
}
bool ExceptionTracker::IsFilterStartOffset(EE_ILEXCEPTION_CLAUSE* pEHClause, DWORD_PTR dwHandlerStartPC)
{
EECodeInfo codeInfo((PCODE)dwHandlerStartPC);
_ASSERTE(codeInfo.IsValid());
return pEHClause->FilterOffset == codeInfo.GetRelOffset();
}
void ExceptionTracker::MakeCallbacksRelatedToHandler(
bool fBeforeCallingHandler,
Thread* pThread,
MethodDesc* pMD,
EE_ILEXCEPTION_CLAUSE* pEHClause,
DWORD_PTR dwHandlerStartPC,
StackFrame sf
)
{
// Here we need to make an extra check for filter handlers because we could be calling the catch handler
// associated with a filter handler and yet the EH clause we have saved is for the filter handler.
BOOL fIsFilterHandler = IsFilterHandler(pEHClause) && ExceptionTracker::IsFilterStartOffset(pEHClause, dwHandlerStartPC);
BOOL fIsFaultOrFinallyHandler = IsFaultOrFinally(pEHClause);
if (fBeforeCallingHandler)
{
StackFrame sfToStore = sf;
if ((this->m_pPrevNestedInfo != NULL) &&
(this->m_pPrevNestedInfo->m_EnclosingClauseInfo == this->m_EnclosingClauseInfo))
{
// If this is a nested exception which has the same enclosing clause as the previous exception,
// we should just propagate the clause info from the previous exception.
sfToStore = this->m_pPrevNestedInfo->m_EHClauseInfo.GetStackFrameForEHClause();
}
m_EHClauseInfo.SetInfo(COR_PRF_CLAUSE_NONE, (UINT_PTR)dwHandlerStartPC, sfToStore);
if (pMD->IsILStub())
{
return;
}
if (fIsFilterHandler)
{
m_EHClauseInfo.SetEHClauseType(COR_PRF_CLAUSE_FILTER);
EEToDebuggerExceptionInterfaceWrapper::ExceptionFilter(pMD, (TADDR) dwHandlerStartPC, pEHClause->FilterOffset, (BYTE*)sf.SP);
EEToProfilerExceptionInterfaceWrapper::ExceptionSearchFilterEnter(pMD);
COUNTER_ONLY(GetPerfCounters().m_Excep.cFiltersExecuted++);
}
else
{
EEToDebuggerExceptionInterfaceWrapper::ExceptionHandle(pMD, (TADDR) dwHandlerStartPC, pEHClause->HandlerStartPC, (BYTE*)sf.SP);
if (fIsFaultOrFinallyHandler)
{
m_EHClauseInfo.SetEHClauseType(COR_PRF_CLAUSE_FINALLY);
EEToProfilerExceptionInterfaceWrapper::ExceptionUnwindFinallyEnter(pMD);
COUNTER_ONLY(GetPerfCounters().m_Excep.cFinallysExecuted++);
}
else
{
m_EHClauseInfo.SetEHClauseType(COR_PRF_CLAUSE_CATCH);
EEToProfilerExceptionInterfaceWrapper::ExceptionCatcherEnter(pThread, pMD);
DACNotify::DoExceptionCatcherEnterNotification(pMD, pEHClause->HandlerStartPC);
}
}
}
else
{
if (pMD->IsILStub())
{
return;
}
if (fIsFilterHandler)
{
EEToProfilerExceptionInterfaceWrapper::ExceptionSearchFilterLeave();
}
else
{
if (fIsFaultOrFinallyHandler)
{
EEToProfilerExceptionInterfaceWrapper::ExceptionUnwindFinallyLeave();
}
else
{
EEToProfilerExceptionInterfaceWrapper::ExceptionCatcherLeave();
}
}
m_EHClauseInfo.ResetInfo();
}
}
//---------------------------------------------------------------------------------------
//
// This function is called by DefaultCatchHandler() to intercept an exception and start an unwind.
//
// Arguments:
// pCurrentEstablisherFrame - unused on WIN64
// pExceptionRecord - EXCEPTION_RECORD of the exception being intercepted
//
// Return Value:
// ExceptionContinueSearch if the exception cannot be intercepted
//
// Notes:
// If the exception is intercepted, this function never returns.
//
EXCEPTION_DISPOSITION ClrDebuggerDoUnwindAndIntercept(X86_FIRST_ARG(EXCEPTION_REGISTRATION_RECORD* pCurrentEstablisherFrame)
EXCEPTION_RECORD* pExceptionRecord)
{
if (!CheckThreadExceptionStateForInterception())
{
return ExceptionContinueSearch;
}
Thread* pThread = GetThread();
ThreadExceptionState* pExState = pThread->GetExceptionState();
UINT_PTR uInterceptStackFrame = 0;
pExState->GetDebuggerState()->GetDebuggerInterceptInfo(NULL, NULL,
(PBYTE*)&uInterceptStackFrame,
NULL, NULL);
ClrUnwindEx(pExceptionRecord, (UINT_PTR)pThread, INVALID_RESUME_ADDRESS, uInterceptStackFrame);
UNREACHABLE();
}
#endif // DEBUGGING_SUPPORTED
#ifdef _DEBUG
inline bool ExceptionTracker::IsValid()
{
bool fRetVal = false;
EX_TRY
{
Thread* pThisThread = GetThread();
if (m_pThread == pThisThread)
{
fRetVal = true;
}
}
EX_CATCH
{
}
EX_END_CATCH(SwallowAllExceptions);
if (!fRetVal)
{
EH_LOG((LL_ERROR, "ExceptionTracker::IsValid() failed! this = 0x%p\n", this));
}
return fRetVal;
}
BOOL ExceptionTracker::ThrowableIsValid()
{
GCX_COOP();
CONSISTENCY_CHECK(IsValid());
BOOL isValid = FALSE;
isValid = (m_pThread->GetThrowable() != NULL);
return isValid;
}
//
// static
UINT_PTR ExceptionTracker::DebugComputeNestingLevel()
{
UINT_PTR uNestingLevel = 0;
Thread* pThread = GetThread();
if (pThread)
{
ExceptionTracker* pTracker;
pTracker = pThread->GetExceptionState()->m_pCurrentTracker;
while (pTracker)
{
uNestingLevel++;
pTracker = pTracker->m_pPrevNestedInfo;
};
}
return uNestingLevel;
}
void DumpClauses(IJitManager* pJitMan, const METHODTOKEN& MethToken, UINT_PTR uMethodStartPC, UINT_PTR dwControlPc)
{
EH_CLAUSE_ENUMERATOR EnumState;
unsigned EHCount;
EH_LOG((LL_INFO1000, " | uMethodStartPC: %p, ControlPc at offset %x\n", uMethodStartPC, dwControlPc - uMethodStartPC));
EHCount = pJitMan->InitializeEHEnumeration(MethToken, &EnumState);
for (unsigned i = 0; i < EHCount; i++)
{
EE_ILEXCEPTION_CLAUSE EHClause;
pJitMan->GetNextEHClause(&EnumState, &EHClause);
EH_LOG((LL_INFO1000, " | %s clause [%x, %x], handler: [%x, %x] %s",
(IsFault(&EHClause) ? "fault" :
(IsFinally(&EHClause) ? "finally" :
(IsFilterHandler(&EHClause) ? "filter" :
(IsTypedHandler(&EHClause) ? "typed" : "unknown")))),
EHClause.TryStartPC , // + uMethodStartPC,
EHClause.TryEndPC , // + uMethodStartPC,
EHClause.HandlerStartPC , // + uMethodStartPC,
EHClause.HandlerEndPC , // + uMethodStartPC
(IsDuplicateClause(&EHClause) ? "[duplicate]" : "")
));
if (IsFilterHandler(&EHClause))
{
LOG((LF_EH, LL_INFO1000, " filter: [%x, ...]",
EHClause.FilterOffset));// + uMethodStartPC
}
LOG((LF_EH, LL_INFO1000, "\n"));
}
}
#define STACK_ALLOC_ARRAY(numElements, type) \
((type *)_alloca((numElements)*(sizeof(type))))
static void DoEHLog(
DWORD lvl,
__in_z char *fmt,
...
)
{
if (!LoggingOn(LF_EH, lvl))
return;
va_list args;
va_start(args, fmt);
UINT_PTR nestinglevel = ExceptionTracker::DebugComputeNestingLevel();
if (nestinglevel)
{
_ASSERTE(FitsIn<UINT_PTR>(2 * nestinglevel));
UINT_PTR cch = 2 * nestinglevel;
char* pPadding = STACK_ALLOC_ARRAY(cch + 1, char);
memset(pPadding, '.', cch);
pPadding[cch] = 0;
LOG((LF_EH, lvl, pPadding));
}
LogSpewValist(LF_EH, lvl, fmt, args);
}
#endif // _DEBUG
void ClrUnwindEx(EXCEPTION_RECORD* pExceptionRecord, UINT_PTR ReturnValue, UINT_PTR TargetIP, UINT_PTR TargetFrameSp)
{
#ifndef FEATURE_PAL
PVOID TargetFrame = (PVOID)TargetFrameSp;
CONTEXT ctx;
RtlUnwindEx(TargetFrame,
(PVOID)TargetIP,
pExceptionRecord,
(PVOID)ReturnValue, // ReturnValue
&ctx,
NULL); // HistoryTable
#else // !FEATURE_PAL
PORTABILITY_ASSERT("UNIXTODO: Implement unwinding for PAL");
#endif // !FEATURE_PAL
// doesn't return
UNREACHABLE();
}
void TrackerAllocator::Init()
{
void* pvFirstPage = (void*)new BYTE[TRACKER_ALLOCATOR_PAGE_SIZE];
ZeroMemory(pvFirstPage, TRACKER_ALLOCATOR_PAGE_SIZE);
m_pFirstPage = (Page*)pvFirstPage;
_ASSERTE(NULL == m_pFirstPage->m_header.m_pNext);
_ASSERTE(0 == m_pFirstPage->m_header.m_idxFirstFree);
m_pCrst = new Crst(CrstException, CRST_UNSAFE_ANYMODE);
EH_LOG((LL_INFO100, "TrackerAllocator::Init() succeeded..\n"));
}
void TrackerAllocator::Terminate()
{
Page* pPage = m_pFirstPage;
while (pPage)
{
Page* pDeleteMe = pPage;
pPage = pPage->m_header.m_pNext;
delete [] pDeleteMe;
}
delete m_pCrst;
}
ExceptionTracker* TrackerAllocator::GetTrackerMemory()
{
CONTRACT(ExceptionTracker*)
{
GC_TRIGGERS;
NOTHROW;
MODE_ANY;
POSTCONDITION(CheckPointer(RETVAL, NULL_OK));
}
CONTRACT_END;
_ASSERTE(NULL != m_pFirstPage);
Page* pPage = m_pFirstPage;
ExceptionTracker* pTracker = NULL;
for (int i = 0; i < TRACKER_ALLOCATOR_MAX_OOM_SPINS; i++)
{
{ // open lock scope
CrstHolder ch(m_pCrst);
while (pPage)
{
int idx;
for (idx = 0; idx < NUM_TRACKERS_PER_PAGE; idx++)
{
pTracker = &(pPage->m_rgTrackers[idx]);
if (pTracker->m_pThread == NULL)
{
break;
}
}
if (idx < NUM_TRACKERS_PER_PAGE)
{
break;
}
else
{
if (NULL == pPage->m_header.m_pNext)
{
Page* pNewPage = (Page*) new (nothrow) BYTE[TRACKER_ALLOCATOR_PAGE_SIZE];
if (pNewPage)
{
STRESS_LOG0(LF_EH, LL_INFO10, "TrackerAllocator: allocated page\n");
pPage->m_header.m_pNext = pNewPage;
ZeroMemory(pPage->m_header.m_pNext, TRACKER_ALLOCATOR_PAGE_SIZE);
}
else
{
STRESS_LOG0(LF_EH, LL_WARNING, "TrackerAllocator: failed to allocate a page\n");
pTracker = NULL;
}
}
pPage = pPage->m_header.m_pNext;
}
}
if (pTracker)
{
Thread* pThread = GetThread();
_ASSERTE(NULL != pPage);
ZeroMemory(pTracker, sizeof(*pTracker));
pTracker->m_pThread = pThread;
EH_LOG((LL_INFO100, "TrackerAllocator: allocating tracker 0x%p, thread = 0x%p\n", pTracker, pTracker->m_pThread));
break;
}
} // end lock scope
//
// We could not allocate a new page of memory. This is a fatal error if it happens twice (nested)
// on the same thread because we have only one m_OOMTracker. We will spin hoping for another thread
// to give back to the pool or for the allocation to succeed.
//
ClrSleepEx(TRACKER_ALLOCATOR_OOM_SPIN_DELAY, FALSE);
STRESS_LOG1(LF_EH, LL_WARNING, "TrackerAllocator: retry #%d\n", i);
}
RETURN pTracker;
}
void TrackerAllocator::FreeTrackerMemory(ExceptionTracker* pTracker)
{
CONTRACTL
{
GC_NOTRIGGER;
NOTHROW;
MODE_ANY;
}
CONTRACTL_END;
// mark this entry as free
EH_LOG((LL_INFO100, "TrackerAllocator: freeing tracker 0x%p, thread = 0x%p\n", pTracker, pTracker->m_pThread));
CONSISTENCY_CHECK(pTracker->IsValid());
FastInterlockExchangePointer(&(pTracker->m_pThread), NULL);
}
// This is Windows specific implementation as it is based upon the notion of collided unwind that is specific
// to Windows 64bit.
//
// If pContext is not NULL, then this function copies pContext to pDispatcherContext->ContextRecord. If pContext
// is NULL, then this function assumes that pDispatcherContext->ContextRecord has already been fixed up. In any
// case, this function then starts to update the various fields in pDispatcherContext.
//
// In order to redirect the unwind, the OS requires us to provide a personality routine for the code at the
// new context we are providing. If RtlVirtualUnwind can't determine the personality routine and using
// the default managed code personality routine isn't appropriate (maybe you aren't returning to managed code)
// specify pUnwindPersonalityRoutine. For instance the debugger uses this to unwind from ExceptionHijack back
// to RaiseException in win32 and specifies an empty personality routine. For more details about this
// see the comments in the code below.
//
// <AMD64-specific>
// AMD64 is more "advanced", in that the DISPATCHER_CONTEXT contains a field for the TargetIp. So we don't have
// to use the control PC in pDispatcherContext->ContextRecord to indicate the target IP for the unwind. However,
// this also means that pDispatcherContext->ContextRecord is expected to be consistent.
// </AMD64-specific>
//
// For more information, refer to vctools\crt\crtw32\misc\{ia64|amd64}\chandler.c for __C_specific_handler() and
// nt\base\ntos\rtl\{ia64|amd64}\exdsptch.c for RtlUnwindEx().
void FixupDispatcherContext(DISPATCHER_CONTEXT* pDispatcherContext, CONTEXT* pContext, LPVOID originalControlPC, PEXCEPTION_ROUTINE pUnwindPersonalityRoutine)
{
#ifndef FEATURE_PAL
if (pContext)
{
STRESS_LOG1(LF_EH, LL_INFO10, "FDC: pContext: %p\n", pContext);
CopyOSContext(pDispatcherContext->ContextRecord, pContext);
}
pDispatcherContext->ControlPc = (UINT_PTR) GetIP(pDispatcherContext->ContextRecord);
#if defined(_TARGET_ARM_) || defined(_TARGET_ARM64_)
// Since this routine is used to fixup contexts for async exceptions,
// clear the CONTEXT_UNWOUND_TO_CALL flag since, semantically, frames
// where such exceptions have happened do not have callsites. On a similar
// note, also clear out the ControlPcIsUnwound field. Post discussion with
// AaronGi from the kernel team, it's safe for us to have both of these
// cleared.
//
// The OS will pick this up with the rest of the DispatcherContext state
// when it processes collided unwind and thus, when our managed personality
// routine is invoked, ExceptionTracker::InitializeCrawlFrame will adjust
// ControlPC correctly.
pDispatcherContext->ContextRecord->ContextFlags &= ~CONTEXT_UNWOUND_TO_CALL;
pDispatcherContext->ControlPcIsUnwound = FALSE;
// Also, clear out the debug-registers flag so that when this context is used by the
// OS, it does not end up setting bogus access breakpoints. The kernel team will also
// be fixing it at their end, in their implementation of collided unwind.
pDispatcherContext->ContextRecord->ContextFlags &= ~CONTEXT_DEBUG_REGISTERS;
#ifdef _TARGET_ARM_
// But keep the architecture flag set (its part of CONTEXT_DEBUG_REGISTERS)
pDispatcherContext->ContextRecord->ContextFlags |= CONTEXT_ARM;
#else // _TARGET_ARM64_
// But keep the architecture flag set (its part of CONTEXT_DEBUG_REGISTERS)
pDispatcherContext->ContextRecord->ContextFlags |= CONTEXT_ARM64;
#endif // _TARGET_ARM_
#endif // _TARGET_ARM_ || _TARGET_ARM64_
INDEBUG(pDispatcherContext->FunctionEntry = (PRUNTIME_FUNCTION)INVALID_POINTER_CD);
INDEBUG(pDispatcherContext->ImageBase = INVALID_POINTER_CD);
pDispatcherContext->FunctionEntry = RtlLookupFunctionEntry(pDispatcherContext->ControlPc,
&(pDispatcherContext->ImageBase),
NULL
);
_ASSERTE(((PRUNTIME_FUNCTION)INVALID_POINTER_CD) != pDispatcherContext->FunctionEntry);
_ASSERTE(INVALID_POINTER_CD != pDispatcherContext->ImageBase);
//
// need to find the establisher frame by virtually unwinding
//
CONTEXT tempContext;
PVOID HandlerData;
CopyOSContext(&tempContext, pDispatcherContext->ContextRecord);
// RtlVirtualUnwind returns the language specific handler for the ControlPC in question
// on ARM and AMD64.
pDispatcherContext->LanguageHandler = RtlVirtualUnwind(
NULL, // HandlerType
pDispatcherContext->ImageBase,
pDispatcherContext->ControlPc,
pDispatcherContext->FunctionEntry,
&tempContext,
&HandlerData,
&(pDispatcherContext->EstablisherFrame),
NULL);
pDispatcherContext->HandlerData = NULL;
pDispatcherContext->HistoryTable = NULL;
// Why does the OS consider it invalid to have a NULL personality routine (or, why does
// the OS assume that DispatcherContext returned from ExceptionCollidedUnwind will always
// have a valid personality routine)?
//
//
// We force the OS to pickup the DispatcherContext (that we fixed above) by returning
// ExceptionCollidedUnwind. Per Dave Cutler, the only entity which is allowed to return
// this exception disposition is the personality routine of the assembly helper which is used
// to invoke the user (stack-based) personality routines. For such invocations made by the
// OS assembly helper, the DispatcherContext it saves before invoking the user personality routine
// will always have a valid personality routine reference and thus, when a real collided unwind happens
// and this exception disposition is returned, OS exception dispatch will have a valid personality routine
// to invoke.
//
// By using this exception disposition to make the OS walk stacks we broke (for async exceptions), we are
// simply abusing the semantic of this disposition. However, since we must use it, we should also check
// that we are returning a valid personality routine reference back to the OS.
if(pDispatcherContext->LanguageHandler == NULL)
{
if (pUnwindPersonalityRoutine != NULL)
{
pDispatcherContext->LanguageHandler = pUnwindPersonalityRoutine;
}
else
{
// We would be here only for fixing up context for an async exception in managed code.
// This implies that we should have got a personality routine returned from the call to
// RtlVirtualUnwind above.
//
// However, if the ControlPC happened to be in the prolog or epilog of a managed method,
// then RtlVirtualUnwind will always return NULL. We cannot return this NULL back to the
// OS as it is an invalid value which the OS does not expect (and attempting to do so will
// result in the kernel exception dispatch going haywire).
#if defined(_DEBUG)
// We should be in jitted code
TADDR adrRedirectedIP = PCODEToPINSTR(pDispatcherContext->ControlPc);
_ASSERTE(ExecutionManager::IsManagedCode(adrRedirectedIP));
#endif // _DEBUG
// Set the personality routine to be returned as the one which is conventionally
// invoked for exception dispatch.
pDispatcherContext->LanguageHandler = (PEXCEPTION_ROUTINE)GetEEFuncEntryPoint(ProcessCLRException);
STRESS_LOG1(LF_EH, LL_INFO10, "FDC: ControlPC was in prolog/epilog, so setting DC->LanguageHandler to %p\n", pDispatcherContext->LanguageHandler);
}
}
_ASSERTE(pDispatcherContext->LanguageHandler != NULL);
#else // !FEATURE_PAL
PORTABILITY_ASSERT("UNIXTODO: Implement the fixup for PAL");
#endif // !FEATURE_PAL
}
// See the comment above for the overloaded version of this function.
FORCEINLINE void FixupDispatcherContext(DISPATCHER_CONTEXT* pDispatcherContext, CONTEXT* pContext, CONTEXT* pOriginalContext, PEXCEPTION_ROUTINE pUnwindPersonalityRoutine = NULL)
{
_ASSERTE(pOriginalContext != NULL);
FixupDispatcherContext(pDispatcherContext, pContext, (LPVOID)::GetIP(pOriginalContext), pUnwindPersonalityRoutine);
}
BOOL FirstCallToHandler (
DISPATCHER_CONTEXT *pDispatcherContext,
CONTEXT **ppContextRecord)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
SO_TOLERANT;
}
CONTRACTL_END;
FaultingExceptionFrame *pFrame = GetFrameFromRedirectedStubStackFrame(pDispatcherContext);
BOOL *pfFilterExecuted = pFrame->GetFilterExecutedFlag();
BOOL fFilterExecuted = *pfFilterExecuted;
STRESS_LOG4(LF_EH, LL_INFO10, "FirstCallToHandler: Fixing exception context for redirect stub, sp %p, establisher %p, flag %p -> %u\n",
GetSP(pDispatcherContext->ContextRecord),
pDispatcherContext->EstablisherFrame,
pfFilterExecuted,
fFilterExecuted);
*ppContextRecord = pFrame->GetExceptionContext();
*pfFilterExecuted = TRUE;
return !fFilterExecuted;
}
EXTERN_C EXCEPTION_DISPOSITION
HijackHandler(IN PEXCEPTION_RECORD pExceptionRecord
WIN64_ARG(IN ULONG64 MemoryStackFp)
NOT_WIN64_ARG(IN ULONG MemoryStackFp),
IN OUT PCONTEXT pContextRecord,
IN OUT PDISPATCHER_CONTEXT pDispatcherContext
)
{
CONTRACTL
{
GC_NOTRIGGER;
NOTHROW;
MODE_ANY;
SO_TOLERANT;
}
CONTRACTL_END;
STRESS_LOG4(LF_EH, LL_INFO10, "HijackHandler: establisher: %p, disp->cxr: %p, sp %p, cxr @ exception: %p\n",
pDispatcherContext->EstablisherFrame,
pDispatcherContext->ContextRecord,
GetSP(pDispatcherContext->ContextRecord),
pContextRecord);
Thread* pThread = GetThread();
CONTEXT *pNewContext = NULL;
VALIDATE_BACKOUT_STACK_CONSUMPTION;
if (FirstCallToHandler(pDispatcherContext, &pNewContext))
{
//
// We've pushed a Frame, but it is not initialized yet, so we
// must not be in preemptive mode
//
CONSISTENCY_CHECK(pThread->PreemptiveGCDisabled());
//
// AdjustContextForThreadStop will reset the ThrowControlForThread state
// on the thread, but we don't want to do that just yet. We need that
// information in our personality routine, so we will reset it back to
// InducedThreadStop and then clear it in our personality routine.
//
CONSISTENCY_CHECK(IsThreadHijackedForThreadStop(pThread, pExceptionRecord));
AdjustContextForThreadStop(pThread, pNewContext);
pThread->SetThrowControlForThread(Thread::InducedThreadStop);
}
FixupDispatcherContext(pDispatcherContext, pNewContext, pContextRecord);
STRESS_LOG4(LF_EH, LL_INFO10, "HijackHandler: new establisher: %p, disp->cxr: %p, new ip: %p, new sp: %p\n",
pDispatcherContext->EstablisherFrame,
pDispatcherContext->ContextRecord,
GetIP(pDispatcherContext->ContextRecord),
GetSP(pDispatcherContext->ContextRecord));
// Returning ExceptionCollidedUnwind will cause the OS to take our new context record
// and dispatcher context and restart the exception dispatching on this call frame,
// which is exactly the behavior we want in order to restore our thread's unwindability
// (which was broken when we whacked the IP to get control over the thread)
return ExceptionCollidedUnwind;
}
EXTERN_C VOID FixContextForFaultingExceptionFrame (
EXCEPTION_RECORD* pExceptionRecord,
CONTEXT *pContextRecord);
EXTERN_C EXCEPTION_DISPOSITION
FixContextHandler(IN PEXCEPTION_RECORD pExceptionRecord
WIN64_ARG(IN ULONG64 MemoryStackFp)
NOT_WIN64_ARG(IN ULONG MemoryStackFp),
IN OUT PCONTEXT pContextRecord,
IN OUT PDISPATCHER_CONTEXT pDispatcherContext
)
{
CONTEXT* pNewContext = NULL;
VALIDATE_BACKOUT_STACK_CONSUMPTION;
// Our backout validation should ensure that we don't SO here.
BEGIN_CONTRACT_VIOLATION(SOToleranceViolation);
if (FirstCallToHandler(pDispatcherContext, &pNewContext))
{
//
// We've pushed a Frame, but it is not initialized yet, so we
// must not be in preemptive mode
//
CONSISTENCY_CHECK(GetThread()->PreemptiveGCDisabled());
FixContextForFaultingExceptionFrame(pExceptionRecord, pNewContext);
}
FixupDispatcherContext(pDispatcherContext, pNewContext, pContextRecord);
END_CONTRACT_VIOLATION;
// Returning ExceptionCollidedUnwind will cause the OS to take our new context record
// and dispatcher context and restart the exception dispatching on this call frame,
// which is exactly the behavior we want in order to restore our thread's unwindability
// (which was broken when we whacked the IP to get control over the thread)
return ExceptionCollidedUnwind;
}
#ifdef _DEBUG
// IsSafeToUnwindFrameChain:
// Arguments:
// pThread the Thread* being unwound
// MemoryStackFpForFrameChain the stack limit to unwind the Frames
// Returns
// FALSE if the value MemoryStackFpForFrameChain falls between a M2U transition frame
// and its corresponding managed method stack pointer
// TRUE otherwise.
//
// If the managed method will *NOT* be unwound by the current exception
// pass we have an error: with no Frame on the stack to report it, the
// managed method will not be included in the next stack walk.
// An example of running into this issue was DDBug 1133, where
// TransparentProxyStubIA64 had a personality routine that removed a
// transition frame. As a consequence the managed method did not
// participate in the stack walk until the exception handler was called. At
// that time the stack walking code was able to see the managed method again
// but by this time all references from this managed method were stale.
BOOL IsSafeToUnwindFrameChain(Thread* pThread, LPVOID MemoryStackFpForFrameChain)
{
// Look for the last Frame to be removed that marks a managed-to-unmanaged transition
Frame* pLastFrameOfInterest = FRAME_TOP;
for (Frame* pf = pThread->m_pFrame; pf < MemoryStackFpForFrameChain; pf = pf->PtrNextFrame())
{
PCODE retAddr = pf->GetReturnAddress();
if (retAddr != NULL && ExecutionManager::IsManagedCode(retAddr))
{
pLastFrameOfInterest = pf;
}
}
// If there is none it's safe to remove all these Frames
if (pLastFrameOfInterest == FRAME_TOP)
{
return TRUE;
}
// Otherwise "unwind" to managed method
REGDISPLAY rd;
CONTEXT ctx;
SetIP(&ctx, 0);
SetSP(&ctx, 0);
FillRegDisplay(&rd, &ctx);
pLastFrameOfInterest->UpdateRegDisplay(&rd);
// We're safe only if the managed method will be unwound also
LPVOID managedSP = dac_cast<PTR_VOID>(GetRegdisplaySP(&rd));
if (managedSP < MemoryStackFpForFrameChain)
{
return TRUE;
}
else
{
return FALSE;
}
}
#endif // _DEBUG
void CleanUpForSecondPass(Thread* pThread, bool fIsSO, LPVOID MemoryStackFpForFrameChain, LPVOID MemoryStackFp)
{
WRAPPER_NO_CONTRACT;
EH_LOG((LL_INFO100, "Exception is going into unmanaged code, unwinding frame chain to %p\n", MemoryStackFpForFrameChain));
// On AMD64 the establisher pointer is the live stack pointer, but on
// IA64 and ARM it's the caller's stack pointer. It makes no difference, since there
// is no Frame anywhere in CallDescrWorker's region of stack.
// First make sure that unwinding the frame chain does not remove any transition frames
// that report managed methods that will not be unwound.
// If this assert fires it's probably the personality routine of some assembly code that
// incorrectly removed a transition frame (more details in IsSafeToUnwindFrameChain)
// [Do not perform the IsSafeToUnwindFrameChain() check in the SO case, since
// IsSafeToUnwindFrameChain() requires a large amount of stack space.]
_ASSERTE(fIsSO || IsSafeToUnwindFrameChain(pThread, (Frame*)MemoryStackFpForFrameChain));
UnwindFrameChain(pThread, (Frame*)MemoryStackFpForFrameChain);
// Only pop the trackers if this is not an SO. It's not safe to pop the trackers during EH for an SO.
// Instead, we rely on the END_SO_TOLERANT_CODE macro to call ClearExceptionStateAfterSO(). Of course,
// we may leak in the UMThunkStubCommon() case where we don't have this macro lower on the stack
// (stack grows up).
if (!fIsSO)
{
ExceptionTracker::PopTrackerIfEscaping((void*)MemoryStackFp);
}
}
EXTERN_C EXCEPTION_DISPOSITION
UMThunkUnwindFrameChainHandler(IN PEXCEPTION_RECORD pExceptionRecord
WIN64_ARG(IN ULONG64 MemoryStackFp)
NOT_WIN64_ARG(IN ULONG MemoryStackFp),
IN OUT PCONTEXT pContextRecord,
IN OUT PDISPATCHER_CONTEXT pDispatcherContext
)
{
Thread* pThread = GetThread();
if (pThread == NULL) {
return ExceptionContinueSearch;
}
bool fIsSO =
IsSOExceptionCode(pExceptionRecord->ExceptionCode);
VALIDATE_BACKOUT_STACK_CONSUMPTION;
if (IS_UNWINDING(pExceptionRecord->ExceptionFlags))
{
if (fIsSO)
{
if (!pThread->PreemptiveGCDisabled())
{
pThread->DisablePreemptiveGC();
}
}
// The VALIDATE_BACKOUT_STACK_CONSUMPTION makes sure that this function does not use stack more than backout limit.
CONTRACT_VIOLATION(SOToleranceViolation);
CleanUpForSecondPass(pThread, fIsSO, (void*)MemoryStackFp, (void*)MemoryStackFp);
}
// The asm stub put us into COOP mode, but we're about to scan unmanaged call frames
// so unmanaged filters/handlers/etc can run and we must be in PREEMP mode for that.
if (pThread->PreemptiveGCDisabled())
{
if (fIsSO)
{
// We don't have stack to do full-version EnablePreemptiveGC.
FastInterlockAnd (&pThread->m_fPreemptiveGCDisabled, 0);
}
else
{
pThread->EnablePreemptiveGC();
}
}
return ExceptionContinueSearch;
}
EXTERN_C EXCEPTION_DISPOSITION
UMEntryPrestubUnwindFrameChainHandler(
IN PEXCEPTION_RECORD pExceptionRecord
WIN64_ARG(IN ULONG64 MemoryStackFp)
NOT_WIN64_ARG(IN ULONG MemoryStackFp),
IN OUT PCONTEXT pContextRecord,
IN OUT PDISPATCHER_CONTEXT pDispatcherContext
)
{
EXCEPTION_DISPOSITION disposition = UMThunkUnwindFrameChainHandler(
pExceptionRecord,
MemoryStackFp,
pContextRecord,
pDispatcherContext
);
return disposition;
}
EXTERN_C EXCEPTION_DISPOSITION
UMThunkStubUnwindFrameChainHandler(
IN PEXCEPTION_RECORD pExceptionRecord
WIN64_ARG(IN ULONG64 MemoryStackFp)
NOT_WIN64_ARG(IN ULONG MemoryStackFp),
IN OUT PCONTEXT pContextRecord,
IN OUT PDISPATCHER_CONTEXT pDispatcherContext
)
{
#ifdef _DEBUG
// If the exception is escaping the last CLR personality routine on the stack,
// then state a flag on the thread to indicate so.
//
// We check for thread object since this function is the personality routine of the UMThunk
// and we can landup here even when thread creation (within the thunk) fails.
if (GetThread() != NULL)
{
SetReversePInvokeEscapingUnhandledExceptionStatus(IS_UNWINDING(pExceptionRecord->ExceptionFlags),
MemoryStackFp
);
}
#endif // _DEBUG
// We need to ReverseLeaveRuntime if we are unwinding (since there is no
// frame to do this for us...
if (IS_UNWINDING(pExceptionRecord->ExceptionFlags))
{
BYTE bFlag;
#ifdef _TARGET_AMD64_
bFlag = *(BYTE*)(pDispatcherContext->ContextRecord->Rbp + UMTHUNKSTUB_HOST_NOTIFY_FLAG_RBPOFFSET);
#elif defined(_TARGET_ARM_) || defined(_TARGET_ARM64_)
// On ARM, we do not need to do anything here. If required, ReverseEnterRuntime should happen
// in the VM in UMThunkStubWorker via a holder so that during an exceptional case, we will
// automatically perform the ReverseLeaveRuntime.
bFlag = 0;
#else
bFlag = 0;
PORTABILITY_ASSERT("NYI -- UMThunkStubUnwindFrameChainHandler notify host of ReverseLeaveRuntime");
#endif // _TARGET_AMD64_
if (0 != bFlag)
{
GetThread()->ReverseLeaveRuntime();
}
}
EXCEPTION_DISPOSITION disposition = UMThunkUnwindFrameChainHandler(
pExceptionRecord,
MemoryStackFp,
pContextRecord,
pDispatcherContext
);
return disposition;
}
// This is the personality routine setup for the assembly helper (CallDescrWorker) that calls into
// managed code.
EXTERN_C EXCEPTION_DISPOSITION
CallDescrWorkerUnwindFrameChainHandler(IN PEXCEPTION_RECORD pExceptionRecord
WIN64_ARG(IN ULONG64 MemoryStackFp)
NOT_WIN64_ARG(IN ULONG MemoryStackFp),
IN OUT PCONTEXT pContextRecord,
IN OUT PDISPATCHER_CONTEXT pDispatcherContext
)
{
Thread* pThread = GetThread();
_ASSERTE(pThread);
if (IsSOExceptionCode(pExceptionRecord->ExceptionCode))
{
if (IS_UNWINDING(pExceptionRecord->ExceptionFlags))
{
GCX_COOP_NO_DTOR();
CleanUpForSecondPass(pThread, true, (void*)MemoryStackFp, (void*)MemoryStackFp);
}
FastInterlockAnd (&pThread->m_fPreemptiveGCDisabled, 0);
// We'll let the SO infrastructure handle this exception... at that point, we
// know that we'll have enough stack to do it.
return ExceptionContinueSearch;
}
EXCEPTION_DISPOSITION retVal = ProcessCLRException(pExceptionRecord,
MemoryStackFp,
pContextRecord,
pDispatcherContext);
// Our backout validation should ensure that we don't SO here. Add a
// backout validation here.
BEGIN_CONTRACT_VIOLATION(SOToleranceViolation);
if (retVal == ExceptionContinueSearch)
{
if (IS_UNWINDING(pExceptionRecord->ExceptionFlags))
{
CleanUpForSecondPass(pThread, false, (void*)MemoryStackFp, (void*)MemoryStackFp);
}
// We're scanning out from CallDescr and potentially through the EE and out to unmanaged.
// So switch to preemptive mode.
GCX_PREEMP_NO_DTOR();
}
END_CONTRACT_VIOLATION;
return retVal;
}
#ifdef FEATURE_COMINTEROP
EXTERN_C EXCEPTION_DISPOSITION
ReverseComUnwindFrameChainHandler(IN PEXCEPTION_RECORD pExceptionRecord
WIN64_ARG(IN ULONG64 MemoryStackFp)
NOT_WIN64_ARG(IN ULONG MemoryStackFp),
IN OUT PCONTEXT pContextRecord,
IN OUT PDISPATCHER_CONTEXT pDispatcherContext
)
{
if (IS_UNWINDING(pExceptionRecord->ExceptionFlags))
{
ComMethodFrame::DoSecondPassHandlerCleanup(GetThread()->GetFrame());
}
return ExceptionContinueSearch;
}
#endif // FEATURE_COMINTEROP
EXTERN_C EXCEPTION_DISPOSITION
FixRedirectContextHandler(
IN PEXCEPTION_RECORD pExceptionRecord
WIN64_ARG(IN ULONG64 MemoryStackFp)
NOT_WIN64_ARG(IN ULONG MemoryStackFp),
IN OUT PCONTEXT pContextRecord,
IN OUT PDISPATCHER_CONTEXT pDispatcherContext
)
{
CONTRACTL
{
GC_NOTRIGGER;
NOTHROW;
MODE_ANY;
SO_TOLERANT;
}
CONTRACTL_END;
STRESS_LOG4(LF_EH, LL_INFO10, "FixRedirectContextHandler: sp %p, establisher %p, cxr: %p, disp cxr: %p\n",
GetSP(pDispatcherContext->ContextRecord),
pDispatcherContext->EstablisherFrame,
pContextRecord,
pDispatcherContext->ContextRecord);
VALIDATE_BACKOUT_STACK_CONSUMPTION;
CONTEXT *pRedirectedContext = GetCONTEXTFromRedirectedStubStackFrame(pDispatcherContext);
FixupDispatcherContext(pDispatcherContext, pRedirectedContext, pContextRecord);
// Returning ExceptionCollidedUnwind will cause the OS to take our new context record
// and dispatcher context and restart the exception dispatching on this call frame,
// which is exactly the behavior we want in order to restore our thread's unwindability
// (which was broken when we whacked the IP to get control over the thread)
return ExceptionCollidedUnwind;
}
#endif // DACCESS_COMPILE
void ExceptionTracker::StackRange::Reset()
{
LIMITED_METHOD_CONTRACT;
m_sfLowBound.SetMaxVal();
m_sfHighBound.Clear();
}
bool ExceptionTracker::StackRange::IsEmpty()
{
LIMITED_METHOD_CONTRACT;
return (m_sfLowBound.IsMaxVal() &&
m_sfHighBound.IsNull());
}
bool ExceptionTracker::StackRange::IsSupersededBy(StackFrame sf)
{
LIMITED_METHOD_CONTRACT;
CONSISTENCY_CHECK(IsConsistent());
return (sf >= m_sfLowBound);
}
void ExceptionTracker::StackRange::CombineWith(StackFrame sfCurrent, StackRange* pPreviousRange)
{
LIMITED_METHOD_CONTRACT;
if ((pPreviousRange->m_sfHighBound < sfCurrent) && IsEmpty())
{
// This case comes from an unusual situation. It is possible for a new nested tracker to start its
// first pass at a higher SP than any previously scanned frame in the previous "enclosing" tracker.
// Typically this doesn't happen because the ProcessCLRException callback is made multiple times for
// the frame where the nesting first occurs and that will ensure that the stack range of the new
// nested exception is extended to contain the scan range of the previous tracker's scan. However,
// if the exception dispatch calls a C++ handler (e.g. a finally) and then that handler tries to
// reverse-pinvoke into the runtime, AND we trigger an exception (e.g. ThreadAboard,
// AppDomainUnloaded) before we reach another managed frame (which would have the CLR personality
// routine associated with it), the first callback to ProcessCLRException for this new exception
// will occur on a frame that has never been seen before by the current tracker.
//
// So in this case, we'll see a sfCurrent that is larger than the previous tracker's high bound and
// we'll have an empty scan range for the current tracker. And we'll just need to pre-init the
// scanned stack range for the new tracker to the previous tracker's range. This maintains the
// invariant that the scanned range for nested trackers completely cover the scanned range of thier
// previous tracker once they "escape" the previous tracker.
STRESS_LOG3(LF_EH, LL_INFO100,
"Initializing current StackRange with previous tracker's StackRange. sfCurrent: %p, prev low: %p, prev high: %p\n",
sfCurrent.SP, pPreviousRange->m_sfLowBound.SP, pPreviousRange->m_sfHighBound.SP);
*this = *pPreviousRange;
}
else
{
m_sfHighBound = pPreviousRange->m_sfHighBound;
}
}
bool ExceptionTracker::StackRange::Contains(StackFrame sf)
{
LIMITED_METHOD_CONTRACT;
CONSISTENCY_CHECK(IsConsistent());
return ((m_sfLowBound <= sf) &&
(sf <= m_sfHighBound));
}
void ExceptionTracker::StackRange::ExtendUpperBound(StackFrame sf)
{
LIMITED_METHOD_CONTRACT;
CONSISTENCY_CHECK(IsConsistent());
CONSISTENCY_CHECK(sf > m_sfHighBound);
m_sfHighBound = sf;
}
void ExceptionTracker::StackRange::ExtendLowerBound(StackFrame sf)
{
LIMITED_METHOD_CONTRACT;
CONSISTENCY_CHECK(IsConsistent());
CONSISTENCY_CHECK(sf < m_sfLowBound);
m_sfLowBound = sf;
}
void ExceptionTracker::StackRange::TrimLowerBound(StackFrame sf)
{
LIMITED_METHOD_CONTRACT;
CONSISTENCY_CHECK(IsConsistent());
CONSISTENCY_CHECK(sf >= m_sfLowBound);
m_sfLowBound = sf;
}
StackFrame ExceptionTracker::StackRange::GetLowerBound()
{
LIMITED_METHOD_CONTRACT;
CONSISTENCY_CHECK(IsConsistent());
return m_sfLowBound;
}
StackFrame ExceptionTracker::StackRange::GetUpperBound()
{
LIMITED_METHOD_CONTRACT;
CONSISTENCY_CHECK(IsConsistent());
return m_sfHighBound;
}
#ifdef _DEBUG
bool ExceptionTracker::StackRange::IsDisjointWithAndLowerThan(StackRange* pOtherRange)
{
CONSISTENCY_CHECK(IsConsistent());
CONSISTENCY_CHECK(pOtherRange->IsConsistent());
return m_sfHighBound < pOtherRange->m_sfLowBound;
}
#endif // _DEBUG
#ifdef _DEBUG
bool ExceptionTracker::StackRange::IsConsistent()
{
LIMITED_METHOD_CONTRACT;
if (m_sfLowBound.IsMaxVal() ||
m_sfHighBound.IsNull())
{
return true;
}
if (m_sfLowBound <= m_sfHighBound)
{
return true;
}
LOG((LF_EH, LL_ERROR, "sp: low: %p high: %p\n", m_sfLowBound.SP, m_sfHighBound.SP));
return false;
}
#endif // _DEBUG
// Determine if the given StackFrame is in the stack region unwound by the specified ExceptionTracker.
// This is used by the stackwalker to skip funclets. Refer to the calls to this method in StackWalkFramesEx()
// for more information.
//
// Effectively, this will make the stackwalker skip all the frames until it reaches the frame
// containing the funclet. Details of the skipping logic are described in the method implementation.
//
// static
bool ExceptionTracker::IsInStackRegionUnwoundBySpecifiedException(CrawlFrame * pCF, PTR_ExceptionTracker pExceptionTracker)
{
LIMITED_METHOD_CONTRACT;
_ASSERTE(pCF != NULL);
// The tracker must be in the second pass, and its stack range must not be empty.
if ( (pExceptionTracker == NULL) ||
pExceptionTracker->IsInFirstPass() ||
pExceptionTracker->m_ScannedStackRange.IsEmpty())
{
return false;
}
CallerStackFrame csfToCheck;
if (pCF->IsFrameless())
{
csfToCheck = CallerStackFrame::FromRegDisplay(pCF->GetRegisterSet());
}
else
{
csfToCheck = CallerStackFrame((UINT_PTR)pCF->GetFrame());
}
StackFrame sfLowerBound = pExceptionTracker->m_ScannedStackRange.GetLowerBound();
StackFrame sfUpperBound = pExceptionTracker->m_ScannedStackRange.GetUpperBound();
//
// Let's take an example callstack that grows from left->right:
//
// M5 (50) -> M4 (40) -> M3 (30) -> M2 (20) -> M1 (10) ->throw
//
// These are all managed frames, where M1 throws and the exception is caught
// in M4. The numbers in the brackets is the value of stack pointer after
// the prolog is executed (or, incase of dynamic allocation, its SP after
// dynamic allocation) and will be the SP at the time the callee function
// is invoked.
//
// When the stackwalker is asked to skip funclets during the stackwalk,
// it will skip all the frames on the stack until it reaches the frame
// containing the funclet after it has identified the funclet from
// which the skipping of frames needs to commence.
//
// At such a point, the exception tracker's scanned stack range's
// lowerbound will correspond to the frame that had the exception
// and the upper bound will correspond to the frame that had the funclet.
// For scenarios like security stackwalk that maybe triggered out of a
// funclet (e.g. a catch block), skipping funclets and frames in this fashion
// is expected to lead us to the parent frame containing the funclet as it
// will contain an object of interest (e.g. security descriptor).
//
// The check below ensures that we skip the frames from the one that
// had exception to the one that is the callee of the method containing
// the funclet of interest. In the example above, this would mean skipping
// from M1 to M3.
//
// We use CallerSP of a given CrawlFrame to perform such a skip. On AMD64,
// the first frame where CallerSP will be greater than SP of the frame
// itself will be when we reach the lowest frame itself (i.e. M1). On a similar
// note, the only time when CallerSP of a given CrawlFrame will be equal to the
// upper bound is when we reach the callee of the frame containing the funclet.
// Thus, our check for the skip range is done by the following clause:
//
// if ((sfLowerBound < csfToCheck) && (csfToCheck <= sfUpperBound))
//
// On ARM & ARM64, while the lower and upper bounds are populated using the Establisher
// frame given by the OS during exception dispatch, they actually correspond to the
// SP of the caller of a given frame, instead of being the SP of the given frame.
// That is, on ARM, we will have lowerBound as 20 (corresponding to M1) and
// upperBound as 50 (corresponding to M4 which contains the catch funclet).
//
// Thus, to skip frames on ARM until we reach the frame containing funclet of
// interest, the skipping will done by the following clause:
//
// if ((sfLowerBound <= csfToCheck) && (csfToCheck < sfUpperBound))
//
// The first time when CallerSP of a given CrawlFrame will be the same as lowerBound
// is when we will reach the first frame to be skipped. Likewise, last frame whose
// CallerSP will be less than the upperBound will be the callee of the frame
// containing the funclet. When CallerSP is equal to the upperBound, we have reached
// the frame containing the funclet and DO NOT want to skip it. Hence, "<"
// in the 2nd part of the clause.
// Remember that sfLowerBound and sfUpperBound are in the "OS format".
// Refer to the comment for CallerStackFrame for more information.
#if defined(_TARGET_AMD64_)
if ((sfLowerBound < csfToCheck) && (csfToCheck <= sfUpperBound))
#else // _TARGET_ARM_ || _TARGET_ARM64_
if ((sfLowerBound <= csfToCheck) && (csfToCheck < sfUpperBound))
#endif // _TARGET_AMD64_
{
return true;
}
else
{
return false;
}
}
// Returns a bool indicating if the specified CrawlFrame has been unwound by the active exception.
bool ExceptionTracker::IsInStackRegionUnwoundByCurrentException(CrawlFrame * pCF)
{
LIMITED_METHOD_CONTRACT;
Thread * pThread = pCF->pThread;
PTR_ExceptionTracker pCurrentTracker = pThread->GetExceptionState()->GetCurrentExceptionTracker();
return ExceptionTracker::IsInStackRegionUnwoundBySpecifiedException(pCF, pCurrentTracker);
}
// Returns a bool indicating if the specified CrawlFrame has been unwound by any active (e.g. nested) exceptions.
//
// This method uses various fields of the ExceptionTracker data structure to do its work. Since this code runs on the thread
// performing the GC stackwalk, it must be ensured that these fields are not updated on another thread in parallel. Thus,
// any access to the fields in question that may result in updating them should happen in COOP mode. This provides a high-level
// synchronization with the GC thread since when GC stackwalk is active, attempt to enter COOP mode will result in the thread blocking
// and thus, attempts to update such fields will be synchronized.
//
// Currently, the following fields are used below:
//
// m_ExceptionFlags, m_ScannedStackRange, m_sfCurrentEstablisherFrame, m_sfLastUnwoundEstablisherFrame,
// m_pInitialExplicitFrame, m_pLimitFrame, m_pPrevNestedInfo.
//
bool ExceptionTracker::HasFrameBeenUnwoundByAnyActiveException(CrawlFrame * pCF)
{
LIMITED_METHOD_CONTRACT;
_ASSERTE(pCF != NULL);
// Enumerate all (nested) exception trackers and see if any of them has unwound the
// specified CrawlFrame.
Thread * pTargetThread = pCF->pThread;
PTR_ExceptionTracker pTopTracker = pTargetThread->GetExceptionState()->GetCurrentExceptionTracker();
PTR_ExceptionTracker pCurrentTracker = pTopTracker;
bool fHasFrameBeenUnwound = false;
while (pCurrentTracker != NULL)
{
bool fSkipCurrentTracker = false;
// The tracker must be in the second pass, and its stack range must not be empty.
if (pCurrentTracker->IsInFirstPass() ||
pCurrentTracker->m_ScannedStackRange.IsEmpty())
{
fSkipCurrentTracker = true;
}
if (!fSkipCurrentTracker)
{
CallerStackFrame csfToCheck;
bool fFrameless = false;
if (pCF->IsFrameless())
{
csfToCheck = CallerStackFrame::FromRegDisplay(pCF->GetRegisterSet());
fFrameless = true;
}
else
{
csfToCheck = CallerStackFrame((UINT_PTR)pCF->GetFrame());
}
STRESS_LOG4(LF_EH|LF_GCROOTS, LL_INFO100, "CrawlFrame (%p): Frameless: %s %s: %p\n", pCF, fFrameless?"Yes":"No", fFrameless?"CallerSP":"Address", csfToCheck.SP);
StackFrame sfLowerBound = pCurrentTracker->m_ScannedStackRange.GetLowerBound();
StackFrame sfUpperBound = pCurrentTracker->m_ScannedStackRange.GetUpperBound();
StackFrame sfCurrentEstablisherFrame = pCurrentTracker->GetCurrentEstablisherFrame();
StackFrame sfLastUnwoundEstablisherFrame = pCurrentTracker->GetLastUnwoundEstablisherFrame();
STRESS_LOG4(LF_EH|LF_GCROOTS, LL_INFO100, "LowerBound/UpperBound/CurrentEstablisherFrame/LastUnwoundManagedFrame: %p/%p/%p/%p\n", sfLowerBound.SP, sfUpperBound.SP,
sfCurrentEstablisherFrame.SP, sfLastUnwoundEstablisherFrame.SP);
// Refer to the detailed comment in ExceptionTracker::IsInStackRegionUnwoundBySpecifiedException on the nature
// of this check.
//
#if defined(_TARGET_AMD64_)
if ((sfLowerBound < csfToCheck) && (csfToCheck <= sfUpperBound))
#elif defined(_TARGET_ARM_) || defined(_TARGET_ARM64_)
if ((sfLowerBound <= csfToCheck) && (csfToCheck < sfUpperBound))
#else
PORTABILITY_ASSERT("ExceptionTracker::HasFrameBeenUnwoundByAnyActiveException");
#endif // _TARGET_AMD64_
{
fHasFrameBeenUnwound = true;
break;
}
//
// The frame in question was not found to be covered by the scanned stack range of the exception tracker.
// If the frame is managed, then its possible that it forms the upper bound of the scanned stack range.
//
// The scanned stack range is updated by our personality routine once ExceptionTracker::ProcessOSExceptionNotification is invoked.
// However, it is possible that we have unwound a frame and returned back to the OS (in preemptive mode) and:
//
// 1) Either our personality routine has been invoked for the subsequent upstack managed frame but it has not yet got a chance to update
// the scanned stack range, OR
// 2) We have simply returned to the kernel exception dispatch and yet to be invoked for a subsequent frame.
//
// In such a window, if we have been asked to check if the frame forming the upper bound of the scanned stack range has been unwound, or not,
// then do the needful validations.
//
// This is applicable to managed frames only.
if (fFrameless)
{
#if defined(_TARGET_AMD64_)
// On X64, if the SP of the managed frame indicates that the frame is forming the upper bound,
// then:
//
// For case (1) above, sfCurrentEstablisherFrame will be the same as the callerSP of the managed frame.
// For case (2) above, sfLastUnwoundEstbalisherFrame would be the same as the managed frame's SP (or upper bound)
//
// For these scenarios, the frame is considered unwound.
if (GetRegdisplaySP(pCF->GetRegisterSet()) == sfUpperBound.SP)
{
if (csfToCheck == sfCurrentEstablisherFrame)
{
fHasFrameBeenUnwound = true;
break;
}
else if (sfUpperBound == sfLastUnwoundEstablisherFrame)
{
fHasFrameBeenUnwound = true;
break;
}
}
#else // _TARGET_ARM_ || _TARGET_ARM64_
// On ARM, if the callerSP of the managed frame is the same as upper bound, then:
//
// For case (1), sfCurrentEstablisherFrame will be above the callerSP of the managed frame (since EstbalisherFrame is the caller SP for a given frame on ARM)
// For case (2), upper bound will be the same as LastUnwoundEstbalisherFrame.
//
// For these scenarios, the frame is considered unwound.
if (sfUpperBound == csfToCheck)
{
if (csfToCheck < sfCurrentEstablisherFrame)
{
fHasFrameBeenUnwound = true;
break;
}
else if (sfLastUnwoundEstablisherFrame == sfUpperBound)
{
fHasFrameBeenUnwound = true;
break;
}
}
#endif // _TARGET_AMD64_
}
// The frame in question does not appear in the current tracker's scanned stack range (of managed frames).
// If the frame is an explicit frame, then check if it equal to (or greater) than the initial explicit frame
// of the tracker. We can do this equality comparison because explicit frames are stack allocated.
//
// Do keep in mind that InitialExplicitFrame is only set in the 2nd (unwind) pass, which works
// fine for the purpose of this method since it operates on exception trackers in the second pass only.
if (!fFrameless)
{
PTR_Frame pInitialExplicitFrame = pCurrentTracker->GetInitialExplicitFrame();
PTR_Frame pLimitFrame = pCurrentTracker->GetLimitFrame();
#if !defined(DACCESS_COMPILE)
STRESS_LOG2(LF_EH|LF_GCROOTS, LL_INFO100, "InitialExplicitFrame: %p, LimitFrame: %p\n", pInitialExplicitFrame, pLimitFrame);
#endif // !defined(DACCESS_COMPILE)
// Ideally, we would like to perform a comparison check to determine if the
// frame has been unwound. This, however, is based upon the premise that
// each explicit frame that is added to the frame chain is at a lower
// address than this predecessor.
//
// This works for frames across function calls but if we have multiple
// explicit frames in the same function, then the compiler is free to
// assign an address it deems fit. Thus, its totally possible for a
// frame at the head of the frame chain to be @ a higher address than
// its predecessor. This has been observed to be true with VC++ compiler
// in the CLR ret build.
//
// To address this, we loop starting from the InitialExplicitFrame until we reach
// the LimitFrame. Since all frames starting from the InitialExplicitFrame, and prior
// to the LimitFrame, have been unwound, we break out of the loop if we find
// the frame we are looking for, setting a flag indicating that the frame in question
// was unwound.
/*if ((sfInitialExplicitFrame <= csfToCheck) && (csfToCheck < sfLimitFrame))
{
// The explicit frame falls in the range of explicit frames unwound by this tracker.
fHasFrameBeenUnwound = true;
break;
}*/
PTR_Frame pFrameToCheck = (PTR_Frame)csfToCheck.SP;
PTR_Frame pCurrentFrame = pInitialExplicitFrame;
{
while((pCurrentFrame != FRAME_TOP) && (pCurrentFrame != pLimitFrame))
{
if (pCurrentFrame == pFrameToCheck)
{
fHasFrameBeenUnwound = true;
break;
}
pCurrentFrame = pCurrentFrame->PtrNextFrame();
}
}
if (fHasFrameBeenUnwound == true)
{
break;
}
}
}
// Move to the next (previous) tracker
pCurrentTracker = pCurrentTracker->GetPreviousExceptionTracker();
}
if (fHasFrameBeenUnwound)
STRESS_LOG0(LF_EH|LF_GCROOTS, LL_INFO100, "Has already been unwound\n");
return fHasFrameBeenUnwound;
}
//---------------------------------------------------------------------------------------
//
// Given the CrawlFrame of the current frame, return a StackFrame representing the current frame.
// This StackFrame should only be used in a check to see if the current frame is the parent method frame
// of a particular funclet. Don't use the returned StackFrame in any other way except to pass it back to
// ExceptionTracker::IsUnwoundToTargetParentFrame(). The comparison logic is very platform-dependent.
//
// Arguments:
// pCF - the CrawlFrame for the current frame
//
// Return Value:
// Return a StackFrame for parent frame check
//
// Notes:
// Don't use the returned StackFrame in any other way.
//
//static
StackFrame ExceptionTracker::GetStackFrameForParentCheck(CrawlFrame * pCF)
{
WRAPPER_NO_CONTRACT;
StackFrame sfResult;
// Returns the CrawlFrame's caller's SP - this is used to determine if we have
// reached the intended CrawlFrame in question (or not).
// sfParent is returned by the EH subsystem, which uses the OS format, i.e. the initial SP before
// any dynamic stack allocation. The stackwalker uses the current SP, i.e. the SP after all
// dynamic stack allocations. Thus, we cannot do an equality check. Instead, we get the
// CallerStackFrame, which is the caller SP.
sfResult = (StackFrame)CallerStackFrame::FromRegDisplay(pCF->GetRegisterSet());
return sfResult;
}
//---------------------------------------------------------------------------------------
//
// Given the StackFrame of a parent method frame, determine if we have unwound to it during stackwalking yet.
// The StackFrame should be the return value of one of the FindParentStackFrameFor*() functions.
// Refer to the comment for UnwindStackFrame for more information.
//
// Arguments:
// pCF - the CrawlFrame of the current frame
// sfParent - the StackFrame of the target parent method frame,
// returned by one of the FindParentStackFrameFor*() functions
//
// Return Value:
// whether we have unwound to the target parent method frame
//
// static
bool ExceptionTracker::IsUnwoundToTargetParentFrame(CrawlFrame * pCF, StackFrame sfParent)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
PRECONDITION( CheckPointer(pCF, NULL_NOT_OK) );
PRECONDITION( pCF->IsFrameless() );
PRECONDITION( pCF->GetRegisterSet()->IsCallerContextValid || pCF->GetRegisterSet()->IsCallerSPValid );
}
CONTRACTL_END;
StackFrame sfToCheck = GetStackFrameForParentCheck(pCF);
return IsUnwoundToTargetParentFrame(sfToCheck, sfParent);
}
// static
bool ExceptionTracker::IsUnwoundToTargetParentFrame(StackFrame sfToCheck, StackFrame sfParent)
{
LIMITED_METHOD_CONTRACT;
return (sfParent == sfToCheck);
}
// Given the CrawlFrame for a funclet frame, return the frame pointer of the enclosing funclet frame.
// For filter funclet frames and a normal method frames, this function returns a NULL StackFrame.
//
// <WARNING>
// It is not valid to call this function on an arbitrary funclet. You have to be doing a full stackwalk from
// the leaf frame and skipping method frames as indicated by the return value of this function. This function
// relies on the ExceptionTrackers, which are collapsed in the second pass when a nested exception escapes.
// When this happens, we'll lose information on the funclet represented by the collapsed tracker.
// </WARNING>
//
// Return Value:
// StackFrame.IsNull() - no skipping is necessary
// StackFrame.IsMaxVal() - skip one frame and then ask again
// Anything else - skip to the method frame indicated by the return value and ask again
//
// static
StackFrame ExceptionTracker::FindParentStackFrameForStackWalk(CrawlFrame* pCF, bool fForGCReporting /*= false */)
{
WRAPPER_NO_CONTRACT;
// We should never skip filter funclets. However, if we are stackwalking for GC reference
// reporting, then we need to get the stackframe of the parent frame (where the filter was
// invoked from) so that when we reach it, we can indicate that the filter has already
// performed the reporting.
//
// Thus, for GC reporting purposes, get filter's parent frame.
if (pCF->IsFilterFunclet() && (!fForGCReporting))
{
return StackFrame();
}
else
{
return FindParentStackFrameHelper(pCF, NULL, NULL, NULL, fForGCReporting);
}
}
// Given the CrawlFrame for a filter funclet frame, return the frame pointer of the parent method frame.
// It also returns the relative offset and the caller SP of the parent method frame.
//
// <WARNING>
// The same warning for FindParentStackFrameForStackWalk() also applies here. Moreoever, although
// this function seems to be more convenient, it may potentially trigger a full stackwalk! Do not
// call this unless you know absolutely what you are doing. In most cases FindParentStackFrameForStackWalk()
// is what you need.
// </WARNING>
//
// Return Value:
// StackFrame.IsNull() - no skipping is necessary
// Anything else - the StackFrame of the parent method frame
//
// static
StackFrame ExceptionTracker::FindParentStackFrameEx(CrawlFrame* pCF,
DWORD* pParentOffset,
UINT_PTR* pParentCallerSP)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
PRECONDITION( pCF != NULL );
PRECONDITION( pCF->IsFilterFunclet() );
}
CONTRACTL_END;
bool fRealParent = false;
StackFrame sfResult = ExceptionTracker::FindParentStackFrameHelper(pCF, &fRealParent, pParentOffset, pParentCallerSP);
if (fRealParent)
{
// If the enclosing method is the parent method, then we are done.
return sfResult;
}
else
{
// Otherwise we need to do a full stackwalk to find the parent method frame.
// This should only happen if we are calling a filter inside a funclet.
return ExceptionTracker::RareFindParentStackFrame(pCF, pParentOffset, pParentCallerSP);
}
}
// static
StackFrame ExceptionTracker::GetCallerSPOfParentOfNonExceptionallyInvokedFunclet(CrawlFrame *pCF)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
PRECONDITION(pCF != NULL);
PRECONDITION(pCF->IsFunclet() && (!pCF->IsFilterFunclet()));
}
CONTRACTL_END;
PREGDISPLAY pRD = pCF->GetRegisterSet();
// Ensure that the caller Context is valid.
_ASSERTE(pRD->IsCallerContextValid);
// Make a copy of the caller context
T_CONTEXT tempContext;
CopyOSContext(&tempContext, pRD->pCallerContext);
// Now unwind it to get the context of the caller's caller.
EECodeInfo codeInfo(dac_cast<PCODE>(GetIP(pRD->pCallerContext)));
Thread::VirtualUnwindCallFrame(&tempContext, NULL, &codeInfo);
StackFrame sfRetVal = StackFrame((UINT_PTR)(GetSP(&tempContext)));
_ASSERTE(!sfRetVal.IsNull() && !sfRetVal.IsMaxVal());
return sfRetVal;
}
// static
StackFrame ExceptionTracker::FindParentStackFrameHelper(CrawlFrame* pCF,
bool* pfRealParent,
DWORD* pParentOffset,
UINT_PTR* pParentCallerSP,
bool fForGCReporting /* = false */)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
PRECONDITION( pCF != NULL );
PRECONDITION( pCF->IsFunclet() );
PRECONDITION( CheckPointer(pfRealParent, NULL_OK) );
PRECONDITION( CheckPointer(pParentOffset, NULL_OK) );
PRECONDITION( CheckPointer(pParentCallerSP, NULL_OK) );
}
CONTRACTL_END;
StackFrame sfResult;
REGDISPLAY* pRegDisplay = pCF->GetRegisterSet();
// At this point, we need a valid caller SP and the CallerStackFrame::FromRegDisplay
// asserts that the RegDisplay contains one.
CallerStackFrame csfCurrent = CallerStackFrame::FromRegDisplay(pRegDisplay);
ExceptionTracker *pCurrentTracker = NULL;
bool fIsFilterFunclet = pCF->IsFilterFunclet();
// We can't do this on an unmanaged thread.
Thread* pThread = pCF->pThread;
if (pThread == NULL)
{
_ASSERTE(!"FindParentStackFrame() called on an unmanaged thread");
goto lExit;
}
// Check for out-of-line finally funclets. Filter funclets can't be out-of-line.
if (!fIsFilterFunclet)
{
if (pRegDisplay->IsCallerContextValid)
{
PCODE callerIP = dac_cast<PCODE>(GetIP(pRegDisplay->pCallerContext));
BOOL fIsCallerInVM = FALSE;
// Check if the caller IP is in mscorwks. If it is not, then it is an out-of-line finally.
// Normally, the caller of a finally is ExceptionTracker::CallHandler().
#if defined(DACCESS_COMPILE)
HMODULE_TGT hEE = DacGlobalBase();
#else // !DACCESS_COMPILE
HMODULE_TGT hEE = g_pMSCorEE;
#endif // !DACCESS_COMPILE
fIsCallerInVM = IsIPInModule(hEE, callerIP);
if (!fIsCallerInVM)
{
if (!fForGCReporting)
{
sfResult.SetMaxVal();
goto lExit;
}
else
{
// We have run into a non-exceptionally invoked finally funclet (aka out-of-line finally funclet).
// Since these funclets are invoked from JITted code, we will not find their EnclosingClauseCallerSP
// in an exception tracker as one does not exist (remember, these funclets are invoked "non"-exceptionally).
//
// At this point, the caller context is that of the parent frame of the funclet. All we need is the CallerSP
// of that parent. We leverage a helper function that will perform an unwind against the caller context
// and return us the SP (of the caller of the funclet's parent).
StackFrame sfCallerSPOfFuncletParent = ExceptionTracker::GetCallerSPOfParentOfNonExceptionallyInvokedFunclet(pCF);
return sfCallerSPOfFuncletParent;
}
}
}
}
for (pCurrentTracker = pThread->GetExceptionState()->m_pCurrentTracker;
pCurrentTracker != NULL;
pCurrentTracker = pCurrentTracker->m_pPrevNestedInfo)
{
// Check if the tracker has just been created.
if (pCurrentTracker->m_ScannedStackRange.IsEmpty())
{
continue;
}
// Since the current frame is a non-filter funclet, determine if its caller is the same one
// as was saved against the exception tracker before the funclet was invoked in ExceptionTracker::CallHandler.
CallerStackFrame csfFunclet = pCurrentTracker->m_EHClauseInfo.GetCallerStackFrameForEHClause();
if (csfCurrent == csfFunclet)
{
// The EnclosingClauseCallerSP is initialized in ExceptionTracker::ProcessManagedCallFrame, just before
// invoking the funclets. Basically, we are using the SP of the caller of the frame containing the funclet
// to determine if we have reached the frame containing the funclet.
EnclosingClauseInfo srcEnclosingClause = (fForGCReporting)?pCurrentTracker->m_EnclosingClauseInfoForGCReporting:pCurrentTracker->m_EnclosingClauseInfo;
sfResult = (StackFrame)(CallerStackFrame(srcEnclosingClause.GetEnclosingClauseCallerSP()));
// Check whether the tracker has called any funclet yet.
if (sfResult.IsNull())
{
continue;
}
// Set the relevant information.
if (pfRealParent != NULL)
{
*pfRealParent = !srcEnclosingClause.EnclosingClauseIsFunclet();
}
if (pParentOffset != NULL)
{
*pParentOffset = srcEnclosingClause.GetEnclosingClauseOffset();
}
if (pParentCallerSP != NULL)
{
*pParentCallerSP = srcEnclosingClause.GetEnclosingClauseCallerSP();
}
break;
}
}
lExit: ;
STRESS_LOG3(LF_EH|LF_GCROOTS, LL_INFO100, "Returning 0x%p as the parent stack frame for %s 0x%p\n",
sfResult.SP, fIsFilterFunclet ? "filter funclet" : "funclet", csfCurrent.SP);
return sfResult;
}
struct RareFindParentStackFrameCallbackState
{
StackFrame m_sfTarget;
StackFrame m_sfParent;
bool m_fFoundTarget;
DWORD m_dwParentOffset;
UINT_PTR m_uParentCallerSP;
};
// This is the callback for the stackwalk to get the parent stack frame for a filter funclet.
//
// static
StackWalkAction ExceptionTracker::RareFindParentStackFrameCallback(CrawlFrame* pCF, LPVOID pData)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
}
CONTRACTL_END;
RareFindParentStackFrameCallbackState* pState = (RareFindParentStackFrameCallbackState*)pData;
// In all cases, we don't care about explicit frame.
if (!pCF->IsFrameless())
{
return SWA_CONTINUE;
}
REGDISPLAY* pRegDisplay = pCF->GetRegisterSet();
StackFrame sfCurrent = StackFrame::FromRegDisplay(pRegDisplay);
// Check if we have reached the target already.
if (!pState->m_fFoundTarget)
{
if (sfCurrent != pState->m_sfTarget)
{
return SWA_CONTINUE;
}
pState->m_fFoundTarget = true;
}
// We hae reached the target, now do the normal frames skipping.
if (!pState->m_sfParent.IsNull())
{
if (pState->m_sfParent.IsMaxVal() || IsUnwoundToTargetParentFrame(pCF, pState->m_sfParent))
{
// We have reached the specified method frame to skip to.
// Now clear the flag and ask again.
pState->m_sfParent.Clear();
}
}
if (pState->m_sfParent.IsNull() && pCF->IsFunclet())
{
pState->m_sfParent = ExceptionTracker::FindParentStackFrameHelper(pCF, NULL, NULL, NULL);
}
// If we still need to skip, then continue the stackwalk.
if (!pState->m_sfParent.IsNull())
{
return SWA_CONTINUE;
}
// At this point, we are done.
pState->m_sfParent = ExceptionTracker::GetStackFrameForParentCheck(pCF);
pState->m_dwParentOffset = pCF->GetRelOffset();
_ASSERTE(pRegDisplay->IsCallerContextValid);
pState->m_uParentCallerSP = GetSP(pRegDisplay->pCallerContext);
return SWA_ABORT;
}
// static
StackFrame ExceptionTracker::RareFindParentStackFrame(CrawlFrame* pCF,
DWORD* pParentOffset,
UINT_PTR* pParentCallerSP)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
PRECONDITION( pCF != NULL );
PRECONDITION( pCF->IsFunclet() );
PRECONDITION( CheckPointer(pParentOffset, NULL_OK) );
PRECONDITION( CheckPointer(pParentCallerSP, NULL_OK) );
}
CONTRACTL_END;
Thread* pThread = pCF->pThread;
RareFindParentStackFrameCallbackState state;
state.m_sfParent.Clear();
state.m_sfTarget = StackFrame::FromRegDisplay(pCF->GetRegisterSet());
state.m_fFoundTarget = false;
PTR_Frame pFrame = pCF->pFrame;
T_CONTEXT ctx;
REGDISPLAY rd;
CopyRegDisplay((const PREGDISPLAY)pCF->GetRegisterSet(), &rd, &ctx);
pThread->StackWalkFramesEx(&rd, &ExceptionTracker::RareFindParentStackFrameCallback, &state, 0, pFrame);
if (pParentOffset != NULL)
{
*pParentOffset = state.m_dwParentOffset;
}
if (pParentCallerSP != NULL)
{
*pParentCallerSP = state.m_uParentCallerSP;
}
return state.m_sfParent;
}
ExceptionTracker::StackRange::StackRange()
{
WRAPPER_NO_CONTRACT;
#ifndef DACCESS_COMPILE
Reset();
#endif // DACCESS_COMPILE
}
ExceptionTracker::EnclosingClauseInfo::EnclosingClauseInfo()
{
LIMITED_METHOD_CONTRACT;
m_fEnclosingClauseIsFunclet = false;
m_dwEnclosingClauseOffset = 0;
m_uEnclosingClauseCallerSP = 0;
}
ExceptionTracker::EnclosingClauseInfo::EnclosingClauseInfo(bool fEnclosingClauseIsFunclet,
DWORD dwEnclosingClauseOffset,
UINT_PTR uEnclosingClauseCallerSP)
{
LIMITED_METHOD_CONTRACT;
m_fEnclosingClauseIsFunclet = fEnclosingClauseIsFunclet;
m_dwEnclosingClauseOffset = dwEnclosingClauseOffset;
m_uEnclosingClauseCallerSP = uEnclosingClauseCallerSP;
}
bool ExceptionTracker::EnclosingClauseInfo::EnclosingClauseIsFunclet()
{
LIMITED_METHOD_CONTRACT;
return m_fEnclosingClauseIsFunclet;
}
DWORD ExceptionTracker::EnclosingClauseInfo::GetEnclosingClauseOffset()
{
LIMITED_METHOD_CONTRACT;
return m_dwEnclosingClauseOffset;
}
UINT_PTR ExceptionTracker::EnclosingClauseInfo::GetEnclosingClauseCallerSP()
{
LIMITED_METHOD_CONTRACT;
return m_uEnclosingClauseCallerSP;
}
void ExceptionTracker::EnclosingClauseInfo::SetEnclosingClauseCallerSP(UINT_PTR callerSP)
{
LIMITED_METHOD_CONTRACT;
m_uEnclosingClauseCallerSP = callerSP;
}
bool ExceptionTracker::EnclosingClauseInfo::operator==(const EnclosingClauseInfo & rhs)
{
LIMITED_METHOD_CONTRACT;
SUPPORTS_DAC;
return ((this->m_fEnclosingClauseIsFunclet == rhs.m_fEnclosingClauseIsFunclet) &&
(this->m_dwEnclosingClauseOffset == rhs.m_dwEnclosingClauseOffset) &&
(this->m_uEnclosingClauseCallerSP == rhs.m_uEnclosingClauseCallerSP));
}
void ExceptionTracker::ReleaseResources()
{
#ifndef DACCESS_COMPILE
if (m_hThrowable)
{
if (!CLRException::IsPreallocatedExceptionHandle(m_hThrowable))
{
DestroyHandle(m_hThrowable);
}
m_hThrowable = NULL;
}
m_StackTraceInfo.FreeStackTrace();
#ifndef FEATURE_PAL
// Clear any held Watson Bucketing details
GetWatsonBucketTracker()->ClearWatsonBucketDetails();
#endif // !FEATURE_PAL
#endif // DACCESS_COMPILE
}
void ExceptionTracker::SetEnclosingClauseInfo(bool fEnclosingClauseIsFunclet,
DWORD dwEnclosingClauseOffset,
UINT_PTR uEnclosingClauseCallerSP)
{
// Preserve the details of the current frame for GC reporting before
// we apply the nested exception logic below.
this->m_EnclosingClauseInfoForGCReporting = EnclosingClauseInfo(fEnclosingClauseIsFunclet,
dwEnclosingClauseOffset,
uEnclosingClauseCallerSP);
if (this->m_pPrevNestedInfo != NULL)
{
PTR_ExceptionTracker pPrevTracker = this->m_pPrevNestedInfo;
CallerStackFrame csfPrevEHClause = pPrevTracker->m_EHClauseInfo.GetCallerStackFrameForEHClause();
// Just propagate the information if this is a nested exception.
if (csfPrevEHClause.SP == uEnclosingClauseCallerSP)
{
this->m_EnclosingClauseInfo = pPrevTracker->m_EnclosingClauseInfo;
return;
}
}
this->m_EnclosingClauseInfo = EnclosingClauseInfo(fEnclosingClauseIsFunclet,
dwEnclosingClauseOffset,
uEnclosingClauseCallerSP);
}
#ifdef DACCESS_COMPILE
void ExceptionTracker::EnumMemoryRegions(CLRDataEnumMemoryFlags flags)
{
// ExInfo is embedded so don't enum 'this'.
OBJECTHANDLE_EnumMemoryRegions(m_hThrowable);
m_ptrs.ExceptionRecord.EnumMem();
m_ptrs.ContextRecord.EnumMem();
}
#endif // DACCESS_COMPILE
#ifndef DACCESS_COMPILE
// This is a thin wrapper around ResetThreadAbortState. Its primarily used to
// instantiate CrawlFrame, when required, for walking the stack on IA64.
//
// The "when required" part are the set of conditions checked prior to the call to
// this method in ExceptionTracker::ProcessOSExceptionNotification (and asserted in
// ResetThreadabortState).
//
// Also, since CrawlFrame ctor is protected, it can only be instantiated by friend
// types (which ExceptionTracker is).
// static
void ExceptionTracker::ResetThreadAbortStatus(PTR_Thread pThread, CrawlFrame *pCf, StackFrame sfCurrentStackFrame)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
PRECONDITION(pThread != NULL);
WIN64_ONLY(PRECONDITION(pCf != NULL);)
WIN64_ONLY(PRECONDITION(!sfCurrentStackFrame.IsNull());)
}
CONTRACTL_END;
if (pThread->IsAbortRequested())
{
ResetThreadAbortState(pThread, pCf, sfCurrentStackFrame);
}
}
#endif //!DACCESS_COMPILE
#endif // _WIN64
|