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
|
//
// 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"
#include "eetwain.h"
#include "dbginterface.h"
#include "gcenv.h"
#define RETURN_ADDR_OFFS 1 // in DWORDS
#include "gcinfo.h"
#ifdef USE_GC_INFO_DECODER
#include "gcinfodecoder.h"
#endif
#define X86_INSTR_W_TEST_ESP 0x4485 // test [esp+N], eax
#define X86_INSTR_TEST_ESP_SIB 0x24
#define X86_INSTR_PUSH_0 0x6A // push 00, entire instruction is 0x6A00
#define X86_INSTR_PUSH_IMM 0x68 // push NNNN,
#define X86_INSTR_W_PUSH_IND_IMM 0x35FF // push [NNNN]
#define X86_INSTR_CALL_REL32 0xE8 // call rel32
#define X86_INSTR_W_CALL_IND_IMM 0x15FF // call [addr32]
#define X86_INSTR_NOP 0x90 // nop
#define X86_INSTR_NOP2 0x9090 // 2-byte nop
#define X86_INSTR_NOP3_1 0x9090 // 1st word of 3-byte nop
#define X86_INSTR_NOP3_3 0x90 // 3rd byte of 3-byte nop
#define X86_INSTR_NOP4 0x90909090 // 4-byte nop
#define X86_INSTR_NOP5_1 0x90909090 // 1st dword of 5-byte nop
#define X86_INSTR_NOP5_5 0x90 // 5th byte of 5-byte nop
#define X86_INSTR_INT3 0xCC // int3
#define X86_INSTR_HLT 0xF4 // hlt
#define X86_INSTR_PUSH_EBP 0x55 // push ebp
#define X86_INSTR_W_MOV_EBP_ESP 0xEC8B // mov ebp, esp
#define X86_INSTR_POP_ECX 0x59 // pop ecx
#define X86_INSTR_RET 0xC2 // ret
#define X86_INSTR_w_LEA_ESP_EBP_BYTE_OFFSET 0x658d // lea esp, [ebp-bOffset]
#define X86_INSTR_w_LEA_ESP_EBP_DWORD_OFFSET 0xa58d // lea esp, [ebp-dwOffset]
#define X86_INSTR_JMP_NEAR_REL32 0xE9 // near jmp rel32
#define X86_INSTR_w_JMP_FAR_IND_IMM 0x25FF // far jmp [addr32]
#ifndef USE_GC_INFO_DECODER
#ifdef _DEBUG
// For dumping of verbose info.
#ifndef DACCESS_COMPILE
static bool trFixContext = false;
#endif
static bool trEnumGCRefs = false;
static bool dspPtr = false; // prints the live ptrs as reported
#endif
// NOTE: enabling compiler optimizations, even for debug builds.
// Comment this out in order to be able to fully debug methods here.
#if defined(_MSC_VER)
#pragma optimize("tg", on)
#endif
__forceinline unsigned decodeUnsigned(PTR_CBYTE& src)
{
LIMITED_METHOD_CONTRACT;
SUPPORTS_DAC;
#ifdef DACCESS_COMPILE
PTR_CBYTE begin = src;
#endif
BYTE byte = *src++;
unsigned value = byte & 0x7f;
while (byte & 0x80)
{
#ifdef DACCESS_COMPILE
// In DAC builds, the target data may be corrupt. Rather than return incorrect data
// and risk wasting time in a potentially long loop, we want to fail early and gracefully.
// The data is encoded with 7 value-bits per byte, and so we may need to read a maximum
// of 5 bytes (7*5=35) to read a full 32-bit integer.
if ((src - begin) > 5)
{
DacError(CORDBG_E_TARGET_INCONSISTENT);
}
#endif
byte = *src++;
value <<= 7;
value += byte & 0x7f;
}
return value;
}
__forceinline int decodeSigned(PTR_CBYTE& src)
{
LIMITED_METHOD_CONTRACT;
SUPPORTS_DAC;
#ifdef DACCESS_COMPILE
PTR_CBYTE begin = src;
#endif
BYTE byte = *src++;
BYTE first = byte;
int value = byte & 0x3f;
while (byte & 0x80)
{
#ifdef DACCESS_COMPILE
// In DAC builds, the target data may be corrupt. Rather than return incorrect data
// and risk wasting time in a potentially long loop, we want to fail early and gracefully.
// The data is encoded with 7 value-bits per byte, and so we may need to read a maximum
// of 5 bytes (7*5=35) to read a full 32-bit integer.
if ((src - begin) > 5)
{
DacError(CORDBG_E_TARGET_INCONSISTENT);
}
#endif
byte = *src++;
value <<= 7;
value += byte & 0x7f;
}
if (first & 0x40)
value = -value;
return value;
}
// Fast versions of the above, with one iteration of the loop unrolled
#define fastDecodeUnsigned(src) (((*(src) & 0x80) == 0) ? (unsigned) (*(src)++) : decodeUnsigned((src)))
#define fastDecodeSigned(src) (((*(src) & 0xC0) == 0) ? (unsigned) (*(src)++) : decodeSigned((src)))
// Fast skipping past encoded integers
#ifndef DACCESS_COMPILE
#define fastSkipUnsigned(src) { while ((*(src)++) & 0x80) { } }
#define fastSkipSigned(src) { while ((*(src)++) & 0x80) { } }
#else
// In DAC builds we want to trade-off a little perf in the common case for reliaiblity against corrupt data.
#define fastSkipUnsigned(src) (decodeUnsigned(src))
#define fastSkipSigned(src) (decodeSigned(src))
#endif
/*****************************************************************************
*
* Decodes the methodInfoPtr and returns the decoded information
* in the hdrInfo struct. The EIP parameter is the PC location
* within the active method.
*/
static size_t crackMethodInfoHdr(PTR_VOID methodInfoPtr,
unsigned curOffset,
hdrInfo * infoPtr)
{
CONTRACTL {
NOTHROW;
GC_NOTRIGGER;
HOST_NOCALLS;
SUPPORTS_DAC;
} CONTRACTL_END;
PTR_CBYTE table = PTR_CBYTE(methodInfoPtr);
#if VERIFY_GC_TABLES
_ASSERTE(*castto(table, unsigned short *)++ == 0xFEEF);
#endif
infoPtr->methodSize = fastDecodeUnsigned(table);
_ASSERTE(curOffset >= 0);
_ASSERTE(curOffset <= infoPtr->methodSize);
/* Decode the InfoHdr */
InfoHdr header;
table = decodeHeader(table, &header);
BOOL hasArgTabOffset = FALSE;
if (header.untrackedCnt == HAS_UNTRACKED)
{
hasArgTabOffset = TRUE;
header.untrackedCnt = fastDecodeUnsigned(table);
}
if (header.varPtrTableSize == HAS_VARPTR)
{
hasArgTabOffset = TRUE;
header.varPtrTableSize = fastDecodeUnsigned(table);
}
if (header.gsCookieOffset == HAS_GS_COOKIE_OFFSET)
{
header.gsCookieOffset = fastDecodeUnsigned(table);
}
if (header.syncStartOffset == HAS_SYNC_OFFSET)
{
header.syncStartOffset = decodeUnsigned(table);
header.syncEndOffset = decodeUnsigned(table);
_ASSERTE(header.syncStartOffset != INVALID_SYNC_OFFSET && header.syncEndOffset != INVALID_SYNC_OFFSET);
_ASSERTE(header.syncStartOffset < header.syncEndOffset);
}
/* Some sanity checks on header */
_ASSERTE( header.prologSize +
(size_t)(header.epilogCount*header.epilogSize) <= infoPtr->methodSize);
_ASSERTE( header.epilogCount == 1 || !header.epilogAtEnd);
_ASSERTE( header.untrackedCnt <= header.argCount+header.frameSize);
_ASSERTE( header.ebpSaved || !(header.ebpFrame || header.doubleAlign));
_ASSERTE(!header.ebpFrame || !header.doubleAlign );
_ASSERTE( header.ebpFrame || !header.security );
_ASSERTE( header.ebpFrame || !header.handlers );
_ASSERTE( header.ebpFrame || !header.localloc );
_ASSERTE( header.ebpFrame || !header.editNcontinue); // <TODO> : Esp frames NYI for EnC</TODO>
/* Initialize the infoPtr struct */
infoPtr->argSize = header.argCount * 4;
infoPtr->ebpFrame = header.ebpFrame;
infoPtr->interruptible = header.interruptible;
infoPtr->prologSize = header.prologSize;
infoPtr->epilogSize = header.epilogSize;
infoPtr->epilogCnt = header.epilogCount;
infoPtr->epilogEnd = header.epilogAtEnd;
infoPtr->untrackedCnt = header.untrackedCnt;
infoPtr->varPtrTableSize = header.varPtrTableSize;
infoPtr->gsCookieOffset = header.gsCookieOffset;
infoPtr->syncStartOffset = header.syncStartOffset;
infoPtr->syncEndOffset = header.syncEndOffset;
infoPtr->doubleAlign = header.doubleAlign;
infoPtr->securityCheck = header.security;
infoPtr->handlers = header.handlers;
infoPtr->localloc = header.localloc;
infoPtr->editNcontinue = header.editNcontinue;
infoPtr->varargs = header.varargs;
infoPtr->profCallbacks = header.profCallbacks;
infoPtr->genericsContext = header.genericsContext;
infoPtr->genericsContextIsMethodDesc = header.genericsContextIsMethodDesc;
infoPtr->isSpeculativeStackWalk = false;
/* Are we within the prolog of the method? */
if (curOffset < infoPtr->prologSize)
{
infoPtr->prologOffs = curOffset;
}
else
{
infoPtr->prologOffs = hdrInfo::NOT_IN_PROLOG;
}
/* Assume we're not in the epilog of the method */
infoPtr->epilogOffs = hdrInfo::NOT_IN_EPILOG;
/* Are we within an epilog of the method? */
if (infoPtr->epilogCnt)
{
unsigned epilogStart;
if (infoPtr->epilogCnt > 1 || !infoPtr->epilogEnd)
{
#if VERIFY_GC_TABLES
_ASSERTE(*castto(table, unsigned short *)++ == 0xFACE);
#endif
epilogStart = 0;
for (unsigned i = 0; i < infoPtr->epilogCnt; i++)
{
epilogStart += fastDecodeUnsigned(table);
if (curOffset > epilogStart &&
curOffset < epilogStart + infoPtr->epilogSize)
{
infoPtr->epilogOffs = curOffset - epilogStart;
}
}
}
else
{
epilogStart = infoPtr->methodSize - infoPtr->epilogSize;
if (curOffset > epilogStart &&
curOffset < epilogStart + infoPtr->epilogSize)
{
infoPtr->epilogOffs = curOffset - epilogStart;
}
}
infoPtr->syncEpilogStart = epilogStart;
}
unsigned argTabOffset = INVALID_ARGTAB_OFFSET;
if (hasArgTabOffset)
{
argTabOffset = fastDecodeUnsigned(table);
}
infoPtr->argTabOffset = argTabOffset;
size_t frameDwordCount = header.frameSize;
/* Set the rawStackSize to the number of bytes that it bumps ESP */
infoPtr->rawStkSize = (UINT)(frameDwordCount * sizeof(size_t));
/* Calculate the callee saves regMask and adjust stackSize to */
/* include the callee saves register spills */
unsigned savedRegs = RM_NONE;
unsigned savedRegsCount = 0;
if (header.ediSaved)
{
savedRegsCount++;
savedRegs |= RM_EDI;
}
if (header.esiSaved)
{
savedRegsCount++;
savedRegs |= RM_ESI;
}
if (header.ebxSaved)
{
savedRegsCount++;
savedRegs |= RM_EBX;
}
if (header.ebpSaved)
{
savedRegsCount++;
savedRegs |= RM_EBP;
}
infoPtr->savedRegMask = (RegMask)savedRegs;
infoPtr->savedRegsCountExclFP = savedRegsCount;
if (header.ebpFrame || header.doubleAlign)
{
_ASSERTE(header.ebpSaved);
infoPtr->savedRegsCountExclFP = savedRegsCount - 1;
}
frameDwordCount += savedRegsCount;
infoPtr->stackSize = (UINT)(frameDwordCount * sizeof(size_t));
_ASSERTE(infoPtr->gsCookieOffset == INVALID_GS_COOKIE_OFFSET ||
(infoPtr->gsCookieOffset < infoPtr->stackSize) &&
((header.gsCookieOffset % sizeof(void*)) == 0));
return table - PTR_CBYTE(methodInfoPtr);
}
/*****************************************************************************/
// We do a "pop eax; jmp eax" to return from a fault or finally handler
const size_t END_FIN_POP_STACK = sizeof(TADDR);
// The offset (in bytes) from EBP for the secutiy object on the stack
inline size_t GetSecurityObjectOffset(hdrInfo * info)
{
SUPPORTS_DAC;
_ASSERTE(info->securityCheck && info->ebpFrame);
unsigned position = info->savedRegsCountExclFP +
1;
return position * sizeof(TADDR);
}
inline
size_t GetLocallocSPOffset(hdrInfo * info)
{
LIMITED_METHOD_CONTRACT;
SUPPORTS_DAC;
_ASSERTE(info->localloc && info->ebpFrame);
unsigned position = info->savedRegsCountExclFP +
info->securityCheck +
1;
return position * sizeof(TADDR);
}
inline
size_t GetParamTypeArgOffset(hdrInfo * info)
{
SUPPORTS_DAC;
_ASSERTE((info->genericsContext || info->handlers) && info->ebpFrame);
unsigned position = info->savedRegsCountExclFP +
info->securityCheck +
info->localloc +
1; // For CORINFO_GENERICS_CTXT_FROM_PARAMTYPEARG
return position * sizeof(TADDR);
}
inline size_t GetStartShadowSPSlotsOffset(hdrInfo * info)
{
WRAPPER_NO_CONTRACT;
SUPPORTS_DAC;
_ASSERTE(info->handlers && info->ebpFrame);
return GetParamTypeArgOffset(info) +
sizeof(TADDR); // Slot for end-of-last-executed-filter
}
/*****************************************************************************
* Returns the start of the hidden slots for the shadowSP for functions
* with exception handlers. There is one slot per nesting level starting
* near Ebp and is zero-terminated after the active slots.
*/
inline
PTR_TADDR GetFirstBaseSPslotPtr(TADDR ebp, hdrInfo * info)
{
LIMITED_METHOD_DAC_CONTRACT;
_ASSERTE(info->handlers && info->ebpFrame);
size_t offsetFromEBP = GetStartShadowSPSlotsOffset(info)
+ sizeof(TADDR); // to get to the *start* of the next slot
return PTR_TADDR(ebp - offsetFromEBP);
}
inline size_t GetEndShadowSPSlotsOffset(hdrInfo * info, unsigned maxHandlerNestingLevel)
{
WRAPPER_NO_CONTRACT;
_ASSERTE(info->handlers && info->ebpFrame);
unsigned numberOfShadowSPSlots = maxHandlerNestingLevel +
1 + // For zero-termination
1; // For a filter (which can be active at the same time as a catch/finally handler
return GetStartShadowSPSlotsOffset(info) +
(numberOfShadowSPSlots * sizeof(TADDR));
}
/*****************************************************************************
* returns the base frame pointer corresponding to the target nesting level.
*/
inline
TADDR GetOutermostBaseFP(TADDR ebp, hdrInfo * info)
{
LIMITED_METHOD_DAC_CONTRACT;
// we are not taking into account double alignment. We are
// safe because the jit currently bails on double alignment if there
// are handles or localalloc
_ASSERTE(!info->doubleAlign);
if (info->localloc)
{
// If the function uses localloc we will fetch the ESP from the localloc
// slot.
PTR_TADDR pLocalloc = PTR_TADDR(ebp - GetLocallocSPOffset(info));
return (*pLocalloc);
}
else
{
// Default, go back all the method's local stack size
return ebp - info->stackSize + sizeof(int);
}
}
/*****************************************************************************
*
* For functions with handlers, checks if it is currently in a handler.
* Either of unwindESP or unwindLevel will specify the target nesting level.
* If unwindLevel is specified, info about the funclet at that nesting level
* will be returned. (Use if you are interested in a specific nesting level.)
* If unwindESP is specified, info for nesting level invoked before the stack
* reached unwindESP will be returned. (Use if you have a specific ESP value
* during stack walking.)
*
* *pBaseSP is set to the base SP (base of the stack on entry to
* the current funclet) corresponding to the target nesting level.
* *pNestLevel is set to the nesting level of the target nesting level (useful
* if unwindESP!=IGNORE_VAL
* *pHasInnerFilter will be set to true (only when unwindESP!=IGNORE_VAL) if a filter
* is currently active, but the target nesting level is an outer nesting level.
* *pHadInnerFilter - was the last use of the frame to execute a filter.
* This mainly affects GC lifetime reporting.
*/
enum FrameType
{
FR_NORMAL, // Normal method frame - no exceptions currently active
FR_FILTER, // Frame-let of a filter
FR_HANDLER, // Frame-let of a callable catch/fault/finally
FR_INVALID, // Invalid frame (for speculative stackwalks)
};
enum { IGNORE_VAL = -1 };
FrameType GetHandlerFrameInfo(hdrInfo * info,
TADDR frameEBP,
TADDR unwindESP,
DWORD unwindLevel,
TADDR * pBaseSP = NULL, /* OUT */
DWORD * pNestLevel = NULL, /* OUT */
bool * pHasInnerFilter = NULL, /* OUT */
bool * pHadInnerFilter = NULL) /* OUT */
{
CONTRACTL {
NOTHROW;
GC_NOTRIGGER;
HOST_NOCALLS;
SUPPORTS_DAC;
} CONTRACTL_END;
_ASSERTE(info->ebpFrame && info->handlers);
// One and only one of them should be IGNORE_VAL
_ASSERTE((unwindESP == (TADDR) IGNORE_VAL) !=
(unwindLevel == (DWORD) IGNORE_VAL));
_ASSERTE(pHasInnerFilter == NULL || unwindESP != (TADDR) IGNORE_VAL);
// Many of the conditions that we'd like to assert cannot be asserted in the case that we're
// in the middle of a stackwalk seeded by a profiler, since such seeds can't be trusted
// (profilers are external, untrusted sources). So during profiler walks, we test the condition
// and throw an exception if it's not met. Otherwise, we just assert the condition.
#define FAIL_IF_SPECULATIVE_WALK(condition) \
if (info->isSpeculativeStackWalk) \
{ \
if (!(condition)) \
{ \
return FR_INVALID; \
} \
} \
else \
{ \
_ASSERTE(condition); \
}
PTR_TADDR pFirstBaseSPslot = GetFirstBaseSPslotPtr(frameEBP, info);
TADDR baseSP = GetOutermostBaseFP(frameEBP, info);
bool nonLocalHandlers = false; // Are the funclets invoked by EE (instead of managed code itself)
bool hasInnerFilter = false;
bool hadInnerFilter = false;
/* Get the last non-zero slot >= unwindESP, or lvl<unwindLevel.
Also do some sanity checks */
// The shadow slots contain the SP of the nested EH clauses currently active on the stack.
// The slots grow towards lower address on the stack and is terminted by a NULL entry.
// Since each subsequent slot contains the SP of a more nested EH clause, the contents of the slots are
// expected to be in decreasing order.
size_t lvl;
PTR_TADDR pSlot;
for(lvl = 0, pSlot = pFirstBaseSPslot;
*pSlot && lvl < unwindLevel;
pSlot--, lvl++)
{
// Filters cant have inner funclets
FAIL_IF_SPECULATIVE_WALK(!(baseSP & ICodeManager::SHADOW_SP_IN_FILTER));
TADDR curSlotVal = *pSlot;
// The shadowSPs have to be less unless the stack has been unwound.
FAIL_IF_SPECULATIVE_WALK(baseSP > curSlotVal ||
(baseSP == curSlotVal && pSlot == pFirstBaseSPslot));
if (curSlotVal == LCL_FINALLY_MARK)
{
// Locally called finally
baseSP -= sizeof(TADDR);
}
else
{
// Is this a funclet we unwound before (can only happen with filters) ?
// If unwindESP is specified, normally we expect it to be the last entry in the shadow slot array.
// Or, if there is a filter, we expect unwindESP to be the second last entry. However, this may
// not be the case in DAC builds. For example, the user can use .cxr in an EH clause to set a
// CONTEXT captured in the try clause. In this case, unwindESP will be the ESP of the parent
// function, but the shadow slot array will contain the SP of the EH clause, which is closer to
// the leaf than the parent method.
if (unwindESP != (TADDR) IGNORE_VAL &&
unwindESP > END_FIN_POP_STACK +
(curSlotVal & ~ICodeManager::SHADOW_SP_BITS))
{
// In non-DAC builds, the only time unwindESP is closer to the root than entries in the shadow
// slot array is when the last entry in the array is for a filter. Also, filters can't have
// nested handlers.
if ((pSlot[0] & ICodeManager::SHADOW_SP_IN_FILTER) &&
(pSlot[-1] == 0) &&
!(baseSP & ICodeManager::SHADOW_SP_IN_FILTER))
{
if (pSlot[0] & ICodeManager::SHADOW_SP_FILTER_DONE)
hadInnerFilter = true;
else
hasInnerFilter = true;
break;
}
else
{
#if defined(DACCESS_COMPILE)
// In DAC builds, this could happen. We just need to bail out of this loop early.
break;
#else // !DACCESS_COMPILE
// In non-DAC builds, this is an error.
FAIL_IF_SPECULATIVE_WALK(FALSE);
#endif // DACCESS_COMPILE
}
}
nonLocalHandlers = true;
baseSP = curSlotVal;
}
}
if (unwindESP != (TADDR) IGNORE_VAL)
{
FAIL_IF_SPECULATIVE_WALK(baseSP >= unwindESP ||
baseSP == unwindESP - sizeof(TADDR)); // About to locally call a finally
if (baseSP < unwindESP) // About to locally call a finally
baseSP = unwindESP;
}
else
{
FAIL_IF_SPECULATIVE_WALK(lvl == unwindLevel); // unwindLevel must be currently active on stack
}
if (pBaseSP)
*pBaseSP = baseSP & ~ICodeManager::SHADOW_SP_BITS;
if (pNestLevel)
{
*pNestLevel = (DWORD)lvl;
}
if (pHasInnerFilter)
*pHasInnerFilter = hasInnerFilter;
if (pHadInnerFilter)
*pHadInnerFilter = hadInnerFilter;
if (baseSP & ICodeManager::SHADOW_SP_IN_FILTER)
{
FAIL_IF_SPECULATIVE_WALK(!hasInnerFilter); // nested filters not allowed
return FR_FILTER;
}
else if (nonLocalHandlers)
{
return FR_HANDLER;
}
else
{
return FR_NORMAL;
}
#undef FAIL_IF_SPECULATIVE_WALK
}
// Returns the number of bytes at the beginning of the stack frame that shouldn't be
// modified by an EnC. This is everything except the space for locals and temporaries.
inline size_t GetSizeOfFrameHeaderForEnC(hdrInfo * info)
{
WRAPPER_NO_CONTRACT;
// See comment above Compiler::lvaAssignFrameOffsets() in src\jit\il\lclVars.cpp
// for frame layout
// EnC supports increasing the maximum handler nesting level by always
// assuming that the max is MAX_EnC_HANDLER_NESTING_LEVEL. Methods with
// a higher max cannot be updated by EnC
// Take the offset (from EBP) of the last slot of the header, plus one for the EBP slot itself
// to get the total size of the header.
return sizeof(TADDR) +
GetEndShadowSPSlotsOffset(info, MAX_EnC_HANDLER_NESTING_LEVEL);
}
#endif // !USE_GC_INFO_DECODER
#ifndef DACCESS_COMPILE
/*****************************************************************************
*
* Setup context to enter an exception handler (a 'catch' block).
* This is the last chance for the runtime support to do fixups in
* the context before execution continues inside a filter, catch handler,
* or finally.
*/
void EECodeManager::FixContext( ContextType ctxType,
EHContext *ctx,
EECodeInfo *pCodeInfo,
DWORD dwRelOffset,
DWORD nestingLevel,
OBJECTREF thrownObject,
CodeManState *pState,
size_t ** ppShadowSP,
size_t ** ppEndRegion)
{
CONTRACTL {
NOTHROW;
GC_NOTRIGGER;
} CONTRACTL_END;
_ASSERTE((ctxType == FINALLY_CONTEXT) == (thrownObject == NULL));
#ifdef _TARGET_X86_
_ASSERTE(sizeof(CodeManStateBuf) <= sizeof(pState->stateBuf));
CodeManStateBuf * stateBuf = (CodeManStateBuf*)pState->stateBuf;
/* Extract the necessary information from the info block header */
stateBuf->hdrInfoSize = (DWORD)crackMethodInfoHdr(pCodeInfo->GetGCInfo(),
dwRelOffset,
&stateBuf->hdrInfoBody);
pState->dwIsSet = 1;
#ifdef _DEBUG
if (trFixContext) {
printf("FixContext [%s][%s] for %s.%s: ",
stateBuf->hdrInfoBody.ebpFrame?"ebp":" ",
stateBuf->hdrInfoBody.interruptible?"int":" ",
"UnknownClass","UnknownMethod");
fflush(stdout);
}
#endif
/* make sure that we have an ebp stack frame */
_ASSERTE(stateBuf->hdrInfoBody.ebpFrame);
_ASSERTE(stateBuf->hdrInfoBody.handlers); // <TODO>@TODO : This will alway be set. Remove it</TODO>
TADDR baseSP;
GetHandlerFrameInfo(&stateBuf->hdrInfoBody, ctx->Ebp,
ctxType == FILTER_CONTEXT ? ctx->Esp : IGNORE_VAL,
ctxType == FILTER_CONTEXT ? (DWORD) IGNORE_VAL : nestingLevel,
&baseSP,
&nestingLevel);
_ASSERTE((size_t)ctx->Ebp >= baseSP);
_ASSERTE(baseSP >= (size_t)ctx->Esp);
ctx->Esp = (DWORD)baseSP;
// EE will write Esp to **pShadowSP before jumping to handler
PTR_TADDR pBaseSPslots =
GetFirstBaseSPslotPtr(ctx->Ebp, &stateBuf->hdrInfoBody);
*ppShadowSP = (size_t *)&pBaseSPslots[-(int) nestingLevel ];
pBaseSPslots[-(int)(nestingLevel+1)] = 0; // Zero out the next slot
// EE will write the end offset of the filter
if (ctxType == FILTER_CONTEXT)
*ppEndRegion = (size_t *)pBaseSPslots + 1;
/* This is just a simple assigment of throwObject to ctx->Eax,
just pretend the cast goo isn't there.
*/
*((OBJECTREF*)&(ctx->Eax)) = thrownObject;
#else // !_TARGET_X86_
_ASSERTE(!"@NYI - EECodeManager::FixContext (EETwain.cpp)");
#endif // _TARGET_X86_
}
/*****************************************************************************/
bool VarIsInReg(ICorDebugInfo::VarLoc varLoc)
{
LIMITED_METHOD_CONTRACT;
switch(varLoc.vlType)
{
case ICorDebugInfo::VLT_REG:
case ICorDebugInfo::VLT_REG_REG:
case ICorDebugInfo::VLT_REG_STK:
return true;
default:
return false;
}
}
#ifdef EnC_SUPPORTED
/*****************************************************************************
* Last chance for the runtime support to do fixups in the context
* before execution continues inside an EnC updated function.
* It also adjusts ESP and munges on the stack. So the caller has to make
* sure that that stack region isnt needed (by doing a localloc)
* Also, if this returns EnC_FAIL, we should not have munged the
* context ie. transcated commit
* The plan of attack is:
* 1) Error checking up front. If we get through here, everything
* else should work
* 2) Get all the info about current variables, registers, etc
* 3) zero out the stack frame - this'll initialize _all_ variables
* 4) Put the variables from step 3 into their new locations.
*
* Note that while we use the ShuffleVariablesGet/Set methods, they don't
* have any info/logic that's internal to the runtime: another codemanger
* could easily duplicate what they do, which is why we're calling into them.
*/
HRESULT EECodeManager::FixContextForEnC(PCONTEXT pCtx,
EECodeInfo * pOldCodeInfo,
const ICorDebugInfo::NativeVarInfo * oldMethodVars,
SIZE_T oldMethodVarsCount,
EECodeInfo * pNewCodeInfo,
const ICorDebugInfo::NativeVarInfo * newMethodVars,
SIZE_T newMethodVarsCount)
{
CONTRACTL {
DISABLED(NOTHROW);
DISABLED(GC_NOTRIGGER);
} CONTRACTL_END;
HRESULT hr = S_OK;
// Grab a copy of the context before the EnC update.
T_CONTEXT oldCtx = *pCtx;
#if defined(_TARGET_X86_)
LOG((LF_CORDB, LL_INFO100, "EECM::FixContextForEnC\n"));
/* Extract the necessary information from the info block header */
hdrInfo oldInfo, newInfo;
crackMethodInfoHdr(pOldCodeInfo->GetGCInfo(),
pOldCodeInfo->GetRelOffset(),
&oldInfo);
crackMethodInfoHdr(pNewCodeInfo->GetGCInfo(),
pNewCodeInfo->GetRelOffset(),
&newInfo);
//1) Error checking up front. If we get through here, everything
// else should work
if (!oldInfo.editNcontinue || !newInfo.editNcontinue) {
LOG((LF_ENC, LL_INFO100, "**Error** EECM::FixContextForEnC EnC_INFOLESS_METHOD\n"));
return CORDBG_E_ENC_INFOLESS_METHOD;
}
if (!oldInfo.ebpFrame || !newInfo.ebpFrame) {
LOG((LF_ENC, LL_INFO100, "**Error** EECM::FixContextForEnC Esp frames NYI\n"));
return E_FAIL; // Esp frames NYI
}
if (pCtx->Esp != pCtx->Ebp - oldInfo.stackSize + sizeof(DWORD)) {
LOG((LF_ENC, LL_INFO100, "**Error** EECM::FixContextForEnC stack should be empty\n"));
return E_FAIL; // stack should be empty - <TODO> @TODO : Barring localloc</TODO>
}
if (oldInfo.handlers)
{
bool hasInnerFilter;
TADDR baseSP;
FrameType frameType = GetHandlerFrameInfo(&oldInfo, pCtx->Ebp,
pCtx->Esp, IGNORE_VAL,
&baseSP, NULL, &hasInnerFilter);
_ASSERTE(frameType != FR_INVALID);
_ASSERTE(!hasInnerFilter); // FixContextForEnC() is called for bottommost funclet
// If the method is in a fuclet, and if the framesize grows, we are in trouble.
if (frameType != FR_NORMAL)
{
/* <TODO> @TODO : What if the new method offset is in a fuclet,
and the old is not, or the nesting level changed, etc </TODO> */
if (oldInfo.stackSize != newInfo.stackSize) {
LOG((LF_ENC, LL_INFO100, "**Error** EECM::FixContextForEnC stack size mismatch\n"));
return CORDBG_E_ENC_IN_FUNCLET;
}
}
}
/* @TODO: Check if we have grown out of space for locals, in the face of localloc */
_ASSERTE(!oldInfo.localloc && !newInfo.localloc);
// Always reserve space for the securityCheck slot
_ASSERTE(oldInfo.securityCheck && newInfo.securityCheck);
// @TODO: If nesting level grows above the MAX_EnC_HANDLER_NESTING_LEVEL,
// we should return EnC_NESTED_HANLDERS
_ASSERTE(oldInfo.handlers && newInfo.handlers);
LOG((LF_ENC, LL_INFO100, "EECM::FixContextForEnC: Checks out\n"));
#elif defined(_TARGET_AMD64_)
// Strategy for zeroing out the frame on x64:
//
// The stack frame looks like this (stack grows up)
//
// =======================================
// <--- RSP == RBP (invariant: localalloc disallowed before remap)
// Arguments for next call (if there is one)
// PSPSym (optional)
// JIT temporaries (if any)
// Security object (if any)
// Local variables (if any)
// ---------------------------------------
// Frame header (stuff we must preserve, such as bool for synchronized
// methods, saved RBP, etc.)
// Return address (also included in frame header)
// ---------------------------------------
// Arguments for this frame (that's getting remapped). Will naturally be preserved
// since fixed-frame size doesn't include this.
// =======================================
//
// Goal: Zero out everything AFTER (above) frame header.
//
// How do we find this stuff?
//
// EECodeInfo::GetFixedStackSize() gives us the full size from the top ("Arguments
// for next call") all the way down to and including Return Address.
//
// GetSizeOfEditAndContinuePreservedArea() gives us the size in bytes of the
// frame header at the bottom.
//
// So we start at RSP, and zero out:
// GetFixedStackSize() - GetSizeOfEditAndContinuePreservedArea() bytes.
//
// We'll need to restore PSPSym; location gotten from GCInfo.
// We'll need to copy security object; location gotten from GCInfo.
// GCInfo for old method
GcInfoDecoder oldGcDecoder(
dac_cast<PTR_CBYTE>(pOldCodeInfo->GetGCInfo()),
GcInfoDecoderFlags(DECODE_SECURITY_OBJECT | DECODE_PSP_SYM | DECODE_EDIT_AND_CONTINUE),
0 // Instruction offset (not needed)
);
// GCInfo for new method
GcInfoDecoder newGcDecoder(
dac_cast<PTR_CBYTE>(pNewCodeInfo->GetGCInfo()),
GcInfoDecoderFlags(DECODE_SECURITY_OBJECT | DECODE_PSP_SYM | DECODE_EDIT_AND_CONTINUE),
0 // Instruction offset (not needed)
);
UINT32 oldSizeOfPreservedArea = oldGcDecoder.GetSizeOfEditAndContinuePreservedArea();
UINT32 newSizeOfPreservedArea = newGcDecoder.GetSizeOfEditAndContinuePreservedArea();
// This ensures the JIT generated EnC compliant code.
if ((oldSizeOfPreservedArea == NO_SIZE_OF_EDIT_AND_CONTINUE_PRESERVED_AREA) ||
(newSizeOfPreservedArea == NO_SIZE_OF_EDIT_AND_CONTINUE_PRESERVED_AREA))
{
_ASSERTE(!"FixContextForEnC called on a non-EnC-compliant method frame");
return CORDBG_E_ENC_INFOLESS_METHOD;
}
// JIT is required to emit frame register for EnC-compliant code
_ASSERTE(pOldCodeInfo->HasFrameRegister());
_ASSERTE(pNewCodeInfo->HasFrameRegister());
TADDR oldStackBase = GetSP(&oldCtx);
// This verifies no localallocs were used in the old method. (RBP == RSP for
// EnC-compliant x64 code.)
if (oldStackBase != oldCtx.Rbp)
return E_FAIL;
// EnC remap inside handlers is not supported
if (pOldCodeInfo->IsFunclet() || pNewCodeInfo->IsFunclet())
return CORDBG_E_ENC_IN_FUNCLET;
if (oldSizeOfPreservedArea != newSizeOfPreservedArea)
{
_ASSERTE(!"FixContextForEnC called with method whose frame header size changed from old to new version.");
return E_FAIL;
}
// Note: we cannot assert anything about the relationship between oldFixedStackSize
// and newFixedStackSize. It's possible the edited frame grows (new locals) or
// shrinks (less temporaries).
DWORD oldFixedStackSize = pOldCodeInfo->GetFixedStackSize();
DWORD newFixedStackSize = pNewCodeInfo->GetFixedStackSize();
TADDR callerSP = oldStackBase + oldFixedStackSize;
// If the old code saved a security object, store the object's reference now.
OBJECTREF securityObject = NULL;
INT32 nOldSecurityObjectStackSlot = oldGcDecoder.GetSecurityObjectStackSlot();
if (nOldSecurityObjectStackSlot != NO_SECURITY_OBJECT)
{
securityObject = ObjectToOBJECTREF(*PTR_PTR_Object(callerSP + nOldSecurityObjectStackSlot));
}
#ifdef _DEBUG
// If the old method has a PSPSym, then its value should == FP
INT32 nOldPspSymStackSlot = oldGcDecoder.GetPSPSymStackSlot();
if (nOldPspSymStackSlot != NO_PSP_SYM)
{
// Read the PSP.
TADDR oldPSP = *PTR_TADDR(oldStackBase + nOldPspSymStackSlot);
// Now we're set up to assert that PSPSym's value == FP
_ASSERTE(oldPSP == GetFP(&oldCtx));
}
#endif // _DEBUG
#else
PORTABILITY_ASSERT("Edit-and-continue not enabled on this platform.");
#endif
// 2) Get all the info about current variables, registers, etc
const ICorDebugInfo::NativeVarInfo * pOldVar;
// sorted by varNumber
ICorDebugInfo::NativeVarInfo * oldMethodVarsSorted = NULL;
ICorDebugInfo::NativeVarInfo * oldMethodVarsSortedBase = NULL;
ICorDebugInfo::NativeVarInfo *newMethodVarsSorted = NULL;
ICorDebugInfo::NativeVarInfo *newMethodVarsSortedBase = NULL;
SIZE_T *rgVal1 = NULL;
SIZE_T *rgVal2 = NULL;
{
SIZE_T local;
// We'll need to sort the old native var info by variable number, since the
// order of them isn't necc. the same. We'll use the number as the key.
// We will assume we may have hidden arguments (which have negative values as the index)
unsigned oldNumVars = unsigned(-ICorDebugInfo::UNKNOWN_ILNUM);
for (pOldVar = oldMethodVars, local = 0;
local < oldMethodVarsCount;
local++, pOldVar++)
{
DWORD varNumber = pOldVar->varNumber;
if (signed(varNumber) >= 0)
{
// This is an explicit (not special) var, so add its varNumber + 1 to our
// max count ("+1" because varNumber is zero-based).
oldNumVars = max(oldNumVars, unsigned(-ICorDebugInfo::UNKNOWN_ILNUM) + varNumber + 1);
}
}
oldMethodVarsSortedBase = new (nothrow) ICorDebugInfo::NativeVarInfo[oldNumVars];
if (!oldMethodVarsSortedBase)
{
hr = E_FAIL;
goto ErrExit;
}
oldMethodVarsSorted = oldMethodVarsSortedBase + (-ICorDebugInfo::UNKNOWN_ILNUM);
memset((void *)oldMethodVarsSortedBase, 0, oldNumVars * sizeof(ICorDebugInfo::NativeVarInfo));
for (local = 0; local < oldNumVars;local++)
oldMethodVarsSortedBase[local].loc.vlType = ICorDebugInfo::VLT_INVALID;
BYTE **rgVCs = NULL;
DWORD oldMethodOffset = pOldCodeInfo->GetRelOffset();
for (pOldVar = oldMethodVars, local = 0;
local < oldMethodVarsCount;
local++, pOldVar++)
{
DWORD varNumber = pOldVar->varNumber;
_ASSERTE(varNumber + unsigned(-ICorDebugInfo::UNKNOWN_ILNUM) < oldNumVars);
// Only care about old local variables alive at oldMethodOffset
if (pOldVar->startOffset <= oldMethodOffset &&
pOldVar->endOffset > oldMethodOffset)
{
oldMethodVarsSorted[varNumber] = *pOldVar;
}
}
// 3) Next sort the new var info by varNumber. We want to do this here, since
// we're allocating memory (which may fail) - do this before going to step 2
// First, count the new vars the same way we did the old vars above.
const ICorDebugInfo::NativeVarInfo * pNewVar;
unsigned newNumVars = unsigned(-ICorDebugInfo::UNKNOWN_ILNUM);
for (pNewVar = newMethodVars, local = 0;
local < newMethodVarsCount;
local++, pNewVar++)
{
DWORD varNumber = pNewVar->varNumber;
if (signed(varNumber) >= 0)
{
// This is an explicit (not special) var, so add its varNumber + 1 to our
// max count ("+1" because varNumber is zero-based).
newNumVars = max(newNumVars, unsigned(-ICorDebugInfo::UNKNOWN_ILNUM) + varNumber + 1);
}
}
// sorted by varNumber
newMethodVarsSortedBase = new (nothrow) ICorDebugInfo::NativeVarInfo[newNumVars];
if (!newMethodVarsSortedBase)
{
hr = E_FAIL;
goto ErrExit;
}
newMethodVarsSorted = newMethodVarsSortedBase + (-ICorDebugInfo::UNKNOWN_ILNUM);
memset(newMethodVarsSortedBase, 0, newNumVars * sizeof(ICorDebugInfo::NativeVarInfo));
for (local = 0; local < newNumVars;local++)
newMethodVarsSortedBase[local].loc.vlType = ICorDebugInfo::VLT_INVALID;
DWORD newMethodOffset = pNewCodeInfo->GetRelOffset();
for (pNewVar = newMethodVars, local = 0;
local < newMethodVarsCount;
local++, pNewVar++)
{
DWORD varNumber = pNewVar->varNumber;
_ASSERTE(varNumber + unsigned(-ICorDebugInfo::UNKNOWN_ILNUM) < newNumVars);
// Only care about new local variables alive at newMethodOffset
if (pNewVar->startOffset <= newMethodOffset &&
pNewVar->endOffset > newMethodOffset)
{
newMethodVarsSorted[varNumber] = *pNewVar;
}
}
_ASSERTE(newNumVars >= oldNumVars ||
!"Not allowed to reduce the number of locals between versions!");
LOG((LF_ENC, LL_INFO100, "EECM::FixContextForEnC: gathered info!\n"));
rgVal1 = new (nothrow) SIZE_T[newNumVars];
if (rgVal1 == NULL)
{
hr = E_FAIL;
goto ErrExit;
}
rgVal2 = new (nothrow) SIZE_T[newNumVars];
if (rgVal2 == NULL)
{
hr = E_FAIL;
goto ErrExit;
}
// 4) Next we'll zero them out, so any variables that aren't in scope
// in the old method, but are in scope in the new, will have the
// default, zero, value.
memset(rgVal1, 0, sizeof(SIZE_T) * newNumVars);
memset(rgVal2, 0, sizeof(SIZE_T) * newNumVars);
unsigned varsToGet = (oldNumVars > newNumVars) ? newNumVars
: oldNumVars;
// 2) Get all the info about current variables, registers, etc.
hr = g_pDebugInterface->GetVariablesFromOffset(pOldCodeInfo->GetMethodDesc(),
varsToGet,
oldMethodVarsSortedBase,
oldMethodOffset,
&oldCtx,
rgVal1,
rgVal2,
newNumVars,
&rgVCs);
if (FAILED(hr))
{
goto ErrExit;
}
LOG((LF_ENC, LL_INFO100, "EECM::FixContextForEnC: got vars!\n"));
/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*
* IMPORTANT : Once we start munging on the context, we cannot return
* EnC_FAIL, as this should be a transacted commit,
**=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*/
#if defined(_TARGET_X86_)
// Zero out all the registers as some may hold new variables.
pCtx->Eax = pCtx->Ecx = pCtx->Edx = pCtx->Ebx =
pCtx->Esi = pCtx->Edi = 0;
// 3) zero out the stack frame - this'll initialize _all_ variables
/*-------------------------------------------------------------------------
* Adjust the stack height
*/
pCtx->Esp -= (newInfo.stackSize - oldInfo.stackSize);
// Zero-init the local and tempory section of new stack frame being careful to avoid
// touching anything in the frame header.
// This is necessary to ensure that any JIT temporaries in the old version can't be mistaken
// for ObjRefs now.
size_t frameHeaderSize = GetSizeOfFrameHeaderForEnC( &newInfo );
_ASSERTE( frameHeaderSize <= oldInfo.stackSize );
_ASSERTE( GetSizeOfFrameHeaderForEnC( &oldInfo ) == frameHeaderSize );
#elif defined(_TARGET_AMD64_)
// Next few statements zero out all registers that may end up holding new variables.
// volatile int registers (JIT may use these to enregister variables)
pCtx->Rax = pCtx->Rcx = pCtx->Rdx = pCtx->R8 = pCtx->R9 = pCtx->R10 = pCtx->R11 = 0;
// volatile float registers
pCtx->Xmm1.High = pCtx->Xmm1.Low = 0;
pCtx->Xmm2.High = pCtx->Xmm2.Low = 0;
pCtx->Xmm3.High = pCtx->Xmm3.Low = 0;
pCtx->Xmm4.High = pCtx->Xmm4.Low = 0;
pCtx->Xmm5.High = pCtx->Xmm5.Low = 0;
// Any saved nonvolatile registers should also be zeroed out, but there are none
// in EnC-compliant x64 code. Yes, you read that right. Registers like RDI, RSI,
// RBX, etc., which are often saved in the prolog of non-EnC code are NOT saved in
// EnC code. EnC code instead just agrees never to use those registers so they
// remain pristine for the caller (except RBP, which is considered part of the frame
// header, and is thus not zeroed out by us).
// 3) zero out the stack frame - this'll initialize _all_ variables
/*-------------------------------------------------------------------------
* Adjust the stack height
*/
TADDR newStackBase = callerSP - newFixedStackSize;
SetSP(pCtx, newStackBase);
// We want to zero-out everything pushed after the frame header. This way we'll zero
// out locals (both old & new) and temporaries. This is necessary to ensure that any
// JIT temporaries in the old version can't be mistaken for ObjRefs now. (I am told
// this last point is less of an issue on x64 as it is on x86, but zeroing out the
// temporaries is still the cleanest, most robust way to go.)
size_t frameHeaderSize = newSizeOfPreservedArea;
_ASSERTE(frameHeaderSize <= oldFixedStackSize);
_ASSERTE(frameHeaderSize <= newFixedStackSize);
// For EnC-compliant x64 code, Rbp == Rsp. Since Rsp changed above, update Rbp now
pCtx->Rbp = newStackBase;
#else // !X86, !AMD64
PORTABILITY_ASSERT("Edit-and-continue not enabled on this platform.");
#endif
// Perform some debug-only sanity checks on stack variables. Some checks are
// performed differently between X86/AMD64.
#ifdef _DEBUG
for( unsigned i = 0; i < newNumVars; i++ )
{
// Make sure that stack variables existing in both old and new methods did not
// move. This matters if the address of a local is used in the remapped method.
// For example:
//
// static unsafe void Main(string[] args)
// {
// int x;
// int* p = &x;
// <- Edit made here - cannot move address of x
// *p = 5;
// }
//
if ((i + unsigned(-ICorDebugInfo::UNKNOWN_ILNUM) < oldNumVars) && // Does variable exist in old method?
(oldMethodVarsSorted[i].loc.vlType == ICorDebugInfo::VLT_STK) && // Is the variable on the stack?
(newMethodVarsSorted[i].loc.vlType == ICorDebugInfo::VLT_STK))
{
SIZE_T * pOldVarStackLocation = NativeVarStackAddr(oldMethodVarsSorted[i].loc, &oldCtx);
SIZE_T * pNewVarStackLocation = NativeVarStackAddr(newMethodVarsSorted[i].loc, pCtx);
_ASSERTE(pOldVarStackLocation == pNewVarStackLocation);
}
// Sanity-check that the range we're clearing contains all of the stack variables
#if defined(_TARGET_X86_)
const ICorDebugInfo::VarLoc &varLoc = newMethodVarsSortedBase[i].loc;
if( varLoc.vlType == ICorDebugInfo::VLT_STK )
{
// This is an EBP frame, all stack variables should be EBP relative
_ASSERTE( varLoc.vlStk.vlsBaseReg == ICorDebugInfo::REGNUM_EBP );
// Generic special args may show up as locals with positive offset from EBP, so skip them
if( varLoc.vlStk.vlsOffset <= 0 )
{
// Normal locals must occur after the header on the stack
_ASSERTE( unsigned(-varLoc.vlStk.vlsOffset) >= frameHeaderSize );
// Value must occur before the top of the stack
_ASSERTE( unsigned(-varLoc.vlStk.vlsOffset) < newInfo.stackSize );
}
// Ideally we'd like to verify that the stack locals (if any) start at exactly the end
// of the header. However, we can't easily determine the size of value classes here,
// and so (since the stack grows towards 0) can't easily determine where the end of
// the local lies.
}
#elif defined (_TARGET_AMD64_)
switch(newMethodVarsSortedBase[i].loc.vlType)
{
default:
// No validation here for non-stack locals
break;
case ICorDebugInfo::VLT_STK_BYREF:
{
// For byrefs, verify that the ptr will be zeroed out
SIZE_T regOffs = GetRegOffsInCONTEXT(newMethodVarsSortedBase[i].loc.vlStk.vlsBaseReg);
TADDR baseReg = *(TADDR *)(regOffs + (BYTE*)pCtx);
TADDR addrOfPtr = baseReg + newMethodVarsSortedBase[i].loc.vlStk.vlsOffset;
_ASSERTE(
// The ref must exist in the portion we'll zero-out
(
(newStackBase <= addrOfPtr) &&
(addrOfPtr < newStackBase + (newFixedStackSize - frameHeaderSize))
) ||
// OR in the caller's frame (for parameters)
(addrOfPtr >= newStackBase + newFixedStackSize));
// Deliberately fall through, so that we also verify that the value that the ptr
// points to will be zeroed out
// ...
}
case ICorDebugInfo::VLT_STK:
case ICorDebugInfo::VLT_STK2:
case ICorDebugInfo::VLT_REG_STK:
case ICorDebugInfo::VLT_STK_REG:
SIZE_T * pVarStackLocation = NativeVarStackAddr(newMethodVarsSortedBase[i].loc, pCtx);
_ASSERTE (pVarStackLocation != NULL);
_ASSERTE(
// The value must exist in the portion we'll zero-out
(
(newStackBase <= (TADDR) pVarStackLocation) &&
((TADDR) pVarStackLocation < newStackBase + (newFixedStackSize - frameHeaderSize))
) ||
// OR in the caller's frame (for parameters)
((TADDR) pVarStackLocation >= newStackBase + newFixedStackSize));
break;
}
#else // !X86, !X64
PORTABILITY_ASSERT("Edit-and-continue not enabled on this platform.");
#endif
}
#endif // _DEBUG
// Clear the local and temporary stack space
#if defined (_TARGET_X86_)
memset((void*)(size_t)(pCtx->Esp), 0, newInfo.stackSize - frameHeaderSize );
#elif defined (_TARGET_AMD64_)
memset((void*)newStackBase, 0, newFixedStackSize - frameHeaderSize);
// On AMD64, after zeroing out the stack, restore the security object and PSPSym...
// There is no relationship we can guarantee between the old code having a security
// object and the new code having a security object. If the new code does have a
// security object, then we copy over the old security object's reference if there
// was one (else we copy over NULL, which is fine). If the new code doesn't have a
// security object, we do nothing.
INT32 nNewSecurityObjectStackSlot = newGcDecoder.GetSecurityObjectStackSlot();
if (nNewSecurityObjectStackSlot != NO_SECURITY_OBJECT)
{
*PTR_PTR_Object(callerSP + nNewSecurityObjectStackSlot) = OBJECTREFToObject(securityObject);
}
// Restore PSPSym for the new function. Its value should be set to our new FP. But
// first, we gotta find PSPSym's location on the stack
INT32 nNewPspSymStackSlot = newGcDecoder.GetPSPSymStackSlot();
if (nNewPspSymStackSlot != NO_PSP_SYM)
{
*PTR_TADDR(newStackBase + nNewPspSymStackSlot) = GetFP(pCtx);
}
#else // !X86, !X64
PORTABILITY_ASSERT("Edit-and-continue not enabled on this platform.");
#endif
// 4) Put the variables from step 3 into their new locations.
LOG((LF_ENC, LL_INFO100, "EECM::FixContextForEnC: set vars!\n"));
// Move the old variables into their new places.
hr = g_pDebugInterface->SetVariablesAtOffset(pNewCodeInfo->GetMethodDesc(),
newNumVars,
newMethodVarsSortedBase,
newMethodOffset,
pCtx, // place them into the new context
rgVal1,
rgVal2,
rgVCs);
/*-----------------------------------------------------------------------*/
}
ErrExit:
if (oldMethodVarsSortedBase)
delete[] oldMethodVarsSortedBase;
if (newMethodVarsSortedBase)
delete[] newMethodVarsSortedBase;
if (rgVal1 != NULL)
delete[] rgVal1;
if (rgVal2 != NULL)
delete[] rgVal2;
LOG((LF_ENC, LL_INFO100, "EECM::FixContextForEnC: exiting!\n"));
return hr;
}
#endif // !EnC_SUPPORTED
#endif // #ifndef DACCESS_COMPILE
#ifdef USE_GC_INFO_DECODER
/*****************************************************************************
*
* Is the function currently at a "GC safe point" ?
*/
bool EECodeManager::IsGcSafe( EECodeInfo *pCodeInfo,
DWORD dwRelOffset)
{
CONTRACTL {
NOTHROW;
GC_NOTRIGGER;
} CONTRACTL_END;
GcInfoDecoder gcInfoDecoder(
dac_cast<PTR_CBYTE>(pCodeInfo->GetGCInfo()),
DECODE_INTERRUPTIBILITY,
dwRelOffset
);
return gcInfoDecoder.IsInterruptible();
}
#if defined(_TARGET_AMD64_) && defined(_DEBUG)
struct FindEndOfLastInterruptibleRegionState
{
unsigned curOffset;
unsigned endOffset;
unsigned lastRangeOffset;
};
bool FindEndOfLastInterruptibleRegionCB (
UINT32 startOffset,
UINT32 stopOffset,
LPVOID hCallback)
{
FindEndOfLastInterruptibleRegionState *pState = (FindEndOfLastInterruptibleRegionState*)hCallback;
//
// If the current range doesn't overlap the given range, keep searching.
//
if ( startOffset >= pState->endOffset
|| stopOffset < pState->curOffset)
{
return false;
}
//
// If the range overlaps the end, then the last point is the end.
//
if ( stopOffset > pState->endOffset
/*&& startOffset < pState->endOffset*/)
{
// The ranges should be sorted in increasing order.
CONSISTENCY_CHECK(startOffset >= pState->lastRangeOffset);
pState->lastRangeOffset = pState->endOffset;
return true;
}
//
// See if the end of this range is the closet to the end that we've found
// so far.
//
if (stopOffset > pState->lastRangeOffset)
pState->lastRangeOffset = stopOffset;
return false;
}
/*
Locates the end of the last interruptible region in the given code range.
Returns 0 if the entire range is uninterruptible. Returns the end point
if the entire range is interruptible.
*/
unsigned EECodeManager::FindEndOfLastInterruptibleRegion(unsigned curOffset,
unsigned endOffset,
PTR_VOID methodInfoPtr)
{
#ifndef DACCESS_COMPILE
BYTE* gcInfoAddr = (BYTE*) methodInfoPtr;
GcInfoDecoder gcInfoDecoder(
gcInfoAddr,
DECODE_FOR_RANGES_CALLBACK,
0);
FindEndOfLastInterruptibleRegionState state;
state.curOffset = curOffset;
state.endOffset = endOffset;
state.lastRangeOffset = 0;
gcInfoDecoder.EnumerateInterruptibleRanges(&FindEndOfLastInterruptibleRegionCB, &state);
return state.lastRangeOffset;
#else
DacNotImpl();
return NULL;
#endif // #ifndef DACCESS_COMPILE
}
#endif // _TARGET_AMD64_ && _DEBUG
#else // !USE_GC_INFO_DECODER
/*****************************************************************************
*
* Is the function currently at a "GC safe point" ?
*/
bool EECodeManager::IsGcSafe( EECodeInfo *pCodeInfo,
DWORD dwRelOffset)
{
CONTRACTL {
NOTHROW;
GC_NOTRIGGER;
SUPPORTS_DAC;
} CONTRACTL_END;
hdrInfo info;
BYTE * table;
/* Extract the necessary information from the info block header */
table = (BYTE *)crackMethodInfoHdr(pCodeInfo->GetGCInfo(),
dwRelOffset,
&info);
/* workaround: prevent interruption within prolog/epilog */
if (info.prologOffs != hdrInfo::NOT_IN_PROLOG || info.epilogOffs != hdrInfo::NOT_IN_EPILOG)
return false;
#if VERIFY_GC_TABLES
_ASSERTE(*castto(table, unsigned short *)++ == 0xBEEF);
#endif
return (info.interruptible);
}
/*****************************************************************************/
static
PTR_CBYTE skipToArgReg(const hdrInfo& info, PTR_CBYTE table)
{
CONTRACTL {
NOTHROW;
GC_NOTRIGGER;
SUPPORTS_DAC;
} CONTRACTL_END;
#ifdef _DEBUG
PTR_CBYTE tableStart = table;
#else
if (info.argTabOffset != INVALID_ARGTAB_OFFSET)
{
return table + info.argTabOffset;
}
#endif
unsigned count;
#if VERIFY_GC_TABLES
_ASSERTE(*castto(table, unsigned short *)++ == 0xBEEF);
#endif
/* Skip over the untracked frame variable table */
count = info.untrackedCnt;
while (count-- > 0) {
fastSkipSigned(table);
}
#if VERIFY_GC_TABLES
_ASSERTE(*castto(table, unsigned short *)++ == 0xCAFE);
#endif
/* Skip over the frame variable lifetime table */
count = info.varPtrTableSize;
while (count-- > 0) {
fastSkipUnsigned(table); fastSkipUnsigned(table); fastSkipUnsigned(table);
}
#if VERIFY_GC_TABLES
_ASSERTE(*castto(table, unsigned short *) == 0xBABE);
#endif
#ifdef _DEBUG
if (info.argTabOffset != INVALID_ARGTAB_OFFSET)
{
CONSISTENCY_CHECK_MSGF((info.argTabOffset == (unsigned) (table - tableStart)),
("table = %p, tableStart = %p, info.argTabOffset = %d", table, tableStart, info.argTabOffset));
}
#endif
return table;
}
/*****************************************************************************/
#define regNumToMask(regNum) RegMask(1<<regNum)
/*****************************************************************************
Helper for scanArgRegTable() and scanArgRegTableI() for regMasks
*/
void * getCalleeSavedReg(PREGDISPLAY pContext, regNum reg)
{
LIMITED_METHOD_CONTRACT;
SUPPORTS_DAC;
switch (reg)
{
case REGI_EBP: return pContext->pEbp;
case REGI_EBX: return pContext->pEbx;
case REGI_ESI: return pContext->pEsi;
case REGI_EDI: return pContext->pEdi;
default: _ASSERTE(!"bad info.thisPtrResult"); return NULL;
}
}
/*****************************************************************************
These functions converts the bits in the GC encoding to RegMask
*/
inline
RegMask convertCalleeSavedRegsMask(unsigned inMask) // EBP,EBX,ESI,EDI
{
LIMITED_METHOD_CONTRACT;
SUPPORTS_DAC;
_ASSERTE((inMask & 0x0F) == inMask);
unsigned outMask = RM_NONE;
if (inMask & 0x1) outMask |= RM_EDI;
if (inMask & 0x2) outMask |= RM_ESI;
if (inMask & 0x4) outMask |= RM_EBX;
if (inMask & 0x8) outMask |= RM_EBP;
return (RegMask) outMask;
}
inline
RegMask convertAllRegsMask(unsigned inMask) // EAX,ECX,EDX,EBX, EBP,ESI,EDI
{
LIMITED_METHOD_CONTRACT;
SUPPORTS_DAC;
_ASSERTE((inMask & 0xEF) == inMask);
unsigned outMask = RM_NONE;
if (inMask & 0x01) outMask |= RM_EAX;
if (inMask & 0x02) outMask |= RM_ECX;
if (inMask & 0x04) outMask |= RM_EDX;
if (inMask & 0x08) outMask |= RM_EBX;
if (inMask & 0x20) outMask |= RM_EBP;
if (inMask & 0x40) outMask |= RM_ESI;
if (inMask & 0x80) outMask |= RM_EDI;
return (RegMask)outMask;
}
/*****************************************************************************
* scan the register argument table for the not fully interruptible case.
this function is called to find all live objects (pushed arguments)
and to get the stack base for EBP-less methods.
NOTE: If info->argTabResult is NULL, info->argHnumResult indicates
how many bits in argMask are valid
If info->argTabResult is non-NULL, then the argMask field does
not fit in 32-bits and the value in argMask meaningless.
Instead argHnum specifies the number of (variable-length) elements
in the array, and argTabBytes specifies the total byte size of the
array. [ Note this is an extremely rare case ]
*/
#ifdef _PREFAST_
#pragma warning(push)
#pragma warning(disable:21000) // Suppress PREFast warning about overly large function
#endif
static
unsigned scanArgRegTable(PTR_CBYTE table,
unsigned curOffs,
hdrInfo * info)
{
CONTRACTL {
NOTHROW;
GC_NOTRIGGER;
SUPPORTS_DAC;
} CONTRACTL_END;
regNum thisPtrReg = REGI_NA;
#ifdef _DEBUG
bool isCall = false;
#endif
unsigned regMask = 0; // EBP,EBX,ESI,EDI
unsigned argMask = 0;
unsigned argHnum = 0;
PTR_CBYTE argTab = 0;
unsigned argTabBytes = 0;
unsigned stackDepth = 0;
unsigned iregMask = 0; // EBP,EBX,ESI,EDI
unsigned iargMask = 0;
unsigned iptrMask = 0;
#if VERIFY_GC_TABLES
_ASSERTE(*castto(table, unsigned short *)++ == 0xBABE);
#endif
unsigned scanOffs = 0;
_ASSERTE(scanOffs <= info->methodSize);
if (info->ebpFrame) {
/*
Encoding table for methods with an EBP frame and
that are not fully interruptible
The encoding used is as follows:
this pointer encodings:
01000000 this pointer in EBX
00100000 this pointer in ESI
00010000 this pointer in EDI
tiny encoding:
0bsdDDDD
requires code delta < 16 (4-bits)
requires pushed argmask == 0
where DDDD is code delta
b indicates that register EBX is a live pointer
s indicates that register ESI is a live pointer
d indicates that register EDI is a live pointer
small encoding:
1DDDDDDD bsdAAAAA
requires code delta < 120 (7-bits)
requires pushed argmask < 64 (5-bits)
where DDDDDDD is code delta
AAAAA is the pushed args mask
b indicates that register EBX is a live pointer
s indicates that register ESI is a live pointer
d indicates that register EDI is a live pointer
medium encoding
0xFD aaaaaaaa AAAAdddd bseDDDDD
requires code delta < 0x1000000000 (9-bits)
requires pushed argmask < 0x1000000000000 (12-bits)
where DDDDD is the upper 5-bits of the code delta
dddd is the low 4-bits of the code delta
AAAA is the upper 4-bits of the pushed arg mask
aaaaaaaa is the low 8-bits of the pushed arg mask
b indicates that register EBX is a live pointer
s indicates that register ESI is a live pointer
e indicates that register EDI is a live pointer
medium encoding with interior pointers
0xF9 DDDDDDDD bsdAAAAAA iiiIIIII
requires code delta < (8-bits)
requires pushed argmask < (5-bits)
where DDDDDDD is the code delta
b indicates that register EBX is a live pointer
s indicates that register ESI is a live pointer
d indicates that register EDI is a live pointer
AAAAA is the pushed arg mask
iii indicates that EBX,EDI,ESI are interior pointers
IIIII indicates that bits is the arg mask are interior
pointers
large encoding
0xFE [0BSD0bsd][32-bit code delta][32-bit argMask]
b indicates that register EBX is a live pointer
s indicates that register ESI is a live pointer
d indicates that register EDI is a live pointer
B indicates that register EBX is an interior pointer
S indicates that register ESI is an interior pointer
D indicates that register EDI is an interior pointer
requires pushed argmask < 32-bits
large encoding with interior pointers
0xFA [0BSD0bsd][32-bit code delta][32-bit argMask][32-bit interior pointer mask]
b indicates that register EBX is a live pointer
s indicates that register ESI is a live pointer
d indicates that register EDI is a live pointer
B indicates that register EBX is an interior pointer
S indicates that register ESI is an interior pointer
D indicates that register EDI is an interior pointer
requires pushed argmask < 32-bits
requires pushed iArgmask < 32-bits
huge encoding This is the only encoding that supports
a pushed argmask which is greater than
32-bits.
0xFB [0BSD0bsd][32-bit code delta]
[32-bit table count][32-bit table size]
[pushed ptr offsets table...]
b indicates that register EBX is a live pointer
s indicates that register ESI is a live pointer
d indicates that register EDI is a live pointer
B indicates that register EBX is an interior pointer
S indicates that register ESI is an interior pointer
D indicates that register EDI is an interior pointer
the list count is the number of entries in the list
the list size gives the byte-lenght of the list
the offsets in the list are variable-length
*/
while (scanOffs < curOffs)
{
iregMask = 0;
iargMask = 0;
argTab = NULL;
#ifdef _DEBUG
isCall = true;
#endif
/* Get the next byte and check for a 'special' entry */
unsigned encType = *table++;
#if defined(DACCESS_COMPILE)
// In this scenario, it is invalid to have a zero byte in the GC info encoding (refer to the
// comments above). At least one bit has to be set. For example, a byte can represent which
// register is the "this" pointer, and this byte has to be 0x10, 0x20, or 0x40. Having a zero
// byte indicates there is most likely some sort of DAC error, and it may lead to problems such as
// infinite loops. So we bail out early instead.
if (encType == 0)
{
DacError(CORDBG_E_TARGET_INCONSISTENT);
UNREACHABLE();
}
#endif // DACCESS_COMPILE
switch (encType)
{
unsigned val, nxt;
default:
/* A tiny or small call entry */
val = encType;
if ((val & 0x80) == 0x00) {
if (val & 0x0F) {
/* A tiny call entry */
scanOffs += (val & 0x0F);
regMask = (val & 0x70) >> 4;
argMask = 0;
argHnum = 0;
}
else {
/* This pointer liveness encoding */
regMask = (val & 0x70) >> 4;
if (regMask == 0x1)
thisPtrReg = REGI_EDI;
else if (regMask == 0x2)
thisPtrReg = REGI_ESI;
else if (regMask == 0x4)
thisPtrReg = REGI_EBX;
else
_ASSERTE(!"illegal encoding for 'this' pointer liveness");
}
}
else {
/* A small call entry */
scanOffs += (val & 0x7F);
val = *table++;
regMask = val >> 5;
argMask = val & 0x1F;
argHnum = 5;
}
break;
case 0xFD: // medium encoding
argMask = *table++;
val = *table++;
argMask |= ((val & 0xF0) << 4);
argHnum = 12;
nxt = *table++;
scanOffs += (val & 0x0F) + ((nxt & 0x1F) << 4);
regMask = nxt >> 5; // EBX,ESI,EDI
break;
case 0xF9: // medium encoding with interior pointers
scanOffs += *table++;
val = *table++;
argMask = val & 0x1F;
argHnum = 5;
regMask = val >> 5;
val = *table++;
iargMask = val & 0x1F;
iregMask = val >> 5;
break;
case 0xFE: // large encoding
case 0xFA: // large encoding with interior pointers
val = *table++;
regMask = val & 0x7;
iregMask = val >> 4;
scanOffs += *dac_cast<PTR_DWORD>(table); table += sizeof(DWORD);
argMask = *dac_cast<PTR_DWORD>(table); table += sizeof(DWORD);
argHnum = 31;
if (encType == 0xFA) // read iargMask
{
iargMask = *dac_cast<PTR_DWORD>(table); table += sizeof(DWORD);
}
break;
case 0xFB: // huge encoding This is the only partially interruptible
// encoding that supports a pushed ArgMask
// which is greater than 32-bits.
// The ArgMask is encoded using the argTab
val = *table++;
regMask = val & 0x7;
iregMask = val >> 4;
scanOffs += *dac_cast<PTR_DWORD>(table); table += sizeof(DWORD);
argHnum = *dac_cast<PTR_DWORD>(table); table += sizeof(DWORD);
argTabBytes = *dac_cast<PTR_DWORD>(table); table += sizeof(DWORD);
argTab = table; table += argTabBytes;
argMask = 0;
break;
case 0xFF:
scanOffs = curOffs + 1;
break;
} // end case
// iregMask & iargMask are subsets of regMask & argMask respectively
_ASSERTE((iregMask & regMask) == iregMask);
_ASSERTE((iargMask & argMask) == iargMask);
} // end while
}
else {
/*
* Encoding table for methods with an ESP frame and are not fully interruptible
* This encoding does not support a pushed ArgMask greater than 32
*
* The encoding used is as follows:
*
* push 000DDDDD ESP push one item with 5-bit delta
* push 00100000 [pushCount] ESP push multiple items
* reserved 0011xxxx
* skip 01000000 [Delta] Skip Delta, arbitrary sized delta
* skip 0100DDDD Skip small Delta, for call (DDDD != 0)
* pop 01CCDDDD ESP pop CC items with 4-bit delta (CC != 00)
* call 1PPPPPPP Call Pattern, P=[0..79]
* call 1101pbsd DDCCCMMM Call RegMask=pbsd,ArgCnt=CCC,
* ArgMask=MMM Delta=commonDelta[DD]
* call 1110pbsd [ArgCnt] [ArgMask] Call ArgCnt,RegMask=pbsd,[32-bit ArgMask]
* call 11111000 [PBSDpbsd][32-bit delta][32-bit ArgCnt]
* [32-bit PndCnt][32-bit PndSize][PndOffs...]
* iptr 11110000 [IPtrMask] Arbitrary 32-bit Interior Pointer Mask
* thisptr 111101RR This pointer is in Register RR
* 00=EDI,01=ESI,10=EBX,11=EBP
* reserved 111100xx xx != 00
* reserved 111110xx xx != 00
* reserved 11111xxx xxx != 000 && xxx != 111(EOT)
*
* The value 11111111 [0xFF] indicates the end of the table.
*
* An offset (at which stack-walking is performed) without an explicit encoding
* is assumed to be a trivial call-site (no GC registers, stack empty before and
* after) to avoid having to encode all trivial calls.
*
* Note on the encoding used for interior pointers
*
* The iptr encoding must immediately preceed a call encoding. It is used to
* transform a normal GC pointer addresses into an interior pointers for GC purposes.
* The mask supplied to the iptr encoding is read from the least signicant bit
* to the most signicant bit. (i.e the lowest bit is read first)
*
* p indicates that register EBP is a live pointer
* b indicates that register EBX is a live pointer
* s indicates that register ESI is a live pointer
* d indicates that register EDI is a live pointer
* P indicates that register EBP is an interior pointer
* B indicates that register EBX is an interior pointer
* S indicates that register ESI is an interior pointer
* D indicates that register EDI is an interior pointer
*
* As an example the following sequence indicates that EDI.ESI and the 2nd pushed pointer
* in ArgMask are really interior pointers. The pointer in ESI in a normal pointer:
*
* iptr 11110000 00010011 => read Interior Ptr, Interior Ptr, Normal Ptr, Normal Ptr, Interior Ptr
* call 11010011 DDCCC011 RRRR=1011 => read EDI is a GC-pointer, ESI is a GC-pointer. EBP is a GC-pointer
* MMM=0011 => read two GC-pointers arguments on the stack (nested call)
*
* Since the call instruction mentions 5 GC-pointers we list them in the required order:
* EDI, ESI, EBP, 1st-pushed pointer, 2nd-pushed pointer
*
* And we apply the Interior Pointer mask mmmm=10011 to the above five ordered GC-pointers
* we learn that EDI and ESI are interior GC-pointers and that the second push arg is an
* interior GC-pointer.
*/
#if defined(DACCESS_COMPILE)
DWORD cbZeroBytes = 0;
#endif // DACCESS_COMPILE
while (scanOffs <= curOffs)
{
unsigned callArgCnt;
unsigned skip;
unsigned newRegMask, inewRegMask;
unsigned newArgMask, inewArgMask;
unsigned oldScanOffs = scanOffs;
if (iptrMask)
{
// We found this iptrMask in the previous iteration.
// This iteration must be for a call. Set these variables
// so that they are available at the end of the loop
inewRegMask = iptrMask & 0x0F; // EBP,EBX,ESI,EDI
inewArgMask = iptrMask >> 4;
iptrMask = 0;
}
else
{
// Zero out any stale values.
inewRegMask = 0;
inewArgMask = 0;
}
/* Get the next byte and decode it */
unsigned val = *table++;
#if defined(DACCESS_COMPILE)
// In this scenario, a 0 means that there is a push at the current offset. For a struct with
// two double fields, the JIT may use two movq instructions to push the struct onto the stack, and
// the JIT will encode 4 pushes at the same code offset. This means that we can have up to 4
// consecutive bytes of 0 without changing the code offset. Having more than 4 consecutive bytes
// of zero indicates that there is most likely some sort of DAC error, and it may lead to problems
// such as infinite loops. So we bail out early instead.
if (val == 0)
{
cbZeroBytes += 1;
if (cbZeroBytes > 4)
{
DacError(CORDBG_E_TARGET_INCONSISTENT);
UNREACHABLE();
}
}
else
{
cbZeroBytes = 0;
}
#endif // DACCESS_COMPILE
#ifdef _DEBUG
if (scanOffs != curOffs)
isCall = false;
#endif
/* Check pushes, pops, and skips */
if (!(val & 0x80)) {
// iptrMask can immediately precede only calls
_ASSERTE(inewRegMask == 0);
_ASSERTE(inewArgMask == 0);
if (!(val & 0x40)) {
unsigned pushCount;
if (!(val & 0x20))
{
//
// push 000DDDDD ESP push one item, 5-bit delta
//
pushCount = 1;
scanOffs += val & 0x1f;
}
else
{
//
// push 00100000 [pushCount] ESP push multiple items
//
_ASSERTE(val == 0x20);
pushCount = fastDecodeUnsigned(table);
}
if (scanOffs > curOffs)
{
scanOffs = oldScanOffs;
goto FINISHED;
}
stackDepth += pushCount;
}
else if ((val & 0x3f) != 0) {
//
// pop 01CCDDDD pop CC items, 4-bit delta
//
scanOffs += val & 0x0f;
if (scanOffs > curOffs)
{
scanOffs = oldScanOffs;
goto FINISHED;
}
stackDepth -= (val & 0x30) >> 4;
} else if (scanOffs < curOffs) {
//
// skip 01000000 [Delta] Skip arbitrary sized delta
//
skip = fastDecodeUnsigned(table);
scanOffs += skip;
}
else // don't process a skip if we are already at curOffs
goto FINISHED;
/* reset regs and args state since we advance past last call site */
regMask = 0;
iregMask = 0;
argMask = 0;
iargMask = 0;
argHnum = 0;
}
else /* It must be a call, thisptr, or iptr */
{
switch ((val & 0x70) >> 4) {
default: // case 0-4, 1000xxxx through 1100xxxx
//
// call 1PPPPPPP Call Pattern, P=[0..79]
//
decodeCallPattern((val & 0x7f), &callArgCnt,
&newRegMask, &newArgMask, &skip);
// If we've already reached curOffs and the skip amount
// is non-zero then we are done
if ((scanOffs == curOffs) && (skip > 0))
goto FINISHED;
// otherwise process this call pattern
scanOffs += skip;
if (scanOffs > curOffs)
goto FINISHED;
#ifdef _DEBUG
isCall = true;
#endif
regMask = newRegMask;
argMask = newArgMask; argTab = NULL;
iregMask = inewRegMask;
iargMask = inewArgMask;
stackDepth -= callArgCnt;
argHnum = 2; // argMask is known to be <= 3
break;
case 5:
//
// call 1101RRRR DDCCCMMM Call RegMask=RRRR,ArgCnt=CCC,
// ArgMask=MMM Delta=commonDelta[DD]
//
newRegMask = val & 0xf; // EBP,EBX,ESI,EDI
val = *table++; // read next byte
skip = callCommonDelta[val>>6];
// If we've already reached curOffs and the skip amount
// is non-zero then we are done
if ((scanOffs == curOffs) && (skip > 0))
goto FINISHED;
// otherwise process this call encoding
scanOffs += skip;
if (scanOffs > curOffs)
goto FINISHED;
#ifdef _DEBUG
isCall = true;
#endif
regMask = newRegMask;
iregMask = inewRegMask;
callArgCnt = (val >> 3) & 0x7;
stackDepth -= callArgCnt;
argMask = (val & 0x7); argTab = NULL;
iargMask = inewArgMask;
argHnum = 3;
break;
case 6:
//
// call 1110RRRR [ArgCnt] [ArgMask]
// Call ArgCnt,RegMask=RRR,ArgMask
//
#ifdef _DEBUG
isCall = true;
#endif
regMask = val & 0xf; // EBP,EBX,ESI,EDI
iregMask = inewRegMask;
callArgCnt = fastDecodeUnsigned(table);
stackDepth -= callArgCnt;
argMask = fastDecodeUnsigned(table); argTab = NULL;
iargMask = inewArgMask;
argHnum = sizeof(argMask) * 8; // The size of argMask in bits
break;
case 7:
switch (val & 0x0C)
{
case 0x00:
//
// 0xF0 iptr 11110000 [IPtrMask] Arbitrary Interior Pointer Mask
//
iptrMask = fastDecodeUnsigned(table);
break;
case 0x04:
//
// 0xF4 thisptr 111101RR This pointer is in Register RR
// 00=EDI,01=ESI,10=EBX,11=EBP
//
{
static const regNum calleeSavedRegs[] =
{ REGI_EDI, REGI_ESI, REGI_EBX, REGI_EBP };
thisPtrReg = calleeSavedRegs[val&0x3];
}
break;
case 0x08:
//
// 0xF8 call 11111000 [PBSDpbsd][32-bit delta][32-bit ArgCnt]
// [32-bit PndCnt][32-bit PndSize][PndOffs...]
//
val = *table++;
skip = *dac_cast<PTR_DWORD>(table); table += sizeof(DWORD);
// [VSUQFE 4670]
// If we've already reached curOffs and the skip amount
// is non-zero then we are done
if ((scanOffs == curOffs) && (skip > 0))
goto FINISHED;
// [VSUQFE 4670]
scanOffs += skip;
if (scanOffs > curOffs)
goto FINISHED;
#ifdef _DEBUG
isCall = true;
#endif
regMask = val & 0xF;
iregMask = val >> 4;
callArgCnt = *dac_cast<PTR_DWORD>(table); table += sizeof(DWORD);
stackDepth -= callArgCnt;
argHnum = *dac_cast<PTR_DWORD>(table); table += sizeof(DWORD);
argTabBytes = *dac_cast<PTR_DWORD>(table); table += sizeof(DWORD);
argTab = table;
table += argTabBytes;
break;
case 0x0C:
//
// 0xFF end 11111111 End of table marker
//
_ASSERTE(val==0xff);
goto FINISHED;
default:
_ASSERTE(!"reserved GC encoding");
break;
}
break;
} // end switch
} // end else (!(val & 0x80))
// iregMask & iargMask are subsets of regMask & argMask respectively
_ASSERTE((iregMask & regMask) == iregMask);
_ASSERTE((iargMask & argMask) == iargMask);
} // end while
} // end else ebp-less frame
FINISHED:
// iregMask & iargMask are subsets of regMask & argMask respectively
_ASSERTE((iregMask & regMask) == iregMask);
_ASSERTE((iargMask & argMask) == iargMask);
if (scanOffs != curOffs)
{
/* must have been a boring call */
info->regMaskResult = RM_NONE;
info->argMaskResult = ptrArgTP(0);
info->iregMaskResult = RM_NONE;
info->iargMaskResult = ptrArgTP(0);
info->argHnumResult = 0;
info->argTabResult = NULL;
info->argTabBytes = 0;
}
else
{
info->regMaskResult = convertCalleeSavedRegsMask(regMask);
info->argMaskResult = ptrArgTP(argMask);
info->argHnumResult = argHnum;
info->iregMaskResult = convertCalleeSavedRegsMask(iregMask);
info->iargMaskResult = ptrArgTP(iargMask);
info->argTabResult = argTab;
info->argTabBytes = argTabBytes;
}
#ifdef _DEBUG
if (scanOffs != curOffs) {
isCall = false;
}
_ASSERTE(thisPtrReg == REGI_NA || (!isCall || (regNumToMask(thisPtrReg) & info->regMaskResult)));
#endif
info->thisPtrResult = thisPtrReg;
_ASSERTE(int(stackDepth) < INT_MAX); // check that it did not underflow
return (stackDepth * sizeof(unsigned));
}
#ifdef _PREFAST_
#pragma warning(pop)
#endif
/*****************************************************************************
* scan the register argument table for the fully interruptible case.
this function is called to find all live objects (pushed arguments)
and to get the stack base for fully interruptible methods.
Returns size of things pushed on the stack for ESP frames
*/
static
unsigned scanArgRegTableI(PTR_CBYTE table,
unsigned curOffs,
hdrInfo * info)
{
CONTRACTL {
NOTHROW;
GC_NOTRIGGER;
SUPPORTS_DAC;
} CONTRACTL_END;
regNum thisPtrReg = REGI_NA;
unsigned ptrRegs = 0;
unsigned iptrRegs = 0;
unsigned ptrOffs = 0;
unsigned argCnt = 0;
ptrArgTP ptrArgs(0);
ptrArgTP iptrArgs(0);
ptrArgTP argHigh(0);
bool isThis = false;
bool iptr = false;
#if VERIFY_GC_TABLES
_ASSERTE(*castto(table, unsigned short *)++ == 0xBABE);
#endif
/*
Encoding table for methods that are fully interruptible
The encoding used is as follows:
ptr reg dead 00RRRDDD [RRR != 100]
ptr reg live 01RRRDDD [RRR != 100]
non-ptr arg push 10110DDD [SSS == 110]
ptr arg push 10SSSDDD [SSS != 110] && [SSS != 111]
ptr arg pop 11CCCDDD [CCC != 000] && [CCC != 110] && [CCC != 111]
little delta skip 11000DDD [CCC == 000]
bigger delta skip 11110BBB [CCC == 110]
The values used in the encodings are as follows:
DDD code offset delta from previous entry (0-7)
BBB bigger delta 000=8,001=16,010=24,...,111=64
RRR register number (EAX=000,ECX=001,EDX=010,EBX=011,
EBP=101,ESI=110,EDI=111), ESP=100 is reserved
SSS argument offset from base of stack. This is
redundant for frameless methods as we can
infer it from the previous pushes+pops. However,
for EBP-methods, we only report GC pushes, and
so we need SSS
CCC argument count being popped (includes only ptrs for EBP methods)
The following are the 'large' versions:
large delta skip 10111000 [0xB8] , encodeUnsigned(delta)
large ptr arg push 11111000 [0xF8] , encodeUnsigned(pushCount)
large non-ptr arg push 11111001 [0xF9] , encodeUnsigned(pushCount)
large ptr arg pop 11111100 [0xFC] , encodeUnsigned(popCount)
large arg dead 11111101 [0xFD] , encodeUnsigned(popCount) for caller-pop args.
Any GC args go dead after the call,
but are still sitting on the stack
this pointer prefix 10111100 [0xBC] the next encoding is a ptr live
or a ptr arg push
and contains the this pointer
interior or by-ref 10111111 [0xBF] the next encoding is a ptr live
pointer prefix or a ptr arg push
and contains an interior
or by-ref pointer
The value 11111111 [0xFF] indicates the end of the table.
*/
#if defined(DACCESS_COMPILE)
bool fLastByteIsZero = false;
#endif // DACCESS_COMPILE
/* Have we reached the instruction we're looking for? */
while (ptrOffs <= curOffs)
{
unsigned val;
int isPop;
unsigned argOfs;
unsigned regMask;
// iptrRegs & iptrArgs are subsets of ptrRegs & ptrArgs respectively
_ASSERTE((iptrRegs & ptrRegs) == iptrRegs);
_ASSERTE((iptrArgs & ptrArgs) == iptrArgs);
/* Now find the next 'life' transition */
val = *table++;
#if defined(DACCESS_COMPILE)
// In this scenario, a zero byte means that EAX is going dead at the current offset. Since EAX
// can't go dead more than once at any given offset, it's invalid to have two consecutive bytes
// of zero. If this were to happen, then it means that there is most likely some sort of DAC
// error, and it may lead to problems such as infinite loops. So we bail out early instead.
if ((val == 0) && fLastByteIsZero)
{
DacError(CORDBG_E_TARGET_INCONSISTENT);
UNREACHABLE();
}
fLastByteIsZero = (val == 0);
#endif // DACCESS_COMPILE
if (!(val & 0x80))
{
/* A small 'regPtr' encoding */
regNum reg;
ptrOffs += (val ) & 0x7;
if (ptrOffs > curOffs) {
iptr = isThis = false;
goto REPORT_REFS;
}
reg = (regNum)((val >> 3) & 0x7);
regMask = 1 << reg; // EAX,ECX,EDX,EBX,---,EBP,ESI,EDI
#if 0
printf("regMask = %04X -> %04X\n", ptrRegs,
(val & 0x40) ? (ptrRegs | regMask)
: (ptrRegs & ~regMask));
#endif
/* The register is becoming live/dead here */
if (val & 0x40)
{
/* Becomes Live */
_ASSERTE((ptrRegs & regMask) == 0);
ptrRegs |= regMask;
if (isThis)
{
thisPtrReg = reg;
}
if (iptr)
{
iptrRegs |= regMask;
}
}
else
{
/* Becomes Dead */
_ASSERTE((ptrRegs & regMask) != 0);
ptrRegs &= ~regMask;
if (reg == thisPtrReg)
{
thisPtrReg = REGI_NA;
}
if (iptrRegs & regMask)
{
iptrRegs &= ~regMask;
}
}
iptr = isThis = false;
continue;
}
/* This is probably an argument push/pop */
argOfs = (val & 0x38) >> 3;
/* 6 [110] and 7 [111] are reserved for other encodings */
if (argOfs < 6)
{
/* A small argument encoding */
ptrOffs += (val & 0x07);
if (ptrOffs > curOffs) {
iptr = isThis = false;
goto REPORT_REFS;
}
isPop = (val & 0x40);
ARG:
if (isPop)
{
if (argOfs == 0)
continue; // little skip encoding
/* We remove (pop) the top 'argOfs' entries */
_ASSERTE(argOfs || argOfs <= argCnt);
/* adjust # of arguments */
argCnt -= argOfs;
_ASSERTE(argCnt < MAX_PTRARG_OFS);
// printf("[%04X] popping %u args: mask = %04X\n", ptrOffs, argOfs, (int)ptrArgs);
do
{
_ASSERTE(!isZero(argHigh));
/* Do we have an argument bit that's on? */
if (intersect(ptrArgs, argHigh))
{
/* Turn off the bit */
setDiff(ptrArgs, argHigh);
setDiff(iptrArgs, argHigh);
/* We've removed one more argument bit */
argOfs--;
}
else if (info->ebpFrame)
argCnt--;
else /* !ebpFrame && not a ref */
argOfs--;
/* Continue with the next lower bit */
argHigh >>= 1;
}
while (argOfs);
_ASSERTE((info->ebpFrame != 0) ||
isZero(argHigh) ||
(argHigh == CONSTRUCT_ptrArgTP(1, (argCnt-1))));
if (info->ebpFrame)
{
while (!intersect(argHigh, ptrArgs) && (!isZero(argHigh)))
argHigh >>= 1;
}
}
else
{
/* Add a new ptr arg entry at stack offset 'argOfs' */
if (argOfs >= MAX_PTRARG_OFS)
{
_ASSERTE_ALL_BUILDS("clr/src/VM/eetwain.cpp", !"scanArgRegTableI: args pushed 'too deep'");
}
else
{
/* For ESP-frames, all pushes are reported, and so
argOffs has to be consistent with argCnt */
_ASSERTE(info->ebpFrame || argCnt == argOfs);
/* store arg count */
argCnt = argOfs + 1;
_ASSERTE((argCnt < MAX_PTRARG_OFS));
/* Compute the appropriate argument offset bit */
ptrArgTP argMask = CONSTRUCT_ptrArgTP(1, argOfs);
// printf("push arg at offset %02u --> mask = %04X\n", argOfs, (int)argMask);
/* We should never push twice at the same offset */
_ASSERTE(!intersect( ptrArgs, argMask));
_ASSERTE(!intersect(iptrArgs, argMask));
/* We should never push within the current highest offset */
// _ASSERTE(argHigh < argMask);
/* This is now the highest bit we've set */
argHigh = argMask;
/* Set the appropriate bit in the argument mask */
ptrArgs |= argMask;
if (iptr)
iptrArgs |= argMask;
}
iptr = isThis = false;
}
continue;
}
else if (argOfs == 6)
{
if (val & 0x40) {
/* Bigger delta 000=8,001=16,010=24,...,111=64 */
ptrOffs += (((val & 0x07) + 1) << 3);
}
else {
/* non-ptr arg push */
_ASSERTE(!(info->ebpFrame));
ptrOffs += (val & 0x07);
if (ptrOffs > curOffs) {
iptr = isThis = false;
goto REPORT_REFS;
}
argHigh = CONSTRUCT_ptrArgTP(1, argCnt);
argCnt++;
_ASSERTE(argCnt < MAX_PTRARG_OFS);
}
continue;
}
/* argOfs was 7 [111] which is reserved for the larger encodings */
_ASSERTE(argOfs==7);
switch (val)
{
case 0xFF:
iptr = isThis = false;
goto REPORT_REFS; // the method might loop !!!
case 0xB8:
val = fastDecodeUnsigned(table);
ptrOffs += val;
continue;
case 0xBC:
isThis = true;
break;
case 0xBF:
iptr = true;
break;
case 0xF8:
case 0xFC:
isPop = val & 0x04;
argOfs = fastDecodeUnsigned(table);
goto ARG;
case 0xFD: {
argOfs = fastDecodeUnsigned(table);
_ASSERTE(argOfs && argOfs <= argCnt);
// Kill the top "argOfs" pointers.
ptrArgTP argMask;
for(argMask = CONSTRUCT_ptrArgTP(1, argCnt); (argOfs != 0); argMask >>= 1)
{
_ASSERTE(!isZero(argMask) && !isZero(ptrArgs)); // there should be remaining pointers
if (intersect(ptrArgs, argMask))
{
setDiff(ptrArgs, argMask);
setDiff(iptrArgs, argMask);
argOfs--;
}
}
// For ebp-frames, need to find the next higest pointer for argHigh
if (info->ebpFrame)
{
for(argHigh = ptrArgTP(0); !isZero(argMask); argMask >>= 1)
{
if (intersect(ptrArgs, argMask)) {
argHigh = argMask;
break;
}
}
}
} break;
case 0xF9:
argOfs = fastDecodeUnsigned(table);
argCnt += argOfs;
break;
default:
_ASSERTE(!"Unexpected special code %04X");
}
}
/* Report all live pointer registers */
REPORT_REFS:
_ASSERTE((iptrRegs & ptrRegs) == iptrRegs); // iptrRegs is a subset of ptrRegs
_ASSERTE((iptrArgs & ptrArgs) == iptrArgs); // iptrArgs is a subset of ptrArgs
/* Save the current live register, argument set, and argCnt */
info->regMaskResult = convertAllRegsMask(ptrRegs);
info->argMaskResult = ptrArgs;
info->argHnumResult = 0;
info->iregMaskResult = convertAllRegsMask(iptrRegs);
info->iargMaskResult = iptrArgs;
info->thisPtrResult = thisPtrReg;
_ASSERTE(thisPtrReg == REGI_NA || (regNumToMask(thisPtrReg) & info->regMaskResult));
if (info->ebpFrame)
{
return 0;
}
else
{
_ASSERTE(int(argCnt) < INT_MAX); // check that it did not underflow
return (argCnt * sizeof(unsigned));
}
}
/*****************************************************************************/
unsigned GetPushedArgSize(hdrInfo * info, PTR_CBYTE table, DWORD curOffs)
{
SUPPORTS_DAC;
unsigned sz;
if (info->interruptible)
{
sz = scanArgRegTableI(skipToArgReg(*info, table),
curOffs,
info);
}
else
{
sz = scanArgRegTable(skipToArgReg(*info, table),
curOffs,
info);
}
return sz;
}
/*****************************************************************************/
inline
void TRASH_CALLEE_UNSAVED_REGS(PREGDISPLAY pContext)
{
LIMITED_METHOD_DAC_CONTRACT;
#ifdef _DEBUG
/* This is not completely correct as we lose the current value, but
it should not really be useful to anyone. */
static DWORD s_badData = 0xDEADBEEF;
pContext->pEax = pContext->pEcx = pContext->pEdx = &s_badData;
#endif //_DEBUG
}
/*****************************************************************************
* Sizes of certain i386 instructions which are used in the prolog/epilog
*/
// Can we use sign-extended byte to encode the imm value, or do we need a dword
#define CAN_COMPRESS(val) ((INT8)(val) == (INT32)(val))
#define SZ_ADD_REG(val) ( 2 + (CAN_COMPRESS(val) ? 1 : 4))
#define SZ_AND_REG(val) SZ_ADD_REG(val)
#define SZ_POP_REG 1
#define SZ_LEA(offset) SZ_ADD_REG(offset)
#define SZ_MOV_REG_REG 2
bool IsMarkerInstr(BYTE val)
{
SUPPORTS_DAC;
#ifdef _DEBUG
return (val == X86_INSTR_INT3) || // Debugger might stomp with an int3
(val == X86_INSTR_HLT && GCStress<cfg_any>::IsEnabled()); // GcCover might stomp with a Hlt
#else
return false;
#endif
}
/* Check if the given instruction opcode is the one we expect.
This is a "necessary" but not "sufficient" check as it ignores the check
if the instruction is one of our special markers (for debugging and GcStress) */
bool CheckInstrByte(BYTE val, BYTE expectedValue)
{
SUPPORTS_DAC;
return ((val == expectedValue) || IsMarkerInstr(val));
}
/* Similar to CheckInstrByte(). Use this to check a masked opcode (ignoring
optional bits in the opcode encoding).
valPattern is the masked out value.
expectedPattern is the mask value we expect.
val is the actual instruction opcode
*/
bool CheckInstrBytePattern(BYTE valPattern, BYTE expectedPattern, BYTE val)
{
SUPPORTS_DAC;
_ASSERTE((valPattern & val) == valPattern);
return ((valPattern == expectedPattern) || IsMarkerInstr(val));
}
/* Similar to CheckInstrByte() */
bool CheckInstrWord(WORD val, WORD expectedValue)
{
LIMITED_METHOD_CONTRACT;
SUPPORTS_DAC;
return ((val == expectedValue) || IsMarkerInstr(val & 0xFF));
}
// Use this to check if the instruction at offset "walkOffset" has already
// been executed
// "actualHaltOffset" is the offset when the code was suspended
// It is assumed that there is linear control flow from offset 0 to "actualHaltOffset".
//
// This has been factored out just so that the intent of the comparison
// is clear (compared to the opposite intent)
bool InstructionAlreadyExecuted(unsigned walkOffset, unsigned actualHaltOffset)
{
SUPPORTS_DAC;
return (walkOffset < actualHaltOffset);
}
// skips past a "arith REG, IMM"
inline unsigned SKIP_ARITH_REG(int val, PTR_CBYTE base, unsigned offset)
{
LIMITED_METHOD_DAC_CONTRACT;
unsigned delta = 0;
if (val != 0)
{
#ifdef _DEBUG
// Confirm that arith instruction is at the correct place
_ASSERTE(CheckInstrBytePattern(base[offset ] & 0xFD, 0x81, base[offset]) &&
CheckInstrBytePattern(base[offset+1] & 0xC0, 0xC0, base[offset+1]));
// only use DWORD form if needed
_ASSERTE(((base[offset] & 2) != 0) == CAN_COMPRESS(val) ||
IsMarkerInstr(base[offset]));
#endif
delta = 2 + (CAN_COMPRESS(val) ? 1 : 4);
}
return(offset + delta);
}
inline unsigned SKIP_PUSH_REG(PTR_CBYTE base, unsigned offset)
{
LIMITED_METHOD_DAC_CONTRACT;
// Confirm it is a push instruction
_ASSERTE(CheckInstrBytePattern(base[offset] & 0xF8, 0x50, base[offset]));
return(offset + 1);
}
inline unsigned SKIP_POP_REG(PTR_CBYTE base, unsigned offset)
{
LIMITED_METHOD_DAC_CONTRACT;
// Confirm it is a pop instruction
_ASSERTE(CheckInstrBytePattern(base[offset] & 0xF8, 0x58, base[offset]));
return(offset + 1);
}
inline unsigned SKIP_MOV_REG_REG(PTR_CBYTE base, unsigned offset)
{
LIMITED_METHOD_DAC_CONTRACT;
// Confirm it is a move instruction
// Note that only the first byte may have been stomped on by IsMarkerInstr()
// So we can check the second byte directly
_ASSERTE(CheckInstrBytePattern(base[offset] & 0xFD, 0x89, base[offset]) &&
(base[offset+1] & 0xC0) == 0xC0);
return(offset + 2);
}
inline unsigned SKIP_LEA_ESP_EBP(int val, PTR_CBYTE base, unsigned offset)
{
LIMITED_METHOD_DAC_CONTRACT;
#ifdef _DEBUG
// Confirm it is the right instruction
// Note that only the first byte may have been stomped on by IsMarkerInstr()
// So we can check the second byte directly
WORD wOpcode = *(PTR_WORD)base;
_ASSERTE((CheckInstrWord(wOpcode, X86_INSTR_w_LEA_ESP_EBP_BYTE_OFFSET) &&
(val == *(PTR_SBYTE)(base+2)) &&
CAN_COMPRESS(val)) ||
(CheckInstrWord(wOpcode, X86_INSTR_w_LEA_ESP_EBP_DWORD_OFFSET) &&
(val == *(PTR_INT32)(base+2)) &&
!CAN_COMPRESS(val)));
#endif
unsigned delta = 2 + (CAN_COMPRESS(val) ? 1 : 4);
return(offset + delta);
}
unsigned SKIP_ALLOC_FRAME(int size, PTR_CBYTE base, unsigned offset)
{
CONTRACTL {
NOTHROW;
GC_NOTRIGGER;
SUPPORTS_DAC;
} CONTRACTL_END;
_ASSERTE(size != 0);
if (size == sizeof(void*))
{
// We do "push eax" instead of "sub esp,4"
return (SKIP_PUSH_REG(base, offset));
}
if (size >= CORINFO_PAGE_SIZE)
{
if (size < (3 * CORINFO_PAGE_SIZE))
{
// add 7 bytes for one or two TEST EAX, [ESP+CORINFO_PAGE_SIZE]
offset += (size / CORINFO_PAGE_SIZE) * 7;
}
else
{
// xor eax, eax 2
// [nop] 0-3
// loop:
// test [esp + eax], eax 3
// sub eax, 0x1000 5
// cmp EAX, -size 5
// jge loop 2
offset += 2;
// NGEN images that support rejit may have extra nops we need to skip over
while (offset < 5)
{
if (CheckInstrByte(base[offset], X86_INSTR_NOP))
{
offset++;
}
else
{
break;
}
}
offset += 15;
}
}
// sub ESP, size
return (SKIP_ARITH_REG(size, base, offset));
}
#endif // !USE_GC_INFO_DECODER
#if !defined(_TARGET_X86_) && !defined(CROSSGEN_COMPILE)
void EECodeManager::EnsureCallerContextIsValid( PREGDISPLAY pRD, StackwalkCacheEntry* pCacheEntry, EECodeInfo * pCodeInfo /*= NULL*/ )
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
SUPPORTS_DAC;
}
CONTRACTL_END;
if( !pRD->IsCallerContextValid )
{
#if !defined(DACCESS_COMPILE)
if (pCacheEntry != NULL)
{
// lightened schema: take stack unwind info from stackwalk cache
QuickUnwindStackFrame(pRD, pCacheEntry, EnsureCallerStackFrameIsValid);
}
else
#endif // !DACCESS_COMPILE
{
// We need to make a copy here (instead of switching the pointers), in order to preserve the current context
*(pRD->pCallerContext) = *(pRD->pCurrentContext);
NOT_X86(*(pRD->pCallerContextPointers) = *(pRD->pCurrentContextPointers));
T_KNONVOLATILE_CONTEXT_POINTERS *pCallerContextPointers = NULL;
NOT_X86(pCallerContextPointers = pRD->pCallerContextPointers);
Thread::VirtualUnwindCallFrame(pRD->pCallerContext, pCallerContextPointers, pCodeInfo);
}
pRD->IsCallerContextValid = TRUE;
}
_ASSERTE( pRD->IsCallerContextValid );
}
size_t EECodeManager::GetCallerSp( PREGDISPLAY pRD )
{
CONTRACTL {
NOTHROW;
GC_NOTRIGGER;
SUPPORTS_DAC;
} CONTRACTL_END;
// Don't add usage of this field. This is only temporary.
// See ExceptionTracker::InitializeCrawlFrame() for more information.
if (!pRD->IsCallerSPValid)
{
EnsureCallerContextIsValid(pRD, NULL);
}
return (size_t) (GetSP(pRD->pCallerContext));
}
#endif // !defined(_TARGET_X86_) && !defined(CROSSGEN_COMPILE)
/*
* Light unwind the current stack frame, using provided cache entry.
* pPC, Esp and pEbp of pContext are updated.
*/
// static
void EECodeManager::QuickUnwindStackFrame(PREGDISPLAY pRD, StackwalkCacheEntry *pCacheEntry, QuickUnwindFlag flag)
{
CONTRACTL {
NOTHROW;
GC_NOTRIGGER;
} CONTRACTL_END;
_ASSERTE(pCacheEntry);
_ASSERTE(GetControlPC(pRD) == (PCODE)(pCacheEntry->IP));
#if defined(_TARGET_X86_)
_ASSERTE(flag == UnwindCurrentStackFrame);
_ASSERTE(!pCacheEntry->fUseEbp || pCacheEntry->fUseEbpAsFrameReg);
if (pCacheEntry->fUseEbpAsFrameReg)
{
_ASSERTE(pCacheEntry->fUseEbp);
// EBP frame, update ESP through EBP, since ESPOffset may vary
pRD->pEbp = PTR_DWORD((TADDR)*pRD->pEbp);
pRD->Esp = (TADDR)pRD->pEbp + sizeof(void*);
}
else
{
_ASSERTE(!pCacheEntry->fUseEbp);
// ESP frame, update up to retAddr using ESPOffset
pRD->Esp += pCacheEntry->ESPOffset;
}
pRD->PCTAddr = (TADDR)pRD->Esp;
pRD->ControlPC = *PTR_PCODE(pRD->PCTAddr);
pRD->Esp += sizeof(void*) + pCacheEntry->argSize;
#elif defined(_TARGET_AMD64_)
if (pRD->IsCallerContextValid)
{
pRD->pCurrentContext->Rbp = pRD->pCallerContext->Rbp;
pRD->pCurrentContext->Rsp = pRD->pCallerContext->Rsp;
pRD->pCurrentContext->Rip = pRD->pCallerContext->Rip;
}
else
{
PCONTEXT pSourceCtx = NULL;
PCONTEXT pTargetCtx = NULL;
if (flag == UnwindCurrentStackFrame)
{
pTargetCtx = pRD->pCurrentContext;
pSourceCtx = pRD->pCurrentContext;
}
else
{
pTargetCtx = pRD->pCallerContext;
pSourceCtx = pRD->pCurrentContext;
}
// Unwind RBP. The offset is relative to the current sp.
if (pCacheEntry->RBPOffset == 0)
{
pTargetCtx->Rbp = pSourceCtx->Rbp;
}
else
{
pTargetCtx->Rbp = *(UINT_PTR*)(pSourceCtx->Rsp + pCacheEntry->RBPOffset);
}
// Adjust the sp. From this pointer onwards pCurrentContext->Rsp is the caller sp.
pTargetCtx->Rsp = pSourceCtx->Rsp + pCacheEntry->RSPOffset;
// Retrieve the return address.
pTargetCtx->Rip = *(UINT_PTR*)((pTargetCtx->Rsp) - sizeof(UINT_PTR));
}
if (flag == UnwindCurrentStackFrame)
{
SyncRegDisplayToCurrentContext(pRD);
pRD->IsCallerContextValid = FALSE;
pRD->IsCallerSPValid = FALSE; // Don't add usage of this field. This is only temporary.
}
#else // !_TARGET_X86_ && !_TARGET_AMD64_
PORTABILITY_ASSERT("EECodeManager::QuickUnwindStackFrame is not implemented on this platform.");
#endif // !_TARGET_X86_ && !_TARGET_AMD64_
}
/*****************************************************************************/
#ifdef _TARGET_X86_ // UnwindStackFrame
/*****************************************************************************/
const RegMask CALLEE_SAVED_REGISTERS_MASK[] =
{
RM_EDI, // first register to be pushed
RM_ESI,
RM_EBX,
RM_EBP // last register to be pushed
};
const SIZE_T REGDISPLAY_OFFSET_OF_CALLEE_SAVED_REGISTERS[] =
{
offsetof(REGDISPLAY, pEdi), // first register to be pushed
offsetof(REGDISPLAY, pEsi),
offsetof(REGDISPLAY, pEbx),
offsetof(REGDISPLAY, pEbp) // last register to be pushed
};
/*****************************************************************************/
void UnwindEspFrameEpilog(
PREGDISPLAY pContext,
hdrInfo * info,
PTR_CBYTE epilogBase,
unsigned flags)
{
LIMITED_METHOD_CONTRACT;
SUPPORTS_DAC;
_ASSERTE(info->epilogOffs != hdrInfo::NOT_IN_EPILOG);
_ASSERTE(!info->ebpFrame && !info->doubleAlign);
_ASSERTE(info->epilogOffs > 0);
int offset = 0;
unsigned ESP = pContext->Esp;
if (info->rawStkSize)
{
if (!InstructionAlreadyExecuted(offset, info->epilogOffs))
{
/* We have NOT executed the "ADD ESP, FrameSize",
so manually adjust stack pointer */
ESP += info->rawStkSize;
}
// We have already popped off the frame (excluding the callee-saved registers)
if (epilogBase[0] == X86_INSTR_POP_ECX)
{
// We may use "POP ecx" for doing "ADD ESP, 4",
// or we may not (in the case of JMP epilogs)
_ASSERTE(info->rawStkSize == sizeof(void*));
offset = SKIP_POP_REG(epilogBase, offset);
}
else
{
// "add esp, rawStkSize"
offset = SKIP_ARITH_REG(info->rawStkSize, epilogBase, offset);
}
}
/* Remaining callee-saved regs are at ESP. Need to update
regsMask as well to exclude registers which have already been popped. */
const RegMask regsMask = info->savedRegMask;
/* Increment "offset" in steps to see which callee-saved
registers have already been popped */
for (unsigned i = NumItems(CALLEE_SAVED_REGISTERS_MASK); i > 0; i--)
{
RegMask regMask = CALLEE_SAVED_REGISTERS_MASK[i - 1];
if (!(regMask & regsMask))
continue;
if (!InstructionAlreadyExecuted(offset, info->epilogOffs))
{
/* We have NOT yet popped off the register.
Get the value from the stack if needed */
if ((flags & UpdateAllRegs) || (regMask == RM_EBP))
{
SIZE_T offsetOfRegPtr = REGDISPLAY_OFFSET_OF_CALLEE_SAVED_REGISTERS[i - 1];
*(LPVOID*)(PBYTE(pContext) + offsetOfRegPtr) = PTR_DWORD((TADDR)ESP);
}
/* Adjust ESP */
ESP += sizeof(void*);
}
offset = SKIP_POP_REG(epilogBase, offset);
}
//CEE_JMP generates an epilog similar to a normal CEE_RET epilog except for the last instruction
_ASSERTE(CheckInstrBytePattern(epilogBase[offset] & X86_INSTR_RET, X86_INSTR_RET, epilogBase[offset]) //ret
|| CheckInstrBytePattern(epilogBase[offset], X86_INSTR_JMP_NEAR_REL32, epilogBase[offset]) //jmp ret32
|| CheckInstrWord(*PTR_WORD(epilogBase + offset), X86_INSTR_w_JMP_FAR_IND_IMM)); //jmp [addr32]
/* Finally we can set pPC */
pContext->PCTAddr = (TADDR)ESP;
pContext->ControlPC = *PTR_PCODE(pContext->PCTAddr);
pContext->Esp = ESP;
}
/*****************************************************************************/
void UnwindEbpDoubleAlignFrameEpilog(
PREGDISPLAY pContext,
hdrInfo * info,
PTR_CBYTE epilogBase,
unsigned flags)
{
LIMITED_METHOD_CONTRACT;
SUPPORTS_DAC;
_ASSERTE(info->epilogOffs != hdrInfo::NOT_IN_EPILOG);
_ASSERTE(info->ebpFrame || info->doubleAlign);
_ASSERTE(info->argSize < 0x10000); // "ret" only has a 2 byte operand
/* See how many instructions we have executed in the
epilog to determine which callee-saved registers
have already been popped */
int offset = 0;
unsigned ESP = pContext->Esp;
bool needMovEspEbp = false;
if (info->doubleAlign)
{
// add esp, rawStkSize
if (!InstructionAlreadyExecuted(offset, info->epilogOffs))
ESP += info->rawStkSize;
_ASSERTE(info->rawStkSize != 0);
offset = SKIP_ARITH_REG(info->rawStkSize, epilogBase, offset);
// We also need "mov esp, ebp" after popping the callee-saved registers
needMovEspEbp = true;
}
else
{
bool needLea = false;
if (info->localloc)
{
// ESP may be variable if a localloc was actually executed. We will reset it.
// lea esp, [ebp-calleeSavedRegs]
needLea = true;
}
else if (info->savedRegsCountExclFP == 0)
{
// We will just generate "mov esp, ebp" and be done with it.
if (info->rawStkSize != 0)
{
needMovEspEbp = true;
}
}
else if (info->rawStkSize == 0)
{
// do nothing before popping the callee-saved registers
}
else if (info->rawStkSize == sizeof(void*))
{
// "pop ecx" will make ESP point to the callee-saved registers
if (!InstructionAlreadyExecuted(offset, info->epilogOffs))
ESP += sizeof(void*);
offset = SKIP_POP_REG(epilogBase, offset);
}
else
{
// We need to make ESP point to the callee-saved registers
// lea esp, [ebp-calleeSavedRegs]
needLea = true;
}
if (needLea)
{
// lea esp, [ebp-calleeSavedRegs]
unsigned calleeSavedRegsSize = info->savedRegsCountExclFP * sizeof(void*);
if (!InstructionAlreadyExecuted(offset, info->epilogOffs))
ESP = (*pContext->pEbp) - calleeSavedRegsSize;
offset = SKIP_LEA_ESP_EBP(-int(calleeSavedRegsSize), epilogBase, offset);
}
}
for (unsigned i = NumItems(CALLEE_SAVED_REGISTERS_MASK) - 1; i > 0; i--)
{
RegMask regMask = CALLEE_SAVED_REGISTERS_MASK[i - 1];
_ASSERTE(regMask != RM_EBP);
if ((info->savedRegMask & regMask) == 0)
continue;
if (!InstructionAlreadyExecuted(offset, info->epilogOffs))
{
if (flags & UpdateAllRegs)
{
SIZE_T offsetOfRegPtr = REGDISPLAY_OFFSET_OF_CALLEE_SAVED_REGISTERS[i - 1];
*(LPVOID*)(PBYTE(pContext) + offsetOfRegPtr) = PTR_DWORD((TADDR)ESP);
}
ESP += sizeof(void*);
}
offset = SKIP_POP_REG(epilogBase, offset);
}
if (needMovEspEbp)
{
if (!InstructionAlreadyExecuted(offset, info->epilogOffs))
ESP = *pContext->pEbp;
offset = SKIP_MOV_REG_REG(epilogBase, offset);
}
// Have we executed the pop EBP?
if (!InstructionAlreadyExecuted(offset, info->epilogOffs))
{
pContext->pEbp = PTR_DWORD(TADDR(ESP));
ESP += sizeof(void*);
}
offset = SKIP_POP_REG(epilogBase, offset);
pContext->PCTAddr = (TADDR)ESP;
pContext->ControlPC = *PTR_PCODE(pContext->PCTAddr);
pContext->Esp = ESP;
}
//****************************************************************************
// This is the value ESP is incremented by on doing a "return"
inline SIZE_T ESPIncrOnReturn(hdrInfo * info)
{
SUPPORTS_DAC;
return sizeof(void *) + // pop off the return address
// Note varargs is caller-popped
(info->varargs ? 0 : info->argSize);
}
/*****************************************************************************/
void UnwindEpilog(
PREGDISPLAY pContext,
hdrInfo * info,
PTR_CBYTE epilogBase,
unsigned flags)
{
LIMITED_METHOD_CONTRACT;
SUPPORTS_DAC;
_ASSERTE(info->epilogOffs != hdrInfo::NOT_IN_EPILOG);
// _ASSERTE(flags & ActiveStackFrame); // <TODO> Wont work for thread death</TODO>
_ASSERTE(info->epilogOffs > 0);
if (info->ebpFrame || info->doubleAlign)
{
UnwindEbpDoubleAlignFrameEpilog(pContext, info, epilogBase, flags);
}
else
{
UnwindEspFrameEpilog(pContext, info, epilogBase, flags);
}
#ifdef _DEBUG
if (flags & UpdateAllRegs)
TRASH_CALLEE_UNSAVED_REGS(pContext);
#endif
/* Now adjust stack pointer */
pContext->Esp += ESPIncrOnReturn(info);
}
/*****************************************************************************/
void UnwindEspFrameProlog(
PREGDISPLAY pContext,
hdrInfo * info,
PTR_CBYTE methodStart,
unsigned flags)
{
LIMITED_METHOD_CONTRACT;
SUPPORTS_DAC;
/* we are in the middle of the prolog */
_ASSERTE(info->prologOffs != hdrInfo::NOT_IN_PROLOG);
_ASSERTE(!info->ebpFrame && !info->doubleAlign);
unsigned offset = 0;
#ifdef _DEBUG
// If the first two instructions are 'nop, int3', then we will
// assume that is from a JitHalt operation and skip past it
if (methodStart[0] == X86_INSTR_NOP && methodStart[1] == X86_INSTR_INT3)
{
offset += 2;
}
#endif
const DWORD curOffs = info->prologOffs;
unsigned ESP = pContext->Esp;
// Find out how many callee-saved regs have already been pushed
unsigned regsMask = RM_NONE;
PTR_DWORD savedRegPtr = PTR_DWORD((TADDR)ESP);
for (unsigned i = 0; i < NumItems(CALLEE_SAVED_REGISTERS_MASK); i++)
{
RegMask regMask = CALLEE_SAVED_REGISTERS_MASK[i];
if (!(info->savedRegMask & regMask))
continue;
if (InstructionAlreadyExecuted(offset, curOffs))
{
ESP += sizeof(void*);
regsMask |= regMask;
}
offset = SKIP_PUSH_REG(methodStart, offset);
}
if (info->rawStkSize)
{
offset = SKIP_ALLOC_FRAME(info->rawStkSize, methodStart, offset);
// Note that this assumes that only the last instruction in SKIP_ALLOC_FRAME
// actually updates ESP
if (InstructionAlreadyExecuted(offset, curOffs + 1))
{
savedRegPtr += (info->rawStkSize / sizeof(DWORD));
ESP += info->rawStkSize;
}
}
//
// Stack probe checks here
//
// Poison the value, we don't set it properly at the end of the prolog
INDEBUG(offset = 0xCCCCCCCC);
// Always restore EBP
if (regsMask & RM_EBP)
pContext->pEbp = savedRegPtr++;
if (flags & UpdateAllRegs)
{
if (regsMask & RM_EBX)
pContext->pEbx = savedRegPtr++;
if (regsMask & RM_ESI)
pContext->pEsi = savedRegPtr++;
if (regsMask & RM_EDI)
pContext->pEdi = savedRegPtr++;
TRASH_CALLEE_UNSAVED_REGS(pContext);
}
#if 0
// NOTE:
// THIS IS ONLY TRUE IF PROLOGSIZE DOES NOT INCLUDE REG-VAR INITIALIZATION !!!!
//
/* there is (potentially) only one additional
instruction in the prolog, (push ebp)
but if we would have been passed that instruction,
info->prologOffs would be hdrInfo::NOT_IN_PROLOG!
*/
_ASSERTE(offset == info->prologOffs);
#endif
pContext->Esp = ESP;
}
/*****************************************************************************/
void UnwindEspFrame(
PREGDISPLAY pContext,
hdrInfo * info,
PTR_CBYTE table,
PTR_CBYTE methodStart,
DWORD curOffs,
unsigned flags)
{
LIMITED_METHOD_CONTRACT;
SUPPORTS_DAC;
_ASSERTE(!info->ebpFrame && !info->doubleAlign);
_ASSERTE(info->epilogOffs == hdrInfo::NOT_IN_EPILOG);
unsigned ESP = pContext->Esp;
if (info->prologOffs != hdrInfo::NOT_IN_PROLOG)
{
if (info->prologOffs != 0) // Do nothing for the very start of the method
{
UnwindEspFrameProlog(pContext, info, methodStart, flags);
ESP = pContext->Esp;
}
}
else
{
/* we are past the prolog, ESP has been set above */
// Are there any arguments pushed on the stack?
ESP += GetPushedArgSize(info, table, curOffs);
ESP += info->rawStkSize;
const RegMask regsMask = info->savedRegMask;
for (unsigned i = NumItems(CALLEE_SAVED_REGISTERS_MASK); i > 0; i--)
{
RegMask regMask = CALLEE_SAVED_REGISTERS_MASK[i - 1];
if ((regMask & regsMask) == 0)
continue;
SIZE_T offsetOfRegPtr = REGDISPLAY_OFFSET_OF_CALLEE_SAVED_REGISTERS[i - 1];
*(LPVOID*)(PBYTE(pContext) + offsetOfRegPtr) = PTR_DWORD((TADDR)ESP);
ESP += sizeof(unsigned);
}
}
/* we can now set the (address of the) return address */
pContext->PCTAddr = (TADDR)ESP;
pContext->ControlPC = *PTR_PCODE(pContext->PCTAddr);
/* Now adjust stack pointer */
pContext->Esp = ESP + ESPIncrOnReturn(info);
}
/*****************************************************************************/
void UnwindEbpDoubleAlignFrameProlog(
PREGDISPLAY pContext,
hdrInfo * info,
PTR_CBYTE methodStart,
unsigned flags)
{
LIMITED_METHOD_DAC_CONTRACT;
_ASSERTE(info->prologOffs != hdrInfo::NOT_IN_PROLOG);
_ASSERTE(info->ebpFrame || info->doubleAlign);
DWORD offset = 0;
#ifdef _DEBUG
// If the first two instructions are 'nop, int3', then we will
// assume that is from a JitHalt operation and skip past it
if (methodStart[0] == X86_INSTR_NOP && methodStart[1] == X86_INSTR_INT3)
{
offset += 2;
}
#endif
/* Check for the case where EBP has not been updated yet. */
const DWORD curOffs = info->prologOffs;
// If we have still not excecuted "push ebp; mov ebp, esp", then we need to
// report the frame relative to ESP
if (!InstructionAlreadyExecuted(offset + 1, curOffs))
{
_ASSERTE(CheckInstrByte(methodStart [offset], X86_INSTR_PUSH_EBP) ||
CheckInstrWord(*PTR_WORD(methodStart + offset), X86_INSTR_W_MOV_EBP_ESP) ||
CheckInstrByte(methodStart [offset], X86_INSTR_JMP_NEAR_REL32)); // a rejit jmp-stamp
/* If we're past the "push ebp", adjust ESP to pop EBP off */
if (curOffs == (offset + 1))
pContext->Esp += sizeof(TADDR);
/* Stack pointer points to return address */
pContext->PCTAddr = (TADDR)pContext->Esp;
pContext->ControlPC = *PTR_PCODE(pContext->PCTAddr);
/* EBP and callee-saved registers still have the correct value */
return;
}
// We are atleast after the "push ebp; mov ebp, esp"
offset = SKIP_MOV_REG_REG(methodStart,
SKIP_PUSH_REG(methodStart, offset));
/* At this point, EBP has been set up. The caller's ESP and the return value
can be determined using EBP. Since we are still in the prolog,
we need to know our exact location to determine the callee-saved registers */
const unsigned curEBP = *pContext->pEbp;
if (flags & UpdateAllRegs)
{
PTR_DWORD pSavedRegs = PTR_DWORD((TADDR)curEBP);
/* make sure that we align ESP just like the method's prolog did */
if (info->doubleAlign)
{
// "and esp,-8"
offset = SKIP_ARITH_REG(-8, methodStart, offset);
if (curEBP & 0x04)
{
pSavedRegs--;
#ifdef _DEBUG
if (dspPtr) printf("EnumRef: dblalign ebp: %08X\n", curEBP);
#endif
}
}
/* Increment "offset" in steps to see which callee-saved
registers have been pushed already */
for (unsigned i = 0; i < NumItems(CALLEE_SAVED_REGISTERS_MASK) - 1; i++)
{
RegMask regMask = CALLEE_SAVED_REGISTERS_MASK[i];
_ASSERTE(regMask != RM_EBP);
if ((info->savedRegMask & regMask) == 0)
continue;
if (InstructionAlreadyExecuted(offset, curOffs))
{
SIZE_T offsetOfRegPtr = REGDISPLAY_OFFSET_OF_CALLEE_SAVED_REGISTERS[i];
*(LPVOID*)(PBYTE(pContext) + offsetOfRegPtr) = --pSavedRegs;
}
// "push reg"
offset = SKIP_PUSH_REG(methodStart, offset) ;
}
TRASH_CALLEE_UNSAVED_REGS(pContext);
}
/* The caller's saved EBP is pointed to by our EBP */
pContext->pEbp = PTR_DWORD((TADDR)curEBP);
pContext->Esp = DWORD((TADDR)(curEBP + sizeof(void *)));
/* Stack pointer points to return address */
pContext->PCTAddr = (TADDR)pContext->Esp;
pContext->ControlPC = *PTR_PCODE(pContext->PCTAddr);
}
/*****************************************************************************/
bool UnwindEbpDoubleAlignFrame(
PREGDISPLAY pContext,
hdrInfo * info,
PTR_CBYTE methodStart,
unsigned flags,
StackwalkCacheUnwindInfo *pUnwindInfo) // out-only, perf improvement
{
LIMITED_METHOD_CONTRACT;
SUPPORTS_DAC;
_ASSERTE(info->ebpFrame || info->doubleAlign);
const unsigned curESP = pContext->Esp;
const unsigned curEBP = *pContext->pEbp;
/* First check if we are in a filter (which is obviously after the prolog) */
if (info->handlers && info->prologOffs == hdrInfo::NOT_IN_PROLOG)
{
TADDR baseSP;
FrameType frameType = GetHandlerFrameInfo(info, curEBP,
curESP, (DWORD) IGNORE_VAL,
&baseSP);
/* If we are in a filter, we only need to unwind the funclet stack.
For catches/finallies, the normal handling will
cause the frame to be unwound all the way up to ebp skipping
other frames above it. This is OK, as those frames will be
dead. Also, the EE will detect that this has happened and it
will handle any EE frames correctly.
*/
if (frameType == FR_INVALID)
{
return false;
}
if (frameType == FR_FILTER)
{
pContext->PCTAddr = baseSP;
pContext->ControlPC = *PTR_PCODE(pContext->PCTAddr);
pContext->Esp = (DWORD)(baseSP + sizeof(TADDR));
// pContext->pEbp = same as before;
#ifdef _DEBUG
/* The filter has to be called by the VM. So we dont need to
update callee-saved registers.
*/
if (flags & UpdateAllRegs)
{
static DWORD s_badData = 0xDEADBEEF;
pContext->pEax = pContext->pEbx = pContext->pEcx =
pContext->pEdx = pContext->pEsi = pContext->pEdi = &s_badData;
}
#endif
if (pUnwindInfo)
{
// The filter funclet is like an ESP-framed-method.
pUnwindInfo->fUseEbp = FALSE;
pUnwindInfo->fUseEbpAsFrameReg = FALSE;
}
return true;
}
}
//
// Prolog of an EBP method
//
if (info->prologOffs != hdrInfo::NOT_IN_PROLOG)
{
UnwindEbpDoubleAlignFrameProlog(pContext, info, methodStart, flags);
/* Now adjust stack pointer. */
pContext->Esp += ESPIncrOnReturn(info);
return true;
}
if (flags & UpdateAllRegs)
{
// Get to the first callee-saved register
PTR_DWORD pSavedRegs = PTR_DWORD((TADDR)curEBP);
if (info->doubleAlign && (curEBP & 0x04))
pSavedRegs--;
for (unsigned i = 0; i < NumItems(CALLEE_SAVED_REGISTERS_MASK) - 1; i++)
{
RegMask regMask = CALLEE_SAVED_REGISTERS_MASK[i];
if ((info->savedRegMask & regMask) == 0)
continue;
SIZE_T offsetOfRegPtr = REGDISPLAY_OFFSET_OF_CALLEE_SAVED_REGISTERS[i];
*(LPVOID*)(PBYTE(pContext) + offsetOfRegPtr) = --pSavedRegs;
}
}
/* The caller's ESP will be equal to EBP + retAddrSize + argSize. */
pContext->Esp = (DWORD)(curEBP + sizeof(curEBP) + ESPIncrOnReturn(info));
/* The caller's saved EIP is right after our EBP */
pContext->PCTAddr = (TADDR)curEBP + RETURN_ADDR_OFFS * sizeof(TADDR);
pContext->ControlPC = *PTR_PCODE(pContext->PCTAddr);
/* The caller's saved EBP is pointed to by our EBP */
pContext->pEbp = PTR_DWORD((TADDR)curEBP);
return true;
}
/*****************************************************************************
*
* Unwind the current stack frame, i.e. update the virtual register
* set in pContext. This will be similar to the state after the function
* returns back to caller (IP points to after the call, Frame and Stack
* pointer has been reset, callee-saved registers restored (if UpdateAllRegs),
* callee-unsaved registers are trashed.
* Returns success of operation.
*/
bool EECodeManager::UnwindStackFrame(PREGDISPLAY pContext,
EECodeInfo *pCodeInfo,
unsigned flags,
CodeManState *pState,
StackwalkCacheUnwindInfo *pUnwindInfo /* out-only, perf improvement */)
{
CONTRACTL {
NOTHROW;
GC_NOTRIGGER;
HOST_NOCALLS;
SUPPORTS_DAC;
} CONTRACTL_END;
// Address where the method has been interrupted
PCODE breakPC = pContext->ControlPC;
_ASSERTE(PCODEToPINSTR(breakPC) == pCodeInfo->GetCodeAddress());
PTR_CBYTE methodStart = PTR_CBYTE(pCodeInfo->GetSavedMethodCode());
PTR_VOID methodInfoPtr = pCodeInfo->GetGCInfo();
DWORD curOffs = pCodeInfo->GetRelOffset();
_ASSERTE(sizeof(CodeManStateBuf) <= sizeof(pState->stateBuf));
CodeManStateBuf * stateBuf = (CodeManStateBuf*)pState->stateBuf;
if (pState->dwIsSet == 0)
{
/* Extract the necessary information from the info block header */
stateBuf->hdrInfoSize = (DWORD)crackMethodInfoHdr(methodInfoPtr,
curOffs,
&stateBuf->hdrInfoBody);
}
PTR_CBYTE table = dac_cast<PTR_CBYTE>(methodInfoPtr) + stateBuf->hdrInfoSize;
hdrInfo * info = &stateBuf->hdrInfoBody;
info->isSpeculativeStackWalk = ((flags & SpeculativeStackwalk) != 0);
if (pUnwindInfo != NULL)
{
pUnwindInfo->securityObjectOffset = 0;
if (info->securityCheck)
{
_ASSERTE(info->ebpFrame);
SIZE_T securityObjectOffset = (GetSecurityObjectOffset(info) / sizeof(void*));
_ASSERTE(securityObjectOffset != 0);
pUnwindInfo->securityObjectOffset = DWORD(securityObjectOffset);
}
pUnwindInfo->fUseEbpAsFrameReg = info->ebpFrame;
pUnwindInfo->fUseEbp = ((info->savedRegMask & RM_EBP) != 0);
}
if (info->epilogOffs != hdrInfo::NOT_IN_EPILOG)
{
/*---------------------------------------------------------------------
* First, handle the epilog
*/
PTR_CBYTE epilogBase = (PTR_CBYTE) (breakPC - info->epilogOffs);
UnwindEpilog(pContext, info, epilogBase, flags);
}
else if (!info->ebpFrame && !info->doubleAlign)
{
/*---------------------------------------------------------------------
* Now handle ESP frames
*/
UnwindEspFrame(pContext, info, table, methodStart, curOffs, flags);
return true;
}
else
{
/*---------------------------------------------------------------------
* Now we know that have an EBP frame
*/
if (!UnwindEbpDoubleAlignFrame(pContext, info, methodStart, flags, pUnwindInfo))
return false;
}
// TODO [DAVBR]: For the full fix for VsWhidbey 450273, all the below
// may be uncommented once isLegalManagedCodeCaller works properly
// with non-return address inputs, and with non-DEBUG builds
/*
// Ensure isLegalManagedCodeCaller succeeds for speculative stackwalks.
// (We just assert this below for non-speculative stackwalks.)
//
FAIL_IF_SPECULATIVE_WALK(isLegalManagedCodeCaller(GetControlPC(pContext)));
*/
return true;
}
/*****************************************************************************/
#elif !defined(CROSSGEN_COMPILE) // _TARGET_X86_ - UnwindStackFrame
/*****************************************************************************/
bool EECodeManager::UnwindStackFrame(PREGDISPLAY pContext,
EECodeInfo *pCodeInfo,
unsigned flags,
CodeManState *pState,
StackwalkCacheUnwindInfo *pUnwindInfo /* out-only, perf improvement */)
{
CONTRACTL {
NOTHROW;
GC_NOTRIGGER;
} CONTRACTL_END;
#if defined(_TARGET_AMD64_)
// To avoid unnecessary computation, we only crack the unwind info if pUnwindInfo is not NULL, which only happens
// if the LIGHTUNWIND flag is passed to StackWalkFramesEx().
if (pUnwindInfo != NULL)
{
pCodeInfo->GetOffsetsFromUnwindInfo(&(pUnwindInfo->RSPOffsetFromUnwindInfo),
&(pUnwindInfo->RBPOffset));
}
#endif // _TARGET_AMD64_
_ASSERTE(pCodeInfo != NULL);
Thread::VirtualUnwindCallFrame(pContext, pCodeInfo);
return true;
}
/*****************************************************************************/
#else // _TARGET_X86_ - UnwindStackFrame
bool EECodeManager::UnwindStackFrame(PREGDISPLAY pContext,
EECodeInfo *pCodeInfo,
unsigned flags,
CodeManState *pState,
StackwalkCacheUnwindInfo *pUnwindInfo /* out-only, perf improvement */)
{
_ASSERTE(!"EECodeManager::UnwindStackFrame not supported in this build configuration");
return true;
}
#endif // _TARGET_X86_ - UnwindStackFrame
/*****************************************************************************/
/* report args in 'msig' to the GC.
'argsStart' is start of the stack-based arguments
'varArgSig' describes the arguments
'ctx' has the GC reporting info
*/
void promoteVarArgs(PTR_BYTE argsStart, PTR_VASigCookie varArgSig, GCCONTEXT* ctx)
{
WRAPPER_NO_CONTRACT;
//Note: no instantiations needed for varargs
MetaSig msig(varArgSig->signature,
varArgSig->pModule,
NULL);
PTR_BYTE pFrameBase = argsStart - TransitionBlock::GetOffsetOfArgs();
ArgIterator argit(&msig);
#ifdef _TARGET_X86_
// For the X86 target the JIT does not report any of the fixed args for a varargs method
// So we report the fixed args via the promoteArgs call below
bool skipFixedArgs = false;
#else
// For other platforms the JITs do report the fixed args of a varargs method
// So we must tell promoteArgs to skip to the end of the fixed args
bool skipFixedArgs = true;
#endif
bool inVarArgs = false;
int argOffset;
while ((argOffset = argit.GetNextOffset()) != TransitionBlock::InvalidOffset)
{
if (msig.GetArgProps().AtSentinel())
inVarArgs = true;
// if skipFixedArgs is false we report all arguments
// otherwise we just report the varargs.
if (!skipFixedArgs || inVarArgs)
msig.GcScanRoots(pFrameBase + argOffset, ctx->f, ctx->sc);
}
}
INDEBUG(void* forceStack1;)
#if defined(_TARGET_X86_)
/*****************************************************************************
*
* Enumerate all live object references in that function using
* the virtual register set.
* Returns success of operation.
*/
bool EECodeManager::EnumGcRefs( PREGDISPLAY pContext,
EECodeInfo *pCodeInfo,
unsigned flags,
GCEnumCallback pCallBack,
LPVOID hCallBack,
DWORD relOffsetOverride)
{
CONTRACTL {
NOTHROW;
GC_NOTRIGGER;
} CONTRACTL_END;
PTR_VOID methodInfoPtr = pCodeInfo->GetGCInfo();
unsigned curOffs = pCodeInfo->GetRelOffset();
unsigned EBP = *pContext->pEbp;
unsigned ESP = pContext->Esp;
unsigned ptrOffs;
unsigned count;
hdrInfo info;
PTR_CBYTE table = PTR_CBYTE(methodInfoPtr);
#if 0
printf("EECodeManager::EnumGcRefs - EIP = %08x ESP = %08x offset = %x GC Info is at %08x\n", *pContext->pPC, ESP, curOffs, table);
#endif
/* Extract the necessary information from the info block header */
table += crackMethodInfoHdr(methodInfoPtr,
curOffs,
&info);
_ASSERTE( curOffs <= info.methodSize);
#ifdef _DEBUG
// if ((methodInfoPtr == (void*)0x37760d0) && (curOffs == 0x264))
// __asm int 3;
if (trEnumGCRefs) {
static unsigned lastESP = 0;
unsigned diffESP = ESP - lastESP;
if (diffESP > 0xFFFF) {
printf("------------------------------------------------------\n");
}
lastESP = ESP;
printf("EnumGCRefs [%s][%s] at %s.%s + 0x%03X:\n",
info.ebpFrame?"ebp":" ",
info.interruptible?"int":" ",
"UnknownClass","UnknownMethod", curOffs);
fflush(stdout);
}
#endif
/* Are we in the prolog or epilog of the method? */
if (info.prologOffs != hdrInfo::NOT_IN_PROLOG ||
info.epilogOffs != hdrInfo::NOT_IN_EPILOG)
{
#if !DUMP_PTR_REFS
// Under normal circumstances the system will not suspend a thread
// if it is in the prolog or epilog of the function. However ThreadAbort
// exception or stack overflows can cause EH to happen in a prolog.
// Once in the handler, a GC can happen, so we can get to this code path.
// However since we are tearing down this frame, we don't need to report
// anything and we can simply return.
_ASSERTE(flags & ExecutionAborted);
#endif
return true;
}
#ifdef _DEBUG
#define CHK_AND_REPORT_REG(reg, doIt, iptr, regName) \
if (doIt) \
{ \
if (dspPtr) \
printf(" Live pointer register %s: ", #regName); \
pCallBack(hCallBack, \
(OBJECTREF*)(pContext->p##regName), \
(iptr ? GC_CALL_INTERIOR : 0) \
| CHECK_APP_DOMAIN \
DAC_ARG(DacSlotLocation(reg, 0, false))); \
}
#else // !_DEBUG
#define CHK_AND_REPORT_REG(reg, doIt, iptr, regName) \
if (doIt) \
pCallBack(hCallBack, \
(OBJECTREF*)(pContext->p##regName), \
(iptr ? GC_CALL_INTERIOR : 0) \
| CHECK_APP_DOMAIN \
DAC_ARG(DacSlotLocation(reg, 0, false)));
#endif // _DEBUG
/* What kind of a frame is this ? */
FrameType frameType = FR_NORMAL;
TADDR baseSP = 0;
if (info.handlers)
{
_ASSERTE(info.ebpFrame);
bool hasInnerFilter, hadInnerFilter;
frameType = GetHandlerFrameInfo(&info, EBP,
ESP, (DWORD) IGNORE_VAL,
&baseSP, NULL,
&hasInnerFilter, &hadInnerFilter);
_ASSERTE(frameType != FR_INVALID);
/* If this is the parent frame of a filter which is currently
executing, then the filter would have enumerated the frame using
the filter PC.
*/
if (hasInnerFilter)
return true;
/* If are in a try and we had a filter execute, we may have reported
GC refs from the filter (and not using the try's offset). So
we had better use the filter's end offset, as the try is
effectively dead and its GC ref's would be stale */
if (hadInnerFilter)
{
PTR_TADDR pFirstBaseSPslot = GetFirstBaseSPslotPtr(EBP, &info);
curOffs = (unsigned)pFirstBaseSPslot[1] - 1;
_ASSERTE(curOffs < info.methodSize);
/* Extract the necessary information from the info block header */
table = PTR_CBYTE(methodInfoPtr);
table += crackMethodInfoHdr(methodInfoPtr,
curOffs,
&info);
}
}
bool willContinueExecution = !(flags & ExecutionAborted);
unsigned pushedSize = 0;
/* if we have been interrupted we don't have to report registers/arguments
* because we are about to lose this context anyway.
* Alas, if we are in a ebp-less method we have to parse the table
* in order to adjust ESP.
*
* Note that we report "this" for all methods, even if
* noncontinuable, because because of the off chance they may be
* synchronized and we have to release the monitor on unwind. This
* could conceivably be optimized, but it turns out to be more
* expensive to check whether we're synchronized (which involves
* consulting metadata) than to just report "this" all the time in
* our most important scenarios.
*/
if (info.interruptible)
{
pushedSize = scanArgRegTableI(skipToArgReg(info, table), curOffs, &info);
RegMask regs = info.regMaskResult;
RegMask iregs = info.iregMaskResult;
ptrArgTP args = info.argMaskResult;
ptrArgTP iargs = info.iargMaskResult;
_ASSERTE((isZero(args) || pushedSize != 0) || info.ebpFrame);
_ASSERTE((args & iargs) == iargs);
// Only synchronized methods and generic code that accesses
// the type context via "this" need to report "this".
// If its reported for other methods, its probably
// done incorrectly. So flag such cases.
_ASSERTE(info.thisPtrResult == REGI_NA ||
pCodeInfo->GetMethodDesc()->IsSynchronized() ||
pCodeInfo->GetMethodDesc()->AcquiresInstMethodTableFromThis());
/* now report registers and arguments if we are not interrupted */
if (willContinueExecution)
{
/* Propagate unsafed registers only in "current" method */
/* If this is not the active method, then the callee wil
* trash these registers, and so we wont need to report them */
if (flags & ActiveStackFrame)
{
CHK_AND_REPORT_REG(REGI_EAX, regs & RM_EAX, iregs & RM_EAX, Eax);
CHK_AND_REPORT_REG(REGI_ECX, regs & RM_ECX, iregs & RM_ECX, Ecx);
CHK_AND_REPORT_REG(REGI_EDX, regs & RM_EDX, iregs & RM_EDX, Edx);
}
CHK_AND_REPORT_REG(REGI_EBX, regs & RM_EBX, iregs & RM_EBX, Ebx);
CHK_AND_REPORT_REG(REGI_EBP, regs & RM_EBP, iregs & RM_EBP, Ebp);
CHK_AND_REPORT_REG(REGI_ESI, regs & RM_ESI, iregs & RM_ESI, Esi);
CHK_AND_REPORT_REG(REGI_EDI, regs & RM_EDI, iregs & RM_EDI, Edi);
_ASSERTE(!(regs & RM_ESP));
/* Report any pending pointer arguments */
DWORD * pPendingArgFirst; // points **AT** first parameter
if (!info.ebpFrame)
{
// -sizeof(void*) because we want to point *AT* first parameter
pPendingArgFirst = (DWORD *)(size_t)(ESP + pushedSize - sizeof(void*));
}
else
{
_ASSERTE(willContinueExecution);
if (info.handlers)
{
// -sizeof(void*) because we want to point *AT* first parameter
pPendingArgFirst = (DWORD *)(size_t)(baseSP - sizeof(void*));
}
else if (info.localloc)
{
baseSP = *(DWORD *)(size_t)(EBP - GetLocallocSPOffset(&info));
// -sizeof(void*) because we want to point *AT* first parameter
pPendingArgFirst = (DWORD *)(size_t) (baseSP - sizeof(void*));
}
else
{
// Note that 'info.stackSize includes the size for pushing EBP, but EBP is pushed
// BEFORE EBP is set from ESP, thus (EBP - info.stackSize) actually points past
// the frame by one DWORD, and thus points *AT* the first parameter
pPendingArgFirst = (DWORD *)(size_t)(EBP - info.stackSize);
}
}
if (!isZero(args))
{
unsigned i = 0;
ptrArgTP b(1);
for (; !isZero(args) && (i < MAX_PTRARG_OFS); i += 1, b <<= 1)
{
if (intersect(args,b))
{
unsigned argAddr = (unsigned)(size_t)(pPendingArgFirst - i);
bool iptr = false;
setDiff(args, b);
if (intersect(iargs,b))
{
setDiff(iargs, b);
iptr = true;
}
#ifdef _DEBUG
if (dspPtr)
{
printf(" Pushed ptr arg [E");
if (info.ebpFrame)
printf("BP-%02XH]: ", EBP - argAddr);
else
printf("SP+%02XH]: ", argAddr - ESP);
}
#endif
_ASSERTE(true == GC_CALL_INTERIOR);
pCallBack(hCallBack, (OBJECTREF *)(size_t)argAddr, (int)iptr | CHECK_APP_DOMAIN
DAC_ARG(DacSlotLocation(info.ebpFrame ? REGI_EBP : REGI_ESP,
info.ebpFrame ? EBP - argAddr : argAddr - ESP,
true)));
}
}
}
}
else
{
// Is "this" enregistered. If so, report it as we might need to
// release the monitor for synchronized methods.
// Else, it is on the stack and will be reported below.
if (info.thisPtrResult != REGI_NA)
{
// Synchronized methods and methods satisfying
// MethodDesc::AcquiresInstMethodTableFromThis (i.e. those
// where "this" is reported in thisPtrResult) are
// not supported on value types.
_ASSERTE((regNumToMask(info.thisPtrResult) & info.iregMaskResult)== 0);
void * thisReg = getCalleeSavedReg(pContext, info.thisPtrResult);
pCallBack(hCallBack, (OBJECTREF *)thisReg, CHECK_APP_DOMAIN
DAC_ARG(DacSlotLocation(info.thisPtrResult, 0, false)));
}
}
}
else /* not interruptible */
{
pushedSize = scanArgRegTable(skipToArgReg(info, table), curOffs, &info);
RegMask regMask = info.regMaskResult;
RegMask iregMask = info.iregMaskResult;
ptrArgTP argMask = info.argMaskResult;
ptrArgTP iargMask = info.iargMaskResult;
unsigned argHnum = info.argHnumResult;
PTR_CBYTE argTab = info.argTabResult;
// Only synchronized methods and generic code that accesses
// the type context via "this" need to report "this".
// If its reported for other methods, its probably
// done incorrectly. So flag such cases.
_ASSERTE(info.thisPtrResult == REGI_NA ||
pCodeInfo->GetMethodDesc()->IsSynchronized() ||
pCodeInfo->GetMethodDesc()->AcquiresInstMethodTableFromThis());
/* now report registers and arguments if we are not interrupted */
if (willContinueExecution)
{
/* Report all live pointer registers */
CHK_AND_REPORT_REG(REGI_EDI, regMask & RM_EDI, iregMask & RM_EDI, Edi);
CHK_AND_REPORT_REG(REGI_ESI, regMask & RM_ESI, iregMask & RM_ESI, Esi);
CHK_AND_REPORT_REG(REGI_EBX, regMask & RM_EBX, iregMask & RM_EBX, Ebx);
CHK_AND_REPORT_REG(REGI_EBP, regMask & RM_EBP, iregMask & RM_EBP, Ebp);
/* Esp cant be reported */
_ASSERTE(!(regMask & RM_ESP));
/* No callee-trashed registers */
_ASSERTE(!(regMask & RM_CALLEE_TRASHED));
/* EBP can't be reported unless we have an EBP-less frame */
_ASSERTE(!(regMask & RM_EBP) || !(info.ebpFrame));
/* Report any pending pointer arguments */
if (argTab != 0)
{
unsigned lowBits, stkOffs, argAddr, val;
// argMask does not fit in 32-bits
// thus arguments are reported via a table
// Both of these are very rare cases
do
{
val = fastDecodeUnsigned(argTab);
lowBits = val & OFFSET_MASK;
stkOffs = val & ~OFFSET_MASK;
_ASSERTE((lowBits == 0) || (lowBits == byref_OFFSET_FLAG));
argAddr = ESP + stkOffs;
#ifdef _DEBUG
if (dspPtr)
printf(" Pushed %sptr arg at [ESP+%02XH]",
lowBits ? "iptr " : "", stkOffs);
#endif
_ASSERTE(byref_OFFSET_FLAG == GC_CALL_INTERIOR);
pCallBack(hCallBack, (OBJECTREF *)(size_t)argAddr, lowBits | CHECK_APP_DOMAIN
DAC_ARG(DacSlotLocation(REGI_ESP, stkOffs, true)));
}
while(--argHnum);
_ASSERTE(info.argTabResult + info.argTabBytes == argTab);
}
else
{
unsigned argAddr = ESP;
while (!isZero(argMask))
{
_ASSERTE(argHnum-- > 0);
if (toUnsigned(argMask) & 1)
{
bool iptr = false;
if (toUnsigned(iargMask) & 1)
iptr = true;
#ifdef _DEBUG
if (dspPtr)
printf(" Pushed ptr arg at [ESP+%02XH]",
argAddr - ESP);
#endif
_ASSERTE(true == GC_CALL_INTERIOR);
pCallBack(hCallBack, (OBJECTREF *)(size_t)argAddr, (int)iptr | CHECK_APP_DOMAIN
DAC_ARG(DacSlotLocation(REGI_ESP, argAddr - ESP, true)));
}
argMask >>= 1;
iargMask >>= 1;
argAddr += 4;
}
}
}
else
{
// Is "this" enregistered. If so, report it as we will need to
// release the monitor. Else, it is on the stack and will be
// reported below.
// For partially interruptible code, info.thisPtrResult will be
// the last known location of "this". So the compiler needs to
// generate information which is correct at every point in the code,
// not just at call sites.
if (info.thisPtrResult != REGI_NA)
{
// Synchronized methods on value types are not supported
_ASSERTE((regNumToMask(info.thisPtrResult) & info.iregMaskResult)== 0);
void * thisReg = getCalleeSavedReg(pContext, info.thisPtrResult);
pCallBack(hCallBack, (OBJECTREF *)thisReg, CHECK_APP_DOMAIN
DAC_ARG(DacSlotLocation(info.thisPtrResult, 0, false)));
}
}
} //info.interruptible
/* compute the argument base (reference point) */
unsigned argBase;
if (info.ebpFrame)
argBase = EBP;
else
argBase = ESP + pushedSize;
#if VERIFY_GC_TABLES
_ASSERTE(*castto(table, unsigned short *)++ == 0xBEEF);
#endif
unsigned ptrAddr;
unsigned lowBits;
/* Process the untracked frame variable table */
count = info.untrackedCnt;
int lastStkOffs = 0;
while (count-- > 0)
{
int stkOffs = fastDecodeSigned(table);
stkOffs = lastStkOffs - stkOffs;
lastStkOffs = stkOffs;
_ASSERTE(0 == ~OFFSET_MASK % sizeof(void*));
lowBits = OFFSET_MASK & stkOffs;
stkOffs &= ~OFFSET_MASK;
ptrAddr = argBase + stkOffs;
if (info.doubleAlign && stkOffs >= int(info.stackSize - sizeof(void*))) {
// We encode the arguments as if they were ESP based variables even though they aren't
// If this frame would have ben an ESP based frame, This fake frame is one DWORD
// smaller than the real frame because it did not push EBP but the real frame did.
// Thus to get the correct EBP relative offset we have to ajust by info.stackSize-sizeof(void*)
ptrAddr = EBP + (stkOffs-(info.stackSize - sizeof(void*)));
}
#ifdef _DEBUG
if (dspPtr)
{
printf(" Untracked %s%s local at [E",
(lowBits & pinned_OFFSET_FLAG) ? "pinned " : "",
(lowBits & byref_OFFSET_FLAG) ? "byref" : "");
int dspOffs = ptrAddr;
char frameType;
if (info.ebpFrame) {
dspOffs -= EBP;
frameType = 'B';
}
else {
dspOffs -= ESP;
frameType = 'S';
}
if (dspOffs < 0)
printf("%cP-%02XH]: ", frameType, -dspOffs);
else
printf("%cP+%02XH]: ", frameType, +dspOffs);
}
#endif
_ASSERTE((pinned_OFFSET_FLAG == GC_CALL_PINNED) &&
(byref_OFFSET_FLAG == GC_CALL_INTERIOR));
pCallBack(hCallBack, (OBJECTREF*)(size_t)ptrAddr, lowBits | CHECK_APP_DOMAIN
DAC_ARG(DacSlotLocation(info.ebpFrame ? REGI_EBP : REGI_ESP,
info.ebpFrame ? EBP - ptrAddr : ptrAddr - ESP,
true)));
}
#if VERIFY_GC_TABLES
_ASSERTE(*castto(table, unsigned short *)++ == 0xCAFE);
#endif
/* Process the frame variable lifetime table */
count = info.varPtrTableSize;
/* If we are not in the active method, we are currently pointing
* to the return address; at the return address stack variables
* can become dead if the call the last instruction of a try block
* and the return address is the jump around the catch block. Therefore
* we simply assume an offset inside of call instruction.
*/
unsigned newCurOffs;
if (willContinueExecution)
{
newCurOffs = (flags & ActiveStackFrame) ? curOffs // after "call"
: curOffs-1; // inside "call"
}
else
{
/* However if ExecutionAborted, then this must be one of the
* ExceptionFrames. Handle accordingly
*/
_ASSERTE(!(flags & AbortingCall) || !(flags & ActiveStackFrame));
newCurOffs = (flags & AbortingCall) ? curOffs-1 // inside "call"
: curOffs; // at faulting instr, or start of "try"
}
ptrOffs = 0;
while (count-- > 0)
{
int stkOffs;
unsigned begOffs;
unsigned endOffs;
stkOffs = fastDecodeUnsigned(table);
begOffs = ptrOffs + fastDecodeUnsigned(table);
endOffs = begOffs + fastDecodeUnsigned(table);
_ASSERTE(0 == ~OFFSET_MASK % sizeof(void*));
lowBits = OFFSET_MASK & stkOffs;
stkOffs &= ~OFFSET_MASK;
if (info.ebpFrame) {
stkOffs = -stkOffs;
_ASSERTE(stkOffs < 0);
}
else {
_ASSERTE(stkOffs >= 0);
}
ptrAddr = argBase + stkOffs;
/* Is this variable live right now? */
if (newCurOffs >= begOffs)
{
if (newCurOffs < endOffs)
{
#ifdef _DEBUG
if (dspPtr) {
printf(" Frame %s%s local at [E",
(lowBits & byref_OFFSET_FLAG) ? "byref " : "",
(lowBits & this_OFFSET_FLAG) ? "this-ptr" : "");
int dspOffs = ptrAddr;
char frameType;
if (info.ebpFrame) {
dspOffs -= EBP;
frameType = 'B';
}
else {
dspOffs -= ESP;
frameType = 'S';
}
if (dspOffs < 0)
printf("%cP-%02XH]: ", frameType, -dspOffs);
else
printf("%cP+%02XH]: ", frameType, +dspOffs);
}
#endif
_ASSERTE(byref_OFFSET_FLAG == GC_CALL_INTERIOR);
pCallBack(hCallBack, (OBJECTREF*)(size_t)ptrAddr, (lowBits & byref_OFFSET_FLAG) | CHECK_APP_DOMAIN
DAC_ARG(DacSlotLocation(info.ebpFrame ? REGI_EBP : REGI_ESP,
info.ebpFrame ? EBP - ptrAddr : ptrAddr - ESP,
true)));
}
}
// exit loop early if start of live range is beyond PC, as ranges are sorted by lower bound
else break;
ptrOffs = begOffs;
}
#if VERIFY_GC_TABLES
_ASSERTE(*castto(table, unsigned short *)++ == 0xBABE);
#endif
/* Are we a varargs function, if so we have to report all args
except 'this' (note that the GC tables created by the x86 jit
do not contain ANY arguments except 'this' (even if they
were statically declared */
if (info.varargs) {
LOG((LF_GCINFO, LL_INFO100, "Reporting incoming vararg GC refs\n"));
PTR_BYTE argsStart;
if (info.ebpFrame || info.doubleAlign)
argsStart = PTR_BYTE((size_t)EBP) + 2* sizeof(void*); // pushed EBP and retAddr
else
argsStart = PTR_BYTE((size_t)argBase) + info.stackSize + sizeof(void*); // ESP + locals + retAddr
#if defined(_DEBUG) && !defined(DACCESS_COMPILE) && !defined(CROSSGEN_COMPILE)
// Note that I really want to say hCallBack is a GCCONTEXT, but this is pretty close
extern void GcEnumObject(LPVOID pData, OBJECTREF *pObj, DWORD flags);
_ASSERTE((void*) GcEnumObject == pCallBack);
#endif
GCCONTEXT *pCtx = (GCCONTEXT *) hCallBack;
// For varargs, look up the signature using the varArgSig token passed on the stack
PTR_VASigCookie varArgSig = *PTR_PTR_VASigCookie(argsStart);
promoteVarArgs(argsStart, varArgSig, pCtx);
}
return true;
}
#elif defined(USE_GC_INFO_DECODER) && !defined(CROSSGEN_COMPILE) // !defined(_TARGET_X86_)
/*****************************************************************************
*
* Enumerate all live object references in that function using
* the virtual register set.
* Returns success of operation.
*/
bool EECodeManager::EnumGcRefs( PREGDISPLAY pRD,
EECodeInfo *pCodeInfo,
unsigned flags,
GCEnumCallback pCallBack,
LPVOID hCallBack,
DWORD relOffsetOverride)
{
CONTRACTL {
NOTHROW;
GC_NOTRIGGER;
} CONTRACTL_END;
unsigned curOffs = pCodeInfo->GetRelOffset();
#ifdef _TARGET_ARM_
// On ARM, the low-order bit of an instruction pointer indicates Thumb vs. ARM mode.
// Mask this off; all instructions are two-byte aligned.
curOffs &= (~THUMB_CODE);
#endif // _TARGET_ARM_
#ifdef _DEBUG
// Get the name of the current method
const char * methodName = pCodeInfo->GetMethodDesc()->GetName();
LOG((LF_GCINFO, LL_INFO1000, "Reporting GC refs for %s at offset %04x.\n",
methodName, curOffs));
#endif
PTR_BYTE gcInfoAddr = dac_cast<PTR_BYTE>(pCodeInfo->GetGCInfo());
#if defined(STRESS_HEAP) && defined(PARTIALLY_INTERRUPTIBLE_GC_SUPPORTED)
#ifdef USE_GC_INFO_DECODER
// When we simulate a hijack during gcstress
// we start with ActiveStackFrame and the offset
// after the call
// We need to make it look like a non-leaf frame
// so that it's treated like a regular hijack
if (flags & ActiveStackFrame)
{
GcInfoDecoder _gcInfoDecoder(
gcInfoAddr,
DECODE_INTERRUPTIBILITY,
curOffs
);
if(!_gcInfoDecoder.IsInterruptible())
{
// This must be the offset after a call
#ifdef _DEBUG
GcInfoDecoder _safePointDecoder(gcInfoAddr, (GcInfoDecoderFlags)0, 0);
_ASSERTE(_safePointDecoder.IsSafePoint(curOffs));
#endif
flags &= ~((unsigned)ActiveStackFrame);
}
}
#endif // USE_GC_INFO_DECODER
#endif // STRESS_HEAP && PARTIALLY_INTERRUPTIBLE_GC_SUPPORTED
#ifdef _DEBUG
if (flags & ActiveStackFrame)
{
GcInfoDecoder _gcInfoDecoder(
gcInfoAddr,
DECODE_INTERRUPTIBILITY,
curOffs
);
_ASSERTE(_gcInfoDecoder.IsInterruptible());
}
#endif
#ifdef USE_GC_INFO_DECODER
/* If we are not in the active method, we are currently pointing
* to the return address; at the return address stack variables
* can become dead if the call is the last instruction of a try block
* and the return address is the jump around the catch block. Therefore
* we simply assume an offset inside of call instruction.
* NOTE: The GcInfoDecoder depends on this; if you change it, you must
* revisit the GcInfoEncoder/Decoder
*/
if (!(flags & ExecutionAborted))
{
if (!(flags & ActiveStackFrame))
{
curOffs--;
LOG((LF_GCINFO, LL_INFO1000, "Adjusted GC reporting offset due to flags !ExecutionAborted && !ActiveStackFrame. Now reporting GC refs for %s at offset %04x.\n",
methodName, curOffs));
}
}
else
{
/* However if ExecutionAborted, then this must be one of the
* ExceptionFrames. Handle accordingly
*/
_ASSERTE(!(flags & AbortingCall) || !(flags & ActiveStackFrame));
if (flags & AbortingCall)
{
curOffs--;
LOG((LF_GCINFO, LL_INFO1000, "Adjusted GC reporting offset due to flags ExecutionAborted && AbortingCall. Now reporting GC refs for %s at offset %04x.\n",
methodName, curOffs));
}
}
// Check if we have been given an override value for relOffset
if (relOffsetOverride != NO_OVERRIDE_OFFSET)
{
// We've been given an override offset for GC Info
#ifdef _DEBUG
GcInfoDecoder _gcInfoDecoder(
gcInfoAddr,
DECODE_CODE_LENGTH,
0
);
// We only use override offset for wantsReportOnlyLeaf
_ASSERTE(_gcInfoDecoder.WantsReportOnlyLeaf());
#endif // _DEBUG
curOffs = relOffsetOverride;
#ifdef _TARGET_ARM_
// On ARM, the low-order bit of an instruction pointer indicates Thumb vs. ARM mode.
// Mask this off; all instructions are two-byte aligned.
curOffs &= (~THUMB_CODE);
#endif // _TARGET_ARM_
LOG((LF_GCINFO, LL_INFO1000, "Adjusted GC reporting offset to provided override offset. Now reporting GC refs for %s at offset %04x.\n",
methodName, curOffs));
}
#endif // USE_GC_INFO_DECODER
#if defined(WIN64EXCEPTIONS) // funclets
if (pCodeInfo->GetJitManager()->IsFilterFunclet(pCodeInfo))
{
// Filters are the only funclet that run during the 1st pass, and must have
// both the leaf and the parent frame reported. In order to avoid double
// reporting of the untracked variables, do not report them for the filter.
flags |= NoReportUntracked;
}
#endif // WIN64EXCEPTIONS
bool reportScratchSlots;
// We report scratch slots only for leaf frames.
// A frame is non-leaf if we are executing a call, or a fault occurred in the function.
// The only case in which we need to report scratch slots for a non-leaf frame
// is when execution has to be resumed at the point of interruption (via ResumableFrame)
//<TODO>Implement ResumableFrame</TODO>
_ASSERTE( sizeof( BOOL ) >= sizeof( ActiveStackFrame ) );
reportScratchSlots = (flags & ActiveStackFrame) != 0;
GcInfoDecoder gcInfoDecoder(
gcInfoAddr,
GcInfoDecoderFlags (DECODE_GC_LIFETIMES | DECODE_SECURITY_OBJECT | DECODE_VARARG),
curOffs
);
if (!gcInfoDecoder.EnumerateLiveSlots(
pRD,
reportScratchSlots,
flags,
pCallBack,
hCallBack
))
{
return false;
}
#ifdef WIN64EXCEPTIONS // funclets
//
// If we're in a funclet, we do not want to report the incoming varargs. This is
// taken care of by the parent method and the funclet should access those arguments
// by way of the parent method's stack frame.
//
if(pCodeInfo->IsFunclet())
{
return true;
}
#endif // WIN64EXCEPTIONS
if (gcInfoDecoder.GetIsVarArg())
{
MethodDesc* pMD = pCodeInfo->GetMethodDesc();
_ASSERTE(pMD != NULL);
// This does not apply to x86 because of how it handles varargs (it never
// reports the arguments from the explicit method signature).
//
#ifndef _TARGET_X86_
//
// SPECIAL CASE:
// IL marshaling stubs have signatures that are marked as vararg,
// but they are callsite sigs that actually contain complete sig
// info. There are two reasons for this:
// 1) the stub callsites expect the method to be vararg
// 2) the marshaling stub must have full sig info so that
// it can do a ldarg.N on the arguments it needs to marshal.
// The result of this is that the code below will report the
// variable arguments twice--once from the va sig cookie and once
// from the explicit method signature (in the method's gc info).
//
// This fix to this is to early out of the va sig cookie reporting
// in this special case.
//
if (pMD->IsILStub())
{
return true;
}
#endif // !_TARGET_X86_
LOG((LF_GCINFO, LL_INFO100, "Reporting incoming vararg GC refs\n"));
// Find the offset of the VASigCookie. It's offsets are relative to
// the base of a FramedMethodFrame.
int VASigCookieOffset;
{
MetaSig msigFindVASig(pMD);
ArgIterator argit(&msigFindVASig);
VASigCookieOffset = argit.GetVASigCookieOffset() - TransitionBlock::GetOffsetOfArgs();
}
PTR_BYTE prevSP = dac_cast<PTR_BYTE>(GetCallerSp(pRD));
_ASSERTE(prevSP + VASigCookieOffset >= dac_cast<PTR_BYTE>(GetSP(pRD->pCurrentContext)));
#if defined(_DEBUG) && !defined(DACCESS_COMPILE) && !defined(CROSSGEN_COMPILE)
// Note that I really want to say hCallBack is a GCCONTEXT, but this is pretty close
extern void GcEnumObject(LPVOID pData, OBJECTREF *pObj, DWORD flags);
_ASSERTE((void*) GcEnumObject == pCallBack);
#endif
GCCONTEXT *pCtx = (GCCONTEXT *) hCallBack;
// For varargs, look up the signature using the varArgSig token passed on the stack
PTR_VASigCookie varArgSig = *PTR_PTR_VASigCookie(prevSP + VASigCookieOffset);
promoteVarArgs(prevSP, varArgSig, pCtx);
}
return true;
}
#else // !defined(_TARGET_X86_) && !(defined(USE_GC_INFO_DECODER) && !defined(CROSSGEN_COMPILE))
bool EECodeManager::EnumGcRefs( PREGDISPLAY pContext,
EECodeInfo *pCodeInfo,
unsigned flags,
GCEnumCallback pCallBack,
LPVOID hCallBack,
DWORD relOffsetOverride)
{
PORTABILITY_ASSERT("EECodeManager::EnumGcRefs is not implemented on this platform.");
return false;
}
#endif // _TARGET_X86_
/*****************************************************************************
*
* Return the address of the local security object reference
* using data that was previously cached before in UnwindStackFrame
* using StackwalkCacheUnwindInfo
*/
OBJECTREF* EECodeManager::GetAddrOfSecurityObjectFromCachedInfo(PREGDISPLAY pRD, StackwalkCacheUnwindInfo * stackwalkCacheUnwindInfo)
{
LIMITED_METHOD_CONTRACT;
#ifdef _TARGET_X86_
size_t securityObjectOffset = stackwalkCacheUnwindInfo->securityObjectOffset;
_ASSERTE(securityObjectOffset != 0);
// We pretend that filters are ESP-based methods in UnwindEbpDoubleAlignFrame().
// Hence we cannot enforce this assert.
// _ASSERTE(stackwalkCacheUnwindInfo->fUseEbpAsFrameReg);
return (OBJECTREF *) (size_t) (DWORD(*pRD->pEbp) - (securityObjectOffset * sizeof(void*)));
#else
PORTABILITY_ASSERT("EECodeManager::GetAddrOfSecurityObjectFromContext is not implemented on this platform.");
return NULL;
#endif
}
#ifndef DACCESS_COMPILE
OBJECTREF* EECodeManager::GetAddrOfSecurityObject(CrawlFrame *pCF)
{
CONTRACTL {
NOTHROW;
GC_NOTRIGGER;
} CONTRACTL_END;
REGDISPLAY* pRD = pCF->GetRegisterSet();
IJitManager* pJitMan = pCF->GetJitManager();
METHODTOKEN methodToken = pCF->GetMethodToken();
unsigned relOffset = pCF->GetRelOffset();
CodeManState* pState = pCF->GetCodeManState();
PTR_VOID methodInfoPtr = pJitMan->GetGCInfo(methodToken);
_ASSERTE(sizeof(CodeManStateBuf) <= sizeof(pState->stateBuf));
#if defined(_TARGET_X86_)
CodeManStateBuf * stateBuf = (CodeManStateBuf*)pState->stateBuf;
/* Extract the necessary information from the info block header */
stateBuf->hdrInfoSize = (DWORD)crackMethodInfoHdr(methodInfoPtr, // <TODO>truncation</TODO>
relOffset,
&stateBuf->hdrInfoBody);
pState->dwIsSet = 1;
if (stateBuf->hdrInfoBody.securityCheck)
{
_ASSERTE(stateBuf->hdrInfoBody.ebpFrame);
if(stateBuf->hdrInfoBody.prologOffs == hdrInfo::NOT_IN_PROLOG &&
stateBuf->hdrInfoBody.epilogOffs == hdrInfo::NOT_IN_EPILOG)
{
return (OBJECTREF *)(size_t)(((DWORD)*pRD->pEbp) - GetSecurityObjectOffset(&stateBuf->hdrInfoBody));
}
}
#elif defined(USE_GC_INFO_DECODER) && !defined(CROSSGEN_COMPILE)
BYTE* gcInfoAddr = (BYTE*) methodInfoPtr;
GcInfoDecoder gcInfoDecoder(
gcInfoAddr,
DECODE_SECURITY_OBJECT,
0
);
INT32 spOffset = gcInfoDecoder.GetSecurityObjectStackSlot();
if( spOffset != NO_SECURITY_OBJECT )
{
UINT_PTR uCallerSP = GetCallerSp(pRD);
if (pCF->IsFunclet())
{
if (!pCF->IsFilterFunclet())
{
// Cannot retrieve the security object for a non-filter funclet.
return NULL;
}
DWORD dwParentOffset = 0;
UINT_PTR uParentCallerSP = 0;
// If this is a filter funclet, retrieve the information of the parent method
// and use that to find the security object.
ExceptionTracker::FindParentStackFrameEx(pCF, &dwParentOffset, &uParentCallerSP);
relOffset = dwParentOffset;
uCallerSP = uParentCallerSP;
}
// Security object is always live anyplace we can throw or take a GC
OBJECTREF* pSlot = (OBJECTREF*) (spOffset + uCallerSP);
return pSlot;
}
#else // !_TARGET_X86_ && !(USE_GC_INFO_DECODER && !CROSSGEN_COMPILE)
PORTABILITY_ASSERT("EECodeManager::GetAddrOfSecurityObject is not implemented on this platform.");
#endif
return NULL;
}
#endif
/*****************************************************************************
*
* Returns "this" pointer if it is a non-static method
* AND the object is still alive.
* Returns NULL in all other cases.
* Unfortunately, the semantics of this call currently depend on the architecture.
* On non-x86 architectures, where we use GcInfo{En,De}Coder, this returns NULL for
* all cases except the case where the GenericsContext is determined via "this." On x86,
* it will definitely return a non-NULL value in that case, and for synchronized methods;
* it may also return a non-NULL value for other cases, depending on how the method is compiled.
*/
OBJECTREF EECodeManager::GetInstance( PREGDISPLAY pContext,
EECodeInfo* pCodeInfo)
{
CONTRACTL {
NOTHROW;
GC_NOTRIGGER;
MODE_COOPERATIVE;
SUPPORTS_DAC;
} CONTRACTL_END;
#ifdef _TARGET_X86_
PTR_VOID methodInfoPtr = pCodeInfo->GetGCInfo();
unsigned relOffset = pCodeInfo->GetRelOffset();
PTR_CBYTE table = PTR_CBYTE(methodInfoPtr);
hdrInfo info;
unsigned stackDepth;
TADDR taArgBase;
unsigned count;
/* Extract the necessary information from the info block header */
table += crackMethodInfoHdr(methodInfoPtr,
relOffset,
&info);
// We do not have accurate information in the prolog or the epilog
if (info.prologOffs != hdrInfo::NOT_IN_PROLOG ||
info.epilogOffs != hdrInfo::NOT_IN_EPILOG)
{
return NULL;
}
if (info.interruptible)
{
stackDepth = scanArgRegTableI(skipToArgReg(info, table), (unsigned)relOffset, &info);
}
else
{
stackDepth = scanArgRegTable (skipToArgReg(info, table), (unsigned)relOffset, &info);
}
if (info.ebpFrame)
{
_ASSERTE(stackDepth == 0);
taArgBase = *pContext->pEbp;
}
else
{
taArgBase = pContext->Esp + stackDepth;
}
// Only synchronized methods and generic code that accesses
// the type context via "this" need to report "this".
// If it's reported for other methods, it's probably
// done incorrectly. So flag such cases.
_ASSERTE(info.thisPtrResult == REGI_NA ||
pCodeInfo->GetMethodDesc()->IsSynchronized() ||
pCodeInfo->GetMethodDesc()->AcquiresInstMethodTableFromThis());
if (info.thisPtrResult != REGI_NA)
{
// the register contains the Object pointer.
TADDR uRegValue = *(reinterpret_cast<TADDR *>(getCalleeSavedReg(pContext, info.thisPtrResult)));
return ObjectToOBJECTREF(PTR_Object(uRegValue));
}
#if VERIFY_GC_TABLES
_ASSERTE(*castto(table, unsigned short *)++ == 0xBEEF);
#endif
/* Parse the untracked frame variable table */
/* The 'this' pointer can never be located in the untracked table */
/* as we only allow pinned and byrefs in the untracked table */
count = info.untrackedCnt;
while (count-- > 0)
{
fastSkipSigned(table);
}
/* Look for the 'this' pointer in the frame variable lifetime table */
count = info.varPtrTableSize;
unsigned tmpOffs = 0;
while (count-- > 0)
{
unsigned varOfs = fastDecodeUnsigned(table);
unsigned begOfs = tmpOffs + fastDecodeUnsigned(table);
unsigned endOfs = begOfs + fastDecodeUnsigned(table);
_ASSERTE(!info.ebpFrame || (varOfs!=0));
/* Is this variable live right now? */
if (((unsigned)relOffset >= begOfs) && ((unsigned)relOffset < endOfs))
{
/* Does it contain the 'this' pointer */
if (varOfs & this_OFFSET_FLAG)
{
unsigned ofs = varOfs & ~OFFSET_MASK;
/* Tracked locals for EBP frames are always at negative offsets */
if (info.ebpFrame)
taArgBase -= ofs;
else
taArgBase += ofs;
return (OBJECTREF)(size_t)(*PTR_DWORD(taArgBase));
}
}
tmpOffs = begOfs;
}
#if VERIFY_GC_TABLES
_ASSERTE(*castto(table, unsigned short *) == 0xBABE);
#endif
return NULL;
#elif defined(USE_GC_INFO_DECODER) && !defined(CROSSGEN_COMPILE)
PTR_VOID token = EECodeManager::GetExactGenericsToken(pContext, pCodeInfo);
OBJECTREF oRef = ObjectToOBJECTREF(PTR_Object(dac_cast<TADDR>(token)));
VALIDATEOBJECTREF(oRef);
return oRef;
#else // !_TARGET_X86_ && !(USE_GC_INFO_DECODER && !CROSSGEN_COMPILE)
PORTABILITY_ASSERT("Port: EECodeManager::GetInstance is not implemented on this platform.");
return NULL;
#endif // _TARGET_X86_
}
GenericParamContextType EECodeManager::GetParamContextType(PREGDISPLAY pContext,
EECodeInfo * pCodeInfo)
{
WRAPPER_NO_CONTRACT;
SUPPORTS_DAC;
#ifdef _TARGET_X86_
/* Extract the necessary information from the info block header */
PTR_VOID methodInfoPtr = pCodeInfo->GetGCInfo();
unsigned relOffset = pCodeInfo->GetRelOffset();
hdrInfo info;
PTR_CBYTE table = PTR_CBYTE(methodInfoPtr);
table += crackMethodInfoHdr(methodInfoPtr,
relOffset,
&info);
if (!info.genericsContext ||
info.prologOffs != hdrInfo::NOT_IN_PROLOG ||
info.epilogOffs != hdrInfo::NOT_IN_EPILOG)
{
return GENERIC_PARAM_CONTEXT_NONE;
}
else if (info.genericsContextIsMethodDesc)
{
return GENERIC_PARAM_CONTEXT_METHODDESC;
}
else
{
return GENERIC_PARAM_CONTEXT_METHODTABLE;
}
// On x86 the generic param context parameter is never this.
#elif defined(USE_GC_INFO_DECODER)
PTR_VOID methodInfoPtr = pCodeInfo->GetGCInfo();
PTR_CBYTE gcInfoAddr = PTR_CBYTE(methodInfoPtr);
GcInfoDecoder gcInfoDecoder(
gcInfoAddr,
GcInfoDecoderFlags (DECODE_GENERICS_INST_CONTEXT),
0
);
INT32 spOffsetGenericsContext = gcInfoDecoder.GetGenericsInstContextStackSlot();
if (spOffsetGenericsContext != NO_GENERICS_INST_CONTEXT)
{
if (gcInfoDecoder.HasMethodDescGenericsInstContext())
{
return GENERIC_PARAM_CONTEXT_METHODDESC;
}
else if (gcInfoDecoder.HasMethodTableGenericsInstContext())
{
return GENERIC_PARAM_CONTEXT_METHODTABLE;
}
return GENERIC_PARAM_CONTEXT_THIS;
}
return GENERIC_PARAM_CONTEXT_NONE;
#else // !_TARGET_X86_ && !USE_GC_INFO_DECODER
PORTABILITY_ASSERT("Port: EECodeManager::GetParamContextType is not implemented on this platform.");
return GENERIC_PARAM_CONTEXT_NONE;
#endif // _TARGET_X86_
}
/*****************************************************************************
*
* Returns the extra argument passed to to shared generic code if it is still alive.
* Returns NULL in all other cases.
*/
PTR_VOID EECodeManager::GetParamTypeArg(PREGDISPLAY pContext,
EECodeInfo * pCodeInfo)
{
WRAPPER_NO_CONTRACT;
SUPPORTS_DAC;
#ifdef _TARGET_X86_
PTR_VOID methodInfoPtr = pCodeInfo->GetGCInfo();
unsigned relOffset = pCodeInfo->GetRelOffset();
/* Extract the necessary information from the info block header */
hdrInfo info;
PTR_CBYTE table = PTR_CBYTE(methodInfoPtr);
table += crackMethodInfoHdr(methodInfoPtr,
relOffset,
&info);
if (!info.genericsContext ||
info.prologOffs != hdrInfo::NOT_IN_PROLOG ||
info.epilogOffs != hdrInfo::NOT_IN_EPILOG)
{
return NULL;
}
TADDR fp = GetRegdisplayFP(pContext);
TADDR taParamTypeArg = *PTR_TADDR(fp - GetParamTypeArgOffset(&info));
return PTR_VOID(taParamTypeArg);
#elif defined(USE_GC_INFO_DECODER) && !defined(CROSSGEN_COMPILE)
return EECodeManager::GetExactGenericsToken(pContext, pCodeInfo);
#else // !_TARGET_X86_ && !(USE_GC_INFO_DECODER && !CROSSGEN_COMPILE)
PORTABILITY_ASSERT("Port: EECodeManager::GetInstance is not implemented on this platform.");
return NULL;
#endif // _TARGET_X86_
}
#if defined(WIN64EXCEPTIONS) && !defined(CROSSGEN_COMPILE)
/*
Returns the generics token. This is used by GetInstance() and GetParamTypeArg() on WIN64.
*/
//static
PTR_VOID EECodeManager::GetExactGenericsToken(PREGDISPLAY pContext,
EECodeInfo * pCodeInfo)
{
WRAPPER_NO_CONTRACT;
SUPPORTS_DAC;
return EECodeManager::GetExactGenericsToken(GetCallerSp(pContext), pCodeInfo);
}
//static
PTR_VOID EECodeManager::GetExactGenericsToken(SIZE_T baseStackSlot,
EECodeInfo * pCodeInfo)
{
WRAPPER_NO_CONTRACT;
SUPPORTS_DAC;
PTR_VOID methodInfoPtr = pCodeInfo->GetGCInfo();
PTR_CBYTE gcInfoAddr = PTR_CBYTE(methodInfoPtr);
GcInfoDecoder gcInfoDecoder(
gcInfoAddr,
GcInfoDecoderFlags (DECODE_PSP_SYM | DECODE_GENERICS_INST_CONTEXT),
0
);
INT32 spOffsetGenericsContext = gcInfoDecoder.GetGenericsInstContextStackSlot();
if (spOffsetGenericsContext != NO_GENERICS_INST_CONTEXT)
{
TADDR taSlot;
if (pCodeInfo->IsFunclet())
{
INT32 spOffsetPSPSym = gcInfoDecoder.GetPSPSymStackSlot();
_ASSERTE(spOffsetPSPSym != NO_PSP_SYM);
#ifdef _TARGET_AMD64_
// On AMD64 the spOffsetPSPSym is relative to the "Initial SP": the stack
// pointer at the end of the prolog before and dynamic allocations, so it
// can be the same for funclets and the main function.
// However, we have a caller SP, so we need to convert
baseStackSlot -= pCodeInfo->GetFixedStackSize();
#endif // _TARGET_AMD64_
// For funclets we have to do an extra dereference to get the PSPSym first.
TADDR newBaseStackSlot = *PTR_TADDR(baseStackSlot + spOffsetPSPSym);
#ifdef _TARGET_AMD64_
// On AMD64 the PSPSym stores the "Initial SP": the stack pointer at the end of
// prolog, before any dynamic allocations.
// However, the GenericsContext offset is relative to the caller SP for all
// platforms. So here we adjust to convert AMD64's initial sp to a caller SP.
// But we have to be careful to use the main function's EECodeInfo, not the
// funclet's EECodeInfo because they have different stack sizes!
newBaseStackSlot += pCodeInfo->GetMainFunctionInfo().GetFixedStackSize();
#endif // _TARGET_AMD64_
taSlot = (TADDR)( spOffsetGenericsContext + newBaseStackSlot );
}
else
{
taSlot = (TADDR)( spOffsetGenericsContext + baseStackSlot );
}
TADDR taExactGenericsToken = *PTR_TADDR(taSlot);
return PTR_VOID(taExactGenericsToken);
}
return NULL;
}
#endif // WIN64EXCEPTIONS / CROSSGEN_COMPILE
/*****************************************************************************/
void * EECodeManager::GetGSCookieAddr(PREGDISPLAY pContext,
EECodeInfo * pCodeInfo,
CodeManState * pState)
{
CONTRACTL {
NOTHROW;
GC_NOTRIGGER;
} CONTRACTL_END;
_ASSERTE(sizeof(CodeManStateBuf) <= sizeof(pState->stateBuf));
PTR_VOID methodInfoPtr = pCodeInfo->GetGCInfo();
unsigned relOffset = pCodeInfo->GetRelOffset();
#if defined(_TARGET_X86_)
CodeManStateBuf * stateBuf = (CodeManStateBuf*)pState->stateBuf;
/* Extract the necessary information from the info block header */
hdrInfo * info = &stateBuf->hdrInfoBody;
stateBuf->hdrInfoSize = (DWORD)crackMethodInfoHdr(methodInfoPtr, // <TODO>truncation</TODO>
relOffset,
info);
pState->dwIsSet = 1;
if (info->prologOffs != hdrInfo::NOT_IN_PROLOG ||
info->epilogOffs != hdrInfo::NOT_IN_EPILOG ||
info->gsCookieOffset == INVALID_GS_COOKIE_OFFSET)
{
return NULL;
}
if (info->ebpFrame)
{
return PVOID(SIZE_T((DWORD(*pContext->pEbp) - info->gsCookieOffset)));
}
else
{
PTR_CBYTE table = PTR_CBYTE(methodInfoPtr) + stateBuf->hdrInfoSize;
unsigned argSize = GetPushedArgSize(info, table, relOffset);
return PVOID(SIZE_T(pContext->Esp + argSize + info->gsCookieOffset));
}
#elif defined(USE_GC_INFO_DECODER) && !defined(CROSSGEN_COMPILE)
PTR_CBYTE gcInfoAddr = PTR_CBYTE(methodInfoPtr);
if (pCodeInfo->IsFunclet())
{
return NULL;
}
GcInfoDecoder gcInfoDecoder(
gcInfoAddr,
DECODE_GS_COOKIE,
0
);
INT32 spOffsetGSCookie = gcInfoDecoder.GetGSCookieStackSlot();
if (spOffsetGSCookie != NO_GS_COOKIE)
{
if(relOffset >= gcInfoDecoder.GetGSCookieValidRangeStart()
&& relOffset < gcInfoDecoder.GetGSCookieValidRangeEnd())
{
SIZE_T baseStackSlot = GetCallerSp(pContext);
return (LPVOID)( spOffsetGSCookie + baseStackSlot );
}
}
return NULL;
#else
PORTABILITY_WARNING("EECodeManager::GetGSCookieAddr is not implemented on this platform.");
return NULL;
#endif
}
/*****************************************************************************
*
* Returns true if the given IP is in the given method's prolog or epilog.
*/
bool EECodeManager::IsInPrologOrEpilog(DWORD relPCoffset,
PTR_VOID methodInfoPtr,
size_t* prologSize)
{
CONTRACTL {
NOTHROW;
GC_NOTRIGGER;
} CONTRACTL_END;
#ifndef USE_GC_INFO_DECODER
hdrInfo info;
crackMethodInfoHdr(methodInfoPtr, relPCoffset, &info);
if (prologSize)
*prologSize = info.prologSize;
return ((info.prologOffs != hdrInfo::NOT_IN_PROLOG) ||
(info.epilogOffs != hdrInfo::NOT_IN_EPILOG));
#else // USE_GC_INFO_DECODER
_ASSERTE(!"@NYI - EECodeManager::IsInPrologOrEpilog (EETwain.cpp)");
return false;
#endif // USE_GC_INFO_DECODER
}
/*****************************************************************************
*
* Returns true if the given IP is in the synchronized region of the method (valid for synchronized functions only)
*/
bool EECodeManager::IsInSynchronizedRegion(
DWORD relOffset,
PTR_VOID methodInfoPtr,
unsigned flags)
{
CONTRACTL {
NOTHROW;
GC_NOTRIGGER;
} CONTRACTL_END;
#ifndef USE_GC_INFO_DECODER
hdrInfo info;
crackMethodInfoHdr(methodInfoPtr, relOffset, &info);
// We should be called only for synchronized methods
_ASSERTE(info.syncStartOffset != INVALID_SYNC_OFFSET && info.syncEndOffset != INVALID_SYNC_OFFSET);
_ASSERTE(info.syncStartOffset < info.syncEndOffset);
_ASSERTE(info.epilogCnt <= 1);
_ASSERTE(info.epilogCnt == 0 || info.syncEndOffset <= info.syncEpilogStart);
return (info.syncStartOffset < relOffset && relOffset < info.syncEndOffset) ||
(info.syncStartOffset == relOffset && (flags & (ActiveStackFrame|ExecutionAborted))) ||
// Synchronized methods have at most one epilog. The epilog does not have to be at the end of the method though.
// Everything after the epilog is also in synchronized region.
(info.epilogCnt != 0 && info.syncEpilogStart + info.epilogSize <= relOffset);
#else // USE_GC_INFO_DECODER
_ASSERTE(!"@NYI - EECodeManager::IsInSynchronizedRegion (EETwain.cpp)");
return false;
#endif // USE_GC_INFO_DECODER
}
/*****************************************************************************
*
* Returns the size of a given function.
*/
size_t EECodeManager::GetFunctionSize(PTR_VOID methodInfoPtr)
{
CONTRACTL {
NOTHROW;
GC_NOTRIGGER;
SUPPORTS_DAC;
} CONTRACTL_END;
#if defined(_TARGET_X86_)
hdrInfo info;
crackMethodInfoHdr(methodInfoPtr, 0, &info);
return info.methodSize;
#elif defined(USE_GC_INFO_DECODER)
PTR_BYTE gcInfoAddr = PTR_BYTE(methodInfoPtr);
GcInfoDecoder gcInfoDecoder(
gcInfoAddr,
DECODE_CODE_LENGTH,
0
);
UINT32 codeLength = gcInfoDecoder.GetCodeLength();
_ASSERTE( codeLength > 0 );
return codeLength;
#else // !_TARGET_X86_ && !USE_GC_INFO_DECODER
PORTABILITY_ASSERT("EECodeManager::GetFunctionSize is not implemented on this platform.");
return 0;
#endif
}
/*****************************************************************************
*
* Returns the size of the frame of the given function.
*/
unsigned int EECodeManager::GetFrameSize(PTR_VOID methodInfoPtr)
{
CONTRACTL {
NOTHROW;
GC_NOTRIGGER;
} CONTRACTL_END;
#ifndef USE_GC_INFO_DECODER
hdrInfo info;
crackMethodInfoHdr(methodInfoPtr, 0, &info);
// currently only used by E&C callers need to know about doubleAlign
// in all likelyhood
_ASSERTE(!info.doubleAlign);
return info.stackSize;
#else // USE_GC_INFO_DECODER
PORTABILITY_ASSERT("EECodeManager::GetFrameSize is not implemented on this platform.");
return false;
#endif // USE_GC_INFO_DECODER
}
#ifndef DACCESS_COMPILE
/*****************************************************************************/
const BYTE* EECodeManager::GetFinallyReturnAddr(PREGDISPLAY pReg)
{
LIMITED_METHOD_CONTRACT;
#ifdef _TARGET_X86_
return *(const BYTE**)(size_t)(GetRegdisplaySP(pReg));
#else
PORTABILITY_ASSERT("EECodeManager::GetFinallyReturnAddr is not implemented on this platform.");
return NULL;
#endif
}
BOOL EECodeManager::IsInFilter(void *methodInfoPtr,
unsigned offset,
PCONTEXT pCtx,
DWORD curNestLevel)
{
CONTRACTL {
NOTHROW;
GC_NOTRIGGER;
} CONTRACTL_END;
#ifdef _TARGET_X86_
/* Extract the necessary information from the info block header */
hdrInfo info;
crackMethodInfoHdr(methodInfoPtr,
offset,
&info);
/* make sure that we have an ebp stack frame */
_ASSERTE(info.ebpFrame);
_ASSERTE(info.handlers); // <TODO> This will alway be set. Remove it</TODO>
TADDR baseSP;
DWORD nestingLevel;
FrameType frameType = GetHandlerFrameInfo(&info, pCtx->Ebp,
pCtx->Esp, (DWORD) IGNORE_VAL,
&baseSP, &nestingLevel);
_ASSERTE(frameType != FR_INVALID);
// _ASSERTE(nestingLevel == curNestLevel);
return frameType == FR_FILTER;
#else
PORTABILITY_ASSERT("EECodeManager::IsInFilter is not implemented on this platform.");
return FALSE;
#endif
}
BOOL EECodeManager::LeaveFinally(void *methodInfoPtr,
unsigned offset,
PCONTEXT pCtx)
{
CONTRACTL {
NOTHROW;
GC_NOTRIGGER;
} CONTRACTL_END;
#ifdef _TARGET_X86_
hdrInfo info;
crackMethodInfoHdr(methodInfoPtr,
offset,
&info);
DWORD nestingLevel;
GetHandlerFrameInfo(&info, pCtx->Ebp, pCtx->Esp, (DWORD) IGNORE_VAL, NULL, &nestingLevel);
// Compute an index into the stack-based table of esp values from
// each level of catch block.
PTR_TADDR pBaseSPslots = GetFirstBaseSPslotPtr(pCtx->Ebp, &info);
PTR_TADDR pPrevSlot = pBaseSPslots - (nestingLevel - 1);
/* Currently, LeaveFinally() is not used if the finally is invoked in the
second pass for unwinding. So we expect the finally to be called locally */
_ASSERTE(*pPrevSlot == LCL_FINALLY_MARK);
*pPrevSlot = 0; // Zero out the previous shadow ESP
pCtx->Esp += sizeof(TADDR); // Pop the return value off the stack
return TRUE;
#else
PORTABILITY_ASSERT("EEJitManager::LeaveFinally is not implemented on this platform.");
return FALSE;
#endif
}
void EECodeManager::LeaveCatch(void *methodInfoPtr,
unsigned offset,
PCONTEXT pCtx)
{
CONTRACTL {
NOTHROW;
GC_NOTRIGGER;
} CONTRACTL_END;
#ifdef _TARGET_X86_
#ifdef _DEBUG
TADDR baseSP;
DWORD nestingLevel;
bool hasInnerFilter;
hdrInfo info;
crackMethodInfoHdr(methodInfoPtr, offset, &info);
GetHandlerFrameInfo(&info, pCtx->Ebp, pCtx->Esp, (DWORD) IGNORE_VAL,
&baseSP, &nestingLevel, &hasInnerFilter);
// _ASSERTE(frameType == FR_HANDLER);
// _ASSERTE(pCtx->Esp == baseSP);
#endif
return;
#else // !_TARGET_X86_
PORTABILITY_ASSERT("EECodeManager::LeaveCatch is not implemented on this platform.");
return;
#endif // _TARGET_X86_
}
#endif // #ifndef DACCESS_COMPILE
#ifdef DACCESS_COMPILE
void EECodeManager::EnumMemoryRegions(CLRDataEnumMemoryFlags flags)
{
DAC_ENUM_VTHIS();
}
#endif // #ifdef DACCESS_COMPILE
/*
* GetAmbientSP
*
* This function computes the zero-depth stack pointer for the given nesting
* level within the method given. Nesting level is the the depth within
* try-catch-finally blocks, and is zero based. It is up to the caller to
* supply a valid nesting level value.
*
*/
TADDR EECodeManager::GetAmbientSP(PREGDISPLAY pContext,
EECodeInfo *pCodeInfo,
DWORD dwRelOffset,
DWORD nestingLevel,
CodeManState *pState)
{
CONTRACTL {
NOTHROW;
GC_NOTRIGGER;
SUPPORTS_DAC;
} CONTRACTL_END;
#ifdef _TARGET_X86_
PTR_VOID methodInfoPtr = pCodeInfo->GetGCInfo();
_ASSERTE(sizeof(CodeManStateBuf) <= sizeof(pState->stateBuf));
CodeManStateBuf * stateBuf = (CodeManStateBuf*)pState->stateBuf;
PTR_CBYTE table = PTR_CBYTE(methodInfoPtr);
/* Extract the necessary information from the info block header */
stateBuf->hdrInfoSize = (DWORD)crackMethodInfoHdr(methodInfoPtr,
dwRelOffset,
&stateBuf->hdrInfoBody);
table += stateBuf->hdrInfoSize;
pState->dwIsSet = 1;
#if defined(_DEBUG) && !defined(DACCESS_COMPILE)
if (trFixContext)
{
printf("GetAmbientSP [%s][%s] for %s.%s: ",
stateBuf->hdrInfoBody.ebpFrame?"ebp":" ",
stateBuf->hdrInfoBody.interruptible?"int":" ",
"UnknownClass","UnknownMethod");
fflush(stdout);
}
#endif // _DEBUG && !DACCESS_COMPILE
if ((stateBuf->hdrInfoBody.prologOffs != hdrInfo::NOT_IN_PROLOG) ||
(stateBuf->hdrInfoBody.epilogOffs != hdrInfo::NOT_IN_EPILOG))
{
return NULL;
}
/* make sure that we have an ebp stack frame */
if (stateBuf->hdrInfoBody.handlers)
{
_ASSERTE(stateBuf->hdrInfoBody.ebpFrame);
TADDR baseSP;
GetHandlerFrameInfo(&stateBuf->hdrInfoBody,
GetRegdisplayFP(pContext),
(DWORD) IGNORE_VAL,
nestingLevel,
&baseSP);
_ASSERTE((GetRegdisplayFP(pContext) >= baseSP) && (baseSP >= GetRegdisplaySP(pContext)));
return baseSP;
}
_ASSERTE(nestingLevel == 0);
if (stateBuf->hdrInfoBody.ebpFrame)
{
return GetOutermostBaseFP(GetRegdisplayFP(pContext), &stateBuf->hdrInfoBody);
}
TADDR baseSP = GetRegdisplaySP(pContext);
if (stateBuf->hdrInfoBody.interruptible)
{
baseSP += scanArgRegTableI(skipToArgReg(stateBuf->hdrInfoBody, table),
dwRelOffset,
&stateBuf->hdrInfoBody);
}
else
{
baseSP += scanArgRegTable(skipToArgReg(stateBuf->hdrInfoBody, table),
dwRelOffset,
&stateBuf->hdrInfoBody);
}
return baseSP;
#else // !_TARGET_X86_
PORTABILITY_ASSERT("EECodeManager::GetAmbientSP is not implemented on this platform.");
return 0;
#endif // _TARGET_X86_
}
/*
Get the number of bytes used for stack parameters.
This is currently only used on x86.
*/
// virtual
ULONG32 EECodeManager::GetStackParameterSize(EECodeInfo * pCodeInfo)
{
CONTRACTL {
NOTHROW;
GC_NOTRIGGER;
SUPPORTS_DAC;
} CONTRACTL_END;
#if defined(_TARGET_X86_)
PTR_VOID methodInfoPtr = pCodeInfo->GetGCInfo();
unsigned dwOffset = pCodeInfo->GetRelOffset();
CodeManState state;
state.dwIsSet = 0;
_ASSERTE(sizeof(CodeManStateBuf) <= sizeof(state.stateBuf));
CodeManStateBuf * pStateBuf = reinterpret_cast<CodeManStateBuf *>(state.stateBuf);
hdrInfo * pHdrInfo = &(pStateBuf->hdrInfoBody);
pStateBuf->hdrInfoSize = (DWORD)crackMethodInfoHdr(methodInfoPtr, dwOffset, pHdrInfo);
// We need to subtract 4 here because ESPIncrOnReturn() includes the stack slot containing the return
// address.
return (ULONG32)(ESPIncrOnReturn(pHdrInfo) - 4);
#else
return 0;
#endif // _TARGET_X86_
}
|