1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401
|
// bpf translation pass
// Copyright (C) 2016-2022 Red Hat Inc.
//
// This file is part of systemtap, and is free software. You can
// redistribute it and/or modify it under the terms of the GNU General
// Public License (GPL); either version 2, or (at your option) any
// later version.
#include "config.h"
#include "bpf-internal.h"
#include "parse.h"
#include "staptree.h"
#include "elaborate.h"
#include "session.h"
#include "translator-output.h"
#include "tapsets.h"
#include <sstream>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
extern "C" {
#include <libelf.h>
/* Unfortunately strtab manipulation functions were only officially added
to elfutils libdw in 0.167. Before that there were internal unsupported
ebl variants. While libebl.h isn't supported we'll try to use it anyway
if the elfutils we build against is too old. */
#include <elfutils/version.h>
#if _ELFUTILS_PREREQ (0, 167)
#include <elfutils/libdwelf.h>
typedef Dwelf_Strent Stap_Strent;
typedef Dwelf_Strtab Stap_Strtab;
#define stap_strtab_init dwelf_strtab_init
#define stap_strtab_add(X,Y) dwelf_strtab_add(X,Y)
#define stap_strtab_free dwelf_strtab_free
#define stap_strtab_finalize dwelf_strtab_finalize
#define stap_strent_offset dwelf_strent_off
#else
#include <elfutils/libebl.h>
typedef Ebl_Strent Stap_Strent;
typedef Ebl_Strtab Stap_Strtab;
#define stap_strtab_init ebl_strtabinit
#define stap_strtab_add(X,Y) ebl_strtabadd(X,Y,0)
#define stap_strtab_free ebl_strtabfree
#define stap_strtab_finalize ebl_strtabfinalize
#define stap_strent_offset ebl_strtaboffset
#endif
#include <linux/version.h>
#include <asm/ptrace.h>
}
// XXX: Required static data and methods from bpf::globals, shared with stapbpf.
#include "bpf-shared-globals.h"
#ifndef EM_BPF
#define EM_BPF 0xeb9f
#endif
#ifndef R_BPF_MAP_FD
#define R_BPF_MAP_FD 1
#endif
std::string module_name;
namespace bpf {
struct side_effects_visitor : public expression_visitor
{
bool side_effects;
side_effects_visitor() : side_effects(false) { }
void visit_expression(expression *) { }
void visit_pre_crement(pre_crement *) { side_effects = true; }
void visit_post_crement(post_crement *) { side_effects = true; }
void visit_assignment (assignment *) { side_effects = true; }
void visit_functioncall (functioncall *) { side_effects = true; }
void visit_print_format (print_format *) { side_effects = true; }
void visit_stat_op (stat_op *) { side_effects = true; }
void visit_hist_op (hist_op *) { side_effects = true; }
};
struct init_block : public ::block
{
// This block contains statements that initialize global variables
// with default values. It should be visited first among any
// begin probe bodies. Note that initialization of internal globals
// (ex. the exit status) is handled by the stapbpf runtime.
init_block(globals &glob);
~init_block();
bool empty() { return this->statements.empty(); }
};
init_block::init_block(globals &glob)
{
for (auto i = glob.globals.begin(); i != glob.globals.end(); ++i)
{
struct vardecl *v = i->first;
if (v->init && v->type == pe_long)
{
struct literal_number *num = static_cast<literal_number *>(v->init);
struct symbol *sym = new symbol;
struct assignment *asgn = new assignment;
struct expr_statement *stmt = new expr_statement;
sym->referent = v;
asgn->type = pe_long;
asgn->op = "=";
asgn->left = sym;
asgn->right = num;
stmt->value = asgn;
this->statements.push_back(stmt);
}
}
}
init_block::~init_block()
{
for (auto i = this->statements.begin(); i != this->statements.end(); ++i)
{
struct expr_statement *stmt = static_cast<expr_statement *>(*i);
struct assignment *asgn = static_cast<assignment *>(stmt->value);
struct symbol *sym = static_cast<symbol *>(asgn->left);
// referent and right are not owned by this.
sym->referent = NULL;
asgn->right = NULL;
delete sym;
delete asgn;
delete stmt;
}
}
static bool
has_side_effects (expression *e)
{
side_effects_visitor t;
e->visit (&t);
return t.side_effects;
}
/* forward declarations */
struct asm_stmt;
struct bpf_unparser : public throwing_visitor
{
// The visitor class isn't as helpful as it might be. As a consequence,
// the RESULT member is set after visiting any expression type. Use the
// emit_expr helper to return the result properly.
value *result;
// The program into which we are emitting code.
program &this_prog;
globals &glob;
value *this_in_arg0 = NULL;
// The "current" block into which we are currently emitting code.
insn_append_inserter this_ins;
void set_block(block *b)
{ this_ins.b = b; this_ins.i = b->last; }
void clear_block()
{ this_ins.b = NULL; this_ins.i = NULL; }
bool in_block() const
{ return this_ins.b != NULL; }
// Destinations for "break", "continue", and "return" respectively.
std::vector<block *> loop_break;
std::vector<block *> loop_cont;
std::vector<block *> func_return;
std::vector<value *> func_return_val;
std::vector<functiondecl *> func_calls;
// Used to track errors.
value *error_status;
// Used to switch execution of program to catch blocks.
std::vector<block *> catch_jump;
std::vector<value *> catch_msg;
// Contains the mapping for resource constraints set by -D.
std::map<std::string, int> constraints;
// Local variable declarations.
typedef std::unordered_map<vardecl *, value *> locals_map;
locals_map *this_locals;
// Return 0.
block *ret0_block;
block *exit_block;
block *get_ret0_block();
block *get_exit_block();
// TODO General triage of bpf-possible functionality:
virtual void visit_embeddedcode (embeddedcode *s);
virtual void visit_try_block (try_block* s);
virtual void visit_block (::block *s);
virtual void visit_null_statement (null_statement *s);
virtual void visit_expr_statement (expr_statement *s);
virtual void visit_if_statement (if_statement* s);
virtual void visit_for_loop (for_loop* s);
virtual void visit_foreach_loop (foreach_loop* s);
virtual void visit_return_statement (return_statement* s);
virtual void visit_delete_statement (delete_statement* s);
virtual void visit_next_statement (next_statement* s);
virtual void visit_break_statement (break_statement* s);
virtual void visit_continue_statement (continue_statement* s);
virtual void visit_literal_string (literal_string *e);
virtual void visit_literal_number (literal_number* e);
// TODO visit_embedded_expr -> UNHANDLED, could treat as embedded_code
virtual void visit_binary_expression (binary_expression* e);
virtual void visit_unary_expression (unary_expression* e);
virtual void visit_pre_crement (pre_crement* e);
virtual void visit_post_crement (post_crement* e);
virtual void visit_logical_or_expr (logical_or_expr* e);
virtual void visit_logical_and_expr (logical_and_expr* e);
virtual void visit_array_in (array_in* e);
// ??? visit_regex_query -> UNHANDLED, requires new kernel functionality
virtual void visit_compound_expression (compound_expression *e);
virtual void visit_comparison (comparison* e);
// TODO visit_concatenation for kernel probes -> (2) pseudo-LOOP: copy the
// strings while concatenating
virtual void visit_concatenation (concatenation* e);
virtual void visit_ternary_expression (ternary_expression* e);
virtual void visit_assignment (assignment* e);
virtual void visit_symbol (symbol* e);
virtual void visit_target_register (target_register* e);
virtual void visit_target_deref (target_deref* e);
// visit_target_bitfield -> ?? should already be handled in earlier pass?
// visit_target_symbol -> ?? should already be handled in earlier pass
virtual void visit_arrayindex (arrayindex *e);
virtual void visit_functioncall (functioncall* e);
virtual void visit_print_format (print_format* e);
virtual void visit_stat_op (stat_op* e);
virtual void visit_hist_op (hist_op* e);
// visit_atvar_op -> ?? should already be handled in earlier pass
// visit_cast_op -> ?? should already be handled in earlier pass
// visit_autocast_op -> ?? should already be handled in earlier pass
// visit_defined_op -> ?? should already be handled in earlier pass
// visit_entry_op -> ?? should already be handled in earlier pass
// visit_perf_op -> ?? should already be handled in earlier pass
// TODO: Other bpf functionality to take advantage of in tapsets, or as alternate implementations:
// - backtrace.stp :: BPF_MAP_TYPE_STACKTRACE + bpf_getstackid
// - BPF_MAP_TYPE_LRU_HASH :: for size-limited maps
// - BPF_MAP_GET_NEXT_KEY :: for user-space iteration through maps
// see https://ferrisellis.com/posts/ebpf_syscall_and_maps/#ebpf-map-types
void emit_stmt(statement *s);
void emit_mov(value *d, value *s);
void emit_jmp(block *b);
void emit_cond(expression *e, block *t, block *f);
void emit_statmap_lookup(value *dest, globals::map_idx map_id, value *idx);
void emit_statmap_update(globals::map_idx map_id, value *idx,
int idx_ofs, value *val);
void emit_aggregation(vardecl *var, globals::map_slot& g, value *val,
value *idx = NULL, int idx_ofs = 0);
void emit_store(expression *dest, value *src);
value *emit_expr(expression *e);
value *emit_bool(expression *e);
value *emit_context_var(bpf_context_vardecl *v);
void emit_transport_msg(globals::perf_event_type msg,
value *arg = NULL, exp_type format_type = pe_unknown);
value *emit_functioncall(functiondecl *f, const std::vector<value *> &args);
value *emit_print_format(const std::string &format,
const std::vector<value *> &actual,
bool print_to_stream = true,
const token *tok = NULL);
// Used for the embedded-code assembler:
opcode parse_opcode_tentative (const asm_stmt &stmt, const std::string &str,
/*OUT*/bool &numeric_opcode);
bool parse_imm_optional (const asm_stmt &stmt, const std::string &str,
/*OUT*/int64_t &val);
int64_t parse_imm (const asm_stmt &stmt, const std::string &str);
void parse_reg_offset (const asm_stmt &stmt, const std::string &str,
/*OUT*/std::string ®, /*OUT*/int64_t &off);
void parse_asm_opcode (const std::vector<std::string> &args,
/*OUT*/asm_stmt &stmt);
size_t parse_asm_stmt (embeddedcode *s, size_t start,
/*OUT*/asm_stmt &stmt);
value *emit_asm_arg(const asm_stmt &stmt, const std::string &arg,
bool allow_imm = true, bool allow_emit = true);
value *emit_asm_reg(const asm_stmt &stmt, const std::string ®);
value *get_asm_reg(const asm_stmt &stmt, const std::string ®);
void emit_asm_opcode(const asm_stmt &stmt,
std::map<std::string, block *> label_map);
// Used for the embedded-code assembler's diagnostics:
source_loc adjusted_loc;
size_t adjust_pos;
std::vector<token *> adjusted_toks; // track for delayed deallocation
// Used for string data:
value *emit_literal_string(const std::string &str, const token *tok);
value *emit_string_copy(value *dest, int ofs, value *src, bool zero_pad = false);
// Used for passing long and string arguments on the stack where an address is expected:
void emit_long_arg(value *arg, int ofs, value *val);
void emit_str_arg(value *arg, int ofs, value *str);
void add_prologue();
void add_epilogue();
locals_map *new_locals(const std::vector<vardecl *> &);
bpf_unparser (program &c, globals &g);
virtual ~bpf_unparser ();
};
bpf_unparser::bpf_unparser(program &p, globals &g)
: throwing_visitor ("unhandled statement or expression type"),
result(NULL), this_prog(p), glob(g), this_locals(NULL),
ret0_block(NULL), exit_block(NULL)
{
// If there are any resource constraints set with -D, we populate
// them into a map (as we cannot use macros in stapbpf).
for (std::string macro: glob.session->c_macros)
{
// Example: MAXERRORS=3
size_t delim = macro.find('=');
std::string option = macro.substr(0, delim);
int limit = std::stoi(macro.substr(delim + 1));
// Negative limits become 0.
if (limit < 0)
limit = 0;
constraints[option] = limit;
}
}
bpf_unparser::~bpf_unparser()
{
// TODO: Need to delay this deallocation even further for error reporting.
//for (std::vector<token *>::iterator it = adjusted_toks.begin();
// it != adjusted_toks.end(); it++)
// delete *it;
delete this_locals;
}
bpf_unparser::locals_map *
bpf_unparser::new_locals(const std::vector<vardecl *> &vars)
{
locals_map *m = new locals_map;
for (std::vector<vardecl *>::const_iterator i = vars.begin ();
i != vars.end (); ++i)
{
const locals_map::value_type v (*i, this_prog.new_reg());
auto ok = m->insert (v);
assert (ok.second);
}
return m;
}
block *
bpf_unparser::get_exit_block()
{
if (exit_block)
return exit_block;
block* cont = this_ins.get_block();
block* exit = this_prog.new_block();
set_block(exit);
add_epilogue();
this_prog.mk_exit(this_ins);
set_block(cont);
exit_block = exit;
return exit;
}
block *
bpf_unparser::get_ret0_block()
{
if (ret0_block)
return ret0_block;
block *b = this_prog.new_block();
insn_append_inserter ins(b, "ret0_block");
this_prog.mk_mov(ins, this_prog.lookup_reg(BPF_REG_0), this_prog.new_imm(0));
b->fallthru = new edge(b, get_exit_block());
ret0_block = b;
return b;
}
void
bpf_unparser::emit_stmt(statement *s)
{
if (s)
s->visit (this);
}
value *
bpf_unparser::emit_expr(expression *e)
{
e->visit (this);
value *v = result;
result = NULL;
return v;
}
void
bpf_unparser::emit_mov(value *d, value *s)
{
this_prog.mk_mov(this_ins, d, s);
}
void
bpf_unparser::emit_jmp(block *b)
{
// Begin by hoping that we can simply place the destination as fallthru.
// If this assumption doesn't hold, it'll be fixed by reorder_blocks.
assert(in_block());
block *this_block = this_ins.get_block ();
this_block->fallthru = new edge(this_block, b);
clear_block ();
}
void
bpf_unparser::emit_cond(expression *e, block *t_dest, block *f_dest)
{
condition cond;
value *s0, *s1;
// Look for and handle logical operators first.
if (logical_or_expr *l = dynamic_cast<logical_or_expr *>(e))
{
block *cont_block = this_prog.new_block ();
emit_cond (l->left, t_dest, cont_block);
set_block (cont_block);
emit_cond (l->right, t_dest, f_dest);
return;
}
if (logical_and_expr *l = dynamic_cast<logical_and_expr *>(e))
{
block *cont_block = this_prog.new_block ();
emit_cond (l->left, cont_block, f_dest);
set_block (cont_block);
emit_cond (l->right, t_dest, f_dest);
return;
}
if (unary_expression *u = dynamic_cast<unary_expression *>(e))
if (u->op == "!")
{
emit_cond (u->operand, f_dest, t_dest);
return;
}
// What is left must generate a comparison + conditional branch.
if (comparison *c = dynamic_cast<comparison *>(e))
{
s0 = emit_expr (c->left);
s1 = emit_expr (c->right);
if (c->op == "==")
cond = EQ;
else if (c->op == "!=")
cond = NE;
else if (c->op == "<")
cond = LT;
else if (c->op == "<=")
cond = LE;
else if (c->op == ">")
cond = GT;
else if (c->op == ">=")
cond = GE;
else
throw SEMANTIC_ERROR (_("unhandled comparison operator"), e->tok);
}
else
{
binary_expression *bin = dynamic_cast<binary_expression *>(e);
if (bin && bin->op == "&")
{
s0 = emit_expr (bin->left);
s1 = emit_expr (bin->right);
cond = TEST;
}
else
{
// Fall back to E != 0.
s0 = emit_expr (e);
s1 = this_prog.new_imm(0);
cond = NE;
}
}
this_prog.mk_jcond (this_ins, cond, s0, s1, t_dest, f_dest);
clear_block ();
}
value *
bpf_unparser::emit_bool (expression *e)
{
block *else_block = this_prog.new_block ();
block *join_block = this_prog.new_block ();
value *r = this_prog.new_reg();
emit_mov (r, this_prog.new_imm(1));
emit_cond (e, join_block, else_block);
set_block (else_block);
emit_mov (r, this_prog.new_imm(0));
emit_jmp (join_block);
set_block(join_block);
return r;
}
/* PR23476: Helpers for loading/storing long values in a stat field map.
Several of these map operations are issued for each stats operation,
so we avoid code duplication by taking an index already on the stack.
??? These helpers could be used in other contexts than just stats. */
void
bpf_unparser::emit_statmap_lookup(value *dest, globals::map_idx map_id, value *idx)
{
this_prog.load_map(this_ins, this_prog.lookup_reg(BPF_REG_1), map_id);
emit_mov(this_prog.lookup_reg(BPF_REG_2), idx); // XXX idx stored by caller
this_prog.mk_call(this_ins, BPF_FUNC_map_lookup_elem, 2);
// Check for null pointer:
value *r0 = this_prog.lookup_reg(BPF_REG_0);
value *i0 = this_prog.new_imm(0);
block *cont_block = this_prog.new_block();
block *join_block = this_prog.new_block();
emit_mov(dest, i0); // default to a result of 0
this_prog.mk_jcond(this_ins, EQ, r0, i0, join_block, cont_block);
set_block(cont_block);
this_prog.mk_ld(this_ins, BPF_DW, dest, r0, 0);
emit_jmp(join_block);
set_block(join_block);
}
void
bpf_unparser::emit_statmap_update(globals::map_idx map_id, value *idx,
int idx_ofs, value *val)
{
int val_ofs = idx_ofs - 8;
if ((-val_ofs) % 8 != 0) // align to double-word
val_ofs -= 8 - (-val_ofs) % 8;
this_prog.use_tmp_space(-val_ofs);
this_prog.load_map(this_ins, this_prog.lookup_reg(BPF_REG_1), map_id);
emit_mov(this_prog.lookup_reg(BPF_REG_2), idx); // XXX idx stored by caller
emit_long_arg(this_prog.lookup_reg(BPF_REG_3), val_ofs, val);
emit_mov(this_prog.lookup_reg(BPF_REG_4), this_prog.new_imm(0)); // TODO
this_prog.mk_call(this_ins, BPF_FUNC_map_update_elem, 4);
}
// XXX Based on __stap_stat_add in runtime/stat-common.c.
// There might be a clever way to avoid code duplication later,
// but right now the code format is too different. Just reimplement.
void
bpf_unparser::emit_aggregation(vardecl *var, globals::map_slot& ms,
value *val, value *idx, int idx_ofs)
{
#ifdef DEBUG_CODEGEN
this_ins.notes.push("agg");
#endif
// Obtain the correct stats_map and index:
assert (ms.is_stat());
globals::stats_map sd;
if (var->arity == 0)
{
assert (ms.is_scalar() && idx == NULL);
sd = glob.scalar_stats;
// idx is an offset into scalar stat field maps, store on the stack
value *frame = this_prog.lookup_reg(BPF_REG_10);
idx_ofs = -4; // BPF_W
this_prog.mk_st(this_ins, BPF_W, frame, idx_ofs,
this_prog.new_imm(ms.idx));
this_prog.use_tmp_space(-idx_ofs);
idx = this_prog.new_reg();
this_prog.mk_binary(this_ins, BPF_ADD, idx,
frame, this_prog.new_imm(idx_ofs));
}
else // var->arity > 0
{
assert (!ms.is_scalar());
assert (var->arity > 0 && idx != NULL);
auto it = glob.array_stats.find(var);
assert (it != glob.array_stats.end()); // XXX: should check earlier
sd = it->second;
// idx is a value stored on the stack
}
for (auto f : globals::stat_fields)
assert(sd.find(f) != sd.end());
// TODO PR23476: Emit simplified code for now.
//
// ??? lock stat
// if (idx not in sd[stat_iter_field] || sd->count == 0) {
// sd->count = 1;
// sd->sum = val;
// } else {
// if(stat_op_count) sd->count++;
// if(stat_op_sum) sd->sum += val;
// }
// ??? unlock stat
block *then_block = this_prog.new_block ();
block *else_block = this_prog.new_block ();
block *join_block = this_prog.new_block ();
value *tmp = this_prog.new_reg();
emit_statmap_lookup(tmp, sd["count"], idx);
this_prog.mk_jcond (this_ins, EQ, tmp, this_prog.new_imm(0),
then_block, else_block);
set_block (then_block);
emit_statmap_update(sd["count"], idx, idx_ofs, this_prog.new_imm(1));
emit_statmap_update(sd["sum"], idx, idx_ofs, val);
emit_jmp (join_block);
set_block (else_block);
if (1) // TODO: if (stat_op_count)
{
emit_statmap_lookup(tmp, sd["count"], idx);
this_prog.mk_binary(this_ins, BPF_ADD, tmp, tmp, this_prog.new_imm(1));
emit_statmap_update(sd["count"], idx, idx_ofs, tmp);
}
if (1) // TODO: if (stat_op_sum)
{
emit_statmap_lookup(tmp, sd["sum"], idx);
this_prog.mk_binary(this_ins, BPF_ADD, tmp, tmp, val);
emit_statmap_update(sd["sum"], idx, idx_ofs, tmp);
}
emit_jmp (join_block);
set_block(join_block);
#ifdef DEBUG_CODEGEN
this_ins.notes.pop();
#endif
}
void
bpf_unparser::emit_store(expression *e, value *val)
{
if (symbol *s = dynamic_cast<symbol *>(e)) // scalar lvalue
{
vardecl *var = s->referent;
assert (var->arity == 0);
auto g = glob.globals.find (var);
if (g != glob.globals.end())
{
value *frame = this_prog.lookup_reg(BPF_REG_10);
int key_ofs, val_ofs;
// BPF_FUNC_map_update_elem will dereference the address
// passed in BPF_REG_3:
switch (var->type)
{
case pe_long:
// Store the long on the stack and pass its address:
val_ofs = -8;
emit_long_arg(this_prog.lookup_reg(BPF_REG_3), val_ofs, val);
break;
case pe_string:
// Zero-pad and copy the string to the stack and pass its address:
val_ofs = -BPF_MAXSTRINGLEN;
emit_str_arg(this_prog.lookup_reg(BPF_REG_3), val_ofs, val);
this_prog.use_tmp_space(BPF_MAXSTRINGLEN);
break;
case pe_stats:
// Emit separate code to update stat fields:
emit_aggregation(var, g->second, val);
return;
default:
goto err;
}
key_ofs = val_ofs - 4;
this_prog.mk_st(this_ins, BPF_W, frame, key_ofs,
this_prog.new_imm(g->second.idx));
this_prog.use_tmp_space(-key_ofs);
// XXX g->second.is_stat() handled above
this_prog.load_map(this_ins, this_prog.lookup_reg(BPF_REG_1),
g->second.map_id);
this_prog.mk_binary(this_ins, BPF_ADD,
this_prog.lookup_reg(BPF_REG_2),
frame, this_prog.new_imm(key_ofs));
emit_mov(this_prog.lookup_reg(BPF_REG_4), this_prog.new_imm(0));
this_prog.mk_call(this_ins, BPF_FUNC_map_update_elem, 4);
return;
}
auto i = this_locals->find (var);
if (i != this_locals->end ())
{
emit_mov (i->second, val);
return;
}
}
else if (arrayindex *a = dynamic_cast<arrayindex *>(e)) // array lvalue
{
if (symbol *a_sym = dynamic_cast<symbol *>(a->base))
{
vardecl *v = a_sym->referent;
int key_ofs = 0, val_ofs;
auto g = glob.globals.find(v);
if (g == glob.globals.end())
throw SEMANTIC_ERROR(_("unknown array variable"), v->tok);
unsigned element = v->arity;
// iterate over the elements
do {
--element;
value *idx = emit_expr(a->indexes[element]);
switch (v->index_types[element])
{
case pe_long:
// Store the long on the stack and pass its address:
key_ofs -= 8;
emit_long_arg(this_prog.lookup_reg(BPF_REG_2), key_ofs, idx);
break;
case pe_string:
// Zero-pad and copy the string to the stack and pass its address:
key_ofs -= BPF_MAXSTRINGLEN;
emit_str_arg(this_prog.lookup_reg(BPF_REG_2), key_ofs, idx);
break;
default:
throw SEMANTIC_ERROR(_("unhandled index type"), e->tok);
}
} while (element);
switch (v->type)
{
case pe_long:
// Store the long on the stack and pass its address:
val_ofs = key_ofs - 8;
emit_long_arg(this_prog.lookup_reg(BPF_REG_3), val_ofs, val);
break;
case pe_string:
// Zero-pad and copy the string to the stack and pass its address:
val_ofs = key_ofs - BPF_MAXSTRINGLEN;
emit_str_arg(this_prog.lookup_reg(BPF_REG_3), val_ofs, val);
this_prog.use_tmp_space(BPF_MAXSTRINGLEN);
break;
case pe_stats:
// Emit separate code to update stat fields:
{
value *idx = this_prog.new_reg();
value *frame = this_prog.lookup_reg(BPF_REG_10);
this_prog.mk_binary(this_ins, BPF_ADD, idx,
frame, this_prog.new_imm(key_ofs));
this_prog.use_tmp_space(-key_ofs);
emit_aggregation(v, g->second, val, idx, key_ofs);
}
return;
default:
throw SEMANTIC_ERROR(_("unhandled array type"), v->tok);
}
this_prog.use_tmp_space(-val_ofs);
// XXX g->second.is_stat() handled above
this_prog.load_map(this_ins, this_prog.lookup_reg(BPF_REG_1),
g->second.map_id);
emit_mov(this_prog.lookup_reg(BPF_REG_4), this_prog.new_imm(0));
this_prog.mk_call(this_ins, BPF_FUNC_map_update_elem, 4);
return;
}
}
err:
throw SEMANTIC_ERROR (_("unknown lvalue"), e->tok);
}
/* WORK IN PROGRESS: A simple eBPF assembler.
In order to effectively write eBPF tapset functions, we want to use
embedded-code assembly rather than compile from SystemTap code. At
the same time, we want to hook into stapbpf functionality to
reserve stack memory, allocate virtual registers or signal errors.
The assembler syntax will probably take a couple of attempts to get
just right. The first attempt keeps things as close as possible to the
first embedded-code assembler, with a few more features and a
disgustingly lenient parser that allows* things like
$ this is all one "**identifier**" believe-it!-or-not
(* Asterisk: except in the first opcode / operator keyword.)
Ahh for the days of 1960s FORTRAN.
PR29307: The second attempt adds support for the assembler syntax
from iovisor's docs
i.e. https://github.com/iovisor/bpf-docs/blob/master/eBPF.md
Comma after opcode now optional, semicolons can be replaced with
newline.
I also considered the syntax from
kernel Documentation/networking/filter.rst or bpfc(8),
also implemented in kernel tools/bpf/bpf_exp.y,
but the addressing-mode syntax seems a bit too baroque to bother
for the time being.
*/
/* Supported assembly statement types include:
<stmt> ::= label <dest=label>
<stmt> ::= <dest=label>:
<stmt> ::= alloc <dest=reg>, <imm=imm> [, align|noalign];
<stmt> ::= call <dest=optreg>, <param[0]=function name>, <param[1]=arg>, ...;
<stmt> ::= jump_to_catch <param[0]=error message>;
<stmt> ::= register_error <param[0]=error message>;
<stmt> ::= terminate;
<stmt> ::= <code=integer or symbolic opcode>
<dest=reg>, [<src1=reg>,] [<off/jmp_target=off>,] [<imm=imm>];
Supported argument types include:
<arg> ::= <reg> | <imm>
<optreg> ::= <reg> | -
<reg> ::= <register index> | r<register index> | $ctx
$<identifier> | $<integer constant> | $$ | <string constant>
<imm> ::= <integer constant> | BPF_MAXSTRINGLEN | BPF_F_CURRENT_CPU | -
<off> ::= <imm> | <jump label>
*/
/* TODO PR29307 Suggested further improvements for the assembler syntax:
1. dest argument of call is optional
2. jump_to_catch and register_error error msg support formats
*/
// #define BPF_ASM_DEBUG
struct asm_stmt {
std::string kind;
unsigned code;
std::string dest, src1;
int64_t off, imm;
// metadata for jmp instructions
// ??? The logic around these flags could be pruned a bit.
bool has_jmp_target = false;
bool has_fallthrough = false;
std::string jmp_target, fallthrough;
// metadata for call, error instructions
std::vector<std::string> params;
// metadata for alloc instructions
bool align_alloc;
token *tok;
};
std::ostream&
operator << (std::ostream& o, const asm_stmt& stmt)
{
if (stmt.kind == "label")
o << "label, " << stmt.dest << ";";
else if (stmt.kind == "opcode")
{
o << std::hex << stmt.code;
// TODO std::hex is sticky? need to verify
std::string opcode_name(bpf_opcode_name(stmt.code));
if (opcode_name != "unknown")
o << "(" << opcode_name << ")";
o << ", "
<< stmt.dest << ", "
<< stmt.src1 << ", ";
if (stmt.off != 0 || stmt.jmp_target == "")
o << stmt.off;
else if (stmt.off != 0) // && stmt.jmp_target != ""
o << stmt.off << "/";
if (stmt.jmp_target != "")
o << "label:" << stmt.jmp_target;
o << ", "
<< stmt.imm << ";"
<< (stmt.has_fallthrough ? " +FALLTHROUGH " + stmt.fallthrough : "");
}
else if (stmt.kind == "alloc")
{
o << "alloc, " << stmt.dest << ", " << stmt.imm << ";";
}
else if (stmt.kind == "call")
{
o << "call, " << stmt.dest << ", ";
for (unsigned k = 0; k < stmt.params.size(); k++)
{
o << stmt.params[k];
o << (k >= stmt.params.size() - 1 ? ";" : ", ");
}
}
else
o << "<unknown asm_stmt kind '" << stmt.kind << "'>";
return o;
}
bool
is_numeric (const std::string &str)
{
size_t pos = 0;
try {
stol(str, &pos, 0);
} catch (const std::invalid_argument &e) {
return false;
} catch (const std::out_of_range &e) {
/* XXX: probably numeric but not valid; give up */
return false;
} catch (...) {
/* XXX: handle other errors the same way */
std::cerr << "BUG: bpf assembler -- is_numeric() saw unexpected exception" << std::endl;
return false;
}
return (pos == str.size());
}
opcode
bpf_unparser::parse_opcode_tentative (const asm_stmt &stmt, const std::string &str, /*OUT*/bool &numeric_opcode)
{
opcode code;
try {
code = stoul(str, 0, 0);
numeric_opcode = true;
} catch (std::exception &e) { // XXX: invalid_argument, out_of_range
code = bpf_opcode_id(str);
numeric_opcode = false;
if (code == 0)
throw SEMANTIC_ERROR (_F("invalid bpf embeddedcode opcode '%s'",
str.c_str()), stmt.tok);
}
return code;
}
bool
bpf_unparser::parse_imm_optional (const asm_stmt &stmt, const std::string &str, /*OUT*/int64_t &val)
{
(void)stmt; /* XXX unused; could report errors, but we don't */
if (str == "BPF_MAXSTRINGLEN")
val = BPF_MAXSTRINGLEN;
else if (str == "BPF_F_CURRENT_CPU")
val = BPF_F_CURRENT_CPU;
else if (str == "-")
val = 0;
else try {
val = stol(str, 0, 0);
} catch (std::exception &e) { // XXX: invalid_argument, out_of_range
val = 0;
return false;
}
return true;
}
int64_t
bpf_unparser::parse_imm (const asm_stmt &stmt, const std::string &str)
{
int64_t val;
if (!parse_imm_optional(stmt, str, val))
{
throw SEMANTIC_ERROR (_F("invalid bpf embeddedcode operand '%s'",
str.c_str()), stmt.tok);
}
return val;
}
/* Parse an argument of the form [reg+off] or [reg-off]. */
void
bpf_unparser::parse_reg_offset (const asm_stmt &stmt, const std::string &str,
/*OUT*/std::string ®, /*OUT*/int64_t &off)
{
{
if (str.length() < 3 || str[0] != '[' || str[str.size()-1] != ']')
goto error;
size_t separator = str.find_first_of("+-", 0);
if (separator == std::string::npos)
goto error;
reg = str.substr(1,separator-1);
char sep_chr = str[separator];
std::string off_str = str.substr(separator+1,str.size()-1-separator-1);
off = parse_imm(stmt, off_str);
if (sep_chr == '-')
off = -off;
return;
}
error:
throw SEMANTIC_ERROR (_F("invalid bpf embeddedcode operand '%s', expected [reg+off] or [reg-off]",
str.c_str()), stmt.tok);
}
/* Parse an assembly opcode, then write the output in stmt. */
void
bpf_unparser::parse_asm_opcode (const std::vector<std::string> &args, /*OUT*/asm_stmt &stmt)
{
stmt.kind = "opcode";
bool numeric_opcode;
stmt.code = parse_opcode_tentative(stmt, args[0], numeric_opcode);
opcode tentative_code = stmt.code;
stmt.has_jmp_target =
BPF_CLASS(stmt.code) == BPF_JMP
&& BPF_OP(stmt.code) != BPF_EXIT
&& BPF_OP(stmt.code) != BPF_CALL;
stmt.has_fallthrough = // only for jcond
stmt.has_jmp_target
&& BPF_OP(stmt.code) != BPF_JA;
// XXX: stmt.fallthrough is computed by visit_embeddedcode
// XXX default values required for emit_asm_opcode
stmt.dest = "-";
stmt.src1 = "-";
stmt.off = 0;
stmt.jmp_target = "-";
stmt.imm = 0;
unsigned cat = bpf_opcode_category(stmt.code);
if (args.size() == 5) // op dest src jmp_target/off imm
{
stmt.dest = args[1];
stmt.src1 = args[2];
if (stmt.has_jmp_target)
{
stmt.off = 0;
stmt.jmp_target = args[3];
}
else
stmt.off = parse_imm(stmt, args[3]);
stmt.imm = parse_imm(stmt, args[4]);
}
else if (cat == BPF_MEMORY_ARI4 && args.size() == 4) // op src dest imm
{
stmt.src1 = args[1];
stmt.dest = args[2];
stmt.imm = parse_imm(stmt, args[3]);
}
else if (cat == BPF_BRANCH_ARI4 && args.size() == 4 && stmt.has_jmp_target) // op dest imm jmp_target, op dest jmp_target imm, op dest src jmp_target
{
stmt.dest = args[1];
// disambiguate opcode taking imm vs src
if (parse_imm_optional(stmt, args[2], stmt.imm))
{
stmt.code = bpf_opcode_variant_imm(stmt.code);
stmt.jmp_target = args[3];
}
else if (parse_imm_optional(stmt, args[3], stmt.imm))
{
stmt.code = bpf_opcode_variant_imm(stmt.code);
stmt.jmp_target = args[2];
}
else
{
stmt.src1 = args[2];
stmt.jmp_target = args[3];
}
// error if stmt.code was specified numerically and doesn't match
if (numeric_opcode && stmt.code != tentative_code)
throw SEMANTIC_ERROR (_F("numeric opcode '%x' given argument types for '%x'",
tentative_code, stmt.code), stmt.tok); // TODO convert opcode to string
}
else if (cat == BPF_MEMORY_ARI34_SRCOFF && args.size() == 4) // op dest src off
{
stmt.dest = args[1];
stmt.src1 = args[2];
stmt.off = parse_imm(stmt, args[3]);
}
else if (cat == BPF_MEMORY_ARI34_SRCOFF && args.size() == 3) // op dest [src+off]
{
stmt.dest = args[1];
parse_reg_offset(stmt, args[2], stmt.dest, stmt.off);
}
else if (cat == BPF_MEMORY_ARI34_DSTOFF_IMM && args.size() == 4) // op dest off imm, op dest src imm
{
stmt.dest = args[1];
// allow off/src to be ordered according to either convention
if (parse_imm_optional(stmt, args[2], stmt.off))
{
stmt.imm = parse_imm(stmt, args[2]);
}
else
{
stmt.imm = parse_imm(stmt, args[2]);
stmt.off = parse_imm(stmt, args[3]);
}
}
else if (cat == BPF_MEMORY_ARI34_DSTOFF_IMM && args.size() == 3) // op [dest+off] imm
{
parse_reg_offset(stmt, args[1], stmt.dest, stmt.off);
stmt.imm = parse_imm(stmt, args[2]);
}
else if (cat == BPF_MEMORY_ARI34_DSTOFF && args.size() == 4) // op dest off src, op dest src off
{
stmt.dest = args[1];
// allow off/src to be ordered according to either convention
if (parse_imm_optional(stmt, args[2], stmt.off))
{
stmt.src1 = args[3];
}
else
{
stmt.src1 = args[2];
stmt.off = parse_imm(stmt, args[3]);
}
}
else if (cat == BPF_MEMORY_ARI34_DSTOFF && args.size() == 3) // op [dest+off] src
{
parse_reg_offset(stmt, args[1], stmt.dest, stmt.off);
stmt.src1 = args[2];
}
else if (cat == BPF_ALU_ARI3 && args.size() == 3) // op dest src, op dest imm
{
stmt.dest = args[1];
// disambiguate opcode taking imm vs src
if (parse_imm_optional(stmt, args[2], stmt.imm))
{
stmt.code = bpf_opcode_variant_imm(stmt.code);
}
else
{
stmt.src1 = args[2];
}
// error if stmt.code was specified numerically and doesn't match
if (numeric_opcode && stmt.code != tentative_code)
throw SEMANTIC_ERROR (_F("numeric opcode '%x' given argument types for '%x'",
tentative_code, stmt.code), stmt.tok); // TODO convert opcode to string
}
else if (cat == BPF_MEMORY_ARI3 && args.size() == 3) // op dest imm
{
stmt.dest = args[1];
stmt.imm = parse_imm(stmt, args[2]);
}
else if (cat == BPF_ALU_ARI2 && args.size() == 2) // op dest
{
stmt.dest = args[1];
}
else if (cat == BPF_BRANCH_ARI2 && args.size() == 2) // op jmp_target
{
stmt.jmp_target = args[1];
}
else if (cat == BPF_CALL_ARI2 && args.size() == 2) // op imm/helper_name
{
if (!parse_imm_optional(stmt, args[2], stmt.imm))
{
// TODO: handle helper_name by convering stmt to a "call" directive?
throw SEMANTIC_ERROR (_F("invalid bpf embeddedcode syntax (opcode expects imm, found '%s')", args[2].c_str()), stmt.tok);
}
}
else if (cat == BPF_EXIT_ARI1 && args.size() == 1) // op
{
// nothing
}
else
{
const char * expected_args = bpf_expected_args(cat);
throw SEMANTIC_ERROR (_F("invalid bpf embeddedcode syntax (opcode expects %s args, found %llu)", expected_args, (long long) args.size()-1), stmt.tok);
}
}
/* Parse an assembly statement starting from position start in code,
then write the output in stmt. Returns a position immediately after
the parsed statement. */
size_t
bpf_unparser::parse_asm_stmt (embeddedcode *s, size_t start,
/*OUT*/asm_stmt &stmt)
{
const interned_string &code = s->code;
retry:
std::vector<std::string> args;
unsigned n = code.size();
size_t pos;
bool in_comment = false;
bool in_string = false;
bool in_starting_keyword = true; // first keyword terminated by space
bool trailing_comma = false; // newline not after comma separates statements
bool is_label = false; // XXX "label:" syntax
// ??? As before, parser is extremely non-rigorous and could do
// with some tightening in terms of the inputs it accepts.
std::string arg = "";
size_t save_start = start; // -- position for diagnostics
for (pos = start; pos < n; pos++)
{
char c = code[pos];
char c2 = pos + 1 < n ? code [pos + 1] : 0;
if (in_comment)
{
if (c == '*' && c2 == '/')
++pos, in_comment = false;
// else skip
}
else if (in_string)
{
// resulting string will be processed by translate_escapes()
if (c == '"')
arg.push_back(c), in_string = false; // include quote
else if (c == '\\' && c2 == '"')
++pos, arg.push_back(c), arg.push_back(c2);
else // accept any char, including whitespace
arg.push_back(c);
}
else if (c == ';' || (c == '\n' && !trailing_comma)) // reached end of statement
{
// XXX: This strips out empty args. A more rigorous parser would error.
if (arg != "")
args.push_back(arg);
arg = "";
pos++, in_starting_keyword = true;
break;
}
else if (c == ':') // reached end of label
{
is_label = true;
pos++, in_starting_keyword = false;
trailing_comma = false;
break;
}
else if (c == ','
|| (isspace(c) && in_starting_keyword && arg != "")) // reached end of argument
{
// XXX: This strips out empty args. A more rigorous parser would error.
if (arg != "")
args.push_back(arg);
arg = "";
in_starting_keyword = false;
trailing_comma = (c == ','); // XXX only after an actual comma
}
else if (isspace(c) && !in_string)
continue; // skip
else if (c == '/' && c2 == '*')
++pos, in_comment = true; // XXX in_starting_keyword unchanged
else if (c == '"') // found a literal string
{
if (arg.empty() && args.empty())
save_start = pos; // start of first argument
// XXX: This allows '"' inside an arg and will treat the
// string as a sequence of weird identifier characters. A
// more rigorous parser would error on mixing strings and
// regular chars.
arg.push_back(c); // include quote
in_string = true, in_starting_keyword = false;
trailing_comma = false;
}
else // found (we assume) a regular char
{
if (arg.empty() && args.empty())
save_start = pos; // start of first argument
// XXX: As before, this strips whitespace within args
// (so '$ab', '$ a b' and '$a b' are equivalent).
//
// A more rigorous parser would track in_arg
// and after_arg states and error on whitespace within args.
arg.push_back(c);
trailing_comma = false;
}
}
// final ';' is optional, so we watch for a trailing arg:
if (arg != "") args.push_back(arg);
// handle 'label:' syntax
if (is_label)
{
std::string lb = args[0];
args[0] = "label";
args.push_back(lb);
}
// handle the case with no args
if (args.empty() && pos >= n)
return std::string::npos; // finished parsing
else if (args.empty())
{
// XXX: This skips an empty statement.
// A more rigorous parser would error.
start = pos;
goto retry;
}
// compute token with adjusted source location for diagnostics
// TODO: needs some attention to how multiline tokens are printed in error reporting -- with this code, caret aligns incorrectly
for (/* use saved adjust_pos */; adjust_pos < save_start && adjust_pos < n; adjust_pos++)
{
char c = code[adjust_pos];
if (c == '\n')
{
adjusted_loc.line++;
adjusted_loc.column = 1;
}
else
adjusted_loc.column++;
}
// Now populate the statement data.
stmt = asm_stmt(); // clear pre-existing data
// set token with adjusted source location
stmt.tok = s->tok->adjust_location(adjusted_loc);
adjusted_toks.push_back(stmt.tok);
#ifdef BPF_ASM_DEBUG
std::cerr << "bpf_asm parse_asm_stmt: tokenizer got ";
for (unsigned k = 0; k < args.size(); k++)
std::cerr << args[k] << ", ";
std::cerr << std::endl;
#endif
if (args[0] == "label")
{
if (args.size() != 2)
throw SEMANTIC_ERROR (_F("invalid bpf embeddedcode syntax (label expects 1 arg, found %llu)", (long long) args.size()-1), stmt.tok);
stmt.kind = args[0];
stmt.dest = args[1];
}
else if (args[0] == "alloc")
{
if (args.size() != 3 && args.size() != 4)
throw SEMANTIC_ERROR (_F("invalid bpf embeddedcode syntax (alloc expects 2 or 3 args, found %llu)", (long long) args.size()-1), stmt.tok);
stmt.kind = args[0];
stmt.dest = args[1];
stmt.imm = parse_imm(stmt, args[2]);
// handle align, noalign options
if (args.size() == 4 && args[3] == "align")
{
stmt.align_alloc = true;
}
else if (args.size() == 4 && args[3] == "noalign")
{
stmt.align_alloc = false;
}
else if (args.size() == 4)
throw SEMANTIC_ERROR (_F("invalid bpf embeddedcode syntax (alloc expects 'align' or 'noalign' as 3rd arg, found '%s'", args[3].c_str()), stmt.tok);
else
{
stmt.align_alloc = false;
}
}
else if (args[0] == "jump_to_catch")
{
if (args.size() != 2)
throw SEMANTIC_ERROR (_F("invalid bpf embeddedcode syntax (jump_to_catch expects 1 arg, found %llu)", (long long) args.size()-1), stmt.tok);
stmt.kind = args[0];
stmt.params.push_back(args[1]); // Error message
}
else if (args[0] == "register_error")
{
if (args.size() != 2)
throw SEMANTIC_ERROR (_F("invalid bpf embeddedcode syntax (register_error expects 1 arg, found %llu)", (long long) args.size()-1), stmt.tok);
stmt.kind = args[0];
stmt.params.push_back(args[1]); // Error message
}
else if (args[0] == "terminate")
{
if (args.size() != 1)
throw SEMANTIC_ERROR (_F("invalid bpf embeddedcode syntax (terminate does not take any args, found %llu)", (long long) args.size()-1), stmt.tok);
stmt.kind = args[0];
}
else if (args[0] == "call")
{
if (args.size() < 3)
throw SEMANTIC_ERROR (_F("invalid bpf embeddedcode syntax (call expects at least 2 args, found %llu)", (long long) args.size()-1), stmt.tok);
stmt.kind = args[0];
// TODO: handle optional dest
stmt.dest = args[1];
assert(stmt.params.empty());
for (unsigned k = 2; k < args.size(); k++)
stmt.params.push_back(args[k]);
}
else if (is_numeric(args[0]) || bpf_opcode_id(args[0]) != 0x0)
{
parse_asm_opcode(args, stmt);
}
else
throw SEMANTIC_ERROR (_F("unknown bpf embeddedcode operator '%s'",
args[0].c_str()), stmt.tok);
// we returned one statement, there may be more parsing to be done
return pos;
}
/* forward declaration */
std::string translate_escapes (const interned_string &str, const token* tok);
/* Convert a <reg> or <imm> operand to a value.
May emit code to store a string constant on the stack. */
value *
bpf_unparser::emit_asm_arg (const asm_stmt &stmt, const std::string &arg,
bool allow_imm, bool allow_emit)
{
if (arg == "$$")
{
/* arg is a return value */
if (func_return.empty())
throw SEMANTIC_ERROR (_("no return value outside function"), stmt.tok);
return func_return_val.back();
}
else if (arg == "$ctx")
{
/* provide the context where available */
return this_in_arg0 ? this_in_arg0 : this_prog.new_imm(0x0);
}
else if (arg[0] == '$')
{
/* assume arg is a variable */
std::string var = arg.substr(1);
for (auto i = this_locals->begin(); i != this_locals->end(); ++i)
{
vardecl *v = i->first;
if (var == v->unmangled_name)
return i->second;
}
/* if it's an unknown variable, allocate a temporary */
struct vardecl *vd = new vardecl;
vd->name = "__bpfasm__local_" + var;
vd->unmangled_name = var;
vd->type = pe_long;
vd->arity = 0;
value *reg = this_prog.new_reg();
const locals_map::value_type v (vd, reg);
auto ok = this_locals->insert (v);
assert (ok.second);
return reg;
}
else if (is_numeric(arg) && allow_imm)
{
/* arg is an immediate constant */
int64_t imm = stol(arg, 0, 0);
return this_prog.new_imm(imm);
}
else if (is_numeric(arg) || arg[0] == 'r')
{
/* arg is a register number */
std::string reg = arg[0] == 'r' ? arg.substr(1) : arg;
unsigned long num = ULONG_MAX;
bool parsed = false;
try {
num = stoul(reg, 0, 0);
parsed = true;
} catch (std::exception &e) {} // XXX: invalid_argument, out_of_range
if (!parsed || num > 10)
throw SEMANTIC_ERROR (_F("invalid bpf register '%s'",
arg.c_str()), stmt.tok);
return this_prog.lookup_reg(num);
}
else if (arg[0] == '"')
{
if (!allow_emit)
throw SEMANTIC_ERROR (_F("invalid bpf argument %s "
"(string literal not allowed here)",
arg.c_str()), stmt.tok);
/* arg is a string constant */
if (arg[arg.size() - 1] != '"')
throw SEMANTIC_ERROR (_F("BUG: improper string %s",
arg.c_str()), stmt.tok);
std::string escaped_str = arg.substr(1,arg.size()-2); /* strip quotes */
std::string str = translate_escapes(escaped_str, stmt.tok);
return emit_literal_string(str, stmt.tok);
}
else if (arg == "BPF_MAXSTRINGLEN" || arg == "BPF_F_CURRENT_CPU")
{
/* arg is a system constant */
if (!allow_imm)
throw SEMANTIC_ERROR (_F("invalid bpf register '%s'",
arg.c_str()), stmt.tok);
if (arg == "BPF_MAXSTRINGLEN")
return this_prog.new_imm(BPF_MAXSTRINGLEN);
else // arg == "BPF_F_CURRENT_CPU"
return this_prog.new_imm(BPF_F_CURRENT_CPU);
}
else if (arg == "-")
{
/* arg is null a.k.a '0' */
if (!allow_imm)
throw SEMANTIC_ERROR (_F("invalid bpf register '%s'",
arg.c_str()), stmt.tok);
return this_prog.new_imm(0);
}
else if (allow_imm)
throw SEMANTIC_ERROR (_F("invalid bpf argument '%s'",
arg.c_str()), stmt.tok);
else
throw SEMANTIC_ERROR (_F("invalid bpf register '%s'",
arg.c_str()), stmt.tok);
}
/* As above, but don't accept immediate values.
Do accept string constants (since they're stored in a register). */
value *
bpf_unparser::emit_asm_reg (const asm_stmt &stmt, const std::string ®)
{
return emit_asm_arg(stmt, reg, /*allow_imm=*/false);
}
/* As above, but don't allow string constants or anything that emits code.
Useful if the context requires an lvalue. */
value *
bpf_unparser::get_asm_reg (const asm_stmt &stmt, const std::string ®)
{
return emit_asm_arg(stmt, reg, /*allow_imm=*/false, /*allow_emit=*/false);
}
void
bpf_unparser::emit_asm_opcode (const asm_stmt &stmt,
std::map<std::string, block *> label_map)
{
if (stmt.code > 0xff && stmt.code != BPF_LD_MAP)
throw SEMANTIC_ERROR (_("invalid bpf code"), stmt.tok);
bool r_dest = false, r_src0 = false, r_src1 = false, i_src1 = false;
bool op_jmp = false, op_jcond = false;
condition c = EQ; // <- quiet a compiler warning about uninitialized c
switch (BPF_CLASS (stmt.code))
{
case BPF_LDX:
r_dest = r_src1 = true;
break;
case BPF_STX:
r_src0 = r_src1 = true;
break;
case BPF_ST:
r_src0 = i_src1 = true;
break;
case BPF_ALU:
case BPF_ALU64:
r_dest = true;
if (stmt.code & BPF_X)
r_src1 = true;
else
i_src1 = true;
switch (BPF_OP (stmt.code))
{
case BPF_NEG:
case BPF_MOV:
break;
case BPF_END:
/* X/K bit repurposed as LE/BE. */
i_src1 = false, r_src1 = true;
break;
default:
r_src0 = true;
}
break;
case BPF_JMP:
switch (BPF_OP (stmt.code))
{
case BPF_EXIT:
// no special treatment needed
break;
case BPF_CALL:
i_src1 = true;
break;
case BPF_JA:
op_jmp = true;
break;
default:
// XXX: assume this is a jcond op
op_jcond = true;
r_src0 = true;
if (stmt.code & BPF_X)
r_src1 = true;
else
i_src1 = true;
}
// compute jump condition c
switch (BPF_OP (stmt.code))
{
case BPF_JEQ: c = EQ; break;
case BPF_JNE: c = NE; break;
case BPF_JGT: c = GTU; break;
case BPF_JGE: c = GEU; break;
case BPF_JLT: c = LTU; break;
case BPF_JLE: c = LEU; break;
case BPF_JSGT: c = GT; break;
case BPF_JSGE: c = GE; break;
case BPF_JSLT: c = LT; break;
case BPF_JSLE: c = LE; break;
case BPF_JSET: c = TEST; break;
default:
if (op_jcond)
throw SEMANTIC_ERROR (_("invalid branch in bpf code"), stmt.tok);
}
break;
default:
if (stmt.code == BPF_LD_MAP)
r_dest = true, i_src1 = true;
else
throw SEMANTIC_ERROR (_F("unknown opcode '%d' in bpf code",
stmt.code), stmt.tok);
}
value *v_dest = NULL;
if (r_dest || r_src0)
v_dest = get_asm_reg(stmt, stmt.dest);
else if (stmt.dest != "0" && stmt.dest != "-")
throw SEMANTIC_ERROR (_F("invalid register field '%s' in bpf code",
stmt.dest.c_str()), stmt.tok);
value *v_src1 = NULL;
if (r_src1)
v_src1 = emit_asm_reg(stmt, stmt.src1);
else
{
if (stmt.src1 != "0" && stmt.src1 != "-")
throw SEMANTIC_ERROR (_F("invalid register field '%s' in bpf code",
stmt.src1.c_str()), stmt.tok);
if (i_src1)
v_src1 = this_prog.new_imm(stmt.imm);
else if (stmt.imm != 0)
throw SEMANTIC_ERROR (_("invalid immediate field in bpf code"), stmt.tok);
}
if (stmt.off != (int16_t)stmt.off)
throw SEMANTIC_ERROR (_F("offset field '%lld' out of range in bpf code", (long long) stmt.off), stmt.tok);
if (op_jmp)
{
block *target = label_map[stmt.jmp_target];
this_prog.mk_jmp(this_ins, target);
}
else if (op_jcond)
{
if (label_map.count(stmt.jmp_target) == 0)
throw SEMANTIC_ERROR(_F("undefined jump target '%s' in bpf code",
stmt.jmp_target.c_str()), stmt.tok);
if (label_map.count(stmt.fallthrough) == 0)
throw SEMANTIC_ERROR(_F("BUG: undefined fallthrough target '%s'",
stmt.fallthrough.c_str()), stmt.tok);
block *target = label_map[stmt.jmp_target];
block *fallthrough = label_map[stmt.fallthrough];
this_prog.mk_jcond(this_ins, c, v_dest, v_src1, target, fallthrough);
}
else // regular opcode
{
insn *i = this_ins.new_insn();
i->code = stmt.code;
i->dest = (r_dest ? v_dest : NULL);
i->src0 = (r_src0 ? v_dest : NULL);
i->src1 = v_src1;
i->off = stmt.off;
}
}
void
bpf_unparser::visit_embeddedcode (embeddedcode *s)
{
#ifdef DEBUG_CODEGEN
this_ins.notes.push("asm");
// XXX verbose; for more precise diagnostics:
//std::stringstream os; os << s->tok->location;
//this_ins.notes.push("asm@" + os.str());
#endif
// XXX allocate asm_stmts off the stack to avoid deallocating tok on throw
std::vector<asm_stmt> *statements_p = new std::vector<asm_stmt>;
std::vector<asm_stmt> &statements = *statements_p;
asm_stmt stmt;
// PR24528: The /* userspace */ annotation is used to mark
// userspace-only BPF embeddedcode tapset functions.
if (s->tagged_p("/* userspace */") &&
this_prog.target == target_kernel_bpf)
throw SEMANTIC_ERROR(_("embeddedcode marked /* userspace */ in kernel bpf probe"), s->tok);
// track adjusted source location for each stmt
adjusted_loc = s->tok->location;
adjust_pos = 0;
size_t pos = 0;
while ((pos = parse_asm_stmt(s, pos, stmt)) != std::string::npos)
{
statements.push_back(stmt);
}
// XXX past this point, adjusted_loc/adjust_pos no longer used,
// therefore safe to overwrite in a recursive visit_embeddedcode call
// build basic block table
std::map<std::string, block *> label_map;
block *entry_block = this_ins.b;
label_map[";;entry"] = entry_block;
bool after_label = true;
asm_stmt *after_jump = NULL;
unsigned fallthrough_count = 0;
for (std::vector<asm_stmt>::iterator it = statements.begin();
it != statements.end(); it++)
{
stmt = *it;
if (after_jump != NULL && stmt.kind == "label")
{
after_jump->has_fallthrough = true;
after_jump->fallthrough = stmt.dest;
}
else if (after_jump != NULL)
{
block *b = this_prog.new_block();
// generate unique label for fallthrough edge
std::ostringstream oss;
oss << "fallthrough;;" << fallthrough_count++;
std::string fallthrough_label = oss.str();
// XXX: semicolons prevent collision with programmer-defined labels
label_map[fallthrough_label] = b;
set_block(b);
after_jump->has_fallthrough = true;
after_jump->fallthrough = fallthrough_label;
}
if (stmt.kind == "label" && after_label)
{
// avoid creating multiple blocks for consecutive labels
label_map[stmt.dest] = this_ins.b;
after_jump = NULL;
}
else if (stmt.kind == "label")
{
block *b = this_prog.new_block();
label_map[stmt.dest] = b;
set_block(b);
after_label = true;
after_jump = NULL;
}
else if (stmt.has_fallthrough)
{
after_label = false;
after_jump = &*it; // be sure to refer to original, not copied stmt
}
else if (stmt.kind == "opcode" && BPF_CLASS(stmt.code) == BPF_JMP
&& BPF_OP(stmt.code) != BPF_CALL /* CALL stays in the same block */)
{
after_label = false;
after_jump = &*it; // be sure to refer to original, not copied stmt
}
else
{
after_label = false;
after_jump = NULL;
}
}
if (after_jump != NULL) // ??? should just fall through to exit
throw SEMANTIC_ERROR (_("BUG: bpf embeddedcode doesn't support "
"fallthrough on final asm_stmt"), stmt.tok);
// emit statements
bool jumped_already = false;
set_block(entry_block);
for (std::vector<asm_stmt>::iterator it = statements.begin();
it != statements.end(); it++)
{
stmt = *it;
#ifdef BPF_ASM_DEBUG
std::cerr << "bpf_asm visit_embeddedcode: " << stmt << std::endl;
#endif
if (stmt.kind == "label")
{
if (!jumped_already)
emit_jmp (label_map[stmt.dest]);
set_block(label_map[stmt.dest]);
}
else if (stmt.kind == "alloc")
{
/* Reserve stack space and store its address in dest. */
int ofs = -this_prog.max_tmp_space - stmt.imm;
if (stmt.align_alloc && (-ofs) % 8 != 0) // align to double-word
ofs -= 8 - (-ofs) % 8;
this_prog.use_tmp_space(-ofs);
// ??? Consider using a storage allocator and this_prog.new_obj().
value *dest = get_asm_reg(stmt, stmt.dest);
this_prog.mk_binary(this_ins, BPF_ADD, dest,
this_prog.lookup_reg(BPF_REG_10) /*frame*/,
this_prog.new_imm(ofs));
}
else if (stmt.kind == "jump_to_catch")
{
/**
* jump_to_catch allows the program to switch the execution to
* a catch block in the case that an error is called during the
* corresponding try block. Pointers to catch blocks are set up
* before the code for the try block is emitted and are stored
* in catch_jump.
*/
// Store the error message for the catch block.
value *msg = emit_asm_arg(stmt, stmt.params[0]);
catch_msg.push_back(msg);
// error_block contains the code for the error procedure in the
// case that error is called outside a try-catch statement.
block* error_block = this_prog.new_block();
// Since it is known at compile time as to whether the error is
// called inside a try-catch block or not, a jump to the correct
// procedure can be emitted.
if (!catch_jump.empty())
emit_jmp(catch_jump.back());
else
emit_jmp(error_block);
set_block(error_block);
}
else if (stmt.kind == "register_error")
{
// Set the error status.
value *status = this_prog.new_imm(1);
emit_mov(error_status, status);
// NB: The error message has to be stored for future printing. The current
// mechanism uses a perf_event to pass the string into userspace. This has
// to be done because storing the string on the BPF stack consumes too much
// space, and this space is only freed during the epilogue where the error
// message is printed. If future versions of BPF introduce more stack space,
// the mechanism could be altered to use the stack instead.
value *error_msg = emit_asm_arg(stmt, stmt.params[0]);
emit_transport_msg(globals::STP_STORE_ERROR_MSG, error_msg, pe_string);
}
else if (stmt.kind == "terminate")
{
/* Short-circuit the program to its completition. */
block* join_block = this_prog.new_block();
block* exit_block = get_exit_block();
emit_jmp(exit_block);
set_block(join_block);
}
else if (stmt.kind == "call")
{
assert (!stmt.params.empty());
std::string func_name = stmt.params[0];
bpf_func_id hid = bpf_function_id(func_name);
if (hid != __BPF_FUNC_MAX_ID)
{
// ??? For diagnostics: check if the number of arguments is correct.
regno r = BPF_REG_1; unsigned nargs = 0;
for (unsigned k = 1; k < stmt.params.size(); k++)
{
// ??? Could make params optional to avoid the MOVs,
// ??? since the calling convention is well-known.
value *from_reg = emit_asm_arg(stmt, stmt.params[k]);
value *to_reg = this_prog.lookup_reg(r);
this_prog.mk_mov(this_ins, to_reg, from_reg);
nargs++; r++;
}
this_prog.mk_call(this_ins, hid, nargs);
if (stmt.dest != "-")
{
value *dest = get_asm_reg(stmt, stmt.dest);
this_prog.mk_mov(this_ins, dest,
this_prog.lookup_reg(BPF_REG_0) /* returnval */);
}
// ??? For diagnostics: check other cases with stmt.dest.
}
else if (func_name == "printf" || func_name == "sprintf")
{
if (stmt.params.size() < 2)
throw SEMANTIC_ERROR (_F("bpf embeddedcode '%s' expects format string, "
"none provided", func_name.c_str()),
stmt.tok);
std::string format = stmt.params[1];
if (format.size() < 2 || format[0] != '"'
|| format[format.size()-1] != '"')
throw SEMANTIC_ERROR (_F("bpf embeddedcode '%s' expects format string, "
"but first parameter is not a string literal",
func_name.c_str()), stmt.tok);
format = format.substr(1,format.size()-2); /* strip quotes */
format = translate_escapes(format, stmt.tok);
size_t format_bytes = format.size() + 1;
if (format_bytes > BPF_MAXFORMATLEN)
throw SEMANTIC_ERROR(_("Format string for print too long"), stmt.tok);
std::vector<value *> args;
for (unsigned k = 2; k < stmt.params.size(); k++)
args.push_back(emit_asm_arg(stmt, stmt.params[k]));
if (args.size() > BPF_MAXPRINTFARGS)
throw SEMANTIC_ERROR(_NF("additional argument to print",
"too many arguments to print (%zu)",
args.size(), args.size()), stmt.tok);
bool print_to_stream = (func_name == "printf");
value *retval = emit_print_format(format, args, print_to_stream, stmt.tok);
if (retval != NULL && stmt.dest != "-")
{
value *dest = get_asm_reg(stmt, stmt.dest);
this_prog.mk_mov(this_ins, dest, retval);
}
// ??? For diagnostics: check other cases with retval and stmt.dest.
}
else
{
// TODO: Experimental code for supporting basic functioncalls.
// Needs improvement and simplification to work with full generality.
// But thus far, it is sufficient for calling exit().
#if 1
if (func_name != "exit")
throw SEMANTIC_ERROR(_("BUG: bpf embeddedcode non-helper 'call' operation only supports printf(),sprintf(),exit() for now"), stmt.tok);
#elif 1
throw SEMANTIC_ERROR(_("BUG: bpf embeddedcode non-helper 'call' operation only supports printf(),sprintf() for now"), stmt.tok);
#endif
#if 1
// ???: Passing systemtap_session through all the way to here
// seems intrusive, but less intrusive than moving
// embedded-code assembly to the translate_globals() pass.
symresolution_info sym (*glob.session);
functioncall *call = new functioncall;
call->tok = stmt.tok;
unsigned nargs = stmt.params.size() - 1;
std::vector<functiondecl*> fds
= sym.find_functions (call, func_name, nargs, stmt.tok);
delete call;
if (fds.empty())
// ??? Could call levenshtein_suggest() as in
// symresolution_info::visit_functioncall().
throw SEMANTIC_ERROR(_("bpf embeddedcode unresolved function call"), stmt.tok);
if (fds.size() > 1)
throw SEMANTIC_ERROR(_("bpf embeddedcode unhandled function overloading"), stmt.tok);
functiondecl *f = fds[0];
// TODO: Imitation of semantic_pass_symbols, does not
// cover full generality of the lookup process.
update_visitor_loop (*glob.session, glob.session->code_filters, f->body);
sym.current_function = f; sym.current_probe = 0;
f->body->visit (&sym);
// ??? For now, always inline the function call.
for (auto i = func_calls.begin(); i != func_calls.end(); ++i)
if (f == *i)
throw SEMANTIC_ERROR (_("unhandled function recursion"), stmt.tok);
// Collect the function arguments.
std::vector<value *> args;
for (unsigned k = 1; k < stmt.params.size(); k++)
args.push_back(emit_asm_arg(stmt, stmt.params[k]));
if (args.size () != f->formal_args.size())
throw SEMANTIC_ERROR(_F("bpf embeddedcode call to function '%s' "
"expected %zu arguments, got %zu",
func_name.c_str(),
f->formal_args.size(), args.size()),
stmt.tok);
value *retval = emit_functioncall(f, args);
if (stmt.dest != "-")
{
value *dest = get_asm_reg(stmt, stmt.dest);
this_prog.mk_mov(this_ins, dest, retval);
}
// ??? For diagnostics: check other cases with retval and stmt.dest.
#endif
}
}
else if (stmt.kind == "opcode")
{
emit_asm_opcode (stmt, label_map);
}
else
throw SEMANTIC_ERROR (_F("BUG: bpf embeddedcode contains unexpected "
"asm_stmt kind '%s'", stmt.kind.c_str()),
stmt.tok);
if (stmt.has_fallthrough)
{
jumped_already = true;
set_block(label_map[stmt.fallthrough]);
}
else
jumped_already = false;
}
delete statements_p;
#ifdef DEBUG_CODEGEN
this_ins.notes.pop(); // asm
#endif
}
void
bpf_unparser::visit_try_block (try_block* s)
{
block* catch_block = this_prog.new_block();
block* join_block = this_prog.new_block();
// Prepare the catch block in case an error is called. The
// catch block code is emitted after the try block because
// error messages are propagated during the error statements
// which are expected to occur in the try blocks.
catch_jump.push_back(catch_block);
// Emit code for statements inside try block. If one of these
// statements is a call to error(...), then the execution will
// switch over to the catch block set up above.
emit_stmt(s->try_block);
// Remove the catch block as the try block has been emitted
// (this is useful when dealing with nested try-catch blocks).
catch_jump.pop_back();
if (in_block ())
emit_jmp(join_block);
set_block(catch_block);
// Set up connection to the error message.
if (s->catch_error_var)
{
vardecl* catch_var_decl = s->catch_error_var->referent;
auto j = this_locals->find(catch_var_decl);
if (j == this_locals->end())
throw SEMANTIC_ERROR(_("unknown value"), catch_var_decl->tok);
value* catch_var = j->second;
// This message is stored during jump_to_catch.
value* error_var = catch_msg.back();
catch_msg.pop_back();
this_prog.mk_mov(this_ins, catch_var, error_var);
}
// After setting up the message, the catch block can run.
emit_stmt(s->catch_block);
if (in_block ())
emit_jmp(join_block);
set_block(join_block);
}
void
bpf_unparser::visit_block (::block *s)
{
unsigned n = s->statements.size();
for (unsigned i = 0; i < n; ++i)
emit_stmt (s->statements[i]);
}
void
bpf_unparser::visit_null_statement (null_statement *)
{ }
void
bpf_unparser::visit_expr_statement (expr_statement *s)
{
(void) emit_expr (s->value);
}
void
bpf_unparser::visit_if_statement (if_statement* s)
{
block *then_block = this_prog.new_block ();
block *join_block = this_prog.new_block ();
if (s->elseblock)
{
block *else_block = this_prog.new_block ();
emit_cond (s->condition, then_block, else_block);
set_block (then_block);
emit_stmt (s->thenblock);
if (in_block ())
emit_jmp (join_block);
set_block (else_block);
emit_stmt (s->elseblock);
if (in_block ())
emit_jmp (join_block);
}
else
{
emit_cond (s->condition, then_block, join_block);
set_block (then_block);
emit_stmt (s->thenblock);
if (in_block ())
emit_jmp (join_block);
}
set_block (join_block);
}
void
bpf_unparser::visit_for_loop (for_loop* s)
{
// PR24528: Userspace-only feature.
if (this_prog.target == target_kernel_bpf)
throw SEMANTIC_ERROR(_("unsupported loop in bpf kernel probe"), s->tok);
// TODO: Future versions of BPF will include limited looping capability.
block *body_block = this_prog.new_block ();
block *iter_block = this_prog.new_block ();
block *test_block = this_prog.new_block ();
block *join_block = this_prog.new_block ();
emit_stmt (s->init);
if (!in_block ())
return;
emit_jmp (test_block);
loop_break.push_back (join_block);
loop_cont.push_back (iter_block);
set_block (body_block);
emit_stmt (s->block);
if (in_block ())
emit_jmp (iter_block);
loop_cont.pop_back ();
loop_break.pop_back ();
set_block (iter_block);
emit_stmt (s->incr);
if (in_block ())
emit_jmp (test_block);
set_block (test_block);
emit_cond (s->cond, body_block, join_block);
set_block (join_block);
}
void
bpf_unparser::visit_foreach_loop(foreach_loop* s)
{
// PR24528: Userspace-only feature.
if (this_prog.target == target_kernel_bpf)
throw SEMANTIC_ERROR(_("unsupported loop in bpf kernel probe"), s->tok);
// TODO: Future versions of BPF will include limited looping capability.
// TODO: Handle array_slice in foreach iteration.
if (!s->array_slice.empty())
throw SEMANTIC_ERROR(_("unsupported array slice in bpf foreach loop"), s->tok);
bool composite_key = s->indexes.size() != 1;
std::vector<vardecl *> key_decls;
std::vector<value *> keys; // key_decls[i] refers to keys[i]
std::vector<unsigned> key_offsets; // key_decls[i] is at keys_offset[i]
// Populate key_decls
for (unsigned k = 0; k < s->indexes.size(); k++)
{
vardecl *keydecl = s->indexes[k]->referent;
key_decls.push_back(keydecl);
auto i = this_locals->find(keydecl);
if (i == this_locals->end())
throw SEMANTIC_ERROR(_("unknown index"), keydecl->tok);
keys.push_back(i->second);
}
// Get arraydecl
symbol *a;
if (! (a = dynamic_cast<symbol *>(s->base)))
throw SEMANTIC_ERROR(_("unknown type"), s->base->tok);
vardecl *arraydecl = a->referent;
// Populate key_offsets, foreach_info
globals::foreach_info info;
info.sort_direction = s->sort_direction;
info.sort_column = s->sort_column;
// XXX: s->sort_column may be uninitialized if s->sort_direction == 0
//if (s->sort_direction == 0) info.sort_column = 1;
info.keysize = 0;
info.sort_column_size = 0;
info.sort_column_ofs = 0;
for (unsigned k = 0; k < arraydecl->index_types.size(); k++)
{
auto type = arraydecl->index_types[k];
int this_column_size;
// PR23875: foreach should handle string keys
if (type == pe_long)
{
this_column_size = 8;
}
else if (type == pe_string)
{
this_column_size = BPF_MAXSTRINGLEN;
}
else
{
throw SEMANTIC_ERROR(_("unhandled foreach index type"), s->tok);
}
if (info.sort_column == k + 1) // record sort column
{
info.sort_column_size = this_column_size;
info.sort_column_ofs = info.keysize;
}
key_offsets.push_back(info.keysize);
info.keysize += this_column_size;
}
if (arraydecl->index_types.size() == 1)
{
// Signals map_get_next_key to treat the key as a single value:
info.sort_column_ofs = -1;
}
// Save foreach_info to foreach_loop_info_table
globals::loop_idx foreach_id = glob.foreach_loop_info.size();
glob.foreach_loop_info.push_back(info);
// Get map_slot for arraydecl
auto g = glob.globals.find(arraydecl);
if (g == glob.globals.end())
throw SEMANTIC_ERROR(_("unknown array"), arraydecl->tok);
int map_id = g->second.map_id;
bool is_stat_array = g->second.is_stat();
// PR23476: Handle foreach iteration for stats arrays.
assert(!g->second.is_scalar()); // XXX scalar map slot was used for arraydecl
if (is_stat_array)
{
// Get stats_map for arraydecl
auto all_fields = glob.array_stats.find(arraydecl);
if (all_fields == glob.array_stats.end())
throw SEMANTIC_ERROR(_("unknown stats array"), arraydecl->tok);
// Get the correct map for aggregates:
auto one_field = all_fields->second.find(globals::stat_iter_field);
assert (one_field != all_fields->second.end());
map_id = one_field->second;
// XXX: Since foreach only handles/returns keys, for the basic
// case it's sufficient to simply iterate one of the stat field
// maps.
//
// TODO PR24528: But if sorting on aggregate is required
// (when info.sort_column==0, s->sort_aggr is set),
// then map_get_next_key will need to perform aggregation
// calculations, and these will require access to more than one map.
//
// TODO PR24528: Need to pass s->sort_aggr, agg_idx via foreach_info.
// TODO PR24528: Verify with foreach_sort_stat.exp testcase.
if (info.sort_column == 0)
throw SEMANTIC_ERROR(_("unsupported sorted iteration on stat aggregate"), arraydecl->tok);
}
// Initialize constants, values, blocks
int keyref_size = 8; // the BPF stack holds a pointer to the key
value *limit;
if (s->limit)
limit = this_prog.new_reg();
else
limit = this_prog.new_imm(-1);
value *keyref;
if (composite_key)
keyref = this_prog.new_reg();
else
keyref = keys[0];
value *i0 = this_prog.new_imm(0);
value *id = this_prog.new_imm(foreach_id);
value *frame = this_prog.lookup_reg(BPF_REG_10);
block *body_block = this_prog.new_block ();
block *load_block_1 = this_prog.new_block ();
block *iter_block = this_prog.new_block ();
block *join_block = this_prog.new_block ();
// Reserve stack space; XXX may be cleared by the loop body
value *key_ofs = this_prog.new_imm(-keyref_size);
value *newkey_ofs = this_prog.new_imm(-keyref_size-keyref_size);
this_prog.use_tmp_space(2*keyref_size);
// Setup iteration limit
if (s->limit)
this_prog.mk_mov(this_ins, limit, emit_expr(s->limit));
// Get the first key
this_prog.load_map (this_ins, this_prog.lookup_reg(BPF_REG_1), map_id);
this_prog.mk_mov (this_ins, this_prog.lookup_reg(BPF_REG_2), i0);
this_prog.mk_binary (this_ins, BPF_ADD, this_prog.lookup_reg(BPF_REG_3),
frame, newkey_ofs);
this_prog.mk_mov (this_ins, this_prog.lookup_reg(BPF_REG_4), id);
this_prog.mk_mov (this_ins, this_prog.lookup_reg(BPF_REG_5), limit);
this_prog.mk_call (this_ins, BPF_FUNC_map_get_next_key, 5);
this_prog.mk_jcond (this_ins, NE, this_prog.lookup_reg(BPF_REG_0), i0,
join_block, load_block_1);
// Enter loop body
set_block(body_block);
loop_break.push_back (join_block);
loop_cont.push_back (iter_block);
emit_stmt(s->block); // XXX may clobber key, newkey at top of stack
loop_cont.pop_back ();
loop_break.pop_back();
if (in_block ())
emit_jmp(iter_block);
// Get the next key, exit loop if map_get_next_key doesn't return 0
set_block(iter_block);
this_prog.mk_st (this_ins, BPF_DW, frame, -keyref_size /*key_ofs*/, keyref);
this_prog.load_map (this_ins, this_prog.lookup_reg(BPF_REG_1), map_id);
this_prog.mk_binary (this_ins, BPF_ADD, this_prog.lookup_reg(BPF_REG_2),
frame, key_ofs);
this_prog.mk_binary (this_ins, BPF_ADD, this_prog.lookup_reg(BPF_REG_3),
frame, newkey_ofs);
this_prog.mk_mov (this_ins, this_prog.lookup_reg(BPF_REG_4), id);
this_prog.mk_mov (this_ins, this_prog.lookup_reg(BPF_REG_5), limit);
this_prog.mk_call (this_ins, BPF_FUNC_map_get_next_key, 5);
this_prog.mk_jcond (this_ins, NE, this_prog.lookup_reg(BPF_REG_0), i0,
join_block, load_block_1);
// Load from newkey_ofs to keyref
set_block(load_block_1);
this_prog.mk_ld (this_ins, BPF_DW, keyref,
frame, -keyref_size-keyref_size /*newkey_ofs*/);
// XXX For single-key arrays, keyref already contains the value:
// - either the integer value (for a pe_long key)
// - or a pointer to the string value (for a pe_string key)
// PR23478: Unpack keyref into individual indices
if (composite_key)
{
for (unsigned k = 0; k < s->indexes.size(); k++)
{
switch (key_decls[k]->type)
{
case pe_long:
// XXX load the long value
this_prog.mk_ld (this_ins, BPF_DW, keys[k], keyref, key_offsets[k]);
break;
case pe_string:
// XXX pass a pointer to the string value
this_prog.mk_binary (this_ins, BPF_ADD, keys[k],
keyref, this_prog.new_imm(key_offsets[k]));
break;
default:
throw SEMANTIC_ERROR (_("unhandled foreach key type"),
key_decls[k]->tok);
}
}
}
// If the foreach loop requests a value, retrieve the value
if (s->value)
{
vardecl *valdecl = s->value->referent;
// TODO PR23476: is s->value ever set for a statistic array iteration?
if (is_stat_array)
throw SEMANTIC_ERROR(_("unsupported value iteration on stat aggregate"), arraydecl->tok);
auto i = this_locals->find(valdecl);
if (i == this_locals->end())
throw SEMANTIC_ERROR(_("unknown value"), valdecl->tok);
value *val = i->second;
block *load_block_2 = this_prog.new_block ();
this_prog.load_map (this_ins, this_prog.lookup_reg(BPF_REG_1), map_id);
// To lookup value, we pass a pointer to the key.
// If the key is a single integer, we need to pass the integer value's
// location in the stack. Otherwise, keyref already holds the pointer.
if (!composite_key && key_decls[0]->type == pe_long)
{
// XXX reuse not-yet-clobbered newkey value from map_get_next_key
this_prog.mk_binary (this_ins, BPF_ADD,
this_prog.lookup_reg(BPF_REG_2),
frame, newkey_ofs);
}
else
{
this_prog.mk_mov (this_ins, this_prog.lookup_reg(BPF_REG_2), keyref);
}
this_prog.mk_call(this_ins, BPF_FUNC_map_lookup_elem, 2);
this_prog.mk_jcond (this_ins, EQ, this_prog.lookup_reg(BPF_REG_0), i0,
join_block, load_block_2);
// Load the corresponding value if key was valid
set_block(load_block_2);
switch (valdecl->type)
{
case pe_long:
// If the value is an integer, we must dereference the pointer:
this_prog.mk_ld(this_ins, BPF_DW, val, this_prog.lookup_reg(BPF_REG_0), 0);
break;
case pe_string:
this_prog.mk_mov(this_ins, val, this_prog.lookup_reg(BPF_REG_0));
break;
default:
throw SEMANTIC_ERROR (_("unhandled foreach value type"), valdecl->tok);
}
}
// Decrement the iteration limit
if (s->limit)
this_prog.mk_binary (this_ins, BPF_ADD, limit, limit, this_prog.new_imm(-1));
emit_jmp(body_block);
set_block(join_block);
}
void
bpf_unparser::visit_break_statement (break_statement* s)
{
if (loop_break.empty ())
throw SEMANTIC_ERROR (_("cannot 'break' outside loop"), s->tok);
emit_jmp (loop_break.back ());
}
void
bpf_unparser:: visit_continue_statement (continue_statement* s)
{
if (loop_cont.empty ())
throw SEMANTIC_ERROR (_("cannot 'continue' outside loop"), s->tok);
emit_jmp (loop_cont.back ());
}
void
bpf_unparser::visit_return_statement (return_statement* s)
{
if (func_return.empty ())
throw SEMANTIC_ERROR (_("cannot 'return' outside function"), s->tok);
assert (!func_return_val.empty ());
if (s->value)
emit_mov (func_return_val.back (), emit_expr (s->value));
emit_jmp (func_return.back ());
}
void
bpf_unparser::visit_next_statement (next_statement* s)
{
if (!func_return.empty ())
throw SEMANTIC_ERROR(_("bpf unhandled next statement in function"), s->tok);
emit_jmp(exit_block);
}
void
bpf_unparser::visit_delete_statement (delete_statement *s)
{
expression *e = s->value;
if (symbol *s = dynamic_cast<symbol *>(e))
{
vardecl *var = s->referent;
if (var->arity != 0)
throw SEMANTIC_ERROR (_("unimplemented delete of array"), s->tok);
auto g = glob.globals.find (var);
if (g != glob.globals.end())
{
value *frame = this_prog.lookup_reg(BPF_REG_10);
int key_ofs, val_ofs;
switch (var->type)
{
case pe_long:
val_ofs = -8;
this_prog.mk_st(this_ins, BPF_DW, frame, val_ofs,
this_prog.new_imm(0));
this_prog.mk_binary(this_ins, BPF_ADD,
this_prog.lookup_reg(BPF_REG_3),
frame, this_prog.new_imm(val_ofs));
break;
// ??? pe_string -> (2) TODO delete ref (but leave the storage for later cleanup of the entire containing struct?)
// ??? pe_stats -> TODOXXX
default:
goto err;
}
key_ofs = val_ofs - 4;
this_prog.mk_st(this_ins, BPF_W, frame, key_ofs,
this_prog.new_imm(g->second.idx));
this_prog.use_tmp_space(-key_ofs);
// TODO: Handle map_id < 0 for pe_stats, or assert otherwise.
if (g->second.map_id < 0)
throw SEMANTIC_ERROR (_("unsupported delete operation on statistics aggregate"), s->tok); // TODOXXX PR23476
this_prog.load_map(this_ins, this_prog.lookup_reg(BPF_REG_1),
g->second.map_id);
this_prog.mk_binary(this_ins, BPF_ADD,
this_prog.lookup_reg(BPF_REG_2),
frame, this_prog.new_imm(key_ofs));
emit_mov(this_prog.lookup_reg(BPF_REG_4), this_prog.new_imm(0));
this_prog.mk_call(this_ins, BPF_FUNC_map_update_elem, 4);
return;
}
auto i = this_locals->find (var);
if (i != this_locals->end ())
{
emit_mov (i->second, this_prog.new_imm(0));
return;
}
}
else if (arrayindex *a = dynamic_cast<arrayindex *>(e))
{
if (symbol *a_sym = dynamic_cast<symbol *>(a->base))
{
vardecl *v = a_sym->referent;
int key_ofs = 0;
auto g = glob.globals.find(v);
if (g == glob.globals.end())
throw SEMANTIC_ERROR(_("unknown array variable"), v->tok);
unsigned element = v->arity;
// iterate over the elements
do {
--element;
value *idx = emit_expr(a->indexes[element]);
switch (v->index_types[element])
{
case pe_long:
// Store the long on the stack and pass its address:
key_ofs -= 8;
emit_long_arg(this_prog.lookup_reg(BPF_REG_2), key_ofs, idx);
break;
case pe_string:
// Zero-pad and copy the string to the stack and pass its address:
key_ofs -= BPF_MAXSTRINGLEN;
emit_str_arg(this_prog.lookup_reg(BPF_REG_2), key_ofs, idx);
break;
default:
throw SEMANTIC_ERROR(_("unhandled index type"), e->tok);
}
} while (element);
this_prog.use_tmp_space(-key_ofs);
// TODO: Handle map_id < 0 for pe_stats or assert otherwise.
if (g->second.map_id < 0)
throw SEMANTIC_ERROR (_("unsupported delete operation on statistics aggregate"), a->tok); // TODOXXX PR23476
this_prog.load_map(this_ins, this_prog.lookup_reg(BPF_REG_1),
g->second.map_id);
this_prog.mk_call(this_ins, BPF_FUNC_map_delete_elem, 2);
return;
}
}
err:
throw SEMANTIC_ERROR (_("unknown lvalue"), e->tok);
}
// Translate string escape characters.
// Accepts strings produced by parse.cxx lexer::scan and
// by the eBPF embedded-code assembler.
//
// PR23559: This is currently an eBPF-only version of the function
// that does not translate octal escapes.
std::string
translate_escapes (const interned_string &str, const token* tok)
{
std::string result;
bool saw_esc = false;
for (interned_string::const_iterator j = str.begin();
j != str.end(); ++j)
{
if (saw_esc)
{
saw_esc = false;
switch (*j)
{
case 'f': result += '\f'; break;
case 'n': result += '\n'; break;
case 'r': result += '\r'; break;
case 't': result += '\t'; break;
case 'v': result += '\v'; break;
// Translate octal and hex escapes:
case '0' ... '7':
{
unsigned int c = 0;
// An octal escape sequence is at most 3 characters.
for (unsigned k = 0; k < 3; ++k)
{
c = c * 8 + (*j - '0');
++j;
if (j == str.end() || *j < '0' || *j > '7')
{
--j; // avoid swallowing extra char
break;
}
}
// TODO: this check should be performed by the parser
if (c > 255 /* \377 */)
throw SEMANTIC_ERROR (_("octal escape sequence out of range"), tok);
if (c != 0) // XXX skip '\0' as it can break a transport tag
result += (char) c;
}
break;
case 'x':
{
unsigned int c = 0; ++j;
// A hex escape sequence is arbitrarily long.
// XXX: Behaviour is 'undefined' when overflowing char.
for (; j != str.end(); ++j)
{
if (*j >= '0' && *j <= '9')
c = c * 16 + (*j - '0');
else if (*j >= 'a' && *j <= 'f')
c = c * 16 + (*j - 'a' + 10);
else if (*j >= 'A' && *j <= 'F')
c = c * 16 + (*j - 'A' + 10);
else
{
--j; // avoid swallowing extra char
break;
}
}
// TODO: this check should be performed by the parser
if (c > 0xff)
throw SEMANTIC_ERROR (_("hex escape sequence out of range"), tok);
if (c != 0) // XXX skip '\0' as it can break a transport tag
result += (char) c;
// If we've hit the end of the string , then return the result.
if (j == str.end())
return result;
}
break;
default: result += *j; break;
}
}
else if (*j == '\\')
saw_esc = true;
else
result += *j;
}
return result;
}
value *
bpf_unparser::emit_literal_string (const std::string &str, const token *tok)
{
size_t str_bytes = str.size() + 1;
if (str_bytes > BPF_MAXSTRINGLEN)
throw SEMANTIC_ERROR(_("string literal too long"), tok);
return this_prog.new_str(str); // will be lowered to a pointer by bpf-opt.cxx
}
void
bpf_unparser::visit_literal_string (literal_string* e)
{
interned_string v = e->value;
std::string str = translate_escapes(v, e->tok);
result = emit_literal_string(str, e->tok);
}
void
bpf_unparser::visit_literal_number (literal_number* e)
{
result = this_prog.new_imm(e->value);
}
void
bpf_unparser::visit_binary_expression (binary_expression* e)
{
int code;
if (e->op == "+")
code = BPF_ADD;
else if (e->op == "-")
code = BPF_SUB;
else if (e->op == "*")
code = BPF_MUL;
else if (e->op == "&")
code = BPF_AND;
else if (e->op == "|")
code = BPF_OR;
else if (e->op == "^")
code = BPF_XOR;
else if (e->op == "<<")
code = BPF_LSH;
else if (e->op == ">>")
code = BPF_ARSH;
else if (e->op == ">>>")
code = BPF_RSH;
else if (e->op == "/")
code = BPF_DIV;
else if (e->op == "%")
code = BPF_MOD;
else
throw SEMANTIC_ERROR (_("unhandled binary operator"), e->tok);
value *s0 = this_prog.new_reg();
// copy e->left into a seperate reg in case evaluating e->right
// causes e->left to mutate (ex. x + x++).
this_prog.mk_mov(this_ins, s0, emit_expr (e->left));
value *s1 = emit_expr (e->right);
value *d = this_prog.new_reg ();
this_prog.mk_binary (this_ins, code, d, s0, s1);
result = d;
}
void
bpf_unparser::visit_unary_expression (unary_expression* e)
{
if (e->op == "-")
{
// Note that negative literals appear in the script langauge as
// unary negations over positive literals.
if (literal_number *lit = dynamic_cast<literal_number *>(e))
result = this_prog.new_imm(-(uint64_t)lit->value);
else
{
value *s = emit_expr (e->operand);
value *d = this_prog.new_reg();
this_prog.mk_unary (this_ins, BPF_NEG, d, s);
result = d;
}
}
else if (e->op == "~")
{
value *s1 = this_prog.new_imm(-1);
value *s0 = emit_expr (e->operand);
value *d = this_prog.new_reg ();
this_prog.mk_binary (this_ins, BPF_XOR, d, s0, s1);
result = d;
}
else if (e->op == "!")
result = emit_bool (e);
else if (e->op == "+")
result = emit_expr (e->operand);
else
throw SEMANTIC_ERROR (_("unhandled unary operator"), e->tok);
}
void
bpf_unparser::visit_pre_crement (pre_crement* e)
{
int dir;
if (e->op == "++")
dir = 1;
else if (e->op == "--")
dir = -1;
else
throw SEMANTIC_ERROR (_("unhandled crement operator"), e->tok);
value *c = this_prog.new_imm(dir);
value *v = emit_expr (e->operand);
this_prog.mk_binary (this_ins, BPF_ADD, v, v, c);
emit_store (e->operand, v);
result = v;
}
void
bpf_unparser::visit_post_crement (post_crement* e)
{
int dir;
if (e->op == "++")
dir = 1;
else if (e->op == "--")
dir = -1;
else
throw SEMANTIC_ERROR (_("unhandled crement operator"), e->tok);
value *c = this_prog.new_imm(dir);
value *r = this_prog.new_reg ();
value *v = emit_expr (e->operand);
emit_mov (r, v);
this_prog.mk_binary (this_ins, BPF_ADD, v, v, c);
emit_store (e->operand, v);
result = r;
}
void
bpf_unparser::visit_logical_or_expr (logical_or_expr* e)
{
result = emit_bool (e);
}
void
bpf_unparser::visit_logical_and_expr (logical_and_expr* e)
{
result = emit_bool (e);
}
// ??? This matches the code in translate.cxx, but it looks like the
// functionality has been disabled in the SystemTap parser.
void
bpf_unparser::visit_compound_expression (compound_expression* e)
{
e->left->visit(this);
e->right->visit(this); // overwrite result of first expression
}
void
bpf_unparser::visit_comparison (comparison* e)
{
result = emit_bool (e);
}
void
bpf_unparser::visit_concatenation (concatenation* e)
{
if (this_prog.target == target_kernel_bpf)
throw SEMANTIC_ERROR(_("unsupported in bpf kernel probe"), e->tok);
// We make use of many temporary registers because intermediate strings
// can arise from function calls which may clobber registers that hold data.
value *l = emit_expr (e->left);
value* placeholder_l = this_prog.new_reg();
this_prog.mk_mov(this_ins, placeholder_l, l);
value *r = emit_expr (e->right);
value* placeholder_r = this_prog.new_reg();
this_prog.mk_mov(this_ins, placeholder_r, r);
this_prog.mk_mov(this_ins, this_prog.lookup_reg(BPF_REG_1), placeholder_l);
this_prog.mk_mov(this_ins, this_prog.lookup_reg(BPF_REG_2), placeholder_r);
// Call function to concatenate.
this_prog.mk_call(this_ins, BPF_FUNC_str_concat, 2);
value* str = this_prog.new_reg();
this_prog.mk_mov(this_ins, str, this_prog.lookup_reg(BPF_REG_0));
result = str;
}
void
bpf_unparser::visit_ternary_expression (ternary_expression* e)
{
block *join_block = this_prog.new_block ();
value *r = this_prog.new_reg ();
if (!has_side_effects (e->truevalue))
{
block *else_block = this_prog.new_block ();
emit_mov (r, emit_expr (e->truevalue));
emit_cond (e->cond, join_block, else_block);
set_block (else_block);
emit_mov (r, emit_expr (e->falsevalue));
emit_jmp (join_block);
}
else if (!has_side_effects (e->falsevalue))
{
block *then_block = this_prog.new_block ();
emit_mov (r, emit_expr (e->falsevalue));
emit_cond (e->cond, join_block, then_block);
set_block (then_block);
emit_mov (r, emit_expr (e->truevalue));
emit_jmp (join_block);
}
else
{
block *then_block = this_prog.new_block ();
block *else_block = this_prog.new_block ();
emit_cond (e->cond, then_block, else_block);
set_block (then_block);
emit_mov (r, emit_expr (e->truevalue));
emit_jmp (join_block);
set_block (else_block);
emit_mov (r, emit_expr (e->falsevalue));
emit_jmp (join_block);
}
set_block (join_block);
result = r;
}
void
bpf_unparser::visit_assignment (assignment* e)
{
value *r = emit_expr (e->right);
if (e->op == "<<<")
; // XXX: handled by emit_store(), which checks for statistics lvalue
else if (e->op != "=")
{
int code;
if (e->op == "+=")
code = BPF_ADD;
else if (e->op == "-=")
code = BPF_SUB;
else if (e->op == "*=")
code = BPF_MUL;
else if (e->op == "/=")
code = BPF_DIV;
else if (e->op == "%=")
code = BPF_MOD;
else if (e->op == "<<=")
code = BPF_LSH;
else if (e->op == ">>=")
code = BPF_ARSH;
else if (e->op == "&=")
code = BPF_AND;
else if (e->op == "^=")
code = BPF_XOR;
else if (e->op == "|=")
code = BPF_OR;
else
throw SEMANTIC_ERROR (_("unhandled assignment operator"), e->tok);
value *l = emit_expr (e->left);
this_prog.mk_binary (this_ins, code, l, l, r);
r = l;
}
emit_store (e->left, r);
result = r;
}
value *
bpf_unparser::emit_context_var(bpf_context_vardecl *v)
{
// similar to visit_target_deref but the size/offset info
// is given in v->size/v->offset instead of an expression.
value *d = this_prog.new_reg();
if (v->size > 8)
{
// Compute a pointer but do not dereference. Needed
// for array context variables.
this_prog.mk_binary (this_ins, BPF_ADD, d, this_in_arg0,
this_prog.new_imm(v->offset));
return d;
}
value *frame = this_prog.lookup_reg(BPF_REG_10);
this_prog.mk_binary (this_ins, BPF_ADD, this_prog.lookup_reg(BPF_REG_3),
this_in_arg0, this_prog.new_imm(v->offset));
this_prog.mk_mov (this_ins, this_prog.lookup_reg(BPF_REG_2),
this_prog.new_imm(v->size));
this_prog.mk_binary (this_ins, BPF_ADD, this_prog.lookup_reg(BPF_REG_1),
frame, this_prog.new_imm(-v->size));
this_prog.use_tmp_space (v->size);
this_prog.mk_call (this_ins, BPF_FUNC_probe_read, 3);
int opc;
switch (v->size)
{
case 1: opc = BPF_B; break;
case 2: opc = BPF_H; break;
case 4: opc = BPF_W; break;
case 8: opc = BPF_DW; break;
default: assert(0);
}
this_prog.mk_ld (this_ins, opc, d, frame, -v->size);
if (v->is_signed && v->size < 8)
{
value *sh = this_prog.new_imm ((8 - v->size) * 8);
this_prog.mk_binary (this_ins, BPF_LSH, d, d, sh);
this_prog.mk_binary (this_ins, BPF_ARSH, d, d, sh);
}
return d;
}
void
bpf_unparser::visit_symbol(symbol *s)
{
vardecl *v = s->referent;
assert (v->arity < 1);
if (bpf_context_vardecl *c = dynamic_cast<bpf_context_vardecl*>(v))
{
result = emit_context_var(c);
return;
}
auto g = glob.globals.find (v);
if (g != glob.globals.end())
{
if (g->second.is_stat())
throw SEMANTIC_ERROR (_("unhandled statistics variable"), s->tok); // TODOXXX PR23476
value *frame = this_prog.lookup_reg(BPF_REG_10);
this_prog.mk_st(this_ins, BPF_W, frame, -4,
this_prog.new_imm(g->second.idx));
this_prog.use_tmp_space(4);
this_prog.load_map(this_ins, this_prog.lookup_reg(BPF_REG_1),
g->second.map_id);
this_prog.mk_binary(this_ins, BPF_ADD, this_prog.lookup_reg(BPF_REG_2),
frame, this_prog.new_imm(-4));
this_prog.mk_call(this_ins, BPF_FUNC_map_lookup_elem, 2);
value *r0 = this_prog.lookup_reg(BPF_REG_0);
value *i0 = this_prog.new_imm(0);
block *cont_block = this_prog.new_block();
block *exit_block = get_exit_block();
// Note that the kernel bpf verifier requires that we check that
// the pointer is non-null.
this_prog.mk_jcond(this_ins, EQ, r0, i0, exit_block, cont_block);
set_block(cont_block);
result = this_prog.new_reg();
switch (v->type)
{
case pe_long:
this_prog.mk_ld(this_ins, BPF_DW, result, r0, 0);
break;
case pe_string:
// Just return the address of the string within the map:
emit_mov(result, r0);
break;
default:
throw SEMANTIC_ERROR (_("unhandled global variable type"), s->tok);
}
return;
}
// ??? Maybe use result = this_locals.at (v);
// to throw std::out_of_range on lookup failure.
auto l = this_locals->find (v);
if (l != this_locals->end())
{
result = (*l).second;
return;
}
throw SEMANTIC_ERROR (_("unknown variable"), s->tok);
}
void
bpf_unparser::visit_arrayindex(arrayindex *e)
{
if (symbol *sym = dynamic_cast<symbol *>(e->base))
{
vardecl *v = sym->referent;
auto g = glob.globals.find(v);
if (g == glob.globals.end())
throw SEMANTIC_ERROR(_("unknown array variable"), v->tok);
if (g->second.is_stat())
throw SEMANTIC_ERROR (_("unhandled statistics variable"), v->tok); // TODOXXX PR23476
unsigned element = v->arity;
int key_ofs = 0;
// iterate over the elements
do {
--element;
value *idx = emit_expr(e->indexes[element]);
switch (v->index_types[element])
{
case pe_long:
// Store the long on the stack and pass its address:
key_ofs -= 8;
emit_long_arg(this_prog.lookup_reg(BPF_REG_2), key_ofs, idx);
break;
case pe_string:
// Zero-pad and copy the string to the stack and pass its address:
key_ofs -= BPF_MAXSTRINGLEN;
emit_str_arg(this_prog.lookup_reg(BPF_REG_2), key_ofs, idx);
break;
default:
throw SEMANTIC_ERROR(_("unhandled index type"), e->tok);
}
} while (element);
this_prog.use_tmp_space(-key_ofs);
this_prog.load_map(this_ins, this_prog.lookup_reg(BPF_REG_1),
g->second.map_id);
value *r0 = this_prog.lookup_reg(BPF_REG_0);
value *i0 = this_prog.new_imm(0);
block *t_block = this_prog.new_block();
block *f_block = this_prog.new_block();
block *join_block = this_prog.new_block();
result = this_prog.new_reg();
this_prog.mk_call(this_ins, BPF_FUNC_map_lookup_elem, 2);
this_prog.mk_jcond(this_ins, EQ, r0, i0, t_block, f_block);
// Key is not in the array. Evaluate to 0.
set_block(t_block);
emit_mov(result, i0);
emit_jmp(join_block);
// Key is in the array. Get value from stack.
set_block(f_block);
if (v->type == pe_long)
this_prog.mk_ld(this_ins, BPF_DW, result, r0, 0);
else
emit_mov(result, r0);
emit_jmp(join_block);
set_block(join_block);
}
else
throw SEMANTIC_ERROR(_("unhandled arrayindex expression"), e->tok);
}
void
bpf_unparser::visit_array_in(array_in* e)
{
arrayindex *a = e->operand;
if (symbol *s = dynamic_cast<symbol *>(a->base))
{
vardecl *v = s->referent;
auto g = glob.globals.find (v);
if (g == glob.globals.end())
throw SEMANTIC_ERROR(_("unknown variable"), v->tok);
unsigned element = v->arity;
int key_ofs = 0;
// iterate over the elements
do {
--element;
value *idx = emit_expr(a->indexes[element]);
switch(v->index_types[element])
{
case pe_long:
// Store the long on the stack and pass its address:
key_ofs -= 8;
emit_long_arg(this_prog.lookup_reg(BPF_REG_2), key_ofs, idx);
break;
case pe_string:
// Zero-pad and copy the string to the stack and pass its address:
key_ofs -= BPF_MAXSTRINGLEN;
emit_str_arg(this_prog.lookup_reg(BPF_REG_2), key_ofs, idx);
break;
default:
throw SEMANTIC_ERROR(_("unhandled index type"), e->tok);
}
} while (element);
this_prog.use_tmp_space(-key_ofs);
// TODO: Handle map_id < 0 for pe_stats or assert otherwise.
if (g->second.map_id < 0)
throw SEMANTIC_ERROR (_("unsupported array-in operation on statistics aggregate"), s->tok); // TODOXXX PR23476
this_prog.load_map(this_ins, this_prog.lookup_reg(BPF_REG_1),
g->second.map_id);
this_prog.mk_call(this_ins, BPF_FUNC_map_lookup_elem, 2);
value *r0 = this_prog.lookup_reg(BPF_REG_0);
value *i0 = this_prog.new_imm(0);
value *i1 = this_prog.new_imm(1);
value *d = this_prog.new_reg();
block *b0 = this_prog.new_block();
block *b1 = this_prog.new_block();
block *cont_block = this_prog.new_block();
this_prog.mk_jcond(this_ins, EQ, r0, i0, b0, b1);
// d = 0
set_block(b0);
this_prog.mk_mov(this_ins, d, i0);
b0->fallthru = new edge(b0, cont_block);
// d = 1
set_block(b1);
this_prog.mk_mov(this_ins, d, i1);
b1->fallthru = new edge(b1, cont_block);
set_block(cont_block);
result = d;
return;
}
/// ??? hist_op
throw SEMANTIC_ERROR(_("unhandled operand type"), a->base->tok);
}
void
bpf_unparser::visit_target_deref (target_deref* e)
{
// ??? For some hosts, including x86_64, it works to read userspace
// and kernelspace with the same function. For others, like s390x,
// this only works to read kernelspace.
value *src = emit_expr (e->addr);
value *frame = this_prog.lookup_reg (BPF_REG_10);
this_prog.mk_mov (this_ins, this_prog.lookup_reg(BPF_REG_3), src);
this_prog.mk_mov (this_ins, this_prog.lookup_reg(BPF_REG_2),
this_prog.new_imm (e->size));
this_prog.mk_binary (this_ins, BPF_ADD, this_prog.lookup_reg(BPF_REG_1),
frame, this_prog.new_imm (-(int64_t)e->size));
this_prog.use_tmp_space(e->size);
this_prog.mk_call(this_ins, BPF_FUNC_probe_read, 3);
value *d = this_prog.new_reg ();
int opc;
switch (e->size)
{
case 1: opc = BPF_B; break;
case 2: opc = BPF_H; break;
case 4: opc = BPF_W; break;
case 8: opc = BPF_DW; break;
default:
throw SEMANTIC_ERROR(_("unhandled deref size"), e->tok);
}
this_prog.mk_ld (this_ins, opc, d, frame, -e->size);
if (e->signed_p && e->size < 8)
{
value *sh = this_prog.new_imm ((8 - e->size) * 8);
this_prog.mk_binary (this_ins, BPF_LSH, d, d, sh);
this_prog.mk_binary (this_ins, BPF_ARSH, d, d, sh);
}
result = d;
}
void
bpf_unparser::visit_target_register (target_register* e)
{
// ??? Should not hard-code register size.
int size = sizeof(void *);
// ??? Should not hard-code register offsets in pr_regs.
int ofs = 0;
switch (e->regno)
{
#if defined(__i386__)
case 0: ofs = offsetof(pt_regs, eax); break;
case 1: ofs = offsetof(pt_regs, ecx); break;
case 2: ofs = offsetof(pt_regs, edx); break;
case 3: ofs = offsetof(pt_regs, ebx); break;
case 4: ofs = offsetof(pt_regs, esp); break;
case 5: ofs = offsetof(pt_regs, ebp); break;
case 6: ofs = offsetof(pt_regs, esi); break;
case 7: ofs = offsetof(pt_regs, edi); break;
case 8: ofs = offsetof(pt_regs, eip); break;
#elif defined(__x86_64__)
case 0: ofs = offsetof(pt_regs, rax); break;
case 1: ofs = offsetof(pt_regs, rdx); break;
case 2: ofs = offsetof(pt_regs, rcx); break;
case 3: ofs = offsetof(pt_regs, rbx); break;
case 4: ofs = offsetof(pt_regs, rsi); break;
case 5: ofs = offsetof(pt_regs, rdi); break;
case 6: ofs = offsetof(pt_regs, rbp); break;
case 7: ofs = offsetof(pt_regs, rsp); break;
case 8: ofs = offsetof(pt_regs, r8); break;
case 9: ofs = offsetof(pt_regs, r9); break;
case 10: ofs = offsetof(pt_regs, r10); break;
case 11: ofs = offsetof(pt_regs, r11); break;
case 12: ofs = offsetof(pt_regs, r12); break;
case 13: ofs = offsetof(pt_regs, r13); break;
case 14: ofs = offsetof(pt_regs, r14); break;
case 15: ofs = offsetof(pt_regs, r15); break;
case 16: ofs = offsetof(pt_regs, rip); break;
#elif defined(__arm__)
case 0: ofs = offsetof(pt_regs, uregs[0]); break;
case 1: ofs = offsetof(pt_regs, uregs[1]); break;
case 2: ofs = offsetof(pt_regs, uregs[2]); break;
case 3: ofs = offsetof(pt_regs, uregs[3]); break;
case 4: ofs = offsetof(pt_regs, uregs[4]); break;
case 5: ofs = offsetof(pt_regs, uregs[5]); break;
case 6: ofs = offsetof(pt_regs, uregs[6]); break;
case 7: ofs = offsetof(pt_regs, uregs[7]); break;
case 8: ofs = offsetof(pt_regs, uregs[8]); break;
case 9: ofs = offsetof(pt_regs, uregs[9]); break;
case 10: ofs = offsetof(pt_regs, uregs[10]); break;
case 11: ofs = offsetof(pt_regs, uregs[11]); break;
case 12: ofs = offsetof(pt_regs, uregs[12]); break;
case 13: ofs = offsetof(pt_regs, uregs[13]); break;
case 14: ofs = offsetof(pt_regs, uregs[14]); break;
case 15: ofs = offsetof(pt_regs, uregs[15]); break;
#elif defined(__aarch64__)
case 0: ofs = offsetof(user_pt_regs, regs[0]); break;
case 1: ofs = offsetof(user_pt_regs, regs[1]); break;
case 2: ofs = offsetof(user_pt_regs, regs[2]); break;
case 3: ofs = offsetof(user_pt_regs, regs[3]); break;
case 4: ofs = offsetof(user_pt_regs, regs[4]); break;
case 5: ofs = offsetof(user_pt_regs, regs[5]); break;
case 6: ofs = offsetof(user_pt_regs, regs[6]); break;
case 7: ofs = offsetof(user_pt_regs, regs[7]); break;
case 8: ofs = offsetof(user_pt_regs, regs[8]); break;
case 9: ofs = offsetof(user_pt_regs, regs[9]); break;
case 10: ofs = offsetof(user_pt_regs, regs[10]); break;
case 11: ofs = offsetof(user_pt_regs, regs[11]); break;
case 12: ofs = offsetof(user_pt_regs, regs[12]); break;
case 13: ofs = offsetof(user_pt_regs, regs[13]); break;
case 14: ofs = offsetof(user_pt_regs, regs[14]); break;
case 15: ofs = offsetof(user_pt_regs, regs[15]); break;
case 16: ofs = offsetof(user_pt_regs, regs[16]); break;
case 17: ofs = offsetof(user_pt_regs, regs[17]); break;
case 18: ofs = offsetof(user_pt_regs, regs[18]); break;
case 19: ofs = offsetof(user_pt_regs, regs[19]); break;
case 20: ofs = offsetof(user_pt_regs, regs[20]); break;
case 21: ofs = offsetof(user_pt_regs, regs[21]); break;
case 22: ofs = offsetof(user_pt_regs, regs[22]); break;
case 23: ofs = offsetof(user_pt_regs, regs[23]); break;
case 24: ofs = offsetof(user_pt_regs, regs[24]); break;
case 25: ofs = offsetof(user_pt_regs, regs[25]); break;
case 26: ofs = offsetof(user_pt_regs, regs[26]); break;
case 27: ofs = offsetof(user_pt_regs, regs[27]); break;
case 28: ofs = offsetof(user_pt_regs, regs[28]); break;
case 29: ofs = offsetof(user_pt_regs, regs[29]); break;
case 30: ofs = offsetof(user_pt_regs, regs[30]); break;
case 31: ofs = offsetof(user_pt_regs, sp); break;
#elif defined(__powerpc__)
case 0: ofs = offsetof(pt_regs, gpr[0]); break;
case 1: ofs = offsetof(pt_regs, gpr[1]); break;
case 2: ofs = offsetof(pt_regs, gpr[2]); break;
case 3: ofs = offsetof(pt_regs, gpr[3]); break;
case 4: ofs = offsetof(pt_regs, gpr[4]); break;
case 5: ofs = offsetof(pt_regs, gpr[5]); break;
case 6: ofs = offsetof(pt_regs, gpr[6]); break;
case 7: ofs = offsetof(pt_regs, gpr[7]); break;
case 8: ofs = offsetof(pt_regs, gpr[8]); break;
case 9: ofs = offsetof(pt_regs, gpr[9]); break;
case 10: ofs = offsetof(pt_regs, gpr[10]); break;
case 11: ofs = offsetof(pt_regs, gpr[11]); break;
case 12: ofs = offsetof(pt_regs, gpr[12]); break;
case 13: ofs = offsetof(pt_regs, gpr[13]); break;
case 14: ofs = offsetof(pt_regs, gpr[14]); break;
case 15: ofs = offsetof(pt_regs, gpr[15]); break;
case 16: ofs = offsetof(pt_regs, gpr[16]); break;
case 17: ofs = offsetof(pt_regs, gpr[17]); break;
case 18: ofs = offsetof(pt_regs, gpr[18]); break;
case 19: ofs = offsetof(pt_regs, gpr[19]); break;
case 20: ofs = offsetof(pt_regs, gpr[20]); break;
case 21: ofs = offsetof(pt_regs, gpr[21]); break;
case 22: ofs = offsetof(pt_regs, gpr[22]); break;
case 23: ofs = offsetof(pt_regs, gpr[23]); break;
case 24: ofs = offsetof(pt_regs, gpr[24]); break;
case 25: ofs = offsetof(pt_regs, gpr[25]); break;
case 26: ofs = offsetof(pt_regs, gpr[26]); break;
case 27: ofs = offsetof(pt_regs, gpr[27]); break;
case 28: ofs = offsetof(pt_regs, gpr[28]); break;
case 29: ofs = offsetof(pt_regs, gpr[29]); break;
case 30: ofs = offsetof(pt_regs, gpr[30]); break;
case 31: ofs = offsetof(pt_regs, gpr[31]); break;
case 64: ofs = offsetof(pt_regs, ccr); break;
case 66: ofs = offsetof(pt_regs, msr); break;
case 101: ofs = offsetof(pt_regs, xer); break;
case 108: ofs = offsetof(pt_regs, link); break;
case 109: ofs = offsetof(pt_regs, ctr); break;
case 118: ofs = offsetof(pt_regs, dsisr); break;
case 119: ofs = offsetof(pt_regs, dar); break;
# if !defined(__powerpc64__)
case 100: ofs = offsetof(pt_regs, mq); break;
# endif
// ??? NIP is not assigned to a dwarf register number at all.
#elif defined(__s390__)
case 0: ofs = offsetof(user_regs_struct, gprs[0]); break;
case 1: ofs = offsetof(user_regs_struct, gprs[1]); break;
case 2: ofs = offsetof(user_regs_struct, gprs[2]); break;
case 3: ofs = offsetof(user_regs_struct, gprs[3]); break;
case 4: ofs = offsetof(user_regs_struct, gprs[4]); break;
case 5: ofs = offsetof(user_regs_struct, gprs[5]); break;
case 6: ofs = offsetof(user_regs_struct, gprs[6]); break;
case 7: ofs = offsetof(user_regs_struct, gprs[7]); break;
case 8: ofs = offsetof(user_regs_struct, gprs[8]); break;
case 9: ofs = offsetof(user_regs_struct, gprs[9]); break;
case 10: ofs = offsetof(user_regs_struct, gprs[10]); break;
case 11: ofs = offsetof(user_regs_struct, gprs[11]); break;
case 12: ofs = offsetof(user_regs_struct, gprs[12]); break;
case 13: ofs = offsetof(user_regs_struct, gprs[13]); break;
case 14: ofs = offsetof(user_regs_struct, gprs[14]); break;
case 15: ofs = offsetof(user_regs_struct, gprs[15]); break;
// Note that the FPRs are not numbered sequentially
case 16: ofs = offsetof(user_regs_struct, fp_regs.fprs[0]); break;
case 17: ofs = offsetof(user_regs_struct, fp_regs.fprs[2]); break;
case 18: ofs = offsetof(user_regs_struct, fp_regs.fprs[4]); break;
case 19: ofs = offsetof(user_regs_struct, fp_regs.fprs[6]); break;
case 20: ofs = offsetof(user_regs_struct, fp_regs.fprs[1]); break;
case 21: ofs = offsetof(user_regs_struct, fp_regs.fprs[3]); break;
case 22: ofs = offsetof(user_regs_struct, fp_regs.fprs[5]); break;
case 23: ofs = offsetof(user_regs_struct, fp_regs.fprs[7]); break;
case 24: ofs = offsetof(user_regs_struct, fp_regs.fprs[8]); break;
case 25: ofs = offsetof(user_regs_struct, fp_regs.fprs[10]); break;
case 26: ofs = offsetof(user_regs_struct, fp_regs.fprs[12]); break;
case 27: ofs = offsetof(user_regs_struct, fp_regs.fprs[14]); break;
case 28: ofs = offsetof(user_regs_struct, fp_regs.fprs[9]); break;
case 29: ofs = offsetof(user_regs_struct, fp_regs.fprs[11]); break;
case 30: ofs = offsetof(user_regs_struct, fp_regs.fprs[13]); break;
case 31: ofs = offsetof(user_regs_struct, fp_regs.fprs[15]); break;
// ??? Omitting CTRs (not in user_regs_struct)
// ??? Omitting ACRs (lazy, and unlikely to appear in unwind)
case 64: ofs = offsetof(user_regs_struct, psw.mask); break;
case 65: ofs = offsetof(user_regs_struct, psw.addr); break;
#endif
default:
throw SEMANTIC_ERROR(_("unhandled register number"), e->tok);
}
value *frame = this_prog.lookup_reg (BPF_REG_10);
this_prog.mk_binary (this_ins, BPF_ADD, this_prog.lookup_reg(BPF_REG_3),
this_in_arg0, this_prog.new_imm (ofs));
this_prog.mk_mov (this_ins, this_prog.lookup_reg(BPF_REG_2),
this_prog.new_imm (size));
this_prog.mk_binary (this_ins, BPF_ADD, this_prog.lookup_reg(BPF_REG_1),
frame, this_prog.new_imm (-size));
this_prog.use_tmp_space(size);
this_prog.mk_call(this_ins, BPF_FUNC_probe_read, 3);
value *d = this_prog.new_reg ();
int opc;
switch (size)
{
case 4: opc = BPF_W; break;
case 8: opc = BPF_DW; break;
default:
throw SEMANTIC_ERROR(_("unhandled register size"), e->tok);
}
this_prog.mk_ld (this_ins, opc, d, frame, -size);
result = d;
}
// Emit unrolled-loop code to write string literal from src to
// dest[+ofs] in 4-byte chunks, with optional zero-padding up to
// BPF_MAXSTRINGLEN.
//
// ??? Could use 8-byte chunks if we're starved for instruction count.
// ??? Endianness of the target comes into play here.
value *
emit_simple_literal_str(program &this_prog, insn_inserter &this_ins,
value *dest, int ofs, const std::string &src, bool zero_pad)
{
#ifdef DEBUG_CODEGEN
this_ins.notes.push("str");
#endif
size_t str_bytes = src.size() + 1;
size_t str_words = (str_bytes + 3) / 4;
for (unsigned i = 0; i < str_words; ++i)
{
uint32_t word = 0;
for (unsigned j = 0; j < 4; ++j)
if (i * 4 + j < str_bytes - 1)
{
// ??? assuming little-endian target
//
// Must cast each signed char in src to unsigned char first
// in order to avoid the implicit sign extension resulting
// from the uint32_t cast.
word |= ((uint32_t)(unsigned char)src[i * 4 + j]) << (j * 8);
}
this_prog.mk_st(this_ins, BPF_W,
dest, (int32_t)i * 4 + ofs,
this_prog.new_imm(word));
}
// XXX: bpf_map_update_elem and bpf_map_lookup_elem will always copy
// exactly BPF_MAXSTRINGLEN bytes, which can cause problems with
// garbage data beyond the end of the string, particularly for map
// keys. The silliest way to solve this is by padding every string
// constant to BPF_MAXSTRINGLEN bytes, but the stack isn't really
// big enough for this to work with practical programs.
//
// So instead we have this optional code to pad the string, and
// enable the option only when copying a string to a map key.
if (zero_pad)
{
for (unsigned i = str_words; i < BPF_MAXSTRINGLEN / 4; i++)
{
this_prog.mk_st(this_ins, BPF_W,
dest, (int32_t)i * 4 + ofs,
this_prog.new_imm(0));
}
}
value *out = this_prog.new_reg();
this_prog.mk_binary(this_ins, BPF_ADD, out,
dest, this_prog.new_imm(ofs));
#ifdef DEBUG_CODEGEN
this_ins.notes.pop(); // str
#endif
return out;
}
// Emit unrolled-loop code to write string value from src to
// dest[+ofs] in 4-byte chunks, with optional zero-padding up to
// BPF_MAXSTRINGLEN.
//
// TODO (PR23860): This code does not work when the source and target
// regions overlap.
//
// ??? Could use 8-byte chunks if we're starved for instruction count.
// ??? Endianness of the target may come into play here.
value *
bpf_unparser::emit_string_copy(value *dest, int ofs, value *src, bool zero_pad)
{
if (src->is_str())
{
/* If src is a string literal, its exact length is known and
we can emit simpler, unconditional string copying code. */
std::string str = src->str();
return emit_simple_literal_str(this_prog, this_ins,
dest, ofs, str, zero_pad);
}
#ifdef DEBUG_CODEGEN
this_ins.notes.push(zero_pad ? "strcpy_zero_pad" : "strcpy");
#endif
size_t str_bytes = BPF_MAXSTRINGLEN;
size_t str_words = (str_bytes + 3) / 4;
value *out = this_prog.new_reg(); // -- where to store the final string addr
block *return_block = this_prog.new_block();
// XXX: It is sometimes possible to receive src == NULL.
// trace_printk() did not care about being passed such values, but
// applying strcpy() to NULL will (understandably) fail the
// verifier. Therefore, we need to check for this possibility first:
block *null_copy_block = this_prog.new_block();
block *normal_block = this_prog.new_block();
this_prog.mk_jcond(this_ins, EQ, src, this_prog.new_imm(0),
null_copy_block, normal_block);
// Only call emit_simple_literal_str() if we can't reuse the zero-pad code:
if (!zero_pad)
{
set_block(null_copy_block);
value *empty_str = emit_simple_literal_str (this_prog, this_ins,
dest, ofs, "", false);
emit_mov(out, empty_str);
emit_jmp(return_block);
}
set_block(normal_block);
/* block_A[i] copies src[4*i] to dest[4*i+ofs];
block_B[i] copies 0 to dest[4*i+ofs], produced only if zero_pad is true. */
std::vector<block *> block_A, block_B;
block_A.push_back(this_ins.get_block());
if (zero_pad) block_B.push_back(null_copy_block);
for (unsigned i = 0; i < str_words; ++i)
{
block *next_block;
if (i < str_words - 1)
{
/* Create block_A[i+1], block_B[i+1]: */
block_A.push_back(this_prog.new_block());
if (zero_pad) block_B.push_back(this_prog.new_block());
next_block = block_A[i+1];
}
else
{
next_block = return_block;
}
set_block(block_A[i]);
value *word = this_prog.new_reg();
this_prog.mk_ld(this_ins, BPF_W, word,
src, (int32_t)i * 4);
this_prog.mk_st(this_ins, BPF_W,
dest, (int32_t)i * 4 + ofs,
word);
/* Finish unconditionally after copying BPF_MAXSTRINGLEN bytes: */
if (i == str_words - 1)
{
emit_jmp(next_block);
continue;
}
// Determining whether a word contains a NUL byte is a neat bit-fiddling puzzle.
// Kudos go to Valgrind and Memcheck for showing the way, along the lines of:
//
// b1 := word & 0xff; nz1 := (-b1)|b1; all_nz = nz1
// b2 := (word >> 8) & 0xff; nz2 := (-b2)|b2; all_nz = all_nz & nz2
// b3 := (word >> 16) & 0xff; nz3 := (-b3)|b3; all_nz = all_nz & nz3
// b4 := (word >> 24) & 0xff; nz4 := (-b4)|b4; all_nz = all_nz & nz4
// all_nz := nz1 & nz2 & nz3 & nz4
//
// Here, nzX is 0 iff bX is NUL, all_nz is 0 iff word contains a NUL byte.
value *all_nz = this_prog.new_reg();
value *bN = this_prog.new_reg();
value *nZ = this_prog.new_reg();
for (unsigned j = 0; j < 4; j++)
{
unsigned shift = 8*j;
if (shift != 0)
{
this_prog.mk_binary(this_ins, BPF_RSH, bN, word, this_prog.new_imm(shift));
}
else
{
emit_mov(bN, word);
}
this_prog.mk_binary(this_ins, BPF_AND, bN, bN, this_prog.new_imm(0xff));
this_prog.mk_unary(this_ins, BPF_NEG, nZ, bN);
this_prog.mk_binary(this_ins, BPF_OR, nZ, nZ, bN);
if (j == 0)
{
emit_mov(all_nz, nZ);
}
else
{
this_prog.mk_binary(this_ins, BPF_AND, all_nz, all_nz, nZ);
}
}
this_prog.mk_jcond(this_ins, EQ, all_nz, this_prog.new_imm(0),
zero_pad ? block_B[i+1] : return_block, next_block);
}
// XXX: Zero-padding is only used under specific circumstances;
// see the corresponding comment in emit_simple_literal_str().
if (zero_pad)
{
for (unsigned i = 0; i < str_words; ++i)
{
set_block(block_B[i]);
this_prog.mk_st(this_ins, BPF_W,
dest, (int32_t)i * 4 + ofs,
this_prog.new_imm(0));
emit_jmp(i < str_words - 1 ? block_B[i+1] : return_block);
}
}
set_block(return_block);
this_prog.mk_binary(this_ins, BPF_ADD, out,
dest, this_prog.new_imm(ofs));
#ifdef DEBUG_CODEGEN
this_ins.notes.pop(); // strcpy
#endif
return out;
}
// Used for passing long arguments on the stack where an address is
// expected. Store val in a stack slot at offset ofs and store the
// stack address of val in arg.
void
bpf_unparser::emit_long_arg(value *arg, int ofs, value *val)
{
value *frame = this_prog.lookup_reg(BPF_REG_10);
this_prog.mk_st(this_ins, BPF_DW, frame, ofs, val);
this_prog.mk_binary(this_ins, BPF_ADD, arg,
frame, this_prog.new_imm(ofs));
}
// Used for passing string arguments on the stack where an address is
// expected. Zero-pad and copy str to the stack at offset ofs and
// store the stack address of str in arg. Zero-padding is required
// since functions such as map_update_elem will expect a fixed-length
// value of BPF_MAXSTRINGLEN for string map keys.
void
bpf_unparser::emit_str_arg(value *arg, int ofs, value *str)
{
value *frame = this_prog.lookup_reg(BPF_REG_10);
value *out = emit_string_copy(frame, ofs, str, true /* zero pad */);
emit_mov(arg, out);
}
value *
bpf_unparser::emit_functioncall (functiondecl *f, const std::vector<value *>& args)
{
// Create a new map for the function's local variables.
locals_map *locals = new_locals(f->locals);
// Install locals in the map.
unsigned n = args.size();
for (unsigned i = 0; i < n; ++i)
{
const locals_map::value_type v (f->formal_args[i], args[i]);
auto ok = locals->insert (v);
assert (ok.second);
}
locals_map *old_locals = this_locals;
this_locals = locals;
block *join_block = this_prog.new_block ();
value *retval = this_prog.new_reg ();
func_calls.push_back (f);
func_return.push_back (join_block);
func_return_val.push_back (retval);
emit_stmt (f->body);
func_return_val.pop_back ();
func_return.pop_back ();
func_calls.pop_back ();
if (in_block ())
emit_jmp (join_block);
set_block (join_block);
this_locals = old_locals;
delete locals;
return retval;
}
void
bpf_unparser::visit_functioncall (functioncall *e)
{
// ??? Function overloading isn't handled.
if (e->referents.size () != 1)
throw SEMANTIC_ERROR (_("unhandled function overloading"), e->tok);
functiondecl *f = e->referents[0];
// ??? For now, always inline the function call.
for (auto i = func_calls.begin(); i != func_calls.end(); ++i)
if (f == *i)
throw SEMANTIC_ERROR (_("unhandled function recursion"), e->tok);
// XXX: Should have been checked in earlier pass.
assert (e->args.size () == f->formal_args.size ());
// Evaluate and collect the function arguments.
std::vector<value *> args;
for (unsigned n = e->args.size (), i = 0; i < n; ++i)
{
value *r = this_prog.new_reg ();
emit_mov (r, emit_expr (e->args[i]));
args.push_back(r);
}
result = emit_functioncall(f, args);
}
int
globals::intern_string (std::string& str)
{
if (interned_str_map.count(str) > 0)
return interned_str_map[str];
int this_idx = interned_strings.size();
interned_strings.push_back(str);
interned_str_map[str] = this_idx;
return this_idx;
}
// Generates perf_event_output transport message glue code.
//
// XXX: Based on the interface of perf_event_output, this_in_arg0 must
// be a pt_regs * struct. In fact, the BPF program apparently has to
// pass the context given to the program as arg 0, regardless of the
// type. For the sake of user-space helpers (e.g. begin/end) we just
// pass NULL when this_in_arg0 is not available. Should not happen
// in-kernel where BPF programs apparently always have a context, but
// it's worth noting the assumptions here.
//
// TODO: We need to specify the transport message format more
// compactly. Thus far, everything is written as double-words to avoid
// getting 'misaligned stack access' errors from the verifier.
//
// TODO: We could extend this interface to allow passing multiple
// values in one transport message, e.g. a sequence of pe_long.
void
bpf_unparser::emit_transport_msg (globals::perf_event_type msg,
value *arg, exp_type format_type)
{
// Harmonize the information in arg, format_type, and msg:
if (arg != NULL)
{
if (format_type == pe_unknown)
format_type = arg->format_type;
assert(format_type == arg->format_type || arg->format_type == pe_unknown);
if (arg->is_str() && arg->is_format() && format_type == pe_unknown)
format_type = pe_string;
// XXX: Finally, pick format_type based on msg (inferred from format string):
if (msg == globals::STP_PRINTF_ARG_LONG && format_type == pe_unknown)
format_type = pe_long;
else if (msg == globals::STP_PRINTF_ARG_STR && format_type == pe_unknown)
format_type = pe_string;
}
unsigned arg_size = 0;
if (arg != NULL)
switch (format_type)
{
case pe_long:
arg_size = 8;
break;
case pe_string:
if (arg->is_str() && arg->is_format())
arg_size = sizeof(BPF_TRANSPORT_ARG); // pass index of interned str
else
{
arg_size = BPF_MAXSTRINGLEN;
// XXX hack for PR25169: Unfortunately, we may conflict with prior
// stack allocations in embedded assembly code which were done
// before seeing this transport message. So we need to allocate
// below max_tmp_space. Could switch to a preallocation scheme that
// scans the code for string operations.
arg_size += this_prog.max_tmp_space;
}
break;
default:
assert(false); // XXX: Should be caught earlier.
}
// XXX: The following force-aligns all elements to double word boundary.
// Could probably switch to single-word alignment with more careful design.
if (arg_size % 8 != 0)
arg_size += 8 - arg_size % 8;
int arg_ofs = -arg_size;
int msg_ofs = arg_ofs-sizeof(BPF_TRANSPORT_VAL);
if (msg_ofs % 8 != 0)
msg_ofs -= (8 - (-msg_ofs) % 8);
this_prog.use_tmp_space(-msg_ofs);
value *frame = this_prog.lookup_reg(BPF_REG_10);
// store arg
if (arg != NULL)
switch (format_type)
{
case pe_long:
this_prog.mk_st(this_ins, BPF_DW, frame, arg_ofs, arg);
break;
case pe_string:
if (arg->is_str() && arg->is_format())
{
int idx = glob.intern_string(arg->str_val);
this_prog.mk_st(this_ins, BPF_DW, frame, arg_ofs,
this_prog.new_imm(idx));
}
else
emit_string_copy(frame, arg_ofs, arg, false /* no zero pad */);
break;
default:
assert(false); // XXX: Should be caught earlier.
}
// double word -- XXX verifier forces aligned access
this_prog.mk_st(this_ins, BPF_DW, frame, msg_ofs, this_prog.new_imm(msg));
value *ctx = this_in_arg0 == NULL ? this_prog.new_imm(0) : this_in_arg0;
emit_mov(this_prog.lookup_reg(BPF_REG_1), ctx); // ctx
this_prog.load_map(this_ins, this_prog.lookup_reg(BPF_REG_2),
globals::perf_event_map_idx);
emit_mov(this_prog.lookup_reg(BPF_REG_3),
this_prog.new_imm(BPF_F_CURRENT_CPU)); // flags
this_prog.mk_binary(this_ins, BPF_ADD,
this_prog.lookup_reg(BPF_REG_4),
frame, this_prog.new_imm(msg_ofs));
emit_mov(this_prog.lookup_reg(BPF_REG_5), this_prog.new_imm(-msg_ofs));
this_prog.mk_call(this_ins, BPF_FUNC_perf_event_output, 5);
}
globals::perf_event_type
printf_arg_type (value *arg, const print_format::format_component &c)
{
switch (arg->format_type)
{
case pe_long:
return globals::STP_PRINTF_ARG_LONG;
case pe_string:
return globals::STP_PRINTF_ARG_STR;
case pe_unknown:
// XXX: Could be a lot stricter and force
// arg->format_type and c.type to match.
switch (c.type) {
case print_format::conv_pointer:
case print_format::conv_number:
case print_format::conv_char:
case print_format::conv_memory:
case print_format::conv_memory_hex:
case print_format::conv_binary:
return globals::STP_PRINTF_ARG_LONG;
case print_format::conv_string:
return globals::STP_PRINTF_ARG_STR;
default:
assert(false); // XXX
}
default:
assert(false); // XXX: Should be caught earlier.
}
}
value *
bpf_unparser::emit_print_format (const std::string& format,
const std::vector<value *>& actual,
bool print_to_stream,
const token *tok)
{
size_t nargs = actual.size();
if (!print_to_stream)
{
// PR24528: Userspace-only feature.
if (this_prog.target == target_kernel_bpf)
throw SEMANTIC_ERROR(_("unsupported sprintf in bpf kernel probe"), tok);
// TODO: sprintf() has an additional constraint on arguments due
// to passing them in a very small number of registers.
if (actual.size() > BPF_MAXSPRINTFARGS)
throw SEMANTIC_ERROR(_NF("additional argument to sprintf",
"too many arguments to sprintf (%zu)",
actual.size(), actual.size()), tok);
// Emit an ordinary function call to sprintf.
size_t format_bytes = format.size() + 1;
this_prog.mk_mov(this_ins, this_prog.lookup_reg(BPF_REG_1),
this_prog.new_str(format, true /*format_str*/));
emit_mov(this_prog.lookup_reg(BPF_REG_2), this_prog.new_imm(format_bytes));
for (size_t i = 0; i < nargs; ++i)
emit_mov(this_prog.lookup_reg(BPF_REG_3 + i), actual[i]);
this_prog.mk_call(this_ins, BPF_FUNC_sprintf, nargs + 2);
return this_prog.lookup_reg(BPF_REG_0);
}
// Filter components to include only non-literal printf arguments:
std::vector<print_format::format_component> all_components =
print_format::string_to_components(format);
// XXX: Could pass print_format * to avoid extra parse, except for embedded-code.
std::vector<print_format::format_component> components;
for (auto &c : all_components) {
if (c.type != print_format::conv_literal)
components.push_back(c);
}
if (components.size() != nargs)
{
if (tok != NULL)
throw SEMANTIC_ERROR(_F("format string expected %zu args, got %zu",
components.size(), nargs), tok);
else
assert(false); // XXX: Should be caught earlier.
}
emit_transport_msg(globals::STP_PRINTF_START, this_prog.new_imm(nargs), pe_long);
emit_transport_msg(globals::STP_PRINTF_FORMAT, this_prog.new_str(format, true /*format_str*/));
for (size_t i = 0; i < nargs; ++i)
emit_transport_msg(printf_arg_type(actual[i], components[i]), actual[i]);
emit_transport_msg(globals::STP_PRINTF_END);
return NULL;
}
void
bpf_unparser::visit_print_format (print_format *e)
{
if (e->hist)
throw SEMANTIC_ERROR (_("unhandled histogram print"), e->tok);
size_t nargs = e->args.size();
size_t i;
if (nargs > BPF_MAXPRINTFARGS)
throw SEMANTIC_ERROR(_NF("additional argument to print",
"too many arguments to print (%zu)",
e->args.size(), e->args.size()), e->tok);
std::vector<value *> actual;
for (i = 0; i < nargs; ++i)
{
value *arg = emit_expr(e->args[i]);
arg->format_type = e->args[i]->type;
actual.push_back(arg);
}
for (size_t i = 0; i < nargs; ++i)
if (actual[i]->format_type == pe_stats)
throw SEMANTIC_ERROR (_("cannot print a raw stats object"), e->args[i]->tok);
else if (actual[i]->format_type != pe_long && actual[i]->format_type != pe_string)
throw SEMANTIC_ERROR (_("cannot print unknown expression type"), e->args[i]->tok);
std::string format;
if (e->print_with_format)
{
// If this is a long string with no actual arguments, it will be
// interned in the format string table as usual.
interned_string fstr = e->raw_components;
format += translate_escapes(fstr, e->tok);
}
else
{
// Synthesize a print-format string if the user didn't
// provide one; the synthetic string simply contains one
// directive for each argument.
std::string delim;
if (e->print_with_delim)
{
interned_string dstr = e->delimiter;
for (interned_string::const_iterator j = dstr.begin();
j != dstr.end(); ++j)
{
if (*j == '%')
delim += '%';
delim += *j;
}
}
for (i = 0; i < nargs; ++i)
{
if (i > 0 && e->print_with_delim)
format += delim;
switch (e->args[i]->type)
{
default:
case pe_unknown:
throw SEMANTIC_ERROR(_("cannot print unknown expression type"),
e->args[i]->tok);
case pe_stats:
throw SEMANTIC_ERROR(_("cannot print a raw stats object"),
e->args[i]->tok);
case pe_long:
format += "%ld";
break;
case pe_string:
format += "%s";
break;
}
}
if (e->print_with_newline)
format += '\n';
}
size_t format_bytes = format.size() + 1;
if (format_bytes > BPF_MAXFORMATLEN)
throw SEMANTIC_ERROR(_("Format string for print too long"), e->tok);
value *retval = emit_print_format(format, actual, e->print_to_stream, e->tok);
if (retval != NULL)
result = retval;
}
void
bpf_unparser::visit_stat_op (stat_op* e)
{
#ifdef DEBUG_CODEGEN
this_ins.notes.push("stat_get");
#endif
// XXX PR24528: This code is userspace-only. Unfortunately, BPF does
// not allow accessing percpu map elements from other cpus in
// kernel-space, so for now we will just issue a fake helper call
// and let the userspace sort this out.
//
// "I don't see a case where accessing other cpu per-cpu element
// wouldn't be a bug in the program."
// https://lore.kernel.org/patchwork/patch/634595/
if (this_prog.target == target_kernel_bpf)
throw SEMANTIC_ERROR(_("unsupported extraction function in bpf kernel probe"), e->tok);
switch (e->ctype)
{
case sc_average:
case sc_count:
case sc_sum:
break; // ok to pass to the helper
case sc_none:
assert (0); // should not happen, as sc_none is only used in foreach slots
// TODO PR23476: Not yet implemented.
case sc_min:
case sc_max:
case sc_variance:
default:
throw SEMANTIC_ERROR (_("unhandled stat op"), e->tok);
}
// identify the aggregate for the userspace interpreter
globals::agg_idx agg = 0;
if (symbol *s = dynamic_cast<symbol *>(e->stat)) // scalar stat value
{
vardecl *v = s->referent;
assert (v->arity == 0);
agg = 0; // id for scalar stat value
if (v->type != pe_stats)
throw SEMANTIC_ERROR (_("unexpected aggregate of non-statistic"), v->tok);
auto g = glob.globals.find (v);
if (g == glob.globals.end())
throw SEMANTIC_ERROR(_("unknown statistics variable"), v->tok);
if (!g->second.is_stat())
throw SEMANTIC_ERROR(_("not a statistics variable"), v->tok);
// Store the long on the stack and pass its address:
emit_long_arg(this_prog.lookup_reg(BPF_REG_2), -8,
this_prog.new_imm(g->second.idx));
this_prog.use_tmp_space(8);
}
else if (arrayindex *a = dynamic_cast<arrayindex *>(e->stat)) // array stat value
{
if (symbol *a_sym = dynamic_cast<symbol *>(a->base))
{
vardecl *v = a_sym->referent;
agg = glob.aggregates[v]; // id for array stat value
auto g = glob.globals.find(v);
if (g == glob.globals.end())
throw SEMANTIC_ERROR(_("unknown array variable"), v->tok);
unsigned element = v->arity;
unsigned key_ofs = 0;
// iterate over the elements
do {
--element;
value *idx = emit_expr(a->indexes[element]);
switch (v->index_types[element])
{
case pe_long:
// Store the long on the stack and pass its address:
key_ofs -= 8;
emit_long_arg(this_prog.lookup_reg(BPF_REG_2), key_ofs, idx);
break;
case pe_string:
// Zero-pad and copy the string to the stack and pass its address:
key_ofs -= BPF_MAXSTRINGLEN;
emit_str_arg(this_prog.lookup_reg(BPF_REG_2), key_ofs, idx);
break;
default:
throw SEMANTIC_ERROR(_("unhandled index type"), v->tok);
}
} while (element);
this_prog.use_tmp_space(-key_ofs);
}
else
throw SEMANTIC_ERROR(_("unknown statistics value"), e->stat->tok);
}
emit_mov(this_prog.lookup_reg(BPF_REG_1), this_prog.new_imm(agg)); // agg_idx
uint64_t sc_type = globals::intern_sc_type(e->ctype);
emit_mov(this_prog.lookup_reg(BPF_REG_3), this_prog.new_imm(sc_type));
this_prog.mk_call (this_ins, BPF_FUNC_stapbpf_stat_get, 3);
result = this_prog.new_reg();
emit_mov(result, this_prog.lookup_reg(BPF_REG_0));
#ifdef DEBUG_CODEGEN
this_ins.notes.pop();
#endif
}
void
bpf_unparser::visit_hist_op (hist_op *e)
{
// TODO PR24424: Implement as a perf-request or as a userspace-only helper.
throw SEMANTIC_ERROR (_("unhandled hist op"), e->tok);
}
// } // anon namespace
void
build_internal_globals(globals& glob)
{
struct vardecl exit;
exit.name = "__global___STAPBPF_exit";
exit.unmangled_name = "__STAPBPF_exit";
exit.type = pe_long;
exit.arity = 0;
glob.internal_exit = exit;
struct vardecl errors;
errors.name = "__global___STAPBPF_errors";
errors.unmangled_name = "__STAPBPF_errors";
errors.type = pe_long;
errors.arity = 0;
glob.internal_errors = errors;
glob.globals.insert(std::pair<vardecl *, globals::map_slot>
(&glob.internal_exit,
globals::map_slot(0, globals::EXIT)));
glob.globals.insert(std::pair<vardecl *, globals::map_slot>
(&glob.internal_errors,
globals::map_slot(0, globals::ERRORS)));
glob.maps.push_back
({ BPF_MAP_TYPE_HASH, 4, /* NB: value_size */ 8, globals::NUM_INTERNALS, 0 });
// PR22330: Use a PERF_EVENT_ARRAY map for message transport:
glob.maps.push_back
({ BPF_MAP_TYPE_PERF_EVENT_ARRAY, 4, 4, globals::NUM_CPUS_PLACEHOLDER, 0 });
// XXX: NUM_CPUS_PLACEHOLDER will be replaced at loading time.
}
static void
translate_globals (globals &glob, systemtap_session& s)
{
int long_map = -1; // -- for scalar long variables
int str_map = -1; // -- for scalar string variables
build_internal_globals(glob);
for (auto i = s.globals.begin(); i != s.globals.end(); ++i)
{
vardecl *v = *i;
int this_map, this_idx;
switch (v->arity)
{
case 0: // scalars
switch (v->type)
{
case pe_long:
if (long_map < 0)
{
globals::bpf_map_def m = {
BPF_MAP_TYPE_ARRAY, 4, 8, 0, 0
};
long_map = glob.maps.size();
glob.maps.push_back(m);
}
this_map = long_map;
this_idx = glob.maps[long_map].max_entries++;
break;
case pe_string:
if (str_map < 0)
{
globals::bpf_map_def m = {
BPF_MAP_TYPE_ARRAY, 4, BPF_MAXSTRINGLEN, 0, 0
};
str_map = glob.maps.size();
glob.maps.push_back(m);
}
this_map = str_map;
this_idx = glob.maps[str_map].max_entries++;
break;
case pe_stats:
if (glob.scalar_stats.empty())
{
for (globals::stat_field f : globals::stat_fields)
{
globals::bpf_map_def m = {
BPF_MAP_TYPE_PERCPU_ARRAY, 4, 8, 0, 0
};
globals::map_idx map_id = glob.maps.size();
glob.maps.push_back(m);
glob.scalar_stats[f] = map_id;
}
// ??? TODO: skip/drop any stat fields unused by all aggregates
// TODO PR24424: special case for 'histogram' field
}
this_map = -1; // Mark as statistical aggregate.
// Add one element to each stat field's array:
this_idx = -1;
for (globals::stat_field f : globals::stat_fields)
{
// XXX: Not all aggregates use the same stat
// fields. Some slots may therefore be unused, but
// it simplifies things a lot to use the same index
// for all fields of an aggregate.
int map_id = glob.scalar_stats[f];
int check_idx = glob.maps[map_id].max_entries++;
if (this_idx == -1)
this_idx = check_idx;
else
assert(check_idx == this_idx); // XXX: All arrays same length.
}
assert(this_idx >= 0);
break;
default:
throw SEMANTIC_ERROR (_("unhandled scalar type"), v->tok);
}
break;
default: // arrays (one or more dimension)
{
unsigned key_size = 0;
unsigned max_entries;
unsigned element = v->arity;
do {
--element;
switch (v->index_types[element])
{
case pe_long:
key_size += 8;
break;
case pe_string:
key_size += BPF_MAXSTRINGLEN;
break;
default:
throw SEMANTIC_ERROR (_("unhandled index type"), v->tok);
}
} while (element);
max_entries = v->maxsize > 0 ? v->maxsize : BPF_MAXMAPENTRIES;
if (v->type == pe_stats)
{
glob.array_stats[v] = globals::stats_map();
for (globals::stat_field f : globals::stat_fields)
{
globals::bpf_map_def m = {
BPF_MAP_TYPE_PERCPU_HASH, 0, 0, 0, 0
};
m.key_size = key_size;
m.max_entries = max_entries;
m.value_size = 8; // XXX: for stat data, sizeof(uint64_t)
int map_id = glob.maps.size();
glob.maps.push_back(m);
glob.array_stats[v][f] = map_id;
// Assign an agg_idx to identify the aggregate from BPF code.
// XXX: agg_idx 0 is reserved for scalar_stats:
glob.aggregates[v] = 1 + glob.aggregates.size();
// ??? TODO: skip/drop any stat fields unused by this aggregate
// TODO PR24424: special case for 'histogram' field
}
this_map = -1; // Mark as statistical aggregate.
this_idx = -1; // Mark as array.
}
else
{
globals::bpf_map_def m = { BPF_MAP_TYPE_HASH, 0, 0, 0, 0 };
m.key_size = key_size;
switch (v->type)
{
case pe_long:
m.value_size = 8;
break;
case pe_string:
m.value_size = BPF_MAXSTRINGLEN;
break;
// XXX: case pe_stats is handled above
default:
throw SEMANTIC_ERROR (_("unhandled array element type"), v->tok);
}
m.max_entries = max_entries;
this_map = glob.maps.size();
glob.maps.push_back(m);
this_idx = -1; // XXX: was 0, check if this is used correctly
}
}
break;
}
assert(this_map != globals::internal_map_idx);
auto ok = (glob.globals.insert
(std::pair<vardecl *, globals::map_slot>
(v, globals::map_slot(this_map, this_idx))));
assert(ok.second);
}
}
struct BPF_Section
{
Elf_Scn *scn;
Elf64_Shdr *shdr;
std::string name;
Stap_Strent *name_ent;
Elf_Data *data;
bool free_data; // NB: then data must have been malloc()'d!
BPF_Section(const std::string &n);
~BPF_Section();
};
BPF_Section::BPF_Section(const std::string &n)
: scn(0), name(n), name_ent(0), data(0), free_data(false)
{ }
BPF_Section::~BPF_Section()
{
if (free_data)
free(data->d_buf);
}
struct BPF_Symbol
{
std::string name;
Stap_Strent *name_ent;
Elf64_Sym sym;
BPF_Symbol(const std::string &n, BPF_Section *, long);
};
BPF_Symbol::BPF_Symbol(const std::string &n, BPF_Section *sec, long off)
: name(n), name_ent(0)
{
memset(&sym, 0, sizeof(sym));
sym.st_shndx = elf_ndxscn(sec->scn);
sym.st_value = off;
}
struct BPF_Output
{
Elf *elf;
Elf64_Ehdr *ehdr;
Stap_Strtab *str_tab;
std::vector<BPF_Section *> sections;
std::vector<BPF_Symbol *> symbols;
BPF_Output(int fd);
~BPF_Output();
BPF_Section *new_scn(const std::string &n);
BPF_Symbol *new_sym(const std::string &n, BPF_Section *, long);
BPF_Symbol *append_sym(const std::string &n, BPF_Section *, long);
};
BPF_Output::BPF_Output(int fd)
: elf(elf_begin(fd, ELF_C_WRITE_MMAP, NULL)),
ehdr(elf64_newehdr(elf)),
str_tab(stap_strtab_init(true))
{
ehdr->e_type = ET_REL;
ehdr->e_machine = EM_BPF;
}
BPF_Output::~BPF_Output()
{
stap_strtab_free(str_tab);
for (auto i = symbols.begin(); i != symbols.end(); ++i)
delete *i;
for (auto i = sections.begin(); i != sections.end(); ++i)
delete *i;
elf_end(elf);
}
BPF_Section *
BPF_Output::new_scn(const std::string &name)
{
BPF_Section *n = new BPF_Section(name);
Elf_Scn *scn = elf_newscn(elf);
n->scn = scn;
n->shdr = elf64_getshdr(scn);
n->data = elf_newdata(scn);
n->name_ent = stap_strtab_add(str_tab, n->name.c_str());
sections.push_back(n);
return n;
}
BPF_Symbol *
BPF_Output::new_sym(const std::string &name, BPF_Section *sec, long off)
{
BPF_Symbol *s = new BPF_Symbol(name, sec, off);
s->name_ent = stap_strtab_add(str_tab, s->name.c_str());
return s;
}
BPF_Symbol *
BPF_Output::append_sym(const std::string &name, BPF_Section *sec, long off)
{
BPF_Symbol *s = new_sym(name, sec, off);
symbols.push_back(s);
return s;
}
static void
output_kernel_version(BPF_Output &eo, const std::string &base_version)
{
unsigned long maj = 0, min = 0, rel = 0;
char *q;
maj = strtoul(base_version.c_str(), &q, 10);
if (*q == '.')
{
min = strtoul(q + 1, &q, 10);
if (*q == '.')
rel = strtoul(q + 1, NULL, 10);
}
BPF_Section *so = eo.new_scn("version");
Elf_Data *data = so->data;
data->d_buf = malloc(sizeof(uint32_t));
assert (data->d_buf);
* (uint32_t*) data->d_buf = KERNEL_VERSION(maj, min, rel);
data->d_type = ELF_T_BYTE;
data->d_size = 4;
data->d_align = 4;
so->free_data = true;
so->shdr->sh_type = SHT_PROGBITS;
so->shdr->sh_entsize = 4;
}
static void
output_license(BPF_Output &eo)
{
BPF_Section *so = eo.new_scn("license");
Elf_Data *data = so->data;
data->d_buf = (void *)"GPL";
data->d_type = ELF_T_BYTE;
data->d_size = 4;
so->shdr->sh_type = SHT_PROGBITS;
}
static void
output_stapbpf_script_name(BPF_Output &eo, const std::string script_name)
{
BPF_Section *so = eo.new_scn("stapbpf_script_name");
Elf_Data *data = so->data;
size_t script_name_len = strlen(script_name.c_str());
data->d_buf = (void *)malloc(script_name_len + 1);
char *script_name_buf = (char *)data->d_buf;
script_name.copy(script_name_buf, script_name_len);
script_name_buf[script_name_len] = '\0';
data->d_type = ELF_T_BYTE;
data->d_size = script_name_len + 1;
so->free_data = true;
so->shdr->sh_type = SHT_PROGBITS;
}
static void
output_maps(BPF_Output &eo, globals &glob)
{
unsigned nmaps = glob.maps.size();
if (nmaps == 0)
return;
assert(sizeof(unsigned) == sizeof(Elf64_Word));
const size_t bpf_map_def_sz = sizeof(globals::bpf_map_def);
BPF_Section *so = eo.new_scn("maps");
Elf_Data *data = so->data;
data->d_buf = glob.maps.data();
data->d_type = ELF_T_BYTE;
data->d_size = nmaps * bpf_map_def_sz;
data->d_align = 4;
so->shdr->sh_type = SHT_PROGBITS;
so->shdr->sh_entsize = bpf_map_def_sz;
// Allow the global arrays to have their actual names.
eo.symbols.reserve(nmaps);
for (unsigned i = 0; i < nmaps; ++i)
eo.symbols.push_back(NULL);
for (auto i = glob.globals.begin(); i != glob.globals.end(); ++i)
{
vardecl *v = i->first;
if (v->arity <= 0)
continue;
if (i->second.is_stat())
continue;
unsigned m = i->second.map_id;
assert(eo.symbols[m] == NULL);
BPF_Symbol *s = eo.new_sym(v->name, so, m * bpf_map_def_sz);
s->sym.st_info = ELF64_ST_INFO(STB_LOCAL, STT_OBJECT);
s->sym.st_size = bpf_map_def_sz;
eo.symbols[m] = s;
}
// Give internal names to stat maps.
for (auto i = glob.scalar_stats.begin(); i != glob.scalar_stats.end(); ++i)
{
std::string f = i->first;
unsigned m = i->second;
assert(eo.symbols[m] == NULL);
BPF_Symbol *s = eo.new_sym(std::string("stat.") + f,
so, m * bpf_map_def_sz);
s->sym.st_info = ELF64_ST_INFO(STB_LOCAL, STT_OBJECT);
eo.symbols[m] = s;
}
for (auto i = glob.array_stats.begin(); i != glob.array_stats.end(); ++i)
{
vardecl *v = i->first;
for (auto j = i->second.begin(); j != i->second.end(); ++j)
{
std::string f = j->first;
unsigned m = j->second;
assert(eo.symbols[m] == NULL);
BPF_Symbol *s = eo.new_sym(std::string(v->name) + std::string(".stat.") + f,
so, m * bpf_map_def_sz);
s->sym.st_info = ELF64_ST_INFO(STB_LOCAL, STT_OBJECT);
eo.symbols[m] = s;
}
}
// Give internal names to other maps.
for (unsigned i = 0; i < nmaps; ++i)
{
if (eo.symbols[i] != NULL)
continue;
BPF_Symbol *s = eo.new_sym(std::string("map.") + std::to_string(i),
so, i * bpf_map_def_sz);
s->sym.st_info = ELF64_ST_INFO(STB_LOCAL, STT_OBJECT);
s->sym.st_size = bpf_map_def_sz;
eo.symbols[i] = s;
}
}
static void
output_interned_strings(BPF_Output &eo, globals& glob)
{
// XXX: Don't use SHT_STRTAB since it can reorder the strings, iiuc
// requiring us to use yet more ELF infrastructure to refer to them
// and forcing us to generate this section at the same time as the
// code instead of in a separate procedure. To avoid that, manually
// write a SHT_PROGBITS section in SHT_STRTAB format.
if (glob.interned_strings.size() == 0)
return;
BPF_Section *str = eo.new_scn("stapbpf_interned_strings");
Elf_Data *data = str->data;
size_t interned_strings_len = 1; // extra NUL byte
for (auto i = glob.interned_strings.begin();
i != glob.interned_strings.end(); ++i)
{
std::string &str = *i;
interned_strings_len += str.size() + 1; // with NUL byte
}
data->d_buf = (void *)malloc(interned_strings_len);
char *interned_strings_buf = (char *)data->d_buf;
interned_strings_buf[0] = '\0';
unsigned ofs = 1;
for (auto i = glob.interned_strings.begin();
i != glob.interned_strings.end(); ++i)
{
std::string &str = *i;
assert(ofs+str.size()+1 <= interned_strings_len);
str.copy(interned_strings_buf+ofs, str.size());
interned_strings_buf[ofs+str.size()] = '\0';
ofs += str.size() + 1;
}
assert(ofs == interned_strings_len);
data->d_type = ELF_T_BYTE;
data->d_size = interned_strings_len;
str->free_data = true;
str->shdr->sh_type = SHT_PROGBITS;
}
static void
output_statsmap(void *d_buf, globals::agg_idx agg_id, const globals::stats_map &sm)
{
globals::interned_stats_map ism = globals::intern_stats_map(sm);
uint64_t *ix = (uint64_t *)d_buf;
*ix = (uint64_t)agg_id;
for (unsigned i = 0; i < globals::stat_fields.size(); i++)
{
globals::stat_field sf = globals::stat_fields[i];
auto it = sm.find(sf);
assert (it != sm.end());
ix++; *ix = (uint64_t)it->second;
}
}
static void
output_interned_aggregates(BPF_Output &eo, globals& glob)
{
if (glob.scalar_stats.empty() && glob.aggregates.size() == 0)
return;
BPF_Section *agg = eo.new_scn("stapbpf_aggregates");
Elf_Data *data = agg->data;
size_t interned_aggregate_len =
sizeof(uint64_t) * (1 + globals::stat_fields.size());
unsigned n_aggregates =
glob.scalar_stats.empty() ? glob.aggregates.size() : glob.aggregates.size() + 1;
data->d_buf = (void *)calloc(n_aggregates, interned_aggregate_len);
data->d_size = interned_aggregate_len * n_aggregates;
size_t ofs = 0; // XXX after glob.scalar_stats
if (!glob.scalar_stats.empty())
{
output_statsmap(data->d_buf, ofs, glob.scalar_stats);
ofs += interned_aggregate_len;
}
char *ix = (char *)data->d_buf;
for (auto i = glob.aggregates.begin();
i != glob.aggregates.end(); i++)
{
assert(glob.array_stats.count(i->first) != 0);
output_statsmap((void *)(ix+ofs), i->second, glob.array_stats[i->first]);
ofs += interned_aggregate_len;
}
assert (ofs == data->d_size);
data->d_type = ELF_T_BYTE;
agg->free_data = true;
agg->shdr->sh_type = SHT_PROGBITS;
}
static void
output_foreach_loop_info(BPF_Output &eo, globals& glob)
{
if (glob.foreach_loop_info.empty())
return;
/* XXX This method of serializing the foreach loop info struct is
clumsy but not so likely to run into struct ser/de weirdness. */
BPF_Section *agg = eo.new_scn("stapbpf_foreach_loop_info");
Elf_Data *data = agg->data;
size_t interned_foreach_info_len =
sizeof(uint64_t) * globals::n_foreach_info_fields;
unsigned n_foreach_loops = glob.foreach_loop_info.size();
data->d_buf = (void *)calloc(n_foreach_loops, interned_foreach_info_len);
data->d_size = interned_foreach_info_len * n_foreach_loops;
size_t ofs = 0;
uint64_t *ix = (uint64_t *)data->d_buf;
for (auto i = glob.foreach_loop_info.begin();
i != glob.foreach_loop_info.end(); i++)
{
globals::interned_foreach_info ifi = globals::intern_foreach_info(*i);
for (auto j = ifi.begin(); j != ifi.end(); j++)
{
*ix = (uint64_t)*j;
ofs += sizeof(uint64_t);
ix++;
}
}
assert (ofs == data->d_size);
data->d_type = ELF_T_BYTE;
agg->free_data = true;
agg->shdr->sh_type = SHT_PROGBITS;
}
void
bpf_unparser::add_prologue()
{
/**
* Before the probe can be executed, the probe's prologue will
* check to see if exit(...) has been called or if an error has
* occurred. To check if an error has occurred, it will see if
* the number of soft errors has exceeded the specified limit.
*/
// Create and clear error status and error message.
error_status = this_prog.new_reg();
emit_mov(error_status, this_prog.new_imm(0));
// Prepare exit block.
block *exit_block = get_exit_block();
// Prepare commonly used variables.
value *i0 = this_prog.new_imm(0);
value* frame = this_prog.lookup_reg(BPF_REG_10);
// If there is no soft error constraint, it is defaulted to 0.
int l = (constraints.find("MAXERRORS") != constraints.end()) ? constraints["MAXERRORS"] : 0;
value* limit = this_prog.new_imm(l);
int map_id = bpf::globals::internal_map_idx;
int map_key = bpf::globals::EXIT;
int key_size = 4;
// Prepare arguments for BPF_FUNC_map_lookup_elem.
this_prog.mk_st(this_ins, BPF_W, frame, -key_size, this_prog.new_imm(map_key));
this_prog.use_tmp_space(key_size);
// Lookup exit status.
this_prog.load_map(this_ins, this_prog.lookup_reg(BPF_REG_1), map_id);
this_prog.mk_binary(this_ins, BPF_ADD, this_prog.lookup_reg(BPF_REG_2), frame, this_prog.new_imm(-key_size));
this_prog.mk_call(this_ins, BPF_FUNC_map_lookup_elem, 2);
block *cont_block = this_prog.new_block();
// Check if BPF_FUNC_map_lookup_elem returned nullptr.
value *r0 = this_prog.lookup_reg(BPF_REG_0);
this_prog.mk_jcond(this_ins, EQ, r0, i0, exit_block, cont_block);
set_block(cont_block);
// Load exit status into exit_status.
value *exit_status = this_prog.new_reg();
this_prog.mk_ld(this_ins, BPF_DW, exit_status, r0, 0);
cont_block = this_prog.new_block();
// If exit_status == 1, jump to exit, otherwise continue with handler.
this_prog.mk_jcond(this_ins, EQ, exit_status, this_prog.new_imm(1), exit_block, cont_block);
set_block(cont_block);
// Check the error count.
map_key = bpf::globals::ERRORS;
// Prepare arguments for BPF_FUNC_map_lookup_elem.
this_prog.mk_st(this_ins, BPF_W, frame, -key_size, this_prog.new_imm(map_key));
this_prog.use_tmp_space(key_size);
// Lookup error count.
this_prog.load_map(this_ins, this_prog.lookup_reg(BPF_REG_1), map_id);
this_prog.mk_binary(this_ins, BPF_ADD, this_prog.lookup_reg(BPF_REG_2), frame, this_prog.new_imm(-key_size));
this_prog.mk_call(this_ins, BPF_FUNC_map_lookup_elem, 2);
cont_block = this_prog.new_block();
// Check if BPF_FUNC_map_lookup_elem returned nullptr.
r0 = this_prog.lookup_reg(BPF_REG_0);
this_prog.mk_jcond(this_ins, EQ, r0, i0, exit_block, cont_block);
set_block(cont_block);
// Load current error count into error_count.
value* error_count = this_prog.new_reg();
this_prog.mk_ld(this_ins, BPF_DW, error_count, r0, 0);
cont_block = this_prog.new_block();
// If the limit has been exceeded, proceed towards the exit.
this_prog.mk_jcond(this_ins, GT, error_count, limit, exit_block, cont_block);
set_block(cont_block);
}
void
bpf_unparser::add_epilogue()
{
/**
* Before the probe can finishes, the probe's epilogue will
* increment the error count if any errors occured and will
* also print the corresponding error message.
*/
// Prepare commonly used variables.
value *i0 = this_prog.new_imm(0);
value* frame = this_prog.lookup_reg(BPF_REG_10);
// If no limit has been specified, it is defaulted to 0.
int l = (constraints.find("MAXERRORS") != constraints.end()) ? constraints["MAXERRORS"] : 0;
value* limit = this_prog.new_imm(l);
block *error_block = this_prog.new_block();
block *exit_block = this_prog.new_block();
// Check if an error was called. If it was, run the error handler.
this_prog.mk_jcond(this_ins, EQ, i0, error_status, exit_block, error_block);
set_block(error_block);
// Print error message.
emit_transport_msg(globals::STP_PRINT_ERROR_MSG);
int map_id = globals::internal_map_idx;
int map_key = globals::ERRORS;
int key_size = 4;
int val_size = 8;
// Prepare arguments for BPF_FUNC_map_lookup_elem.
this_prog.mk_st(this_ins, BPF_W, frame, -key_size, this_prog.new_imm(map_key));
this_prog.use_tmp_space(key_size);
// Lookup error count.
this_prog.load_map(this_ins, this_prog.lookup_reg(BPF_REG_1), map_id);
this_prog.mk_binary(this_ins, BPF_ADD, this_prog.lookup_reg(BPF_REG_2), frame, this_prog.new_imm(-key_size));
this_prog.mk_call(this_ins, BPF_FUNC_map_lookup_elem, 2);
block *increment_block = this_prog.new_block();
// Check if BPF_FUNC_map_lookup_elem returned nullptr.
value *r0 = this_prog.lookup_reg(BPF_REG_0);
this_prog.mk_jcond(this_ins, EQ, r0, i0, exit_block, increment_block);
set_block(increment_block);
// Load current error count into error_count.
value *error_count = this_prog.new_reg();
this_prog.mk_ld(this_ins, BPF_DW, error_count, r0, 0);
// Increment the number of errors.
this_prog.mk_binary(this_ins, BPF_ADD, error_count, error_count, this_prog.new_imm(1));
// Prepare arguments for BPF_FUNC_map_update_elem.
this_prog.mk_st(this_ins, BPF_DW, frame, -val_size, error_count);
this_prog.use_tmp_space(val_size);
this_prog.mk_st(this_ins, BPF_W, frame, -val_size-key_size, this_prog.new_imm(map_key));
this_prog.use_tmp_space(key_size);
// Update the global error count.
this_prog.load_map(this_ins, this_prog.lookup_reg(BPF_REG_1), map_id);
this_prog.mk_binary(this_ins, BPF_ADD, this_prog.lookup_reg(BPF_REG_2), frame, this_prog.new_imm(-val_size-key_size));
this_prog.mk_binary(this_ins, BPF_ADD, this_prog.lookup_reg(BPF_REG_3), frame, this_prog.new_imm(-val_size));
this_prog.mk_mov(this_ins, this_prog.lookup_reg(BPF_REG_4), this_prog.new_imm(0));
this_prog.mk_call(this_ins, BPF_FUNC_map_update_elem, 4);
block *exceeded_block = this_prog.new_block();
// Check if limit is exceeded. If so, communicate a hard error.
this_prog.mk_jcond(this_ins, LE, error_count, limit, exit_block, exceeded_block);
set_block(exceeded_block);
// Communicate a hard error.
emit_transport_msg(bpf::globals::STP_ERROR);
emit_jmp(exit_block);
set_block(exit_block);
}
static void
translate_probe(program &prog, globals &glob, derived_probe *dp)
{
bpf_unparser u(prog, glob);
u.this_locals = u.new_locals(dp->locals);
u.set_block(prog.new_block ());
// Save the input argument early.
// ??? Ideally this would be deleted as dead code if it were unused;
// we don't implement that at the moment. Nor is it easy to support
// inserting a new start block that would enable retroactively saving
// this only when needed.
u.this_in_arg0 = prog.lookup_reg(BPF_REG_6);
prog.mk_mov(u.this_ins, u.this_in_arg0, prog.lookup_reg(BPF_REG_1));
u.add_prologue();
dp->body->visit (&u);
if (u.in_block())
u.emit_jmp(u.get_ret0_block());
}
static void
translate_probe_v(program &prog, globals &glob,
const std::vector<derived_probe *> &v)
{
bpf_unparser u(prog, glob);
block *this_block;
if (prog.blocks.empty())
this_block = prog.new_block();
else
{
u.set_block(prog.blocks.back());
this_block = prog.new_block();
u.emit_jmp(this_block);
}
for (size_t n = v.size(), i = 0; i < n; ++i)
{
u.set_block(this_block);
derived_probe *dp = v[i];
u.this_locals = u.new_locals(dp->locals);
if (i == 0)
{
// Create and clear the error status.
u.error_status = prog.new_reg();
prog.mk_mov(u.this_ins, u.error_status, prog.new_imm(0));
}
dp->body->visit (&u);
delete u.this_locals;
u.this_locals = NULL;
if (i == n - 1)
this_block = u.get_ret0_block();
else
this_block = prog.new_block();
if (u.in_block())
u.emit_jmp(this_block);
}
}
static void
translate_init_and_probe_v(program &prog, globals &glob, init_block &b,
const std::vector<derived_probe *> &v)
{
bpf_unparser u(prog, glob);
block *this_block = prog.new_block();
u.set_block(this_block);
b.visit(&u);
if (!v.empty())
translate_probe_v(prog, glob, v);
else
{
this_block = u.get_ret0_block();
assert(u.in_block());
u.emit_jmp(this_block);
}
}
static BPF_Section *
output_probe(BPF_Output &eo, program &prog,
const std::string &name, unsigned flags)
{
unsigned ninsns = 0, nreloc = 0;
// Count insns and relocations; drop in jump offset.
for (auto i = prog.blocks.begin(); i != prog.blocks.end(); ++i)
{
block *b = *i;
for (insn *j = b->first; j != NULL; j = j->next)
{
unsigned code = j->code;
if ((code & 0xff) == (BPF_LD | BPF_IMM | BPF_DW))
{
if (code == BPF_LD_MAP)
nreloc += 1;
ninsns += 2;
}
else
{
if (j->is_jmp())
{
// ??? Forwarders should be removed by bpf-opt.cxx thread_jumps,
// but we seem to miss or reintroduce a few. Minimal fix:
block *target = b->taken->next;
while (target->first == NULL)
{
target = target->is_forwarder();
assert (target != NULL);
}
j->off = target->first->id - (j->id + 1);
}
else if (j->is_call())
j->off = 0;
ninsns += 1;
}
}
}
bpf_insn *buf = (bpf_insn*) calloc (ninsns, sizeof(bpf_insn));
assert (buf);
Elf64_Rel *rel = (Elf64_Rel*) calloc (nreloc, sizeof(Elf64_Rel));
assert (rel);
unsigned i = 0, r = 0;
for (auto bi = prog.blocks.begin(); bi != prog.blocks.end(); ++bi)
{
block *b = *bi;
for (insn *j = b->first; j != NULL; j = j->next)
{
unsigned code = j->code;
value *d = j->dest;
value *s = j->src1;
if (code == BPF_LD_MAP)
{
unsigned val = s->imm();
// Note that we arrange for the map symbols to be first.
rel[r].r_offset = i * sizeof(bpf_insn);
rel[r].r_info = ELF64_R_INFO(val + 1, R_BPF_MAP_FD);
r += 1;
buf[i + 0].code = code;
buf[i + 0].dst_reg = d->reg();
buf[i + 0].src_reg = code >> 8;
i += 2;
}
else if (code == (BPF_LD | BPF_IMM | BPF_DW))
{
uint64_t val = s->imm();
buf[i + 0].code = code;
buf[i + 0].dst_reg = d->reg();
buf[i + 0].src_reg = code >> 8;
buf[i + 0].imm = val;
buf[i + 1].imm = val >> 32;
i += 2;
}
else
{
buf[i].code = code;
if (!d)
d = j->src0;
if (d)
buf[i].dst_reg = d->reg();
if (s)
{
if (s->is_reg())
buf[i].src_reg = s->reg();
else
buf[i].imm = s->imm();
}
buf[i].off = j->off;
i += 1;
}
}
}
assert(i == ninsns);
assert(r == nreloc);
BPF_Section *so = eo.new_scn(name);
Elf_Data *data = so->data;
data->d_buf = buf;
data->d_type = ELF_T_BYTE;
data->d_size = ninsns * sizeof(bpf_insn);
data->d_align = 8;
so->free_data = true;
so->shdr->sh_type = SHT_PROGBITS;
so->shdr->sh_flags = SHF_EXECINSTR | flags;
if (nreloc)
{
BPF_Section *ro = eo.new_scn(std::string(".rel.") + name);
Elf_Data *rdata = ro->data;
rdata->d_buf = rel;
rdata->d_type = ELF_T_REL;
rdata->d_size = nreloc * sizeof(Elf64_Rel);
ro->free_data = true;
ro->shdr->sh_type = SHT_REL;
ro->shdr->sh_info = elf_ndxscn(so->scn);
}
return so;
}
static void
output_symbols_sections(BPF_Output &eo)
{
BPF_Section *str = eo.new_scn(".strtab");
str->shdr->sh_type = SHT_STRTAB;
str->shdr->sh_entsize = 1;
unsigned nsym = eo.symbols.size();
unsigned isym = 0;
if (nsym > 0)
{
BPF_Section *sym = eo.new_scn(".symtab");
sym->shdr->sh_type = SHT_SYMTAB;
sym->shdr->sh_link = elf_ndxscn(str->scn);
sym->shdr->sh_info = nsym + 1;
Elf64_Sym *buf = new Elf64_Sym[nsym + 1];
memset(buf, 0, sizeof(Elf64_Sym));
sym->data->d_buf = buf;
sym->data->d_type = ELF_T_SYM;
sym->data->d_size = (nsym + 1) * sizeof(Elf64_Sym);
stap_strtab_finalize(eo.str_tab, str->data);
for (unsigned i = 0; i < nsym; ++i)
{
BPF_Symbol *s = eo.symbols[i];
Elf64_Sym *b = buf + (i + 1);
*b = s->sym;
b->st_name = stap_strent_offset(s->name_ent);
}
isym = elf_ndxscn(sym->scn);
}
else
stap_strtab_finalize(eo.str_tab, str->data);
eo.ehdr->e_shstrndx = elf_ndxscn(str->scn);
for (auto i = eo.sections.begin(); i != eo.sections.end(); ++i)
{
BPF_Section *s = *i;
s->shdr->sh_name = stap_strent_offset(s->name_ent);
if (s->shdr->sh_type == SHT_REL)
s->shdr->sh_link = isym;
}
}
} // namespace bpf
int
translate_bpf_pass (systemtap_session& s)
{
using namespace bpf;
init_bpf_opcode_tables();
init_bpf_helper_tables();
if (elf_version(EV_CURRENT) == EV_NONE)
return 1;
module_name = s.module_name;
const std::string module = s.tmpdir + "/" + s.module_filename();
int fd = open(module.c_str(), O_RDWR | O_CREAT | O_TRUNC, 0666);
if (fd < 0)
return 1;
BPF_Output eo(fd);
globals glob; glob.session = &s;
int ret = 0;
const token* t = 0;
try
{
translate_globals(glob, s);
output_maps(eo, glob);
if (s.be_derived_probes || !glob.empty())
{
std::vector<derived_probe *> begin_v, end_v, error_v;
sort_for_bpf(s, s.be_derived_probes, begin_v, end_v, error_v);
init_block init(glob);
if (!init.empty())
{
if (!begin_v.empty())
t = begin_v[0]->tok;
program p(target_user_bpfinterp);
translate_init_and_probe_v(p, glob, init, begin_v);
p.generate();
output_probe(eo, p, "stap_begin", 0);
}
else if (!begin_v.empty())
{
t = begin_v[0]->tok;
program p(target_user_bpfinterp);
translate_probe_v(p, glob, begin_v);
p.generate();
output_probe(eo, p, "stap_begin", 0);
}
if (!end_v.empty())
{
t = end_v[0]->tok;
program p(target_user_bpfinterp);
translate_probe_v(p, glob, end_v);
p.generate();
output_probe(eo, p, "stap_end", 0);
}
if (!error_v.empty())
{
t = error_v[0]->tok;
program p(target_user_bpfinterp);
translate_probe_v(p, glob, error_v);
p.generate();
output_probe(eo, p, "stap_error", 0);
}
}
if (s.generic_kprobe_derived_probes)
{
sort_for_bpf_probe_arg_vector kprobe_v;
sort_for_bpf(s, s.generic_kprobe_derived_probes, kprobe_v);
for (auto i = kprobe_v.begin(); i != kprobe_v.end(); ++i)
{
t = i->first->tok;
program p(target_kernel_bpf);
translate_probe(p, glob, i->first);
p.generate();
output_probe(eo, p, i->second, SHF_ALLOC);
}
}
if (s.procfs_derived_probes)
{
sort_for_bpf_probe_arg_vector procfs_v;
sort_for_bpf(s, s.procfs_derived_probes, procfs_v);
for (auto i = procfs_v.begin(); i != procfs_v.end(); ++i)
{
t = i->first->tok;
program p(target_user_bpfinterp);
translate_probe(p, glob, i->first);
p.generate();
output_probe(eo, p, i->second, 0);
}
}
if (s.perf_derived_probes)
{
sort_for_bpf_probe_arg_vector perf_v;
sort_for_bpf(s, s.perf_derived_probes, perf_v);
for (auto i = perf_v.begin(); i != perf_v.end(); ++i)
{
t = i->first->tok;
program p(target_kernel_bpf);
translate_probe(p, glob, i->first);
p.generate();
output_probe(eo, p, i->second, SHF_ALLOC);
}
}
if (s.hrtimer_derived_probes || s.timer_derived_probes)
{
sort_for_bpf_probe_arg_vector timer_v;
sort_for_bpf(s, s.hrtimer_derived_probes,
s.timer_derived_probes, timer_v);
for (auto i = timer_v.begin(); i != timer_v.end(); ++i)
{
t = i->first->tok;
// TODO PR23477: Also support userspace timer probes.
program p(target_kernel_bpf);
translate_probe(p, glob, i->first);
p.generate();
output_probe(eo, p, i->second, SHF_ALLOC);
}
}
if (s.tracepoint_derived_probes)
{
sort_for_bpf_probe_arg_vector trace_v;
sort_for_bpf(s, s.tracepoint_derived_probes, trace_v);
for (auto i = trace_v.begin(); i != trace_v.end(); ++i)
{
t = i->first->tok;
program p(target_kernel_bpf);
translate_probe(p, glob, i->first);
p.generate();
output_probe(eo, p, i->second, SHF_ALLOC);
}
}
if (s.uprobe_derived_probes)
{
sort_for_bpf_probe_arg_vector uprobe_v;
sort_for_bpf(s, s.uprobe_derived_probes, uprobe_v);
for (auto i = uprobe_v.begin(); i != uprobe_v.end(); ++i)
{
t = i->first->tok;
program p(target_kernel_bpf);
translate_probe(p, glob, i->first);
p.generate();
output_probe(eo, p, i->second, SHF_ALLOC);
}
}
// PR26234: would like to support process.{begin,end} probes,
// but BPF doesn't give any clear way to probe the same context....
if (s.utrace_derived_probes)
warn_for_bpf(s, s.utrace_derived_probes, "utrace probe");
// XXX PR26234: need to warn about other probe groups....
if (s.hwbkpt_derived_probes)
warn_for_bpf(s, s.hwbkpt_derived_probes, "hardware breakpoint probe");
if (s.netfilter_derived_probes)
warn_for_bpf(s, s.netfilter_derived_probes, "netfilter probe");
if (s.profile_derived_probes)
warn_for_bpf(s, s.profile_derived_probes, "timer.profile probe");
if (s.mark_derived_probes)
warn_for_bpf(s, s.mark_derived_probes, "static marker probe");
if (s.python_derived_probes)
warn_for_bpf(s, s.python_derived_probes, "python probe");
// s.task_finder_derived_probes -- synthetic
// s.vma_tracker_derived_probes -- synthetic
// s.dynprobe_derived_probes -- synthetic, dyninst only
output_kernel_version(eo, s.kernel_base_release);
output_license(eo);
output_stapbpf_script_name(eo, escaped_literal_string(s.script_basename()));
output_interned_strings(eo, glob);
output_interned_aggregates(eo, glob);
output_foreach_loop_info(eo, glob);
output_symbols_sections(eo);
int64_t r = elf_update(eo.elf, ELF_C_WRITE_MMAP);
if (r < 0)
{
std::clog << "Error writing output file: "
<< elf_errmsg(elf_errno()) << std::endl;
ret = 1;
}
}
catch (const semantic_error &e)
{
s.print_error(e);
ret = 1;
}
catch (const std::runtime_error &e)
{
semantic_error er(ERR_SRC, _F("bpf translation failure: %s", e.what()), t);
s.print_error(er);
ret = 1;
}
catch (...)
{
std::cerr << "bpf translation internal error" << std::endl;
ret = 1;
}
close(fd);
if (ret == 1)
unlink(s.translated_source.c_str());
return ret;
}
|