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
//! Functions for parsing and evaluating DWARF expressions.
#[cfg(feature = "read")]
use alloc::vec::Vec;
use core::mem;
use super::util::{ArrayLike, ArrayVec};
use crate::common::{DebugAddrIndex, DebugInfoOffset, Encoding, Register};
use crate::constants;
use crate::read::{Error, Reader, ReaderOffset, Result, StoreOnHeap, UnitOffset, Value, ValueType};
/// A reference to a DIE, either relative to the current CU or
/// relative to the section.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DieReference<T = usize> {
/// A CU-relative reference.
UnitRef(UnitOffset<T>),
/// A section-relative reference.
DebugInfoRef(DebugInfoOffset<T>),
}
/// A single decoded DWARF expression operation.
///
/// DWARF expression evaluation is done in two parts: first the raw
/// bytes of the next part of the expression are decoded; and then the
/// decoded operation is evaluated. This approach lets other
/// consumers inspect the DWARF expression without reimplementing the
/// decoding operation.
///
/// Multiple DWARF opcodes may decode into a single `Operation`. For
/// example, both `DW_OP_deref` and `DW_OP_xderef` are represented
/// using `Operation::Deref`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Operation<R, Offset = <R as Reader>::Offset>
where
R: Reader<Offset = Offset>,
Offset: ReaderOffset,
{
/// Dereference the topmost value of the stack.
Deref {
/// The DIE of the base type or 0 to indicate the generic type
base_type: UnitOffset<Offset>,
/// The size of the data to dereference.
size: u8,
/// True if the dereference operation takes an address space
/// argument from the stack; false otherwise.
space: bool,
},
/// Drop an item from the stack.
Drop,
/// Pick an item from the stack and push it on top of the stack.
/// This operation handles `DW_OP_pick`, `DW_OP_dup`, and
/// `DW_OP_over`.
Pick {
/// The index, from the top of the stack, of the item to copy.
index: u8,
},
/// Swap the top two stack items.
Swap,
/// Rotate the top three stack items.
Rot,
/// Take the absolute value of the top of the stack.
Abs,
/// Bitwise `and` of the top two values on the stack.
And,
/// Divide the top two values on the stack.
Div,
/// Subtract the top two values on the stack.
Minus,
/// Modulus of the top two values on the stack.
Mod,
/// Multiply the top two values on the stack.
Mul,
/// Negate the top of the stack.
Neg,
/// Bitwise `not` of the top of the stack.
Not,
/// Bitwise `or` of the top two values on the stack.
Or,
/// Add the top two values on the stack.
Plus,
/// Add a constant to the topmost value on the stack.
PlusConstant {
/// The value to add.
value: u64,
},
/// Logical left shift of the 2nd value on the stack by the number
/// of bits given by the topmost value on the stack.
Shl,
/// Right shift of the 2nd value on the stack by the number of
/// bits given by the topmost value on the stack.
Shr,
/// Arithmetic left shift of the 2nd value on the stack by the
/// number of bits given by the topmost value on the stack.
Shra,
/// Bitwise `xor` of the top two values on the stack.
Xor,
/// Branch to the target location if the top of stack is nonzero.
Bra {
/// The relative offset to the target bytecode.
target: i16,
},
/// Compare the top two stack values for equality.
Eq,
/// Compare the top two stack values using `>=`.
Ge,
/// Compare the top two stack values using `>`.
Gt,
/// Compare the top two stack values using `<=`.
Le,
/// Compare the top two stack values using `<`.
Lt,
/// Compare the top two stack values using `!=`.
Ne,
/// Unconditional branch to the target location.
Skip {
/// The relative offset to the target bytecode.
target: i16,
},
/// Push an unsigned constant value on the stack. This handles multiple
/// DWARF opcodes.
UnsignedConstant {
/// The value to push.
value: u64,
},
/// Push a signed constant value on the stack. This handles multiple
/// DWARF opcodes.
SignedConstant {
/// The value to push.
value: i64,
},
/// Indicate that this piece's location is in the given register.
///
/// Completes the piece or expression.
Register {
/// The register number.
register: Register,
},
/// Find the value of the given register, add the offset, and then
/// push the resulting sum on the stack.
RegisterOffset {
/// The register number.
register: Register,
/// The offset to add.
offset: i64,
/// The DIE of the base type or 0 to indicate the generic type
base_type: UnitOffset<Offset>,
},
/// Compute the frame base (using `DW_AT_frame_base`), add the
/// given offset, and then push the resulting sum on the stack.
FrameOffset {
/// The offset to add.
offset: i64,
},
/// No operation.
Nop,
/// Push the object address on the stack.
PushObjectAddress,
/// Evaluate a DWARF expression as a subroutine. The expression
/// comes from the `DW_AT_location` attribute of the indicated
/// DIE.
Call {
/// The DIE to use.
offset: DieReference<Offset>,
},
/// Compute the address of a thread-local variable and push it on
/// the stack.
TLS,
/// Compute the call frame CFA and push it on the stack.
CallFrameCFA,
/// Terminate a piece.
Piece {
/// The size of this piece in bits.
size_in_bits: u64,
/// The bit offset of this piece. If `None`, then this piece
/// was specified using `DW_OP_piece` and should start at the
/// next byte boundary.
bit_offset: Option<u64>,
},
/// The object has no location, but has a known constant value.
///
/// Represents `DW_OP_implicit_value`.
/// Completes the piece or expression.
ImplicitValue {
/// The implicit value to use.
data: R,
},
/// The object has no location, but its value is at the top of the stack.
///
/// Represents `DW_OP_stack_value`.
/// Completes the piece or expression.
StackValue,
/// The object is a pointer to a value which has no actual location,
/// such as an implicit value or a stack value.
///
/// Represents `DW_OP_implicit_pointer`.
/// Completes the piece or expression.
ImplicitPointer {
/// The `.debug_info` offset of the value that this is an implicit pointer into.
value: DebugInfoOffset<Offset>,
/// The byte offset into the value that the implicit pointer points to.
byte_offset: i64,
},
/// Evaluate an expression at the entry to the current subprogram, and push it on the stack.
///
/// Represents `DW_OP_entry_value`.
EntryValue {
/// The expression to be evaluated.
expression: R,
},
/// This represents a parameter that was optimized out.
///
/// The offset points to the definition of the parameter, and is
/// matched to the `DW_TAG_GNU_call_site_parameter` in the caller that also
/// points to the same definition of the parameter.
///
/// Represents `DW_OP_GNU_parameter_ref`.
ParameterRef {
/// The DIE to use.
offset: UnitOffset<Offset>,
},
/// Relocate the address if needed, and push it on the stack.
///
/// Represents `DW_OP_addr`.
Address {
/// The offset to add.
address: u64,
},
/// Read the address at the given index in `.debug_addr, relocate the address if needed,
/// and push it on the stack.
///
/// Represents `DW_OP_addrx`.
AddressIndex {
/// The index of the address in `.debug_addr`.
index: DebugAddrIndex<Offset>,
},
/// Read the address at the given index in `.debug_addr, and push it on the stack.
/// Do not relocate the address.
///
/// Represents `DW_OP_constx`.
ConstantIndex {
/// The index of the address in `.debug_addr`.
index: DebugAddrIndex<Offset>,
},
/// Interpret the value bytes as a constant of a given type, and push it on the stack.
///
/// Represents `DW_OP_const_type`.
TypedLiteral {
/// The DIE of the base type.
base_type: UnitOffset<Offset>,
/// The value bytes.
value: R,
},
/// Pop the top stack entry, convert it to a different type, and push it on the stack.
///
/// Represents `DW_OP_convert`.
Convert {
/// The DIE of the base type.
base_type: UnitOffset<Offset>,
},
/// Pop the top stack entry, reinterpret the bits in its value as a different type,
/// and push it on the stack.
///
/// Represents `DW_OP_reinterpret`.
Reinterpret {
/// The DIE of the base type.
base_type: UnitOffset<Offset>,
},
/// The index of a local in the currently executing function.
///
/// Represents `DW_OP_WASM_location 0x00`.
/// Completes the piece or expression.
WasmLocal {
/// The index of the local.
index: u32,
},
/// The index of a global.
///
/// Represents `DW_OP_WASM_location 0x01` or `DW_OP_WASM_location 0x03`.
/// Completes the piece or expression.
WasmGlobal {
/// The index of the global.
index: u32,
},
/// The index of an item on the operand stack.
///
/// Represents `DW_OP_WASM_location 0x02`.
/// Completes the piece or expression.
WasmStack {
/// The index of the stack item. 0 is the bottom of the operand stack.
index: u32,
},
}
#[derive(Debug)]
enum OperationEvaluationResult<R: Reader> {
Piece,
Incomplete,
Complete { location: Location<R> },
Waiting(EvaluationWaiting<R>, EvaluationResult<R>),
}
/// A single location of a piece of the result of a DWARF expression.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Location<R, Offset = <R as Reader>::Offset>
where
R: Reader<Offset = Offset>,
Offset: ReaderOffset,
{
/// The piece is empty. Ordinarily this means the piece has been
/// optimized away.
Empty,
/// The piece is found in a register.
Register {
/// The register number.
register: Register,
},
/// The piece is found in memory.
Address {
/// The address.
address: u64,
},
/// The piece has no location but its value is known.
Value {
/// The value.
value: Value,
},
/// The piece is represented by some constant bytes.
Bytes {
/// The value.
value: R,
},
/// The piece is a pointer to a value which has no actual location.
ImplicitPointer {
/// The `.debug_info` offset of the value that this is an implicit pointer into.
value: DebugInfoOffset<Offset>,
/// The byte offset into the value that the implicit pointer points to.
byte_offset: i64,
},
}
impl<R, Offset> Location<R, Offset>
where
R: Reader<Offset = Offset>,
Offset: ReaderOffset,
{
/// Return true if the piece is empty.
pub fn is_empty(&self) -> bool {
matches!(*self, Location::Empty)
}
}
/// The description of a single piece of the result of a DWARF
/// expression.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Piece<R, Offset = <R as Reader>::Offset>
where
R: Reader<Offset = Offset>,
Offset: ReaderOffset,
{
/// If given, the size of the piece in bits. If `None`, there
/// must be only one piece whose size is all of the object.
pub size_in_bits: Option<u64>,
/// If given, the bit offset of the piece within the location.
/// If the location is a `Location::Register` or `Location::Value`,
/// then this offset is from the least significant bit end of
/// the register or value.
/// If the location is a `Location::Address` then the offset uses
/// the bit numbering and direction conventions of the language
/// and target system.
///
/// If `None`, the piece starts at the location. If the
/// location is a register whose size is larger than the piece,
/// then placement within the register is defined by the ABI.
pub bit_offset: Option<u64>,
/// Where this piece is to be found.
pub location: Location<R, Offset>,
}
// A helper function to handle branch offsets.
fn compute_pc<R: Reader>(pc: &R, bytecode: &R, offset: i16) -> Result<R> {
let pc_offset = pc.offset_from(bytecode);
let new_pc_offset = pc_offset.wrapping_add(R::Offset::from_i16(offset));
if new_pc_offset > bytecode.len() {
Err(Error::BadBranchTarget(new_pc_offset.into_u64()))
} else {
let mut new_pc = bytecode.clone();
new_pc.skip(new_pc_offset)?;
Ok(new_pc)
}
}
fn generic_type<O: ReaderOffset>() -> UnitOffset<O> {
UnitOffset(O::from_u64(0).unwrap())
}
impl<R, Offset> Operation<R, Offset>
where
R: Reader<Offset = Offset>,
Offset: ReaderOffset,
{
/// Parse a single DWARF expression operation.
///
/// This is useful when examining a DWARF expression for reasons other
/// than direct evaluation.
///
/// `bytes` points to a the operation to decode. It should point into
/// the same array as `bytecode`, which should be the entire
/// expression.
pub fn parse(bytes: &mut R, encoding: Encoding) -> Result<Operation<R, Offset>> {
let opcode = bytes.read_u8()?;
let name = constants::DwOp(opcode);
match name {
constants::DW_OP_addr => {
let address = bytes.read_address(encoding.address_size)?;
Ok(Operation::Address { address })
}
constants::DW_OP_deref => Ok(Operation::Deref {
base_type: generic_type(),
size: encoding.address_size,
space: false,
}),
constants::DW_OP_const1u => {
let value = bytes.read_u8()?;
Ok(Operation::UnsignedConstant {
value: u64::from(value),
})
}
constants::DW_OP_const1s => {
let value = bytes.read_i8()?;
Ok(Operation::SignedConstant {
value: i64::from(value),
})
}
constants::DW_OP_const2u => {
let value = bytes.read_u16()?;
Ok(Operation::UnsignedConstant {
value: u64::from(value),
})
}
constants::DW_OP_const2s => {
let value = bytes.read_i16()?;
Ok(Operation::SignedConstant {
value: i64::from(value),
})
}
constants::DW_OP_const4u => {
let value = bytes.read_u32()?;
Ok(Operation::UnsignedConstant {
value: u64::from(value),
})
}
constants::DW_OP_const4s => {
let value = bytes.read_i32()?;
Ok(Operation::SignedConstant {
value: i64::from(value),
})
}
constants::DW_OP_const8u => {
let value = bytes.read_u64()?;
Ok(Operation::UnsignedConstant { value })
}
constants::DW_OP_const8s => {
let value = bytes.read_i64()?;
Ok(Operation::SignedConstant { value })
}
constants::DW_OP_constu => {
let value = bytes.read_uleb128()?;
Ok(Operation::UnsignedConstant { value })
}
constants::DW_OP_consts => {
let value = bytes.read_sleb128()?;
Ok(Operation::SignedConstant { value })
}
constants::DW_OP_dup => Ok(Operation::Pick { index: 0 }),
constants::DW_OP_drop => Ok(Operation::Drop),
constants::DW_OP_over => Ok(Operation::Pick { index: 1 }),
constants::DW_OP_pick => {
let value = bytes.read_u8()?;
Ok(Operation::Pick { index: value })
}
constants::DW_OP_swap => Ok(Operation::Swap),
constants::DW_OP_rot => Ok(Operation::Rot),
constants::DW_OP_xderef => Ok(Operation::Deref {
base_type: generic_type(),
size: encoding.address_size,
space: true,
}),
constants::DW_OP_abs => Ok(Operation::Abs),
constants::DW_OP_and => Ok(Operation::And),
constants::DW_OP_div => Ok(Operation::Div),
constants::DW_OP_minus => Ok(Operation::Minus),
constants::DW_OP_mod => Ok(Operation::Mod),
constants::DW_OP_mul => Ok(Operation::Mul),
constants::DW_OP_neg => Ok(Operation::Neg),
constants::DW_OP_not => Ok(Operation::Not),
constants::DW_OP_or => Ok(Operation::Or),
constants::DW_OP_plus => Ok(Operation::Plus),
constants::DW_OP_plus_uconst => {
let value = bytes.read_uleb128()?;
Ok(Operation::PlusConstant { value })
}
constants::DW_OP_shl => Ok(Operation::Shl),
constants::DW_OP_shr => Ok(Operation::Shr),
constants::DW_OP_shra => Ok(Operation::Shra),
constants::DW_OP_xor => Ok(Operation::Xor),
constants::DW_OP_bra => {
let target = bytes.read_i16()?;
Ok(Operation::Bra { target })
}
constants::DW_OP_eq => Ok(Operation::Eq),
constants::DW_OP_ge => Ok(Operation::Ge),
constants::DW_OP_gt => Ok(Operation::Gt),
constants::DW_OP_le => Ok(Operation::Le),
constants::DW_OP_lt => Ok(Operation::Lt),
constants::DW_OP_ne => Ok(Operation::Ne),
constants::DW_OP_skip => {
let target = bytes.read_i16()?;
Ok(Operation::Skip { target })
}
constants::DW_OP_lit0
| constants::DW_OP_lit1
| constants::DW_OP_lit2
| constants::DW_OP_lit3
| constants::DW_OP_lit4
| constants::DW_OP_lit5
| constants::DW_OP_lit6
| constants::DW_OP_lit7
| constants::DW_OP_lit8
| constants::DW_OP_lit9
| constants::DW_OP_lit10
| constants::DW_OP_lit11
| constants::DW_OP_lit12
| constants::DW_OP_lit13
| constants::DW_OP_lit14
| constants::DW_OP_lit15
| constants::DW_OP_lit16
| constants::DW_OP_lit17
| constants::DW_OP_lit18
| constants::DW_OP_lit19
| constants::DW_OP_lit20
| constants::DW_OP_lit21
| constants::DW_OP_lit22
| constants::DW_OP_lit23
| constants::DW_OP_lit24
| constants::DW_OP_lit25
| constants::DW_OP_lit26
| constants::DW_OP_lit27
| constants::DW_OP_lit28
| constants::DW_OP_lit29
| constants::DW_OP_lit30
| constants::DW_OP_lit31 => Ok(Operation::UnsignedConstant {
value: (opcode - constants::DW_OP_lit0.0).into(),
}),
constants::DW_OP_reg0
| constants::DW_OP_reg1
| constants::DW_OP_reg2
| constants::DW_OP_reg3
| constants::DW_OP_reg4
| constants::DW_OP_reg5
| constants::DW_OP_reg6
| constants::DW_OP_reg7
| constants::DW_OP_reg8
| constants::DW_OP_reg9
| constants::DW_OP_reg10
| constants::DW_OP_reg11
| constants::DW_OP_reg12
| constants::DW_OP_reg13
| constants::DW_OP_reg14
| constants::DW_OP_reg15
| constants::DW_OP_reg16
| constants::DW_OP_reg17
| constants::DW_OP_reg18
| constants::DW_OP_reg19
| constants::DW_OP_reg20
| constants::DW_OP_reg21
| constants::DW_OP_reg22
| constants::DW_OP_reg23
| constants::DW_OP_reg24
| constants::DW_OP_reg25
| constants::DW_OP_reg26
| constants::DW_OP_reg27
| constants::DW_OP_reg28
| constants::DW_OP_reg29
| constants::DW_OP_reg30
| constants::DW_OP_reg31 => Ok(Operation::Register {
register: Register((opcode - constants::DW_OP_reg0.0).into()),
}),
constants::DW_OP_breg0
| constants::DW_OP_breg1
| constants::DW_OP_breg2
| constants::DW_OP_breg3
| constants::DW_OP_breg4
| constants::DW_OP_breg5
| constants::DW_OP_breg6
| constants::DW_OP_breg7
| constants::DW_OP_breg8
| constants::DW_OP_breg9
| constants::DW_OP_breg10
| constants::DW_OP_breg11
| constants::DW_OP_breg12
| constants::DW_OP_breg13
| constants::DW_OP_breg14
| constants::DW_OP_breg15
| constants::DW_OP_breg16
| constants::DW_OP_breg17
| constants::DW_OP_breg18
| constants::DW_OP_breg19
| constants::DW_OP_breg20
| constants::DW_OP_breg21
| constants::DW_OP_breg22
| constants::DW_OP_breg23
| constants::DW_OP_breg24
| constants::DW_OP_breg25
| constants::DW_OP_breg26
| constants::DW_OP_breg27
| constants::DW_OP_breg28
| constants::DW_OP_breg29
| constants::DW_OP_breg30
| constants::DW_OP_breg31 => {
let value = bytes.read_sleb128()?;
Ok(Operation::RegisterOffset {
register: Register((opcode - constants::DW_OP_breg0.0).into()),
offset: value,
base_type: generic_type(),
})
}
constants::DW_OP_regx => {
let register = bytes.read_uleb128().and_then(Register::from_u64)?;
Ok(Operation::Register { register })
}
constants::DW_OP_fbreg => {
let value = bytes.read_sleb128()?;
Ok(Operation::FrameOffset { offset: value })
}
constants::DW_OP_bregx => {
let register = bytes.read_uleb128().and_then(Register::from_u64)?;
let offset = bytes.read_sleb128()?;
Ok(Operation::RegisterOffset {
register,
offset,
base_type: generic_type(),
})
}
constants::DW_OP_piece => {
let size = bytes.read_uleb128()?;
Ok(Operation::Piece {
size_in_bits: 8 * size,
bit_offset: None,
})
}
constants::DW_OP_deref_size => {
let size = bytes.read_u8()?;
Ok(Operation::Deref {
base_type: generic_type(),
size,
space: false,
})
}
constants::DW_OP_xderef_size => {
let size = bytes.read_u8()?;
Ok(Operation::Deref {
base_type: generic_type(),
size,
space: true,
})
}
constants::DW_OP_nop => Ok(Operation::Nop),
constants::DW_OP_push_object_address => Ok(Operation::PushObjectAddress),
constants::DW_OP_call2 => {
let value = bytes.read_u16().map(R::Offset::from_u16)?;
Ok(Operation::Call {
offset: DieReference::UnitRef(UnitOffset(value)),
})
}
constants::DW_OP_call4 => {
let value = bytes.read_u32().map(R::Offset::from_u32)?;
Ok(Operation::Call {
offset: DieReference::UnitRef(UnitOffset(value)),
})
}
constants::DW_OP_call_ref => {
let value = bytes.read_offset(encoding.format)?;
Ok(Operation::Call {
offset: DieReference::DebugInfoRef(DebugInfoOffset(value)),
})
}
constants::DW_OP_form_tls_address | constants::DW_OP_GNU_push_tls_address => {
Ok(Operation::TLS)
}
constants::DW_OP_call_frame_cfa => Ok(Operation::CallFrameCFA),
constants::DW_OP_bit_piece => {
let size = bytes.read_uleb128()?;
let offset = bytes.read_uleb128()?;
Ok(Operation::Piece {
size_in_bits: size,
bit_offset: Some(offset),
})
}
constants::DW_OP_implicit_value => {
let len = bytes.read_uleb128().and_then(R::Offset::from_u64)?;
let data = bytes.split(len)?;
Ok(Operation::ImplicitValue { data })
}
constants::DW_OP_stack_value => Ok(Operation::StackValue),
constants::DW_OP_implicit_pointer | constants::DW_OP_GNU_implicit_pointer => {
let value = if encoding.version == 2 {
bytes
.read_address(encoding.address_size)
.and_then(Offset::from_u64)?
} else {
bytes.read_offset(encoding.format)?
};
let byte_offset = bytes.read_sleb128()?;
Ok(Operation::ImplicitPointer {
value: DebugInfoOffset(value),
byte_offset,
})
}
constants::DW_OP_addrx | constants::DW_OP_GNU_addr_index => {
let index = bytes.read_uleb128().and_then(R::Offset::from_u64)?;
Ok(Operation::AddressIndex {
index: DebugAddrIndex(index),
})
}
constants::DW_OP_constx | constants::DW_OP_GNU_const_index => {
let index = bytes.read_uleb128().and_then(R::Offset::from_u64)?;
Ok(Operation::ConstantIndex {
index: DebugAddrIndex(index),
})
}
constants::DW_OP_entry_value | constants::DW_OP_GNU_entry_value => {
let len = bytes.read_uleb128().and_then(R::Offset::from_u64)?;
let expression = bytes.split(len)?;
Ok(Operation::EntryValue { expression })
}
constants::DW_OP_GNU_parameter_ref => {
let value = bytes.read_u32().map(R::Offset::from_u32)?;
Ok(Operation::ParameterRef {
offset: UnitOffset(value),
})
}
constants::DW_OP_const_type | constants::DW_OP_GNU_const_type => {
let base_type = bytes.read_uleb128().and_then(R::Offset::from_u64)?;
let len = bytes.read_u8()?;
let value = bytes.split(R::Offset::from_u8(len))?;
Ok(Operation::TypedLiteral {
base_type: UnitOffset(base_type),
value,
})
}
constants::DW_OP_regval_type | constants::DW_OP_GNU_regval_type => {
let register = bytes.read_uleb128().and_then(Register::from_u64)?;
let base_type = bytes.read_uleb128().and_then(R::Offset::from_u64)?;
Ok(Operation::RegisterOffset {
register,
offset: 0,
base_type: UnitOffset(base_type),
})
}
constants::DW_OP_deref_type | constants::DW_OP_GNU_deref_type => {
let size = bytes.read_u8()?;
let base_type = bytes.read_uleb128().and_then(R::Offset::from_u64)?;
Ok(Operation::Deref {
base_type: UnitOffset(base_type),
size,
space: false,
})
}
constants::DW_OP_xderef_type => {
let size = bytes.read_u8()?;
let base_type = bytes.read_uleb128().and_then(R::Offset::from_u64)?;
Ok(Operation::Deref {
base_type: UnitOffset(base_type),
size,
space: true,
})
}
constants::DW_OP_convert | constants::DW_OP_GNU_convert => {
let base_type = bytes.read_uleb128().and_then(R::Offset::from_u64)?;
Ok(Operation::Convert {
base_type: UnitOffset(base_type),
})
}
constants::DW_OP_reinterpret | constants::DW_OP_GNU_reinterpret => {
let base_type = bytes.read_uleb128().and_then(R::Offset::from_u64)?;
Ok(Operation::Reinterpret {
base_type: UnitOffset(base_type),
})
}
constants::DW_OP_WASM_location => match bytes.read_u8()? {
0x0 => {
let index = bytes.read_uleb128_u32()?;
Ok(Operation::WasmLocal { index })
}
0x1 => {
let index = bytes.read_uleb128_u32()?;
Ok(Operation::WasmGlobal { index })
}
0x2 => {
let index = bytes.read_uleb128_u32()?;
Ok(Operation::WasmStack { index })
}
0x3 => {
let index = bytes.read_u32()?;
Ok(Operation::WasmGlobal { index })
}
_ => Err(Error::InvalidExpression(name)),
},
_ => Err(Error::InvalidExpression(name)),
}
}
}
#[derive(Debug)]
enum EvaluationState<R: Reader> {
Start(Option<u64>),
Ready,
Error(Error),
Complete,
Waiting(EvaluationWaiting<R>),
}
#[derive(Debug)]
enum EvaluationWaiting<R: Reader> {
Memory,
Register { offset: i64 },
FrameBase { offset: i64 },
Tls,
Cfa,
AtLocation,
EntryValue,
ParameterRef,
RelocatedAddress,
IndexedAddress,
TypedLiteral { value: R },
Convert,
Reinterpret,
}
/// The state of an `Evaluation` after evaluating a DWARF expression.
/// The evaluation is either `Complete`, or it requires more data
/// to continue, as described by the variant.
#[derive(Debug, PartialEq)]
pub enum EvaluationResult<R: Reader> {
/// The `Evaluation` is complete, and `Evaluation::result()` can be called.
Complete,
/// The `Evaluation` needs a value from memory to proceed further. Once the
/// caller determines what value to provide it should resume the `Evaluation`
/// by calling `Evaluation::resume_with_memory`.
RequiresMemory {
/// The address of the value required.
address: u64,
/// The size of the value required. This is guaranteed to be at most the
/// word size of the target architecture.
size: u8,
/// If not `None`, a target-specific address space value.
space: Option<u64>,
/// The DIE of the base type or 0 to indicate the generic type
base_type: UnitOffset<R::Offset>,
},
/// The `Evaluation` needs a value from a register to proceed further. Once
/// the caller determines what value to provide it should resume the
/// `Evaluation` by calling `Evaluation::resume_with_register`.
RequiresRegister {
/// The register number.
register: Register,
/// The DIE of the base type or 0 to indicate the generic type
base_type: UnitOffset<R::Offset>,
},
/// The `Evaluation` needs the frame base address to proceed further. Once
/// the caller determines what value to provide it should resume the
/// `Evaluation` by calling `Evaluation::resume_with_frame_base`. The frame
/// base address is the address produced by the location description in the
/// `DW_AT_frame_base` attribute of the current function.
RequiresFrameBase,
/// The `Evaluation` needs a value from TLS to proceed further. Once the
/// caller determines what value to provide it should resume the
/// `Evaluation` by calling `Evaluation::resume_with_tls`.
RequiresTls(u64),
/// The `Evaluation` needs the CFA to proceed further. Once the caller
/// determines what value to provide it should resume the `Evaluation` by
/// calling `Evaluation::resume_with_call_frame_cfa`.
RequiresCallFrameCfa,
/// The `Evaluation` needs the DWARF expression at the given location to
/// proceed further. Once the caller determines what value to provide it
/// should resume the `Evaluation` by calling
/// `Evaluation::resume_with_at_location`.
RequiresAtLocation(DieReference<R::Offset>),
/// The `Evaluation` needs the value produced by evaluating a DWARF
/// expression at the entry point of the current subprogram. Once the
/// caller determines what value to provide it should resume the
/// `Evaluation` by calling `Evaluation::resume_with_entry_value`.
RequiresEntryValue(Expression<R>),
/// The `Evaluation` needs the value of the parameter at the given location
/// in the current function's caller. Once the caller determines what value
/// to provide it should resume the `Evaluation` by calling
/// `Evaluation::resume_with_parameter_ref`.
RequiresParameterRef(UnitOffset<R::Offset>),
/// The `Evaluation` needs an address to be relocated to proceed further.
/// Once the caller determines what value to provide it should resume the
/// `Evaluation` by calling `Evaluation::resume_with_relocated_address`.
RequiresRelocatedAddress(u64),
/// The `Evaluation` needs an address from the `.debug_addr` section.
/// This address may also need to be relocated.
/// Once the caller determines what value to provide it should resume the
/// `Evaluation` by calling `Evaluation::resume_with_indexed_address`.
RequiresIndexedAddress {
/// The index of the address in the `.debug_addr` section,
/// relative to the `DW_AT_addr_base` of the compilation unit.
index: DebugAddrIndex<R::Offset>,
/// Whether the address also needs to be relocated.
relocate: bool,
},
/// The `Evaluation` needs the `ValueType` for the base type DIE at
/// the give unit offset. Once the caller determines what value to provide it
/// should resume the `Evaluation` by calling
/// `Evaluation::resume_with_base_type`.
RequiresBaseType(UnitOffset<R::Offset>),
}
/// The bytecode for a DWARF expression or location description.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Expression<R: Reader>(pub R);
impl<R: Reader> Expression<R> {
/// Create an evaluation for this expression.
///
/// The `encoding` is determined by the
/// [`CompilationUnitHeader`](struct.CompilationUnitHeader.html) or
/// [`TypeUnitHeader`](struct.TypeUnitHeader.html) that this expression
/// relates to.
///
/// # Examples
/// ```rust,no_run
/// use gimli::Expression;
/// # let endian = gimli::LittleEndian;
/// # let debug_info = gimli::DebugInfo::from(gimli::EndianSlice::new(&[], endian));
/// # let unit = debug_info.units().next().unwrap().unwrap();
/// # let bytecode = gimli::EndianSlice::new(&[], endian);
/// let expression = gimli::Expression(bytecode);
/// let mut eval = expression.evaluation(unit.encoding());
/// let mut result = eval.evaluate().unwrap();
/// ```
#[cfg(feature = "read")]
#[inline]
pub fn evaluation(self, encoding: Encoding) -> Evaluation<R> {
Evaluation::new(self.0, encoding)
}
/// Return an iterator for the operations in the expression.
pub fn operations(self, encoding: Encoding) -> OperationIter<R> {
OperationIter {
input: self.0,
encoding,
}
}
}
/// An iterator for the operations in an expression.
#[derive(Debug, Clone, Copy)]
pub struct OperationIter<R: Reader> {
input: R,
encoding: Encoding,
}
impl<R: Reader> OperationIter<R> {
/// Read the next operation in an expression.
pub fn next(&mut self) -> Result<Option<Operation<R>>> {
if self.input.is_empty() {
return Ok(None);
}
match Operation::parse(&mut self.input, self.encoding) {
Ok(op) => Ok(Some(op)),
Err(e) => {
self.input.empty();
Err(e)
}
}
}
/// Return the current byte offset of the iterator.
pub fn offset_from(&self, expression: &Expression<R>) -> R::Offset {
self.input.offset_from(&expression.0)
}
}
#[cfg(feature = "fallible-iterator")]
impl<R: Reader> fallible_iterator::FallibleIterator for OperationIter<R> {
type Item = Operation<R>;
type Error = Error;
fn next(&mut self) -> ::core::result::Result<Option<Self::Item>, Self::Error> {
OperationIter::next(self)
}
}
/// Specification of what storage should be used for [`Evaluation`].
///
#[cfg_attr(
feature = "read",
doc = "
Normally you would only need to use [`StoreOnHeap`], which places the stacks and the results
on the heap using [`Vec`]. This is the default storage type parameter for [`Evaluation`].
"
)]
///
/// If you need to avoid [`Evaluation`] from allocating memory, e.g. for signal safety,
/// you can provide you own storage specification:
/// ```rust,no_run
/// # use gimli::*;
/// # let bytecode = EndianSlice::new(&[], LittleEndian);
/// # let encoding = unimplemented!();
/// # let get_register_value = |_, _| Value::Generic(42);
/// # let get_frame_base = || 0xdeadbeef;
/// #
/// struct StoreOnStack;
///
/// impl<R: Reader> EvaluationStorage<R> for StoreOnStack {
/// type Stack = [Value; 64];
/// type ExpressionStack = [(R, R); 4];
/// type Result = [Piece<R>; 1];
/// }
///
/// let mut eval = Evaluation::<_, StoreOnStack>::new_in(bytecode, encoding);
/// let mut result = eval.evaluate().unwrap();
/// while result != EvaluationResult::Complete {
/// match result {
/// EvaluationResult::RequiresRegister { register, base_type } => {
/// let value = get_register_value(register, base_type);
/// result = eval.resume_with_register(value).unwrap();
/// },
/// EvaluationResult::RequiresFrameBase => {
/// let frame_base = get_frame_base();
/// result = eval.resume_with_frame_base(frame_base).unwrap();
/// },
/// _ => unimplemented!(),
/// };
/// }
///
/// let result = eval.as_result();
/// println!("{:?}", result);
/// ```
pub trait EvaluationStorage<R: Reader> {
/// The storage used for the evaluation stack.
type Stack: ArrayLike<Item = Value>;
/// The storage used for the expression stack.
type ExpressionStack: ArrayLike<Item = (R, R)>;
/// The storage used for the results.
type Result: ArrayLike<Item = Piece<R>>;
}
#[cfg(feature = "read")]
impl<R: Reader> EvaluationStorage<R> for StoreOnHeap {
type Stack = Vec<Value>;
type ExpressionStack = Vec<(R, R)>;
type Result = Vec<Piece<R>>;
}
/// A DWARF expression evaluator.
///
/// # Usage
/// A DWARF expression may require additional data to produce a final result,
/// such as the value of a register or a memory location. Once initial setup
/// is complete (i.e. `set_initial_value()`, `set_object_address()`) the
/// consumer calls the `evaluate()` method. That returns an `EvaluationResult`,
/// which is either `EvaluationResult::Complete` or a value indicating what
/// data is needed to resume the `Evaluation`. The consumer is responsible for
/// producing that data and resuming the computation with the correct method,
/// as documented for `EvaluationResult`. Only once an `EvaluationResult::Complete`
/// is returned can the consumer call `result()`.
///
/// This design allows the consumer of `Evaluation` to decide how and when to
/// produce the required data and resume the computation. The `Evaluation` can
/// be driven synchronously (as shown below) or by some asynchronous mechanism
/// such as futures.
///
/// # Examples
/// ```rust,no_run
/// use gimli::{Evaluation, EvaluationResult, Expression};
/// # let bytecode = gimli::EndianSlice::new(&[], gimli::LittleEndian);
/// # let encoding = unimplemented!();
/// # let get_register_value = |_, _| gimli::Value::Generic(42);
/// # let get_frame_base = || 0xdeadbeef;
///
/// let mut eval = Evaluation::new(bytecode, encoding);
/// let mut result = eval.evaluate().unwrap();
/// while result != EvaluationResult::Complete {
/// match result {
/// EvaluationResult::RequiresRegister { register, base_type } => {
/// let value = get_register_value(register, base_type);
/// result = eval.resume_with_register(value).unwrap();
/// },
/// EvaluationResult::RequiresFrameBase => {
/// let frame_base = get_frame_base();
/// result = eval.resume_with_frame_base(frame_base).unwrap();
/// },
/// _ => unimplemented!(),
/// };
/// }
///
/// let result = eval.result();
/// println!("{:?}", result);
/// ```
#[derive(Debug)]
pub struct Evaluation<R: Reader, S: EvaluationStorage<R> = StoreOnHeap> {
bytecode: R,
encoding: Encoding,
object_address: Option<u64>,
max_iterations: Option<u32>,
iteration: u32,
state: EvaluationState<R>,
// Stack operations are done on word-sized values. We do all
// operations on 64-bit values, and then mask the results
// appropriately when popping.
addr_mask: u64,
// The stack.
stack: ArrayVec<S::Stack>,
// The next operation to decode and evaluate.
pc: R,
// If we see a DW_OP_call* operation, the previous PC and bytecode
// is stored here while evaluating the subroutine.
expression_stack: ArrayVec<S::ExpressionStack>,
value_result: Option<Value>,
result: ArrayVec<S::Result>,
}
#[cfg(feature = "read")]
impl<R: Reader> Evaluation<R> {
/// Create a new DWARF expression evaluator.
///
/// The new evaluator is created without an initial value, without
/// an object address, and without a maximum number of iterations.
pub fn new(bytecode: R, encoding: Encoding) -> Self {
Self::new_in(bytecode, encoding)
}
/// Get the result of this `Evaluation`.
///
/// # Panics
/// Panics if this `Evaluation` has not been driven to completion.
pub fn result(self) -> Vec<Piece<R>> {
match self.state {
EvaluationState::Complete => self.result.into_vec(),
_ => {
panic!("Called `Evaluation::result` on an `Evaluation` that has not been completed")
}
}
}
}
impl<R: Reader, S: EvaluationStorage<R>> Evaluation<R, S> {
/// Create a new DWARF expression evaluator.
///
/// The new evaluator is created without an initial value, without
/// an object address, and without a maximum number of iterations.
pub fn new_in(bytecode: R, encoding: Encoding) -> Self {
let pc = bytecode.clone();
Evaluation {
bytecode,
encoding,
object_address: None,
max_iterations: None,
iteration: 0,
state: EvaluationState::Start(None),
addr_mask: if encoding.address_size == 8 {
!0u64
} else {
(1 << (8 * u64::from(encoding.address_size))) - 1
},
stack: Default::default(),
expression_stack: Default::default(),
pc,
value_result: None,
result: Default::default(),
}
}
/// Set an initial value to be pushed on the DWARF expression
/// evaluator's stack. This can be used in cases like
/// `DW_AT_vtable_elem_location`, which require a value on the
/// stack before evaluation commences. If no initial value is
/// set, and the expression uses an opcode requiring the initial
/// value, then evaluation will fail with an error.
///
/// # Panics
/// Panics if `set_initial_value()` has already been called, or if
/// `evaluate()` has already been called.
pub fn set_initial_value(&mut self, value: u64) {
match self.state {
EvaluationState::Start(None) => {
self.state = EvaluationState::Start(Some(value));
}
_ => panic!(
"`Evaluation::set_initial_value` was called twice, or after evaluation began."
),
};
}
/// Set the enclosing object's address, as used by
/// `DW_OP_push_object_address`. If no object address is set, and
/// the expression uses an opcode requiring the object address,
/// then evaluation will fail with an error.
pub fn set_object_address(&mut self, value: u64) {
self.object_address = Some(value);
}
/// Set the maximum number of iterations to be allowed by the
/// expression evaluator.
///
/// An iteration corresponds approximately to the evaluation of a
/// single operation in an expression ("approximately" because the
/// implementation may allow two such operations in some cases).
/// The default is not to have a maximum; once set, it's not
/// possible to go back to this default state. This value can be
/// set to avoid denial of service attacks by bad DWARF bytecode.
pub fn set_max_iterations(&mut self, value: u32) {
self.max_iterations = Some(value);
}
fn pop(&mut self) -> Result<Value> {
match self.stack.pop() {
Some(value) => Ok(value),
None => Err(Error::NotEnoughStackItems),
}
}
fn push(&mut self, value: Value) -> Result<()> {
self.stack.try_push(value).map_err(|_| Error::StackFull)
}
fn evaluate_one_operation(&mut self) -> Result<OperationEvaluationResult<R>> {
let operation = Operation::parse(&mut self.pc, self.encoding)?;
match operation {
Operation::Deref {
base_type,
size,
space,
} => {
let entry = self.pop()?;
let addr = entry.to_u64(self.addr_mask)?;
let addr_space = if space {
let entry = self.pop()?;
let value = entry.to_u64(self.addr_mask)?;
Some(value)
} else {
None
};
return Ok(OperationEvaluationResult::Waiting(
EvaluationWaiting::Memory,
EvaluationResult::RequiresMemory {
address: addr,
size,
space: addr_space,
base_type,
},
));
}
Operation::Drop => {
self.pop()?;
}
Operation::Pick { index } => {
let len = self.stack.len();
let index = index as usize;
if index >= len {
return Err(Error::NotEnoughStackItems);
}
let value = self.stack[len - index - 1];
self.push(value)?;
}
Operation::Swap => {
let top = self.pop()?;
let next = self.pop()?;
self.push(top)?;
self.push(next)?;
}
Operation::Rot => {
let one = self.pop()?;
let two = self.pop()?;
let three = self.pop()?;
self.push(one)?;
self.push(three)?;
self.push(two)?;
}
Operation::Abs => {
let value = self.pop()?;
let result = value.abs(self.addr_mask)?;
self.push(result)?;
}
Operation::And => {
let rhs = self.pop()?;
let lhs = self.pop()?;
let result = lhs.and(rhs, self.addr_mask)?;
self.push(result)?;
}
Operation::Div => {
let rhs = self.pop()?;
let lhs = self.pop()?;
let result = lhs.div(rhs, self.addr_mask)?;
self.push(result)?;
}
Operation::Minus => {
let rhs = self.pop()?;
let lhs = self.pop()?;
let result = lhs.sub(rhs, self.addr_mask)?;
self.push(result)?;
}
Operation::Mod => {
let rhs = self.pop()?;
let lhs = self.pop()?;
let result = lhs.rem(rhs, self.addr_mask)?;
self.push(result)?;
}
Operation::Mul => {
let rhs = self.pop()?;
let lhs = self.pop()?;
let result = lhs.mul(rhs, self.addr_mask)?;
self.push(result)?;
}
Operation::Neg => {
let v = self.pop()?;
let result = v.neg(self.addr_mask)?;
self.push(result)?;
}
Operation::Not => {
let value = self.pop()?;
let result = value.not(self.addr_mask)?;
self.push(result)?;
}
Operation::Or => {
let rhs = self.pop()?;
let lhs = self.pop()?;
let result = lhs.or(rhs, self.addr_mask)?;
self.push(result)?;
}
Operation::Plus => {
let rhs = self.pop()?;
let lhs = self.pop()?;
let result = lhs.add(rhs, self.addr_mask)?;
self.push(result)?;
}
Operation::PlusConstant { value } => {
let lhs = self.pop()?;
let rhs = Value::from_u64(lhs.value_type(), value)?;
let result = lhs.add(rhs, self.addr_mask)?;
self.push(result)?;
}
Operation::Shl => {
let rhs = self.pop()?;
let lhs = self.pop()?;
let result = lhs.shl(rhs, self.addr_mask)?;
self.push(result)?;
}
Operation::Shr => {
let rhs = self.pop()?;
let lhs = self.pop()?;
let result = lhs.shr(rhs, self.addr_mask)?;
self.push(result)?;
}
Operation::Shra => {
let rhs = self.pop()?;
let lhs = self.pop()?;
let result = lhs.shra(rhs, self.addr_mask)?;
self.push(result)?;
}
Operation::Xor => {
let rhs = self.pop()?;
let lhs = self.pop()?;
let result = lhs.xor(rhs, self.addr_mask)?;
self.push(result)?;
}
Operation::Bra { target } => {
let entry = self.pop()?;
let v = entry.to_u64(self.addr_mask)?;
if v != 0 {
self.pc = compute_pc(&self.pc, &self.bytecode, target)?;
}
}
Operation::Eq => {
let rhs = self.pop()?;
let lhs = self.pop()?;
let result = lhs.eq(rhs, self.addr_mask)?;
self.push(result)?;
}
Operation::Ge => {
let rhs = self.pop()?;
let lhs = self.pop()?;
let result = lhs.ge(rhs, self.addr_mask)?;
self.push(result)?;
}
Operation::Gt => {
let rhs = self.pop()?;
let lhs = self.pop()?;
let result = lhs.gt(rhs, self.addr_mask)?;
self.push(result)?;
}
Operation::Le => {
let rhs = self.pop()?;
let lhs = self.pop()?;
let result = lhs.le(rhs, self.addr_mask)?;
self.push(result)?;
}
Operation::Lt => {
let rhs = self.pop()?;
let lhs = self.pop()?;
let result = lhs.lt(rhs, self.addr_mask)?;
self.push(result)?;
}
Operation::Ne => {
let rhs = self.pop()?;
let lhs = self.pop()?;
let result = lhs.ne(rhs, self.addr_mask)?;
self.push(result)?;
}
Operation::Skip { target } => {
self.pc = compute_pc(&self.pc, &self.bytecode, target)?;
}
Operation::UnsignedConstant { value } => {
self.push(Value::Generic(value))?;
}
Operation::SignedConstant { value } => {
self.push(Value::Generic(value as u64))?;
}
Operation::RegisterOffset {
register,
offset,
base_type,
} => {
return Ok(OperationEvaluationResult::Waiting(
EvaluationWaiting::Register { offset },
EvaluationResult::RequiresRegister {
register,
base_type,
},
));
}
Operation::FrameOffset { offset } => {
return Ok(OperationEvaluationResult::Waiting(
EvaluationWaiting::FrameBase { offset },
EvaluationResult::RequiresFrameBase,
));
}
Operation::Nop => {}
Operation::PushObjectAddress => {
if let Some(value) = self.object_address {
self.push(Value::Generic(value))?;
} else {
return Err(Error::InvalidPushObjectAddress);
}
}
Operation::Call { offset } => {
return Ok(OperationEvaluationResult::Waiting(
EvaluationWaiting::AtLocation,
EvaluationResult::RequiresAtLocation(offset),
));
}
Operation::TLS => {
let entry = self.pop()?;
let index = entry.to_u64(self.addr_mask)?;
return Ok(OperationEvaluationResult::Waiting(
EvaluationWaiting::Tls,
EvaluationResult::RequiresTls(index),
));
}
Operation::CallFrameCFA => {
return Ok(OperationEvaluationResult::Waiting(
EvaluationWaiting::Cfa,
EvaluationResult::RequiresCallFrameCfa,
));
}
Operation::Register { register } => {
let location = Location::Register { register };
return Ok(OperationEvaluationResult::Complete { location });
}
Operation::ImplicitValue { ref data } => {
let location = Location::Bytes {
value: data.clone(),
};
return Ok(OperationEvaluationResult::Complete { location });
}
Operation::StackValue => {
let value = self.pop()?;
let location = Location::Value { value };
return Ok(OperationEvaluationResult::Complete { location });
}
Operation::ImplicitPointer { value, byte_offset } => {
let location = Location::ImplicitPointer { value, byte_offset };
return Ok(OperationEvaluationResult::Complete { location });
}
Operation::EntryValue { ref expression } => {
return Ok(OperationEvaluationResult::Waiting(
EvaluationWaiting::EntryValue,
EvaluationResult::RequiresEntryValue(Expression(expression.clone())),
));
}
Operation::ParameterRef { offset } => {
return Ok(OperationEvaluationResult::Waiting(
EvaluationWaiting::ParameterRef,
EvaluationResult::RequiresParameterRef(offset),
));
}
Operation::Address { address } => {
return Ok(OperationEvaluationResult::Waiting(
EvaluationWaiting::RelocatedAddress,
EvaluationResult::RequiresRelocatedAddress(address),
));
}
Operation::AddressIndex { index } => {
return Ok(OperationEvaluationResult::Waiting(
EvaluationWaiting::IndexedAddress,
EvaluationResult::RequiresIndexedAddress {
index,
relocate: true,
},
));
}
Operation::ConstantIndex { index } => {
return Ok(OperationEvaluationResult::Waiting(
EvaluationWaiting::IndexedAddress,
EvaluationResult::RequiresIndexedAddress {
index,
relocate: false,
},
));
}
Operation::Piece {
size_in_bits,
bit_offset,
} => {
let location = if self.stack.is_empty() {
Location::Empty
} else {
let entry = self.pop()?;
let address = entry.to_u64(self.addr_mask)?;
Location::Address { address }
};
self.result
.try_push(Piece {
size_in_bits: Some(size_in_bits),
bit_offset,
location,
})
.map_err(|_| Error::StackFull)?;
return Ok(OperationEvaluationResult::Piece);
}
Operation::TypedLiteral { base_type, value } => {
return Ok(OperationEvaluationResult::Waiting(
EvaluationWaiting::TypedLiteral { value },
EvaluationResult::RequiresBaseType(base_type),
));
}
Operation::Convert { base_type } => {
return Ok(OperationEvaluationResult::Waiting(
EvaluationWaiting::Convert,
EvaluationResult::RequiresBaseType(base_type),
));
}
Operation::Reinterpret { base_type } => {
return Ok(OperationEvaluationResult::Waiting(
EvaluationWaiting::Reinterpret,
EvaluationResult::RequiresBaseType(base_type),
));
}
Operation::WasmLocal { .. }
| Operation::WasmGlobal { .. }
| Operation::WasmStack { .. } => {
return Err(Error::UnsupportedEvaluation);
}
}
Ok(OperationEvaluationResult::Incomplete)
}
/// Get the result if this is an evaluation for a value.
///
/// Returns `None` if the evaluation contained operations that are only
/// valid for location descriptions.
///
/// # Panics
/// Panics if this `Evaluation` has not been driven to completion.
pub fn value_result(&self) -> Option<Value> {
match self.state {
EvaluationState::Complete => self.value_result,
_ => {
panic!("Called `Evaluation::value_result` on an `Evaluation` that has not been completed")
}
}
}
/// Get the result of this `Evaluation`.
///
/// # Panics
/// Panics if this `Evaluation` has not been driven to completion.
pub fn as_result(&self) -> &[Piece<R>] {
match self.state {
EvaluationState::Complete => &self.result,
_ => {
panic!(
"Called `Evaluation::as_result` on an `Evaluation` that has not been completed"
)
}
}
}
/// Evaluate a DWARF expression. This method should only ever be called
/// once. If the returned `EvaluationResult` is not
/// `EvaluationResult::Complete`, the caller should provide the required
/// value and resume the evaluation by calling the appropriate resume_with
/// method on `Evaluation`.
pub fn evaluate(&mut self) -> Result<EvaluationResult<R>> {
match self.state {
EvaluationState::Start(initial_value) => {
if let Some(value) = initial_value {
self.push(Value::Generic(value))?;
}
self.state = EvaluationState::Ready;
}
EvaluationState::Ready => {}
EvaluationState::Error(err) => return Err(err),
EvaluationState::Complete => return Ok(EvaluationResult::Complete),
EvaluationState::Waiting(_) => panic!(),
};
match self.evaluate_internal() {
Ok(r) => Ok(r),
Err(e) => {
self.state = EvaluationState::Error(e);
Err(e)
}
}
}
/// Resume the `Evaluation` with the provided memory `value`. This will apply
/// the provided memory value to the evaluation and continue evaluating
/// opcodes until the evaluation is completed, reaches an error, or needs
/// more information again.
///
/// # Panics
/// Panics if this `Evaluation` did not previously stop with `EvaluationResult::RequiresMemory`.
pub fn resume_with_memory(&mut self, value: Value) -> Result<EvaluationResult<R>> {
match self.state {
EvaluationState::Error(err) => return Err(err),
EvaluationState::Waiting(EvaluationWaiting::Memory) => {
self.push(value)?;
}
_ => panic!(
"Called `Evaluation::resume_with_memory` without a preceding `EvaluationResult::RequiresMemory`"
),
};
self.evaluate_internal()
}
/// Resume the `Evaluation` with the provided `register` value. This will apply
/// the provided register value to the evaluation and continue evaluating
/// opcodes until the evaluation is completed, reaches an error, or needs
/// more information again.
///
/// # Panics
/// Panics if this `Evaluation` did not previously stop with `EvaluationResult::RequiresRegister`.
pub fn resume_with_register(&mut self, value: Value) -> Result<EvaluationResult<R>> {
match self.state {
EvaluationState::Error(err) => return Err(err),
EvaluationState::Waiting(EvaluationWaiting::Register { offset }) => {
let offset = Value::from_u64(value.value_type(), offset as u64)?;
let value = value.add(offset, self.addr_mask)?;
self.push(value)?;
}
_ => panic!(
"Called `Evaluation::resume_with_register` without a preceding `EvaluationResult::RequiresRegister`"
),
};
self.evaluate_internal()
}
/// Resume the `Evaluation` with the provided `frame_base`. This will
/// apply the provided frame base value to the evaluation and continue
/// evaluating opcodes until the evaluation is completed, reaches an error,
/// or needs more information again.
///
/// # Panics
/// Panics if this `Evaluation` did not previously stop with `EvaluationResult::RequiresFrameBase`.
pub fn resume_with_frame_base(&mut self, frame_base: u64) -> Result<EvaluationResult<R>> {
match self.state {
EvaluationState::Error(err) => return Err(err),
EvaluationState::Waiting(EvaluationWaiting::FrameBase { offset }) => {
self.push(Value::Generic(frame_base.wrapping_add(offset as u64)))?;
}
_ => panic!(
"Called `Evaluation::resume_with_frame_base` without a preceding `EvaluationResult::RequiresFrameBase`"
),
};
self.evaluate_internal()
}
/// Resume the `Evaluation` with the provided `value`. This will apply
/// the provided TLS value to the evaluation and continue evaluating
/// opcodes until the evaluation is completed, reaches an error, or needs
/// more information again.
///
/// # Panics
/// Panics if this `Evaluation` did not previously stop with `EvaluationResult::RequiresTls`.
pub fn resume_with_tls(&mut self, value: u64) -> Result<EvaluationResult<R>> {
match self.state {
EvaluationState::Error(err) => return Err(err),
EvaluationState::Waiting(EvaluationWaiting::Tls) => {
self.push(Value::Generic(value))?;
}
_ => panic!(
"Called `Evaluation::resume_with_tls` without a preceding `EvaluationResult::RequiresTls`"
),
};
self.evaluate_internal()
}
/// Resume the `Evaluation` with the provided `cfa`. This will
/// apply the provided CFA value to the evaluation and continue evaluating
/// opcodes until the evaluation is completed, reaches an error, or needs
/// more information again.
///
/// # Panics
/// Panics if this `Evaluation` did not previously stop with `EvaluationResult::RequiresCallFrameCfa`.
pub fn resume_with_call_frame_cfa(&mut self, cfa: u64) -> Result<EvaluationResult<R>> {
match self.state {
EvaluationState::Error(err) => return Err(err),
EvaluationState::Waiting(EvaluationWaiting::Cfa) => {
self.push(Value::Generic(cfa))?;
}
_ => panic!(
"Called `Evaluation::resume_with_call_frame_cfa` without a preceding `EvaluationResult::RequiresCallFrameCfa`"
),
};
self.evaluate_internal()
}
/// Resume the `Evaluation` with the provided `bytes`. This will
/// continue processing the evaluation with the new expression provided
/// until the evaluation is completed, reaches an error, or needs more
/// information again.
///
/// # Panics
/// Panics if this `Evaluation` did not previously stop with `EvaluationResult::RequiresAtLocation`.
pub fn resume_with_at_location(&mut self, mut bytes: R) -> Result<EvaluationResult<R>> {
match self.state {
EvaluationState::Error(err) => return Err(err),
EvaluationState::Waiting(EvaluationWaiting::AtLocation) => {
if !bytes.is_empty() {
let mut pc = bytes.clone();
mem::swap(&mut pc, &mut self.pc);
mem::swap(&mut bytes, &mut self.bytecode);
self.expression_stack.try_push((pc, bytes)).map_err(|_| Error::StackFull)?;
}
}
_ => panic!(
"Called `Evaluation::resume_with_at_location` without a precedeing `EvaluationResult::RequiresAtLocation`"
),
};
self.evaluate_internal()
}
/// Resume the `Evaluation` with the provided `entry_value`. This will
/// apply the provided entry value to the evaluation and continue evaluating
/// opcodes until the evaluation is completed, reaches an error, or needs
/// more information again.
///
/// # Panics
/// Panics if this `Evaluation` did not previously stop with `EvaluationResult::RequiresEntryValue`.
pub fn resume_with_entry_value(&mut self, entry_value: Value) -> Result<EvaluationResult<R>> {
match self.state {
EvaluationState::Error(err) => return Err(err),
EvaluationState::Waiting(EvaluationWaiting::EntryValue) => {
self.push(entry_value)?;
}
_ => panic!(
"Called `Evaluation::resume_with_entry_value` without a preceding `EvaluationResult::RequiresEntryValue`"
),
};
self.evaluate_internal()
}
/// Resume the `Evaluation` with the provided `parameter_value`. This will
/// apply the provided parameter value to the evaluation and continue evaluating
/// opcodes until the evaluation is completed, reaches an error, or needs
/// more information again.
///
/// # Panics
/// Panics if this `Evaluation` did not previously stop with `EvaluationResult::RequiresParameterRef`.
pub fn resume_with_parameter_ref(
&mut self,
parameter_value: u64,
) -> Result<EvaluationResult<R>> {
match self.state {
EvaluationState::Error(err) => return Err(err),
EvaluationState::Waiting(EvaluationWaiting::ParameterRef) => {
self.push(Value::Generic(parameter_value))?;
}
_ => panic!(
"Called `Evaluation::resume_with_parameter_ref` without a preceding `EvaluationResult::RequiresParameterRef`"
),
};
self.evaluate_internal()
}
/// Resume the `Evaluation` with the provided relocated `address`. This will use the
/// provided relocated address for the operation that required it, and continue evaluating
/// opcodes until the evaluation is completed, reaches an error, or needs
/// more information again.
///
/// # Panics
/// Panics if this `Evaluation` did not previously stop with
/// `EvaluationResult::RequiresRelocatedAddress`.
pub fn resume_with_relocated_address(&mut self, address: u64) -> Result<EvaluationResult<R>> {
match self.state {
EvaluationState::Error(err) => return Err(err),
EvaluationState::Waiting(EvaluationWaiting::RelocatedAddress) => {
self.push(Value::Generic(address))?;
}
_ => panic!(
"Called `Evaluation::resume_with_relocated_address` without a preceding `EvaluationResult::RequiresRelocatedAddress`"
),
};
self.evaluate_internal()
}
/// Resume the `Evaluation` with the provided indexed `address`. This will use the
/// provided indexed address for the operation that required it, and continue evaluating
/// opcodes until the evaluation is completed, reaches an error, or needs
/// more information again.
///
/// # Panics
/// Panics if this `Evaluation` did not previously stop with
/// `EvaluationResult::RequiresIndexedAddress`.
pub fn resume_with_indexed_address(&mut self, address: u64) -> Result<EvaluationResult<R>> {
match self.state {
EvaluationState::Error(err) => return Err(err),
EvaluationState::Waiting(EvaluationWaiting::IndexedAddress) => {
self.push(Value::Generic(address))?;
}
_ => panic!(
"Called `Evaluation::resume_with_indexed_address` without a preceding `EvaluationResult::RequiresIndexedAddress`"
),
};
self.evaluate_internal()
}
/// Resume the `Evaluation` with the provided `base_type`. This will use the
/// provided base type for the operation that required it, and continue evaluating
/// opcodes until the evaluation is completed, reaches an error, or needs
/// more information again.
///
/// # Panics
/// Panics if this `Evaluation` did not previously stop with `EvaluationResult::RequiresBaseType`.
pub fn resume_with_base_type(&mut self, base_type: ValueType) -> Result<EvaluationResult<R>> {
let value = match self.state {
EvaluationState::Error(err) => return Err(err),
EvaluationState::Waiting(EvaluationWaiting::TypedLiteral { ref value }) => {
Value::parse(base_type, value.clone())?
}
EvaluationState::Waiting(EvaluationWaiting::Convert) => {
let entry = self.pop()?;
entry.convert(base_type, self.addr_mask)?
}
EvaluationState::Waiting(EvaluationWaiting::Reinterpret) => {
let entry = self.pop()?;
entry.reinterpret(base_type, self.addr_mask)?
}
_ => panic!(
"Called `Evaluation::resume_with_base_type` without a preceding `EvaluationResult::RequiresBaseType`"
),
};
self.push(value)?;
self.evaluate_internal()
}
fn end_of_expression(&mut self) -> bool {
while self.pc.is_empty() {
match self.expression_stack.pop() {
Some((newpc, newbytes)) => {
self.pc = newpc;
self.bytecode = newbytes;
}
None => return true,
}
}
false
}
fn evaluate_internal(&mut self) -> Result<EvaluationResult<R>> {
while !self.end_of_expression() {
self.iteration += 1;
if let Some(max_iterations) = self.max_iterations {
if self.iteration > max_iterations {
return Err(Error::TooManyIterations);
}
}
let op_result = self.evaluate_one_operation()?;
match op_result {
OperationEvaluationResult::Piece => {}
OperationEvaluationResult::Incomplete => {
if self.end_of_expression() && !self.result.is_empty() {
// We saw a piece earlier and then some
// unterminated piece. It's not clear this is
// well-defined.
return Err(Error::InvalidPiece);
}
}
OperationEvaluationResult::Complete { location } => {
if self.end_of_expression() {
if !self.result.is_empty() {
// We saw a piece earlier and then some
// unterminated piece. It's not clear this is
// well-defined.
return Err(Error::InvalidPiece);
}
self.result
.try_push(Piece {
size_in_bits: None,
bit_offset: None,
location,
})
.map_err(|_| Error::StackFull)?;
} else {
// If there are more operations, then the next operation must
// be a Piece.
match Operation::parse(&mut self.pc, self.encoding)? {
Operation::Piece {
size_in_bits,
bit_offset,
} => {
self.result
.try_push(Piece {
size_in_bits: Some(size_in_bits),
bit_offset,
location,
})
.map_err(|_| Error::StackFull)?;
}
_ => {
let value =
self.bytecode.len().into_u64() - self.pc.len().into_u64() - 1;
return Err(Error::InvalidExpressionTerminator(value));
}
}
}
}
OperationEvaluationResult::Waiting(waiting, result) => {
self.state = EvaluationState::Waiting(waiting);
return Ok(result);
}
}
}
// If no pieces have been seen, use the stack top as the
// result.
if self.result.is_empty() {
let entry = self.pop()?;
self.value_result = Some(entry);
let addr = entry.to_u64(self.addr_mask)?;
self.result
.try_push(Piece {
size_in_bits: None,
bit_offset: None,
location: Location::Address { address: addr },
})
.map_err(|_| Error::StackFull)?;
}
self.state = EvaluationState::Complete;
Ok(EvaluationResult::Complete)
}
}
#[cfg(test)]
// Tests require leb128::write.
#[cfg(feature = "write")]
mod tests {
use super::*;
use crate::common::Format;
use crate::constants;
use crate::endianity::LittleEndian;
use crate::leb128;
use crate::read::{EndianSlice, Error, Result, UnitOffset};
use crate::test_util::GimliSectionMethods;
use core::usize;
use test_assembler::{Endian, Section};
fn encoding4() -> Encoding {
Encoding {
format: Format::Dwarf32,
version: 4,
address_size: 4,
}
}
fn encoding8() -> Encoding {
Encoding {
format: Format::Dwarf64,
version: 4,
address_size: 8,
}
}
#[test]
fn test_compute_pc() {
// Contents don't matter for this test, just length.
let bytes = [0, 1, 2, 3, 4];
let bytecode = &bytes[..];
let ebuf = &EndianSlice::new(bytecode, LittleEndian);
assert_eq!(compute_pc(ebuf, ebuf, 0), Ok(*ebuf));
assert_eq!(
compute_pc(ebuf, ebuf, -1),
Err(Error::BadBranchTarget(usize::MAX as u64))
);
assert_eq!(compute_pc(ebuf, ebuf, 5), Ok(ebuf.range_from(5..)));
assert_eq!(
compute_pc(&ebuf.range_from(3..), ebuf, -2),
Ok(ebuf.range_from(1..))
);
assert_eq!(
compute_pc(&ebuf.range_from(2..), ebuf, 2),
Ok(ebuf.range_from(4..))
);
}
fn check_op_parse_simple<'input>(
input: &'input [u8],
expect: &Operation<EndianSlice<'input, LittleEndian>>,
encoding: Encoding,
) {
let buf = EndianSlice::new(input, LittleEndian);
let mut pc = buf;
let value = Operation::parse(&mut pc, encoding);
match value {
Ok(val) => {
assert_eq!(val, *expect);
assert_eq!(pc.len(), 0);
}
_ => panic!("Unexpected result"),
}
}
fn check_op_parse_eof(input: &[u8], encoding: Encoding) {
let buf = EndianSlice::new(input, LittleEndian);
let mut pc = buf;
match Operation::parse(&mut pc, encoding) {
Err(Error::UnexpectedEof(id)) => {
assert!(buf.lookup_offset_id(id).is_some());
}
_ => panic!("Unexpected result"),
}
}
fn check_op_parse<F>(
input: F,
expect: &Operation<EndianSlice<LittleEndian>>,
encoding: Encoding,
) where
F: Fn(Section) -> Section,
{
let input = input(Section::with_endian(Endian::Little))
.get_contents()
.unwrap();
for i in 1..input.len() {
check_op_parse_eof(&input[..i], encoding);
}
check_op_parse_simple(&input, expect, encoding);
}
#[test]
fn test_op_parse_onebyte() {
// Doesn't matter for this test.
let encoding = encoding4();
// Test all single-byte opcodes.
#[rustfmt::skip]
let inputs = [
(
constants::DW_OP_deref,
Operation::Deref {
base_type: generic_type(),
size: encoding.address_size,
space: false,
},
),
(constants::DW_OP_dup, Operation::Pick { index: 0 }),
(constants::DW_OP_drop, Operation::Drop),
(constants::DW_OP_over, Operation::Pick { index: 1 }),
(constants::DW_OP_swap, Operation::Swap),
(constants::DW_OP_rot, Operation::Rot),
(
constants::DW_OP_xderef,
Operation::Deref {
base_type: generic_type(),
size: encoding.address_size,
space: true,
},
),
(constants::DW_OP_abs, Operation::Abs),
(constants::DW_OP_and, Operation::And),
(constants::DW_OP_div, Operation::Div),
(constants::DW_OP_minus, Operation::Minus),
(constants::DW_OP_mod, Operation::Mod),
(constants::DW_OP_mul, Operation::Mul),
(constants::DW_OP_neg, Operation::Neg),
(constants::DW_OP_not, Operation::Not),
(constants::DW_OP_or, Operation::Or),
(constants::DW_OP_plus, Operation::Plus),
(constants::DW_OP_shl, Operation::Shl),
(constants::DW_OP_shr, Operation::Shr),
(constants::DW_OP_shra, Operation::Shra),
(constants::DW_OP_xor, Operation::Xor),
(constants::DW_OP_eq, Operation::Eq),
(constants::DW_OP_ge, Operation::Ge),
(constants::DW_OP_gt, Operation::Gt),
(constants::DW_OP_le, Operation::Le),
(constants::DW_OP_lt, Operation::Lt),
(constants::DW_OP_ne, Operation::Ne),
(constants::DW_OP_lit0, Operation::UnsignedConstant { value: 0 }),
(constants::DW_OP_lit1, Operation::UnsignedConstant { value: 1 }),
(constants::DW_OP_lit2, Operation::UnsignedConstant { value: 2 }),
(constants::DW_OP_lit3, Operation::UnsignedConstant { value: 3 }),
(constants::DW_OP_lit4, Operation::UnsignedConstant { value: 4 }),
(constants::DW_OP_lit5, Operation::UnsignedConstant { value: 5 }),
(constants::DW_OP_lit6, Operation::UnsignedConstant { value: 6 }),
(constants::DW_OP_lit7, Operation::UnsignedConstant { value: 7 }),
(constants::DW_OP_lit8, Operation::UnsignedConstant { value: 8 }),
(constants::DW_OP_lit9, Operation::UnsignedConstant { value: 9 }),
(constants::DW_OP_lit10, Operation::UnsignedConstant { value: 10 }),
(constants::DW_OP_lit11, Operation::UnsignedConstant { value: 11 }),
(constants::DW_OP_lit12, Operation::UnsignedConstant { value: 12 }),
(constants::DW_OP_lit13, Operation::UnsignedConstant { value: 13 }),
(constants::DW_OP_lit14, Operation::UnsignedConstant { value: 14 }),
(constants::DW_OP_lit15, Operation::UnsignedConstant { value: 15 }),
(constants::DW_OP_lit16, Operation::UnsignedConstant { value: 16 }),
(constants::DW_OP_lit17, Operation::UnsignedConstant { value: 17 }),
(constants::DW_OP_lit18, Operation::UnsignedConstant { value: 18 }),
(constants::DW_OP_lit19, Operation::UnsignedConstant { value: 19 }),
(constants::DW_OP_lit20, Operation::UnsignedConstant { value: 20 }),
(constants::DW_OP_lit21, Operation::UnsignedConstant { value: 21 }),
(constants::DW_OP_lit22, Operation::UnsignedConstant { value: 22 }),
(constants::DW_OP_lit23, Operation::UnsignedConstant { value: 23 }),
(constants::DW_OP_lit24, Operation::UnsignedConstant { value: 24 }),
(constants::DW_OP_lit25, Operation::UnsignedConstant { value: 25 }),
(constants::DW_OP_lit26, Operation::UnsignedConstant { value: 26 }),
(constants::DW_OP_lit27, Operation::UnsignedConstant { value: 27 }),
(constants::DW_OP_lit28, Operation::UnsignedConstant { value: 28 }),
(constants::DW_OP_lit29, Operation::UnsignedConstant { value: 29 }),
(constants::DW_OP_lit30, Operation::UnsignedConstant { value: 30 }),
(constants::DW_OP_lit31, Operation::UnsignedConstant { value: 31 }),
(constants::DW_OP_reg0, Operation::Register { register: Register(0) }),
(constants::DW_OP_reg1, Operation::Register { register: Register(1) }),
(constants::DW_OP_reg2, Operation::Register { register: Register(2) }),
(constants::DW_OP_reg3, Operation::Register { register: Register(3) }),
(constants::DW_OP_reg4, Operation::Register { register: Register(4) }),
(constants::DW_OP_reg5, Operation::Register { register: Register(5) }),
(constants::DW_OP_reg6, Operation::Register { register: Register(6) }),
(constants::DW_OP_reg7, Operation::Register { register: Register(7) }),
(constants::DW_OP_reg8, Operation::Register { register: Register(8) }),
(constants::DW_OP_reg9, Operation::Register { register: Register(9) }),
(constants::DW_OP_reg10, Operation::Register { register: Register(10) }),
(constants::DW_OP_reg11, Operation::Register { register: Register(11) }),
(constants::DW_OP_reg12, Operation::Register { register: Register(12) }),
(constants::DW_OP_reg13, Operation::Register { register: Register(13) }),
(constants::DW_OP_reg14, Operation::Register { register: Register(14) }),
(constants::DW_OP_reg15, Operation::Register { register: Register(15) }),
(constants::DW_OP_reg16, Operation::Register { register: Register(16) }),
(constants::DW_OP_reg17, Operation::Register { register: Register(17) }),
(constants::DW_OP_reg18, Operation::Register { register: Register(18) }),
(constants::DW_OP_reg19, Operation::Register { register: Register(19) }),
(constants::DW_OP_reg20, Operation::Register { register: Register(20) }),
(constants::DW_OP_reg21, Operation::Register { register: Register(21) }),
(constants::DW_OP_reg22, Operation::Register { register: Register(22) }),
(constants::DW_OP_reg23, Operation::Register { register: Register(23) }),
(constants::DW_OP_reg24, Operation::Register { register: Register(24) }),
(constants::DW_OP_reg25, Operation::Register { register: Register(25) }),
(constants::DW_OP_reg26, Operation::Register { register: Register(26) }),
(constants::DW_OP_reg27, Operation::Register { register: Register(27) }),
(constants::DW_OP_reg28, Operation::Register { register: Register(28) }),
(constants::DW_OP_reg29, Operation::Register { register: Register(29) }),
(constants::DW_OP_reg30, Operation::Register { register: Register(30) }),
(constants::DW_OP_reg31, Operation::Register { register: Register(31) }),
(constants::DW_OP_nop, Operation::Nop),
(constants::DW_OP_push_object_address, Operation::PushObjectAddress),
(constants::DW_OP_form_tls_address, Operation::TLS),
(constants::DW_OP_GNU_push_tls_address, Operation::TLS),
(constants::DW_OP_call_frame_cfa, Operation::CallFrameCFA),
(constants::DW_OP_stack_value, Operation::StackValue),
];
let input = [];
check_op_parse_eof(&input[..], encoding);
for item in inputs.iter() {
let (opcode, ref result) = *item;
check_op_parse(|s| s.D8(opcode.0), result, encoding);
}
}
#[test]
fn test_op_parse_twobyte() {
// Doesn't matter for this test.
let encoding = encoding4();
let inputs = [
(
constants::DW_OP_const1u,
23,
Operation::UnsignedConstant { value: 23 },
),
(
constants::DW_OP_const1s,
(-23i8) as u8,
Operation::SignedConstant { value: -23 },
),
(constants::DW_OP_pick, 7, Operation::Pick { index: 7 }),
(
constants::DW_OP_deref_size,
19,
Operation::Deref {
base_type: generic_type(),
size: 19,
space: false,
},
),
(
constants::DW_OP_xderef_size,
19,
Operation::Deref {
base_type: generic_type(),
size: 19,
space: true,
},
),
];
for item in inputs.iter() {
let (opcode, arg, ref result) = *item;
check_op_parse(|s| s.D8(opcode.0).D8(arg), result, encoding);
}
}
#[test]
fn test_op_parse_threebyte() {
// Doesn't matter for this test.
let encoding = encoding4();
// While bra and skip are 3-byte opcodes, they aren't tested here,
// but rather specially in their own function.
let inputs = [
(
constants::DW_OP_const2u,
23,
Operation::UnsignedConstant { value: 23 },
),
(
constants::DW_OP_const2s,
(-23i16) as u16,
Operation::SignedConstant { value: -23 },
),
(
constants::DW_OP_call2,
1138,
Operation::Call {
offset: DieReference::UnitRef(UnitOffset(1138)),
},
),
(
constants::DW_OP_bra,
(-23i16) as u16,
Operation::Bra { target: -23 },
),
(
constants::DW_OP_skip,
(-23i16) as u16,
Operation::Skip { target: -23 },
),
];
for item in inputs.iter() {
let (opcode, arg, ref result) = *item;
check_op_parse(|s| s.D8(opcode.0).L16(arg), result, encoding);
}
}
#[test]
fn test_op_parse_fivebyte() {
// There are some tests here that depend on address size.
let encoding = encoding4();
let inputs = [
(
constants::DW_OP_addr,
0x1234_5678,
Operation::Address {
address: 0x1234_5678,
},
),
(
constants::DW_OP_const4u,
0x1234_5678,
Operation::UnsignedConstant { value: 0x1234_5678 },
),
(
constants::DW_OP_const4s,
(-23i32) as u32,
Operation::SignedConstant { value: -23 },
),
(
constants::DW_OP_call4,
0x1234_5678,
Operation::Call {
offset: DieReference::UnitRef(UnitOffset(0x1234_5678)),
},
),
(
constants::DW_OP_call_ref,
0x1234_5678,
Operation::Call {
offset: DieReference::DebugInfoRef(DebugInfoOffset(0x1234_5678)),
},
),
];
for item in inputs.iter() {
let (op, arg, ref expect) = *item;
check_op_parse(|s| s.D8(op.0).L32(arg), expect, encoding);
}
}
#[test]
#[cfg(target_pointer_width = "64")]
fn test_op_parse_ninebyte() {
// There are some tests here that depend on address size.
let encoding = encoding8();
let inputs = [
(
constants::DW_OP_addr,
0x1234_5678_1234_5678,
Operation::Address {
address: 0x1234_5678_1234_5678,
},
),
(
constants::DW_OP_const8u,
0x1234_5678_1234_5678,
Operation::UnsignedConstant {
value: 0x1234_5678_1234_5678,
},
),
(
constants::DW_OP_const8s,
(-23i64) as u64,
Operation::SignedConstant { value: -23 },
),
(
constants::DW_OP_call_ref,
0x1234_5678_1234_5678,
Operation::Call {
offset: DieReference::DebugInfoRef(DebugInfoOffset(0x1234_5678_1234_5678)),
},
),
];
for item in inputs.iter() {
let (op, arg, ref expect) = *item;
check_op_parse(|s| s.D8(op.0).L64(arg), expect, encoding);
}
}
#[test]
fn test_op_parse_sleb() {
// Doesn't matter for this test.
let encoding = encoding4();
let values = [
-1i64,
0,
1,
0x100,
0x1eee_eeee,
0x7fff_ffff_ffff_ffff,
-0x100,
-0x1eee_eeee,
-0x7fff_ffff_ffff_ffff,
];
for value in values.iter() {
let mut inputs = vec![
(
constants::DW_OP_consts.0,
Operation::SignedConstant { value: *value },
),
(
constants::DW_OP_fbreg.0,
Operation::FrameOffset { offset: *value },
),
];
for i in 0..32 {
inputs.push((
constants::DW_OP_breg0.0 + i,
Operation::RegisterOffset {
register: Register(i.into()),
offset: *value,
base_type: UnitOffset(0),
},
));
}
for item in inputs.iter() {
let (op, ref expect) = *item;
check_op_parse(|s| s.D8(op).sleb(*value), expect, encoding);
}
}
}
#[test]
fn test_op_parse_uleb() {
// Doesn't matter for this test.
let encoding = encoding4();
let values = [
0,
1,
0x100,
(!0u16).into(),
0x1eee_eeee,
0x7fff_ffff_ffff_ffff,
!0u64,
];
for value in values.iter() {
let mut inputs = vec![
(
constants::DW_OP_constu,
Operation::UnsignedConstant { value: *value },
),
(
constants::DW_OP_plus_uconst,
Operation::PlusConstant { value: *value },
),
];
if *value <= (!0u16).into() {
inputs.push((
constants::DW_OP_regx,
Operation::Register {
register: Register::from_u64(*value).unwrap(),
},
));
}
if *value <= (!0u32).into() {
inputs.extend(&[
(
constants::DW_OP_addrx,
Operation::AddressIndex {
index: DebugAddrIndex(*value as usize),
},
),
(
constants::DW_OP_constx,
Operation::ConstantIndex {
index: DebugAddrIndex(*value as usize),
},
),
]);
}
// FIXME
if *value < !0u64 / 8 {
inputs.push((
constants::DW_OP_piece,
Operation::Piece {
size_in_bits: 8 * value,
bit_offset: None,
},
));
}
for item in inputs.iter() {
let (op, ref expect) = *item;
let input = Section::with_endian(Endian::Little)
.D8(op.0)
.uleb(*value)
.get_contents()
.unwrap();
check_op_parse_simple(&input, expect, encoding);
}
}
}
#[test]
fn test_op_parse_bregx() {
// Doesn't matter for this test.
let encoding = encoding4();
let uvalues = [0, 1, 0x100, !0u16];
let svalues = [
-1i64,
0,
1,
0x100,
0x1eee_eeee,
0x7fff_ffff_ffff_ffff,
-0x100,
-0x1eee_eeee,
-0x7fff_ffff_ffff_ffff,
];
for v1 in uvalues.iter() {
for v2 in svalues.iter() {
check_op_parse(
|s| s.D8(constants::DW_OP_bregx.0).uleb((*v1).into()).sleb(*v2),
&Operation::RegisterOffset {
register: Register(*v1),
offset: *v2,
base_type: UnitOffset(0),
},
encoding,
);
}
}
}
#[test]
fn test_op_parse_bit_piece() {
// Doesn't matter for this test.
let encoding = encoding4();
let values = [0, 1, 0x100, 0x1eee_eeee, 0x7fff_ffff_ffff_ffff, !0u64];
for v1 in values.iter() {
for v2 in values.iter() {
let input = Section::with_endian(Endian::Little)
.D8(constants::DW_OP_bit_piece.0)
.uleb(*v1)
.uleb(*v2)
.get_contents()
.unwrap();
check_op_parse_simple(
&input,
&Operation::Piece {
size_in_bits: *v1,
bit_offset: Some(*v2),
},
encoding,
);
}
}
}
#[test]
fn test_op_parse_implicit_value() {
// Doesn't matter for this test.
let encoding = encoding4();
let data = b"hello";
check_op_parse(
|s| {
s.D8(constants::DW_OP_implicit_value.0)
.uleb(data.len() as u64)
.append_bytes(&data[..])
},
&Operation::ImplicitValue {
data: EndianSlice::new(&data[..], LittleEndian),
},
encoding,
);
}
#[test]
fn test_op_parse_const_type() {
// Doesn't matter for this test.
let encoding = encoding4();
let data = b"hello";
check_op_parse(
|s| {
s.D8(constants::DW_OP_const_type.0)
.uleb(100)
.D8(data.len() as u8)
.append_bytes(&data[..])
},
&Operation::TypedLiteral {
base_type: UnitOffset(100),
value: EndianSlice::new(&data[..], LittleEndian),
},
encoding,
);
check_op_parse(
|s| {
s.D8(constants::DW_OP_GNU_const_type.0)
.uleb(100)
.D8(data.len() as u8)
.append_bytes(&data[..])
},
&Operation::TypedLiteral {
base_type: UnitOffset(100),
value: EndianSlice::new(&data[..], LittleEndian),
},
encoding,
);
}
#[test]
fn test_op_parse_regval_type() {
// Doesn't matter for this test.
let encoding = encoding4();
check_op_parse(
|s| s.D8(constants::DW_OP_regval_type.0).uleb(1).uleb(100),
&Operation::RegisterOffset {
register: Register(1),
offset: 0,
base_type: UnitOffset(100),
},
encoding,
);
check_op_parse(
|s| s.D8(constants::DW_OP_GNU_regval_type.0).uleb(1).uleb(100),
&Operation::RegisterOffset {
register: Register(1),
offset: 0,
base_type: UnitOffset(100),
},
encoding,
);
}
#[test]
fn test_op_parse_deref_type() {
// Doesn't matter for this test.
let encoding = encoding4();
check_op_parse(
|s| s.D8(constants::DW_OP_deref_type.0).D8(8).uleb(100),
&Operation::Deref {
base_type: UnitOffset(100),
size: 8,
space: false,
},
encoding,
);
check_op_parse(
|s| s.D8(constants::DW_OP_GNU_deref_type.0).D8(8).uleb(100),
&Operation::Deref {
base_type: UnitOffset(100),
size: 8,
space: false,
},
encoding,
);
check_op_parse(
|s| s.D8(constants::DW_OP_xderef_type.0).D8(8).uleb(100),
&Operation::Deref {
base_type: UnitOffset(100),
size: 8,
space: true,
},
encoding,
);
}
#[test]
fn test_op_convert() {
// Doesn't matter for this test.
let encoding = encoding4();
check_op_parse(
|s| s.D8(constants::DW_OP_convert.0).uleb(100),
&Operation::Convert {
base_type: UnitOffset(100),
},
encoding,
);
check_op_parse(
|s| s.D8(constants::DW_OP_GNU_convert.0).uleb(100),
&Operation::Convert {
base_type: UnitOffset(100),
},
encoding,
);
}
#[test]
fn test_op_reinterpret() {
// Doesn't matter for this test.
let encoding = encoding4();
check_op_parse(
|s| s.D8(constants::DW_OP_reinterpret.0).uleb(100),
&Operation::Reinterpret {
base_type: UnitOffset(100),
},
encoding,
);
check_op_parse(
|s| s.D8(constants::DW_OP_GNU_reinterpret.0).uleb(100),
&Operation::Reinterpret {
base_type: UnitOffset(100),
},
encoding,
);
}
#[test]
fn test_op_parse_implicit_pointer() {
for op in &[
constants::DW_OP_implicit_pointer,
constants::DW_OP_GNU_implicit_pointer,
] {
check_op_parse(
|s| s.D8(op.0).D32(0x1234_5678).sleb(0x123),
&Operation::ImplicitPointer {
value: DebugInfoOffset(0x1234_5678),
byte_offset: 0x123,
},
encoding4(),
);
check_op_parse(
|s| s.D8(op.0).D64(0x1234_5678).sleb(0x123),
&Operation::ImplicitPointer {
value: DebugInfoOffset(0x1234_5678),
byte_offset: 0x123,
},
encoding8(),
);
check_op_parse(
|s| s.D8(op.0).D64(0x1234_5678).sleb(0x123),
&Operation::ImplicitPointer {
value: DebugInfoOffset(0x1234_5678),
byte_offset: 0x123,
},
Encoding {
format: Format::Dwarf32,
version: 2,
address_size: 8,
},
)
}
}
#[test]
fn test_op_parse_entry_value() {
for op in &[
constants::DW_OP_entry_value,
constants::DW_OP_GNU_entry_value,
] {
let data = b"hello";
check_op_parse(
|s| s.D8(op.0).uleb(data.len() as u64).append_bytes(&data[..]),
&Operation::EntryValue {
expression: EndianSlice::new(&data[..], LittleEndian),
},
encoding4(),
);
}
}
#[test]
fn test_op_parse_gnu_parameter_ref() {
check_op_parse(
|s| s.D8(constants::DW_OP_GNU_parameter_ref.0).D32(0x1234_5678),
&Operation::ParameterRef {
offset: UnitOffset(0x1234_5678),
},
encoding4(),
)
}
#[test]
fn test_op_wasm() {
// Doesn't matter for this test.
let encoding = encoding4();
check_op_parse(
|s| s.D8(constants::DW_OP_WASM_location.0).D8(0).uleb(1000),
&Operation::WasmLocal { index: 1000 },
encoding,
);
check_op_parse(
|s| s.D8(constants::DW_OP_WASM_location.0).D8(1).uleb(1000),
&Operation::WasmGlobal { index: 1000 },
encoding,
);
check_op_parse(
|s| s.D8(constants::DW_OP_WASM_location.0).D8(2).uleb(1000),
&Operation::WasmStack { index: 1000 },
encoding,
);
check_op_parse(
|s| s.D8(constants::DW_OP_WASM_location.0).D8(3).D32(1000),
&Operation::WasmGlobal { index: 1000 },
encoding,
);
}
enum AssemblerEntry {
Op(constants::DwOp),
Mark(u8),
Branch(u8),
U8(u8),
U16(u16),
U32(u32),
U64(u64),
Uleb(u64),
Sleb(u64),
}
fn assemble(entries: &[AssemblerEntry]) -> Vec<u8> {
let mut result = Vec::new();
struct Marker(Option<usize>, Vec<usize>);
let mut markers = Vec::new();
for _ in 0..256 {
markers.push(Marker(None, Vec::new()));
}
fn write(stack: &mut [u8], index: usize, mut num: u64, nbytes: u8) {
for i in 0..nbytes as usize {
stack[index + i] = (num & 0xff) as u8;
num >>= 8;
}
}
fn push(stack: &mut Vec<u8>, num: u64, nbytes: u8) {
let index = stack.len();
for _ in 0..nbytes {
stack.push(0);
}
write(stack, index, num, nbytes);
}
for item in entries {
match *item {
AssemblerEntry::Op(op) => result.push(op.0),
AssemblerEntry::Mark(num) => {
assert!(markers[num as usize].0.is_none());
markers[num as usize].0 = Some(result.len());
}
AssemblerEntry::Branch(num) => {
markers[num as usize].1.push(result.len());
push(&mut result, 0, 2);
}
AssemblerEntry::U8(num) => result.push(num),
AssemblerEntry::U16(num) => push(&mut result, u64::from(num), 2),
AssemblerEntry::U32(num) => push(&mut result, u64::from(num), 4),
AssemblerEntry::U64(num) => push(&mut result, num, 8),
AssemblerEntry::Uleb(num) => {
leb128::write::unsigned(&mut result, num).unwrap();
}
AssemblerEntry::Sleb(num) => {
leb128::write::signed(&mut result, num as i64).unwrap();
}
}
}
// Update all the branches.
for marker in markers {
if let Some(offset) = marker.0 {
for branch_offset in marker.1 {
let delta = offset.wrapping_sub(branch_offset + 2) as u64;
write(&mut result, branch_offset, delta, 2);
}
}
}
result
}
fn check_eval_with_args<F>(
program: &[AssemblerEntry],
expect: Result<&[Piece<EndianSlice<LittleEndian>>]>,
encoding: Encoding,
object_address: Option<u64>,
initial_value: Option<u64>,
max_iterations: Option<u32>,
f: F,
) where
for<'a> F: Fn(
&mut Evaluation<EndianSlice<'a, LittleEndian>>,
EvaluationResult<EndianSlice<'a, LittleEndian>>,
) -> Result<EvaluationResult<EndianSlice<'a, LittleEndian>>>,
{
let bytes = assemble(program);
let bytes = EndianSlice::new(&bytes, LittleEndian);
let mut eval = Evaluation::new(bytes, encoding);
if let Some(val) = object_address {
eval.set_object_address(val);
}
if let Some(val) = initial_value {
eval.set_initial_value(val);
}
if let Some(val) = max_iterations {
eval.set_max_iterations(val);
}
let result = match eval.evaluate() {
Err(e) => Err(e),
Ok(r) => f(&mut eval, r),
};
match (result, expect) {
(Ok(EvaluationResult::Complete), Ok(pieces)) => {
let vec = eval.result();
assert_eq!(vec.len(), pieces.len());
for i in 0..pieces.len() {
assert_eq!(vec[i], pieces[i]);
}
}
(Err(f1), Err(f2)) => {
assert_eq!(f1, f2);
}
otherwise => panic!("Unexpected result: {:?}", otherwise),
}
}
fn check_eval(
program: &[AssemblerEntry],
expect: Result<&[Piece<EndianSlice<LittleEndian>>]>,
encoding: Encoding,
) {
check_eval_with_args(program, expect, encoding, None, None, None, |_, result| {
Ok(result)
});
}
#[test]
fn test_eval_arith() {
// It's nice if an operation and its arguments can fit on a single
// line in the test program.
use self::AssemblerEntry::*;
use crate::constants::*;
// Indices of marks in the assembly.
let done = 0;
let fail = 1;
#[rustfmt::skip]
let program = [
Op(DW_OP_const1u), U8(23),
Op(DW_OP_const1s), U8((-23i8) as u8),
Op(DW_OP_plus),
Op(DW_OP_bra), Branch(fail),
Op(DW_OP_const2u), U16(23),
Op(DW_OP_const2s), U16((-23i16) as u16),
Op(DW_OP_plus),
Op(DW_OP_bra), Branch(fail),
Op(DW_OP_const4u), U32(0x1111_2222),
Op(DW_OP_const4s), U32((-0x1111_2222i32) as u32),
Op(DW_OP_plus),
Op(DW_OP_bra), Branch(fail),
// Plus should overflow.
Op(DW_OP_const1s), U8(0xff),
Op(DW_OP_const1u), U8(1),
Op(DW_OP_plus),
Op(DW_OP_bra), Branch(fail),
Op(DW_OP_const1s), U8(0xff),
Op(DW_OP_plus_uconst), Uleb(1),
Op(DW_OP_bra), Branch(fail),
// Minus should underflow.
Op(DW_OP_const1s), U8(0),
Op(DW_OP_const1u), U8(1),
Op(DW_OP_minus),
Op(DW_OP_const1s), U8(0xff),
Op(DW_OP_ne),
Op(DW_OP_bra), Branch(fail),
Op(DW_OP_const1s), U8(0xff),
Op(DW_OP_abs),
Op(DW_OP_const1u), U8(1),
Op(DW_OP_minus),
Op(DW_OP_bra), Branch(fail),
Op(DW_OP_const4u), U32(0xf078_fffe),
Op(DW_OP_const4u), U32(0x0f87_0001),
Op(DW_OP_and),
Op(DW_OP_bra), Branch(fail),
Op(DW_OP_const4u), U32(0xf078_fffe),
Op(DW_OP_const4u), U32(0xf000_00fe),
Op(DW_OP_and),
Op(DW_OP_const4u), U32(0xf000_00fe),
Op(DW_OP_ne),
Op(DW_OP_bra), Branch(fail),
// Division is signed.
Op(DW_OP_const1s), U8(0xfe),
Op(DW_OP_const1s), U8(2),
Op(DW_OP_div),
Op(DW_OP_plus_uconst), Uleb(1),
Op(DW_OP_bra), Branch(fail),
// Mod is unsigned.
Op(DW_OP_const1s), U8(0xfd),
Op(DW_OP_const1s), U8(2),
Op(DW_OP_mod),
Op(DW_OP_neg),
Op(DW_OP_plus_uconst), Uleb(1),
Op(DW_OP_bra), Branch(fail),
// Overflow is defined for multiplication.
Op(DW_OP_const4u), U32(0x8000_0001),
Op(DW_OP_lit2),
Op(DW_OP_mul),
Op(DW_OP_lit2),
Op(DW_OP_ne),
Op(DW_OP_bra), Branch(fail),
Op(DW_OP_const4u), U32(0xf0f0_f0f0),
Op(DW_OP_const4u), U32(0xf0f0_f0f0),
Op(DW_OP_xor),
Op(DW_OP_bra), Branch(fail),
Op(DW_OP_const4u), U32(0xf0f0_f0f0),
Op(DW_OP_const4u), U32(0x0f0f_0f0f),
Op(DW_OP_or),
Op(DW_OP_not),
Op(DW_OP_bra), Branch(fail),
// In 32 bit mode, values are truncated.
Op(DW_OP_const8u), U64(0xffff_ffff_0000_0000),
Op(DW_OP_lit2),
Op(DW_OP_div),
Op(DW_OP_bra), Branch(fail),
Op(DW_OP_const1u), U8(0xff),
Op(DW_OP_lit1),
Op(DW_OP_shl),
Op(DW_OP_const2u), U16(0x1fe),
Op(DW_OP_ne),
Op(DW_OP_bra), Branch(fail),
Op(DW_OP_const1u), U8(0xff),
Op(DW_OP_const1u), U8(50),
Op(DW_OP_shl),
Op(DW_OP_bra), Branch(fail),
// Absurd shift.
Op(DW_OP_const1u), U8(0xff),
Op(DW_OP_const1s), U8(0xff),
Op(DW_OP_shl),
Op(DW_OP_bra), Branch(fail),
Op(DW_OP_const1s), U8(0xff),
Op(DW_OP_lit1),
Op(DW_OP_shr),
Op(DW_OP_const4u), U32(0x7fff_ffff),
Op(DW_OP_ne),
Op(DW_OP_bra), Branch(fail),
Op(DW_OP_const1s), U8(0xff),
Op(DW_OP_const1u), U8(0xff),
Op(DW_OP_shr),
Op(DW_OP_bra), Branch(fail),
Op(DW_OP_const1s), U8(0xff),
Op(DW_OP_lit1),
Op(DW_OP_shra),
Op(DW_OP_const1s), U8(0xff),
Op(DW_OP_ne),
Op(DW_OP_bra), Branch(fail),
Op(DW_OP_const1s), U8(0xff),
Op(DW_OP_const1u), U8(0xff),
Op(DW_OP_shra),
Op(DW_OP_const1s), U8(0xff),
Op(DW_OP_ne),
Op(DW_OP_bra), Branch(fail),
// Success.
Op(DW_OP_lit0),
Op(DW_OP_nop),
Op(DW_OP_skip), Branch(done),
Mark(fail),
Op(DW_OP_lit1),
Mark(done),
Op(DW_OP_stack_value),
];
let result = [Piece {
size_in_bits: None,
bit_offset: None,
location: Location::Value {
value: Value::Generic(0),
},
}];
check_eval(&program, Ok(&result), encoding4());
}
#[test]
fn test_eval_arith64() {
// It's nice if an operation and its arguments can fit on a single
// line in the test program.
use self::AssemblerEntry::*;
use crate::constants::*;
// Indices of marks in the assembly.
let done = 0;
let fail = 1;
#[rustfmt::skip]
let program = [
Op(DW_OP_const8u), U64(0x1111_2222_3333_4444),
Op(DW_OP_const8s), U64((-0x1111_2222_3333_4444i64) as u64),
Op(DW_OP_plus),
Op(DW_OP_bra), Branch(fail),
Op(DW_OP_constu), Uleb(0x1111_2222_3333_4444),
Op(DW_OP_consts), Sleb((-0x1111_2222_3333_4444i64) as u64),
Op(DW_OP_plus),
Op(DW_OP_bra), Branch(fail),
Op(DW_OP_lit1),
Op(DW_OP_plus_uconst), Uleb(!0u64),
Op(DW_OP_bra), Branch(fail),
Op(DW_OP_lit1),
Op(DW_OP_neg),
Op(DW_OP_not),
Op(DW_OP_bra), Branch(fail),
Op(DW_OP_const8u), U64(0x8000_0000_0000_0000),
Op(DW_OP_const1u), U8(63),
Op(DW_OP_shr),
Op(DW_OP_lit1),
Op(DW_OP_ne),
Op(DW_OP_bra), Branch(fail),
Op(DW_OP_const8u), U64(0x8000_0000_0000_0000),
Op(DW_OP_const1u), U8(62),
Op(DW_OP_shra),
Op(DW_OP_plus_uconst), Uleb(2),
Op(DW_OP_bra), Branch(fail),
Op(DW_OP_lit1),
Op(DW_OP_const1u), U8(63),
Op(DW_OP_shl),
Op(DW_OP_const8u), U64(0x8000_0000_0000_0000),
Op(DW_OP_ne),
Op(DW_OP_bra), Branch(fail),
// Success.
Op(DW_OP_lit0),
Op(DW_OP_nop),
Op(DW_OP_skip), Branch(done),
Mark(fail),
Op(DW_OP_lit1),
Mark(done),
Op(DW_OP_stack_value),
];
let result = [Piece {
size_in_bits: None,
bit_offset: None,
location: Location::Value {
value: Value::Generic(0),
},
}];
check_eval(&program, Ok(&result), encoding8());
}
#[test]
fn test_eval_compare() {
// It's nice if an operation and its arguments can fit on a single
// line in the test program.
use self::AssemblerEntry::*;
use crate::constants::*;
// Indices of marks in the assembly.
let done = 0;
let fail = 1;
#[rustfmt::skip]
let program = [
// Comparisons are signed.
Op(DW_OP_const1s), U8(1),
Op(DW_OP_const1s), U8(0xff),
Op(DW_OP_lt),
Op(DW_OP_bra), Branch(fail),
Op(DW_OP_const1s), U8(0xff),
Op(DW_OP_const1s), U8(1),
Op(DW_OP_gt),
Op(DW_OP_bra), Branch(fail),
Op(DW_OP_const1s), U8(1),
Op(DW_OP_const1s), U8(0xff),
Op(DW_OP_le),
Op(DW_OP_bra), Branch(fail),
Op(DW_OP_const1s), U8(0xff),
Op(DW_OP_const1s), U8(1),
Op(DW_OP_ge),
Op(DW_OP_bra), Branch(fail),
Op(DW_OP_const1s), U8(0xff),
Op(DW_OP_const1s), U8(1),
Op(DW_OP_eq),
Op(DW_OP_bra), Branch(fail),
Op(DW_OP_const4s), U32(1),
Op(DW_OP_const1s), U8(1),
Op(DW_OP_ne),
Op(DW_OP_bra), Branch(fail),
// Success.
Op(DW_OP_lit0),
Op(DW_OP_nop),
Op(DW_OP_skip), Branch(done),
Mark(fail),
Op(DW_OP_lit1),
Mark(done),
Op(DW_OP_stack_value),
];
let result = [Piece {
size_in_bits: None,
bit_offset: None,
location: Location::Value {
value: Value::Generic(0),
},
}];
check_eval(&program, Ok(&result), encoding4());
}
#[test]
fn test_eval_stack() {
// It's nice if an operation and its arguments can fit on a single
// line in the test program.
use self::AssemblerEntry::*;
use crate::constants::*;
#[rustfmt::skip]
let program = [
Op(DW_OP_lit17), // -- 17
Op(DW_OP_dup), // -- 17 17
Op(DW_OP_over), // -- 17 17 17
Op(DW_OP_minus), // -- 17 0
Op(DW_OP_swap), // -- 0 17
Op(DW_OP_dup), // -- 0 17 17
Op(DW_OP_plus_uconst), Uleb(1), // -- 0 17 18
Op(DW_OP_rot), // -- 18 0 17
Op(DW_OP_pick), U8(2), // -- 18 0 17 18
Op(DW_OP_pick), U8(3), // -- 18 0 17 18 18
Op(DW_OP_minus), // -- 18 0 17 0
Op(DW_OP_drop), // -- 18 0 17
Op(DW_OP_swap), // -- 18 17 0
Op(DW_OP_drop), // -- 18 17
Op(DW_OP_minus), // -- 1
Op(DW_OP_stack_value),
];
let result = [Piece {
size_in_bits: None,
bit_offset: None,
location: Location::Value {
value: Value::Generic(1),
},
}];
check_eval(&program, Ok(&result), encoding4());
}
#[test]
fn test_eval_lit_and_reg() {
// It's nice if an operation and its arguments can fit on a single
// line in the test program.
use self::AssemblerEntry::*;
use crate::constants::*;
let mut program = Vec::new();
program.push(Op(DW_OP_lit0));
for i in 0..32 {
program.push(Op(DwOp(DW_OP_lit0.0 + i)));
program.push(Op(DwOp(DW_OP_breg0.0 + i)));
program.push(Sleb(u64::from(i)));
program.push(Op(DW_OP_plus));
program.push(Op(DW_OP_plus));
}
program.push(Op(DW_OP_bregx));
program.push(Uleb(0x1234));
program.push(Sleb(0x1234));
program.push(Op(DW_OP_plus));
program.push(Op(DW_OP_stack_value));
let result = [Piece {
size_in_bits: None,
bit_offset: None,
location: Location::Value {
value: Value::Generic(496),
},
}];
check_eval_with_args(
&program,
Ok(&result),
encoding4(),
None,
None,
None,
|eval, mut result| {
while result != EvaluationResult::Complete {
result = eval.resume_with_register(match result {
EvaluationResult::RequiresRegister {
register,
base_type,
} => {
assert_eq!(base_type, UnitOffset(0));
Value::Generic(u64::from(register.0).wrapping_neg())
}
_ => panic!(),
})?;
}
Ok(result)
},
);
}
#[test]
fn test_eval_memory() {
// It's nice if an operation and its arguments can fit on a single
// line in the test program.
use self::AssemblerEntry::*;
use crate::constants::*;
// Indices of marks in the assembly.
let done = 0;
let fail = 1;
#[rustfmt::skip]
let program = [
Op(DW_OP_addr), U32(0x7fff_ffff),
Op(DW_OP_deref),
Op(DW_OP_const4u), U32(0xffff_fffc),
Op(DW_OP_ne),
Op(DW_OP_bra), Branch(fail),
Op(DW_OP_addr), U32(0x7fff_ffff),
Op(DW_OP_deref_size), U8(2),
Op(DW_OP_const4u), U32(0xfffc),
Op(DW_OP_ne),
Op(DW_OP_bra), Branch(fail),
Op(DW_OP_lit1),
Op(DW_OP_addr), U32(0x7fff_ffff),
Op(DW_OP_xderef),
Op(DW_OP_const4u), U32(0xffff_fffd),
Op(DW_OP_ne),
Op(DW_OP_bra), Branch(fail),
Op(DW_OP_lit1),
Op(DW_OP_addr), U32(0x7fff_ffff),
Op(DW_OP_xderef_size), U8(2),
Op(DW_OP_const4u), U32(0xfffd),
Op(DW_OP_ne),
Op(DW_OP_bra), Branch(fail),
Op(DW_OP_lit17),
Op(DW_OP_form_tls_address),
Op(DW_OP_constu), Uleb(!17),
Op(DW_OP_ne),
Op(DW_OP_bra), Branch(fail),
Op(DW_OP_lit17),
Op(DW_OP_GNU_push_tls_address),
Op(DW_OP_constu), Uleb(!17),
Op(DW_OP_ne),
Op(DW_OP_bra), Branch(fail),
Op(DW_OP_addrx), Uleb(0x10),
Op(DW_OP_deref),
Op(DW_OP_const4u), U32(0x4040),
Op(DW_OP_ne),
Op(DW_OP_bra), Branch(fail),
Op(DW_OP_constx), Uleb(17),
Op(DW_OP_form_tls_address),
Op(DW_OP_constu), Uleb(!27),
Op(DW_OP_ne),
Op(DW_OP_bra), Branch(fail),
// Success.
Op(DW_OP_lit0),
Op(DW_OP_nop),
Op(DW_OP_skip), Branch(done),
Mark(fail),
Op(DW_OP_lit1),
Mark(done),
Op(DW_OP_stack_value),
];
let result = [Piece {
size_in_bits: None,
bit_offset: None,
location: Location::Value {
value: Value::Generic(0),
},
}];
check_eval_with_args(
&program,
Ok(&result),
encoding4(),
None,
None,
None,
|eval, mut result| {
while result != EvaluationResult::Complete {
result = match result {
EvaluationResult::RequiresMemory {
address,
size,
space,
base_type,
} => {
assert_eq!(base_type, UnitOffset(0));
let mut v = address << 2;
if let Some(value) = space {
v += value;
}
v &= (1u64 << (8 * size)) - 1;
eval.resume_with_memory(Value::Generic(v))?
}
EvaluationResult::RequiresTls(slot) => eval.resume_with_tls(!slot)?,
EvaluationResult::RequiresRelocatedAddress(address) => {
eval.resume_with_relocated_address(address)?
}
EvaluationResult::RequiresIndexedAddress { index, relocate } => {
if relocate {
eval.resume_with_indexed_address(0x1000 + index.0 as u64)?
} else {
eval.resume_with_indexed_address(10 + index.0 as u64)?
}
}
_ => panic!(),
};
}
Ok(result)
},
);
}
#[test]
fn test_eval_register() {
// It's nice if an operation and its arguments can fit on a single
// line in the test program.
use self::AssemblerEntry::*;
use crate::constants::*;
for i in 0..32 {
#[rustfmt::skip]
let program = [
Op(DwOp(DW_OP_reg0.0 + i)),
// Included only in the "bad" run.
Op(DW_OP_lit23),
];
let ok_result = [Piece {
size_in_bits: None,
bit_offset: None,
location: Location::Register {
register: Register(i.into()),
},
}];
check_eval(&program[..1], Ok(&ok_result), encoding4());
check_eval(
&program,
Err(Error::InvalidExpressionTerminator(1)),
encoding4(),
);
}
#[rustfmt::skip]
let program = [
Op(DW_OP_regx), Uleb(0x1234)
];
let result = [Piece {
size_in_bits: None,
bit_offset: None,
location: Location::Register {
register: Register(0x1234),
},
}];
check_eval(&program, Ok(&result), encoding4());
}
#[test]
fn test_eval_context() {
// It's nice if an operation and its arguments can fit on a single
// line in the test program.
use self::AssemblerEntry::*;
use crate::constants::*;
// Test `frame_base` and `call_frame_cfa` callbacks.
#[rustfmt::skip]
let program = [
Op(DW_OP_fbreg), Sleb((-8i8) as u64),
Op(DW_OP_call_frame_cfa),
Op(DW_OP_plus),
Op(DW_OP_neg),
Op(DW_OP_stack_value)
];
let result = [Piece {
size_in_bits: None,
bit_offset: None,
location: Location::Value {
value: Value::Generic(9),
},
}];
check_eval_with_args(
&program,
Ok(&result),
encoding8(),
None,
None,
None,
|eval, result| {
match result {
EvaluationResult::RequiresFrameBase => {}
_ => panic!(),
};
match eval.resume_with_frame_base(0x0123_4567_89ab_cdef)? {
EvaluationResult::RequiresCallFrameCfa => {}
_ => panic!(),
};
eval.resume_with_call_frame_cfa(0xfedc_ba98_7654_3210)
},
);
// Test `evaluate_entry_value` callback.
#[rustfmt::skip]
let program = [
Op(DW_OP_entry_value), Uleb(8), U64(0x1234_5678),
Op(DW_OP_stack_value)
];
let result = [Piece {
size_in_bits: None,
bit_offset: None,
location: Location::Value {
value: Value::Generic(0x1234_5678),
},
}];
check_eval_with_args(
&program,
Ok(&result),
encoding8(),
None,
None,
None,
|eval, result| {
let entry_value = match result {
EvaluationResult::RequiresEntryValue(mut expression) => {
expression.0.read_u64()?
}
_ => panic!(),
};
eval.resume_with_entry_value(Value::Generic(entry_value))
},
);
// Test missing `object_address` field.
#[rustfmt::skip]
let program = [
Op(DW_OP_push_object_address),
];
check_eval_with_args(
&program,
Err(Error::InvalidPushObjectAddress),
encoding4(),
None,
None,
None,
|_, _| panic!(),
);
// Test `object_address` field.
#[rustfmt::skip]
let program = [
Op(DW_OP_push_object_address),
Op(DW_OP_stack_value),
];
let result = [Piece {
size_in_bits: None,
bit_offset: None,
location: Location::Value {
value: Value::Generic(0xff),
},
}];
check_eval_with_args(
&program,
Ok(&result),
encoding8(),
Some(0xff),
None,
None,
|_, result| Ok(result),
);
// Test `initial_value` field.
#[rustfmt::skip]
let program = [
];
let result = [Piece {
size_in_bits: None,
bit_offset: None,
location: Location::Address {
address: 0x1234_5678,
},
}];
check_eval_with_args(
&program,
Ok(&result),
encoding8(),
None,
Some(0x1234_5678),
None,
|_, result| Ok(result),
);
}
#[test]
fn test_eval_empty_stack() {
// It's nice if an operation and its arguments can fit on a single
// line in the test program.
use self::AssemblerEntry::*;
use crate::constants::*;
#[rustfmt::skip]
let program = [
Op(DW_OP_stack_value)
];
check_eval(&program, Err(Error::NotEnoughStackItems), encoding4());
}
#[test]
fn test_eval_call() {
// It's nice if an operation and its arguments can fit on a single
// line in the test program.
use self::AssemblerEntry::*;
use crate::constants::*;
#[rustfmt::skip]
let program = [
Op(DW_OP_lit23),
Op(DW_OP_call2), U16(0x7755),
Op(DW_OP_call4), U32(0x7755_aaee),
Op(DW_OP_call_ref), U32(0x7755_aaee),
Op(DW_OP_stack_value)
];
let result = [Piece {
size_in_bits: None,
bit_offset: None,
location: Location::Value {
value: Value::Generic(23),
},
}];
check_eval_with_args(
&program,
Ok(&result),
encoding4(),
None,
None,
None,
|eval, result| {
let buf = EndianSlice::new(&[], LittleEndian);
match result {
EvaluationResult::RequiresAtLocation(_) => {}
_ => panic!(),
};
eval.resume_with_at_location(buf)?;
match result {
EvaluationResult::RequiresAtLocation(_) => {}
_ => panic!(),
};
eval.resume_with_at_location(buf)?;
match result {
EvaluationResult::RequiresAtLocation(_) => {}
_ => panic!(),
};
eval.resume_with_at_location(buf)
},
);
// DW_OP_lit2 DW_OP_mul
const SUBR: &[u8] = &[0x32, 0x1e];
let result = [Piece {
size_in_bits: None,
bit_offset: None,
location: Location::Value {
value: Value::Generic(184),
},
}];
check_eval_with_args(
&program,
Ok(&result),
encoding4(),
None,
None,
None,
|eval, result| {
let buf = EndianSlice::new(SUBR, LittleEndian);
match result {
EvaluationResult::RequiresAtLocation(_) => {}
_ => panic!(),
};
eval.resume_with_at_location(buf)?;
match result {
EvaluationResult::RequiresAtLocation(_) => {}
_ => panic!(),
};
eval.resume_with_at_location(buf)?;
match result {
EvaluationResult::RequiresAtLocation(_) => {}
_ => panic!(),
};
eval.resume_with_at_location(buf)
},
);
}
#[test]
fn test_eval_pieces() {
// It's nice if an operation and its arguments can fit on a single
// line in the test program.
use self::AssemblerEntry::*;
use crate::constants::*;
// Example from DWARF 2.6.1.3.
#[rustfmt::skip]
let program = [
Op(DW_OP_reg3),
Op(DW_OP_piece), Uleb(4),
Op(DW_OP_reg4),
Op(DW_OP_piece), Uleb(2),
];
let result = [
Piece {
size_in_bits: Some(32),
bit_offset: None,
location: Location::Register {
register: Register(3),
},
},
Piece {
size_in_bits: Some(16),
bit_offset: None,
location: Location::Register {
register: Register(4),
},
},
];
check_eval(&program, Ok(&result), encoding4());
// Example from DWARF 2.6.1.3 (but hacked since dealing with fbreg
// in the tests is a pain).
#[rustfmt::skip]
let program = [
Op(DW_OP_reg0),
Op(DW_OP_piece), Uleb(4),
Op(DW_OP_piece), Uleb(4),
Op(DW_OP_addr), U32(0x7fff_ffff),
Op(DW_OP_piece), Uleb(4),
];
let result = [
Piece {
size_in_bits: Some(32),
bit_offset: None,
location: Location::Register {
register: Register(0),
},
},
Piece {
size_in_bits: Some(32),
bit_offset: None,
location: Location::Empty,
},
Piece {
size_in_bits: Some(32),
bit_offset: None,
location: Location::Address {
address: 0x7fff_ffff,
},
},
];
check_eval_with_args(
&program,
Ok(&result),
encoding4(),
None,
None,
None,
|eval, mut result| {
while result != EvaluationResult::Complete {
result = match result {
EvaluationResult::RequiresRelocatedAddress(address) => {
eval.resume_with_relocated_address(address)?
}
_ => panic!(),
};
}
Ok(result)
},
);
#[rustfmt::skip]
let program = [
Op(DW_OP_implicit_value), Uleb(5),
U8(23), U8(24), U8(25), U8(26), U8(0),
];
const BYTES: &[u8] = &[23, 24, 25, 26, 0];
let result = [Piece {
size_in_bits: None,
bit_offset: None,
location: Location::Bytes {
value: EndianSlice::new(BYTES, LittleEndian),
},
}];
check_eval(&program, Ok(&result), encoding4());
#[rustfmt::skip]
let program = [
Op(DW_OP_lit7),
Op(DW_OP_stack_value),
Op(DW_OP_bit_piece), Uleb(5), Uleb(0),
Op(DW_OP_bit_piece), Uleb(3), Uleb(0),
];
let result = [
Piece {
size_in_bits: Some(5),
bit_offset: Some(0),
location: Location::Value {
value: Value::Generic(7),
},
},
Piece {
size_in_bits: Some(3),
bit_offset: Some(0),
location: Location::Empty,
},
];
check_eval(&program, Ok(&result), encoding4());
#[rustfmt::skip]
let program = [
Op(DW_OP_lit7),
];
let result = [Piece {
size_in_bits: None,
bit_offset: None,
location: Location::Address { address: 7 },
}];
check_eval(&program, Ok(&result), encoding4());
#[rustfmt::skip]
let program = [
Op(DW_OP_implicit_pointer), U32(0x1234_5678), Sleb(0x123),
];
let result = [Piece {
size_in_bits: None,
bit_offset: None,
location: Location::ImplicitPointer {
value: DebugInfoOffset(0x1234_5678),
byte_offset: 0x123,
},
}];
check_eval(&program, Ok(&result), encoding4());
#[rustfmt::skip]
let program = [
Op(DW_OP_reg3),
Op(DW_OP_piece), Uleb(4),
Op(DW_OP_reg4),
];
check_eval(&program, Err(Error::InvalidPiece), encoding4());
#[rustfmt::skip]
let program = [
Op(DW_OP_reg3),
Op(DW_OP_piece), Uleb(4),
Op(DW_OP_lit0),
];
check_eval(&program, Err(Error::InvalidPiece), encoding4());
}
#[test]
fn test_eval_max_iterations() {
// It's nice if an operation and its arguments can fit on a single
// line in the test program.
use self::AssemblerEntry::*;
use crate::constants::*;
#[rustfmt::skip]
let program = [
Mark(1),
Op(DW_OP_skip), Branch(1),
];
check_eval_with_args(
&program,
Err(Error::TooManyIterations),
encoding4(),
None,
None,
Some(150),
|_, _| panic!(),
);
}
#[test]
fn test_eval_typed_stack() {
use self::AssemblerEntry::*;
use crate::constants::*;
let base_types = [
ValueType::Generic,
ValueType::U16,
ValueType::U32,
ValueType::F32,
];
// TODO: convert, reinterpret
#[rustfmt::skip]
let tests = [
(
&[
Op(DW_OP_const_type), Uleb(1), U8(2), U16(0x1234),
Op(DW_OP_stack_value),
][..],
Value::U16(0x1234),
),
(
&[
Op(DW_OP_regval_type), Uleb(0x1234), Uleb(1),
Op(DW_OP_stack_value),
][..],
Value::U16(0x2340),
),
(
&[
Op(DW_OP_addr), U32(0x7fff_ffff),
Op(DW_OP_deref_type), U8(2), Uleb(1),
Op(DW_OP_stack_value),
][..],
Value::U16(0xfff0),
),
(
&[
Op(DW_OP_lit1),
Op(DW_OP_addr), U32(0x7fff_ffff),
Op(DW_OP_xderef_type), U8(2), Uleb(1),
Op(DW_OP_stack_value),
][..],
Value::U16(0xfff1),
),
(
&[
Op(DW_OP_const_type), Uleb(1), U8(2), U16(0x1234),
Op(DW_OP_convert), Uleb(2),
Op(DW_OP_stack_value),
][..],
Value::U32(0x1234),
),
(
&[
Op(DW_OP_const_type), Uleb(2), U8(4), U32(0x3f80_0000),
Op(DW_OP_reinterpret), Uleb(3),
Op(DW_OP_stack_value),
][..],
Value::F32(1.0),
),
];
for &(program, value) in &tests {
let result = [Piece {
size_in_bits: None,
bit_offset: None,
location: Location::Value { value },
}];
check_eval_with_args(
program,
Ok(&result),
encoding4(),
None,
None,
None,
|eval, mut result| {
while result != EvaluationResult::Complete {
result = match result {
EvaluationResult::RequiresMemory {
address,
size,
space,
base_type,
} => {
let mut v = address << 4;
if let Some(value) = space {
v += value;
}
v &= (1u64 << (8 * size)) - 1;
let v = Value::from_u64(base_types[base_type.0], v)?;
eval.resume_with_memory(v)?
}
EvaluationResult::RequiresRegister {
register,
base_type,
} => {
let v = Value::from_u64(
base_types[base_type.0],
u64::from(register.0) << 4,
)?;
eval.resume_with_register(v)?
}
EvaluationResult::RequiresBaseType(offset) => {
eval.resume_with_base_type(base_types[offset.0])?
}
EvaluationResult::RequiresRelocatedAddress(address) => {
eval.resume_with_relocated_address(address)?
}
_ => panic!("Unexpected result {:?}", result),
}
}
Ok(result)
},
);
}
}
}