1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285 6286 6287 6288 6289 6290 6291 6292 6293 6294 6295 6296 6297 6298 6299 6300 6301 6302 6303 6304 6305 6306 6307 6308 6309 6310 6311 6312 6313 6314 6315 6316 6317 6318 6319 6320 6321 6322 6323 6324 6325 6326 6327 6328 6329 6330 6331 6332 6333 6334 6335 6336 6337 6338 6339 6340 6341 6342 6343 6344 6345 6346 6347 6348 6349 6350 6351 6352 6353 6354 6355 6356 6357 6358 6359 6360 6361 6362 6363 6364 6365 6366 6367 6368 6369 6370 6371 6372 6373 6374 6375 6376 6377 6378 6379 6380 6381 6382 6383 6384 6385 6386 6387 6388 6389 6390 6391 6392 6393 6394 6395 6396 6397 6398 6399 6400 6401 6402 6403 6404 6405 6406 6407 6408 6409 6410 6411 6412 6413 6414 6415 6416 6417 6418 6419 6420 6421 6422 6423 6424 6425 6426 6427 6428 6429 6430 6431 6432 6433 6434 6435 6436 6437 6438 6439 6440 6441 6442 6443 6444 6445 6446 6447 6448 6449 6450 6451 6452 6453 6454 6455 6456 6457 6458 6459 6460 6461 6462 6463 6464 6465 6466 6467 6468 6469 6470 6471 6472 6473 6474 6475 6476 6477 6478 6479 6480 6481 6482 6483 6484 6485 6486 6487 6488 6489 6490 6491 6492 6493 6494 6495 6496 6497 6498 6499 6500 6501 6502 6503 6504 6505 6506 6507 6508 6509 6510 6511 6512 6513 6514 6515 6516 6517 6518 6519 6520 6521 6522 6523 6524 6525 6526 6527 6528 6529 6530 6531 6532 6533 6534 6535 6536 6537 6538 6539 6540 6541 6542 6543 6544 6545 6546 6547 6548 6549 6550 6551 6552 6553 6554 6555 6556 6557 6558 6559 6560 6561 6562 6563 6564 6565 6566 6567 6568 6569 6570 6571 6572 6573 6574 6575 6576 6577 6578 6579 6580 6581 6582 6583 6584 6585 6586 6587 6588 6589 6590 6591 6592 6593 6594 6595 6596 6597 6598 6599 6600 6601 6602 6603 6604 6605 6606 6607 6608 6609 6610 6611 6612 6613 6614 6615 6616 6617 6618 6619 6620 6621 6622 6623 6624 6625 6626 6627 6628 6629 6630 6631 6632 6633 6634 6635 6636 6637 6638 6639 6640 6641 6642 6643 6644 6645 6646 6647 6648 6649 6650 6651 6652 6653 6654 6655 6656 6657 6658 6659 6660 6661 6662 6663 6664 6665 6666 6667 6668 6669 6670 6671 6672 6673 6674 6675 6676 6677 6678 6679 6680 6681 6682 6683 6684 6685 6686 6687 6688 6689 6690 6691 6692 6693 6694 6695 6696 6697 6698 6699 6700 6701 6702 6703 6704 6705 6706 6707 6708 6709 6710 6711 6712 6713 6714 6715 6716 6717 6718 6719 6720 6721 6722 6723 6724 6725 6726 6727 6728 6729 6730 6731 6732 6733 6734 6735 6736 6737 6738 6739 6740 6741 6742 6743 6744 6745 6746 6747 6748 6749 6750 6751 6752 6753 6754 6755 6756 6757 6758 6759 6760 6761 6762 6763 6764 6765 6766 6767 6768 6769 6770 6771 6772 6773 6774 6775 6776 6777 6778 6779 6780 6781 6782 6783 6784 6785 6786 6787 6788 6789 6790 6791 6792 6793 6794 6795 6796 6797 6798 6799 6800 6801 6802 6803 6804 6805 6806 6807 6808 6809 6810 6811 6812 6813 6814 6815 6816 6817 6818 6819 6820 6821 6822 6823 6824 6825 6826 6827 6828 6829 6830 6831 6832 6833 6834 6835 6836 6837 6838 6839 6840 6841 6842 6843 6844 6845 6846 6847 6848 6849 6850 6851 6852 6853 6854 6855 6856 6857 6858 6859 6860 6861 6862 6863 6864 6865 6866 6867 6868 6869 6870 6871 6872 6873 6874 6875 6876 6877 6878 6879 6880 6881 6882 6883 6884 6885 6886 6887 6888 6889 6890 6891 6892 6893 6894 6895 6896 6897 6898 6899 6900 6901 6902 6903 6904 6905 6906 6907 6908 6909 6910 6911 6912 6913 6914 6915 6916 6917 6918 6919 6920 6921 6922 6923 6924 6925 6926 6927 6928 6929 6930 6931 6932 6933 6934 6935 6936 6937 6938 6939 6940 6941 6942 6943 6944 6945 6946 6947 6948 6949 6950 6951 6952 6953 6954 6955 6956 6957 6958 6959 6960 6961 6962 6963 6964 6965 6966 6967 6968 6969 6970 6971 6972 6973 6974 6975 6976 6977 6978 6979 6980 6981 6982 6983 6984 6985 6986 6987 6988 6989 6990 6991 6992 6993 6994 6995 6996 6997 6998 6999 7000 7001 7002 7003 7004 7005 7006 7007 7008 7009 7010 7011 7012 7013 7014 7015 7016 7017 7018 7019 7020 7021 7022 7023 7024 7025 7026 7027 7028 7029 7030 7031 7032 7033 7034 7035 7036 7037 7038 7039 7040 7041 7042 7043 7044 7045 7046 7047 7048 7049 7050 7051 7052 7053 7054 7055 7056 7057 7058 7059 7060 7061 7062 7063 7064 7065 7066 7067 7068 7069 7070 7071 7072 7073 7074 7075 7076 7077 7078 7079 7080 7081 7082 7083 7084 7085 7086 7087 7088 7089 7090 7091 7092 7093 7094 7095 7096 7097 7098 7099 7100 7101 7102 7103 7104 7105 7106 7107 7108 7109 7110 7111 7112 7113 7114 7115 7116 7117 7118 7119 7120 7121 7122 7123 7124 7125 7126 7127 7128 7129 7130 7131 7132 7133 7134 7135 7136 7137 7138 7139 7140 7141 7142 7143 7144 7145 7146 7147 7148 7149 7150 7151 7152 7153 7154 7155 7156 7157 7158 7159 7160 7161 7162 7163 7164 7165 7166 7167 7168 7169 7170 7171 7172 7173 7174 7175 7176 7177 7178 7179 7180 7181 7182 7183 7184 7185 7186 7187 7188 7189 7190 7191 7192 7193 7194 7195 7196 7197 7198 7199 7200 7201 7202 7203 7204 7205 7206 7207 7208 7209 7210 7211 7212 7213 7214 7215 7216 7217 7218 7219 7220 7221 7222 7223 7224 7225 7226 7227 7228 7229 7230 7231 7232 7233 7234 7235 7236 7237 7238 7239 7240 7241 7242 7243 7244 7245 7246 7247 7248 7249 7250 7251 7252 7253 7254 7255 7256 7257 7258 7259 7260 7261 7262 7263 7264 7265 7266 7267 7268 7269 7270 7271 7272 7273 7274 7275 7276 7277 7278 7279 7280 7281 7282 7283 7284 7285 7286 7287 7288 7289 7290 7291 7292 7293 7294 7295 7296 7297 7298 7299 7300 7301 7302 7303 7304 7305 7306 7307 7308 7309 7310 7311 7312 7313 7314 7315 7316 7317 7318 7319 7320 7321 7322 7323 7324 7325 7326 7327 7328 7329 7330 7331 7332 7333 7334 7335 7336 7337 7338 7339 7340 7341 7342 7343 7344 7345 7346 7347 7348 7349 7350 7351 7352 7353 7354 7355 7356 7357 7358 7359 7360 7361 7362 7363 7364 7365 7366 7367 7368 7369 7370 7371 7372 7373 7374 7375 7376 7377 7378 7379 7380 7381 7382 7383 7384 7385 7386 7387 7388 7389 7390 7391 7392 7393 7394 7395 7396 7397 7398 7399 7400 7401 7402 7403 7404 7405 7406 7407 7408 7409 7410 7411 7412 7413 7414 7415 7416 7417 7418 7419 7420 7421 7422 7423 7424 7425 7426 7427 7428 7429 7430 7431 7432 7433 7434 7435 7436 7437 7438 7439 7440 7441 7442 7443 7444 7445 7446 7447 7448 7449 7450 7451 7452 7453 7454 7455 7456 7457 7458 7459 7460 7461 7462 7463 7464 7465 7466 7467 7468 7469 7470 7471 7472 7473 7474 7475 7476 7477 7478 7479 7480 7481 7482 7483 7484 7485 7486 7487 7488 7489 7490 7491 7492 7493 7494 7495 7496 7497 7498 7499 7500 7501 7502 7503 7504 7505 7506 7507 7508 7509 7510 7511 7512 7513 7514 7515 7516 7517 7518 7519 7520 7521 7522 7523 7524 7525 7526 7527 7528 7529 7530 7531 7532 7533 7534 7535 7536 7537 7538 7539 7540 7541 7542 7543 7544 7545 7546 7547 7548 7549 7550 7551 7552 7553 7554 7555 7556 7557 7558 7559 7560 7561 7562 7563 7564 7565 7566 7567 7568 7569 7570 7571 7572 7573 7574 7575 7576 7577 7578 7579 7580 7581 7582 7583 7584 7585 7586 7587 7588 7589 7590 7591 7592 7593 7594 7595 7596 7597 7598 7599 7600 7601 7602 7603 7604 7605 7606 7607 7608 7609 7610 7611 7612 7613 7614 7615 7616 7617 7618 7619 7620 7621 7622 7623 7624 7625 7626 7627 7628 7629 7630 7631 7632 7633 7634 7635 7636 7637 7638 7639 7640 7641 7642 7643 7644 7645 7646 7647 7648 7649 7650 7651 7652 7653 7654 7655 7656 7657 7658 7659 7660 7661 7662 7663 7664 7665 7666 7667 7668 7669 7670 7671 7672 7673 7674 7675 7676 7677 7678 7679 7680 7681 7682 7683 7684 7685 7686 7687 7688 7689 7690 7691 7692 7693 7694 7695 7696 7697 7698 7699 7700 7701 7702 7703 7704 7705 7706 7707 7708 7709 7710 7711 7712 7713 7714 7715 7716 7717 7718 7719 7720 7721 7722 7723 7724 7725 7726 7727 7728 7729 7730 7731 7732 7733 7734 7735 7736 7737 7738 7739 7740 7741 7742 7743 7744 7745 7746 7747 7748 7749 7750 7751 7752 7753 7754 7755 7756 7757 7758 7759 7760 7761 7762 7763 7764 7765 7766 7767 7768 7769 7770 7771 7772 7773 7774 7775 7776 7777 7778 7779 7780 7781 7782 7783 7784 7785 7786 7787 7788 7789 7790 7791 7792 7793 7794 7795 7796 7797 7798 7799 7800 7801 7802 7803 7804 7805 7806 7807 7808 7809 7810 7811 7812 7813 7814 7815 7816 7817 7818 7819 7820 7821 7822 7823 7824 7825 7826 7827 7828 7829 7830 7831 7832 7833 7834 7835 7836 7837 7838 7839 7840 7841 7842 7843 7844 7845 7846 7847 7848 7849 7850 7851 7852 7853 7854 7855 7856 7857 7858 7859 7860 7861 7862 7863 7864 7865 7866 7867 7868 7869 7870 7871 7872 7873 7874 7875 7876 7877 7878 7879 7880 7881 7882 7883 7884 7885 7886 7887 7888 7889 7890 7891 7892 7893 7894 7895 7896 7897 7898 7899 7900 7901 7902 7903 7904 7905 7906 7907 7908 7909 7910 7911 7912 7913 7914 7915 7916 7917 7918 7919 7920 7921 7922 7923 7924 7925 7926 7927 7928 7929 7930 7931 7932 7933 7934 7935 7936 7937 7938 7939 7940 7941 7942 7943 7944 7945 7946 7947 7948 7949 7950 7951 7952 7953 7954 7955 7956 7957 7958 7959 7960 7961 7962 7963 7964 7965 7966 7967 7968 7969 7970 7971 7972 7973 7974 7975 7976 7977 7978 7979 7980 7981 7982 7983 7984 7985 7986 7987 7988 7989 7990 7991 7992 7993 7994 7995 7996 7997 7998 7999 8000 8001 8002 8003 8004 8005 8006 8007 8008 8009 8010 8011 8012 8013 8014 8015 8016 8017 8018 8019 8020 8021 8022 8023 8024 8025 8026 8027 8028 8029 8030 8031 8032 8033 8034 8035 8036 8037 8038 8039 8040 8041 8042 8043 8044 8045 8046 8047 8048 8049 8050 8051 8052 8053 8054 8055 8056 8057 8058 8059 8060 8061 8062 8063 8064 8065 8066 8067 8068 8069 8070 8071 8072 8073 8074 8075 8076 8077 8078 8079 8080 8081 8082 8083 8084 8085 8086 8087 8088 8089 8090 8091 8092 8093 8094 8095 8096 8097 8098 8099 8100 8101 8102 8103 8104 8105 8106 8107 8108 8109 8110 8111 8112 8113 8114 8115 8116 8117 8118 8119 8120 8121 8122 8123 8124 8125 8126 8127 8128 8129 8130 8131 8132 8133 8134 8135 8136 8137 8138 8139 8140 8141 8142 8143 8144 8145 8146 8147 8148 8149 8150 8151 8152 8153 8154 8155 8156 8157 8158 8159 8160 8161 8162 8163 8164 8165 8166 8167 8168 8169 8170 8171 8172 8173 8174 8175 8176 8177 8178 8179 8180 8181 8182 8183 8184 8185 8186 8187 8188 8189 8190 8191 8192 8193 8194 8195 8196 8197 8198 8199 8200 8201 8202 8203 8204 8205 8206 8207 8208 8209 8210 8211 8212 8213 8214 8215 8216 8217 8218 8219 8220 8221 8222 8223 8224 8225 8226 8227 8228 8229 8230 8231 8232 8233 8234 8235 8236 8237 8238 8239 8240 8241 8242 8243 8244 8245 8246 8247 8248 8249 8250 8251 8252 8253 8254 8255 8256 8257 8258 8259 8260 8261 8262 8263 8264 8265 8266 8267 8268 8269 8270 8271 8272 8273 8274 8275 8276 8277 8278 8279 8280 8281 8282 8283 8284 8285 8286 8287 8288 8289 8290 8291 8292 8293 8294 8295 8296 8297 8298 8299 8300 8301 8302 8303 8304 8305 8306 8307 8308 8309 8310 8311 8312 8313 8314 8315 8316 8317 8318 8319 8320 8321 8322 8323 8324 8325 8326 8327 8328 8329 8330 8331 8332 8333 8334 8335 8336 8337 8338 8339 8340 8341 8342 8343 8344 8345 8346 8347 8348 8349 8350 8351 8352 8353 8354 8355 8356 8357 8358 8359 8360 8361 8362 8363 8364 8365 8366 8367 8368 8369 8370 8371 8372 8373 8374 8375 8376 8377 8378 8379 8380 8381 8382 8383 8384 8385 8386 8387 8388 8389 8390 8391 8392 8393 8394 8395 8396 8397 8398 8399 8400 8401 8402 8403 8404 8405 8406 8407 8408 8409 8410 8411 8412 8413 8414 8415 8416 8417 8418 8419 8420 8421 8422 8423 8424 8425 8426 8427 8428 8429 8430 8431 8432 8433 8434 8435 8436 8437 8438 8439 8440 8441 8442 8443 8444 8445 8446 8447 8448 8449 8450 8451 8452 8453 8454 8455 8456 8457 8458 8459 8460 8461 8462 8463 8464 8465 8466 8467 8468 8469 8470 8471 8472 8473 8474 8475 8476 8477 8478 8479 8480 8481 8482 8483 8484 8485 8486 8487 8488 8489 8490 8491 8492 8493 8494 8495 8496 8497 8498 8499 8500 8501 8502 8503 8504 8505 8506 8507 8508 8509 8510 8511 8512 8513 8514 8515 8516 8517 8518 8519 8520 8521 8522 8523 8524 8525 8526 8527 8528 8529 8530 8531 8532 8533 8534 8535 8536 8537 8538 8539 8540 8541 8542 8543 8544 8545 8546 8547 8548 8549 8550 8551 8552 8553 8554 8555 8556 8557 8558 8559 8560 8561 8562 8563 8564 8565 8566 8567 8568 8569 8570 8571 8572 8573 8574 8575 8576 8577 8578 8579 8580 8581 8582 8583 8584 8585 8586 8587 8588 8589 8590 8591 8592 8593 8594 8595 8596 8597 8598 8599 8600 8601 8602 8603 8604 8605 8606 8607 8608 8609 8610 8611 8612 8613 8614 8615 8616 8617 8618 8619 8620 8621 8622 8623 8624 8625 8626 8627 8628 8629 8630 8631 8632 8633 8634 8635 8636 8637 8638 8639 8640 8641 8642 8643 8644 8645 8646 8647 8648 8649 8650 8651 8652 8653 8654 8655 8656 8657 8658 8659 8660 8661 8662 8663 8664 8665 8666 8667 8668 8669 8670 8671 8672 8673 8674 8675 8676 8677 8678 8679 8680 8681 8682 8683 8684 8685 8686 8687 8688 8689 8690 8691 8692 8693 8694 8695 8696 8697 8698 8699 8700 8701 8702 8703 8704 8705 8706 8707 8708 8709 8710 8711 8712 8713 8714 8715 8716 8717 8718 8719 8720 8721 8722 8723 8724 8725 8726 8727 8728 8729 8730 8731 8732 8733 8734 8735 8736 8737 8738 8739 8740 8741 8742 8743 8744 8745 8746 8747 8748 8749 8750 8751 8752 8753 8754 8755 8756 8757 8758 8759 8760 8761 8762 8763 8764 8765 8766 8767 8768 8769 8770 8771 8772 8773 8774 8775 8776 8777 8778 8779 8780 8781 8782 8783 8784 8785 8786 8787 8788 8789 8790 8791 8792 8793 8794 8795 8796 8797 8798 8799 8800 8801 8802 8803 8804 8805 8806 8807 8808 8809 8810 8811 8812 8813 8814 8815 8816 8817 8818 8819 8820 8821 8822 8823 8824 8825 8826 8827 8828 8829 8830 8831 8832 8833 8834 8835 8836 8837 8838 8839 8840 8841 8842 8843 8844 8845 8846 8847 8848 8849 8850 8851 8852 8853 8854 8855 8856 8857 8858 8859 8860 8861 8862 8863 8864 8865 8866 8867 8868 8869 8870 8871 8872 8873 8874 8875 8876 8877 8878 8879 8880 8881 8882 8883 8884 8885 8886 8887 8888 8889 8890 8891 8892 8893 8894 8895 8896 8897 8898 8899 8900 8901 8902 8903 8904 8905 8906 8907 8908 8909 8910 8911 8912 8913 8914 8915 8916 8917 8918 8919 8920 8921 8922 8923 8924 8925 8926 8927 8928 8929 8930 8931 8932 8933 8934 8935 8936 8937 8938 8939 8940 8941 8942 8943 8944 8945 8946 8947 8948 8949 8950 8951 8952 8953 8954 8955 8956 8957 8958 8959 8960 8961 8962 8963 8964 8965 8966 8967 8968 8969 8970 8971 8972 8973 8974 8975 8976 8977 8978 8979 8980 8981 8982 8983 8984 8985 8986 8987 8988 8989 8990 8991 8992 8993 8994 8995 8996 8997 8998 8999 9000 9001 9002 9003 9004 9005 9006 9007 9008 9009 9010 9011 9012 9013 9014 9015 9016 9017 9018 9019 9020 9021 9022 9023 9024 9025 9026 9027 9028 9029 9030 9031 9032 9033 9034 9035 9036 9037 9038 9039 9040 9041 9042 9043 9044 9045 9046 9047 9048 9049 9050 9051 9052 9053 9054 9055 9056 9057 9058 9059 9060 9061 9062 9063 9064 9065 9066 9067 9068 9069 9070 9071 9072 9073 9074 9075 9076 9077 9078 9079 9080 9081 9082 9083 9084 9085 9086 9087 9088 9089 9090 9091 9092 9093 9094 9095 9096 9097 9098 9099 9100 9101 9102 9103 9104 9105 9106 9107 9108 9109 9110 9111 9112 9113 9114 9115 9116 9117 9118 9119 9120 9121 9122 9123 9124 9125 9126 9127 9128 9129 9130 9131 9132 9133 9134 9135 9136 9137 9138 9139 9140 9141 9142 9143 9144 9145 9146 9147 9148 9149 9150 9151 9152 9153 9154 9155 9156 9157 9158 9159 9160 9161 9162 9163 9164 9165 9166 9167 9168 9169 9170 9171 9172 9173 9174 9175 9176 9177 9178 9179 9180 9181 9182 9183 9184 9185 9186 9187 9188 9189 9190 9191 9192 9193 9194 9195 9196 9197 9198 9199 9200 9201 9202 9203 9204 9205 9206 9207 9208 9209 9210 9211 9212 9213 9214 9215 9216 9217 9218 9219 9220 9221 9222 9223 9224 9225 9226 9227 9228 9229 9230 9231 9232 9233 9234 9235 9236 9237 9238 9239 9240 9241 9242 9243 9244 9245 9246 9247 9248 9249 9250 9251 9252 9253 9254 9255 9256 9257 9258 9259 9260 9261 9262 9263 9264 9265 9266 9267 9268 9269 9270 9271 9272 9273 9274 9275 9276 9277 9278 9279 9280 9281 9282 9283 9284 9285 9286 9287 9288 9289 9290 9291 9292 9293 9294 9295 9296 9297 9298 9299 9300 9301 9302 9303 9304 9305 9306 9307 9308 9309 9310 9311 9312 9313 9314 9315 9316 9317 9318 9319 9320 9321 9322 9323 9324 9325 9326 9327 9328 9329 9330 9331 9332 9333 9334 9335 9336 9337 9338 9339 9340 9341 9342 9343 9344 9345 9346 9347 9348 9349 9350 9351 9352 9353 9354 9355 9356 9357 9358 9359 9360 9361 9362 9363 9364 9365 9366 9367 9368 9369 9370 9371 9372 9373 9374 9375 9376 9377 9378 9379 9380 9381 9382 9383 9384 9385 9386 9387 9388 9389 9390 9391 9392 9393 9394 9395 9396 9397 9398 9399 9400 9401 9402 9403 9404 9405 9406 9407 9408 9409 9410 9411 9412 9413 9414 9415 9416 9417 9418 9419 9420 9421 9422 9423 9424 9425 9426 9427 9428 9429 9430 9431 9432 9433 9434 9435 9436 9437 9438 9439 9440 9441 9442 9443 9444 9445 9446 9447 9448 9449 9450 9451 9452 9453 9454 9455 9456 9457 9458 9459 9460 9461 9462 9463 9464 9465 9466 9467 9468 9469 9470 9471 9472 9473 9474 9475 9476 9477 9478 9479 9480 9481 9482 9483 9484 9485 9486 9487 9488 9489 9490 9491 9492 9493 9494 9495 9496 9497 9498 9499 9500 9501 9502 9503 9504 9505 9506 9507 9508 9509 9510 9511 9512 9513 9514 9515 9516 9517 9518 9519 9520 9521 9522 9523 9524 9525 9526 9527 9528 9529 9530 9531 9532 9533 9534 9535 9536 9537 9538 9539 9540 9541 9542 9543 9544 9545 9546 9547 9548 9549 9550 9551 9552 9553 9554 9555 9556 9557 9558 9559 9560 9561 9562 9563 9564 9565 9566 9567 9568 9569 9570 9571 9572 9573 9574 9575 9576 9577 9578 9579 9580 9581 9582 9583 9584 9585 9586 9587 9588 9589 9590 9591 9592 9593 9594 9595 9596 9597 9598 9599 9600 9601 9602 9603 9604 9605 9606 9607 9608 9609 9610 9611 9612 9613 9614 9615 9616 9617 9618 9619 9620 9621 9622 9623 9624 9625 9626 9627 9628 9629 9630 9631 9632 9633 9634 9635 9636 9637 9638 9639 9640 9641 9642 9643 9644 9645 9646 9647 9648 9649 9650 9651 9652 9653 9654 9655 9656 9657 9658 9659 9660 9661 9662 9663 9664 9665 9666 9667 9668 9669 9670 9671 9672 9673 9674 9675 9676 9677 9678 9679 9680 9681 9682 9683 9684 9685 9686 9687 9688 9689 9690 9691 9692 9693 9694 9695 9696 9697 9698 9699 9700 9701 9702 9703 9704 9705 9706 9707 9708 9709 9710 9711 9712 9713 9714 9715 9716 9717 9718 9719 9720 9721 9722 9723 9724 9725 9726 9727 9728 9729 9730 9731 9732 9733 9734 9735 9736 9737 9738 9739 9740 9741 9742 9743 9744 9745 9746 9747 9748 9749 9750 9751 9752 9753 9754 9755 9756 9757 9758 9759 9760 9761 9762 9763 9764 9765 9766 9767 9768 9769 9770 9771 9772 9773 9774 9775 9776 9777 9778 9779 9780 9781 9782 9783 9784 9785 9786 9787 9788 9789 9790 9791 9792 9793 9794 9795 9796 9797 9798 9799 9800 9801 9802 9803 9804 9805 9806 9807 9808 9809 9810 9811 9812 9813 9814 9815 9816 9817 9818 9819 9820 9821 9822 9823 9824 9825 9826 9827 9828 9829 9830 9831 9832 9833 9834 9835 9836 9837 9838 9839 9840 9841 9842 9843 9844 9845 9846 9847 9848 9849 9850 9851 9852 9853 9854 9855 9856 9857 9858 9859 9860 9861 9862 9863 9864 9865 9866 9867 9868 9869 9870 9871 9872 9873 9874 9875 9876 9877 9878 9879 9880 9881 9882 9883 9884 9885 9886 9887 9888 9889 9890 9891 9892 9893 9894 9895 9896 9897 9898 9899 9900 9901 9902 9903 9904 9905 9906 9907 9908 9909 9910 9911 9912 9913 9914 9915 9916 9917 9918 9919 9920 9921 9922 9923 9924 9925 9926 9927 9928 9929 9930 9931 9932 9933 9934 9935 9936 9937 9938 9939 9940 9941 9942 9943 9944 9945 9946 9947 9948 9949 9950 9951 9952 9953 9954 9955 9956 9957 9958 9959 9960 9961 9962 9963 9964 9965 9966 9967 9968 9969 9970 9971 9972 9973 9974 9975 9976 9977 9978 9979 9980 9981 9982 9983 9984 9985 9986 9987 9988 9989 9990 9991 9992 9993 9994 9995 9996 9997 9998 9999 10000 10001 10002 10003 10004 10005 10006 10007 10008 10009 10010 10011 10012 10013 10014 10015 10016 10017 10018 10019 10020 10021 10022 10023 10024 10025 10026 10027 10028 10029 10030 10031 10032 10033 10034 10035 10036 10037 10038 10039 10040 10041 10042 10043 10044 10045 10046 10047 10048 10049 10050 10051 10052 10053 10054 10055 10056 10057 10058 10059 10060 10061 10062 10063 10064 10065 10066 10067 10068 10069 10070 10071 10072 10073 10074 10075 10076 10077 10078 10079 10080 10081 10082 10083 10084 10085 10086 10087 10088 10089 10090 10091 10092 10093 10094 10095 10096 10097 10098 10099 10100 10101 10102 10103 10104 10105 10106 10107 10108 10109 10110 10111 10112 10113 10114 10115 10116 10117 10118 10119 10120 10121 10122 10123 10124 10125 10126 10127 10128 10129 10130 10131 10132 10133 10134 10135 10136 10137 10138 10139 10140 10141 10142 10143 10144 10145 10146 10147 10148 10149 10150 10151 10152 10153 10154 10155 10156 10157 10158 10159 10160 10161 10162 10163 10164 10165 10166 10167 10168 10169 10170 10171 10172 10173 10174 10175 10176 10177 10178 10179 10180 10181 10182 10183 10184 10185 10186 10187 10188 10189 10190 10191 10192 10193 10194 10195 10196 10197 10198 10199 10200 10201 10202 10203 10204 10205 10206 10207 10208 10209 10210 10211 10212 10213 10214 10215 10216 10217 10218 10219 10220 10221 10222 10223 10224 10225 10226 10227 10228 10229 10230 10231 10232 10233 10234 10235 10236 10237 10238 10239 10240 10241 10242 10243 10244 10245 10246 10247 10248 10249 10250 10251 10252 10253 10254 10255 10256 10257 10258 10259 10260 10261 10262 10263 10264 10265 10266 10267 10268 10269 10270 10271 10272 10273 10274 10275 10276 10277 10278 10279 10280 10281 10282 10283 10284 10285 10286 10287 10288 10289 10290 10291 10292 10293 10294 10295 10296 10297 10298 10299 10300 10301 10302 10303 10304 10305 10306 10307 10308 10309 10310 10311 10312 10313 10314 10315 10316 10317 10318 10319 10320 10321 10322 10323 10324 10325 10326 10327 10328 10329 10330 10331 10332 10333 10334 10335 10336 10337 10338 10339 10340 10341 10342 10343 10344 10345 10346 10347 10348 10349 10350 10351 10352 10353 10354 10355 10356 10357 10358 10359 10360 10361 10362 10363 10364 10365 10366 10367 10368 10369 10370 10371 10372 10373 10374 10375 10376 10377 10378 10379 10380 10381 10382 10383 10384 10385 10386 10387 10388 10389 10390 10391 10392 10393 10394 10395 10396 10397 10398 10399 10400 10401 10402 10403 10404 10405 10406 10407 10408 10409 10410 10411 10412 10413 10414 10415 10416 10417 10418 10419 10420 10421 10422 10423 10424 10425 10426 10427 10428 10429 10430 10431 10432 10433 10434 10435 10436 10437 10438 10439 10440 10441 10442 10443 10444 10445 10446 10447 10448 10449 10450 10451 10452 10453 10454 10455 10456 10457 10458 10459 10460 10461 10462 10463 10464 10465 10466 10467 10468 10469 10470 10471 10472 10473 10474 10475 10476 10477 10478 10479 10480 10481 10482 10483 10484 10485 10486 10487 10488 10489 10490 10491 10492 10493 10494 10495 10496 10497 10498 10499 10500 10501 10502 10503 10504 10505 10506 10507 10508 10509 10510 10511 10512 10513 10514 10515 10516 10517 10518 10519 10520 10521 10522 10523 10524 10525 10526 10527 10528 10529 10530 10531 10532 10533 10534 10535 10536 10537 10538 10539 10540 10541 10542 10543 10544 10545 10546 10547 10548 10549 10550 10551 10552 10553 10554 10555 10556 10557 10558 10559 10560 10561 10562 10563 10564 10565 10566 10567 10568 10569 10570 10571 10572 10573 10574 10575 10576 10577 10578 10579 10580 10581 10582 10583 10584 10585 10586 10587 10588 10589 10590 10591 10592 10593 10594 10595 10596 10597 10598 10599 10600 10601 10602 10603 10604 10605 10606 10607 10608 10609 10610 10611 10612 10613 10614 10615 10616 10617 10618 10619 10620 10621 10622 10623 10624 10625 10626 10627 10628 10629 10630 10631 10632 10633 10634 10635 10636 10637 10638 10639 10640 10641 10642 10643 10644 10645 10646 10647 10648 10649 10650 10651 10652 10653 10654 10655 10656 10657 10658 10659 10660 10661 10662 10663 10664 10665 10666 10667 10668 10669 10670 10671 10672 10673 10674 10675 10676 10677 10678 10679 10680 10681 10682 10683 10684 10685 10686 10687 10688 10689 10690 10691 10692 10693 10694 10695 10696 10697 10698 10699 10700 10701 10702 10703 10704 10705 10706 10707 10708 10709 10710 10711 10712 10713 10714 10715 10716 10717 10718 10719 10720 10721 10722 10723 10724 10725 10726 10727 10728 10729 10730 10731 10732 10733 10734 10735 10736 10737 10738 10739 10740 10741 10742 10743 10744 10745 10746 10747 10748 10749 10750 10751 10752 10753 10754 10755 10756 10757 10758 10759 10760 10761 10762 10763 10764 10765 10766 10767 10768 10769 10770 10771 10772 10773 10774 10775 10776 10777 10778 10779 10780 10781 10782 10783 10784 10785 10786 10787 10788 10789 10790 10791 10792 10793 10794 10795 10796 10797 10798 10799 10800 10801 10802 10803 10804 10805 10806 10807 10808 10809 10810 10811 10812 10813 10814 10815 10816 10817 10818 10819 10820 10821 10822 10823 10824 10825 10826 10827 10828 10829 10830 10831 10832 10833 10834 10835 10836 10837 10838 10839 10840 10841 10842 10843 10844 10845 10846 10847 10848 10849 10850 10851 10852 10853 10854 10855 10856 10857 10858 10859 10860 10861 10862 10863 10864 10865 10866 10867 10868 10869 10870 10871 10872 10873 10874 10875 10876 10877 10878 10879 10880 10881 10882 10883 10884 10885 10886 10887 10888 10889 10890 10891 10892 10893 10894 10895 10896 10897 10898 10899 10900 10901 10902 10903 10904 10905 10906 10907 10908 10909 10910 10911 10912 10913 10914 10915 10916 10917 10918 10919 10920 10921 10922 10923 10924 10925 10926 10927 10928 10929 10930 10931 10932 10933 10934 10935 10936 10937 10938 10939 10940 10941 10942 10943 10944 10945 10946 10947 10948 10949 10950 10951 10952 10953 10954 10955 10956 10957 10958 10959 10960 10961 10962 10963 10964 10965 10966 10967 10968 10969 10970 10971 10972 10973 10974 10975 10976 10977 10978 10979 10980 10981 10982 10983 10984 10985 10986 10987 10988 10989 10990 10991 10992 10993 10994 10995 10996 10997 10998 10999 11000 11001 11002 11003 11004 11005 11006 11007 11008 11009 11010 11011 11012 11013 11014 11015 11016 11017 11018 11019 11020 11021 11022 11023 11024 11025 11026 11027 11028 11029 11030 11031 11032 11033 11034 11035 11036 11037 11038 11039 11040 11041 11042 11043 11044 11045 11046 11047 11048 11049 11050 11051 11052 11053 11054 11055 11056 11057 11058 11059 11060 11061 11062 11063 11064 11065 11066 11067 11068 11069 11070 11071 11072 11073 11074 11075 11076 11077 11078 11079 11080 11081 11082 11083 11084 11085 11086 11087 11088 11089 11090 11091 11092 11093 11094 11095 11096 11097 11098 11099 11100 11101 11102 11103 11104 11105 11106 11107 11108 11109 11110 11111 11112 11113 11114 11115 11116 11117 11118 11119 11120 11121 11122 11123 11124 11125 11126 11127 11128 11129 11130 11131 11132 11133 11134 11135 11136 11137 11138 11139 11140 11141 11142 11143 11144 11145 11146 11147 11148 11149 11150 11151 11152 11153 11154 11155 11156 11157 11158 11159 11160 11161 11162 11163 11164 11165 11166 11167 11168 11169 11170 11171 11172 11173 11174 11175 11176 11177 11178 11179 11180 11181 11182 11183 11184 11185 11186 11187 11188 11189 11190 11191 11192 11193 11194 11195 11196 11197 11198 11199 11200 11201 11202 11203 11204 11205 11206 11207 11208 11209 11210 11211 11212 11213 11214 11215 11216 11217 11218 11219 11220 11221 11222 11223 11224 11225 11226 11227 11228 11229 11230 11231 11232 11233 11234 11235 11236 11237 11238 11239 11240 11241 11242 11243 11244 11245 11246 11247 11248 11249 11250 11251 11252 11253 11254 11255 11256 11257 11258 11259 11260 11261 11262 11263 11264 11265 11266 11267 11268 11269 11270 11271 11272 11273 11274 11275 11276 11277 11278 11279 11280 11281 11282 11283 11284 11285 11286 11287 11288 11289 11290 11291 11292 11293 11294 11295 11296 11297 11298 11299 11300 11301 11302 11303 11304 11305 11306 11307 11308 11309 11310 11311 11312 11313 11314 11315 11316 11317 11318 11319 11320 11321 11322 11323 11324 11325 11326 11327 11328 11329 11330 11331 11332 11333 11334 11335 11336 11337 11338 11339 11340 11341 11342 11343 11344 11345 11346 11347 11348 11349 11350 11351 11352 11353 11354 11355 11356 11357 11358 11359 11360 11361 11362 11363 11364 11365 11366 11367 11368 11369 11370 11371 11372 11373 11374 11375 11376 11377 11378 11379 11380 11381 11382 11383 11384 11385 11386 11387 11388 11389 11390 11391 11392 11393 11394 11395 11396 11397 11398 11399 11400 11401 11402 11403 11404 11405 11406 11407 11408 11409 11410 11411 11412 11413 11414 11415 11416 11417 11418 11419 11420 11421 11422 11423 11424 11425 11426 11427 11428 11429 11430 11431 11432 11433 11434 11435 11436 11437 11438 11439 11440 11441 11442 11443 11444 11445 11446 11447 11448 11449 11450 11451 11452 11453 11454 11455 11456 11457 11458 11459 11460 11461 11462 11463 11464 11465 11466 11467 11468 11469 11470 11471 11472 11473 11474 11475 11476 11477 11478 11479 11480 11481 11482 11483 11484 11485 11486 11487 11488 11489 11490 11491 11492 11493 11494 11495 11496 11497 11498 11499 11500 11501 11502 11503 11504 11505 11506 11507 11508 11509 11510 11511 11512 11513 11514 11515 11516 11517 11518 11519 11520 11521 11522 11523 11524 11525 11526 11527 11528 11529 11530 11531 11532 11533 11534 11535 11536 11537 11538 11539 11540 11541 11542 11543 11544 11545 11546 11547 11548 11549 11550 11551 11552 11553 11554 11555 11556 11557 11558 11559 11560 11561 11562 11563 11564 11565 11566 11567 11568 11569 11570 11571 11572 11573 11574 11575 11576 11577 11578 11579 11580 11581 11582 11583 11584 11585 11586 11587 11588 11589 11590 11591 11592 11593 11594 11595 11596 11597 11598 11599 11600 11601 11602 11603 11604 11605 11606 11607 11608 11609 11610 11611 11612 11613 11614 11615 11616 11617 11618 11619 11620 11621 11622 11623 11624 11625 11626 11627 11628 11629 11630 11631 11632 11633 11634 11635 11636 11637 11638 11639 11640 11641 11642 11643 11644 11645 11646 11647 11648 11649 11650 11651 11652 11653 11654 11655 11656 11657 11658 11659 11660 11661 11662 11663 11664 11665 11666 11667 11668 11669 11670 11671 11672 11673 11674 11675 11676 11677 11678 11679 11680 11681 11682 11683 11684 11685 11686 11687 11688 11689 11690 11691 11692 11693 11694 11695 11696 11697 11698 11699 11700 11701 11702 11703 11704 11705 11706 11707 11708 11709 11710 11711 11712 11713 11714 11715 11716 11717 11718 11719 11720 11721 11722 11723 11724 11725 11726 11727 11728 11729 11730 11731 11732 11733 11734 11735 11736 11737 11738 11739 11740 11741 11742 11743 11744 11745 11746 11747 11748 11749 11750 11751 11752 11753 11754 11755 11756 11757 11758 11759 11760 11761 11762 11763 11764 11765 11766 11767 11768 11769 11770 11771 11772 11773 11774 11775 11776 11777 11778 11779 11780 11781 11782 11783 11784 11785 11786 11787 11788 11789 11790 11791 11792 11793 11794 11795 11796 11797 11798 11799 11800 11801 11802 11803 11804 11805 11806 11807 11808 11809 11810 11811 11812 11813 11814 11815 11816 11817 11818 11819 11820 11821 11822 11823 11824 11825 11826 11827 11828 11829 11830 11831 11832 11833 11834 11835 11836 11837 11838 11839 11840 11841 11842 11843 11844 11845 11846 11847 11848 11849 11850 11851 11852 11853 11854 11855 11856 11857 11858 11859 11860 11861 11862 11863 11864 11865 11866 11867 11868 11869 11870 11871 11872 11873 11874 11875 11876 11877 11878 11879 11880 11881 11882 11883 11884 11885 11886 11887 11888 11889 11890 11891 11892 11893 11894 11895 11896 11897 11898 11899 11900 11901 11902 11903 11904 11905 11906 11907 11908 11909 11910 11911 11912 11913 11914 11915 11916 11917 11918 11919 11920 11921 11922 11923 11924 11925 11926 11927 11928 11929 11930 11931 11932 11933 11934 11935 11936 11937 11938 11939 11940 11941 11942 11943 11944 11945 11946 11947 11948 11949 11950 11951 11952 11953 11954 11955 11956 11957 11958 11959 11960 11961 11962 11963 11964 11965 11966 11967 11968 11969 11970 11971 11972 11973 11974 11975 11976 11977 11978 11979 11980 11981 11982 11983 11984 11985 11986 11987 11988 11989 11990 11991 11992 11993 11994 11995 11996 11997 11998 11999 12000 12001 12002 12003 12004 12005 12006 12007 12008 12009 12010 12011 12012 12013 12014 12015 12016 12017 12018 12019 12020 12021 12022 12023 12024 12025 12026 12027 12028 12029 12030 12031 12032 12033 12034 12035 12036 12037 12038 12039 12040 12041 12042 12043 12044 12045 12046 12047 12048 12049 12050 12051 12052 12053 12054 12055 12056 12057 12058 12059 12060 12061 12062 12063 12064 12065 12066 12067 12068 12069 12070 12071 12072 12073 12074 12075 12076 12077 12078 12079 12080 12081 12082 12083 12084 12085 12086 12087 12088 12089 12090 12091 12092 12093 12094 12095 12096 12097 12098 12099 12100 12101 12102 12103 12104 12105 12106 12107 12108 12109 12110 12111 12112 12113 12114 12115 12116 12117 12118 12119 12120 12121 12122 12123 12124 12125 12126 12127 12128 12129 12130 12131 12132 12133 12134 12135 12136 12137 12138 12139 12140 12141 12142 12143 12144 12145 12146 12147 12148 12149 12150 12151 12152 12153 12154 12155 12156 12157 12158 12159 12160 12161 12162 12163 12164 12165 12166 12167 12168 12169 12170 12171 12172 12173 12174 12175 12176 12177 12178 12179 12180 12181 12182 12183 12184 12185 12186 12187 12188 12189 12190 12191 12192 12193 12194 12195 12196 12197 12198 12199 12200 12201 12202 12203 12204 12205 12206 12207 12208 12209 12210 12211 12212 12213 12214 12215 12216 12217 12218 12219 12220 12221 12222 12223 12224 12225 12226 12227 12228 12229 12230 12231 12232 12233 12234 12235 12236 12237 12238 12239 12240 12241 12242 12243 12244 12245 12246 12247 12248 12249 12250 12251 12252 12253 12254 12255 12256 12257 12258 12259 12260 12261 12262 12263 12264 12265 12266 12267 12268 12269 12270 12271 12272 12273 12274 12275 12276 12277 12278 12279 12280 12281 12282 12283 12284 12285 12286 12287 12288 12289 12290 12291 12292 12293 12294 12295 12296 12297 12298 12299 12300 12301 12302 12303 12304 12305 12306 12307 12308 12309 12310 12311 12312 12313 12314 12315 12316 12317 12318 12319 12320 12321 12322 12323 12324 12325 12326 12327 12328 12329 12330 12331 12332 12333 12334 12335 12336 12337 12338 12339 12340 12341 12342 12343 12344 12345 12346 12347 12348 12349 12350 12351 12352 12353 12354 12355 12356 12357 12358 12359 12360 12361 12362 12363 12364 12365 12366 12367 12368 12369 12370 12371 12372 12373 12374 12375 12376 12377 12378 12379 12380 12381 12382 12383 12384 12385 12386 12387 12388 12389 12390 12391 12392 12393 12394 12395 12396 12397 12398 12399 12400 12401 12402 12403 12404 12405 12406 12407 12408 12409 12410 12411 12412 12413 12414 12415 12416 12417 12418 12419 12420 12421 12422 12423 12424 12425 12426 12427 12428 12429 12430 12431 12432 12433 12434 12435 12436 12437 12438 12439 12440 12441 12442 12443 12444 12445 12446 12447 12448 12449 12450 12451 12452 12453 12454 12455 12456 12457 12458 12459 12460 12461 12462 12463 12464 12465 12466 12467 12468 12469 12470 12471 12472 12473 12474 12475 12476 12477 12478 12479 12480 12481 12482 12483 12484 12485 12486 12487 12488 12489 12490 12491 12492 12493 12494 12495 12496 12497 12498 12499 12500 12501 12502 12503 12504 12505 12506 12507 12508 12509 12510 12511 12512 12513 12514 12515 12516 12517 12518 12519 12520 12521 12522 12523 12524 12525 12526 12527 12528 12529 12530 12531 12532 12533 12534 12535 12536 12537 12538 12539 12540 12541 12542 12543 12544 12545 12546 12547 12548 12549 12550 12551 12552 12553 12554 12555 12556 12557 12558 12559 12560 12561 12562 12563 12564 12565 12566 12567 12568 12569 12570 12571 12572 12573 12574 12575 12576 12577 12578 12579 12580 12581 12582 12583 12584 12585 12586 12587 12588 12589 12590 12591 12592 12593 12594 12595 12596 12597 12598 12599 12600 12601 12602 12603 12604 12605 12606 12607 12608 12609 12610 12611 12612 12613 12614 12615 12616 12617 12618 12619 12620 12621 12622 12623 12624 12625 12626 12627 12628 12629 12630 12631 12632 12633 12634 12635 12636 12637 12638 12639 12640 12641 12642 12643 12644 12645 12646 12647 12648 12649 12650 12651 12652 12653 12654 12655 12656 12657 12658 12659 12660 12661 12662 12663 12664 12665 12666 12667 12668 12669 12670 12671 12672 12673 12674 12675 12676 12677 12678 12679 12680 12681 12682 12683 12684 12685 12686 12687 12688 12689 12690 12691 12692 12693 12694 12695 12696 12697 12698 12699 12700 12701 12702 12703 12704 12705 12706 12707 12708 12709 12710 12711 12712 12713 12714 12715 12716 12717 12718 12719 12720 12721 12722 12723 12724 12725 12726 12727 12728 12729 12730 12731 12732 12733 12734 12735 12736 12737 12738 12739 12740 12741 12742 12743 12744 12745 12746 12747 12748 12749 12750 12751 12752 12753 12754 12755 12756 12757 12758 12759 12760 12761 12762 12763 12764 12765 12766 12767 12768 12769 12770 12771 12772 12773 12774 12775 12776 12777 12778 12779 12780 12781 12782 12783 12784 12785 12786 12787 12788 12789 12790 12791 12792 12793 12794 12795 12796 12797 12798 12799 12800 12801 12802 12803 12804 12805 12806 12807 12808 12809 12810 12811 12812 12813 12814 12815 12816 12817 12818 12819 12820 12821 12822 12823 12824 12825 12826 12827 12828 12829 12830 12831 12832 12833 12834 12835 12836 12837 12838 12839 12840 12841 12842 12843 12844 12845 12846 12847 12848 12849 12850 12851 12852 12853 12854 12855 12856 12857 12858 12859 12860 12861 12862 12863 12864 12865 12866 12867 12868 12869 12870 12871 12872 12873 12874 12875 12876 12877 12878 12879 12880 12881 12882 12883 12884 12885 12886 12887 12888 12889 12890 12891 12892 12893 12894 12895 12896 12897 12898 12899 12900 12901 12902 12903 12904 12905 12906 12907 12908 12909 12910 12911 12912 12913 12914 12915 12916 12917 12918 12919 12920 12921 12922 12923 12924 12925 12926 12927 12928 12929 12930 12931 12932 12933 12934 12935 12936 12937 12938 12939 12940 12941 12942 12943 12944 12945 12946 12947 12948 12949 12950 12951 12952 12953 12954 12955 12956 12957 12958 12959 12960 12961 12962 12963 12964 12965 12966 12967 12968 12969 12970 12971 12972 12973 12974 12975 12976 12977 12978 12979 12980 12981 12982 12983 12984 12985 12986 12987 12988 12989 12990 12991 12992 12993 12994 12995 12996 12997 12998 12999 13000 13001 13002 13003 13004 13005 13006 13007 13008 13009 13010 13011 13012 13013 13014 13015 13016 13017 13018 13019 13020 13021 13022 13023 13024 13025 13026 13027 13028 13029 13030 13031 13032 13033 13034 13035 13036 13037 13038 13039 13040 13041 13042 13043 13044 13045 13046 13047 13048 13049 13050 13051 13052 13053 13054 13055 13056 13057 13058 13059 13060 13061 13062 13063 13064 13065 13066 13067 13068 13069 13070 13071 13072 13073 13074 13075 13076 13077 13078 13079 13080 13081 13082 13083 13084 13085 13086 13087 13088 13089 13090 13091 13092 13093 13094 13095 13096 13097 13098 13099 13100 13101 13102 13103 13104 13105 13106 13107 13108 13109 13110 13111 13112 13113 13114 13115 13116 13117 13118 13119 13120 13121 13122 13123 13124 13125 13126 13127 13128 13129 13130 13131 13132 13133 13134 13135 13136 13137 13138 13139 13140 13141 13142 13143 13144 13145 13146 13147 13148 13149 13150 13151 13152 13153 13154 13155 13156 13157 13158 13159 13160 13161 13162 13163 13164 13165 13166 13167 13168 13169 13170 13171 13172 13173 13174 13175 13176 13177 13178 13179 13180 13181 13182 13183 13184 13185 13186 13187 13188 13189 13190 13191 13192 13193 13194 13195 13196 13197 13198 13199 13200 13201 13202 13203 13204 13205 13206 13207 13208 13209 13210 13211 13212 13213 13214 13215 13216 13217 13218 13219 13220 13221 13222 13223 13224 13225 13226 13227 13228 13229 13230 13231 13232 13233 13234 13235 13236 13237 13238 13239 13240 13241 13242 13243 13244 13245 13246 13247 13248 13249 13250 13251 13252 13253 13254 13255 13256 13257 13258 13259 13260 13261 13262 13263 13264 13265 13266 13267 13268 13269 13270 13271 13272 13273 13274 13275 13276 13277 13278 13279 13280 13281 13282 13283 13284 13285 13286 13287 13288 13289 13290 13291 13292
|
// tapset resolution
// Copyright (C) 2005-2020 Red Hat Inc.
// Copyright (C) 2005-2007 Intel Corporation.
// Copyright (C) 2008 James.Bottomley@HansenPartnership.com
//
// 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 "staptree.h"
#include "elaborate.h"
#include "tapsets.h"
#include "task_finder.h"
#include "tapset-dynprobe.h"
#include "translate.h"
#include "session.h"
#include "util.h"
#include "buildrun.h"
#include "dwarf_wrappers.h"
#include "hash.h"
#include "dwflpp.h"
#include "setupdwfl.h"
#include "loc2stap.h"
#include "analysis.h"
#include <gelf.h>
#include "sdt_types.h"
#include "stringtable.h"
#include <cstdlib>
#include <algorithm>
#include <deque>
#include <iostream>
#include <fstream>
#include <map>
#include <set>
#include <sstream>
#include <stdexcept>
#include <vector>
#include <stack>
#include <cstdarg>
#include <cassert>
#include <iomanip>
#include <cerrno>
extern "C" {
#include <fcntl.h>
#include <elfutils/libdwfl.h>
#include <elfutils/libdw.h>
#include <dwarf.h>
#include <elf.h>
#include <obstack.h>
#include <glob.h>
#include <fnmatch.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <math.h>
#include <regex.h>
#include <unistd.h>
#define __STDC_FORMAT_MACROS
#include <inttypes.h>
}
using namespace std;
using namespace __gnu_cxx;
// for elf.h where PPC64_LOCAL_ENTRY_OFFSET isn't defined
#ifndef PPC64_LOCAL_ENTRY_OFFSET
#define STO_PPC64_LOCAL_BIT 5
#define STO_PPC64_LOCAL_MASK (7 << STO_PPC64_LOCAL_BIT)
#define PPC64_LOCAL_ENTRY_OFFSET(other) \
(((1 << (((other) & STO_PPC64_LOCAL_MASK) >> STO_PPC64_LOCAL_BIT)) >> 2) << 2)
#endif
// for elf.h where EF_PPC64_ABI isn't defined
#ifndef EF_PPC64_ABI
#define EF_PPC64_ABI 3
#endif
// ------------------------------------------------------------------------
string
common_probe_init (derived_probe* p)
{
assert(p->session_index != (unsigned)-1);
return "(&stap_probes[" + lex_cast(p->session_index) + "])";
}
void
common_probe_entryfn_prologue (systemtap_session& s,
string statestr, string statestr2, string probe,
string probe_type, bool overload_processing,
void (*declaration_callback)(systemtap_session& s, void *data),
void (*pre_context_callback)(systemtap_session& s, void *data),
void *callback_data)
{
if (s.runtime_usermode_p())
{
// If session_state() is NULL, then we haven't even initialized shm yet,
// and there's *nothing* for the probe to do. (even alibi is in shm)
// So failure skips this whole block through the end of the epilogue.
s.op->newline() << "if (likely(session_state())) {";
s.op->indent(1);
}
s.op->newline() << "#ifdef STP_ALIBI";
s.op->newline() << "atomic_inc(probe_alibi(" << probe << "->index));";
s.op->newline() << "#else";
if (s.runtime_usermode_p())
s.op->newline() << "int _stp_saved_errno = errno;";
s.op->newline() << "struct context* __restrict__ c = NULL;";
s.op->newline() << "#if !INTERRUPTIBLE";
s.op->newline() << "unsigned long flags;";
s.op->newline() << "#endif";
s.op->newline() << "#ifdef STP_TIMING";
s.op->newline() << "Stat stat = probe_timing(" << probe << "->index);";
s.op->newline() << "#endif";
if (declaration_callback)
declaration_callback(s, callback_data);
if (overload_processing && !s.runtime_usermode_p())
s.op->newline() << "#if defined(STP_TIMING) || defined(STP_OVERLOAD)";
else
s.op->newline() << "#ifdef STP_TIMING";
if (! s.runtime_usermode_p())
{
s.op->newline() << "#ifdef STP_TIMING_NSECS";
s.op->newline() << "s64 cycles_atstart = ktime_get_ns ();";
s.op->newline() << "#else";
s.op->newline() << "cycles_t cycles_atstart = get_cycles ();";
s.op->newline() << "#endif";
}
else
{
s.op->newline() << "struct timespec timespec_atstart;";
s.op->newline() << "(void)clock_gettime(CLOCK_MONOTONIC, ×pec_atstart);";
}
s.op->newline() << "#endif";
s.op->newline() << "#if !INTERRUPTIBLE";
if (pre_context_callback)
pre_context_callback(s, callback_data);
s.op->newline() << "local_irq_save (flags);";
s.op->newline() << "#endif";
if (! s.runtime_usermode_p())
{
// Check for enough free enough stack space
s.op->newline() << "if (unlikely ((((unsigned long) (& c)) & (THREAD_SIZE-1))"; // free space
s.op->newline(1) << "< (MINSTACKSPACE + sizeof (struct thread_info)))) {"; // needed space
// XXX: may need porting to platforms where task_struct is not
// at bottom of kernel stack NB: see also
// CONFIG_DEBUG_STACKOVERFLOW
s.op->newline() << "atomic_inc (skipped_count());";
s.op->newline() << "#ifdef STP_TIMING";
s.op->newline() << "atomic_inc (skipped_count_lowstack());";
s.op->newline() << "#endif";
s.op->newline() << "goto probe_epilogue;";
s.op->newline(-1) << "}";
}
s.op->newline() << "{";
s.op->newline(1) << "unsigned sess_state = atomic_read (session_state());";
s.op->newline() << "#ifdef DEBUG_PROBES";
s.op->newline() << "_stp_dbug(__FUNCTION__, __LINE__, \"session state: %d, "
"expecting " << statestr << " (%d)"
<< (statestr2.empty() ? "" : string(" or ") + statestr2 + " (%d)")
<< "\", sess_state, " << statestr
<< (statestr2.empty() ? "" : string(", ") + statestr2) << ");";
s.op->newline() << "#endif";
s.op->newline() << "if (sess_state != " << statestr
<< (statestr2.empty() ? "" : string(" && sess_state != ") + statestr2)
<< ")";
s.op->newline() << "goto probe_epilogue;";
s.op->newline(-1) << "}";
if (pre_context_callback)
{
s.op->newline() << "#if INTERRUPTIBLE";
pre_context_callback(s, callback_data);
s.op->newline() << "#endif";
}
s.op->newline() << "c = _stp_runtime_entryfn_get_context();";
s.op->newline() << "if (!c) {";
s.op->newline(1) << "#if !INTERRUPTIBLE";
s.op->newline() << "atomic_inc (skipped_count());";
s.op->newline() << "#endif";
s.op->newline() << "#ifdef STP_TIMING";
s.op->newline() << "atomic_inc (skipped_count_reentrant());";
s.op->newline() << "#endif";
s.op->newline() << "goto probe_epilogue;";
s.op->newline(-1) << "}";
s.op->newline();
s.op->newline() << "c->aborted = 0;";
s.op->newline() << "c->locked = 0;";
s.op->newline() << "c->last_stmt = 0;";
s.op->newline() << "c->last_error = 0;";
s.op->newline() << "c->nesting = -1;"; // NB: PR10516 packs locals[] tighter
s.op->newline() << "c->uregs = 0;";
s.op->newline() << "c->kregs = 0;";
s.op->newline() << "c->sregs = 0;";
s.op->newline() << "#if defined __ia64__";
s.op->newline() << "c->unwaddr = 0;";
s.op->newline() << "#endif";
if (s.runtime_usermode_p())
s.op->newline() << "c->probe_index = " << probe << "->index;";
s.op->newline() << "c->probe_point = " << probe << "->pp;";
s.op->newline() << "#ifdef STP_NEED_PROBE_NAME";
s.op->newline() << "c->probe_name = " << probe << "->pn;";
s.op->newline() << "#endif";
s.op->newline() << "c->probe_type = " << probe_type << ";";
// reset Individual Probe State union
s.op->newline() << "memset(&c->ips, 0, sizeof(c->ips));";
s.op->newline() << "c->user_mode_p = 0; c->full_uregs_p = 0; ";
s.op->newline() << "#ifdef STAP_NEED_REGPARM"; // i386 or x86_64 register.stp
s.op->newline() << "c->regparm = 0;";
s.op->newline() << "#endif";
if(!s.suppress_time_limits){
s.op->newline() << "#if INTERRUPTIBLE";
s.op->newline() << "c->actionremaining = MAXACTION_INTERRUPTIBLE;";
s.op->newline() << "#else";
s.op->newline() << "c->actionremaining = MAXACTION;";
s.op->newline() << "#endif";
}
// NB: The following would actually be incorrect.
// That's because cycles_sum/cycles_base values are supposed to survive
// between consecutive probes. Periodically (STP_OVERLOAD_INTERVAL
// cycles), the values will be reset.
/*
s.op->newline() << "#ifdef STP_OVERLOAD";
s.op->newline() << "c->cycles_sum = 0;";
s.op->newline() << "c->cycles_base = 0;";
s.op->newline() << "#endif";
*/
s.op->newline() << "#if defined(STP_NEED_UNWIND_DATA)";
s.op->newline() << "c->uwcache_user.state = uwcache_uninitialized;";
s.op->newline() << "c->uwcache_kernel.state = uwcache_uninitialized;";
s.op->newline() << "#endif";
s.op->newline() << "#if defined(STAP_NEED_CONTEXT_RETURNVAL)";
s.op->newline() << "c->returnval_override_p = 0;";
s.op->newline() << "c->returnval_override = 0;"; // unnecessary
s.op->newline() << "#endif";
}
void
common_probe_entryfn_epilogue (systemtap_session& s,
bool overload_processing,
bool schedule_work_safe)
{
if (!s.runtime_usermode_p()
&& schedule_work_safe)
{
// If a refresh is required, we can safely schedule_work() here
s.op->newline( 0) << "if (atomic_cmpxchg(&need_module_refresh, 1, 0) == 1)";
s.op->newline(+1) << "schedule_work(&module_refresher_work);";
s.op->indent(-1);
}
if (overload_processing && !s.runtime_usermode_p())
s.op->newline() << "#if defined(STP_TIMING) || defined(STP_OVERLOAD)";
else
s.op->newline() << "#ifdef STP_TIMING";
s.op->newline() << "{";
s.op->indent(1);
if (! s.runtime_usermode_p())
{
s.op->newline() << "#ifdef STP_TIMING_NSECS";
s.op->newline() << "s64 cycles_atend = ktime_get_ns ();";
// NB: we truncate nsecs to 64 bits. Perhaps it should be
// fewer, if the hardware counter rolls over really quickly. We
// handle 64-bit wraparound here.
s.op->newline() << "s64 cycles_elapsed = ((s64)cycles_atend > (s64)cycles_atstart)";
s.op->newline(1) << "? ((s64)cycles_atend - (s64)cycles_atstart)";
s.op->newline() << ": (~(s64)0) - (s64)cycles_atstart + (s64)cycles_atend + 1;";
s.op->newline(-1) << "#else";
s.op->newline() << "cycles_t cycles_atend = get_cycles ();";
// NB: we truncate cycles counts to 32 bits. Perhaps it should be
// fewer, if the hardware counter rolls over really quickly. We
// handle 32-bit wraparound here.
s.op->newline() << "int32_t cycles_elapsed = ((int32_t)cycles_atend > (int32_t)cycles_atstart)";
s.op->newline(1) << "? ((int32_t)cycles_atend - (int32_t)cycles_atstart)";
s.op->newline() << ": (~(int32_t)0) - (int32_t)cycles_atstart + (int32_t)cycles_atend + 1;";
s.op->newline() << "#endif";
s.op->indent(-1);
}
else
{
s.op->newline() << "struct timespec timespec_atend, timespec_elapsed;";
s.op->newline() << "long cycles_elapsed;";
s.op->newline() << "(void)clock_gettime(CLOCK_MONOTONIC, ×pec_atend);";
s.op->newline() << "_stp_timespec_sub(×pec_atend, ×pec_atstart, ×pec_elapsed);";
// 'cycles_elapsed' is really elapsed nanoseconds
s.op->newline() << "cycles_elapsed = (timespec_elapsed.tv_sec * NSEC_PER_SEC) + timespec_elapsed.tv_nsec;";
}
s.op->newline() << "#ifdef STP_TIMING";
// STP_TIMING requires min, max, avg (and thus count and sum), but not variance.
s.op->newline() << "if (likely (stat)) _stp_stat_add(stat, cycles_elapsed, 1, 1, 1, 1, 0);";
s.op->newline() << "#endif";
if (overload_processing && !s.runtime_usermode_p())
{
s.op->newline() << "#ifdef STP_OVERLOAD";
s.op->newline() << "{";
// If the cycle count has wrapped (cycles_atend > cycles_base),
// let's go ahead and pretend the interval has been reached.
// This should reset cycles_base and cycles_sum.
s.op->newline(1) << "cycles_t interval = (cycles_atend > c->cycles_base)";
s.op->newline(1) << "? (cycles_atend - c->cycles_base)";
s.op->newline() << ": (STP_OVERLOAD_INTERVAL + 1);";
s.op->newline(-1) << "c->cycles_sum += cycles_elapsed;";
// If we've spent more than STP_OVERLOAD_THRESHOLD cycles in a
// probe during the last STP_OVERLOAD_INTERVAL cycles, the probe
// has overloaded the system and we need to quit.
// NB: this is not suppressible via --suppress-runtime-errors,
// because this is a system safety metric that we cannot trust
// unprivileged users to override.
s.op->newline() << "if (interval > STP_OVERLOAD_INTERVAL) {";
s.op->newline(1) << "if (c->cycles_sum > STP_OVERLOAD_THRESHOLD) {";
s.op->newline(1) << "_stp_error (\"probe overhead (%lld cycles) exceeded threshold (%lld cycles) in last"
" %lld cycles\", (long long) c->cycles_sum, STP_OVERLOAD_THRESHOLD, STP_OVERLOAD_INTERVAL);";
s.op->newline() << "atomic_set (session_state(), STAP_SESSION_ERROR);";
s.op->newline() << "atomic_inc (error_count());";
s.op->newline(-1) << "}";
s.op->newline() << "c->cycles_base = cycles_atend;";
s.op->newline() << "c->cycles_sum = 0;";
s.op->newline(-1) << "}";
s.op->newline(-1) << "}";
s.op->newline() << "#endif";
}
s.op->newline(-1) << "}";
s.op->newline() << "#endif";
s.op->newline() << "c->probe_point = 0;"; // vacated
s.op->newline() << "#ifdef STP_NEED_PROBE_NAME";
s.op->newline() << "c->probe_name = 0;";
s.op->newline() << "#endif";
s.op->newline() << "c->probe_type = 0;";
s.op->newline() << "if (unlikely (c->last_error)) {";
s.op->indent(1);
if (s.suppress_handler_errors) // PR 13306
{
s.op->newline() << "atomic_inc (error_count());";
}
else
{
s.op->newline() << "if (c->last_stmt != NULL)";
s.op->newline(1) << "_stp_softerror (\"%s near %s\", c->last_error, c->last_stmt);";
s.op->newline(-1) << "else";
s.op->newline(1) << "_stp_softerror (\"%s\", c->last_error);";
s.op->indent(-1);
s.op->newline() << "atomic_inc (error_count());";
s.op->newline() << "if (atomic_read (error_count()) > MAXERRORS) {";
s.op->newline(1) << "atomic_set (session_state(), STAP_SESSION_ERROR);";
s.op->newline() << "_stp_exit ();";
s.op->newline(-1) << "}";
}
s.op->newline(-1) << "}";
s.op->newline(-1) << "probe_epilogue:"; // context is free
s.op->indent(1);
if (! s.suppress_handler_errors) // PR 13306
{
// Check for excessive skip counts.
s.op->newline() << "if (unlikely (atomic_read (skipped_count()) > MAXSKIPPED)) {";
s.op->newline(1) << "if (unlikely (pseudo_atomic_cmpxchg(session_state(), STAP_SESSION_RUNNING, STAP_SESSION_ERROR) == STAP_SESSION_RUNNING))";
s.op->newline() << "_stp_error (\"Skipped too many probes, check MAXSKIPPED or try again with stap -t for more details.\");";
s.op->newline(-1) << "}";
}
// We mustn't release the context until after all _stp_error(), so dyninst
// mode can still access the log buffers stored therein.
s.op->newline() << "_stp_runtime_entryfn_put_context(c);";
s.op->newline() << "#if !INTERRUPTIBLE";
s.op->newline() << "local_irq_restore (flags);";
s.op->newline() << "#endif";
if (s.runtime_usermode_p())
{
s.op->newline() << "errno = _stp_saved_errno;";
}
s.op->newline() << "#endif // STP_ALIBI";
if (s.runtime_usermode_p())
s.op->newline(-1) << "}";
}
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
// kprobes (both dwarf based and non-dwarf based) probes
// ------------------------------------------------------------------------
struct generic_kprobe_derived_probe: public derived_probe
{
generic_kprobe_derived_probe(probe *base,
probe_point *location,
interned_string module,
interned_string section,
Dwarf_Addr addr,
bool has_return,
bool has_maxactive = false,
int64_t maxactive_val = 0,
interned_string symbol_name = "",
Dwarf_Addr offset = 0);
virtual void join_group(systemtap_session&) = 0;
interned_string module;
interned_string section;
Dwarf_Addr addr;
bool has_return;
bool has_maxactive;
int64_t maxactive_val;
// PR18889: For modules, we have to probe using "symbol+offset"
// instead of using an address, otherwise we can't probe the init
// section. 'symbol_name' is the closest known symbol to 'addr' and
// 'offset' is the offset from the symbol.
interned_string symbol_name;
Dwarf_Addr offset;
unsigned saved_longs, saved_strings;
generic_kprobe_derived_probe* entry_handler;
std::string args_for_bpf() const;
interned_string sym_name_for_bpf;
};
generic_kprobe_derived_probe::generic_kprobe_derived_probe(probe *base,
probe_point *location,
interned_string module,
interned_string section,
Dwarf_Addr addr,
bool has_return,
bool has_maxactive,
int64_t maxactive_val,
interned_string symbol_name,
Dwarf_Addr offset) :
derived_probe (base, location, true /* .components soon rewritten */ ),
module(module), section(section), addr(addr), has_return(has_return),
has_maxactive(has_maxactive), maxactive_val(maxactive_val),
symbol_name(symbol_name), offset(offset),
saved_longs(0), saved_strings(0), entry_handler(0)
{
}
// ------------------------------------------------------------------------
// Dwarf derived probes. "We apologize for the inconvience."
// ------------------------------------------------------------------------
static const string TOK_KERNEL("kernel");
static const string TOK_MODULE("module");
static const string TOK_FUNCTION("function");
static const string TOK_INLINE("inline");
static const string TOK_CALL("call");
static const string TOK_EXPORTED("exported");
static const string TOK_RETURN("return");
static const string TOK_MAXACTIVE("maxactive");
static const string TOK_STATEMENT("statement");
static const string TOK_ABSOLUTE("absolute");
static const string TOK_PROCESS("process");
static const string TOK_PROVIDER("provider");
static const string TOK_MARK("mark");
static const string TOK_TRACE("trace");
static const string TOK_LABEL("label");
static const string TOK_LIBRARY("library");
static const string TOK_PLT("plt");
static const string TOK_METHOD("method");
static const string TOK_CLASS("class");;
static const string TOK_CALLEE("callee");;
static const string TOK_CALLEES("callees");;
static const string TOK_NEAREST("nearest");;
struct dwarf_query; // forward decl
static int query_cu (Dwarf_Die * cudie, dwarf_query *q);
static void query_addr(Dwarf_Addr addr, dwarf_query *q);
static void query_plt_statement(dwarf_query *q);
struct
symbol_table
{
module_info *mod_info; // associated module
unordered_multimap<interned_string, func_info*> map_by_name;
multimap<Dwarf_Addr, func_info*> map_by_addr;
unordered_map<interned_string, Dwarf_Addr> globals;
unordered_map<interned_string, Dwarf_Addr> locals;
// Section describing function descriptors.
// Set to SHN_UNDEF if there is no such section.
GElf_Word opd_section;
void add_symbol(interned_string name, bool weak, bool descriptor,
Dwarf_Addr addr, Dwarf_Addr entrypc);
enum info_status get_from_elf();
void prepare_section_rejection(Dwfl_Module *mod);
bool reject_section(GElf_Word section);
void purge_syscall_stubs();
set <func_info*> lookup_symbol(interned_string name);
set <Dwarf_Addr> lookup_symbol_address(interned_string name);
func_info *get_func_containing_address(Dwarf_Addr addr);
func_info *get_first_func();
symbol_table(module_info *mi) : mod_info(mi), opd_section(SHN_UNDEF) {}
~symbol_table();
};
static bool null_die(Dwarf_Die *die)
{
static Dwarf_Die null;
return (!die || !memcmp(die, &null, sizeof(null)));
}
enum
function_spec_type
{
function_alone,
function_and_file,
function_file_and_line
};
struct dwarf_builder;
struct dwarf_var_expanding_visitor;
// XXX: This class is a candidate for subclassing to separate
// the relocation vs non-relocation variants. Likewise for
// kprobe vs kretprobe variants.
struct dwarf_derived_probe: public generic_kprobe_derived_probe
{
dwarf_derived_probe (interned_string function,
interned_string filename,
int line,
interned_string module,
interned_string section,
Dwarf_Addr dwfl_addr,
Dwarf_Addr addr,
dwarf_query & q,
Dwarf_Die* scope_die,
interned_string symbol_name = "",
Dwarf_Addr offset = 0);
interned_string path;
bool has_process;
bool has_library;
// generic_kprobe_derived_probe_group::emit_module_decls uses this to emit sdt kprobe definition
interned_string user_path;
interned_string user_lib;
bool access_vars;
void printsig (std::ostream &o) const;
void printsig_nonest (std::ostream &o) const;
virtual void join_group (systemtap_session& s);
void emit_probe_local_init(systemtap_session& s, translator_output * o);
void getargs(std::list<std::string> &arg_set) const;
void emit_privilege_assertion (translator_output*);
void print_dupe_stamp(ostream& o);
// Pattern registration helpers.
static void register_statement_variants(match_node * root,
dwarf_builder * dw,
privilege_t privilege);
static void register_function_variants(match_node * root,
dwarf_builder * dw,
privilege_t privilege);
static void register_function_and_statement_variants(systemtap_session& s,
match_node * root,
dwarf_builder * dw,
privilege_t privilege);
static void register_sdt_variants(systemtap_session& s,
match_node * root,
dwarf_builder * dw);
static void register_plt_variants(systemtap_session& s,
match_node * root,
dwarf_builder * dw);
static void register_patterns(systemtap_session& s);
protected:
dwarf_derived_probe(probe *base,
probe_point *location,
Dwarf_Addr addr,
bool has_return):
generic_kprobe_derived_probe(base, location, "", "", addr, has_return),
has_process(0), has_library(0),
access_vars(false)
{}
private:
list<string> args;
void saveargs(dwarf_query& q, Dwarf_Die* scope_die, Dwarf_Addr dwfl_addr);
};
struct uprobe_derived_probe: public dwarf_derived_probe
{
int pid; // 0 => unrestricted
interned_string build_id_val;
GElf_Addr build_id_vaddr;
uprobe_derived_probe (interned_string function,
interned_string filename,
int line,
interned_string module,
interned_string section,
Dwarf_Addr dwfl_addr,
Dwarf_Addr addr,
dwarf_query & q,
Dwarf_Die* scope_die);
// alternate constructor for process(PID).statement(ADDR).absolute
uprobe_derived_probe (probe *base,
probe_point *location,
int pid,
Dwarf_Addr addr,
bool has_return):
dwarf_derived_probe(base, location, addr, has_return), pid(pid)
{}
void join_group (systemtap_session& s);
void emit_privilege_assertion (translator_output*);
void print_dupe_stamp(ostream& o) { print_dupe_stamp_unprivileged_process_owner (o); }
void getargs(std::list<std::string> &arg_set) const;
void saveargs(int nargs);
void emit_perf_read_handler(systemtap_session& s, unsigned i);
private:
list<string> args;
};
struct generic_kprobe_derived_probe_group: public derived_probe_group
{
friend bool sort_for_bpf(systemtap_session& s,
generic_kprobe_derived_probe_group *ge,
sort_for_bpf_probe_arg_vector &v);
private:
unordered_multimap<interned_string,generic_kprobe_derived_probe*> probes_by_module;
public:
generic_kprobe_derived_probe_group() {}
void enroll (generic_kprobe_derived_probe* probe);
void emit_module_decls (systemtap_session& s);
void emit_module_init (systemtap_session& s);
void emit_module_refresh (systemtap_session& s);
void emit_module_exit (systemtap_session& s);
bool otf_supported (systemtap_session&) { return true; }
// workqueue handling not safe in kprobes context
bool otf_safe_context (systemtap_session&) { return false; }
};
// Helper struct to thread through the dwfl callbacks.
struct base_query
{
base_query(dwflpp & dw, literal_map_t const & params);
base_query(dwflpp & dw, interned_string module_val);
virtual ~base_query() {}
systemtap_session & sess;
dwflpp & dw;
// Used to keep track of which modules were visited during
// iterate_over_modules()
set<string> visited_modules;
// Parameter extractors.
static bool has_null_param(literal_map_t const & params,
interned_string k);
static bool get_string_param(literal_map_t const & params,
interned_string k, interned_string &v);
static bool get_number_param(literal_map_t const & params,
interned_string k, int64_t & v);
static bool get_number_param(literal_map_t const & params,
interned_string k, Dwarf_Addr & v);
static void query_library_callback (base_query *me, const char *data);
static void query_plt_callback (base_query *me, const char *link, size_t addr);
virtual void query_library (const char *data) = 0;
virtual void query_plt (const char *link, size_t addr) = 0;
// Extracted parameters.
bool has_kernel;
bool has_module;
bool has_process;
bool has_library;
bool has_plt;
bool has_statement;
interned_string module_val; // has_kernel => module_val = "kernel"
interned_string path; // executable path if module is a .so
interned_string plt_val; // has_plt => plt wildcard
interned_string build_id_val; // if non-empty, buildid that resulted in resolved path
int64_t pid_val;
virtual void handle_query_module() = 0;
};
base_query::base_query(dwflpp & dw, literal_map_t const & params):
sess(dw.sess), dw(dw),
has_kernel(false), has_module(false), has_process(false),
has_library(false), has_plt(false), has_statement(false),
pid_val(0)
{
has_kernel = has_null_param (params, TOK_KERNEL);
if (has_kernel)
module_val = "kernel";
has_module = get_string_param (params, TOK_MODULE, module_val);
if (has_module)
has_process = false;
else
{
interned_string library_name;
Dwarf_Addr statement_num_val;
has_process = derived_probe_builder::has_param(params, TOK_PROCESS);
has_library = get_string_param (params, TOK_LIBRARY, library_name);
if ((has_plt = has_null_param (params, TOK_PLT)))
plt_val = "*";
else has_plt = get_string_param (params, TOK_PLT, plt_val);
has_statement = get_number_param(params, TOK_STATEMENT, statement_num_val);
if (has_process)
{
if (get_number_param(params, TOK_PROCESS, pid_val))
{
// check that the pid given corresponds to a running process
string pid_err_msg;
if (!is_valid_pid(pid_val, pid_err_msg))
throw SEMANTIC_ERROR(pid_err_msg);
string pid_path = string("/proc/") + lex_cast(pid_val) + "/exe";
module_val = sess.sysroot + pid_path;
}
else
{
// reset the pid_val in case anything weird got written into it
pid_val = 0;
get_string_param(params, TOK_PROCESS, module_val);
if (is_build_id(module_val))
build_id_val = module_val;
}
module_val = find_executable (module_val, sess.sysroot, sess.sysenv);
if (!is_fully_resolved(module_val, "", sess.sysenv))
throw SEMANTIC_ERROR(_F("cannot find executable '%s'",
module_val.to_string().c_str()));
}
// Library probe? Let's target that instead if it is fully resolved (such
// as what query_one_library() would have done for us). Otherwise, we
// resort to iterate_over_libraries().
if (has_library)
{
string library = find_executable (library_name, sess.sysroot,
sess.sysenv, "LD_LIBRARY_PATH");
if (is_fully_resolved(library, "", sess.sysenv, "LD_LIBRARY_PATH"))
{
path = path_remove_sysroot(sess, module_val);
module_val = library;
}
}
}
assert (has_kernel || has_process || has_module);
}
base_query::base_query(dwflpp & dw, interned_string module_val)
: sess(dw.sess), dw(dw),
has_kernel(false), has_module(false), has_process(false),
has_library(false), has_plt(false), has_statement(false),
module_val(module_val), pid_val(0)
{
// NB: This uses '/' to distinguish between kernel modules and userspace,
// which means that userspace modules won't get any PATH searching.
if (module_val.find('/') == string::npos)
{
has_kernel = (module_val == TOK_KERNEL);
has_module = !has_kernel;
has_process = false;
}
else
{
has_kernel = has_module = false;
has_process = true;
}
}
bool
base_query::has_null_param(literal_map_t const & params,
interned_string k)
{
return derived_probe_builder::has_null_param(params, k);
}
bool
base_query::get_string_param(literal_map_t const & params,
interned_string k, interned_string & v)
{
return derived_probe_builder::get_param (params, k, v);
}
bool
base_query::get_number_param(literal_map_t const & params,
interned_string k, int64_t & v)
{
return derived_probe_builder::get_param (params, k, v);
}
bool
base_query::get_number_param(literal_map_t const & params,
interned_string k, Dwarf_Addr & v)
{
int64_t value = 0;
bool present = derived_probe_builder::get_param (params, k, value);
if (present)
v = (Dwarf_Addr) value;
return present;
}
struct dwarf_query : public base_query
{
dwarf_query(probe * base_probe,
probe_point * base_loc,
dwflpp & dw,
literal_map_t const & params,
vector<derived_probe *> & results,
interned_string user_path,
interned_string user_lib);
vector<derived_probe *> & results;
set<interned_string> inlined_non_returnable; // function names
probe * base_probe;
probe_point * base_loc;
interned_string user_path;
interned_string user_lib;
set<string> visited_libraries;
bool resolved_library;
virtual void handle_query_module();
void query_module_dwarf();
void query_module_symtab();
void query_library (const char *data);
void query_plt (const char *entry, size_t addr);
void add_probe_point(interned_string funcname,
interned_string filename,
int line,
Dwarf_Die *scope_die,
Dwarf_Addr addr);
void mount_well_formed_probe_point();
void unmount_well_formed_probe_point();
stack<pair<probe_point*, probe*> > previous_bases;
void replace_probe_point_component_arg(interned_string functor,
interned_string new_functor,
int64_t new_arg,
bool hex = false);
void replace_probe_point_component_arg(interned_string functor,
int64_t new_arg,
bool hex = false);
void replace_probe_point_component_arg(interned_string functor,
interned_string new_functor,
interned_string new_arg);
void replace_probe_point_component_arg(interned_string functor,
interned_string new_arg);
void remove_probe_point_component(interned_string functor);
// Track addresses we've already seen in a given module
set<Dwarf_Addr> alias_dupes;
// Track inlines we've already seen as well
// NB: this can't be compared just by entrypc, as inlines can overlap
set<inline_instance_info> inline_dupes;
// Used in .callee[s] probes, when calling iterate_over_callees() (which
// provides the actual stack). Retains the addrs of the callers unwind addr
// where the callee is found. Specifies multiple callers. E.g. when a callee
// at depth 2 is found, callers[1] has the addr of the caller, and callers[0]
// has the addr of the caller's caller.
stack<Dwarf_Addr> *callers;
bool has_function_str;
bool has_statement_str;
bool has_function_num;
bool has_statement_num;
interned_string statement_str_val;
interned_string function_str_val;
Dwarf_Addr statement_num_val;
Dwarf_Addr function_num_val;
bool has_call;
bool has_exported;
bool has_inline;
bool has_return;
bool has_nearest;
bool has_maxactive;
int64_t maxactive_val;
bool has_label;
interned_string label_val;
bool has_callee;
interned_string callee_val;
bool has_callees_num;
int64_t callees_num_val;
bool has_absolute;
bool has_mark;
void parse_function_spec(const string & spec);
function_spec_type spec_type;
vector<string> scopes;
interned_string function;
interned_string file;
lineno_t lineno_type;
vector<int> linenos;
// Holds the prologue end of the current function
Dwarf_Addr prologue_end;
set<string> filtered_srcfiles;
// Map official entrypc -> func_info object
inline_instance_map_t filtered_inlines;
func_info_map_t filtered_functions;
// Helper when we want to iterate over both
base_func_info_map_t filtered_all();
void query_module_functions ();
interned_string final_function_name(interned_string final_func,
interned_string final_file,
int final_line);
bool is_fully_specified_function();
};
uprobe_derived_probe::uprobe_derived_probe (interned_string function,
interned_string filename,
int line,
interned_string module,
interned_string section,
Dwarf_Addr dwfl_addr,
Dwarf_Addr addr,
dwarf_query & q,
Dwarf_Die* scope_die):
dwarf_derived_probe(function, filename, line, module, section,
dwfl_addr, addr, q, scope_die),
pid(q.pid_val), build_id_vaddr(0)
{
// Process parameter is given as a build-id
if (q.build_id_val.size() > 0)
{
const unsigned char *bits;
int len;
GElf_Addr vaddr;
len = dwfl_module_build_id(q.dw.module, &bits, &vaddr);
if (len > 0)
{
Dwarf_Addr reloc_vaddr = vaddr;
len = dwfl_module_relocate_address(q.dw.module, &reloc_vaddr);
DWFL_ASSERT ("dwfl_module_relocate_address reloc_vaddr", len >= 0);
build_id_vaddr = reloc_vaddr;
build_id_val = q.build_id_val;
}
}
}
static void delete_session_module_cache (systemtap_session& s); // forward decl
struct dwarf_builder: public derived_probe_builder
{
map <string,dwflpp*> kern_dw; /* NB: key string could be a wildcard */
map <string,dwflpp*> user_dw;
interned_string user_path;
interned_string user_lib;
// Holds modules to suggest functions from. NB: aggregates over
// recursive calls to build() when deriving globby probes.
set <string> modules_seen;
dwarf_builder() {}
dwflpp *get_kern_dw(systemtap_session& sess, const string& module, bool debuginfo_needed = true)
{
if (kern_dw[module] == 0)
kern_dw[module] = new dwflpp(sess, module, true, debuginfo_needed); // might throw
return kern_dw[module];
}
dwflpp *get_user_dw(systemtap_session& sess, const string& module)
{
if (user_dw[module] == 0)
user_dw[module] = new dwflpp(sess, module, false); // might throw
return user_dw[module];
}
/* NB: not virtual, so can be called from dtor too: */
void dwarf_build_no_more (bool)
{
delete_map(kern_dw);
delete_map(user_dw);
}
void build_no_more (systemtap_session &s)
{
dwarf_build_no_more (s.verbose > 3);
delete_session_module_cache (s);
}
~dwarf_builder()
{
dwarf_build_no_more (false);
}
virtual void build(systemtap_session & sess,
probe * base,
probe_point * location,
literal_map_t const & parameters,
vector<derived_probe *> & finished_results);
virtual string name() { return "DWARF builder"; }
};
dwarf_query::dwarf_query(probe * base_probe,
probe_point * base_loc,
dwflpp & dw,
literal_map_t const & params,
vector<derived_probe *> & results,
interned_string user_path,
interned_string user_lib)
: base_query(dw, params), results(results), base_probe(base_probe),
base_loc(base_loc), user_path(user_path), user_lib(user_lib),
resolved_library(false), callers(NULL),
has_function_str(false), has_statement_str(false),
has_function_num(false), has_statement_num(false),
statement_num_val(0), function_num_val(0),
has_call(false), has_exported(false), has_inline(false),
has_return(false), has_nearest(false),
has_maxactive(false), maxactive_val(0),
has_label(false), has_callee(false),
has_callees_num(false), callees_num_val(0),
has_absolute(false), has_mark(false),
spec_type(function_alone),
lineno_type(ABSOLUTE),
prologue_end(0)
{
// Reduce the query to more reasonable semantic values (booleans,
// extracted strings, numbers, etc).
has_function_str = get_string_param(params, TOK_FUNCTION, function_str_val);
has_function_num = get_number_param(params, TOK_FUNCTION, function_num_val);
has_statement_str = get_string_param(params, TOK_STATEMENT, statement_str_val);
has_statement_num = get_number_param(params, TOK_STATEMENT, statement_num_val);
has_label = get_string_param(params, TOK_LABEL, label_val);
has_callee = get_string_param(params, TOK_CALLEE, callee_val);
if (has_null_param(params, TOK_CALLEES))
{ // .callees ==> .callees(1) (also equivalent to .callee("*"))
has_callees_num = true;
callees_num_val = 1;
}
else
{
has_callees_num = get_number_param(params, TOK_CALLEES, callees_num_val);
if (has_callees_num && callees_num_val < 1)
throw SEMANTIC_ERROR(_(".callees(N) only acceptable for N >= 1"),
base_probe->tok);
}
has_call = has_null_param(params, TOK_CALL);
has_exported = has_null_param(params, TOK_EXPORTED);
has_inline = has_null_param(params, TOK_INLINE);
has_return = has_null_param(params, TOK_RETURN);
has_nearest = has_null_param(params, TOK_NEAREST);
has_maxactive = get_number_param(params, TOK_MAXACTIVE, maxactive_val);
has_absolute = has_null_param(params, TOK_ABSOLUTE);
has_mark = false;
if (has_function_str)
parse_function_spec(function_str_val);
else if (has_statement_str)
parse_function_spec(statement_str_val);
}
void
dwarf_query::query_module_dwarf()
{
if (has_function_num || has_statement_num)
{
// If we have module("foo").function(0xbeef) or
// module("foo").statement(0xbeef), the address is relative
// to the start of the module, so we seek the function
// number plus the module's bias.
Dwarf_Addr addr = has_function_num ?
function_num_val : statement_num_val;
// These are raw addresses, we need to know what the elf_bias
// is to feed it to libdwfl based functions.
Dwarf_Addr elf_bias;
Elf *elf = dwfl_module_getelf (dw.module, &elf_bias);
assert(elf);
addr += elf_bias;
query_addr(addr, this);
}
else
{
// Otherwise if we have a function("foo") or statement("foo")
// specifier, we have to scan over all the CUs looking for
// the function(s) in question
assert(has_function_str || has_statement_str);
// For simple cases, no wildcard and no source:line, we can do a very
// quick function lookup in a module-wide cache.
if (spec_type == function_alone &&
!dw.name_has_wildcard(function) &&
!startswith(function, "_Z"))
query_module_functions();
else
dw.iterate_over_cus(&query_cu, this, false);
}
}
static void query_func_info (Dwarf_Addr entrypc, func_info & fi,
dwarf_query * q);
static void
query_symtab_func_info (func_info & fi, dwarf_query * q)
{
assert(null_die(&fi.die));
Dwarf_Addr entrypc = fi.entrypc;
// Now compensate for the dw bias because the addresses come
// from dwfl_module_symtab, so fi->entrypc is NOT a normal dw address.
q->dw.get_module_dwarf(false, false);
entrypc -= q->dw.module_bias;
// PR29676. We consult the symbol tables of both the elf and
// dwarf files. The 2 results can contain duplicates so
// check results before continuing to create new probe points
for(auto ddp_it = q->results.begin(); ddp_it != q->results.end(); ++ddp_it){
dwarf_derived_probe *ddp = dynamic_cast<dwarf_derived_probe *> (*ddp_it);
if(ddp && ddp->addr == entrypc)
return;
}
// If there are already probes in this module, lets not duplicate.
// This can come from other weak symbols/aliases or existing
// matches from Dwarf DIE functions. Try to add this entrypc to the
// collection, and only continue if it was new.
if (q->alias_dupes.insert(entrypc).second)
query_func_info(entrypc, fi, q);
}
void
dwarf_query::query_module_symtab()
{
// Get the symbol table if we don't already have it
module_info *mi = dw.mod_info;
if (mi->symtab_status == info_unknown)
mi->get_symtab();
if (mi->symtab_status == info_absent)
return;
func_info *fi = NULL;
symbol_table *sym_table = mi->sym_table;
if (has_function_str && spec_type == function_alone)
{
if (dw.name_has_wildcard(function_str_val))
{
for (auto iter = sym_table->map_by_addr.begin();
iter != sym_table->map_by_addr.end();
++iter)
{
fi = iter->second;
if (!null_die(&fi->die) // already handled in query_module_dwarf()
|| fi->descriptor) // ppc opd (and also undefined symbols)
continue;
if (dw.function_name_matches_pattern(fi->name, function_str_val))
query_symtab_func_info(*fi, this);
}
}
else
{
const auto& fis = sym_table->lookup_symbol(function_str_val);
for (auto it=fis.begin(); it!=fis.end(); ++it)
{
fi = *it;
if (fi && null_die(&fi->die))
query_symtab_func_info(*fi, this);
}
}
}
}
void
dwarf_query::handle_query_module()
{
if (has_plt && has_statement_num)
{
query_plt_statement (this);
return;
}
// PR25841. We may only need dwarf depending on the context-related
// constructs in the probe handler and/or transitively called
// functions. Otherwise, for some probe types (as per the former
// assess_dbinfo_reqt()), we could fall back to query_module_symtab
// (elf-only) and not bother look for / complain about absence of
// dwarf. But ... the worst case for probes where pure elf symbols are
// enough is a warning that dwarf wasn't available. Grin and bear it.
dw.get_module_dwarf(false /* don't require */, true /* warn */);
// prebuild the symbol table to resolve aliases
dw.mod_info->get_symtab();
// reset the dupe-checking for each new module
alias_dupes.clear();
inline_dupes.clear();
if (dw.mod_info->dwarf_status == info_present)
query_module_dwarf();
// Consult the symbol table, asm and weak functions can show up
// in the symbol table but not in dwarf and minidebuginfo is
// located in the gnu_debugdata section, alias_dupes checking
// is done before adding any probe points
// PR29676. Some probes require additional debuginfo
// to expand wildcards (ex. .label, .callee). Since the debuginfo is
// not available, don't bother looking in the symbol table for these results.
// This can result in 0 results, if there is no dwarf info present
if(!pending_interrupts && !(has_label || has_callee || has_callees_num))
query_module_symtab();
}
void
dwarf_query::parse_function_spec(const string & spec)
{
lineno_type = ABSOLUTE;
size_t src_pos, line_pos, scope_pos;
// look for named scopes
scope_pos = spec.rfind("::");
if (scope_pos != string::npos)
{
tokenize_cxx(spec.substr(0, scope_pos), scopes);
scope_pos += 2;
}
else
scope_pos = 0;
// look for a source separator
src_pos = spec.find('@', scope_pos);
if (src_pos == string::npos)
{
function = spec.substr(scope_pos);
spec_type = function_alone;
}
else
{
function = spec.substr(scope_pos, src_pos - scope_pos);
// look for a line-number separator
line_pos = spec.find_first_of(":+", src_pos);
if (line_pos == string::npos)
{
file = spec.substr(src_pos + 1);
spec_type = function_and_file;
}
else
{
file = spec.substr(src_pos + 1, line_pos - src_pos - 1);
// classify the line spec
spec_type = function_file_and_line;
if (spec[line_pos] == '+')
lineno_type = RELATIVE;
else if (spec[line_pos + 1] == '*' &&
spec.length() == line_pos + 2)
lineno_type = WILDCARD;
else
lineno_type = ABSOLUTE;
if (lineno_type != WILDCARD)
try
{
// try to parse N, N-M, or N,M,O,P, or combination thereof...
if (spec.find_first_of(",-", line_pos + 1) != string::npos)
{
lineno_type = ENUMERATED;
vector<string> sub_specs;
tokenize(spec.substr(line_pos + 1), sub_specs, ",");
for (auto line_spec = sub_specs.cbegin();
line_spec != sub_specs.cend(); ++line_spec)
{
vector<string> ranges;
tokenize(*line_spec, ranges, "-");
if (ranges.size() > 1)
{
int low = lex_cast<int>(ranges.front());
int high = lex_cast<int>(ranges.back());
for (int i = low; i <= high; i++)
linenos.push_back(i);
}
else
linenos.push_back(lex_cast<int>(ranges.at(0)));
}
sort(linenos.begin(), linenos.end());
}
else
{
linenos.push_back(lex_cast<int>(spec.substr(line_pos + 1)));
linenos.push_back(lex_cast<int>(spec.substr(line_pos + 1)));
}
}
catch (runtime_error & exn)
{
goto bad;
}
}
}
if (function.empty() ||
(spec_type != function_alone && file.empty()))
goto bad;
if (sess.verbose > 2)
{
//clog << "parsed '" << spec << "'";
clog << _F("parse '%s'", spec.c_str());
if (!scopes.empty())
clog << ", scope '" << scopes[0] << "'";
for (unsigned i = 1; i < scopes.size(); ++i)
clog << "::'" << scopes[i] << "'";
clog << ", func '" << function << "'";
if (spec_type != function_alone)
clog << ", file '" << file << "'";
if (spec_type == function_file_and_line)
{
clog << ", line ";
switch (lineno_type)
{
case ABSOLUTE:
clog << linenos[0];
break;
case RELATIVE:
clog << "+" << linenos[0];
break;
case ENUMERATED:
{
for (auto linenos_it = linenos.cbegin();
linenos_it != linenos.cend(); ++linenos_it)
{
auto range_it = linenos_it;
while ((range_it+1) != linenos.end() && *range_it + 1 == *(range_it+1))
++range_it;
if (linenos_it == range_it)
clog << *linenos_it;
else
clog << *linenos_it << "-" << *range_it;
if (range_it + 1 != linenos.end())
clog << ",";
linenos_it = range_it;
}
}
break;
case WILDCARD:
clog << "*";
break;
}
}
clog << endl;
}
return;
bad:
throw SEMANTIC_ERROR(_F("malformed specification '%s'", spec.c_str()),
base_probe->tok);
}
string path_remove_sysroot(const systemtap_session& sess, const string& path)
{
size_t pos;
string retval = path;
if (!sess.sysroot.empty() &&
(pos = retval.find(sess.sysroot)) != string::npos)
retval.replace(pos, sess.sysroot.length(),
(*(sess.sysroot.end() - 1) == '/' ? "/": ""));
return retval;
}
/*
* Convert 'Global Entry Point' to 'Local Entry Point'.
*
* if @gep contains next address after prologue, don't change it.
*
* For ELF ABI v2 on PPC64 LE, we need to adjust sym.st_value corresponding
* to the bits of sym.st_other. These bits will tell us what's the offset
* of the local entry point from the global entry point.
*
* st_other field is currently only used with ABIv2 on ppc64
*/
static Dwarf_Addr
get_lep(dwarf_query *q, Dwarf_Addr gep)
{
Dwarf_Addr bias;
Dwfl_Module *mod = q->dw.module;
Elf* elf = (dwarf_getelf (dwfl_module_getdwarf (mod, &bias))
?: dwfl_module_getelf (mod, &bias));
GElf_Ehdr ehdr_mem;
GElf_Ehdr* em = gelf_getehdr (elf, &ehdr_mem);
if (em == NULL)
throw SEMANTIC_ERROR (_("Couldn't get elf header"));
if (!(em->e_machine == EM_PPC64) || !((em->e_flags & EF_PPC64_ABI) == 2))
return gep;
int syments = dwfl_module_getsymtab(mod);
for (int i = 1; i < syments; ++i)
{
GElf_Sym sym;
GElf_Word section;
GElf_Addr addr;
#if _ELFUTILS_PREREQ (0, 158)
dwfl_module_getsym_info (mod, i, &sym, &addr, §ion, NULL, NULL);
#else
dwfl_module_getsym (mod, i, &sym, §ion);
addr = sym.st_value;
#endif
/*
* Symbol table contains module_bias + offset. Substract module_bias
* to compare offset with gep.
*/
if ((addr - bias) == gep && (GELF_ST_TYPE(sym.st_info) == STT_FUNC)
&& sym.st_other)
return gep + PPC64_LOCAL_ENTRY_OFFSET(sym.st_other);
}
return gep;
}
void
dwarf_query::add_probe_point(interned_string dw_funcname,
interned_string filename,
int line,
Dwarf_Die* scope_die,
Dwarf_Addr addr)
{
interned_string reloc_section; // base section for relocation purposes
Dwarf_Addr orig_addr = addr;
Dwarf_Addr reloc_addr; // relocated
interned_string module = dw.module_name; // "kernel" or other
interned_string funcname = dw_funcname;
assert (! has_absolute); // already handled in dwarf_builder::build()
addr = get_lep(this, addr);
reloc_addr = dw.relocate_address(addr, reloc_section);
// If we originally used the linkage name, then let's call it that way
const char* linkage_name;
if (!null_die(scope_die) && startswith (this->function, "_Z")
&& (linkage_name = dwarf_linkage_name (scope_die)))
funcname = linkage_name;
if (sess.verbose > 1)
{
clog << _("probe ") << funcname << "@" << filename << ":" << line;
if (string(module) == TOK_KERNEL)
clog << _(" kernel");
else if (has_module)
clog << _(" module=") << module;
else if (has_process)
clog << _(" process=") << module;
if (reloc_section != "") clog << " reloc=" << reloc_section;
clog << " pc=0x" << hex << addr << dec;
}
dwflpp::blocklisted_type blocklisted = dw.blocklisted_p (funcname, filename,
line, module, addr,
has_return);
if (sess.verbose > 1)
clog << endl;
if (module == TOK_KERNEL)
{
// PR 4224: adapt to relocatable kernel by subtracting the _stext address here.
reloc_addr = addr - sess.sym_stext;
reloc_section = "_stext"; // a message to runtime's _stp_module_relocate
}
if (!blocklisted)
{
sess.unwindsym_modules.insert (module);
if (has_process)
{
string module_tgt = path_remove_sysroot(sess, module);
results.push_back (new uprobe_derived_probe(funcname, filename, line,
module_tgt, reloc_section, addr, reloc_addr,
*this, scope_die));
}
else
{
assert (has_kernel || has_module);
// We could only convert probes in the module's .init
// section to symbol+offset probes. However, the module
// refresh code only expects to be called once on a module
// load, so we'll go ahead and convert them all.
if (has_module)
{
module_info *mi = dw.mod_info;
if (mi->symtab_status == info_unknown)
mi->get_symtab();
if (mi->symtab_status == info_absent)
throw SEMANTIC_ERROR(_F("can't retrieve symbol table for function %s",
module_val.to_string().c_str()));
symbol_table *sym_table = mi->sym_table;
func_info *symbol = sym_table->get_func_containing_address(addr);
// Do not use LEP to find offset here. When 'symbol_name'
// is used to register probe, kernel itself will find LEP.
Dwarf_Addr offset = orig_addr - symbol->addr;
results.push_back (new dwarf_derived_probe(funcname, filename,
line, module,
reloc_section, addr,
reloc_addr,
*this, scope_die,
symbol->name,
offset));
}
else
results.push_back (new dwarf_derived_probe(funcname, filename,
line, module,
reloc_section, addr,
reloc_addr,
*this, scope_die));
}
}
else
{
switch (blocklisted)
{
case dwflpp::blocklisted_section:
sess.print_warning(_F("function %s is in blocklisted section",
funcname.to_string().c_str()), base_probe->tok);
break;
case dwflpp::blocklisted_kprobes:
sess.print_warning(_F("kprobes function %s is blocklisted",
funcname.to_string().c_str()), base_probe->tok);
break;
case dwflpp::blocklisted_function_return:
sess.print_warning(_F("function %s return probe is blocklisted",
funcname.to_string().c_str()), base_probe->tok);
break;
case dwflpp::blocklisted_file:
sess.print_warning(_F("function %s is in blocklisted file",
funcname.to_string().c_str()), base_probe->tok);
break;
case dwflpp::blocklisted_function:
default:
sess.print_warning(_F("function %s is blocklisted",
funcname.to_string().c_str()), base_probe->tok);
break;
}
}
}
void
dwarf_query::mount_well_formed_probe_point()
{
interned_string module = dw.module_name;
if (has_process)
module = path_remove_sysroot(sess, module);
vector<probe_point::component*> comps;
for (auto it = base_loc->components.begin();
it != base_loc->components.end(); ++it)
{
if ((*it)->functor == TOK_PROCESS && this->build_id_val != "")
comps.push_back(new probe_point::component((*it)->functor,
new literal_string(this->build_id_val)));
else if ((*it)->functor == TOK_PROCESS || (*it)->functor == TOK_MODULE)
comps.push_back(new probe_point::component((*it)->functor,
new literal_string(has_library ? path : module)));
else
comps.push_back(*it);
}
probe_point *pp = new probe_point(*base_loc);
pp->well_formed = true;
pp->components = comps;
previous_bases.push(make_pair(base_loc, base_probe));
base_loc = pp;
base_probe = new probe(base_probe, pp);
}
void
dwarf_query::unmount_well_formed_probe_point()
{
assert(!previous_bases.empty());
base_loc = previous_bases.top().first;
base_probe = previous_bases.top().second;
previous_bases.pop();
}
void
dwarf_query::replace_probe_point_component_arg(interned_string functor,
interned_string new_functor,
int64_t new_arg,
bool hex)
{
// only allow these operations if we're editing the well-formed loc
assert(!previous_bases.empty());
for (auto it = base_loc->components.begin();
it != base_loc->components.end(); ++it)
if ((*it)->functor == functor)
*it = new probe_point::component(new_functor,
new literal_number(new_arg, hex));
}
void
dwarf_query::replace_probe_point_component_arg(interned_string functor,
int64_t new_arg,
bool hex)
{
replace_probe_point_component_arg(functor, functor, new_arg, hex);
}
void
dwarf_query::replace_probe_point_component_arg(interned_string functor,
interned_string new_functor,
interned_string new_arg)
{
// only allow these operations if we're editing the well-formed loc
assert(!previous_bases.empty());
for (auto it = base_loc->components.begin();
it != base_loc->components.end(); ++it)
if ((*it)->functor == functor)
*it = new probe_point::component(new_functor,
new literal_string(new_arg));
}
void
dwarf_query::replace_probe_point_component_arg(interned_string functor,
interned_string new_arg)
{
replace_probe_point_component_arg(functor, functor, new_arg);
}
void
dwarf_query::remove_probe_point_component(interned_string functor)
{
// only allow these operations if we're editing the well-formed loc
assert(!previous_bases.empty());
vector<probe_point::component*> new_comps;
for (auto it = base_loc->components.begin();
it != base_loc->components.end(); ++it)
if ((*it)->functor != functor)
new_comps.push_back(*it);
base_loc->components = new_comps;
}
interned_string
dwarf_query::final_function_name(interned_string final_func,
interned_string final_file,
int final_line)
{
string final_name = final_func;
if (final_file != "")
{
final_name += ("@" + string(final_file));
if (final_line > 0)
final_name += (":" + lex_cast(final_line));
}
return final_name;
}
bool
dwarf_query::is_fully_specified_function()
{
// A fully specified function is one that was given using a .function() probe
// by full name (no wildcards), and specific srcfile and decl_line.
return (has_function_str
&& spec_type == function_file_and_line
&& !dw.name_has_wildcard(function)
&& filtered_srcfiles.size() == 1
&& !filtered_functions.empty()
&& lineno_type == ABSOLUTE
&& filtered_functions[0].decl_line == linenos[0]);
}
base_func_info_map_t
dwarf_query::filtered_all(void)
{
base_func_info_map_t r;
for (auto f = filtered_functions.cbegin();
f != filtered_functions.cend(); ++f)
r.push_back(*f);
for (auto i = filtered_inlines.cbegin();
i != filtered_inlines.cend(); ++i)
r.push_back(*i);
return r;
}
// The critical determining factor when interpreting a pattern
// string is, perhaps surprisingly: "presence of a lineno". The
// presence of a lineno changes the search strategy completely.
//
// Compare the two cases:
//
// 1. {statement,function}(foo@file.c:lineno)
// - find the files matching file.c
// - in each file, find the functions matching foo
// - query the file for line records matching lineno
// - iterate over the line records,
// - and iterate over the functions,
// - if(haspc(function.DIE, line.addr))
// - if looking for statements: probe(lineno.addr)
// - if looking for functions: probe(function.{entrypc,return,etc.})
//
// 2. {statement,function}(foo@file.c)
// - find the files matching file.c
// - in each file, find the functions matching foo
// - probe(function.{entrypc,return,etc.})
//
// Thus the first decision we make is based on the presence of a
// lineno, and we enter entirely different sets of callbacks
// depending on that decision.
//
// Note that the first case is a generalization fo the second, in that
// we could theoretically search through line records for matching
// file names (a "table scan" in rdbms lingo). Luckily, file names
// are already cached elsewhere, so we can do an "index scan" as an
// optimization.
static void
query_statement (interned_string func,
interned_string file,
int line,
Dwarf_Die *scope_die,
Dwarf_Addr stmt_addr,
dwarf_query * q)
{
try
{
q->add_probe_point(func, file,
line, scope_die, stmt_addr);
}
catch (const semantic_error& e)
{
q->sess.print_error (e);
}
}
static void
query_addr(Dwarf_Addr addr, dwarf_query *q)
{
assert(q->has_function_num || q->has_statement_num);
dwflpp &dw = q->dw;
if (q->sess.verbose > 2)
clog << "query_addr 0x" << hex << addr << dec << endl;
// First pick which CU contains this address
Dwarf_Die* cudie = dw.query_cu_containing_address(addr);
if (!cudie) // address could be wildly out of range
return;
dw.focus_on_cu(cudie);
// Now compensate for the dw bias
addr -= dw.module_bias;
// Per PR5787, we look up the scope die even for
// statement_num's, for blocklist sensitivity and $var
// resolution purposes.
// Find the scopes containing this address
vector<Dwarf_Die> scopes = dw.getscopes(addr);
if (scopes.empty())
return;
// Look for the innermost containing function
Dwarf_Die *fnscope = NULL;
for (size_t i = 0; i < scopes.size(); ++i)
{
int tag = dwarf_tag(&scopes[i]);
if ((tag == DW_TAG_subprogram && !q->has_inline) ||
(tag == DW_TAG_inlined_subroutine &&
!q->has_call && !q->has_return && !q->has_exported))
{
fnscope = &scopes[i];
break;
}
}
if (!fnscope)
return;
dw.focus_on_function(fnscope);
Dwarf_Die *scope = q->has_function_num ? fnscope : &scopes[0];
const char *file = dwarf_decl_file(fnscope) ?: "";
int line;
dwarf_decl_line(fnscope, &line);
// Function probes should reset the addr to the function entry
// and possibly perform prologue searching
if (q->has_function_num)
{
if (!dw.die_entrypc(fnscope, &addr))
return;
if (dwarf_tag(fnscope) == DW_TAG_subprogram &&
q->sess.prologue_searching_mode != systemtap_session::prologue_searching_never &&
(q->sess.prologue_searching_mode == systemtap_session::prologue_searching_always ||
(q->has_process && !q->dw.has_valid_locs()))) // PR 6871 && PR 6941
{
func_info func;
func.die = *fnscope;
func.name = dw.function_name;
func.decl_file = file;
func.decl_line = line;
func.entrypc = addr;
func_info_map_t funcs(1, func);
dw.resolve_prologue_endings (funcs);
q->prologue_end = funcs[0].prologue_end;
// PR13200: if it's a .return probe, we need to emit a *retprobe based
// on the entrypc so here we only use prologue_end for non .return
// probes (note however that .return probes still take advantage of
// prologue_end: PR14436)
if (!q->has_return)
addr = funcs[0].prologue_end;
}
}
else
{
Dwarf_Line *address_line = dwarf_getsrc_die(cudie, addr);
Dwarf_Addr address_line_addr = addr;
if (address_line)
{
file = DWARF_LINESRC(address_line);
line = DWARF_LINENO(address_line);
address_line_addr = DWARF_LINEADDR(address_line);
}
// Verify that a raw address matches the beginning of a
// statement. This is a somewhat lame check that the address
// is at the start of an assembly instruction. Mark probes are in the
// middle of a macro and thus not strictly at a statement beginning.
// Guru mode may override this check.
if (!q->has_mark && (!address_line || address_line_addr != addr))
{
stringstream msg;
msg << _F("address %#" PRIx64 " does not match the beginning of a statement",
addr);
if (address_line)
msg << _F(" (try %#" PRIx64 ")", address_line_addr);
else
msg << _F(" (no line info found for '%s', in module '%s')",
dw.cu_name().c_str(), dw.module_name.c_str());
if (! q->sess.guru_mode)
throw SEMANTIC_ERROR(msg.str());
else
q->sess.print_warning(msg.str());
}
}
// We're ready to build a probe, but before, we need to create the final,
// well-formed version of this location with all the components filled in
q->mount_well_formed_probe_point();
q->replace_probe_point_component_arg(TOK_FUNCTION, addr, true /* hex */ );
q->replace_probe_point_component_arg(TOK_STATEMENT, addr, true /* hex */ );
// Build a probe at this point
query_statement(dw.function_name, file, line, scope, addr, q);
q->unmount_well_formed_probe_point();
}
static void
query_plt_statement(dwarf_query *q)
{
assert (q->has_plt && q->has_statement_num);
Dwarf_Addr addr = q->statement_num_val;
if (q->sess.verbose > 2)
clog << "query_plt_statement 0x" << hex << addr << dec << endl;
// First adjust the raw address to dwfl's elf bias.
Dwarf_Addr elf_bias;
Elf *elf = dwfl_module_getelf (q->dw.module, &elf_bias);
assert(elf);
addr += elf_bias;
// Now compensate for the dw bias
q->dw.get_module_dwarf(false, false);
addr -= q->dw.module_bias;
// Create the final well-formed probe point
q->mount_well_formed_probe_point();
q->replace_probe_point_component_arg(TOK_STATEMENT, q->statement_num_val, true /* hex */ );
// We remove the .plt part here, since if the user provided a .plt probe, then
// the higher-level probe point is already well-formed. On the other hand, if
// the user provides a .plt(PATTERN).statement(0xABCD), the PATTERN is
// irrelevant (we won't iterate over plts) so just take it out.
q->remove_probe_point_component(TOK_PLT);
// Build a probe at this point
query_statement(q->plt_val, NULL, -1, NULL, addr, q);
q->unmount_well_formed_probe_point();
}
static void
query_label (const base_func_info& func,
char const * label,
char const * file,
int line,
Dwarf_Die *scope_die,
Dwarf_Addr stmt_addr,
dwarf_query * q)
{
assert (q->has_statement_str || q->has_function_str);
// weed out functions whose decl_file isn't one of
// the source files that we actually care about
if (q->spec_type != function_alone &&
q->filtered_srcfiles.count(file) == 0)
return;
// Create the final well-formed probe
interned_string canon_func = q->final_function_name(func.name, file ?: "", line);
q->mount_well_formed_probe_point();
q->replace_probe_point_component_arg(TOK_FUNCTION, canon_func);
q->replace_probe_point_component_arg(TOK_LABEL, label);
query_statement(func.name, file, line, scope_die, stmt_addr, q);
q->unmount_well_formed_probe_point();
}
static void
query_callee (base_func_info& callee,
base_func_info& caller,
stack<Dwarf_Addr> *callers,
dwarf_query * q)
{
assert (q->has_function_str);
assert (q->has_callee || q->has_callees_num);
// OK, we found a callee for a targeted caller. To help users see the
// derivation, we add the well-formed form .function(caller).callee(callee).
interned_string canon_caller = q->final_function_name(caller.name, caller.decl_file,
caller.decl_line);
interned_string canon_callee = q->final_function_name(callee.name, callee.decl_file,
callee.decl_line);
q->mount_well_formed_probe_point();
q->replace_probe_point_component_arg(TOK_FUNCTION, canon_caller);
q->replace_probe_point_component_arg(TOK_CALLEES, TOK_CALLEE, canon_callee);
q->replace_probe_point_component_arg(TOK_CALLEE, canon_callee);
// Pass on the callers we'll need to add checks for
q->callers = callers;
query_statement(callee.name, callee.decl_file,
callee.decl_line,
&callee.die, callee.entrypc, q);
q->unmount_well_formed_probe_point();
}
static void
query_inline_instance_info (inline_instance_info & ii,
dwarf_query * q)
{
try
{
assert (! q->has_return); // checked by caller already
assert (q->has_function_str || q->has_statement_str);
if (q->sess.verbose>2)
clog << _F("querying entrypc %#" PRIx64 " of instance of inline '%s'\n",
ii.entrypc, ii.name.to_string().c_str());
interned_string canon_func = q->final_function_name(ii.name, ii.decl_file,
ii.decl_line);
q->mount_well_formed_probe_point();
q->replace_probe_point_component_arg(TOK_FUNCTION, canon_func);
q->replace_probe_point_component_arg(TOK_STATEMENT, canon_func);
query_statement (ii.name, ii.decl_file, ii.decl_line,
&ii.die, ii.entrypc, q);
q->unmount_well_formed_probe_point();
}
catch (semantic_error &e)
{
q->sess.print_error (e);
}
}
static void
query_func_info (Dwarf_Addr entrypc,
func_info & fi,
dwarf_query * q)
{
assert(q->has_function_str || q->has_statement_str);
try
{
interned_string canon_func = q->final_function_name(fi.name, fi.decl_file,
fi.decl_line);
q->mount_well_formed_probe_point();
q->replace_probe_point_component_arg(TOK_FUNCTION, canon_func);
q->replace_probe_point_component_arg(TOK_STATEMENT, canon_func);
// If it's a .return probe, we need to emit a *retprobe based on the
// entrypc (PR13200). Note however that if prologue_end is valid,
// dwarf_derived_probe will still take advantage of it by creating a new
// probe there if necessary to pick up target vars (PR14436).
if (fi.prologue_end == 0 || q->has_return)
{
q->prologue_end = fi.prologue_end;
query_statement (fi.name, fi.decl_file, fi.decl_line,
&fi.die, entrypc, q);
}
else
{
query_statement (fi.name, fi.decl_file, fi.decl_line,
&fi.die, fi.prologue_end, q);
}
q->unmount_well_formed_probe_point();
}
catch (semantic_error &e)
{
q->sess.print_error (e);
}
}
static void
query_srcfile_line (Dwarf_Addr addr, int lineno, dwarf_query * q)
{
assert (q->has_statement_str || q->has_function_str);
assert (q->spec_type == function_file_and_line);
auto bfis = q->filtered_all();
for (auto i = bfis.begin(); i != bfis.end(); ++i)
{
if (q->sess.verbose>3)
clog << _F("checking DIE (dieoffset: %#" PRIx64 ") "
"against scope address %#" PRIx64 "\n",
dwarf_dieoffset(& i->die),
addr);
if (q->dw.die_has_pc (i->die, addr))
{
if (q->sess.verbose>3)
clog << _("filtered DIE lands on srcfile\n");
Dwarf_Die scope;
q->dw.inner_die_containing_pc(i->die, addr, scope);
interned_string canon_func = q->final_function_name(i->name, i->decl_file,
lineno /* NB: not i->decl_line */ );
if (q->has_nearest && (q->lineno_type == ABSOLUTE ||
q->lineno_type == RELATIVE))
{
int lineno_nearest = q->linenos[0];
if (q->lineno_type == RELATIVE)
lineno_nearest += i->decl_line;
interned_string canon_func_nearest = q->final_function_name(i->name,
i->decl_file,
lineno_nearest);
q->mount_well_formed_probe_point();
q->replace_probe_point_component_arg(TOK_STATEMENT, canon_func_nearest);
}
q->mount_well_formed_probe_point();
q->replace_probe_point_component_arg(TOK_FUNCTION, canon_func);
q->replace_probe_point_component_arg(TOK_STATEMENT, canon_func);
query_statement (i->name, i->decl_file,
lineno, // NB: not q->line !
&scope, addr, q);
q->unmount_well_formed_probe_point();
if (q->has_nearest && (q->lineno_type == ABSOLUTE ||
q->lineno_type == RELATIVE))
q->unmount_well_formed_probe_point();
}
}
}
bool
inline_instance_info::operator<(const inline_instance_info& other) const
{
if (entrypc != other.entrypc)
return entrypc < other.entrypc;
if (decl_line != other.decl_line)
return decl_line < other.decl_line;
int cmp = name.compare(other.name);
if (!cmp) // tiebreaker
cmp = decl_file.compare(other.decl_file);
return cmp < 0;
}
static int
query_dwarf_inline_instance (Dwarf_Die * die, dwarf_query * q)
{
assert (q->has_statement_str || q->has_function_str);
assert (!q->has_call && !q->has_return && !q->has_exported);
try
{
if (q->sess.verbose>2)
clog << _F("selected inline instance of %s\n", q->dw.function_name.c_str());
Dwarf_Addr entrypc;
if (q->dw.die_entrypc (die, &entrypc))
{
// PR12609: The tails of partially-inlined functions show up
// in the query_dwarf_func() path, not here. The heads do
// come here, and should be processed here.
inline_instance_info inl;
inl.die = *die;
inl.name = q->dw.function_name;
inl.entrypc = entrypc;
const char* df;
q->dw.function_file (&df);
inl.decl_file = df ?: "";
q->dw.function_line (&inl.decl_line);
// make sure that this inline hasn't already
// been matched from a different CU
if (q->inline_dupes.insert(inl).second)
{
if (q->sess.verbose>3)
clog << _F("added to filtered_inlines (dieoffset: %#" PRIx64 ")\n",
dwarf_dieoffset(&inl.die));
q->filtered_inlines.push_back(inl);
}
}
return DWARF_CB_OK;
}
catch (const semantic_error& e)
{
q->sess.print_error (e);
return DWARF_CB_ABORT;
}
}
static int
query_dwarf_func (Dwarf_Die * func, dwarf_query * q)
{
assert (q->has_statement_str || q->has_function_str);
// weed out functions whose decl_file isn't one of
// the source files that we actually care about
string decl_file = dwarf_decl_file(func)?:"";
if (q->sess.verbose>4)
clog << _F("querying dwarf func in file %s count %zu (func dieoffset: %#" PRIx64 ")\n",
decl_file.c_str(),
q->filtered_srcfiles.count(decl_file),
dwarf_dieoffset(func));
if (q->spec_type != function_alone &&
decl_file != "" && // do not skip decl_file-free DIEs; could be artificial/LTO?
q->filtered_srcfiles.count(decl_file) == 0)
return DWARF_CB_OK;
try
{
q->dw.focus_on_function (func);
if (!q->dw.function_scope_matches(q->scopes))
return DWARF_CB_OK;
// make sure that this function address hasn't
// already been matched under an aliased name
Dwarf_Addr addr;
if (!q->dw.func_is_inline() &&
dwarf_entrypc(func, &addr) == 0 &&
!q->alias_dupes.insert(addr).second)
return DWARF_CB_OK;
if (q->dw.func_is_inline () && (! q->has_call) && (! q->has_return) && (! q->has_exported))
{
if (q->sess.verbose>3)
clog << _F("checking instances of inline %s\n", q->dw.function_name.c_str());
q->dw.iterate_over_inline_instances (query_dwarf_inline_instance, q);
}
else if (q->dw.func_is_inline () && (q->has_return)) // PR 11553
{
q->inlined_non_returnable.insert (q->dw.function_name);
}
else if (!q->dw.func_is_inline () && (! q->has_inline))
{
if (q->has_exported && !q->dw.func_is_exported ())
return DWARF_CB_OK;
if (q->sess.verbose>2)
clog << _F("selected function %s\n", q->dw.function_name.c_str());
func_info func;
q->dw.function_die (&func.die);
func.name = q->dw.function_name;
const char *df;
q->dw.function_file (&df);
func.decl_file = df ?: "";
q->dw.function_line (&func.decl_line);
Dwarf_Addr entrypc;
if (q->dw.function_entrypc (&entrypc))
{
func.entrypc = entrypc;
// PR12609: handle partial-inlined functions. These look
// like normal inlined instances in DWARF (so come through
// here), but in fact are common/tail parts of a normal
// inlined function instance. They do not represent entry
// points, so we filter them out. DWARF/gcc doesn't leave
// any attributes to identify these from there, so we look
// up the ELF symbol name and rely on a heuristic.
GElf_Sym sym;
GElf_Off off = 0;
Dwarf_Addr elf_bias;
Elf *elf = dwfl_module_getelf (q->dw.module, &elf_bias);
assert(elf);
const char *name = dwfl_module_addrinfo (q->dw.module, entrypc + elf_bias,
&off, &sym, NULL, NULL, NULL);
if (q->sess.verbose>3)
clog << _F("%s = dwfl_module_addrinfo(entrypc=%p + %p)\n",
name, (void*)entrypc, (void *)elf_bias);
if (name != NULL && strstr(name, ".part.") != NULL)
{
if (q->sess.verbose>2)
clog << _F("skipping partially-inlined instance "
"%s at %p\n", name, (void*)entrypc);
return DWARF_CB_OK;
}
if (q->sess.verbose>3)
clog << _F("added to filtered_functions (dieoffset: %#" PRIx64 ")\n",
dwarf_dieoffset(&func.die));
q->filtered_functions.push_back (func);
}
/* else this function is fully inlined, just ignore it */
}
return DWARF_CB_OK;
}
catch (const semantic_error& e)
{
q->sess.print_error (e);
return DWARF_CB_ABORT;
}
}
static int
query_cu (Dwarf_Die * cudie, dwarf_query * q)
{
assert (q->has_statement_str || q->has_function_str);
if (pending_interrupts) return DWARF_CB_ABORT;
try
{
q->dw.focus_on_cu (cudie);
if (false && q->sess.verbose>2)
clog << _F("focused on CU '%s', in module '%s'\n",
q->dw.cu_name().c_str(), q->dw.module_name.c_str());
q->filtered_srcfiles.clear();
q->filtered_functions.clear();
q->filtered_inlines.clear();
// In this path, we find "abstract functions", record
// information about them, and then (depending on lineno
// matching) possibly emit one or more of the function's
// associated addresses. Unfortunately the control of this
// cannot easily be turned inside out.
if (q->spec_type != function_alone)
{
// If we have a pattern string with a filename, we need
// to elaborate the srcfile mask in question first.
q->dw.collect_srcfiles_matching (q->file, q->filtered_srcfiles);
// If we have a file pattern and *no* srcfile matches, there's
// no need to look further into this CU, so skip.
if (q->filtered_srcfiles.empty())
return DWARF_CB_OK;
}
// Pick up [entrypc, name, DIE] tuples for all the functions
// matching the query, and fill in the prologue endings of them
// all in a single pass.
q->dw.iterate_over_functions (query_dwarf_func, q, q->function);
if (!q->filtered_functions.empty() &&
!q->has_statement_str && // PR 2608
q->sess.prologue_searching_mode != systemtap_session::prologue_searching_never &&
(q->sess.prologue_searching_mode == systemtap_session::prologue_searching_always ||
(q->has_process && !q->dw.has_valid_locs()))) // PR 6871 && PR 6941
q->dw.resolve_prologue_endings (q->filtered_functions);
if (q->has_label)
{
enum lineno_t lineno_type = WILDCARD;
if (q->spec_type == function_file_and_line)
lineno_type = q->lineno_type;
auto bfis = q->filtered_all();
for (auto i = bfis.begin(); i != bfis.end(); ++i)
q->dw.iterate_over_labels (&i->die, q->label_val, *i, q->linenos,
lineno_type, q, query_label);
}
else if (q->has_callee || q->has_callees_num)
{
// .callee(str) --> str, .callees[(N)] --> "*"
string callee_val = q->has_callee ? q->callee_val : "*";
int64_t callees_num_val = q->has_callees_num ? q->callees_num_val : 1;
// NB: We filter functions that do not match the file here rather than
// in query_callee because we only want the filtering to apply to the
// first level, not to callees that are recursed into if
// callees_num_val > 1.
auto bfis = q->filtered_all();
for (auto i = bfis.begin(); i != bfis.end(); ++i)
{
if (q->spec_type != function_alone &&
q->filtered_srcfiles.count(i->decl_file) == 0)
continue;
q->dw.iterate_over_callees (&i->die, callee_val,
callees_num_val,
q, query_callee, *i);
}
}
else if (q->spec_type == function_file_and_line
// User specified function, file and lineno, but if they match
// exactly a specific function in a specific line at a specific
// decl_line, the user doesn't actually want to probe a lineno,
// but rather the function itself. So let fall through to
// query_func_info/query_inline_instance_info in final else.
&& !q->is_fully_specified_function()
&& !q->has_function_str)
{
auto bfis = q->filtered_all();
for (auto srcfile = q->filtered_srcfiles.cbegin();
srcfile != q->filtered_srcfiles.cend(); ++srcfile)
q->dw.iterate_over_srcfile_lines(srcfile->c_str(), q->linenos,
q->lineno_type, bfis,
query_srcfile_line,
q->has_nearest, q);
}
else
{
// .statement(...:NN) often gets mixed up with .function(...:NN)
if (q->spec_type == function_file_and_line
&& !q->is_fully_specified_function()
&& q->has_function_str)
q->sess.print_warning (_("For probing a particular line, use a "
".statement() probe, not .function()"),
q->base_probe->tok);
// Otherwise, simply probe all resolved functions.
for (auto i = q->filtered_functions.begin();
i != q->filtered_functions.end(); ++i)
query_func_info (i->entrypc, *i, q);
// And all inline instances (if we're not excluding inlines with ".call")
if (! q->has_call)
for (auto i = q->filtered_inlines.begin();
i != q->filtered_inlines.end(); ++i)
query_inline_instance_info (*i, q);
}
return DWARF_CB_OK;
}
catch (const semantic_error& e)
{
// q->sess.print_error (e);
throw;
// return DWARF_CB_ABORT;
}
}
void
dwarf_query::query_module_functions ()
{
try
{
filtered_srcfiles.clear();
filtered_functions.clear();
filtered_inlines.clear();
// Collect all module functions so we know which CUs are interesting
int rc = dw.iterate_single_function(query_dwarf_func, this, function);
if (rc != DWARF_CB_OK)
return;
set<void*> used_cus; // by cu->addr
vector<Dwarf_Die> cus;
Dwarf_Die cu_mem;
auto bfis = filtered_all();
for (auto i = bfis.begin(); i != bfis.end(); ++i)
if (dwarf_diecu(&i->die, &cu_mem, NULL, NULL) &&
used_cus.insert(cu_mem.addr).second)
cus.push_back(cu_mem);
// Reset the dupes since we didn't actually collect them the first time
alias_dupes.clear();
inline_dupes.clear();
// Run the query again on the individual CUs
for (auto i = cus.begin(); i != cus.end(); ++i){
rc = query_cu(&*i, this);
if (rc != DWARF_CB_OK)
return;
}
}
catch (const semantic_error& e)
{
sess.print_error (e);
}
}
static bool
validate_module_elf (systemtap_session& sess,
Dwfl_Module *mod, const char *name, base_query *q)
{
// Validate the machine code in this elf file against the
// session machine. This is important, in case the wrong kind
// of debuginfo is being automagically processed by elfutils.
// While we can tell i686 apart from x86-64, unfortunately
// we can't help confusing i586 vs i686 (both EM_386).
//
// In case of a mismatch, soft-reject (ignore it with a warning).
// This is important in case of probing by buildid or mass
// debuginfod where some random architecture's module might come
// back.
Dwarf_Addr bias;
// We prefer dwfl_module_getdwarf to dwfl_module_getelf here,
// because dwfl_module_getelf can force costly section relocations
// we don't really need, while either will do for this purpose.
Elf* elf = (dwarf_getelf (dwfl_module_getdwarf (mod, &bias))
?: dwfl_module_getelf (mod, &bias));
GElf_Ehdr ehdr_mem;
GElf_Ehdr* em = gelf_getehdr (elf, &ehdr_mem);
if (em == 0) { DWFL_ASSERT ("dwfl_getehdr", dwfl_errno()); }
assert(em);
int elf_machine = em->e_machine;
const char* debug_filename = "";
const char* main_filename = "";
(void) dwfl_module_info (mod, NULL, NULL,
NULL, NULL, NULL,
& main_filename,
& debug_filename);
const string& sess_machine = q->sess.architecture;
string expect_machine; // to match sess.machine (i.e., kernel machine)
string expect_machine2;
// NB: See also the 'uname -m' squashing done in main.cxx.
switch (elf_machine)
{
// x86 and ppc are bi-architecture; a 64-bit kernel
// can normally run either 32-bit or 64-bit *userspace*.
case EM_386:
expect_machine = "i?86";
if (! q->has_process) break; // 32-bit kernel/module
/* Fallthrough */
case EM_X86_64:
expect_machine2 = "x86_64";
break;
case EM_PPC:
case EM_PPC64:
expect_machine = "powerpc";
break;
case EM_S390: expect_machine = "s390"; break;
case EM_IA_64: expect_machine = "ia64"; break;
case EM_ARM: expect_machine = "arm*"; break;
case EM_AARCH64: expect_machine = "arm64"; break;
case EM_MIPS: expect_machine = "mips"; break;
case EM_RISCV: expect_machine = "riscv"; break;
// XXX: fill in some more of these
default: expect_machine = "?"; break;
}
if (! debug_filename) debug_filename = main_filename;
if (! debug_filename) debug_filename = name;
if (fnmatch (expect_machine.c_str(), sess_machine.c_str(), 0) != 0 &&
fnmatch (expect_machine2.c_str(), sess_machine.c_str(), 0) != 0)
{
sess.print_warning (_F("ELF machine %s|%s (code %d) mismatch with target %s in '%s'",
expect_machine.c_str(), expect_machine2.c_str(), elf_machine,
sess_machine.c_str(), debug_filename));
return false;
}
if (q->sess.verbose>2)
clog << _F("focused on module '%s' = [%#" PRIx64 "-%#" PRIx64 ", bias %#" PRIx64
" file %s ELF machine %s|%s (code %d)\n",
q->dw.module_name.c_str(), q->dw.module_start, q->dw.module_end,
q->dw.module_bias, debug_filename, expect_machine.c_str(),
expect_machine2.c_str(), elf_machine);
return true;
}
static Dwarf_Addr
lookup_symbol_address (Dwfl_Module *m, const char* wanted)
{
int syments = dwfl_module_getsymtab(m);
assert(syments);
for (int i = 1; i < syments; ++i)
{
GElf_Sym sym;
const char *name = dwfl_module_getsym(m, i, &sym, NULL);
if (name != NULL && strcmp(name, wanted) == 0)
return sym.st_value;
}
return 0;
}
static int
query_module (Dwfl_Module *mod,
void **,
const char *name,
Dwarf_Addr addr,
base_query *q)
{
try
{
module_info* mi = q->sess.module_cache->cache[name];
if (mi == 0)
{
mi = q->sess.module_cache->cache[name] = new module_info(name);
mi->mod = mod;
mi->addr = addr;
const char* debug_filename = "";
const char* main_filename = "";
(void) dwfl_module_info (mod, NULL, NULL,
NULL, NULL, NULL,
& main_filename,
& debug_filename);
if (debug_filename || main_filename)
{
mi->elf_path = debug_filename ?: main_filename;
}
else if (name == TOK_KERNEL)
{
mi->dwarf_status = info_absent;
}
}
// OK, enough of that module_info caching business.
q->dw.focus_on_module(mod, mi);
// If we have enough information in the pattern to skip a module and
// the module does not match that information, return early.
if (!q->dw.module_name_matches(q->module_val))
return pending_interrupts ? DWARF_CB_ABORT : DWARF_CB_OK;
// Don't allow module("*kernel*") type expressions to match the
// elfutils module "kernel", which we refer to in the probe
// point syntax exclusively as "kernel.*".
if (q->dw.module_name == TOK_KERNEL && ! q->has_kernel)
return pending_interrupts ? DWARF_CB_ABORT : DWARF_CB_OK;
if (mod)
{
if (! validate_module_elf(q->sess, mod, name, q))
return DWARF_CB_OK;
}
else
assert(q->has_kernel); // and no vmlinux to examine
if (q->sess.verbose>2)
cerr << _F("focused on module '%s'\n", q->dw.module_name.c_str());
// Collect a few kernel addresses. XXX: these belong better
// to the sess.module_info["kernel"] struct.
if (q->dw.module_name == TOK_KERNEL)
{
if (! q->sess.sym_kprobes_text_start)
q->sess.sym_kprobes_text_start = lookup_symbol_address (mod, "__kprobes_text_start");
if (! q->sess.sym_kprobes_text_end)
q->sess.sym_kprobes_text_end = lookup_symbol_address (mod, "__kprobes_text_end");
if (! q->sess.sym_stext)
q->sess.sym_stext = lookup_symbol_address (mod, "_stext");
}
// If there is a .library component, then q->path will hold the path to
// the executable if the library was fully resolved. If not (e.g. not
// absolute, or globby), resort to iterate_over_libraries().
if (q->has_library && q->path.empty())
q->dw.iterate_over_libraries (&q->query_library_callback, q);
// .plt is translated to .plt.statement(N). We only want to iterate for the
// .plt case
else if (q->has_plt && ! q->has_statement)
{
q->dw.iterate_over_plt (q, &q->query_plt_callback);
q->visited_modules.insert(name);
}
else
{
// search the module for matches of the probe point.
q->handle_query_module();
q->visited_modules.insert(name);
}
// If we know that there will be no more matches, abort early.
if (q->dw.module_name_final_match(q->module_val) || pending_interrupts)
return DWARF_CB_ABORT;
else
return DWARF_CB_OK;
}
catch (const semantic_error& e)
{
// q->sess.print_error (e);
// return DWARF_CB_ABORT;
throw;
}
}
void
base_query::query_library_callback (base_query *me, const char *data)
{
me->query_library (data);
}
probe*
build_library_probe(dwflpp& dw,
const string& library,
probe *base_probe,
probe_point *base_loc)
{
probe_point* specific_loc = new probe_point(*base_loc);
vector<probe_point::component*> derived_comps;
// Create new probe point for the matching library. This is what will be
// shown in listing mode. Also replace the process(str) with the real
// absolute path rather than keeping what the user typed in.
for (auto it = specific_loc->components.begin();
it != specific_loc->components.end(); ++it)
if ((*it)->functor == TOK_PROCESS)
derived_comps.push_back(new probe_point::component(TOK_PROCESS,
new literal_string(path_remove_sysroot(dw.sess, dw.module_name))));
else if ((*it)->functor == TOK_LIBRARY)
derived_comps.push_back(new probe_point::component(TOK_LIBRARY,
new literal_string(path_remove_sysroot(dw.sess, library)),
true /* from_glob */ ));
else
derived_comps.push_back(*it);
probe_point* derived_loc = new probe_point(*specific_loc);
derived_loc->components = derived_comps;
return new probe (new probe (base_probe, specific_loc), derived_loc);
}
bool
query_one_library (const char *library, dwflpp & dw,
const string user_lib, probe * base_probe, probe_point *base_loc,
vector<derived_probe *> & results)
{
if (dw.function_name_matches_pattern(library, "*" + user_lib))
{
string library_path = find_executable (library, "", dw.sess.sysenv,
"LD_LIBRARY_PATH");
probe *new_base = build_library_probe(dw, library_path,
base_probe, base_loc);
// We pass true for the optional parameter of derive_probes() here to
// indicate that we don't mind if the probe doesn't resolve. This is
// because users expect wildcarded probe points to only apply to a subset
// of matching libraries, in the sense of "any", rather than "all", just
// like module("*") and process("*"). See also dwarf_builder::build().
derive_probes(dw.sess, new_base, results, true /* optional */ );
if (dw.sess.verbose > 2)
clog << _("module=") << library_path << endl;
return true;
}
return false;
}
void
dwarf_query::query_library (const char *library)
{
visited_libraries.insert(library);
if (query_one_library (library, dw, user_lib, base_probe, base_loc, results))
resolved_library = true;
}
struct plt_expanding_visitor: public var_expanding_visitor
{
plt_expanding_visitor(systemtap_session&s, const string & entry):
var_expanding_visitor (s),
entry (entry)
{
}
const string & entry;
void visit_target_symbol (target_symbol* e);
};
void
base_query::query_plt_callback (base_query *me, const char *entry, size_t address)
{
if (me->dw.function_name_matches_pattern (entry, me->plt_val))
me->query_plt (entry, address);
me->dw.mod_info->plt_funcs.insert(entry);
}
void
query_one_plt (const char *entry, long addr, dwflpp & dw,
probe * base_probe, probe_point *base_loc,
vector<derived_probe *> & results, base_query *q)
{
interned_string module = dw.module_name;
if (q->has_process)
module = path_remove_sysroot(dw.sess, module);
probe_point* specific_loc = new probe_point(*base_loc);
specific_loc->well_formed = true;
vector<probe_point::component*> derived_comps;
if (dw.sess.verbose > 2)
clog << _F("plt entry=%s\n", entry);
for (auto it = specific_loc->components.begin();
it != specific_loc->components.end(); ++it)
if ((*it)->functor == TOK_PROCESS)
{
// Replace with fully resolved path
*it = new probe_point::component(TOK_PROCESS,
new literal_string(q->has_library ? q->path : module));
derived_comps.push_back(*it);
}
else if ((*it)->functor == TOK_PLT)
{
// Replace possibly globby component
*it = new probe_point::component(TOK_PLT,
new literal_string(string(entry)));
derived_comps.push_back(*it);
derived_comps.push_back(new probe_point::component(TOK_STATEMENT,
new literal_number(addr, true)));
}
else
derived_comps.push_back(*it);
probe_point* derived_loc = new probe_point(*specific_loc);
derived_loc->components = derived_comps;
probe *new_base = new probe (new probe (base_probe, specific_loc),
derived_loc);
string e = string(entry);
plt_expanding_visitor pltv (dw.sess, e);
var_expand_const_fold_loop (dw.sess, new_base->body, pltv);
literal_map_t params;
for (unsigned i = 0; i < derived_loc->components.size(); ++i)
{
probe_point::component *c = derived_loc->components[i];
params[c->functor] = c->arg;
}
dwarf_query derived_q(new_base, derived_loc, dw, params, results, "", "");
dw.iterate_over_modules<base_query>(&query_module, &derived_q);
}
void
dwarf_query::query_plt (const char *entry, size_t address)
{
query_one_plt (entry, address, dw, base_probe, base_loc, results, this);
}
// This would more naturally fit into elaborate.cxx:semantic_pass_symbols,
// but the needed declaration for module_cache is not available there.
// Nor for that matter in session.cxx. Only in this CU is that field ever
// set (in query_module() above), so we clean it up here too.
static void
delete_session_module_cache (systemtap_session& s)
{
if (s.module_cache) {
if (s.verbose > 3)
clog << _("deleting module_cache") << endl;
delete s.module_cache;
s.module_cache = 0;
}
}
struct dwarf_var_expanding_visitor: public var_expanding_visitor
{
dwarf_query & q;
Dwarf_Die *scope_die;
Dwarf_Addr addr;
block *add_block;
block *add_call_probe; // synthesized from .return probes with saved $vars
// NB: tids are not always collected in add_block & add_call_probe, because
// gen_kretprobe_saved_return doesn't need them. Thus we need these extra
// *_tid bools for gen_mapped_saved_return to tell what's there.
bool add_block_tid, add_call_probe_tid;
unsigned saved_longs, saved_strings; // data saved within kretprobes
unordered_map<Dwarf_Addr, block *> entry_probes;
unordered_map<std::string, expression *> return_ts_map;
vector<Dwarf_Die> scopes;
// probe counter name -> pointer of associated probe
std::set<std::string> perf_counter_refs;
bool visited;
dwarf_var_expanding_visitor(dwarf_query & q, Dwarf_Die *sd, Dwarf_Addr a):
var_expanding_visitor(q.sess),
q(q), scope_die(sd), addr(a), add_block(NULL), add_call_probe(NULL),
add_block_tid(false), add_call_probe_tid(false),
saved_longs(0), saved_strings(0), visited(false) {}
expression* gen_mapped_saved_return(expression* e, const string& name);
expression* gen_kretprobe_saved_return(expression* e);
void visit_target_symbol_saved_return (target_symbol* e);
void visit_target_symbol_context (target_symbol* e);
void visit_target_symbol (target_symbol* e);
void visit_atvar_op (atvar_op* e);
void visit_cast_op (cast_op* e);
void visit_entry_op (entry_op* e);
void visit_perf_op (perf_op* e);
private:
vector<Dwarf_Die>& getscopes(target_symbol *e);
};
unsigned var_expanding_visitor::tick = 0;
var_expanding_visitor::var_expanding_visitor (systemtap_session& s):
update_visitor(s.verbose), sess(s), op()
{
// FIXME: for the time being, by default we only support plain '$foo
// = bar', not '+=' or any other op= variant. This is fixable, but a
// bit ugly.
//
// If derived classes desire to add additional operator support, add
// new operators to this list in the derived class constructor.
valid_ops.insert ("=");
}
void
var_expanding_visitor::provide_lvalue_call(functioncall* fcall)
{
// Provide the functioncall to our parent, so that it can be used to
// substitute for the assignment node immediately above us.
assert(!target_symbol_setter_functioncalls.empty());
*(target_symbol_setter_functioncalls.top()) = fcall;
}
bool
var_expanding_visitor::rewrite_lvalue(const token* tok, interned_string& eop,
expression*& lvalue, expression*& rvalue)
{
// Our job would normally be to require() the left and right sides
// into a new assignment. What we're doing is slightly trickier:
// we're pushing a functioncall** onto a stack, and if our left
// child sets the functioncall* for that value, we're going to
// assume our left child was a target symbol -- transformed into a
// set_target_foo(value) call, and it wants to take our right child
// as the argument "value".
//
// This is why some people claim that languages with
// constructor-decomposing case expressions have a leg up on
// visitors.
functioncall *fcall = NULL;
// Let visit_target_symbol know what operator it should handle.
interned_string* old_op = op;
op = & eop;
target_symbol_setter_functioncalls.push (&fcall);
replace (lvalue);
target_symbol_setter_functioncalls.pop ();
replace (rvalue);
op = old_op;
if (fcall != NULL)
{
// Our left child is informing us that it was a target variable
// and it has been replaced with a set_target_foo() function
// call; we are going to provide that function call -- with the
// right child spliced in as sole argument -- in place of
// ourselves, in the var expansion we're in the middle of making.
if (valid_ops.find (eop) == valid_ops.end ())
{
// Build up a list of supported operators.
string ops;
int valid_ops_size = 0;
for (auto i = valid_ops.begin(); i != valid_ops.end(); i++)
{
ops += " " + *i + ",";
valid_ops_size++;
}
ops.resize(ops.size() - 1); // chop off the last ','
// Throw the error.
throw SEMANTIC_ERROR (_NF("Only the following assign operator is implemented on target variables: %s",
"Only the following assign operators are implemented on target variables: %s",
valid_ops_size, ops.c_str()), tok);
}
assert (lvalue == fcall);
if (rvalue)
fcall->args.push_back (rvalue);
provide (fcall);
return true;
}
else
return false;
}
void
var_expanding_visitor::visit_assignment (assignment* e)
{
if (!rewrite_lvalue (e->tok, e->op, e->left, e->right))
provide (e);
}
void
var_expanding_visitor::visit_pre_crement (pre_crement* e)
{
expression *dummy = NULL;
if (!rewrite_lvalue (e->tok, e->op, e->operand, dummy))
provide (e);
}
void
var_expanding_visitor::visit_post_crement (post_crement* e)
{
expression *dummy = NULL;
if (!rewrite_lvalue (e->tok, e->op, e->operand, dummy))
provide (e);
}
void
var_expanding_visitor::visit_delete_statement (delete_statement* s)
{
string fakeop = "delete";
interned_string fopr = fakeop;
expression *dummy = NULL;
if (!rewrite_lvalue (s->tok, fopr, s->value, dummy))
provide (s);
}
void
var_expanding_visitor::visit_defined_op (defined_op* e)
{
expression * const old_operand = e->operand;
bool resolved = true;
defined_ops.push (e);
try {
replace (e->operand);
// NB: Formerly, we had some curious cases to consider here, depending on what
// various visit_target_symbol() implementations do for successful or
// erroneous resolutions. Some would signal a visit_target_symbol failure
// with an exception, with a set flag within the target_symbol, or nothing
// at all.
//
// Now, failures always have to be signalled with a
// saved_conversion_error being chained to the target_symbol.
// Successes have to result in an attempted rewrite of the
// target_symbol (via provide()).
//
// Edna Mode: "no capes". fche: "no exceptions". reality: not that simple
// dwarf stuff: success: rewrites to a function; failure: retains target_symbol, sets saved_conversion_error
//
// sdt-kprobes sdt.h: success: string or functioncall; failure: semantic_error
//
// sdt-uprobes: success: string or no op; failure: no op; expect derived/synthetic
// dwarf probe to take care of it.
// But this is rather unhelpful. So we rig the sdt_var_expanding_visitor
// to pass through @defined() to the synthetic dwarf probe.
//
// utrace: success: rewrites to function; failure: semantic_error
//
// procfs: success: rewrites to function; failure: semantic_error
//
// ... but @defined() can nest other types of expressions too, for better or for worse,
// which can result in semantic_error.
target_symbol* tsym = dynamic_cast<target_symbol*> (e->operand);
if (tsym && tsym->saved_conversion_error) // failing
resolved = false;
else if (e->operand == old_operand) // unresolved but not marked failing
{
// There are some visitors that won't touch certain target_symbols,
// e.g. dwarf_var_expanding_visitor won't resolve @cast. We should
// leave it for now so some other visitor can have a chance.
defined_ops.pop ();
provide (e);
return;
}
else // resolved, rewritten to some other expression type
resolved = true;
} catch (const semantic_error& e) {
// some uncooperative value like @perf("NO_SUCH_VALUE")
resolved = false;
}
defined_ops.pop ();
if (sess.verbose>2)
clog << _("Resolving ") << *e << ": " << resolved << endl;
literal_number* ln = new literal_number (resolved ? 1 : 0);
ln->tok = e->tok;
abort_provide (ln); // PR20672; stop updating visitor
}
// Traverse a staptree*, looking for any operation that requires probe
// context to work
struct context_op_finder: public traversing_visitor
{
public:
bool context_op_p;
context_op_finder(): context_op_p(false) {}
void visit_target_symbol (target_symbol* e)
{ context_op_p = true; traversing_visitor::visit_target_symbol(e); }
void visit_defined_op (defined_op* e)
{ context_op_p = true; traversing_visitor::visit_defined_op(e); }
void visit_atvar_op (atvar_op* e)
{ context_op_p = true; traversing_visitor::visit_atvar_op(e); }
void visit_cast_op (cast_op* e) // if module is specified, not a context_op_p
{ if (e->module == "") context_op_p = true; traversing_visitor::visit_cast_op(e); }
void visit_autocast_op (autocast_op* e) // XXX do these show up early?
{ context_op_p = true; traversing_visitor::visit_autocast_op(e); }
void visit_perf_op (perf_op* e)
{ context_op_p = true; traversing_visitor::visit_perf_op(e); }
};
void
var_expanding_visitor::visit_functioncall (functioncall* e)
{
update_visitor::visit_functioncall(e); // for arguments etc.
if (strverscmp(sess.compatible.c_str(), "4.3") >= 0 && // PR25841 behaviour
e->referents.size() == 0 && // first time seeing this functioncall
sess.symbol_resolver && // from some sort of symbol-resolution context
sess.symbol_resolver->current_probe) // prevent being called from semantic_pass_symbols function-only loop
{
// need to early resolve
auto refs = sess.symbol_resolver->find_functions (e, e->function, e->args.size (), e->tok);
vector<functiondecl*> copyrefs;
for (auto ri = refs.begin(); ri != refs.end(); ri++)
{
auto r = *ri;
// We accumulate these functiondecls, so we don't recurse infinitely.
// Recursive functions will be handled correctly though because the second
// time we clone, the first clone will be found & reused.
if (early_resolution_in_progress.find(r) != early_resolution_in_progress.end())
continue;
context_op_finder cop;
r->body->visit(& cop);
if (cop.context_op_p) // need to clone
{
r->cloned_p = true; // so don't warn about elision later
if (sess.verbose > 2)
clog << _("need a clone of context-op function ") << *r->tok << endl;
// check if we already cloned it, e.g. if we have two
// calls to the same function from a probe.
string clone_function_name = string("__clone_") +
sess.symbol_resolver->current_probe->name() + string("_of_") + string(r->name);
auto johnny = sess.functions.find(clone_function_name);
if (johnny != sess.functions.end())
{
if (sess.verbose > 3)
clog << _("reusing previous clone") << endl;
e->function = johnny->first; // overwrite functioncall name for -p2 disambiguation
copyrefs.push_back(johnny->second);
continue;
}
// nope, must make a new clone
auto nf = new functiondecl();
nf->synthetic = true;
nf->tok = r->tok;
// nf->unmangled_name = r->unmangled_name;
nf->unmangled_name = nf->name = clone_function_name;
nf->mangle_oldstyle = r->mangle_oldstyle;
nf->has_next = r->has_next;
nf->priority = r->priority;
for (auto ji = r->formal_args.begin(); ji != r->formal_args.end(); ji++)
{
auto j = *ji;
auto v = new vardecl();
v->type = pe_unknown; // = j->type anyway; we're before type inference
v->tok = j->tok;
v->name = j->name;
v->unmangled_name = j->unmangled_name;
nf->formal_args.push_back (v);
}
// leave empty locals, unused_locals -- they'll be filled soon
// deep_copy the body then process it recursively
nf->body = deep_copy_visitor::deep_copy(r->body);
early_resolution_in_progress.insert(r);
require (nf->body, false); // process it recursively
early_resolution_in_progress.erase(r);
sess.functions.insert(make_pair(nf->name, nf));
e->function = nf->name; // overwrite functioncall name for -p2 disambiguation
copyrefs.push_back(nf);
if (sess.verbose > 3) {
clog << _("clone: ");
nf->print(clog);
clog << endl;
}
}
else
copyrefs = refs; // already added into s.functions[]
}
e->referents = copyrefs;
}
else if (strverscmp(sess.compatible.c_str(), "4.3") >= 0 && // PR25841 behaviour
e->referents.size() != 0) // second or later time calling
{
for (auto ri = e->referents.begin(); ri != e->referents.end(); ri++)
{
auto r = *ri;
if (early_resolution_in_progress.find(r) != early_resolution_in_progress.end())
{
// already warned earlier
continue;
}
early_resolution_in_progress.insert(r);
require (r->body, false); // process it recursively
early_resolution_in_progress.erase(r);
}
}
}
struct dwarf_pretty_print
{
dwarf_pretty_print (dwflpp& dw, vector<Dwarf_Die>& scopes, Dwarf_Addr pc,
const string& local, bool userspace_p,
const target_symbol& e, bool lvalue):
dw(dw), local(local), scopes(scopes), pc(pc),
pointer(NULL), pointer_type(),
userspace_p(userspace_p), deref_p(true)
{
init_ts (e);
dw.type_die_for_local (scopes, pc, local, ts, &base_type, lvalue);
}
dwarf_pretty_print (dwflpp& dw, Dwarf_Die *scope_die, Dwarf_Addr pc,
bool userspace_p, const target_symbol& e, bool lvalue):
dw(dw), scopes(1, *scope_die), pc(pc),
pointer(NULL), pointer_type(),
userspace_p(userspace_p), deref_p(true)
{
init_ts (e);
dw.type_die_for_return (&scopes[0], pc, ts, &base_type, lvalue);
}
dwarf_pretty_print (dwflpp& dw, Dwarf_Die *type_die, expression* pointer,
bool deref_p, bool userspace_p, const target_symbol& e,
bool lvalue):
dw(dw), pc(0), pointer(pointer), pointer_type(*type_die),
userspace_p(userspace_p), deref_p(deref_p)
{
init_ts (e);
dw.type_die_for_pointer (type_die, ts, &base_type, lvalue);
}
functioncall* expand ();
~dwarf_pretty_print () { delete ts; }
private:
dwflpp& dw;
target_symbol* ts;
bool print_full;
Dwarf_Die base_type;
string local;
vector<Dwarf_Die> scopes;
Dwarf_Addr pc;
expression* pointer;
Dwarf_Die pointer_type;
const bool userspace_p, deref_p;
void recurse (Dwarf_Die* type, target_symbol* e,
print_format* pf, bool top=false);
void recurse_bitfield (Dwarf_Die* type, target_symbol* e,
print_format* pf);
void recurse_base (Dwarf_Die* type, target_symbol* e,
print_format* pf);
void recurse_array (Dwarf_Die* type, target_symbol* e,
print_format* pf, bool top);
void recurse_pointer (Dwarf_Die* type, target_symbol* e,
print_format* pf, bool top);
void recurse_struct (Dwarf_Die* type, target_symbol* e,
print_format* pf, bool top);
void recurse_struct_members (Dwarf_Die* type, target_symbol* e,
print_format* pf, int& count);
bool print_chars (Dwarf_Die* type, target_symbol* e, print_format* pf);
void init_ts (const target_symbol& e);
expression* deref (target_symbol* e);
bool push_deref (print_format* pf, const string& fmt, target_symbol* e);
};
void
dwarf_pretty_print::init_ts (const target_symbol& e)
{
// Work with a new target_symbol so we can modify arguments
ts = new target_symbol (e);
if (ts->addressof)
throw SEMANTIC_ERROR(_("cannot take address of pretty-printed variable"), ts->tok);
size_t depth = ts->pretty_print_depth ();
if (depth == 0)
throw SEMANTIC_ERROR(_("invalid target_symbol for pretty-print"), ts->tok);
print_full = depth > 1;
ts->components.pop_back();
}
functioncall*
dwarf_pretty_print::expand ()
{
static unsigned tick = 0;
// function pretty_print_X([pointer], [arg1, arg2, ...]) {
// try {
// return sprintf("{.foo=...}", (ts)->foo, ...)
// } catch {
// return "ERROR"
// }
// }
// Create the function decl and call.
string fhash = detox_path(string(ts->tok->location.file->name));
functiondecl *fdecl = new functiondecl;
fdecl->tok = ts->tok;
fdecl->synthetic = true;
fdecl->unmangled_name = fdecl->name = "__private_" + fhash
+ "_dwarf_pretty_print_" + lex_cast(tick++);
fdecl->type = pe_string;
functioncall* fcall = new functioncall;
fcall->referents.push_back(fdecl); // may be needed for post-pass2a sym resolution; autocast08.stp
fcall->tok = ts->tok;
fcall->function = fdecl->name;
fcall->type = pe_string;
// If there's a <pointer>, replace it with a new var and make that
// the first function argument.
if (pointer)
{
vardecl *v = new vardecl;
v->type = pe_long;
v->name = v->unmangled_name = "pointer";
v->tok = ts->tok;
v->synthetic = true;
fdecl->formal_args.push_back (v);
fcall->args.push_back (pointer);
symbol* sym = new symbol;
sym->tok = ts->tok;
sym->name = v->name;
pointer = sym;
}
// For each expression argument, replace it with a function argument.
for (unsigned i = 0; i < ts->components.size(); ++i)
if (ts->components[i].type == target_symbol::comp_expression_array_index)
{
vardecl *v = new vardecl;
v->type = pe_long;
v->unmangled_name = v->name = "index" + lex_cast(i);
v->tok = ts->tok;
fdecl->formal_args.push_back (v);
fcall->args.push_back (ts->components[i].expr_index);
symbol* sym = new symbol;
sym->tok = ts->tok;
sym->name = v->name;
ts->components[i].expr_index = sym;
}
// Create the return sprintf.
print_format* pf = print_format::create(ts->tok, "sprintf");
return_statement* rs = new return_statement;
rs->tok = ts->tok;
rs->value = pf;
// Recurse into the actual values.
recurse (&base_type, ts, pf, true);
pf->components = print_format::string_to_components(pf->raw_components);
// Create the try-catch net
try_block* tb = new try_block;
tb->tok = ts->tok;
tb->try_block = rs;
tb->catch_error_var = 0;
return_statement* rs2 = new return_statement;
rs2->tok = ts->tok;
rs2->value = new literal_string (string("ERROR"));
rs2->value->tok = ts->tok;
tb->catch_block = rs2;
fdecl->body = tb;
fdecl->join (dw.sess);
return fcall;
}
void
dwarf_pretty_print::recurse (Dwarf_Die* start_type, target_symbol* e,
print_format* pf, bool top)
{
// deal with initial void* pointers
if (!deref_p && null_die(start_type))
{
push_deref (pf, "%p", e);
return;
}
Dwarf_Die type;
dw.resolve_unqualified_inner_typedie (start_type, &type, e);
switch (dwarf_tag(&type))
{
default:
// XXX need a warning?
// throw semantic_error ("unsupported type (tag " + lex_cast(dwarf_tag(&type))
// + ") for " + dwarf_type_name(&type), e->tok);
pf->raw_components.append("?");
break;
case DW_TAG_enumeration_type:
case DW_TAG_base_type:
recurse_base (&type, e, pf);
break;
case DW_TAG_array_type:
recurse_array (&type, e, pf, top);
break;
case DW_TAG_pointer_type:
case DW_TAG_reference_type:
case DW_TAG_rvalue_reference_type:
recurse_pointer (&type, e, pf, top);
break;
case DW_TAG_subroutine_type:
push_deref (pf, "<function>:%p", e);
break;
case DW_TAG_union_type:
case DW_TAG_structure_type:
case DW_TAG_class_type:
recurse_struct (&type, e, pf, top);
break;
}
}
// Bit fields are handled as a special-case combination of recurse() and
// recurse_base(), only called from recurse_struct_members(). The main
// difference is that the value is always printed numerically, even if the
// underlying type is a char.
void
dwarf_pretty_print::recurse_bitfield (Dwarf_Die* start_type, target_symbol* e,
print_format* pf)
{
Dwarf_Die type;
dw.resolve_unqualified_inner_typedie (start_type, &type, e);
int tag = dwarf_tag(&type);
if (tag != DW_TAG_base_type && tag != DW_TAG_enumeration_type)
{
// XXX need a warning?
// throw semantic_error ("unsupported bitfield type (tag " + lex_cast(tag)
// + ") for " + dwarf_type_name(&type), e->tok);
pf->raw_components.append("?");
return;
}
Dwarf_Attribute attr;
Dwarf_Word encoding = (Dwarf_Word) -1;
dwarf_formudata (dwarf_attr_integrate (&type, DW_AT_encoding, &attr),
&encoding);
switch (encoding)
{
case DW_ATE_float:
case DW_ATE_complex_float:
// XXX need a warning?
// throw semantic_error ("unsupported bitfield type (encoding " + lex_cast(encoding)
// + ") for " + dwarf_type_name(&type), e->tok);
pf->raw_components.append("?");
break;
case DW_ATE_unsigned:
case DW_ATE_unsigned_char:
push_deref (pf, "%u", e);
break;
case DW_ATE_signed:
case DW_ATE_signed_char:
default:
push_deref (pf, "%i", e);
break;
}
}
void
dwarf_pretty_print::recurse_base (Dwarf_Die* type, target_symbol* e,
print_format* pf)
{
Dwarf_Attribute attr;
Dwarf_Word encoding = (Dwarf_Word) -1;
dwarf_formudata (dwarf_attr_integrate (type, DW_AT_encoding, &attr),
&encoding);
switch (encoding)
{
case DW_ATE_float:
case DW_ATE_complex_float:
// XXX need a warning?
// throw semantic_error ("unsupported type (encoding " + lex_cast(encoding)
// + ") for " + dwarf_type_name(type), e->tok);
pf->raw_components.append("?");
break;
case DW_ATE_UTF: // XXX need to add unicode to _stp_vsprint_char
case DW_ATE_signed_char:
case DW_ATE_unsigned_char:
// Use escapes to make sure that non-printable characters
// don't interrupt our stream (especially '\0' values).
push_deref (pf, "'%#c'", e);
break;
case DW_ATE_unsigned:
push_deref (pf, "%u", e);
break;
case DW_ATE_signed:
default:
push_deref (pf, "%i", e);
break;
}
}
void
dwarf_pretty_print::recurse_array (Dwarf_Die* type, target_symbol* e,
print_format* pf, bool top)
{
if (!top && !print_full)
{
pf->raw_components.append("[...]");
return;
}
Dwarf_Die childtype;
dwarf_attr_die (type, DW_AT_type, &childtype);
if (print_chars (&childtype, e, pf))
return;
pf->raw_components.append("[");
// We print the array up to the first 5 elements.
// XXX how can we determine the array size?
// ... for now, just print the first element
// NB: limit to 32 args; see PR10750 and c_unparser::visit_print_format.
unsigned i, size = 1;
for (i=0; i < size && i < 5 && pf->args.size() < 32; ++i)
{
if (i > 0)
pf->raw_components.append(", ");
target_symbol* e2 = new target_symbol(*e);
e2->components.push_back (target_symbol::component(e->tok, i));
recurse (&childtype, e2, pf);
}
if (i < size || 1/*XXX until real size is known */)
pf->raw_components.append(", ...");
pf->raw_components.append("]");
}
void
dwarf_pretty_print::recurse_pointer (Dwarf_Die* type, target_symbol* e,
print_format* pf, bool top)
{
// We chase to top-level pointers, but leave the rest alone
bool void_p = true;
Dwarf_Die pointee;
if (dwarf_attr_die (type, DW_AT_type, &pointee))
{
try
{
dw.resolve_unqualified_inner_typedie (&pointee, &pointee, e);
void_p = false;
}
catch (const semantic_error&) {}
}
if (!void_p)
{
if (print_chars (&pointee, e, pf))
return;
if (top)
{
recurse (&pointee, e, pf, top);
return;
}
}
push_deref (pf, "%p", e);
}
void
dwarf_pretty_print::recurse_struct (Dwarf_Die* type, target_symbol* e,
print_format* pf, bool top)
{
if (dwarf_hasattr(type, DW_AT_declaration))
{
Dwarf_Die *resolved = dw.declaration_resolve(type);
if (!resolved)
{
// could be an error, but for now just stub it
// throw semantic_error ("unresolved " + dwarf_type_name(type), e->tok);
pf->raw_components.append("{...}");
return;
}
type = resolved;
}
int count = 0;
pf->raw_components.append("{");
if (top || print_full)
recurse_struct_members (type, e, pf, count);
else
pf->raw_components.append("...");
pf->raw_components.append("}");
}
void
dwarf_pretty_print::recurse_struct_members (Dwarf_Die* type, target_symbol* e,
print_format* pf, int& count)
{
/* With inheritance, a subclass may mask member names of parent classes, so
* our search among the inheritance tree must be breadth-first rather than
* depth-first (recursive). The type die is still our starting point. When
* we encounter a masked name, just skip it. */
set<string> dupes;
deque<Dwarf_Die> inheritees(1, *type);
for (; !inheritees.empty(); inheritees.pop_front())
{
Dwarf_Die child, childtype, import;
if (dwarf_child (&inheritees.front(), &child) == 0)
do
{
target_symbol* e2 = e;
// skip static members
if (dwarf_hasattr(&child, DW_AT_declaration))
continue;
int tag = dwarf_tag (&child);
/* Pretend imported units contain members by recursing into
struct_member printing with the same count. */
if (tag == DW_TAG_imported_unit
&& dwarf_attr_die (&child, DW_AT_import, &import))
recurse_struct_members (&import, e2, pf, count);
if (tag != DW_TAG_member && tag != DW_TAG_inheritance)
continue;
dwarf_attr_die (&child, DW_AT_type, &childtype);
if (tag == DW_TAG_inheritance)
{
inheritees.push_back(childtype);
continue;
}
int childtag = dwarf_tag (&childtype);
const char *member = dwarf_diename (&child);
// "_vptr.foo" members are C++ virtual function tables,
// which (generally?) aren't interesting for users.
if (member && startswith(member, "_vptr."))
continue;
// skip inheritance-masked duplicates
if (member && !dupes.insert(member).second)
continue;
if (++count > 1)
pf->raw_components.append(", ");
// NB: limit to 32 args; see PR10750 and c_unparser::visit_print_format.
if (pf->args.size() >= 32)
{
pf->raw_components.append("...");
break;
}
if (member)
{
pf->raw_components.append(".");
pf->raw_components.append(member);
e2 = new target_symbol(*e);
e2->components.push_back (target_symbol::component(e->tok, member));
}
else if (childtag == DW_TAG_union_type)
pf->raw_components.append("<union>");
else if (childtag == DW_TAG_structure_type)
pf->raw_components.append("<class>");
else if (childtag == DW_TAG_class_type)
pf->raw_components.append("<struct>");
pf->raw_components.append("=");
if (dwarf_hasattr_integrate (&child, DW_AT_bit_offset)
|| dwarf_hasattr_integrate (&child, DW_AT_data_bit_offset))
recurse_bitfield (&childtype, e2, pf);
else
recurse (&childtype, e2, pf);
}
while (dwarf_siblingof (&child, &child) == 0);
}
}
bool
dwarf_pretty_print::print_chars (Dwarf_Die* start_type, target_symbol* e,
print_format* pf)
{
Dwarf_Die type;
dw.resolve_unqualified_inner_typedie (start_type, &type, e);
Dwarf_Attribute attr;
Dwarf_Word encoding = (Dwarf_Word) -1;
dwarf_formudata (dwarf_attr_integrate (&type, DW_AT_encoding, &attr),
&encoding);
switch (encoding)
{
case DW_ATE_UTF:
case DW_ATE_signed_char:
case DW_ATE_unsigned_char:
break;
default:
return false;
}
string function = userspace_p ? "user_string_quoted" : "kernel_or_user_string_quoted";
Dwarf_Word size = (Dwarf_Word) -1;
dwarf_formudata (dwarf_attr_integrate (&type, DW_AT_byte_size, &attr), &size);
switch (size)
{
case 1:
break;
case 2:
function += "_utf16";
break;
case 4:
function += "_utf32";
break;
default:
return false;
}
if (push_deref (pf, "%s", e))
{
// steal the last arg for a string access
assert (!pf->args.empty());
functioncall* fcall = new functioncall;
fcall->tok = e->tok;
fcall->function = function;
fcall->args.push_back (pf->args.back());
pf->args.back() = fcall;
}
return true;
}
struct target_bitfield_remover: public update_visitor
{
void visit_target_bitfield(target_bitfield *);
};
void target_bitfield_remover::visit_target_bitfield(target_bitfield *e)
{
replace (e->base);
expression *ret;
if (e->signed_p)
{
binary_expression *ls = new binary_expression;
ls->tok = e->tok;
ls->op = "<<";
ls->left = e->base;
ls->right = new literal_number(64 - e->offset - e->size);
binary_expression *rs = new binary_expression;
rs->tok = e->tok;
rs->op = ">>";
rs->left = ls;
rs->right = new literal_number(64 - e->size);
ret = rs;
}
else
{
binary_expression *rs = new binary_expression;
rs->tok = e->tok;
rs->op = ">>";
rs->left = e->base;
rs->right = new literal_number(e->offset);
uint64_t field = ((uint64_t)2 << (e->size - 1)) - 1;
binary_expression *msk = new binary_expression;
msk->tok = e->tok;
msk->op = "&";
msk->left = rs;
msk->right = new literal_number(field);
ret = msk;
}
provide (ret);
}
// PR10601: adapt to kernel-vs-userspace loc2c-runtime
static const string EMBEDDED_FETCH_DEREF_KERNEL = string("\n")
+ "#define fetch_register k_fetch_register\n"
+ "#define store_register k_store_register\n"
+ "#define deref kderef\n"
+ "#define store_deref store_kderef\n";
static const string EMBEDDED_FETCH_DEREF_USER = string("\n")
+ "#define fetch_register u_fetch_register\n"
+ "#define store_register u_store_register\n"
+ "#define deref uderef\n"
+ "#define store_deref store_uderef\n";
#define EMBEDDED_FETCH_DEREF(U) \
(U ? EMBEDDED_FETCH_DEREF_USER : EMBEDDED_FETCH_DEREF_KERNEL)
static const string EMBEDDED_FETCH_DEREF_DONE = string("\n")
+ "#undef fetch_register\n"
+ "#undef store_register\n"
+ "#undef deref\n"
+ "#undef store_deref\n";
static functioncall*
synthetic_embedded_deref_call(dwflpp& dw, location_context &ctx,
const std::string &function_name,
Dwarf_Die *function_type,
bool userspace_p, bool lvalue_p,
expression *pointer = NULL)
{
target_symbol *e = ctx.e;
const target_symbol *e_orig = ctx.e_orig;
const token *tok = e->tok;
assert (e != NULL);
assert (e_orig != NULL);
// Synthesize a functiondecl to contain an expression.
string fhash = detox_path(string(tok->location.file->name));
functiondecl *fdecl = new functiondecl;
fdecl->synthetic = true;
fdecl->tok = tok;
fdecl->unmangled_name = fdecl->name = "__private_" + fhash + function_name;
// The fdecl type is generic, but we'll be detailed on the fcall below.
fdecl->type = pe_long;
fdecl->type_details = make_shared<exp_type_dwarf>(&dw, function_type,
userspace_p, e->addressof);
// Synthesize a functioncall.
functioncall* fcall = new functioncall;
fcall->tok = tok;
fcall->referents.push_back(fdecl); // may be needed for post-pass2a sym resolution; autocast08.stp
fcall->function = fdecl->name;
fcall->type = fdecl->type;
fcall->type_details = fdecl->type_details;
// ??? Once upon a time we explicitly marked functions with
// /* unprivileged */, /* pure */, and /* stable */. Now that we
// have the // function body as staptree nodes, we simply deduce
// the properties from the nodes.
// If this code snippet uses a precomputed pointer,
// pass that as the first argument.
if (pointer)
{
assert(ctx.pointer);
fdecl->formal_args.push_back(ctx.pointer);
fcall->args.push_back(pointer);
}
// Any non-literal indexes need to be passed as arguments too.
if (!e->components.empty())
{
fdecl->formal_args.insert(fdecl->formal_args.end(),
ctx.indicies.begin(),
ctx.indicies.end()); // indexN..M
assert (e->components.size() == e_orig->components.size());
for (unsigned i = 0; i < e->components.size(); ++i)
if (e->components[i].type == target_symbol::comp_expression_array_index)
fcall->args.push_back(e_orig->components[i].expr_index); // the original index expression
}
// If this code snippet is assigning to an lvalue,
// add a final argument for the rvalue.
expression *ref_exp = ctx.locations.back()->program; // contains rewritten
if (ref_exp == 0) // e.g. if saw ->type == loc_noncontinguous
throw SEMANTIC_ERROR(_("no usable location for symbol [error::dwarf]"), e->tok);
//check if it's a 32-bit float; if it is do the conversion from f32 to f64
int typetag = dwarf_tag (function_type);
if (typetag == DW_TAG_base_type)
{
Dwarf_Attribute encoding_attr;
Dwarf_Word encoding = (Dwarf_Word) -1;
dwarf_formudata (dwarf_attr_integrate (function_type, DW_AT_encoding, &encoding_attr),
& encoding);
Dwarf_Attribute size_attr;
Dwarf_Word byte_size;
if (dwarf_attr_integrate (function_type, DW_AT_byte_size, &size_attr) == NULL
|| dwarf_formudata (&size_attr, &byte_size) != 0)
{
throw (SEMANTIC_ERROR
(_F("cannot get byte_size attribute for type %s: %s",
dwarf_diename (function_type) ?: "<anonymous>",
dwarf_errmsg (-1)), e->tok));
}
if (byte_size > 8)
throw (SEMANTIC_ERROR
("cannot process >64-bit values", e->tok));
if (encoding == DW_ATE_float
&& byte_size == 4)
{
if (lvalue_p) {
throw (SEMANTIC_ERROR
("cannot assign yet to 32-bit float", e->tok));
} else {
functioncall* conv_fcall = new functioncall();
conv_fcall->function = "fp32_to_fp64";
conv_fcall->tok = tok;
conv_fcall->type = pe_long;
conv_fcall->type_details = fcall->type_details;
//conv_fcall->referents = 0;
conv_fcall->args.push_back(fcall);
fcall = conv_fcall;
}
}
}
if (lvalue_p)
{
// NB: We don't know the value for fcall argument yet.
// (see target_symbol_setter_functioncalls)
vardecl *rvalue = new vardecl;
rvalue->type = pe_long;
rvalue->name = rvalue->unmangled_name = "rvalue";
rvalue->tok = tok;
fdecl->formal_args.push_back(rvalue);
symbol *sym = new symbol;
sym->name = rvalue->name;
sym->tok = rvalue->tok;
sym->type = pe_long;
// sym->referent = rvalue;
expression *rhs = sym;
// Expand bitfield writes.
if (target_bitfield *bf = dynamic_cast<target_bitfield *>(ref_exp))
{
uint64_t field = ((uint64_t)2 << (bf->size - 1)) - 1;
ref_exp = bf->base;
if (target_deref *dr = dynamic_cast<target_deref *>(ref_exp))
{
// Compute the address for a deref only once. This is
// particularly important when the address itself is a deref.
expression *addr = ctx.save_expression (dr->addr);
dr->addr = addr;
}
binary_expression *msk = new binary_expression;
msk->tok = tok;
msk->op = "&";
msk->left = sym;
msk->right = new literal_number(field);
binary_expression *sft = new binary_expression;
sft->tok = tok;
sft->op = "<<";
sft->left = msk;
sft->right = new literal_number(bf->offset);
binary_expression *clr = new binary_expression;
clr->tok = tok;
clr->op = "&";
clr->left = deep_copy_visitor::deep_copy(ref_exp);
clr->right = new literal_number(~(field << bf->offset));
binary_expression *ior = new binary_expression;
ior->tok = tok;
ior->op = "|";
ior->left = clr;
ior->right = sft;
rhs = ior;
}
assignment *a = new assignment;
a->tok = tok;
a->op = "=";
a->left = ref_exp;
a->right = rhs;
ref_exp = a;
}
// Expand bitfield reads.
target_bitfield_remover().replace(ref_exp);
fdecl->locals = ctx.locals;
block *blk = new block;
blk->tok = tok;
fdecl->body = blk;
for (auto i = ctx.evals.begin(); i != ctx.evals.end(); ++i)
blk->statements.push_back(*i);
return_statement *ret = new return_statement;
ret->tok = tok;
ret->value = ref_exp;
blk->statements.push_back(ret);
// Add the synthesized decl to the session now.
fdecl->join (dw.sess);
return fcall;
}
expression*
dwarf_pretty_print::deref (target_symbol* e)
{
static unsigned tick = 0;
if (!deref_p)
{
assert (pointer && e->components.empty());
return pointer;
}
bool lvalue_p = false;
location_context ctx(e, pointer);
ctx.pc = pc;
ctx.userspace_p = userspace_p;
Dwarf_Die endtype;
if (pointer)
dw.literal_stmt_for_pointer (ctx, &pointer_type, ctx.e, lvalue_p, &endtype);
else if (!local.empty())
dw.literal_stmt_for_local (ctx, scopes, local, ctx.e, lvalue_p, &endtype);
else
dw.literal_stmt_for_return (ctx, &scopes[0], ctx.e, lvalue_p, &endtype);
string name = "_dwarf_pretty_print_deref_" + lex_cast(tick++);
return synthetic_embedded_deref_call(dw, ctx, name, &endtype, userspace_p,
lvalue_p, pointer);
}
bool
dwarf_pretty_print::push_deref (print_format* pf, const string& fmt,
target_symbol* e)
{
expression* e2 = NULL;
try
{
e2 = deref (e);
}
catch (const semantic_error&)
{
pf->raw_components.append ("?");
return false;
}
pf->raw_components.append (fmt);
pf->args.push_back (e2);
return true;
}
void
dwarf_var_expanding_visitor::visit_target_symbol_saved_return (target_symbol* e)
{
// Get the full name of the target symbol.
stringstream ts_name_stream;
e->print(ts_name_stream);
string ts_name = ts_name_stream.str();
// Check and make sure we haven't already seen this target
// variable in this return probe. If we have, just return our
// last replacement.
auto i = return_ts_map.find(ts_name);
if (i != return_ts_map.end())
{
provide (i->second);
return;
}
// Attempt the expansion directly first, so if there's a problem with the
// variable we won't have a bogus entry probe lying around. Like in
// saveargs(), we pretend for a moment that we're not in a .return.
expression *repl = e;
{
save_and_restore<bool> temp_return (& q.has_return, false);
replace (repl);
}
// If it's still a target_symbol, then it couldn't be resolved. It may
// not have a saved_conversion_error yet, e.g. for null_die(scope_die),
// but we know it's not worth making that bogus entry anyway.
if (dynamic_cast<target_symbol*>(repl))
{
provide (repl);
return;
}
expression *exp;
if (!q.has_process &&
strverscmp(q.sess.kernel_base_release.c_str(), "2.6.25") >= 0)
exp = gen_kretprobe_saved_return(repl);
else
exp = gen_mapped_saved_return(repl, e->sym_name());
// Propagate the DWARF type to the expression in the return probe.
if (repl->type_details && !exp->type_details)
exp->type_details = repl->type_details;
// Provide the variable to our parent so it can be used as a
// substitute for the target symbol.
provide (exp);
// Remember this replacement since we might be able to reuse
// it later if the same return probe references this target
// symbol again.
return_ts_map[ts_name] = exp;
}
static expression*
gen_mapped_saved_return(systemtap_session &sess, expression* e,
const string& name,
block *& add_block, bool& add_block_tid,
block *& add_call_probe, bool& add_call_probe_tid)
{
static unsigned tick = 0;
// We've got to do several things here to handle target
// variables in return probes.
// (1) Synthesize two global arrays. One is the cache of the
// target variable and the other contains a thread specific
// nesting level counter. The arrays will look like
// this:
//
// _entry_tvar_{name}_{num}
// _entry_tvar_{name}_{num}_ctr
string aname = (string("__global_entry_tvar_")
+ name
+ "_" + lex_cast(tick++));
vardecl* vd = new vardecl;
vd->name = vd->unmangled_name = aname;
vd->synthetic = true;
vd->tok = e->tok;
sess.globals.push_back (vd);
string ctrname = aname + "_ctr";
vd = new vardecl;
vd->name = vd->unmangled_name = ctrname;
vd->tok = e->tok;
vd->synthetic = true;
sess.globals.push_back (vd);
// (2) Create a new code block we're going to insert at the
// beginning of this probe to get the cached value into a
// temporary variable. We'll replace the target variable
// reference with the temporary variable reference. The code
// will look like this:
//
// _entry_tvar_tid = tid()
// _entry_tvar_{name}_{num}_tmp
// = _entry_tvar_{name}_{num}[_entry_tvar_tid,
// _entry_tvar_{name}_{num}_ctr[_entry_tvar_tid]]
// delete _entry_tvar_{name}_{num}[_entry_tvar_tid,
// _entry_tvar_{name}_{num}_ctr[_entry_tvar_tid]--]
// if (! _entry_tvar_{name}_{num}_ctr[_entry_tvar_tid])
// delete _entry_tvar_{name}_{num}_ctr[_entry_tvar_tid]
// (2a) Synthesize the tid temporary expression, which will look
// like this:
//
// _entry_tvar_tid = tid()
symbol* tidsym = new symbol;
tidsym->name = string("_entry_tvar_tid");
tidsym->tok = e->tok;
if (add_block == NULL)
{
add_block = new block;
add_block->tok = e->tok;
}
if (!add_block_tid)
{
// Synthesize a functioncall to grab the thread id.
functioncall* fc = new functioncall;
fc->tok = e->tok;
fc->function = string("tid");
// Assign the tid to '_entry_tvar_tid'.
assignment* a = new assignment;
a->tok = e->tok;
a->op = "=";
a->left = tidsym;
a->right = fc;
expr_statement* es = new expr_statement;
es->tok = e->tok;
es->value = a;
add_block->statements.push_back (es);
add_block_tid = true;
}
// (2b) Synthesize an array reference and assign it to a
// temporary variable (that we'll use as replacement for the
// target variable reference). It will look like this:
//
// _entry_tvar_{name}_{num}_tmp
// = _entry_tvar_{name}_{num}[_entry_tvar_tid,
// _entry_tvar_{name}_{num}_ctr[_entry_tvar_tid]]
arrayindex* ai_tvar_base = new arrayindex;
ai_tvar_base->tok = e->tok;
symbol* sym = new symbol;
sym->name = aname;
sym->tok = e->tok;
ai_tvar_base->base = sym;
ai_tvar_base->indexes.push_back(tidsym);
// We need to create a copy of the array index in its current
// state so we can have 2 variants of it (the original and one
// that post-decrements the second index).
arrayindex* ai_tvar = new arrayindex;
arrayindex* ai_tvar_postdec = new arrayindex;
*ai_tvar = *ai_tvar_base;
*ai_tvar_postdec = *ai_tvar_base;
// Synthesize the
// "_entry_tvar_{name}_{num}_ctr[_entry_tvar_tid]" used as the
// second index into the array.
arrayindex* ai_ctr = new arrayindex;
ai_ctr->tok = e->tok;
sym = new symbol;
sym->name = ctrname;
sym->tok = e->tok;
ai_ctr->base = sym;
ai_ctr->indexes.push_back(tidsym);
ai_tvar->indexes.push_back(ai_ctr);
symbol* tmpsym = new symbol;
tmpsym->name = aname + "_tmp";
tmpsym->tok = e->tok;
assignment* a = new assignment;
a->tok = e->tok;
a->op = "=";
a->left = tmpsym;
a->right = ai_tvar;
expr_statement* es = new expr_statement;
es->tok = e->tok;
es->value = a;
add_block->statements.push_back (es);
// (2c) Add a post-decrement to the second array index and
// delete the array value. It will look like this:
//
// delete _entry_tvar_{name}_{num}[_entry_tvar_tid,
// _entry_tvar_{name}_{num}_ctr[_entry_tvar_tid]--]
post_crement* pc = new post_crement;
pc->tok = e->tok;
pc->op = "--";
pc->operand = ai_ctr;
ai_tvar_postdec->indexes.push_back(pc);
delete_statement* ds = new delete_statement;
ds->tok = e->tok;
ds->value = ai_tvar_postdec;
add_block->statements.push_back (ds);
// (2d) Delete the counter value if it is 0. It will look like
// this:
// if (! _entry_tvar_{name}_{num}_ctr[_entry_tvar_tid])
// delete _entry_tvar_{name}_{num}_ctr[_entry_tvar_tid]
ds = new delete_statement;
ds->tok = e->tok;
ds->value = ai_ctr;
unary_expression *ue = new unary_expression;
ue->tok = e->tok;
ue->op = "!";
ue->operand = ai_ctr;
if_statement *ifs = new if_statement;
ifs->tok = e->tok;
ifs->condition = ue;
ifs->thenblock = ds;
ifs->elseblock = NULL;
add_block->statements.push_back (ifs);
// (3) We need an entry probe that saves the value for us in the
// global array we created. Create the entry probe, which will
// look like this:
//
// probe kernel.function("{function}").call {
// _entry_tvar_tid = tid()
// _entry_tvar_{name}_{num}[_entry_tvar_tid,
// ++_entry_tvar_{name}_{num}_ctr[_entry_tvar_tid]]
// = ${param}
// }
if (add_call_probe == NULL)
{
add_call_probe = new block;
add_call_probe->tok = e->tok;
}
if (!add_call_probe_tid)
{
// Synthesize a functioncall to grab the thread id.
functioncall* fc = new functioncall;
fc->tok = e->tok;
fc->function = string("tid");
// Assign the tid to '_entry_tvar_tid'.
assignment* a = new assignment;
a->tok = e->tok;
a->op = "=";
a->left = tidsym;
a->right = fc;
expr_statement* es = new expr_statement;
es->tok = e->tok;
es->value = a;
add_call_probe = new block(add_call_probe, es);
add_call_probe_tid = true;
}
// Save the value, like this:
// _entry_tvar_{name}_{num}[_entry_tvar_tid,
// ++_entry_tvar_{name}_{num}_ctr[_entry_tvar_tid]]
// = ${param}
arrayindex* ai_tvar_preinc = new arrayindex;
*ai_tvar_preinc = *ai_tvar_base;
pre_crement* preinc = new pre_crement;
preinc->tok = e->tok;
preinc->op = "++";
preinc->operand = ai_ctr;
ai_tvar_preinc->indexes.push_back(preinc);
a = new assignment;
a->tok = e->tok;
a->op = "=";
a->left = ai_tvar_preinc;
a->right = e;
es = new expr_statement;
es->tok = e->tok;
es->value = a;
add_call_probe = new block(add_call_probe, es);
// (4) Provide the '_entry_tvar_{name}_{num}_tmp' variable to
// our parent so it can be used as a substitute for the target
// symbol.
delete ai_tvar_base;
return tmpsym;
}
expression*
dwarf_var_expanding_visitor::gen_mapped_saved_return(expression* e,
const string& name)
{
return ::gen_mapped_saved_return(q.sess, e, name, add_block,
add_block_tid, add_call_probe,
add_call_probe_tid);
}
expression*
dwarf_var_expanding_visitor::gen_kretprobe_saved_return(expression* e)
{
// The code for this is simple.
//
// .call:
// _set_kretprobe_long(index, $value)
//
// .return:
// _get_kretprobe_long(index)
//
// (or s/long/string/ for things like $$parms)
unsigned index;
string setfn, getfn;
// We need the caller to predetermine the type of the expression!
switch (e->type)
{
case pe_string:
index = saved_strings++;
setfn = "_set_kretprobe_string";
getfn = "_get_kretprobe_string";
break;
case pe_long:
index = saved_longs++;
setfn = "_set_kretprobe_long";
getfn = "_get_kretprobe_long";
break;
default:
throw SEMANTIC_ERROR(_("unknown type to save in kretprobe"), e->tok);
}
// Create the entry code
// _set_kretprobe_{long|string}(index, $value)
if (add_call_probe == NULL)
{
add_call_probe = new block;
add_call_probe->tok = e->tok;
}
functioncall* set_fc = new functioncall;
set_fc->tok = e->tok;
set_fc->function = setfn;
set_fc->args.push_back(new literal_number(index));
set_fc->args.back()->tok = e->tok;
set_fc->args.push_back(e);
expr_statement* set_es = new expr_statement;
set_es->tok = e->tok;
set_es->value = set_fc;
add_call_probe->statements.push_back(set_es);
// Create the return code
// _get_kretprobe_{long|string}(index)
functioncall* get_fc = new functioncall;
get_fc->tok = e->tok;
get_fc->function = getfn;
get_fc->args.push_back(new literal_number(index));
get_fc->args.back()->tok = e->tok;
return get_fc;
}
void
dwarf_var_expanding_visitor::visit_target_symbol_context (target_symbol* e)
{
if (pending_interrupts) {
provide(e);
return;
}
if (null_die(scope_die)) {
literal_string *empty = new literal_string(string(""));
empty->tok = e->tok;
provide(empty);
return;
}
target_symbol *tsym = new target_symbol(*e);
bool pretty = e->check_pretty_print ();
string format = pretty ? "=%s" : "=%#x";
// Convert $$parms to sprintf of a list of parms and active local vars
// which we recursively evaluate
print_format* pf = print_format::create(e->tok, "sprintf");
if (q.has_return && (e->name == "$$return"))
{
tsym->name = "$return";
// Ignore any variable that isn't accessible.
tsym->saved_conversion_error = 0;
expression *texp = tsym;
replace (texp); // NB: throws nothing ...
if (tsym->saved_conversion_error) // ... but this is how we know it happened.
{
}
else
{
pf->raw_components += "return";
pf->raw_components += format;
pf->args.push_back(texp);
}
}
else
{
// non-.return probe: support $$parms, $$vars, $$locals
bool first = true;
Dwarf_Die result;
vector<Dwarf_Die> scopes = q.dw.getscopes(scope_die);
for (unsigned i = 0; i < scopes.size(); ++i)
{
if (dwarf_tag(&scopes[i]) == DW_TAG_compile_unit)
break; // we don't want file-level variables
if (dwarf_child (&scopes[i], &result) == 0)
do
{
switch (dwarf_tag (&result))
{
case DW_TAG_variable:
if (e->name == "$$parms")
continue;
break;
case DW_TAG_formal_parameter:
if (e->name == "$$locals")
continue;
break;
default:
continue;
}
const char *diename = dwarf_diename (&result);
if (! diename) continue;
if (! first)
pf->raw_components += " ";
pf->raw_components += diename;
first = false;
// Write a placeholder for ugly aggregates
Dwarf_Die type;
if (!pretty && dwarf_attr_die(&result, DW_AT_type, &type))
{
q.dw.resolve_unqualified_inner_typedie(&type, &type, e);
switch (dwarf_tag(&type))
{
case DW_TAG_union_type:
case DW_TAG_structure_type:
case DW_TAG_class_type:
pf->raw_components += "={...}";
continue;
case DW_TAG_array_type:
pf->raw_components += "=[...]";
continue;
}
}
tsym->name = string("$") + diename;
// Ignore any variable that isn't accessible.
tsym->saved_conversion_error = 0;
expression *texp = tsym;
replace (texp); // NB: throws nothing ...
if (tsym->saved_conversion_error) // ... but this is how we know it happened.
{
if (q.sess.verbose>2)
{
for (const semantic_error *c = tsym->saved_conversion_error;
c != 0;
c = c->get_chain()) {
clog << _("variable location problem [man error::dwarf]: ") << c->what() << endl;
}
}
pf->raw_components += "=?";
}
else
{
pf->raw_components += format;
pf->args.push_back(texp);
}
}
while (dwarf_siblingof (&result, &result) == 0);
}
}
pf->components = print_format::string_to_components(pf->raw_components);
pf->type = pe_string;
provide (pf);
}
void
dwarf_var_expanding_visitor::visit_atvar_op (atvar_op *e)
{
// Fill in our current module context if needed
if (e->module.empty())
e->module = q.dw.module_name;
if (e->module == q.dw.module_name && e->cu_name.empty())
{
// process like any other local
// e->sym_name() will do the right thing
visit_target_symbol(e);
return;
}
var_expanding_visitor::visit_atvar_op(e);
}
void
dwarf_var_expanding_visitor::visit_target_symbol (target_symbol *e)
{
assert(e->name.size() > 0 && (e->name[0] == '$' || e->name == "@var"));
visited = true;
bool defined_being_checked = (defined_ops.size() > 0 && (defined_ops.top()->operand == e));
// In this mode, we avoid hiding errors or generating extra code such as for .return saved $vars
try
{
bool lvalue = is_active_lvalue(e);
if (lvalue && !q.sess.guru_mode)
throw SEMANTIC_ERROR(_("write to target variable not permitted; need stap -g"), e->tok);
// XXX: process $context vars should be writable
// See if we need to generate a new probe to save/access function
// parameters from a return probe. PR 1382.
if (q.has_return
&& !defined_being_checked
&& (strverscmp(sess.compatible.c_str(), "4.1") < 0 || e->name != "@var")
&& e->name != "$return" // not the special return-value variable handled below
&& e->name != "$$return") // nor the other special variable handled below
{
if (lvalue)
throw SEMANTIC_ERROR(_("write to target variable not permitted in .return probes"), e->tok);
// PR14924: discourage this syntax
stringstream expr;
e->print(expr);
q.sess.print_warning(_F("confusing usage, value is captured as @entry(%s) in .return probe [man stapprobes] RETURN PROBES", expr.str().c_str()), e->tok);
visit_target_symbol_saved_return(e);
return;
}
if (e->name == "$$vars" || e->name == "$$parms" || e->name == "$$locals"
|| (q.has_return && (e->name == "$$return")))
{
if (lvalue)
throw SEMANTIC_ERROR(_("cannot write to context variable"), e->tok);
if (e->addressof)
throw SEMANTIC_ERROR(_("cannot take address of context variable"), e->tok);
e->assert_no_components("dwarf", true);
visit_target_symbol_context(e);
return;
}
// Everything else (pretty-printed vars, and context vars) require a
// scope_die in which to search for them. If produce an error.
if (null_die(scope_die))
throw SEMANTIC_ERROR(_F("debuginfo scope not found for module '%s', cannot resolve context variable [man error::dwarf]",
q.dw.module_name.c_str()), e->tok);
if (e->check_pretty_print (lvalue))
{
if (q.has_return && (e->name == "$return"))
{
dwarf_pretty_print dpp (q.dw, scope_die, addr,
q.has_process, *e, lvalue);
dpp.expand()->visit(this);
}
else
{
dwarf_pretty_print dpp (q.dw, getscopes(e), addr,
e->sym_name(),
q.has_process, *e, lvalue);
dpp.expand()->visit(this);
}
return;
}
bool userspace_p = q.has_process;
location_context ctx(e);
ctx.pc = addr;
ctx.userspace_p = userspace_p;
// NB: pass the ctx.e (copied/rewritten veraion e, not orig_e),
// so [x] index expressions have their intra-synthetic-function names
Dwarf_Die endtype;
if (q.has_return && (e->name == "$return"))
q.dw.literal_stmt_for_return (ctx, scope_die, ctx.e, lvalue, &endtype);
else
q.dw.literal_stmt_for_local (ctx, getscopes(e), e->sym_name(),
ctx.e, lvalue, &endtype);
// Now that have location information check if change to variable has any effect
if (lvalue) {
if (q.has_kernel &&
q.sess.kernel_config["CONFIG_RETPOLINE"] == string("y"))
q.sess.print_warning(_F("liveness analysis skipped on CONFIG_RETPOLINE kernel %s",
q.dw.mod_info->elf_path.c_str()), e->tok);
else if (liveness(q.sess, e, q.dw.mod_info->elf_path, addr, ctx) < 0) {
q.sess.print_warning(_F("write at %p will have no effect",
(void *)addr), e->tok);
}
}
q.dw.sess.globals.insert(q.dw.sess.globals.end(),
ctx.globals.begin(),
ctx.globals.end());
for (auto it = ctx.entry_probes.begin(); it != ctx.entry_probes.end(); ++it)
{
auto res = entry_probes.find(it->first);
if (res == entry_probes.end())
entry_probes.insert(std::pair<Dwarf_Addr, block *>(it->first, it->second));
else
res->second = new block(res->second, it->second);
}
string fname = (string(lvalue ? "_dwarf_tvar_set" : "_dwarf_tvar_get")
+ "_" + escaped_identifier_string (e->sym_name())
+ "_" + lex_cast(tick++));
functioncall* n = synthetic_embedded_deref_call(q.dw, ctx, fname,
&endtype, userspace_p,
lvalue);
if (lvalue)
provide_lvalue_call (n);
provide(n); // allow recursion to $var1[$var2] subexpressions
}
catch (const semantic_error& er)
{
// We suppress this error message, and pass the unresolved
// target_symbol to the next pass. We hope that this value ends
// up not being referenced after all, so it can be optimized out
// quietly.
if (sess.verbose > 3)
clog << "chaining to " << *e->tok << endl
<< sess.build_error_msg(er) << endl;
e->chain (er);
provide (e);
}
}
void
dwarf_var_expanding_visitor::visit_cast_op (cast_op *e)
{
// Fill in our current module context if needed
if (e->module.empty())
{
// Backward compatibility for @cast() ops, sans module string,
// which expanded to "kernel" rather than to the current
// function/probe context.
if (strverscmp(sess.compatible.c_str(), "4.3") < 0)
e->module = "kernel";
else
e->module = q.dw.module_name;
}
var_expanding_visitor::visit_cast_op(e);
}
void
dwarf_var_expanding_visitor::visit_entry_op (entry_op *e)
{
expression *repl = e;
bool defined_being_checked = (defined_ops.size() > 0 && (defined_ops.top()->operand == e));
// In this mode, we avoid hiding errors or generating extra code such as for .return saved $vars
if (q.has_return)
{
// NB: don't expand the operand here, as if it weren't a return
// probe. The original operand expression is transcribed into
// the synthetic .call probe that gen_mapped_saved_return calls.
// If we were to expand it here, we may e.g. map @perf("...") to
// __perf_read_... prematurely & incorrectly. PR20416
// NB: but ... we sort of want to do a trial-expansion, just to
// see if the contents are rejected, e.g. with a $var-undefined
// error, so that the failure can propagate back up to a containing
// @defined(). PR20821
if (defined_being_checked)
{
save_and_restore<bool> temp_return (& q.has_return, false);
replace (e->operand); // don't generate any @entry machinery!
// propagate the replaced operand upward; it may be a
// target_symbol and have a saved_conversion_error; we
// also don't want to expand @defined(@entry(...)) into
// a full synthetic probe goo.
repl = e->operand;
}
else
{
// XXX it would be nice to use gen_kretprobe_saved_return when available,
// but it requires knowing the types already, which is problematic for
// arbitrary expressons.
repl = gen_mapped_saved_return (e->operand, "entry");
}
}
provide (repl);
}
void
dwarf_var_expanding_visitor::visit_perf_op (perf_op *e)
{
string e_lit_val = e->operand->value;
add_block = new block;
add_block->tok = e->tok;
systemtap_session &s = this->q.sess;
// Find the associated perf.counter probe
auto it = s.perf_counters.begin();
for (; it != s.perf_counters.end(); it++)
if ((*it).first == e_lit_val)
{
// if perf .process("name") omitted, then set it to this process name
if ((*it).second.length() == 0)
(*it).second = this->q.user_path;
if ((*it).second == this->q.user_path)
break;
}
if (it != s.perf_counters.end())
{
perf_counter_refs.insert((*it).first);
// __perf_read_N is assigned in the probe prologue
symbol* sym = new symbol;
sym->tok = e->tok;
sym->name = "__perf_read_" + (*it).first;
provide (sym);
}
else
throw SEMANTIC_ERROR(_F("perf counter '%s' not defined", e_lit_val.c_str()));
}
vector<Dwarf_Die>&
dwarf_var_expanding_visitor::getscopes(target_symbol *e)
{
if (scopes.empty())
{
if(!null_die(scope_die))
scopes = q.dw.getscopes(scope_die);
if (scopes.empty())
//throw semantic_error (_F("unable to find any scopes containing %d", addr), e->tok);
// ((scope_die == NULL) ? "" : (string (" in ") + (dwarf_diename(scope_die) ?: "<unknown>") + "(" + (dwarf_diename(q.dw.cu) ?: "<unknown>") ")" ))
throw SEMANTIC_ERROR ("unable to find any scopes containing "
+ lex_cast_hex(addr)
+ (null_die(scope_die) ? ""
: (string (" in ")
+ (dwarf_diename(scope_die) ?: "<unknown>")
+ "(" + (dwarf_diename(q.dw.cu) ?: "<unknown>")
+ ")"))
+ " while searching for local '"
+ e->sym_name() + "'",
e->tok);
}
return scopes;
}
struct dwarf_cast_expanding_visitor: public var_expanding_visitor
{
dwarf_builder& db;
map<string,string> compiled_headers;
dwarf_cast_expanding_visitor(systemtap_session& s, dwarf_builder& db):
var_expanding_visitor(s), db(db) {}
void visit_cast_op (cast_op* e);
void filter_special_modules(string& module);
};
struct dwarf_cast_query : public base_query
{
cast_op& e;
const bool lvalue;
const bool userspace_p;
functioncall*& result;
dwarf_cast_query(dwflpp& dw, const string& module, cast_op& e, bool lvalue,
const bool userspace_p, functioncall*& result):
base_query(dw, module), e(e), lvalue(lvalue),
userspace_p(userspace_p), result(result) {}
void handle_query_module();
void query_library (const char *) {}
void query_plt (const char *, size_t) {}
};
void
dwarf_cast_query::handle_query_module()
{
static unsigned tick = 0;
if (result)
return;
// look for the type in any CU
Dwarf_Die* type_die = NULL;
string tns = e.type_name;
if (startswith(tns, "class "))
{
// normalize to match dwflpp::global_alias_caching_callback
string struct_name = "struct " + (string)e.type_name.substr(6);
type_die = dw.declaration_resolve_other_cus(struct_name);
}
else
type_die = dw.declaration_resolve_other_cus(tns);
// NB: We now index the types as "struct name"/"union name"/etc. instead of
// just "name". But since we didn't require users to be explicit before, and
// actually sort of discouraged it, we must be flexible now. So if a lookup
// fails with a bare name, try augmenting it.
if (!type_die &&
!startswith(tns, "class ") &&
!startswith(tns, "struct ") &&
!startswith(tns, "union ") &&
!startswith(tns, "enum "))
{
type_die = dw.declaration_resolve_other_cus("struct " + tns);
if (!type_die)
type_die = dw.declaration_resolve_other_cus("union " + tns);
if (!type_die)
type_die = dw.declaration_resolve_other_cus("enum " + tns);
}
if (!type_die)
return;
location_context ctx(&e, e.operand);
ctx.userspace_p = userspace_p;
// ctx may require extra information for --runtime=bpf
symbol *s;
bpf_context_vardecl *v;
if ((s = dynamic_cast<symbol *>(e.operand))
&& (v = dynamic_cast<bpf_context_vardecl *>(s->referent)))
ctx.adapt_pointer_to_bpf(v->size, v->offset, v->is_signed);
Dwarf_Die endtype;
bool ok = false;
try
{
Dwarf_Die cu_mem;
dw.focus_on_cu(dwarf_diecu(type_die, &cu_mem, NULL, NULL));
if (e.check_pretty_print (lvalue))
{
dwarf_pretty_print dpp(dw, type_die, e.operand, true, userspace_p,
e, lvalue);
result = dpp.expand();
return;
}
ok = dw.literal_stmt_for_pointer (ctx, type_die, ctx.e, lvalue, &endtype);
}
catch (const semantic_error& er)
{
// NB: we can have multiple errors, since a @cast
// may be attempted using several different modules:
// @cast(ptr, "type", "module1:module2:...")
e.chain (er);
}
if (!ok)
return;
string fname = (string(lvalue ? "_dwarf_cast_set" : "_dwarf_cast_get")
+ "_" + e.sym_name()
+ "_" + lex_cast(tick++));
result = synthetic_embedded_deref_call(dw, ctx, fname, &endtype,
userspace_p, lvalue, e.operand);
}
void dwarf_cast_expanding_visitor::filter_special_modules(string& module)
{
// look for "<path/to/header>" or "kernel<path/to/header>"
// for those cases, build a module including that header
if (module[module.size() - 1] == '>' &&
(module[0] == '<' || startswith(module, "kernel<")))
{
string header = module;
auto it = compiled_headers.find(header);
if (it != compiled_headers.end())
{
module = it->second;
return;
}
string cached_module;
if (sess.use_cache)
{
// see if the cached module exists
cached_module = find_typequery_hash(sess, module);
if (!cached_module.empty() && !sess.poison_cache)
{
int fd = open(cached_module.c_str(), O_RDONLY);
if (fd != -1)
{
if (sess.verbose > 2)
//TRANSLATORS: Here we're using a cached module.
clog << _("Pass 2: using cached ") << cached_module << endl;
compiled_headers[header] = module = cached_module;
close(fd);
return;
}
}
}
// no cached module, time to make it
if (make_typequery(sess, module) == 0)
{
// try to save typequery in the cache
if (sess.use_cache)
copy_file(module, cached_module, sess.verbose > 2);
compiled_headers[header] = module;
}
}
}
void dwarf_cast_expanding_visitor::visit_cast_op (cast_op* e)
{
bool lvalue = is_active_lvalue(e);
if (lvalue && !sess.guru_mode)
throw SEMANTIC_ERROR(_("write to @cast context variable not permitted; need stap -g"), e->tok);
if (strverscmp(sess.compatible.c_str(), "4.3") < 0) // PR25841 - no need to sub "kernel"
if (e->module.empty())
e->module = "kernel"; // "*" may also be reasonable to search all kernel modules
functioncall* result = NULL;
// split the module string by ':' for alternatives
vector<string> modules;
tokenize(e->module, modules, ":");
bool userspace_p=false; // PR10601
for (unsigned i = 0; !result && i < modules.size(); ++i)
{
string& module = modules[i];
filter_special_modules(module);
// NB: This uses '/' to distinguish between kernel modules and userspace,
// which means that userspace modules won't get any PATH searching.
dwflpp* dw;
try
{
userspace_p=is_user_module (module);
if (! userspace_p)
{
// kernel or kernel module target
dw = db.get_kern_dw(sess, module);
}
else
{
module = find_executable (module, "", sess.sysenv); // canonicalize it
dw = db.get_user_dw(sess, module);
}
}
catch (const semantic_error& er)
{
/* ignore and go to the next module */
continue;
}
dwarf_cast_query q (*dw, module, *e, lvalue, userspace_p, result);
dw->iterate_over_modules<base_query>(&query_module, &q);
}
if (!result)
{
// We pass the unresolved cast_op to the next pass, and hope
// that this value ends up not being referenced after all, so
// it can be optimized out quietly.
provide (e);
return;
}
if (lvalue)
provide_lvalue_call (result);
result->visit (this);
}
static bool resolve_pointer_type(Dwarf_Die& die, bool& isptr);
exp_type_dwarf::exp_type_dwarf(dwflpp* dw, Dwarf_Die* die,
bool userspace_p, bool addressof):
dw(dw), die(*die), userspace_p(userspace_p), is_pointer(false)
{
// is_pointer tells us whether a value is a pointer to the given type, so we
// can dereference it; otherwise it will be treated as an end point.
if (addressof)
// we're already looking at the pointed-to type
is_pointer = true;
else
// use the same test as tracepoints to see what we have
resolve_pointer_type(this->die, is_pointer);
}
functioncall *
exp_type_dwarf::expand(autocast_op* e, bool lvalue)
{
static unsigned tick = 0;
try
{
// make sure we're not dereferencing base types or void
bool deref_p = is_pointer && !null_die(&die);
if (!deref_p)
e->assert_no_components("autocast", true);
if (lvalue && !dw->sess.guru_mode)
throw SEMANTIC_ERROR(_("write not permitted; need stap -g"), e->tok);
if (e->components.empty())
{
if (e->addressof)
throw SEMANTIC_ERROR(_("cannot take address of tracepoint variable"), e->tok);
// no components and no addressof? how did this autocast come to be?
throw SEMANTIC_ERROR(_("internal error: no-op autocast encountered"), e->tok);
}
Dwarf_Die cu_mem;
if (!null_die(&die))
dw->focus_on_cu(dwarf_diecu(&die, &cu_mem, NULL, NULL));
if (e->check_pretty_print (lvalue))
{
dwarf_pretty_print dpp(*dw, &die, e->operand, deref_p, userspace_p,
*e, lvalue);
return dpp.expand();
}
location_context ctx(e, e->operand);
ctx.userspace_p = userspace_p;
Dwarf_Die endtype;
dw->literal_stmt_for_pointer (ctx, &die, ctx.e, lvalue, &endtype);
string fname = (string(lvalue ? "_dwarf_autocast_set"
: "_dwarf_autocast_get")
+ "_" + lex_cast(tick++));
return synthetic_embedded_deref_call(*dw, ctx, fname, &endtype,
userspace_p, lvalue, e->operand);
}
catch (const semantic_error &er)
{
if (dw->sess.verbose > 3)
clog << "chaining to " << *e->tok << endl
<< dw->sess.build_error_msg(er) << endl;
e->chain (er);
return NULL;
}
}
void exp_type_dwarf::print(ostream& o) const
{
o << "dwarf=" << dwarf_type_name((Dwarf_Die*) & die);
}
struct dwarf_atvar_expanding_visitor: public var_expanding_visitor
{
dwarf_builder& db;
dwarf_atvar_expanding_visitor(systemtap_session& s, dwarf_builder& db):
var_expanding_visitor(s), db(db) {}
void visit_atvar_op (atvar_op* e);
};
struct dwarf_atvar_query: public base_query
{
atvar_op& e;
const bool userspace_p, lvalue;
functioncall*& result;
unsigned& tick;
const string cu_name_pattern;
dwarf_atvar_query(dwflpp& dw, const string& module, atvar_op& e,
const bool userspace_p, const bool lvalue,
functioncall*& result,
unsigned& tick):
base_query(dw, module), e(e),
userspace_p(userspace_p), lvalue(lvalue), result(result),
tick(tick), cu_name_pattern(string("*/") + (string)e.cu_name) {}
void handle_query_module ();
void query_library (const char *) {}
void query_plt (const char *, size_t) {}
static int atvar_query_cu (Dwarf_Die *cudie, dwarf_atvar_query *q);
};
int
dwarf_atvar_query::atvar_query_cu (Dwarf_Die * cudie, dwarf_atvar_query *q)
{
if (! q->e.cu_name.empty())
{
const char *die_name = dwarf_diename(cudie) ?: "";
string cns = q->e.cu_name;
if (strcmp(die_name, cns.c_str()) != 0 // Perfect match
&& fnmatch(q->cu_name_pattern.c_str(), die_name, 0) != 0)
{
return DWARF_CB_OK;
}
}
try
{
vector<Dwarf_Die> scopes(1, *cudie);
q->dw.focus_on_cu (cudie);
if (q->e.check_pretty_print (q->lvalue))
{
dwarf_pretty_print dpp (q->dw, scopes, 0, q->e.sym_name(),
q->userspace_p, q->e, q->lvalue);
q->result = dpp.expand();
return DWARF_CB_ABORT;
}
location_context ctx(&q->e);
ctx.userspace_p = q->userspace_p;
Dwarf_Die endtype;
bool ok = q->dw.literal_stmt_for_local (ctx, scopes, q->e.sym_name(),
ctx.e, q->lvalue, &endtype);
if (!ok)
return DWARF_CB_OK;
string fname = (string(q->lvalue ? "_dwarf_tvar_set"
: "_dwarf_tvar_get")
+ "_" + q->e.sym_name()
+ "_" + lex_cast(q->tick++));
q->result = synthetic_embedded_deref_call (q->dw, ctx, fname, &endtype,
q->userspace_p, q->lvalue);
}
catch (const semantic_error& er)
{
if (q->sess.verbose > 3)
clog << "chaining to " << q->e.tok << endl
<< q->sess.build_error_msg(er) << endl;
q->e.chain (er);
return DWARF_CB_OK;
}
if (q->result) {
return DWARF_CB_ABORT;
}
return DWARF_CB_OK;
}
void
dwarf_atvar_query::handle_query_module ()
{
dw.iterate_over_cus(atvar_query_cu, this, false);
}
void
dwarf_atvar_expanding_visitor::visit_atvar_op (atvar_op* e)
{
const bool lvalue = is_active_lvalue(e);
if (lvalue && !sess.guru_mode)
throw SEMANTIC_ERROR(_("write to @var variable not permitted; "
"need stap -g"), e->tok);
if (strverscmp(sess.compatible.c_str(), "4.3") < 0) // PR25841 - no need to sub "kernel"
if (e->module.empty())
e->module = "kernel";
functioncall* result = NULL;
// split the module string by ':' for alternatives
vector<string> modules;
tokenize(e->module, modules, ":");
bool userspace_p = false;
for (unsigned i = 0; !result && i < modules.size(); ++i)
{
string& module = modules[i];
dwflpp* dw;
try
{
userspace_p = is_user_module(module);
if (!userspace_p)
{
// kernel or kernel module target
dw = db.get_kern_dw(sess, module);
}
else
{
module = find_executable(module, "", sess.sysenv);
dw = db.get_user_dw(sess, module);
}
}
catch (const semantic_error& er)
{
/* ignore and go to the next module */
continue;
}
dwarf_atvar_query q (*dw, module, *e, userspace_p, lvalue, result, tick);
dw->iterate_over_modules<base_query>(&query_module, &q);
if (result)
{
sess.unwindsym_modules.insert(module);
if (lvalue)
provide_lvalue_call (result);
result->visit(this);
return;
}
/* Unable to find the variable in the current module, so we chain
* an error in atvar_op */
string esn = e->sym_name();
string mn = module;
string cun = e->cu_name;
semantic_error er(ERR_SRC, _F("unable to find global '%s' in %s%s%s",
esn.c_str(), mn.c_str(),
cun.empty() ? "" : _(", in "),
cun.c_str()));
if (sess.verbose > 3)
clog << "chaining to " << *e->tok << endl
<< sess.build_error_msg(er) << endl;
e->chain (er);
}
provide(e);
}
void
dwarf_derived_probe::printsig (ostream& o) const
{
// Instead of just printing the plain locations, we add a PC value
// as a comment as a way of telling e.g. apart multiple inlined
// function instances. This is distinct from the verbose/clog
// output, since this part goes into the cache hash calculations.
sole_location()->print (o);
if (symbol_name != "")
o << " /* pc=<" << symbol_name << "+" << offset << "> */";
else
o << " /* pc=" << section << "+0x" << hex << addr << dec << " */";
printsig_nested (o);
}
void
dwarf_derived_probe::printsig_nonest (ostream& o) const
{
sole_location()->print (o);
if (symbol_name != "")
o << " /* pc=<" << symbol_name << "+" << offset << "> */";
else
o << " /* pc=" << section << "+0x" << hex << addr << dec << " */";
}
void
dwarf_derived_probe::join_group (systemtap_session& s)
{
// skip probes which are paired entry-handlers
if (!has_return && (saved_longs || saved_strings))
return;
if (! s.generic_kprobe_derived_probes)
s.generic_kprobe_derived_probes = new generic_kprobe_derived_probe_group ();
s.generic_kprobe_derived_probes->enroll (this);
this->group = s.generic_kprobe_derived_probes;
if (has_return && entry_handler)
entry_handler->group = s.generic_kprobe_derived_probes;
}
static bool
kernel_supports_inode_uprobes(systemtap_session& s)
{
// The arch-supports is new to the builtin inode-uprobes, so it makes a
// reasonable indicator of the new API. Else we'll need an autoconf...
// see also buildrun.cxx:kernel_built_uprobs()
return (s.kernel_config["CONFIG_ARCH_SUPPORTS_UPROBES"] == "y"
&& s.kernel_config["CONFIG_UPROBES"] == "y");
}
static bool
kernel_supports_inode_uretprobes(systemtap_session& s)
{
// We need inode-uprobes first, then look for a sign of uretprobes. The only
// non-static function at present is arch_uretprobe_hijack_return_addr.
return kernel_supports_inode_uprobes(s) &&
(s.kernel_functions.count("arch_uretprobe_hijack_return_addr") > 0);
}
void
check_process_probe_kernel_support(systemtap_session& s)
{
// We don't have utrace. For process probes that aren't
// uprobes-based, we just need the task_finder. The task_finder
// needs CONFIG_TRACEPOINTS and specific tracepoints. There is a
// specific autoconf test for its needs.
//
// We'll just require CONFIG_TRACEPOINTS here as a quick-and-dirty
// approximation.
if (! s.need_uprobes && s.kernel_config["CONFIG_TRACEPOINTS"] == "y")
return;
// For uprobes-based process probes, we need the task_finder plus
// the builtin inode-uprobes.
if (s.need_uprobes
&& s.kernel_config["CONFIG_TRACEPOINTS"] == "y"
&& kernel_supports_inode_uprobes(s))
return;
throw SEMANTIC_ERROR (_("process probes not available without kernel CONFIG_TRACEPOINTS/CONFIG_ARCH_SUPPORTS_UPROBES/CONFIG_UPROBES"));
}
dwarf_derived_probe::dwarf_derived_probe(interned_string funcname,
interned_string filename,
int line,
// module & section specify a relocation
// base for <addr>, unless section==""
// (equivalently module=="kernel")
// for userspace, it's a full path, for
// modules, it's either a full path, or
// the basename (e.g. 'btrfs')
interned_string module,
interned_string section,
// NB: dwfl_addr is the virtualized
// address for this symbol.
Dwarf_Addr dwfl_addr,
// addr is the section-offset for
// actual relocation.
Dwarf_Addr addr,
dwarf_query& q,
Dwarf_Die* scope_die /* may be null */,
interned_string symbol_name,
Dwarf_Addr offset)
: generic_kprobe_derived_probe (q.base_probe, q.base_loc, module, section,
addr, q.has_return,
q.has_maxactive, q.maxactive_val, "", offset),
path (q.path),
has_process (q.has_process),
has_library (q.has_library),
user_path (q.user_path),
user_lib (q.user_lib),
access_vars(false)
{
// If we were given a fullpath to a kernel module, then get the simple name
if (q.has_module && is_fully_resolved(module, q.dw.sess.sysroot, q.dw.sess.sysenv))
this->module = modname_from_path(module);
if (q.has_module && symbol_name != "")
this->symbol_name = lex_cast(this->module) + ":" + lex_cast(symbol_name);
if (q.sess.runtime_mode == systemtap_session::bpf_runtime && q.has_return)
this->sym_name_for_bpf = funcname;
if (user_lib.size() != 0)
has_library = true;
if (q.has_process)
{
// We may receive probes on two types of ELF objects: ET_EXEC or ET_DYN.
// ET_EXEC ones need no further relocation on the addr(==dwfl_addr), whereas
// ET_DYN ones do (addr += run-time mmap base address). We tell these apart
// by the incoming section value (".absolute" vs. ".dynamic").
// XXX Assert invariants here too?
// inode-uprobes needs an offset rather than an absolute VM address.
// ditto for userspace runtimes (dyninst)
if ((kernel_supports_inode_uprobes(q.dw.sess) || q.dw.sess.runtime_usermode_p()) &&
section == ".absolute" && addr == dwfl_addr &&
addr >= q.dw.module_start && addr < q.dw.module_end)
this->addr = addr - q.dw.module_start;
}
else
{
// Assert kernel relocation invariants
if (section == "" && dwfl_addr != addr) // addr should be absolute
throw SEMANTIC_ERROR (_("missing relocation basis"), tok);
if (section != "" && dwfl_addr == addr) // addr should be an offset
throw SEMANTIC_ERROR (_("inconsistent relocation address"), tok);
}
// XXX: hack for strange g++/gcc's
#ifndef USHRT_MAX
#define USHRT_MAX 32767
#endif
// Range limit maxactive() value
if (has_maxactive && (maxactive_val < 0 || maxactive_val > USHRT_MAX))
throw SEMANTIC_ERROR (_F("maxactive value out of range [0,%s]",
lex_cast(USHRT_MAX).c_str()), q.base_loc->components.front()->tok);
// Expand target variables in the probe body. Even if the scope_die is
// invalid, we still want to expand things such as $$vars/$$parms/etc...
// (PR15999, PR16473). Access to specific context vars e.g. $argc will not be
// expanded and will produce an error during the typeresolution_info pass.
{
// PR14436: if we're expanding target variables in the probe body of a
// .return probe, we need to make the expansion at the postprologue addr
// instead (if any), which is then also the spot where the entry handler
// probe is placed. (Note that at this point, a nonzero prologue_end
// implies that it should be used, i.e. code is unoptimized).
Dwarf_Addr handler_dwfl_addr = dwfl_addr;
if (q.prologue_end != 0 && q.has_return)
{
handler_dwfl_addr = q.prologue_end;
if (q.sess.verbose > 2)
clog << _F("expanding .return vars at prologue_end (0x%s) "
"rather than entrypc (0x%s)\n",
lex_cast_hex(handler_dwfl_addr).c_str(),
lex_cast_hex(dwfl_addr).c_str());
}
// PR20672, there may be @defined()-guarded @entry() expressions
// in the tree. If any @defined() maps to false, the visitor
// needs to abort so that subsequent @entry()'s are not
// processed (to generate synthetic .call etc. probes). We do a
// a mini relaxation loop here.
dwarf_var_expanding_visitor v (q, scope_die, handler_dwfl_addr);
if (q.sess.symbol_resolver)
q.sess.symbol_resolver->current_probe = this;
var_expand_const_fold_loop (q.sess, this->body, v);
// Propagate perf.counters so we can emit later
this->perf_counter_refs = v.perf_counter_refs;
// Emit local var used to save the perf counter read value
for (auto pcii = v.perf_counter_refs.begin();
pcii != v.perf_counter_refs.end(); pcii++)
{
// Find the associated perf counter probe
for (auto it = q.sess.perf_counters.begin();
it != q.sess.perf_counters.end();
it++)
if ((*it).first == (*pcii))
{
vardecl* vd = new vardecl;
vd->name = vd->unmangled_name = "__perf_read_" + (*it).first;
vd->tok = this->tok;
vd->set_arity(0, this->tok);
vd->type = pe_long;
vd->synthetic = true;
this->locals.push_back (vd);
break;
}
}
if (!q.has_process)
access_vars = v.visited;
// If during target-variable-expanding the probe, we added a new block
// of code, add it to the start of the probe.
if (v.add_block)
this->body = new block(v.add_block, this->body);
// If when target-variable-expanding the probe, we need to synthesize a
// sibling function-entry probe. We don't go through the whole probe derivation
// business (PR10642) that could lead to wildcard/alias resolution, or for that
// dwarf-induced duplication.
if (v.add_call_probe)
{
assert (q.has_return && !q.has_call);
// We temporarily replace q.base_probe.
save_and_restore<statement*> tmp_body (&q.base_probe->body, v.add_call_probe);
save_and_restore<bool> tmp_return (&q.has_return, false);
save_and_restore<bool> tmp_call (&q.has_call, true);
// NB: any moved @entry(EXPR) bits will be expanded during this
// nested *derived_probe ctor for the synthetic .call probe.
// PR20416
if (q.has_process)
{
// Place handler probe at the same addr as where the vars were
// expanded (which may not be the same addr as the one for the
// main retprobe, PR14436).
Dwarf_Addr handler_addr = addr;
if (handler_dwfl_addr != dwfl_addr)
// adjust section offset by prologue_end-entrypc
handler_addr += handler_dwfl_addr - dwfl_addr;
entry_handler = new uprobe_derived_probe (funcname, filename,
line, module, section,
handler_dwfl_addr,
handler_addr, q,
scope_die);
}
else
entry_handler = new dwarf_derived_probe (funcname, filename, line,
module, section, dwfl_addr,
addr, q, scope_die);
entry_handler->synthetic = true;
saved_longs = entry_handler->saved_longs = v.saved_longs;
saved_strings = entry_handler->saved_strings = v.saved_strings;
q.results.push_back (entry_handler);
}
for (auto it = v.entry_probes.begin(); it != v.entry_probes.end(); ++it)
{
save_and_restore<statement*> tmp_body (&q.base_probe->body, it->second);
save_and_restore<bool> tmp_function_num (&q.has_function_num, true);
query_addr (it->first, &q);
}
// Save the local variables for listing mode. If the scope_die is null,
// local vars aren't accessible, so no need to invoke saveargs (PR10820).
if (!null_die(scope_die) &&
(q.sess.dump_mode == systemtap_session::dump_matched_probes_vars ||
q.sess.language_server_mode))
saveargs(q, scope_die, dwfl_addr);
}
// Reset the sole element of the "locations" vector as a
// "reverse-engineered" form of the incoming (q.base_loc) probe
// point. This allows a user to see what function / file / line
// number any particular match of the wildcards.
vector<probe_point::component*> comps;
if (q.has_kernel)
comps.push_back (new probe_point::component(TOK_KERNEL));
else if(q.has_module)
comps.push_back (new probe_point::component(TOK_MODULE, new literal_string(module)));
else if(q.has_process && q.build_id_val != "") // for stap -vL process("buildid").function() etc. probes
comps.push_back (new probe_point::component(TOK_PROCESS, new literal_string(q.build_id_val)));
else if(q.has_process)
comps.push_back (new probe_point::component(TOK_PROCESS, new literal_string(module)));
else
assert (0);
string fn_or_stmt;
if (q.has_function_str || q.has_function_num)
fn_or_stmt = TOK_FUNCTION;
else
fn_or_stmt = TOK_STATEMENT;
if (q.has_function_str || q.has_statement_str)
{
interned_string retro_name = q.final_function_name(funcname, filename, line);
comps.push_back
(new probe_point::component
(fn_or_stmt, new literal_string (retro_name)));
}
else if (q.has_function_num || q.has_statement_num)
{
Dwarf_Addr retro_addr;
if (q.has_function_num)
retro_addr = q.function_num_val;
else
retro_addr = q.statement_num_val;
comps.push_back (new probe_point::component
(fn_or_stmt,
new literal_number(retro_addr, true)));
if (q.has_absolute)
comps.push_back (new probe_point::component (TOK_ABSOLUTE));
}
if (q.has_call)
comps.push_back (new probe_point::component(TOK_CALL));
if (q.has_exported)
comps.push_back (new probe_point::component(TOK_EXPORTED));
if (q.has_inline)
comps.push_back (new probe_point::component(TOK_INLINE));
if (has_return)
comps.push_back (new probe_point::component(TOK_RETURN));
if (has_maxactive)
comps.push_back (new probe_point::component
(TOK_MAXACTIVE, new literal_number(maxactive_val)));
// Overwrite it.
this->sole_location()->components = comps;
// if it's a .callee[s[(N)]] call, add checks to the probe body so that the
// user body is only 'triggered' when called from q.callers[N-1], which
// itself is called from q.callers[N-2], etc... I.E.
// callees(N) --> N elements in q.callers --> N checks against [u]stack(0..N-1)
if ((q.has_callee || q.has_callees_num) && q.callers && !q.callers->empty())
{
if (q.sess.verbose > 2)
clog << _F("adding caller checks for callee %s\n",
funcname.to_string().c_str());
// Copy the stack and empty it out
stack<Dwarf_Addr> callers(*q.callers);
for (unsigned level = 1; !callers.empty(); level++,
callers.pop())
{
Dwarf_Addr caller = callers.top();
// We first need to make the caller addr relocatable
interned_string caller_section;
Dwarf_Addr caller_reloc;
if (module == TOK_KERNEL)
{ // allow for relocatable kernel (see also add_probe_point())
caller_reloc = caller - q.sess.sym_stext;
caller_section = "_stext";
}
else
caller_reloc = q.dw.relocate_address(caller,
caller_section);
if (q.sess.verbose > 2)
clog << _F("adding caller check [u]stack(%d) == reloc(0x%s)\n",
level, lex_cast_hex(caller_reloc).c_str());
// We want to add a statement like this:
// if (!_caller_match(user, mod, sec, addr)) next;
// Something similar is done in semantic_pass_conditions()
functioncall* check = new functioncall();
check->tok = this->tok;
check->function = "_caller_match";
check->args.push_back(new literal_number(q.has_process));
check->args[0]->tok = this->tok;
// For callee .return probes, the callee is popped off stack
// so we don't want to match the frame below the caller
if (q.has_return)
check->args.push_back(new literal_number(level-1));
else
check->args.push_back(new literal_number(level));
check->args[1]->tok = this->tok;
check->args.push_back(new literal_string(this->module));
check->args[2]->tok = this->tok;
check->args.push_back(new literal_string(caller_section));
check->args[3]->tok = this->tok;
check->args.push_back(new literal_number(caller_reloc, true /* hex */));
check->args[4]->tok = this->tok;
unary_expression* notexp = new unary_expression();
notexp->tok = this->tok;
notexp->op = "!";
notexp->operand = check;
if_statement* ifs = new if_statement();
ifs->tok = this->tok;
ifs->thenblock = new next_statement();
ifs->thenblock->tok = this->tok;
ifs->elseblock = NULL;
ifs->condition = notexp;
this->body = new block(ifs, this->body);
}
}
}
void
dwarf_derived_probe::saveargs(dwarf_query& q, Dwarf_Die* scope_die,
Dwarf_Addr dwfl_addr)
{
if (null_die(scope_die))
return;
bool verbose = q.sess.verbose > 2;
if (verbose)
clog << _F("saveargs: examining '%s' (dieoffset: %#" PRIx64 ")\n", (dwarf_diename(scope_die)?: "unknown"), dwarf_dieoffset(scope_die));
if (has_return)
{
/* Only save the return value if it has a type. */
string type_name;
Dwarf_Die type_die;
if (dwarf_attr_die (scope_die, DW_AT_type, &type_die) &&
dwarf_type_name(&type_die, type_name))
args.push_back("$return:"+type_name);
else if (verbose)
clog << _F("saveargs: failed to retrieve type name for return value (dieoffset: %s)\n",
lex_cast_hex(dwarf_dieoffset(scope_die)).c_str());
}
Dwarf_Die arg;
vector<Dwarf_Die> scopes = q.dw.getscopes(scope_die);
for (unsigned i = 0; i < scopes.size(); ++i)
{
if (dwarf_tag(&scopes[i]) == DW_TAG_compile_unit)
break; // we don't want file-level variables
if (dwarf_child (&scopes[i], &arg) == 0)
do
{
switch (dwarf_tag (&arg))
{
case DW_TAG_variable:
case DW_TAG_formal_parameter:
break;
default:
continue;
}
/* Ignore this local if it has no name. */
const char *arg_name = dwarf_diename (&arg);
if (!arg_name)
{
if (verbose)
clog << _F("saveargs: failed to retrieve name for local (dieoffset: %s)\n",
lex_cast_hex(dwarf_dieoffset(&arg)).c_str());
continue;
}
if (verbose)
clog << _F("saveargs: finding location for local '%s' (dieoffset: %s)\n",
arg_name, lex_cast_hex(dwarf_dieoffset(&arg)).c_str());
/* Ignore this local if it has no location (or not at this PC). */
/* NB: It still may not be directly accessible, e.g. if it is an
* aggregate type, implicit_pointer, etc., but the user can later
* figure out how to access the interesting parts. */
/* XXX: Perhaps saveargs() / listings-mode should work by synthesizing
* several synthetic
* probe foo { $var }
* probes, testing them for overall resolvability.
*/
Dwarf_Attribute attr_mem;
if (!dwarf_attr_integrate (&arg, DW_AT_const_value, &attr_mem))
{
Dwarf_Op *expr;
size_t len;
if (!dwarf_attr_integrate (&arg, DW_AT_location, &attr_mem))
{
if (verbose)
clog << _F("saveargs: failed to resolve the location for local '%s' (dieoffset: %s)\n",
arg_name, lex_cast_hex(dwarf_dieoffset(&arg)).c_str());
continue;
}
else if (!(dwarf_getlocation_addr(&attr_mem, dwfl_addr, &expr,
&len, 1) == 1 && len > 0))
{
Dwarf_Addr dwfl_addr2 = q.dw.pr15123_retry_addr (dwfl_addr, & arg);
if (!dwfl_addr2 || (!(dwarf_getlocation_addr(&attr_mem, dwfl_addr2, &expr,
&len, 1) == 1 && len > 0))) {
if (verbose)
clog << _F("saveargs: local '%s' (dieoffset: %s) is not available at this address (%s)\n",
arg_name, lex_cast_hex(dwarf_dieoffset(&arg)).c_str(), lex_cast_hex(dwfl_addr).c_str());
continue;
}
}
}
/* Ignore this local if it has no type. */
string type_name;
Dwarf_Die type_die;
if (!dwarf_attr_die (&arg, DW_AT_type, &type_die) ||
!dwarf_type_name(&type_die, type_name))
{
if (verbose)
clog << _F("saveargs: failed to retrieve type name for local '%s' (dieoffset: %s)\n",
arg_name, lex_cast_hex(dwarf_dieoffset(&arg)).c_str());
continue;
}
/* This local looks good -- save it! */
args.push_back("$"+string(arg_name)+":"+type_name);
}
while (dwarf_siblingof (&arg, &arg) == 0);
}
}
void
dwarf_derived_probe::getargs(std::list<std::string> &arg_set) const
{
arg_set.insert(arg_set.end(), args.begin(), args.end());
}
void
dwarf_derived_probe::emit_privilege_assertion (translator_output* o)
{
if (has_process)
{
// These probes are allowed for unprivileged users, but only in the
// context of processes which they own.
emit_process_owner_assertion (o);
return;
}
// Other probes must contain the default assertion which aborts
// if executed by an unprivileged user.
derived_probe::emit_privilege_assertion (o);
}
void
dwarf_derived_probe::print_dupe_stamp(ostream& o)
{
if (has_process)
{
// These probes are allowed for unprivileged users, but only in the
// context of processes which they own.
print_dupe_stamp_unprivileged_process_owner (o);
return;
}
// Other probes must contain the default dupe stamp
derived_probe::print_dupe_stamp (o);
}
void
dwarf_derived_probe::register_statement_variants(match_node * root,
dwarf_builder * dw,
privilege_t privilege)
{
root
->bind_privilege(privilege)
->bind(dw);
root->bind(TOK_NEAREST)
->bind_privilege(privilege)
->bind(dw);
}
void
dwarf_derived_probe::register_function_variants(match_node * root,
dwarf_builder * dw,
privilege_t privilege)
{
root
->bind_privilege(privilege)
->bind(dw);
root->bind(TOK_CALL)
->bind_privilege(privilege)
->bind(dw);
root->bind(TOK_EXPORTED)
->bind_privilege(privilege)
->bind(dw);
root->bind(TOK_RETURN)
->bind_privilege(privilege)
->bind(dw);
// For process probes / uprobes, .maxactive() is unused.
if (! pr_contains (privilege, pr_stapusr))
{
root->bind(TOK_RETURN)
->bind_num(TOK_MAXACTIVE)->bind(dw);
}
}
void
dwarf_derived_probe::register_function_and_statement_variants(
systemtap_session& s,
match_node * root,
dwarf_builder * dw,
privilege_t privilege
)
{
// Here we match 4 forms:
//
// .function("foo")
// .function(0xdeadbeef)
// .statement("foo")
// .statement(0xdeadbeef)
match_node *fv_root = root->bind_str(TOK_FUNCTION);
register_function_variants(fv_root, dw, privilege);
// ROOT.function("STRING") always gets the .inline and .label variants.
fv_root->bind(TOK_INLINE)
->bind_privilege(privilege)
->bind(dw);
fv_root->bind_str(TOK_LABEL)
->bind_privilege(privilege)
->bind(dw);
fv_root->bind_str(TOK_CALLEE)
->bind_privilege(privilege)
->bind(dw);
fv_root->bind_str(TOK_CALLEE)
->bind(TOK_RETURN)
->bind_privilege(privilege)
->bind(dw);
fv_root->bind_str(TOK_CALLEE)
->bind(TOK_CALL)
->bind_privilege(privilege)
->bind(dw);
fv_root->bind(TOK_CALLEES)
->bind_privilege(privilege)
->bind(dw);
fv_root->bind_num(TOK_CALLEES)
->bind_privilege(privilege)
->bind(dw);
fv_root = root->bind_num(TOK_FUNCTION);
register_function_variants(fv_root, dw, privilege);
// ROOT.function(NUMBER).inline is deprecated in release 1.7 and removed thereafter.
if (strverscmp(s.compatible.c_str(), "1.7") <= 0)
{
fv_root->bind(TOK_INLINE)
->bind_privilege(privilege)
->bind(dw);
}
register_statement_variants(root->bind_str(TOK_STATEMENT), dw, privilege);
register_statement_variants(root->bind_num(TOK_STATEMENT), dw, privilege);
}
void
dwarf_derived_probe::register_sdt_variants(systemtap_session&,
match_node * root,
dwarf_builder * dw)
{
root->bind_str(TOK_MARK)
->bind_privilege(pr_all)
->bind(dw);
root->bind_str(TOK_PROVIDER)->bind_str(TOK_MARK)
->bind_privilege(pr_all)
->bind(dw);
}
void
dwarf_derived_probe::register_plt_variants(systemtap_session&,
match_node * root,
dwarf_builder * dw)
{
root->bind(TOK_PLT)
->bind_privilege(pr_all)
->bind(dw);
root->bind_str(TOK_PLT)
->bind_privilege(pr_all)
->bind(dw);
root->bind(TOK_PLT)
->bind(TOK_RETURN)
->bind_privilege(pr_all)
->bind(dw);
root->bind_str(TOK_PLT)
->bind(TOK_RETURN)
->bind_privilege(pr_all)
->bind(dw);
}
void
dwarf_derived_probe::register_patterns(systemtap_session& s)
{
match_node* root = s.pattern_root;
dwarf_builder *dw = new dwarf_builder();
update_visitor *filter = new dwarf_cast_expanding_visitor(s, *dw);
s.code_filters.push_back(filter);
filter = new dwarf_atvar_expanding_visitor(s, *dw);
s.code_filters.push_back(filter);
register_function_and_statement_variants(s, root->bind(TOK_KERNEL), dw, pr_privileged);
register_function_and_statement_variants(s, root->bind_str(TOK_MODULE), dw, pr_privileged);
root->bind(TOK_KERNEL)->bind_num(TOK_STATEMENT)->bind(TOK_ABSOLUTE)
->bind(dw);
match_node* uprobes[] = {
root->bind(TOK_PROCESS),
root->bind_str(TOK_PROCESS),
root->bind_num(TOK_PROCESS),
root->bind(TOK_PROCESS)->bind_str(TOK_LIBRARY),
root->bind_str(TOK_PROCESS)->bind_str(TOK_LIBRARY),
};
for (size_t i = 0; i < sizeof(uprobes) / sizeof(*uprobes); ++i)
{
register_function_and_statement_variants(s, uprobes[i], dw, pr_all);
register_sdt_variants(s, uprobes[i], dw);
register_plt_variants(s, uprobes[i], dw);
}
}
void
dwarf_derived_probe::emit_probe_local_init(systemtap_session& s, translator_output * o)
{
if (perf_counter_refs.size())
{
o->newline() << "{";
o->indent(1);
unsigned ref_idx = 0;
for (auto pcii = perf_counter_refs.begin();
pcii != perf_counter_refs.end();
pcii++)
{
// Find the associated perf.counter probe
unsigned i = 0;
for (auto it=s.perf_counters.begin() ;
it != s.perf_counters.end();
it++, i++)
{
if ((*it).first == (*pcii))
{
// copy the perf counter values over
//
// NB: We'd like to simplify here. Right now we read
// the perf counters into "values", then copy that
// into the locals. We should be able to remove the
// locals, but the 'symbol' class isn't designed to
// point to the context structure itself, but the
// locals inside the context structure.
o->newline() << "l->l___perf_read_" + (*it).first
+ " = (int64_t)c->perf_read_values["
+ lex_cast(ref_idx) + "];";
ref_idx++;
break;
}
}
}
o->newline(-1) << "}";
}
if (access_vars)
{
// if accessing $variables, emit bsp cache setup for speeding up
o->newline() << "#if defined __ia64__";
o->newline() << "bspcache(c->unwaddr, c->kregs);";
o->newline() << "#endif";
}
}
// ------------------------------------------------------------------------
void
generic_kprobe_derived_probe_group::enroll (generic_kprobe_derived_probe* p)
{
probes_by_module.insert (make_pair (p->module, p));
// XXX: probes put at the same address (or symbol_name+offset)
// should all share a single kprobe/kretprobe, and have their
// handlers executed sequentially.
}
void
generic_kprobe_derived_probe_group::emit_module_decls (systemtap_session& s)
{
if (probes_by_module.empty()) return;
s.op->newline() << "/* ---- dwarf and non-dwarf kprobe-based probes ---- */";
// FIXME: we could do the same thing (finding stats for the embedded
// strings) for 'symbol_name'...
// Let's find some stats for the embedded strings. Maybe they
// are small and uniform enough to justify putting char[MAX]'s into
// the array instead of relocated char*'s.
size_t module_name_max = 0, section_name_max = 0;
size_t module_name_tot = 0, section_name_tot = 0;
size_t all_name_cnt = probes_by_module.size(); // for average
for (auto it = probes_by_module.begin(); it != probes_by_module.end(); it++)
{
generic_kprobe_derived_probe* p = it->second;
#define DOIT(var,expr) do { \
size_t var##_size = (expr) + 1; \
var##_max = max (var##_max, var##_size); \
var##_tot += var##_size; } while (0)
DOIT(module_name, p->module.size());
DOIT(section_name, p->section.size());
#undef DOIT
}
// Decide whether it's worthwhile to use char[] or char* by comparing
// the amount of average waste (max - avg) to the relocation data size
// (3 native long words).
#define CALCIT(var) \
if ((var##_name_max-(var##_name_tot/all_name_cnt)) < (3 * sizeof(void*))) \
{ \
s.op->newline() << "#define STAP_KPROBE_PROBE_STR_" << #var << " " \
<< "const char " << #var \
<< "[" << var##_name_max << "]"; \
if (s.verbose > 2) clog << "stap_kprobe_probe " << #var \
<< "[" << var##_name_max << "]" << endl; \
} \
else \
{ \
s.op->newline() << "#define STAP_KPROBE_PROBE_STR_" << #var << " " \
<< "const char * const " << #var << ""; \
if (s.verbose > 2) clog << "stap_kprobe_probe *" << #var << endl; \
}
CALCIT(module);
CALCIT(section);
#undef CALCIT
s.op->newline() << "#include \"linux/kprobes.c\"";
#define UNDEFIT(var) s.op->newline() << "#undef STAP_KPROBE_PROBE_STR_" << #var
UNDEFIT(module);
UNDEFIT(section);
#undef UNDEFIT
// Emit an array of kprobe/kretprobe pointers
s.op->newline() << "#if defined(STAPCONF_UNREGISTER_KPROBES)";
s.op->newline() << "static void * stap_unreg_kprobes[" << probes_by_module.size() << "];";
s.op->newline() << "#endif";
// Emit the actual probe list.
// NB: we used to plop a union { struct kprobe; struct kretprobe } into
// struct stap_kprobe_probe, but it being initialized data makes it add
// hundreds of bytes of padding per stap_kprobe_probe. (PR5673)
s.op->newline() << "static struct stap_kprobe stap_kprobes[" << probes_by_module.size() << "];";
// NB: bss!
s.op->newline() << "static struct stap_kprobe_probe stap_kprobe_probes[] = {";
s.op->indent(1);
size_t stap_kprobe_idx = 0;
for (auto it = probes_by_module.begin(); it != probes_by_module.end(); it++)
{
generic_kprobe_derived_probe* p = it->second;
s.op->newline() << "{";
if (p->has_return)
s.op->line() << " .return_p=1,";
if (p->has_maxactive)
{
s.op->line() << " .maxactive_p=1,";
assert (p->maxactive_val >= 0 && p->maxactive_val <= USHRT_MAX);
s.op->line() << " .maxactive_val=" << p->maxactive_val << ",";
}
if (p->saved_longs || p->saved_strings)
{
if (p->saved_longs)
s.op->line() << " .saved_longs=" << p->saved_longs << ",";
if (p->saved_strings)
s.op->line() << " .saved_strings=" << p->saved_strings << ",";
if (p->entry_handler)
s.op->line() << " .entry_probe=" << common_probe_init (p->entry_handler) << ",";
}
if (p->locations[0]->optional)
s.op->line() << " .optional_p=1,";
s.op->line() << " .address=(unsigned long)0x" << hex << p->addr << dec << "ULL,";
s.op->line() << " .module=\"" << p->module << "\",";
s.op->line() << " .section=\"" << p->section << "\",";
s.op->line() << " .probe=" << common_probe_init (p) << ",";
s.op->line() << " .kprobe=&stap_kprobes[" << stap_kprobe_idx++ << "],";
if (!p->symbol_name.empty())
{
// After kernel commit 4982223e51, module notifiers are
// being called too early. So, we have to switch to using
// symbol+offset probing for modules.
if (! p->section.empty())
s.op->newline(-1) << "#if LINUX_VERSION_CODE >= KERNEL_VERSION(3,10,0)";
else
s.op->indent(-1);
s.op->newline() << " .symbol_name=\"" << p->symbol_name << "\",";
s.op->line() << " .offset=(unsigned int)" << p->offset << ",";
if (! p->section.empty())
s.op->newline() << "#endif";
s.op->newline(1);
}
s.op->line() << " },";
}
s.op->newline(-1) << "};";
// Emit the kprobes callback function
s.op->newline();
s.op->newline() << "static int enter_kprobe_probe (struct kprobe *inst,";
s.op->line() << " struct pt_regs *regs) {";
// NB: as of PR5673, the kprobe|kretprobe union struct is in BSS
s.op->newline(1) << "int kprobe_idx = ((uintptr_t)inst-(uintptr_t)stap_kprobes)/sizeof(struct stap_kprobe);";
// Check that the index is plausible
s.op->newline() << "struct stap_kprobe_probe *skp = &stap_kprobe_probes[";
s.op->line() << "((kprobe_idx >= 0 && kprobe_idx < " << probes_by_module.size() << ")?";
s.op->line() << "kprobe_idx:0)"; // NB: at least we avoid memory corruption
// XXX: it would be nice to give a more verbose error though; BUG_ON later?
s.op->line() << "];";
common_probe_entryfn_prologue (s, "STAP_SESSION_RUNNING", "", "skp->probe",
"stp_probe_type_kprobe");
s.op->newline() << "c->kregs = regs;";
// Make it look like the IP is set as it wouldn't have been replaced
// by a breakpoint instruction when calling real probe handler. Reset
// IP regs on return, so we don't confuse kprobes. PR10458
s.op->newline() << "{";
s.op->indent(1);
s.op->newline() << "unsigned long kprobes_ip = REG_IP(c->kregs);";
s.op->newline() << "SET_REG_IP(regs, (unsigned long) inst->addr);";
s.op->newline() << "(*skp->probe->ph) (c);";
s.op->newline() << "SET_REG_IP(regs, kprobes_ip);";
s.op->newline(-1) << "}";
common_probe_entryfn_epilogue (s, true, otf_safe_context(s));
s.op->newline() << "return 0;";
s.op->newline(-1) << "}";
// Same for kretprobes
s.op->newline();
s.op->newline() << "static int enter_kretprobe_common (struct kretprobe_instance *inst,";
s.op->line() << " struct pt_regs *regs, int entry) {";
s.op->newline(1) << "struct kretprobe *krp = get_kretprobe(inst);";
// NB: as of PR5673, the kprobe|kretprobe union struct is in BSS
s.op->newline() << "int kprobe_idx = ((uintptr_t)krp-(uintptr_t)stap_kprobes)/sizeof(struct stap_kprobe);";
// Check that the index is plausible
s.op->newline() << "struct stap_kprobe_probe *skp = &stap_kprobe_probes[";
s.op->line() << "((kprobe_idx >= 0 && kprobe_idx < " << probes_by_module.size() << ")?";
s.op->line() << "kprobe_idx:0)"; // NB: at least we avoid memory corruption
// XXX: it would be nice to give a more verbose error though; BUG_ON later?
s.op->line() << "];";
s.op->newline() << "const struct stap_probe *sp = entry ? skp->entry_probe : skp->probe;";
s.op->newline() << "if (sp) {";
s.op->indent(1);
common_probe_entryfn_prologue (s, "STAP_SESSION_RUNNING", "", "sp",
"stp_probe_type_kretprobe");
s.op->newline() << "c->kregs = regs;";
// for assisting runtime's backtrace logic and accessing kretprobe data packets
s.op->newline() << "c->ips.krp.pi = inst;";
s.op->newline() << "c->ips.krp.pi_longs = skp->saved_longs;";
// Make it look like the IP is set as it wouldn't have been replaced
// by a breakpoint instruction when calling real probe handler. Reset
// IP regs on return, so we don't confuse kprobes. PR10458
s.op->newline() << "{";
s.op->newline(1) << "unsigned long kprobes_ip = REG_IP(c->kregs);";
s.op->newline() << "if (entry)";
s.op->newline(1) << "SET_REG_IP(regs, (unsigned long) get_kretprobe(inst)->kp.addr);";
s.op->newline(-1) << "else";
s.op->newline(1) << "SET_REG_IP(regs, (unsigned long) _stp_ret_addr_r(inst));";
s.op->newline(-1) << "(sp->ph) (c);";
s.op->newline() << "SET_REG_IP(regs, kprobes_ip);";
s.op->newline(-1) << "}";
common_probe_entryfn_epilogue (s, true, otf_safe_context(s));
s.op->newline(-1) << "}";
s.op->newline() << "return 0;";
s.op->newline(-1) << "}";
s.op->newline();
}
void
generic_kprobe_derived_probe_group::emit_module_init (systemtap_session& s)
{
if (probes_by_module.empty()) return;
s.op->newline() << "/* ---- dwarf and non-dwarf kprobe-based probes ---- */";
// We'll let stapkp_init() handle reporting errors by setting probe_point to
// NULL.
s.op->newline() << "probe_point = NULL;";
s.op->newline() << "rc = stapkp_init( "
<< "stap_kprobe_probes, "
<< "ARRAY_SIZE(stap_kprobe_probes));";
}
std::string
generic_kprobe_derived_probe::args_for_bpf() const
{
std::stringstream o;
if (has_return)
o << "kretprobe/" << sym_name_for_bpf;
else
o << "kprobe/" << "0x" << std::hex << addr;
return o.str();
}
bool
sort_for_bpf(systemtap_session& s __attribute__ ((unused)),
generic_kprobe_derived_probe_group *ge,
sort_for_bpf_probe_arg_vector &v)
{
if (!ge || ge->probes_by_module.empty())
return false;
for (auto i = ge->probes_by_module.begin();
i != ge->probes_by_module.end(); ++i)
{
generic_kprobe_derived_probe *p = i->second;
v.push_back(std::pair<derived_probe *, std::string>
(p, p->args_for_bpf()));
}
return true;
}
void
generic_kprobe_derived_probe_group::emit_module_refresh (systemtap_session& s)
{
if (probes_by_module.empty()) return;
s.op->newline() << "/* ---- dwarf and non-dwarf kprobe-based probes ---- */";
s.op->newline() << "stapkp_refresh( "
<< "modname, "
<< "stap_kprobe_probes, "
<< "ARRAY_SIZE(stap_kprobe_probes));";
}
void
generic_kprobe_derived_probe_group::emit_module_exit (systemtap_session& s)
{
if (probes_by_module.empty()) return;
s.op->newline() << "/* ---- dwarf and non-dwarf kprobe-based probes ---- */";
s.op->newline() << "stapkp_exit( "
<< "stap_kprobe_probes, "
<< "ARRAY_SIZE(stap_kprobe_probes));";
}
// ------------------------------------------------------------------------
static void sdt_v3_tokenize(const string& str, vector<string>& tokens)
{
string::size_type pos;
string::size_type lastPos = str.find_first_not_of(" ", 0);
string::size_type nextAt = str.find("@", lastPos);
if (nextAt == string::npos)
{
// PR13934: Assembly probes are not forced to use the N@OP form.
// In this case, N is inferred to be the native word size. Since we
// don't have a nice delimiter, just split it on spaces. SDT-asm authors
// then must not put any spaces in arguments, to avoid ambiguity.
tokenize(str, tokens, " ");
return;
}
while (lastPos != string::npos)
{
pos = nextAt + 1;
nextAt = str.find("@", pos);
if (nextAt == string::npos)
pos = string::npos;
else
pos = str.rfind(" ", nextAt);
tokens.push_back(str.substr(lastPos, pos - lastPos));
lastPos = str.find_first_not_of(" ", pos);
}
}
struct sdt_uprobe_var_expanding_visitor: public var_expanding_visitor
{
enum regwidths {QI, QIh, HI, SI, DI};
sdt_uprobe_var_expanding_visitor(systemtap_session& s,
dwflpp& dw,
int elf_machine,
interned_string process_name,
interned_string provider_name,
interned_string probe_name,
stap_sdt_probe_type probe_type,
interned_string arg_string,
int ac):
var_expanding_visitor (s), dw (dw), elf_machine (elf_machine),
process_name (process_name), provider_name (provider_name),
probe_name (probe_name), probe_type (probe_type), arg_count ((unsigned) ac)
{
// sanity check that we're not somehow here for a kernel probe
assert(is_user_module(process_name));
build_dwarf_registers();
need_debug_info = false;
if (probe_type == uprobe3_type)
{
sdt_v3_tokenize(arg_string, arg_tokens);
assert(arg_count <= 12);
}
else
{
tokenize(arg_string, arg_tokens, " ");
assert(arg_count <= 10);
}
}
dwflpp& dw;
int elf_machine;
interned_string process_name;
interned_string provider_name;
interned_string probe_name;
stap_sdt_probe_type probe_type;
unsigned arg_count;
vector<string> arg_tokens;
map<string, pair<unsigned,int> > dwarf_regs;
string regnames;
string percent_regnames;
bool need_debug_info;
void build_dwarf_registers();
void visit_target_symbol (target_symbol* e);
unsigned get_target_symbol_argno_and_validate (target_symbol* e);
long parse_out_arg_precision(string& asmarg);
char parse_out_arg_type(string& asmarg);
expression* try_parse_arg_literal (target_symbol *e,
const string& asmarg,
long precision);
expression* try_parse_arg_register (target_symbol *e,
const string& asmarg,
long precision);
expression* try_parse_arg_offset_register (target_symbol *e,
const string& asmarg,
long precision);
expression* try_parse_arg_register_pair (target_symbol *e,
const string& asmarg,
long precision);
expression* try_parse_arg_effective_addr (target_symbol *e,
const string& asmarg,
long precision);
expression* try_parse_arg_varname (target_symbol *e,
const string& asmarg,
long precision);
void visit_target_symbol_arg (target_symbol* e);
void visit_target_symbol_context (target_symbol* e);
void visit_atvar_op (atvar_op* e);
void visit_cast_op (cast_op* e);
};
void
sdt_uprobe_var_expanding_visitor::build_dwarf_registers ()
{
/* Register name mapping table depends on the elf machine of this particular
probe target process/file, not upon the host. So we can't just
#ifdef _i686_ etc. */
#define DRI(name,num,width) dwarf_regs[name]=make_pair(num,width)
if (elf_machine == EM_X86_64) {
DRI ("%rax", 0, DI); DRI ("%eax", 0, SI); DRI ("%ax", 0, HI);
DRI ("%al", 0, QI); DRI ("%ah", 0, QIh);
DRI ("%rdx", 1, DI); DRI ("%edx", 1, SI); DRI ("%dx", 1, HI);
DRI ("%dl", 1, QI); DRI ("%dh", 1, QIh);
DRI ("%rcx", 2, DI); DRI ("%ecx", 2, SI); DRI ("%cx", 2, HI);
DRI ("%cl", 2, QI); DRI ("%ch", 2, QIh);
DRI ("%rbx", 3, DI); DRI ("%ebx", 3, SI); DRI ("%bx", 3, HI);
DRI ("%bl", 3, QI); DRI ("%bh", 3, QIh);
DRI ("%rsi", 4, DI); DRI ("%esi", 4, SI); DRI ("%si", 4, HI);
DRI ("%sil", 4, QI);
DRI ("%rdi", 5, DI); DRI ("%edi", 5, SI); DRI ("%di", 5, HI);
DRI ("%dil", 5, QI);
DRI ("%rbp", 6, DI); DRI ("%ebp", 6, SI); DRI ("%bp", 6, HI);
DRI ("%bpl", 6, QI);
DRI ("%rsp", 7, DI); DRI ("%esp", 7, SI); DRI ("%sp", 7, HI);
DRI ("%spl", 7, QI);
DRI ("%r8", 8, DI); DRI ("%r8d", 8, SI); DRI ("%r8w", 8, HI);
DRI ("%r8b", 8, QI);
DRI ("%r9", 9, DI); DRI ("%r9d", 9, SI); DRI ("%r9w", 9, HI);
DRI ("%r9b", 9, QI);
DRI ("%r10", 10, DI); DRI ("%r10d", 10, SI); DRI ("%r10w", 10, HI);
DRI ("%r10b", 10, QI);
DRI ("%r11", 11, DI); DRI ("%r11d", 11, SI); DRI ("%r11w", 11, HI);
DRI ("%r11b", 11, QI);
DRI ("%r12", 12, DI); DRI ("%r12d", 12, SI); DRI ("%r12w", 12, HI);
DRI ("%r12b", 12, QI);
DRI ("%r13", 13, DI); DRI ("%r13d", 13, SI); DRI ("%r13w", 13, HI);
DRI ("%r13b", 13, QI);
DRI ("%r14", 14, DI); DRI ("%r14d", 14, SI); DRI ("%r14w", 14, HI);
DRI ("%r14b", 14, QI);
DRI ("%r15", 15, DI); DRI ("%r15d", 15, SI); DRI ("%r15w", 15, HI);
DRI ("%r15b", 15, QI);
DRI ("%rip", 16, DI); DRI ("%eip", 16, SI); DRI ("%ip", 16, HI);
DRI ("%xmm0", 17, DI); DRI ("%xmm1", 18, DI); DRI ("%xmm2", 19, DI); DRI ("%xmm3", 20, DI);
DRI ("%xmm4", 21, DI); DRI ("%xmm5", 22, DI); DRI ("%xmm6", 23, DI); DRI ("%xmm7", 24, DI);
DRI ("%xmm8", 25, DI); DRI ("%xmm9", 26, DI); DRI ("%xmm10", 27, DI); DRI ("%xmm11", 28, DI);
DRI ("%xmm12", 29, DI); DRI ("%xmm13", 30, DI); DRI ("%xmm14", 31, DI); DRI ("%xmm15", 32, DI);
DRI ("%st0", 33, DI); DRI ("%st1", 34, DI); DRI ("%st2", 35, DI); DRI ("%st3", 36, DI);
DRI ("%st4", 37, DI); DRI ("%st5", 38, DI); DRI ("%st6", 39, DI); DRI ("%st7", 40, DI);
} else if (elf_machine == EM_386) {
DRI ("%eax", 0, SI); DRI ("%ax", 0, HI); DRI ("%al", 0, QI);
DRI ("%ah", 0, QIh);
DRI ("%ecx", 1, SI); DRI ("%cx", 1, HI); DRI ("%cl", 1, QI);
DRI ("%ch", 1, QIh);
DRI ("%edx", 2, SI); DRI ("%dx", 2, HI); DRI ("%dl", 2, QI);
DRI ("%dh", 2, QIh);
DRI ("%ebx", 3, SI); DRI ("%bx", 3, HI); DRI ("%bl", 3, QI);
DRI ("%bh", 3, QIh);
DRI ("%esp", 4, SI); DRI ("%sp", 4, HI);
DRI ("%ebp", 5, SI); DRI ("%bp", 5, HI);
DRI ("%esi", 6, SI); DRI ("%si", 6, HI); DRI ("%sil", 6, QI);
DRI ("%edi", 7, SI); DRI ("%di", 7, HI); DRI ("%dil", 7, QI);
} else if (elf_machine == EM_PPC || elf_machine == EM_PPC64) {
DRI ("%r0", 0, DI);
DRI ("%r1", 1, DI);
DRI ("%r2", 2, DI);
DRI ("%r3", 3, DI);
DRI ("%r4", 4, DI);
DRI ("%r5", 5, DI);
DRI ("%r6", 6, DI);
DRI ("%r7", 7, DI);
DRI ("%r8", 8, DI);
DRI ("%r9", 9, DI);
DRI ("%r10", 10, DI);
DRI ("%r11", 11, DI);
DRI ("%r12", 12, DI);
DRI ("%r13", 13, DI);
DRI ("%r14", 14, DI);
DRI ("%r15", 15, DI);
DRI ("%r16", 16, DI);
DRI ("%r17", 17, DI);
DRI ("%r18", 18, DI);
DRI ("%r19", 19, DI);
DRI ("%r20", 20, DI);
DRI ("%r21", 21, DI);
DRI ("%r22", 22, DI);
DRI ("%r23", 23, DI);
DRI ("%r24", 24, DI);
DRI ("%r25", 25, DI);
DRI ("%r26", 26, DI);
DRI ("%r27", 27, DI);
DRI ("%r28", 28, DI);
DRI ("%r29", 29, DI);
DRI ("%r30", 30, DI);
DRI ("%r31", 31, DI);
// PR11821: unadorned register "names" without -mregnames
DRI ("0", 0, DI);
DRI ("1", 1, DI);
DRI ("2", 2, DI);
DRI ("3", 3, DI);
DRI ("4", 4, DI);
DRI ("5", 5, DI);
DRI ("6", 6, DI);
DRI ("7", 7, DI);
DRI ("8", 8, DI);
DRI ("9", 9, DI);
DRI ("10", 10, DI);
DRI ("11", 11, DI);
DRI ("12", 12, DI);
DRI ("13", 13, DI);
DRI ("14", 14, DI);
DRI ("15", 15, DI);
DRI ("16", 16, DI);
DRI ("17", 17, DI);
DRI ("18", 18, DI);
DRI ("19", 19, DI);
DRI ("20", 20, DI);
DRI ("21", 21, DI);
DRI ("22", 22, DI);
DRI ("23", 23, DI);
DRI ("24", 24, DI);
DRI ("25", 25, DI);
DRI ("26", 26, DI);
DRI ("27", 27, DI);
DRI ("28", 28, DI);
DRI ("29", 29, DI);
DRI ("30", 30, DI);
DRI ("31", 31, DI);
} else if (elf_machine == EM_S390) {
DRI ("%r0", 0, DI);
DRI ("%r1", 1, DI);
DRI ("%r2", 2, DI);
DRI ("%r3", 3, DI);
DRI ("%r4", 4, DI);
DRI ("%r5", 5, DI);
DRI ("%r6", 6, DI);
DRI ("%r7", 7, DI);
DRI ("%r8", 8, DI);
DRI ("%r9", 9, DI);
DRI ("%r10", 10, DI);
DRI ("%r11", 11, DI);
DRI ("%r12", 12, DI);
DRI ("%r13", 13, DI);
DRI ("%r14", 14, DI);
DRI ("%r15", 15, DI);
DRI ("%f0", 16, DI);
DRI ("%f1", 17, DI);
DRI ("%f2", 18, DI);
DRI ("%f3", 19, DI);
DRI ("%f4", 20, DI);
DRI ("%f5", 21, DI);
DRI ("%f6", 22, DI);
DRI ("%f7", 23, DI);
DRI ("%f8", 24, DI);
DRI ("%f9", 25, DI);
DRI ("%f10", 26, DI);
DRI ("%f11", 27, DI);
DRI ("%f12", 28, DI);
DRI ("%f13", 29, DI);
DRI ("%f14", 30, DI);
DRI ("%f15", 31, DI);
} else if (elf_machine == EM_ARM) {
DRI ("r0", 0, SI);
DRI ("r1", 1, SI);
DRI ("r2", 2, SI);
DRI ("r3", 3, SI);
DRI ("r4", 4, SI);
DRI ("r5", 5, SI);
DRI ("r6", 6, SI);
DRI ("r7", 7, SI);
DRI ("r8", 8, SI);
DRI ("r9", 9, SI);
DRI ("r10", 10, SI); DRI ("sl", 10, SI);
DRI ("fp", 11, SI);
DRI ("ip", 12, SI);
DRI ("sp", 13, SI);
DRI ("lr", 14, SI);
DRI ("pc", 15, SI);
} else if (elf_machine == EM_AARCH64) {
DRI ("x0", 0, DI); DRI ("w0", 0, SI);
DRI ("x1", 1, DI); DRI ("w1", 1, SI);
DRI ("x2", 2, DI); DRI ("w2", 2, SI);
DRI ("x3", 3, DI); DRI ("w3", 3, SI);
DRI ("x4", 4, DI); DRI ("w4", 4, SI);
DRI ("x5", 5, DI); DRI ("w5", 5, SI);
DRI ("x6", 6, DI); DRI ("w6", 6, SI);
DRI ("x7", 7, DI); DRI ("w7", 7, SI);
DRI ("x8", 8, DI); DRI ("w8", 8, SI);
DRI ("x9", 9, DI); DRI ("w9", 9, SI);
DRI ("x10", 10, DI); DRI ("w10", 10, SI);
DRI ("x11", 11, DI); DRI ("w11", 11, SI);
DRI ("x12", 12, DI); DRI ("w12", 12, SI);
DRI ("x13", 13, DI); DRI ("w13", 13, SI);
DRI ("x14", 14, DI); DRI ("w14", 14, SI);
DRI ("x15", 15, DI); DRI ("w15", 15, SI);
DRI ("x16", 16, DI); DRI ("w16", 16, SI);
DRI ("x17", 17, DI); DRI ("w17", 17, SI);
DRI ("x18", 18, DI); DRI ("w18", 18, SI);
DRI ("x19", 19, DI); DRI ("w19", 19, SI);
DRI ("x20", 20, DI); DRI ("w20", 20, SI);
DRI ("x21", 21, DI); DRI ("w21", 21, SI);
DRI ("x22", 22, DI); DRI ("w22", 22, SI);
DRI ("x23", 23, DI); DRI ("w23", 23, SI);
DRI ("x24", 24, DI); DRI ("w24", 24, SI);
DRI ("x25", 25, DI); DRI ("w25", 25, SI);
DRI ("x26", 26, DI); DRI ("w26", 26, SI);
DRI ("x27", 27, DI); DRI ("w27", 27, SI);
DRI ("x28", 28, DI); DRI ("w28", 28, SI);
DRI ("x29", 29, DI); DRI ("w29", 29, SI);
DRI ("x30", 30, DI); DRI ("w30", 30, SI);
DRI ("sp", 31, DI);
DRI ("v0", 64, DI); DRI ("v1", 65, DI); DRI ("v2", 66, DI); DRI ("v3", 67, DI);
DRI ("v4", 68, DI); DRI ("v5", 69, DI); DRI ("v6", 70, DI); DRI ("v7", 71, DI);
DRI ("v8", 72, DI); DRI ("v9", 73, DI); DRI ("v10", 74, DI); DRI ("v11", 75, DI);
DRI ("v12", 76, DI); DRI ("v13", 77, DI); DRI ("v14", 78, DI); DRI ("v15", 79, DI);
DRI ("v16", 80, DI); DRI ("v17", 81, DI); DRI ("v18", 82, DI); DRI ("v19", 83, DI);
DRI ("v20", 84, DI); DRI ("v21", 85, DI); DRI ("v22", 86, DI); DRI ("v23", 87, DI);
DRI ("v24", 88, DI); DRI ("25", 89, DI); DRI ("v26", 90, DI); DRI ("v27", 91, DI);
DRI ("v28", 92, DI); DRI ("v29", 93, DI); DRI ("v30", 94, DI); DRI ("v31", 95, DI);
} else if (elf_machine == EM_RISCV) {
Dwarf_Addr bias;
Elf* elf = (dwfl_module_getelf (dw.mod_info->mod, &bias));
enum regwidths riscv_reg_width =
(gelf_getclass (elf) == ELFCLASS32) ? SI : DI;
DRI ("x0", 0, riscv_reg_width); DRI ("zero", 0, riscv_reg_width);
DRI ("x1", 1, riscv_reg_width); DRI ("ra", 1, riscv_reg_width);
DRI ("x2", 2, riscv_reg_width); DRI ("sp", 2, riscv_reg_width);
DRI ("x3", 3, riscv_reg_width); DRI ("gp", 3, riscv_reg_width);
DRI ("x4", 4, riscv_reg_width); DRI ("tp", 4, riscv_reg_width);
DRI ("x5", 5, riscv_reg_width); DRI ("t0", 5, riscv_reg_width);
DRI ("x6", 6, riscv_reg_width); DRI ("t1", 6, riscv_reg_width);
DRI ("x7", 7, riscv_reg_width); DRI ("t2", 7, riscv_reg_width);
DRI ("x8", 8, riscv_reg_width); DRI ("s0", 8, riscv_reg_width); DRI ("fp", 8, riscv_reg_width);
DRI ("x9", 9, riscv_reg_width); DRI ("s1", 9, riscv_reg_width);
DRI ("x10", 10, riscv_reg_width); DRI ("a0", 10, riscv_reg_width);
DRI ("x11", 11, riscv_reg_width); DRI ("a1", 11, riscv_reg_width);
DRI ("x12", 12, riscv_reg_width); DRI ("a2", 12, riscv_reg_width);
DRI ("x13", 13, riscv_reg_width); DRI ("a3", 13, riscv_reg_width);
DRI ("x14", 14, riscv_reg_width); DRI ("a4", 14, riscv_reg_width);
DRI ("x15", 15, riscv_reg_width); DRI ("a5", 15, riscv_reg_width);
DRI ("x16", 16, riscv_reg_width); DRI ("a6", 16, riscv_reg_width);
DRI ("x17", 17, riscv_reg_width); DRI ("a7", 17, riscv_reg_width);
DRI ("x18", 18, riscv_reg_width); DRI ("s2", 18, riscv_reg_width);
DRI ("x19", 19, riscv_reg_width); DRI ("s3", 19, riscv_reg_width);
DRI ("x20", 20, riscv_reg_width); DRI ("s4", 20, riscv_reg_width);
DRI ("x21", 21, riscv_reg_width); DRI ("s5", 21, riscv_reg_width);
DRI ("x22", 22, riscv_reg_width); DRI ("s6", 22, riscv_reg_width);
DRI ("x23", 23, riscv_reg_width); DRI ("s7", 23, riscv_reg_width);
DRI ("x24", 24, riscv_reg_width); DRI ("s8", 24, riscv_reg_width);
DRI ("x25", 25, riscv_reg_width); DRI ("s9", 25, riscv_reg_width);
DRI ("x26", 26, riscv_reg_width); DRI ("s10", 26, riscv_reg_width);
DRI ("x27", 27, riscv_reg_width); DRI ("s11", 27, riscv_reg_width);
DRI ("x28", 28, riscv_reg_width); DRI ("t3", 28, riscv_reg_width);
DRI ("x29", 29, riscv_reg_width); DRI ("t4", 29, riscv_reg_width);
DRI ("x30", 30, riscv_reg_width); DRI ("t5", 30, riscv_reg_width);
DRI ("x31", 31, riscv_reg_width); DRI ("t6", 31, riscv_reg_width);
} else if (elf_machine == EM_MIPS) {
Dwarf_Addr bias;
Elf* elf = (dwfl_module_getelf (dw.mod_info->mod, &bias));
enum regwidths mips_reg_width =
(gelf_getclass (elf) == ELFCLASS32) ? SI : DI;
DRI ("$zero", 0, mips_reg_width);
DRI ("$at", 1, mips_reg_width);
DRI ("$v0", 2, mips_reg_width);
DRI ("$v1", 3, mips_reg_width);
DRI ("$a0", 4, mips_reg_width);
DRI ("$a1", 5, mips_reg_width);
DRI ("$a2", 6, mips_reg_width);
DRI ("$a3", 7, mips_reg_width);
DRI ("$a4", 8, mips_reg_width);
DRI ("$a5", 9, mips_reg_width);
DRI ("$a6", 10, mips_reg_width);
DRI ("$a7", 11, mips_reg_width);
DRI ("$t0", 12, mips_reg_width);
DRI ("$t1", 13, mips_reg_width);
DRI ("$t2", 14, mips_reg_width);
DRI ("$t3", 15, mips_reg_width);
DRI ("$s0", 16, mips_reg_width);
DRI ("$s1", 17, mips_reg_width);
DRI ("$s2", 18, mips_reg_width);
DRI ("$s3", 19, mips_reg_width);
DRI ("$s4", 20, mips_reg_width);
DRI ("$s5", 21, mips_reg_width);
DRI ("$s6", 22, mips_reg_width);
DRI ("$s7", 23, mips_reg_width);
DRI ("$t8", 24, mips_reg_width);
DRI ("$t9", 25, mips_reg_width);
DRI ("$k0", 26, mips_reg_width);
DRI ("$k1", 27, mips_reg_width);
DRI ("$gp", 28, mips_reg_width);
DRI ("$sp", 29, mips_reg_width);
DRI ("$s8", 30, mips_reg_width);
DRI ("$fp", 30, mips_reg_width);
DRI ("$ra", 31, mips_reg_width);
DRI ("$0", 0, mips_reg_width);
DRI ("$1", 1, mips_reg_width);
DRI ("$2", 2, mips_reg_width);
DRI ("$3", 3, mips_reg_width);
DRI ("$4", 4, mips_reg_width);
DRI ("$5", 5, mips_reg_width);
DRI ("$6", 6, mips_reg_width);
DRI ("$7", 7, mips_reg_width);
DRI ("$8", 8, mips_reg_width);
DRI ("$9", 9, mips_reg_width);
DRI ("$10", 10, mips_reg_width);
DRI ("$11", 11, mips_reg_width);
DRI ("$12", 12, mips_reg_width);
DRI ("$13", 13, mips_reg_width);
DRI ("$14", 14, mips_reg_width);
DRI ("$15", 15, mips_reg_width);
DRI ("$16", 16, mips_reg_width);
DRI ("$17", 17, mips_reg_width);
DRI ("$18", 18, mips_reg_width);
DRI ("$19", 19, mips_reg_width);
DRI ("$20", 20, mips_reg_width);
DRI ("$21", 21, mips_reg_width);
DRI ("$22", 22, mips_reg_width);
DRI ("$23", 23, mips_reg_width);
DRI ("$24", 24, mips_reg_width);
DRI ("$25", 25, mips_reg_width);
DRI ("$26", 26, mips_reg_width);
DRI ("$27", 27, mips_reg_width);
DRI ("$28", 28, mips_reg_width);
DRI ("$29", 29, mips_reg_width);
DRI ("$30", 30, mips_reg_width);
DRI ("$31", 31, mips_reg_width);
} else if (arg_count) {
/* permit this case; just fall back to dwarf */
}
#undef DRI
// Build regex pieces out of the known dwarf_regs. We keep two separate
// lists: ones with the % prefix (and thus unambigiuous even despite PR11821),
// and ones with no prefix (and thus only usable in unambiguous contexts).
for (auto ri = dwarf_regs.cbegin(); ri != dwarf_regs.cend(); ri++)
{
string regname = ri->first;
assert (regname != "");
// for register names starting with '$' convert the dollar to a
// '\$' as otherwise the regexp tries to match end-of-line
if (regname[0]=='$')
regname = string("\\")+regname;
regnames += string("|")+regname;
if (regname[0]=='%')
percent_regnames += string("|")+regname;
}
// clip off leading |
if (regnames != "")
regnames = regnames.substr(1);
if (percent_regnames != "")
percent_regnames = percent_regnames.substr(1);
}
void
sdt_uprobe_var_expanding_visitor::visit_target_symbol_context (target_symbol* e)
{
if (e->addressof)
throw SEMANTIC_ERROR(_("cannot take address of context variable"), e->tok);
if (e->name == "$$name")
{
literal_string *myname = new literal_string (probe_name);
myname->tok = e->tok;
provide(myname);
return;
}
else if (e->name == "$$provider")
{
literal_string *myname = new literal_string (provider_name);
myname->tok = e->tok;
provide(myname);
return;
}
else if (e->name == "$$vars" || e->name == "$$parms")
{
e->assert_no_components("sdt", true);
// Convert $$vars to sprintf of a list of vars which we recursively evaluate
print_format* pf = print_format::create(e->tok, "sprintf");
for (unsigned i = 1; i <= arg_count; ++i)
{
if (i > 1)
pf->raw_components += " ";
target_symbol *tsym = new target_symbol;
tsym->tok = e->tok;
tsym->name = "$arg" + lex_cast(i);
pf->raw_components += tsym->name;
tsym->components = e->components;
expression *texp = require<expression> (tsym);
if (e->check_pretty_print ())
pf->raw_components += "=%s";
else
pf->raw_components += "=%#x";
pf->args.push_back(texp);
}
pf->components = print_format::string_to_components(pf->raw_components);
provide (pf);
}
else
assert(0); // shouldn't get here
}
unsigned
sdt_uprobe_var_expanding_visitor::get_target_symbol_argno_and_validate (target_symbol *e)
{
// parsing
unsigned argno = 0;
if (startswith(e->name, "$arg"))
{
try
{
argno = lex_cast<unsigned>(e->name.substr(4).to_string());
}
catch (const runtime_error& f)
{
// non-integral $arg suffix: e.g. $argKKKSDF
argno = 0;
}
}
// validation
if (arg_count == 0 || // a sdt.h variant without .probe-stored arg_count
argno < 1 || argno > arg_count) // a $argN with out-of-range N
{
// NB: Either
// 1) uprobe1_type $argN or $FOO (we don't know the arg_count)
// 2) uprobe2_type $FOO (no probe args)
// both of which get resolved later.
// Throw it now, and it might be resolved by DWARF later.
need_debug_info = true;
throw SEMANTIC_ERROR(_("target-symbol requires debuginfo"), e->tok);
}
assert (arg_tokens.size() >= argno);
return argno;
}
long
sdt_uprobe_var_expanding_visitor::parse_out_arg_precision(string& asmarg)
{
long precision;
if (asmarg.find('@') != string::npos)
{
long at_or_type = asmarg.find_first_of("@f");
precision = lex_cast<int>(asmarg.substr(0, at_or_type));
asmarg = asmarg.substr(at_or_type);
}
else
{
// V1/V2 do not have precision field so default to signed long
// V3 asm does not have precision field so default to unsigned long
if (probe_type == uprobe3_type)
precision = sizeof(long); // this is an asm probe
else
precision = -sizeof(long);
}
return precision;
}
char
sdt_uprobe_var_expanding_visitor::parse_out_arg_type(string& asmarg)
{
// Reference: __builtin_classify_type
char type;
if (asmarg.find('@') != string::npos)
{
type = asmarg[0];
asmarg = asmarg.substr(asmarg.find('@')+1);
}
else
type = 'i';
return type;
}
expression*
sdt_uprobe_var_expanding_visitor::try_parse_arg_literal (target_symbol *e,
const string& asmarg,
long precision)
{
expression *argexpr = NULL;
// Here, we test for a numeric literal.
// Only accept (signed) decimals throughout. XXX
// PR11821. NB: on powerpc, literals are not prefixed with $,
// so this regex does not match. But that's OK, since without
// -mregnames, we can't tell them apart from register numbers
// anyway. With -mregnames, we could, if gcc somehow
// communicated to us the presence of that option, but alas it
// doesn't. http://gcc.gnu.org/PR44995.
vector<string> matches;
string regexp;
if (elf_machine == EM_AARCH64 || elf_machine == EM_MIPS) {
regexp = "^([-]?[0-9][0-9]*)$";
} else {
regexp = "^[i\\$#]([-]?[0-9][0-9]*)$";
}
if (!regexp_match (asmarg, regexp, matches)) {
string sn =matches[1];
int64_t n;
// We have to pay attention to the size & sign, as gcc sometimes
// propagates constants that don't quite match, like a negative
// value to fill an unsigned type.
// NB: let it throw if something happens
switch (precision)
{
case -1: n = lex_cast< int8_t>(sn); break;
case 1: n = lex_cast< uint8_t>(sn); break;
case -2: n = lex_cast< int16_t>(sn); break;
case 2: n = lex_cast<uint16_t>(sn); break;
case -4: n = lex_cast< int32_t>(sn); break;
case 4: n = lex_cast<uint32_t>(sn); break;
default:
case -8: n = lex_cast< int64_t>(sn); break;
case 8: n = lex_cast<uint64_t>(sn); break;
}
literal_number* ln = new literal_number(n);
ln->tok = e->tok;
argexpr = ln;
}
return argexpr;
}
expression*
sdt_uprobe_var_expanding_visitor::try_parse_arg_register (target_symbol *e,
const string& asmarg,
long precision)
{
expression *argexpr = NULL;
// test for REGISTER
// NB: Because PR11821, we must use percent_regnames here.
string regexp;
if (elf_machine == EM_PPC || elf_machine == EM_PPC64
|| elf_machine == EM_ARM || elf_machine == EM_AARCH64
|| elf_machine == EM_RISCV)
regexp = "^(" + regnames + ")$";
else
regexp = "^(" + percent_regnames + ")$";
vector<string> matches;
if (!regexp_match(asmarg, regexp, matches))
{
string regname = matches[1];
auto ri = dwarf_regs.find (regname);
if (ri != dwarf_regs.end()) // known register
{
embedded_expr *get_arg1 = new embedded_expr;
string width_adjust;
switch (ri->second.second)
{
case QI: width_adjust = ") & 0xff)"; break;
case QIh: width_adjust = ">>8) & 0xff)"; break;
case HI:
// preserve 16 bit register signness
width_adjust = ") & 0xffff)";
if (precision < 0)
width_adjust += " << 48 >> 48";
break;
case SI:
// preserve 32 bit register signness
width_adjust = ") & 0xffffffff)";
if (precision < 0)
width_adjust += " << 32 >> 32";
break;
default: width_adjust = "))";
}
string type = "";
if (probe_type == uprobe3_type)
type = (precision < 0
? "(int" : "(uint") + lex_cast(abs(precision) * 8) + "_t)";
type = type + "((";
get_arg1->tok = e->tok;
get_arg1->code = string("/* unprivileged */ /* pure */")
+ string(" ((int64_t)") + type
+ string("u_fetch_register(")
+ lex_cast(dwarf_regs[regname].first) + string("))")
+ width_adjust;
argexpr = get_arg1;
}
}
return argexpr;
}
static string
precision_to_function(long precision)
{
switch (precision)
{
case 1: case -1:
return "user_int8";
case 2:
return "user_uint16";
case -2:
return "user_int16";
case 4:
return "user_uint32";
case -4:
return "user_int32";
case 8: case -8:
return "user_int64";
default:
return "user_long";
}
}
expression*
sdt_uprobe_var_expanding_visitor::try_parse_arg_offset_register (target_symbol *e,
const string& asmarg,
long precision)
{
expression *argexpr = NULL;
// test for OFFSET(REGISTER) where OFFSET is +-N+-N+-N
// NB: Despite PR11821, we can use regnames here, since the parentheses
// make things unambiguous. (Note: gdb/stap-probe.c also parses this)
// On ARM test for [REGISTER, OFFSET]
string regexp;
int reg, offset1;
if (elf_machine == EM_ARM || elf_machine == EM_AARCH64)
{
regexp = "^\\[(" + regnames + ")(,[ ]*[#]?([+-]?[0-9]+)([+-][0-9]*)?([+-][0-9]*)?)?\\]$";
reg = 1;
offset1 = 3;
}
else
{
regexp = "^([+-]?[0-9]*)([+-][0-9]*)?([+-][0-9]*)?[(](" + regnames + ")[)]$";
reg = 4;
offset1 = 1;
}
vector<string> matches;
if (!regexp_match(asmarg, regexp, matches))
{
string regname;
int64_t disp = 0;
if (matches[reg].length())
regname = matches[reg];
if (dwarf_regs.find (regname) == dwarf_regs.end())
throw SEMANTIC_ERROR(_F("unrecognized register '%s'", regname.c_str()));
for (int i=offset1; i <= (offset1 + 2); i++)
if (matches[i].length())
// should decode positive/negative hex/decimal
// NB: let it throw if something happens
disp += lex_cast<int64_t>(matches[i]);
// synthesize user_long(%{fetch_register(R)%} + D)
embedded_expr *get_arg1 = new embedded_expr;
get_arg1->tok = e->tok;
get_arg1->code = string("/* unprivileged */ /* pure */")
+ string("u_fetch_register(")
+ lex_cast(dwarf_regs[regname].first) + string(")");
// XXX: may we ever need to cast that to a narrower type?
literal_number* inc = new literal_number(disp);
inc->tok = e->tok;
binary_expression *be = new binary_expression;
be->tok = e->tok;
be->left = get_arg1;
be->op = "+";
be->right = inc;
functioncall *fc = new functioncall;
fc->function = precision_to_function(precision);
fc->tok = e->tok;
fc->args.push_back(be);
argexpr = fc;
}
return argexpr;
}
expression*
sdt_uprobe_var_expanding_visitor::try_parse_arg_register_pair (target_symbol *e,
const string& asmarg,
long precision)
{
// BZ1613157: for powerpc, accept "R,R", as an alias of "(Ra,Rb)"
if (sess.architecture.substr(0,7) == "powerpc")
{
// test for BASE_REGISTER,INDEX_REGISTER
string regexp = "^(" + regnames + "),(" + regnames + ")$";
vector<string> matches;
if (!regexp_match(asmarg, regexp, matches))
{
// delegate to parenthetic syntax
return try_parse_arg_effective_addr (e, string("(")+asmarg+string(")"), precision);
}
}
else if (elf_machine == EM_AARCH64) // BZ1788648
{
// test for [BASE_REGISTER, INDEX_REGISTER]
string regexp = "^\\[(" + regnames + "), (" + regnames + ")\\]$";
vector<string> matches;
if (!regexp_match(asmarg, regexp, matches))
{
// delegate to parenthetic syntax
string regnames = asmarg.substr(1, asmarg.length()-2); // trim the []
return try_parse_arg_effective_addr (e, string("(")+regnames+string(")"), precision); // add the ()
}
}
return NULL;
}
expression*
sdt_uprobe_var_expanding_visitor::try_parse_arg_effective_addr (target_symbol *e,
const string& asmarg,
long precision)
{
expression *argexpr = NULL;
// test for OFFSET(BASE_REGISTER,INDEX_REGISTER[,SCALE]) where OFFSET is +-N+-N+-N
// NB: Despite PR11821, we can use regnames here, since the parentheses
// make things unambiguous. (Note: gdb/stap-probe.c also parses this)
string regexp = "^([+-]?[0-9]*)([+-][0-9]*)?([+-][0-9]*)?[(](" + regnames + "),[ ]?(" +
regnames + ")(,[1248])?[)]$";
vector<string> matches;
if (!regexp_match(asmarg, regexp, matches))
{
string baseregname;
string indexregname;
int64_t disp = 0;
short scale = 1;
if (matches[6].length())
// NB: let it throw if we can't cast
scale = lex_cast<short>(matches[6].substr(1)); // NB: skip the comma!
if (matches[4].length())
baseregname = matches[4];
if (dwarf_regs.find (baseregname) == dwarf_regs.end())
throw SEMANTIC_ERROR(_F("unrecognized base register '%s'", baseregname.c_str()));
if (matches[5].length())
indexregname = matches[5];
if (dwarf_regs.find (indexregname) == dwarf_regs.end())
throw SEMANTIC_ERROR(_F("unrecognized index register '%s'", indexregname.c_str()));
for (int i = 1; i <= 3; i++) // up to three OFFSET terms
if (matches[i].length())
// should decode positive/negative hex/decimal
// NB: let it throw if something happens
disp += lex_cast<int64_t>(matches[i]);
// synthesize user_long(%{fetch_register(R1)+fetch_register(R2)*N%} + D)
embedded_expr *get_arg1 = new embedded_expr;
string regfn = "u_fetch_register";
get_arg1->tok = e->tok;
get_arg1->code = string("/* unprivileged */ /* pure */")
+ regfn + string("(")+lex_cast(dwarf_regs[baseregname].first)+string(")")
+ string("+(")
+ regfn + string("(")+lex_cast(dwarf_regs[indexregname].first)+string(")")
+ string("*")
+ lex_cast(scale)
+ string(")");
// NB: could plop this +DISPLACEMENT bit into the embedded-c expression too
literal_number* inc = new literal_number(disp);
inc->tok = e->tok;
binary_expression *be = new binary_expression;
be->tok = e->tok;
be->left = get_arg1;
be->op = "+";
be->right = inc;
functioncall *fc = new functioncall;
fc->function = precision_to_function(precision);
fc->tok = e->tok;
fc->args.push_back(be);
argexpr = fc;
}
return argexpr;
}
expression*
sdt_uprobe_var_expanding_visitor::try_parse_arg_varname (target_symbol *e,
const string& asmarg,
long precision)
{
static unsigned tick = 0;
expression *argexpr = NULL;
// test for [OFF+]VARNAME[+OFF][(REGISTER)], where VARNAME is a variable
// name. NB: Despite PR11821, we can use regnames here, since the parentheses
// make things unambiguous.
string regex = "^(([0-9]+)[+])?([a-zA-Z_][a-zA-Z0-9_]*)([+][0-9]+)?([(]("
+ regnames + ")[)])?$";
vector<string> matches;
if (!regexp_match(asmarg, regex, matches))
{
assert(matches.size() >= 4);
interned_string varname = matches[3];
// OFF can be before VARNAME (put in matches[2]) or after (put in
// matches[4]) (or both?). Seems like in most cases it comes after,
// unless the code was compiled with -fPIC.
int64_t offset = 0;
if (!matches[2].empty())
offset += lex_cast<int64_t>(matches[2]);
if (matches.size() >= 5 && !matches[4].empty())
offset += lex_cast<int64_t>(matches[4]);
string regname;
if (matches.size() >= 7)
regname = matches[6];
// If it's just VARNAME, then proceed. If it's VARNAME(REGISTER), then
// only proceed if it's RIP-relative addressing on x86_64.
if (regname.empty() || (regname == "%rip" && elf_machine == EM_X86_64))
{
dw.mod_info->get_symtab();
if (dw.mod_info->symtab_status != info_present)
throw SEMANTIC_ERROR(_("can't retrieve symbol table"));
assert(dw.mod_info->sym_table);
unordered_map<interned_string, Dwarf_Addr>& globals = dw.mod_info->sym_table->globals;
unordered_map<interned_string, Dwarf_Addr>& locals = dw.mod_info->sym_table->locals;
Dwarf_Addr addr = 0;
// check symtab locals then globals
if (locals.count(varname))
addr = locals[varname];
if (globals.count(varname))
addr = globals[varname];
if (addr)
{
// add whatever offset is in the operand
addr += offset;
// adjust for dw bias because relocate_address() expects a
// libdw address and this addr is from the symtab
dw.get_module_dwarf(false, false);
addr -= dw.module_bias;
interned_string reloc_section;
Dwarf_Addr reloc_addr = dw.relocate_address(addr, reloc_section);
// OK, we have an address for the variable. Let's create a
// function that will just relocate it at runtime, and then
// call user_[u]int*() on the address it returns.
functioncall *user_int_call = new functioncall;
user_int_call->function = precision_to_function(precision);
user_int_call->tok = e->tok;
string fhash = detox_path(string(e->tok->location.file->name));
functiondecl *get_addr_decl = new functiondecl;
get_addr_decl->tok = e->tok;
get_addr_decl->synthetic = true;
get_addr_decl->unmangled_name = get_addr_decl->name =
"__private_" + fhash + "_sdt_arg_get_addr_" + lex_cast(tick++);
get_addr_decl->type = pe_long;
// build _stp_umodule_relocate(module, addr, current)
stringstream ss;
ss << " /* unprivileged */ /* pure */ /* pragma:vma */" << endl;
ss << "STAP_RETURN(_stp_umodule_relocate(";
ss << "\"" << path_remove_sysroot(sess, process_name) << "\", ";
ss << "0x" << hex << reloc_addr << dec << ", ";
ss << "current";
ss << "));" << endl;
embeddedcode *ec = new embeddedcode;
ec->tok = e->tok;
ec->code = ss.str();
get_addr_decl->body = ec;
get_addr_decl->join(sess);
functioncall *get_addr_call = new functioncall;
get_addr_call->tok = e->tok;
get_addr_call->function = get_addr_decl->name;
user_int_call->args.push_back(get_addr_call);
argexpr = user_int_call;
}
}
}
return argexpr;
}
void
sdt_uprobe_var_expanding_visitor::visit_target_symbol_arg (target_symbol *e)
{
try
{
unsigned argno = get_target_symbol_argno_and_validate(e); // the N in $argN
string asmarg = arg_tokens[argno-1]; // $arg1 => arg_tokens[0]
// Now we try to parse this thing, which is an assembler operand
// expression. If we can't, we warn, back down to need_debug_info
// and hope for the best. Here is the syntax for a few architectures.
// Note that the power iN syntax is only for V3 sdt.h; gcc emits the i.
//
// literal reg reg reg+ base+index*size+ VAR VAR+off RIP-relative
// indirect offset offset VAR+off
// x86 $N %rR (%rR) N(%rR) O(%bR,%iR,S) var var+off var+off(%rip)
// x86_64 $N %rR (%rR) N(%rR) O(%bR,%iR,S) var var+off var+off(%rip)
// power iN R (R) N(R) R,R
// ia64 N rR [r16]
// s390 N %rR 0(rR) N(r15)
// arm #N rR [rR] [rR, #N]
// arm64 N rR [rR] [rR, N]
// mips N $r N($r)
// riscv N r N(r)
expression* argexpr = 0; // filled in in case of successful parse
// Parse (and remove from asmarg) the leading length
long precision = parse_out_arg_precision(asmarg);
char type __attribute__ ((unused));
type = parse_out_arg_type(asmarg);
try
{
if ((argexpr = try_parse_arg_literal(e, asmarg, precision)) != NULL)
goto matched;
// all other matches require registers
if (regnames == "")
throw SEMANTIC_ERROR("no registers to use for parsing");
if ((argexpr = try_parse_arg_register(e, asmarg, precision)) != NULL)
goto matched;
if ((argexpr = try_parse_arg_offset_register(e, asmarg, precision)) != NULL)
goto matched;
if ((argexpr = try_parse_arg_register_pair(e, asmarg, precision)) != NULL)
goto matched;
if ((argexpr = try_parse_arg_effective_addr(e, asmarg, precision)) != NULL)
goto matched;
if ((argexpr = try_parse_arg_varname(e, asmarg, precision)) != NULL)
goto matched;
}
catch (const semantic_error& er)
{
if (sess.verbose > 3)
clog << "chaining to " << *e->tok << endl
<< sess.build_error_msg(er) << endl;
e->chain(er);
}
// The asmarg operand was not recognized. Back down to dwarf.
if (! sess.suppress_warnings)
{
if (probe_type == UPROBE3_TYPE)
sess.print_warning (_F("Can't parse SDT_V3 operand '%s' "
"[man error::sdt]", asmarg.c_str()),
e->tok);
else // must be *PROBE2; others don't get asm operands
sess.print_warning (_F("Downgrading SDT_V2 probe argument to "
"dwarf, can't parse '%s' [man error::sdt]",
asmarg.c_str()),
e->tok);
}
need_debug_info = true;
throw SEMANTIC_ERROR(_("SDT asm not understood, requires debuginfo "
"[man error::sdt]"), e->tok);
/* NOTREACHED */
matched:
assert (argexpr != 0);
if (sess.verbose > 2)
//TRANSLATORS: We're mapping the operand to a new expression*.
clog << _F("mapped asm operand %s to ", asmarg.c_str()) << *argexpr << endl;
if (e->components.empty()) // We have a scalar
{
if (e->addressof)
throw SEMANTIC_ERROR(_("cannot take address of sdt variable"), e->tok);
provide (argexpr);
}
else // $var->foo
{
cast_op *cast = new cast_op;
cast->name = "@cast";
cast->tok = e->tok;
cast->operand = argexpr;
cast->components = e->components;
cast->type_name = (string)probe_name + "_arg" + lex_cast(argno);
cast->module = process_name;
cast->visit(this);
}
}
catch (const semantic_error &er)
{
if (sess.verbose > 3)
clog << "chaining to " << *e->tok << endl
<< sess.build_error_msg(er) << endl;
e->chain (er);
provide (e);
}
}
void
sdt_uprobe_var_expanding_visitor::visit_target_symbol (target_symbol* e)
{
try
{
assert(e->name.size() > 0
&& (e->name[0] == '$' || e->name == "@var"));
if (e->name == "$$name" || e->name == "$$provider" || e->name == "$$parms" || e->name == "$$vars")
visit_target_symbol_context (e);
else
visit_target_symbol_arg (e);
}
catch (const semantic_error &er)
{
if (sess.verbose > 3)
clog << "chaining to " << *e->tok << endl
<< sess.build_error_msg(er) << endl;
e->chain (er);
provide (e);
}
}
void
sdt_uprobe_var_expanding_visitor::visit_atvar_op (atvar_op* e)
{
need_debug_info = true;
// Fill in our current module context if needed
if (e->module.empty())
e->module = process_name;
var_expanding_visitor::visit_atvar_op(e);
}
void
sdt_uprobe_var_expanding_visitor::visit_cast_op (cast_op* e)
{
// Fill in our current module context if needed
if (e->module.empty())
e->module = process_name;
var_expanding_visitor::visit_cast_op(e);
}
void
plt_expanding_visitor::visit_target_symbol (target_symbol *e)
{
try
{
if (e->name == "$$name")
{
literal_string *myname = new literal_string (entry);
myname->tok = e->tok;
provide(myname);
return;
}
// variable not found -> throw a semantic error
// (only to be caught right away, but this may be more complex later...)
string alternatives = "$$name";
throw SEMANTIC_ERROR(_F("unable to find plt variable '%s' (alternatives: %s)",
e->name.to_string().c_str(), alternatives.c_str()), e->tok);
}
catch (const semantic_error &er)
{
if (sess.verbose > 3)
clog << "chaining to " << *e->tok << endl
<< sess.build_error_msg(er) << endl;
e->chain (er);
provide (e);
}
}
struct sdt_query : public base_query
{
sdt_query(probe * base_probe, probe_point * base_loc,
dwflpp & dw, literal_map_t const & params,
vector<derived_probe *> & results, const string user_lib);
void query_library (const char *data);
set<string> visited_libraries;
bool resolved_library;
void query_plt (const char *, size_t) {}
void handle_query_module();
private:
stap_sdt_probe_type probe_type;
enum { probe_section=0, note_section=1, unknown_section=-1 } probe_loc;
probe * base_probe;
probe_point * base_loc;
literal_map_t const & params;
vector<derived_probe *> & results;
interned_string pp_mark;
interned_string pp_provider;
string user_lib;
set<string> probes_handled;
Elf_Data *pdata;
size_t probe_scn_offset;
size_t probe_scn_addr;
uint64_t arg_count;
GElf_Addr base;
GElf_Addr pc;
string arg_string;
string probe_name;
string provider_name;
GElf_Addr semaphore_load_offset;
Dwarf_Addr semaphore;
bool init_probe_scn();
bool get_next_probe();
void iterate_over_probe_entries();
void handle_probe_entry();
static void setup_note_probe_entry_callback (sdt_query *me,
const string& scn_name,
const string& note_name,
int type,
const char *data,
size_t len);
void setup_note_probe_entry (const string& scn_name,
const string& note_name, int type,
const char *data, size_t len);
void record_semaphore(vector<derived_probe *> & results, unsigned start);
probe* convert_location();
bool have_uprobe() {return probe_type == uprobe1_type || probe_type == uprobe2_type || probe_type == uprobe3_type;}
bool have_debuginfo_uprobe(bool need_debug_info)
{return probe_type == uprobe1_type
|| ((probe_type == uprobe2_type || probe_type == uprobe3_type)
&& need_debug_info);}
bool have_debuginfoless_uprobe() {return probe_type == uprobe2_type || probe_type == uprobe3_type;}
};
sdt_query::sdt_query(probe * base_probe, probe_point * base_loc,
dwflpp & dw, literal_map_t const & params,
vector<derived_probe *> & results, const string user_lib):
base_query(dw, params), resolved_library(false),
probe_type(unknown_probe_type), probe_loc(unknown_section),
base_probe(base_probe), base_loc(base_loc), params(params), results(results),
user_lib(user_lib), pdata(0), probe_scn_offset(0), probe_scn_addr(0), arg_count(0),
base(0), pc(0), semaphore_load_offset(0), semaphore(0)
{
assert(get_string_param(params, TOK_MARK, pp_mark));
get_string_param(params, TOK_PROVIDER, pp_provider); // pp_provider == "" -> unspecified
// PR10245: permit usage of dtrace-y "-" separator in marker name;
// map it to double-underscores.
size_t pos = 0;
string pp_mark2 = pp_mark; // copy for string replacement processing
while (1) // there may be more than one
{
size_t i = pp_mark2.find("-", pos);
if (i == string::npos) break;
pp_mark2.replace (i, 1, "__");
pos = i+1; // resume searching after the inserted __
}
pp_mark = pp_mark2;
// XXX: same for pp_provider?
}
void
sdt_query::handle_probe_entry()
{
if (! have_uprobe()
&& !probes_handled.insert(probe_name).second)
return;
if (sess.verbose > 3)
{
//TRANSLATORS: Describing what probe type (kprobe or uprobe) the probe
//TRANSLATORS: is matched to.
clog << _F("matched probe_name %s probe type ", probe_name.c_str());
switch (probe_type)
{
case uprobe1_type:
clog << "uprobe1 at 0x" << hex << pc << dec << endl;
break;
case uprobe2_type:
clog << "uprobe2 at 0x" << hex << pc << dec << endl;
break;
case uprobe3_type:
clog << "uprobe3 at 0x" << hex << pc << dec << endl;
break;
default:
clog << "unknown!" << endl;
break;
}
}
// Extend the derivation chain
probe *new_base = convert_location();
probe_point *new_location = new_base->locations[0];
bool need_debug_info = false;
// We could get the Elf* from either dwarf_getelf(dwfl_module_getdwarf(...))
// or dwfl_module_getelf(...). We only need it for the machine type, which
// should be the same. The bias is used for relocating debuginfoless probes,
// though, so that must come from the possibly-prelinked ELF file, not DWARF.
Dwarf_Addr bias;
Elf* elf = dwfl_module_getelf (dw.mod_info->mod, &bias);
/* Figure out the architecture of this particular ELF file. The
dwarfless register-name mappings depend on it. */
GElf_Ehdr ehdr_mem;
GElf_Ehdr* em = gelf_getehdr (elf, &ehdr_mem);
if (em == 0) { DWFL_ASSERT ("dwfl_getehdr", dwfl_errno()); }
assert(em);
int elf_machine = em->e_machine;
sdt_uprobe_var_expanding_visitor svv (sess, dw, elf_machine, module_val,
provider_name, probe_name, probe_type,
arg_string, arg_count);
if (sess.symbol_resolver) // trigger an early var_expanding_visitor::visit_functioncall pass
sess.symbol_resolver->current_probe = new_base;
// We can't do this the normal DWARF PR25841 way, because here we
// don't have the derived_probe yet, just a new copy of a new base
// probe. Yet we can't wait to do this mapping until later, because
// we need to know the need_debug_info flag as a prerequisite. XXX:
// maybe we could split this visitor into a need_debug_info
// calculator, and do $$name/etc. expansion later on the
// uprobe_derived_probes ... but they may be hiding in this->results
// or odd places.
var_expand_const_fold_loop (sess, new_base->body, svv);
need_debug_info = svv.need_debug_info;
// XXX: why not derive_probes() in the uprobes case too?
literal_map_t params;
for (unsigned i = 0; i < new_location->components.size(); ++i)
{
probe_point::component *c = new_location->components[i];
params[c->functor] = c->arg;
}
unsigned prior_results_size = results.size();
dwarf_query q(new_base, new_location, dw, params, results, "", "");
q.has_mark = true; // enables mid-statement probing
// V1 probes always need dwarf info
// V2+ probes need dwarf info in case of a variable reference
if (have_debuginfo_uprobe(need_debug_info))
dw.iterate_over_modules<base_query>(&query_module, &q);
// For V2+ probes, if variable references weren't used or failed (PR14369),
// then try with the more direct approach. Unresolved $vars might still
// cause their own error, but this gives them a chance to be optimized out.
if (have_debuginfoless_uprobe() && results.size() == prior_results_size)
{
string section;
Dwarf_Addr reloc_addr = q.statement_num_val + bias;
if (dwfl_module_relocations (q.dw.mod_info->mod) > 0)
{
dwfl_module_relocate_address (q.dw.mod_info->mod, &reloc_addr);
section = ".dynamic";
}
else
section = ".absolute";
uprobe_derived_probe* p =
new uprobe_derived_probe ("", "", 0,
path_remove_sysroot(sess,q.module_val),
section,
q.statement_num_val, reloc_addr, q, 0);
p->saveargs (arg_count);
results.push_back (p);
}
sess.unwindsym_modules.insert (dw.module_name);
record_semaphore(results, prior_results_size);
}
void
sdt_query::handle_query_module()
{
if (!init_probe_scn())
return;
if (sess.verbose > 3)
clog << "TOK_MARK: " << pp_mark << " TOK_PROVIDER: " << pp_provider << endl;
if (probe_loc == note_section)
{
GElf_Shdr shdr_mem;
GElf_Shdr *shdr = dw.get_section (".stapsdt.base", &shdr_mem);
// The 'base' lets us adjust the hardcoded addresses in notes for prelink
// effects. The 'semaphore_load_offset' is the load address of the .probes
// section so the semaphore can be converted to a section offset if needed.
if (shdr)
{
base = shdr->sh_addr;
shdr = dw.get_section (".probes", &shdr_mem);
if (shdr)
semaphore_load_offset = shdr->sh_addr - shdr->sh_offset;
}
else
base = semaphore_load_offset = 0;
dw.iterate_over_notes (this, &sdt_query::setup_note_probe_entry_callback);
}
else if (probe_loc == probe_section)
iterate_over_probe_entries ();
}
bool
sdt_query::init_probe_scn()
{
Elf* elf;
GElf_Shdr shdr_mem;
GElf_Shdr *shdr = dw.get_section (".note.stapsdt", &shdr_mem);
if (shdr)
{
probe_loc = note_section;
return true;
}
shdr = dw.get_section (".probes", &shdr_mem, &elf);
if (shdr)
{
pdata = elf_getdata_rawchunk (elf, shdr->sh_offset, shdr->sh_size, ELF_T_BYTE);
probe_scn_offset = 0;
probe_scn_addr = shdr->sh_addr;
assert (pdata != NULL);
if (sess.verbose > 4)
clog << "got .probes elf scn_addr@0x" << probe_scn_addr << ", size: "
<< pdata->d_size << endl;
probe_loc = probe_section;
return true;
}
else
return false;
}
void
sdt_query::setup_note_probe_entry_callback (sdt_query *me,
const string& scn_name,
const string& note_name, int type,
const char *data, size_t len)
{
me->setup_note_probe_entry (scn_name, note_name, type, data, len);
}
void
sdt_query::setup_note_probe_entry (const string& scn_name,
const string& note_name, int type,
const char *data, size_t len)
{
if (scn_name.compare(".note.stapsdt"))
return;
#define _SDT_NOTE_NAME "stapsdt"
if (note_name.compare(_SDT_NOTE_NAME))
return;
#define _SDT_NOTE_TYPE 3
if (type != _SDT_NOTE_TYPE)
return;
// we found a probe entry
union
{
Elf64_Addr a64[3];
Elf32_Addr a32[3];
} buf;
Dwarf_Addr bias;
Elf* elf = (dwfl_module_getelf (dw.mod_info->mod, &bias));
Elf_Data dst =
{
&buf, ELF_T_ADDR, EV_CURRENT,
gelf_fsize (elf, ELF_T_ADDR, 3, EV_CURRENT), 0, 0
};
assert (dst.d_size <= sizeof buf);
if (len < dst.d_size + 3)
return;
Elf_Data src =
{
(void *) data, ELF_T_ADDR, EV_CURRENT,
dst.d_size, 0, 0
};
if (gelf_xlatetom (elf, &dst, &src,
elf_getident (elf, NULL)[EI_DATA]) == NULL)
printf ("gelf_xlatetom: %s", elf_errmsg (-1));
probe_type = uprobe3_type;
const char * provider = data + dst.d_size;
const char *name = (const char*)memchr (provider, '\0', data + len - provider);
if(name++ == NULL)
return;
const char *args = (const char*)memchr (name, '\0', data + len - name);
if (args++ == NULL || memchr (args, '\0', data + len - name) != data + len - 1)
return;
provider_name = provider;
probe_name = name;
arg_string = args;
dw.mod_info->marks.insert(make_pair(provider, name));
// Did we find a matching probe?
if (! (dw.function_name_matches_pattern (probe_name, pp_mark)
&& ((pp_provider == "")
|| dw.function_name_matches_pattern (provider_name, pp_provider))))
return;
// PR13934: Assembly probes are not forced to use the N@OP form.
// If we have '@' then great, else count based on space-delimiters.
arg_count = count(arg_string.begin(), arg_string.end(), '@');
if (!arg_count && !arg_string.empty())
arg_count = 1 + count(arg_string.begin(), arg_string.end(), ' ');
GElf_Addr base_ref;
if (gelf_getclass (elf) == ELFCLASS32)
{
pc = buf.a32[0];
base_ref = buf.a32[1];
semaphore = buf.a32[2];
}
else
{
pc = buf.a64[0];
base_ref = buf.a64[1];
semaphore = buf.a64[2];
}
semaphore += base - base_ref;
pc += base - base_ref;
// The semaphore also needs the ELF bias added now, so
// record_semaphore can properly relocate it later.
semaphore += bias;
if (sess.verbose > 4)
clog << _F(" saw .note.stapsdt %s%s ", probe_name.c_str(), (provider_name != "" ? _(" (provider ")+provider_name+") " : "").c_str()) << "@0x" << hex << pc << dec << endl;
handle_probe_entry();
}
void
sdt_query::iterate_over_probe_entries()
{
// probes are in the .probe section
while (probe_scn_offset < pdata->d_size)
{
stap_sdt_probe_entry_v1 *pbe_v1 = (stap_sdt_probe_entry_v1 *) ((char*)pdata->d_buf + probe_scn_offset);
stap_sdt_probe_entry_v2 *pbe_v2 = (stap_sdt_probe_entry_v2 *) ((char*)pdata->d_buf + probe_scn_offset);
probe_type = (stap_sdt_probe_type)(pbe_v1->type_a);
if (! have_uprobe())
{
// Unless this is a mangled .probes section, this happens
// because the name of the probe comes first, followed by
// the sentinel.
if (sess.verbose > 5)
clog << _F("got unknown probe_type : 0x%x", probe_type) << endl;
probe_scn_offset += sizeof(__uint32_t);
continue;
}
if ((long)pbe_v1 % sizeof(__uint64_t)) // we have stap_sdt_probe_entry_v1.type_b
{
pbe_v1 = (stap_sdt_probe_entry_v1*)((char*)pbe_v1 - sizeof(__uint32_t));
if (pbe_v1->type_b != uprobe1_type)
continue;
}
if (probe_type == uprobe1_type)
{
if (pbe_v1->name == 0) // No name possibly means we have a .so with a relocation
return;
semaphore = 0;
probe_name = (char*)((char*)pdata->d_buf + pbe_v1->name - (char*)probe_scn_addr);
provider_name = ""; // unknown
pc = pbe_v1->arg;
arg_count = 0;
probe_scn_offset += sizeof (stap_sdt_probe_entry_v1);
}
else if (probe_type == uprobe2_type)
{
if (pbe_v2->name == 0) // No name possibly means we have a .so with a relocation
return;
semaphore = pbe_v2->semaphore;
probe_name = (char*)((char*)pdata->d_buf + pbe_v2->name - (char*)probe_scn_addr);
provider_name = (char*)((char*)pdata->d_buf + pbe_v2->provider - (char*)probe_scn_addr);
arg_count = pbe_v2->arg_count;
pc = pbe_v2->pc;
if (pbe_v2->arg_string)
arg_string = (char*)((char*)pdata->d_buf + pbe_v2->arg_string - (char*)probe_scn_addr);
// skip over pbe_v2, probe_name text and provider text
probe_scn_offset = ((long)(pbe_v2->name) - (long)(probe_scn_addr)) + probe_name.length();
probe_scn_offset += sizeof (__uint32_t) - probe_scn_offset % sizeof (__uint32_t);
}
if (sess.verbose > 4)
clog << _("saw .probes ") << probe_name << (provider_name != "" ? _(" (provider ")+provider_name+") " : "")
<< "@0x" << hex << pc << dec << endl;
dw.mod_info->marks.insert(make_pair(provider_name, probe_name));
if (dw.function_name_matches_pattern (probe_name, pp_mark)
&& ((pp_provider == "") || dw.function_name_matches_pattern (provider_name, pp_provider)))
handle_probe_entry ();
}
}
void
sdt_query::record_semaphore (vector<derived_probe *> & results, unsigned start)
{
for (unsigned i=0; i<2; i++) {
// prefer with-provider symbol; look without provider prefix for backward compatibility only
string semaphore = (i==0 ? (provider_name+"_") : "") + probe_name + "_semaphore";
// XXX: multiple addresses?
if (sess.verbose > 2)
clog << _F("looking for semaphore symbol %s ", semaphore.c_str());
Dwarf_Addr addr;
if (this->semaphore)
addr = this->semaphore;
else
addr = lookup_symbol_address(dw.module, semaphore.c_str());
if (addr)
{
if (dwfl_module_relocations (dw.module) > 0)
dwfl_module_relocate_address (dw.module, &addr);
// XXX: relocation basis?
// Dyninst needs the *file*-based offset for semaphores,
// so subtract the difference in load addresses between .text and .probes
if (dw.sess.runtime_usermode_p())
addr -= semaphore_load_offset;
for (unsigned i = start; i < results.size(); ++i)
results[i]->sdt_semaphore_addr = addr;
if (sess.verbose > 2)
clog << _(", found at 0x") << hex << addr << dec << endl;
return;
}
else
if (sess.verbose > 2)
clog << _(", not found") << endl;
}
}
probe*
sdt_query::convert_location ()
{
interned_string module = dw.module_name;
if (has_process)
module = path_remove_sysroot(sess, module);
if (build_id_val != "")
module = build_id_val; // prefer this one
probe_point* specific_loc = new probe_point(*base_loc);
specific_loc->well_formed = true;
vector<probe_point::component*> derived_comps;
for (auto it = specific_loc->components.begin();
it != specific_loc->components.end(); ++it)
if ((*it)->functor == TOK_PROCESS)
{
// replace the possibly incomplete path to process
*it = new probe_point::component(TOK_PROCESS,
new literal_string(has_library ? path : module));
// copy the process name
derived_comps.push_back(*it);
}
else if ((*it)->functor == TOK_LIBRARY)
{
// copy the library name for process probes
derived_comps.push_back(*it);
}
else if ((*it)->functor == TOK_PROVIDER)
{
// replace the possibly wildcarded arg with the specific provider name
*it = new probe_point::component(TOK_PROVIDER,
new literal_string(provider_name));
}
else if ((*it)->functor == TOK_MARK)
{
// replace the possibly wildcarded arg with the specific marker name
*it = new probe_point::component(TOK_MARK,
new literal_string(probe_name));
if (sess.verbose > 3)
switch (probe_type)
{
case uprobe1_type:
clog << _("probe_type == uprobe1, use statement addr: 0x")
<< hex << pc << dec << endl;
break;
case uprobe2_type:
clog << _("probe_type == uprobe2, use statement addr: 0x")
<< hex << pc << dec << endl;
break;
case uprobe3_type:
clog << _("probe_type == uprobe3, use statement addr: 0x")
<< hex << pc << dec << endl;
break;
default:
clog << _F("probe_type == use_uprobe_no_dwarf, use label name: _stapprobe1_%s",
pp_mark.to_string().c_str()) << endl;
}
switch (probe_type)
{
case uprobe1_type:
case uprobe2_type:
case uprobe3_type:
// process("executable").statement(probe_arg)
derived_comps.push_back
(new probe_point::component(TOK_STATEMENT,
new literal_number(pc, true)));
break;
default: // deprecated
// process("executable").function("*").label("_stapprobe1_MARK_NAME")
derived_comps.push_back
(new probe_point::component(TOK_FUNCTION,
new literal_string(string("*"))));
derived_comps.push_back
(new probe_point::component(TOK_LABEL,
new literal_string(string("_stapprobe1_") + (string)pp_mark)));
break;
}
}
probe_point* derived_loc = new probe_point(*specific_loc);
derived_loc->components = derived_comps;
return new probe (new probe (base_probe, specific_loc), derived_loc);
}
void
sdt_query::query_library (const char *library)
{
visited_libraries.insert(library);
if (query_one_library (library, dw, user_lib, base_probe, base_loc, results))
resolved_library = true;
}
string
suggest_marks(systemtap_session& sess,
const set<string>& modules,
const string& mark,
const string& provider)
{
if (mark.empty() || modules.empty() || sess.module_cache == NULL || sess.suppress_costly_diagnostics)
return "";
// PR18577: There isn't any point in generating a suggestion list if
// we're not going to display it.
if ((sess.dump_mode == systemtap_session::dump_matched_probes
|| sess.dump_mode == systemtap_session::dump_matched_probes_vars)
&& sess.verbose < 2)
return "";
set<string> marks;
const auto &cache = sess.module_cache->cache;
bool dash_suggestions = (mark.find("-") != string::npos);
for (auto itmod = modules.begin();
itmod != modules.end(); ++itmod)
{
auto itcache = cache.find(*itmod);
if (itcache != cache.end())
{
for (auto itmarks = itcache->second->marks.cbegin();
itmarks != itcache->second->marks.cend(); ++itmarks)
{
if (provider.empty()
// simulating dw.function_name_matches_pattern()
|| (fnmatch(provider.c_str(), itmarks->first.c_str(), 0) == 0))
{
string marksug = itmarks->second;
if (dash_suggestions)
{
size_t pos = 0;
while (1) // there may be more than one
{
size_t i = marksug.find("__", pos);
if (i == string::npos) break;
marksug.replace (i, 2, "-");
pos = i+1; // resume searching after the inserted -
}
}
marks.insert(marksug);
}
}
}
}
if (sess.verbose > 2)
{
clog << "suggesting " << marks.size() << " marks "
<< "from modules:" << endl;
for (auto itmod = modules.begin();
itmod != modules.end(); ++itmod)
clog << *itmod << endl;
}
if (marks.empty())
return "";
return levenshtein_suggest(mark, marks, 5); // print top 5 marks only
}
string
suggest_plt_functions(systemtap_session& sess,
const set<string>& modules,
const string& func)
{
if (func.empty() || modules.empty() || sess.module_cache == NULL || sess.suppress_costly_diagnostics)
return "";
// PR18577: There isn't any point in generating a suggestion list if
// we're not going to display it.
if ((sess.dump_mode == systemtap_session::dump_matched_probes
|| sess.dump_mode == systemtap_session::dump_matched_probes_vars)
&& sess.verbose < 2)
return "";
set<interned_string> funcs;
const auto &cache = sess.module_cache->cache;
for (auto itmod = modules.begin();
itmod != modules.end(); ++itmod)
{
auto itcache = cache.find(*itmod);
if (itcache != cache.end())
funcs.insert(itcache->second->plt_funcs.begin(),
itcache->second->plt_funcs.end());
}
if (sess.verbose > 2)
{
clog << "suggesting " << funcs.size() << " plt functions "
<< "from modules:" << endl;
for (auto itmod = modules.begin();
itmod != modules.end(); ++itmod)
clog << *itmod << endl;
}
if (funcs.empty())
return "";
return levenshtein_suggest(func, funcs, 5); // print top 5 funcs only
}
string
suggest_dwarf_functions(systemtap_session& sess,
const set<string>& modules,
string func)
{
// Trim any @ component
size_t pos = func.find('@');
if (pos != string::npos)
func.erase(pos);
if (func.empty() || modules.empty() || sess.module_cache == NULL || sess.suppress_costly_diagnostics)
return "";
// PR18577: There isn't any point in generating a suggestion list if
// we're not going to display it.
if ((sess.dump_mode == systemtap_session::dump_matched_probes
|| sess.dump_mode == systemtap_session::dump_matched_probes_vars)
&& sess.verbose < 2)
return "";
// We must first aggregate all the functions from the cache
set<interned_string> funcs;
const auto &cache = sess.module_cache->cache;
for (auto itmod = modules.begin();
itmod != modules.end(); ++itmod)
{
module_info *module;
// retrieve module_info from cache
auto itcache = cache.find(*itmod);
if (itcache != cache.end())
module = itcache->second;
else // module not found
continue;
// add inlines
funcs.insert(module->inlined_funcs.begin(),
module->inlined_funcs.end());
// add all function symbols in cache
if (module->symtab_status != info_present || module->sym_table == NULL)
continue;
const auto& modfuncs = module->sym_table->map_by_name;
for (auto itfuncs = modfuncs.begin();
itfuncs != modfuncs.end(); ++itfuncs)
funcs.insert(itfuncs->first);
}
if (sess.verbose > 2)
{
clog << "suggesting " << funcs.size() << " dwarf functions "
<< "from modules:" << endl;
for (auto itmod = modules.begin();
itmod != modules.end(); ++itmod)
clog << *itmod << endl;
}
if (funcs.empty())
return "";
return levenshtein_suggest(func, funcs, 5); // print top 5 funcs only
}
// Use a glob pattern to find executables or shared libraries
static set<string>
glob_executable(const string& pattern)
{
glob_t the_blob;
set<string> globs;
int rc = glob (pattern.c_str(), 0, NULL, & the_blob);
if (rc)
throw SEMANTIC_ERROR (_F("glob %s error (%d)", pattern.c_str(), rc));
for (unsigned i = 0; i < the_blob.gl_pathc; ++i)
{
const char* globbed = the_blob.gl_pathv[i];
struct stat st;
if (stat (globbed, &st) == 0
&& S_ISREG (st.st_mode)) // see find_executable()
{
// Need to call resolve_path here, in order to path-expand
// patterns like process("stap*"). Otherwise it may go through
// to the next round of expansion as ("stap"), leading to a $PATH
// search that's not consistent with the glob search already done.
string canononicalized = resolve_path (globbed);
// The canonical names can result in duplication, for example
// having followed symlinks that are common with shared libraries,
// so we use a set for unique results.
globs.insert(canononicalized);
}
}
globfree (& the_blob);
return globs;
}
static bool
resolve_library_by_path(base_query & q,
set<string> const & visited_libraries,
probe * base,
probe_point * location,
literal_map_t const & parameters,
vector<derived_probe *> & finished_results)
{
size_t results_pre = finished_results.size();
systemtap_session & sess = q.sess;
dwflpp & dw = q.dw;
interned_string lib;
if (!location->from_globby_comp(TOK_LIBRARY) && q.has_library
&& !visited_libraries.empty()
&& q.get_string_param(parameters, TOK_LIBRARY, lib))
{
// The library didn't fit any DT_NEEDED libraries. As a last effort,
// let's try to look for the library directly.
if (contains_glob_chars (lib))
{
// Evaluate glob here, and call derive_probes recursively with each match.
const auto& globs = glob_executable (lib);
for (auto it = globs.begin(); it != globs.end(); ++it)
{
assert_no_interrupts();
const string& globbed = *it;
if (sess.verbose > 1)
clog << _F("Expanded library(\"%s\") to library(\"%s\")",
lib.to_string().c_str(), globbed.c_str()) << endl;
probe *new_base = build_library_probe(dw, globbed,
base, location);
// We override "optional = true" here, as if the
// wildcarded probe point was given a "?" suffix.
// This is because wildcard probes will be expected
// by users to apply only to some subset of the
// matching binaries, in the sense of "any", rather
// than "all", sort of similarly how
// module("*").function("...") patterns work.
derive_probes (sess, new_base, finished_results,
true /* NB: not location->optional */ );
}
}
else
{
string resolved_lib = find_executable(lib, sess.sysroot, sess.sysenv,
"LD_LIBRARY_PATH");
if (resolved_lib.find('/') != string::npos)
{
probe *new_base = build_library_probe(dw, resolved_lib,
base, location);
derive_probes(sess, new_base, finished_results);
if (lib.find('/') == string::npos)
sess.print_warning(_F("'%s' is not a needed library of '%s'. "
"Specify the full path to squelch this warning.",
resolved_lib.c_str(), dw.module_name.c_str()));
}
else
{
// Otherwise, let's suggest from the DT_NEEDED libraries
string sugs = levenshtein_suggest(lib, visited_libraries, 5);
if (!sugs.empty())
throw SEMANTIC_ERROR (_NF("no match (similar library: %s)",
"no match (similar libraries: %s)",
sugs.find(',') == string::npos,
sugs.c_str()));
}
}
}
return results_pre != finished_results.size();
}
static void
handle_module_token(systemtap_session &sess, interned_string &module_token_val)
{
// Do we have a fully resolved path to the module?
if (!is_fully_resolved(module_token_val, sess.sysroot, sess.sysenv))
{
// If the path isn't fully resolved, it might be a in-tree
// module name or a relative path. If it is a relative path,
// convert it to a full path.
if (module_token_val.find('/') != string::npos)
{
string module_token_val2 = find_executable(module_token_val,
sess.sysroot,
sess.sysenv);
module_token_val = module_token_val2;
}
// If we're here, then it's an in-tree module. Replace any
// dashes with underscores.
else
{
size_t dash_pos = 0;
// copy out for replace operations
string module_token_val2 = module_token_val;
while ((dash_pos = module_token_val2.find('-')) != string::npos)
module_token_val2.replace(int(dash_pos), 1, "_");
module_token_val = module_token_val2;
}
}
}
void
dwarf_builder::build(systemtap_session & sess,
probe * base,
probe_point * location,
literal_map_t const & parameters,
vector<derived_probe *> & finished_results)
{
// NB: the kernel/user dwlfpp objects are long-lived.
// XXX: but they should be per-session, as this builder object
// may be reused if we try to cross-instrument multiple targets.
dwflpp* dw = 0;
literal_map_t filled_parameters = parameters;
interned_string module_name;
int64_t proc_pid;
if (has_null_param (parameters, TOK_KERNEL))
{
bool debuginfo_needed = true;
/* PR26660 kernel.statement(HEX).absolute does not require kernel
* debuginfo */
bool has_statement_num = has_param (parameters, TOK_STATEMENT);
if (has_statement_num)
{
if (has_param (parameters, TOK_ABSOLUTE))
debuginfo_needed = false;
}
//cerr << "debuginfo needed? " << debuginfo_needed << endl;
dw = get_kern_dw(sess, "kernel", debuginfo_needed);
}
else if (get_param (parameters, TOK_MODULE, module_name))
{
handle_module_token(sess, module_name);
filled_parameters[TOK_MODULE] = new literal_string(module_name);
// NB: glob patterns get expanded later, during the offline
// elfutils module listing.
dw = get_kern_dw(sess, module_name);
}
else if (has_param(filled_parameters, TOK_PROCESS))
{
// NB: module_name is not yet set!
if(has_null_param(filled_parameters, TOK_PROCESS))
{
if (!location->auto_path.empty())
{
if (location->components[0]->functor == TOK_PROCESS &&
location->components[0]->arg == 0)
{
// PATH expansion of process component without argument.
// The filename without the .stp extension is used.
string full_path = location->auto_path;
string::size_type start = full_path.find("PATH/") + 4;
string::size_type end = full_path.rfind(".stp");
module_name = full_path.substr(start, end - start);
location->components[0]->arg = new literal_string(module_name);
filled_parameters[TOK_PROCESS] = new literal_string(module_name);
}
}
else
{
string file;
try
{
file = sess.cmd_file();
}
catch (const semantic_error& e)
{
if(sess.target_pid)
throw SEMANTIC_ERROR(_("invalid -x pid for unspecified process"
" probe [man stapprobes]"), NULL, NULL, &e);
else
throw SEMANTIC_ERROR(_("invalid -c command for unspecified process"
" probe [man stapprobes]"), NULL, NULL, &e);
}
if(file.empty())
throw SEMANTIC_ERROR(_("unspecified process probe is invalid without"
" a -c COMMAND or -x PID [man stapprobes]"));
module_name = sess.sysroot + file;
filled_parameters[TOK_PROCESS] = new literal_string(module_name);// this needs to be used in place of the blank map
// in the case of TOK_MARK we need to modify locations as well // XXX why?
if(location->components[0]->functor==TOK_PROCESS &&
location->components[0]->arg == 0)
{
if (sess.target_pid)
location->components[0]->arg = new literal_number(sess.target_pid);
else
location->components[0]->arg = new literal_string(module_name);
}
}
}
// NB: must specifically handle the classical ("string") form here, to make sure
// we get the module_name out.
else if (get_param (parameters, TOK_PROCESS, module_name))
{
if (!location->auto_path.empty())
{
if (!module_name.empty() && module_name[0] != '/')
{
// prefix argument with file location from PATH directory
string full_path = location->auto_path;
string::size_type start = full_path.find("PATH/") + 4;
string::size_type end = full_path.rfind("/");
string arg = module_name;
module_name = full_path.substr(start, end-start+1) + arg;
location->components[0]->arg = new literal_string(module_name);
filled_parameters[TOK_PROCESS] = new literal_string(module_name);
}
}
else
{
filled_parameters[TOK_PROCESS] = new literal_string(module_name);
}
}
else if (get_param (parameters, TOK_PROCESS, proc_pid))
{
// check that the pid given corresponds to a running process
string pid_err_msg;
if (!is_valid_pid(proc_pid, pid_err_msg))
throw SEMANTIC_ERROR(pid_err_msg);
string pid_path = string("/proc/") + lex_cast(proc_pid) + "/exe";
module_name = sess.sysroot + pid_path;
// in the case of TOK_MARK we need to modify locations as well // XXX why?
if(location->components[0]->functor==TOK_PROCESS &&
location->components[0]->arg == 0)
location->components[0]->arg = new literal_number(sess.target_pid);
}
// PR6456 process("/bin/*") glob handling
if (contains_glob_chars (module_name))
{
// Expand glob via rewriting the probe-point process("....")
// parameter, asserted to be the first one.
assert (location->components.size() > 0);
assert (location->components[0]->functor == TOK_PROCESS);
assert (location->components[0]->arg);
literal_string* lit = dynamic_cast<literal_string*>(location->components[0]->arg);
assert (lit);
// Evaluate glob here, and call derive_probes recursively with each match.
const auto& globs = glob_executable (sess.sysroot
+ string(module_name));
unsigned results_pre = finished_results.size();
for (auto it = globs.begin(); it != globs.end(); ++it)
{
assert_no_interrupts();
const string& globbed = *it;
// synthesize a new probe_point, with the glob-expanded string
probe_point *pp = new probe_point (*location);
// PR13338: quote results to prevent recursion
string eglobbed = escape_glob_chars (globbed);
if (sess.verbose > 1)
clog << _F("Expanded process(\"%s\") to process(\"%s\")",
module_name.to_string().c_str(), eglobbed.c_str()) << endl;
string eglobbed_tgt = path_remove_sysroot(sess, eglobbed);
probe_point::component* ppc
= new probe_point::component (TOK_PROCESS,
new literal_string (eglobbed_tgt),
true /* from_glob */ );
ppc->tok = location->components[0]->tok; // overwrite [0] slot, pattern matched above
pp->components[0] = ppc;
probe* new_probe = new probe (base, pp);
// We override "optional = true" here, as if the
// wildcarded probe point was given a "?" suffix.
// This is because wildcard probes will be expected
// by users to apply only to some subset of the
// matching binaries, in the sense of "any", rather
// than "all", sort of similarly how
// module("*").function("...") patterns work.
derive_probes (sess, new_probe, finished_results,
true /* NB: not location->optional */ );
}
unsigned results_post = finished_results.size();
// Did we fail to find a function/plt/mark by name? Let's suggest
// something!
interned_string func;
if (results_pre == results_post
&& get_param(filled_parameters, TOK_FUNCTION, func)
&& !func.empty())
{
string sugs = suggest_dwarf_functions(sess, modules_seen, func);
modules_seen.clear();
if (!sugs.empty())
throw SEMANTIC_ERROR (_NF("no match (similar function: %s)",
"no match (similar functions: %s)",
sugs.find(',') == string::npos,
sugs.c_str()));
}
else if (results_pre == results_post
&& get_param(filled_parameters, TOK_PLT, func)
&& !func.empty())
{
string sugs = suggest_plt_functions(sess, modules_seen, func);
modules_seen.clear();
if (!sugs.empty())
throw SEMANTIC_ERROR (_NF("no match (similar function: %s)",
"no match (similar functions: %s)",
sugs.find(',') == string::npos,
sugs.c_str()));
}
else if (results_pre == results_post
&& get_param(filled_parameters, TOK_MARK, func)
&& !func.empty())
{
interned_string provider;
get_param(filled_parameters, TOK_PROVIDER, provider);
string sugs = suggest_marks(sess, modules_seen, func, provider);
modules_seen.clear();
if (!sugs.empty())
throw SEMANTIC_ERROR (_NF("no match (similar mark: %s)",
"no match (similar marks: %s)",
sugs.find(',') == string::npos,
sugs.c_str()));
}
return; // avoid falling through
}
// PR13338: unquote glob results
module_name = unescape_glob_chars (module_name);
user_path = find_executable (module_name, sess.sysroot, sess.sysenv); // canonicalize it
// Note we don't need to pass the sysroot to
// is_fully_resolved(), since we just passed it to
// find_executable().
if (!is_fully_resolved(user_path, "", sess.sysenv))
throw SEMANTIC_ERROR(_F("cannot find executable '%s'",
user_path.to_string().c_str()));
// if the executable starts with "#!", we look for the interpreter of the script
{
ifstream script_file (user_path.to_string().c_str());
if (script_file.good ())
{
string line;
getline (script_file, line);
if (line.compare (0, 2, "#!") == 0)
{
string path = line.substr(2);
// trim white space
trim(path);
if (! path.empty())
{
// handle "#!/usr/bin/env" redirect
size_t offset = 0;
if (path.compare(0, sizeof("/bin/env")-1, "/bin/env") == 0)
{
offset = sizeof("/bin/env")-1;
}
else if (path.compare(0, sizeof("/usr/bin/env")-1, "/usr/bin/env") == 0)
{
offset = sizeof("/usr/bin/env")-1;
}
if (offset != 0)
{
size_t p3 = path.find_first_not_of(" \t", offset);
if (p3 != string::npos)
{
string env_path = path.substr(p3);
user_path = find_executable (env_path, sess.sysroot,
sess.sysenv);
}
}
else
{
user_path = find_executable (path, sess.sysroot, sess.sysenv);
}
struct stat st;
const string& new_path = user_path;
if (access (new_path.c_str(), X_OK) == 0
&& stat (new_path.c_str(), &st) == 0
&& S_ISREG (st.st_mode)) // see find_executable()
{
if (sess.verbose > 1)
clog << _F("Expanded process(\"%s\") to process(\"%s\")",
module_name.to_string().c_str(), new_path.c_str()) << endl;
assert (location->components.size() > 0);
assert (location->components[0]->functor == TOK_PROCESS);
assert (location->components[0]->arg);
literal_string* lit = dynamic_cast<literal_string*>(location->components[0]->arg);
assert (lit);
// synthesize a new probe_point, with the expanded string
probe_point *pp = new probe_point (*location);
string user_path_tgt = path_remove_sysroot(sess, new_path);
probe_point::component* ppc = new probe_point::component (TOK_PROCESS,
new literal_string (user_path_tgt));
ppc->tok = location->components[0]->tok; // overwrite [0] slot, pattern matched above
pp->components[0] = ppc;
probe* new_probe = new probe (base, pp);
derive_probes (sess, new_probe, finished_results);
script_file.close();
return;
}
}
}
}
script_file.close();
}
// If this is a library probe, then target the library module instead. We
// do this only if the library path is already fully resolved (such as
// what query_one_library() would have done for us). Otherwise, we resort
// to iterate_over_libraries.
if (get_param (parameters, TOK_LIBRARY, user_lib) && !user_lib.empty())
{
string library = find_executable (user_lib, sess.sysroot,
sess.sysenv, "LD_LIBRARY_PATH");
if (is_fully_resolved(library, "", sess.sysenv, "LD_LIBRARY_PATH"))
module_name = library;
else
module_name = user_path; // canonicalize it
}
else
module_name = user_path; // canonicalize it
// uretprobes aren't available everywhere
if (has_null_param(parameters, TOK_RETURN) && !sess.runtime_usermode_p())
{
if (kernel_supports_inode_uprobes(sess) &&
!kernel_supports_inode_uretprobes(sess))
throw SEMANTIC_ERROR
(_("process return probes not available [man error::inode-uprobes]"));
}
// There is a similar check in pass 4 (buildrun), but it is
// needed here too to make sure alternatives for optional
// (? or !) process probes are disposed and/or alternatives
// are selected.
if (!sess.runtime_usermode_p())
check_process_probe_kernel_support(sess);
// user-space target; we use one dwflpp instance per module name
// (= program or shared library)
dw = get_user_dw(sess, module_name);
}
assert(dw);
unsigned results_pre = finished_results.size();
if (sess.verbose > 3)
clog << _F("dwarf_builder::build for %s",
module_name.to_string().c_str()) << endl;
interned_string dummy_mark_name; // NB: PR10245: dummy value, need not substitute - => __
if (get_param(parameters, TOK_MARK, dummy_mark_name))
{
sdt_query sdtq(base, location, *dw, filled_parameters, finished_results, user_lib);
dw->iterate_over_modules<base_query>(&query_module, &sdtq);
// We need to update modules_seen with the modules we've visited
modules_seen.insert(sdtq.visited_modules.begin(),
sdtq.visited_modules.end());
if (results_pre == finished_results.size()
&& sdtq.has_library && !sdtq.resolved_library
&& resolve_library_by_path (sdtq, sdtq.visited_libraries,
base, location, filled_parameters,
finished_results))
return;
// Did we fail to find a mark?
if (results_pre == finished_results.size()
&& !location->from_globby_comp(TOK_MARK))
{
interned_string provider;
(void) get_param(filled_parameters, TOK_PROVIDER, provider);
string sugs = suggest_marks(sess, modules_seen, dummy_mark_name, provider);
modules_seen.clear();
if (!sugs.empty())
throw SEMANTIC_ERROR (_NF("no match (similar mark: %s)",
"no match (similar marks: %s)",
sugs.find(',') == string::npos,
sugs.c_str()));
}
return;
}
dwarf_query q(base, location, *dw, filled_parameters, finished_results, user_path, user_lib);
// XXX: kernel.statement.absolute is a special case that requires no
// dwfl processing. This code should be in a separate builder.
if (q.has_kernel && q.has_absolute)
{
// assert guru mode for absolute probes
if (! q.base_probe->privileged)
{
throw SEMANTIC_ERROR (_("absolute statement probe in unprivileged script; need stap -g"),
q.base_probe->tok);
}
// For kernel.statement(NUM).absolute probe points, we bypass
// all the debuginfo stuff: We just wire up a
// dwarf_derived_probe right here and now.
dwarf_derived_probe* p =
new dwarf_derived_probe ("", "", 0, "kernel", "",
q.statement_num_val, q.statement_num_val,
q, 0);
finished_results.push_back (p);
sess.unwindsym_modules.insert ("kernel");
return;
}
dw->iterate_over_modules<base_query>(&query_module, &q);
// We need to update modules_seen with the modules we've visited
modules_seen.insert(q.visited_modules.begin(),
q.visited_modules.end());
// PR11553 special processing: .return probes requested, but
// some inlined function instances matched.
unsigned i_n_r = q.inlined_non_returnable.size();
unsigned results_post = finished_results.size();
if (i_n_r > 0)
{
if ((results_pre == results_post) && (! sess.suppress_warnings)) // no matches; issue warning
{
string quicklist;
for (auto it = q.inlined_non_returnable.begin();
it != q.inlined_non_returnable.end();
it++)
{
quicklist += " " + (string)(*it);
if (quicklist.size() > 80) // heuristic, don't make an overlong report line
{
quicklist += " ...";
break;
}
}
sess.print_warning (_NF("cannot probe .return of %u inlined function %s",
"cannot probe .return of %u inlined functions %s",
quicklist.size(), i_n_r, quicklist.c_str()));
// There will be also a "no matches" semantic error generated.
}
if (sess.verbose > 1)
clog << _NF("skipped .return probe of %u inlined function",
"skipped .return probe of %u inlined functions", i_n_r, i_n_r) << endl;
if ((sess.verbose > 3) || (sess.verbose > 2 && results_pre == results_post)) // issue details with high verbosity
{
for (auto it = q.inlined_non_returnable.begin();
it != q.inlined_non_returnable.end();
it++)
clog << (*it) << " ";
clog << endl;
}
} // i_n_r > 0
if (results_pre == finished_results.size()
&& q.has_library && !q.resolved_library
&& resolve_library_by_path (q, q.visited_libraries,
base, location, filled_parameters,
finished_results))
return;
// If we just failed to resolve a function/plt by name, we can suggest
// something. We only suggest things for probe points that were not
// synthesized from a glob, i.e. only for 'real' probes. This is also
// required because modules_seen needs to accumulate across recursive
// calls for process(glob)[.library(glob)] probes.
interned_string func;
if (results_pre == results_post && !location->from_globby_comp(TOK_FUNCTION)
&& get_param(filled_parameters, TOK_FUNCTION, func)
&& !func.empty())
{
string sugs = suggest_dwarf_functions(sess, modules_seen, func);
modules_seen.clear();
if (!sugs.empty())
throw SEMANTIC_ERROR (_NF("no match (similar function: %s)",
"no match (similar functions: %s)",
sugs.find(',') == string::npos,
sugs.c_str()));
}
else if (results_pre == results_post && !location->from_globby_comp(TOK_PLT)
&& get_param(filled_parameters, TOK_PLT, func)
&& !func.empty())
{
string sugs = suggest_plt_functions(sess, modules_seen, func);
modules_seen.clear();
if (!sugs.empty())
throw SEMANTIC_ERROR (_NF("no match (similar function: %s)",
"no match (similar functions: %s)",
sugs.find(',') == string::npos,
sugs.c_str()));
}
else if (results_pre != results_post)
// Something was derived so we won't need to suggest something
modules_seen.clear();
}
symbol_table::~symbol_table()
{
delete_map(map_by_addr);
}
void
symbol_table::add_symbol(interned_string name, bool weak, bool descriptor,
Dwarf_Addr addr, Dwarf_Addr entrypc)
{
/* Does the target architecture have function descriptors?
Then we want to filter them out. When seeing a symbol with a name
starting with '.' we assume it is a regular function pointer and
not a pointer to a function descriptor. Note that this might create
duplicates if we also found the function descriptor symbol itself.
dwfl_module_getsym_info () will have resolved the actual function
address for us. But we won't know if we see either or both. */
if (opd_section != SHN_UNDEF)
{
// Map ".sys_foo" to "sys_foo".
if (name[0] == '.')
name.remove_prefix(1);
// Make sure we don't create duplicate func_info's
auto er = map_by_addr.equal_range(addr);
for (auto it = er.first; it != er.second; ++it)
if (it->second->name == name)
return;
}
func_info *fi = new func_info();
fi->entrypc = entrypc;
fi->addr = addr;
fi->name = name;
fi->weak = weak;
fi->descriptor = descriptor;
map_by_name.insert(make_pair(fi->name, fi));
map_by_addr.insert(make_pair(addr, fi));
}
void
symbol_table::prepare_section_rejection(Dwfl_Module *mod __attribute__ ((unused)))
{
Dwarf_Addr bias;
Elf* elf = (dwarf_getelf (dwfl_module_getdwarf (mod, &bias))
?: dwfl_module_getelf (mod, &bias));
GElf_Ehdr ehdr_mem;
GElf_Ehdr* em = gelf_getehdr (elf, &ehdr_mem);
if (em == NULL) throw SEMANTIC_ERROR (_("Couldn't get elf header"));
/* Only old ELFv1 PPC64 ABI have function descriptors. */
opd_section = SHN_UNDEF;
if (em->e_machine != EM_PPC64 || (em->e_flags & EF_PPC64_ABI) == 2)
return;
/*
* The .opd section contains function descriptors that can look
* just like function entry points. For example, there's a function
* descriptor called "do_exit" that links to the entry point ".do_exit".
* Reject all symbols in .opd.
*/
Elf_Scn* scn = 0;
size_t shstrndx;
if (!elf)
return;
if (elf_getshdrstrndx (elf, &shstrndx) != 0)
return;
while ((scn = elf_nextscn(elf, scn)) != NULL)
{
GElf_Shdr shdr_mem;
GElf_Shdr *shdr = gelf_getshdr(scn, &shdr_mem);
if (!shdr)
continue;
const char *name = elf_strptr(elf, shstrndx, shdr->sh_name);
if (!strcmp(name, ".opd"))
{
opd_section = elf_ndxscn(scn);
return;
}
}
}
bool
symbol_table::reject_section(GElf_Word section)
{
if (section == SHN_UNDEF || section == opd_section)
return true;
return false;
}
enum info_status
symbol_table::get_from_elf()
{
Dwfl_Module *mod = mod_info->mod;
int syments = dwfl_module_getsymtab(mod);
assert(syments);
prepare_section_rejection(mod);
for (int i = 1; i < syments; ++i)
{
GElf_Sym sym;
GElf_Word section;
GElf_Addr addr;
bool reject;
/* Note that dwfl_module_getsym does adjust the sym.st_value but doesn't
try to resolve it to a function address. dwfl_module_getsym_info leaves
the st_value in tact (no adjustment applied) and returns the fully
resolved address separately. In that case we can simply reject the
symbol if it is SHN_UNDEF and don't need to call reject_section which
does extra checks to see whether the address fall in an architecture
specific descriptor table (which will never be the case when using the
new dwfl_module_getsym_info). dwfl_module_getsym will only provide us
with the (adjusted) st_value of the symbol, which might point into a
function descriptor table. So in that case we still have to call
reject_section. */
#if _ELFUTILS_PREREQ (0, 158)
const char* n = dwfl_module_getsym_info (mod, i, &sym, &addr, §ion,
NULL, NULL);
reject = section == SHN_UNDEF;
#else
const char* n = dwfl_module_getsym (mod, i, &sym, §ion);
addr = sym.st_value;
reject = reject_section(section);
#endif
if (! n)
continue;
interned_string name = n;
Dwarf_Addr entrypc = addr;
if (GELF_ST_TYPE(sym.st_info) == STT_FUNC)
add_symbol(name, (GELF_ST_BIND(sym.st_info) == STB_WEAK),
reject, addr, entrypc);
if (GELF_ST_TYPE(sym.st_info) == STT_OBJECT
&& GELF_ST_BIND(sym.st_info) == STB_GLOBAL)
globals[name] = addr;
if (GELF_ST_TYPE(sym.st_info) == STT_OBJECT
&& GELF_ST_BIND(sym.st_info) == STB_LOCAL)
locals[name] = addr;
}
return info_present;
}
func_info *
symbol_table::get_func_containing_address(Dwarf_Addr addr)
{
auto iter = map_by_addr.upper_bound(addr);
if (iter == map_by_addr.begin())
return NULL;
else
return (--iter)->second;
}
func_info *
symbol_table::get_first_func()
{
auto iter = map_by_addr.begin();
return (iter)->second;
}
/* Note this function filters out any symbols that are "rejected" because
they are "descriptor" function symbols or SHN_UNDEF symbols. */
set <func_info*>
symbol_table::lookup_symbol(interned_string name)
{
set<func_info*> fis;
auto ret = map_by_name.equal_range(name);
for (auto it = ret.first; it != ret.second; ++it)
if (! it->second->descriptor)
fis.insert(it->second);
return fis;
}
/* Filters out the same "descriptor" or SHN_UNDEF symbols as
symbol_table::lookup_symbol. */
set <Dwarf_Addr>
symbol_table::lookup_symbol_address(interned_string name)
{
set <Dwarf_Addr> addrs;
set <func_info*> fis = lookup_symbol(name);
for (auto it=fis.begin(); it!=fis.end(); ++it)
addrs.insert((*it)->addr);
return addrs;
}
// This is the kernel symbol table. The kernel macro cond_syscall creates
// a weak symbol for each system call and maps it to sys_ni_syscall.
// For system calls not implemented elsewhere, this weak symbol shows up
// in the kernel symbol table. Following the precedent of dwarfful stap,
// we refuse to consider such symbols. Here we delete them from our
// symbol table.
// TODO: Consider generalizing this and/or making it part of blocklist
// processing.
void
symbol_table::purge_syscall_stubs()
{
set<Dwarf_Addr> addrs = lookup_symbol_address("sys_ni_syscall");
if (addrs.empty())
return;
/* Highly unlikely that multiple symbols named "sys_ni_syscall" may exist */
if (addrs.size() > 1)
cerr << _("Multiple 'sys_ni_syscall' symbols found.\n");
Dwarf_Addr stub_addr = * addrs.begin();
auto purge_range = map_by_addr.equal_range(stub_addr);
for (auto iter = purge_range.first;
iter != purge_range.second;
)
{
func_info *fi = iter->second;
if (fi->weak && fi->name != "sys_ni_syscall")
{
map_by_name.erase(fi->name);
map_by_addr.erase(iter++);
delete fi;
}
else
iter++;
}
}
void
module_info::get_symtab()
{
if (symtab_status != info_unknown)
return;
sym_table = new symbol_table(this);
if (!elf_path.empty())
{
symtab_status = sym_table->get_from_elf();
}
else
{
assert(name == TOK_KERNEL);
symtab_status = info_absent;
cerr << _("Error: Cannot find vmlinux.") << endl;;
}
if (symtab_status == info_absent)
{
delete sym_table;
sym_table = NULL;
return;
}
if (name == TOK_KERNEL)
sym_table->purge_syscall_stubs();
}
// update_symtab reconciles data between the elf symbol table and the dwarf
// function enumeration. It updates the symbol table entries with the dwarf
// die that describes the function, which also signals to query_module_symtab
// that a statement probe isn't needed. In return, it also adds aliases to the
// function table for names that share the same addr/die.
void
module_info::update_symtab(cu_function_cache_t *funcs)
{
if (!sym_table)
return;
cu_function_cache_t new_funcs;
for (auto func = funcs->begin();
func != funcs->end(); func++)
{
// optimization: inlines will never be in the symbol table
if (dwarf_func_inline(&func->second) != 0)
{
inlined_funcs.insert(func->first);
continue;
}
// We need to make additional efforts to match mangled elf names to dwarf
// too. DW_AT_linkage_name (or w/ MIPS) can help, but that's sometimes
// missing, so we may also need to try matching by address. See also the
// notes about _Z in dwflpp::iterate_over_functions().
interned_string name = dwarf_linkage_name(&func->second) ?: func->first;
set<func_info*> fis = sym_table->lookup_symbol(name);
if (fis.empty())
continue;
for (auto fi = fis.begin(); fi!=fis.end(); ++fi)
{
// iterate over all functions at the same address
auto er = sym_table->map_by_addr.equal_range((*fi)->addr);
for (auto it = er.first; it != er.second; ++it)
{
// update this function with the dwarf die
it->second->die = func->second;
// if this function is a new alias, then
// save it to merge into the function cache
if (it->second != *fi)
new_funcs.insert(make_pair(it->second->name, it->second->die));
}
}
}
// add all discovered aliases back into the function cache
// NB: this won't replace any names that dwarf may have already found
funcs->insert(new_funcs.begin(), new_funcs.end());
}
module_info::~module_info()
{
if (sym_table)
delete sym_table;
}
// ------------------------------------------------------------------------
// user-space probes
// ------------------------------------------------------------------------
struct uprobe_derived_probe_group: public generic_dpg<uprobe_derived_probe>
{
private:
string make_pbm_key (uprobe_derived_probe* p) {
return (string)p->path + "|" + (string)p->module + "|" + (string)p->section + "|" + (string)lex_cast(p->pid);
}
void emit_module_maxuprobes (systemtap_session& s);
// Using our own utrace-based uprobes
void emit_module_utrace_decls (systemtap_session& s);
void emit_module_utrace_init (systemtap_session& s);
void emit_module_utrace_exit (systemtap_session& s);
// Using the upstream inode-based uprobes
void emit_module_inode_decls (systemtap_session& s);
void emit_module_inode_init (systemtap_session& s);
void emit_module_inode_refresh (systemtap_session& s);
void emit_module_inode_exit (systemtap_session& s);
// Using the dyninst backend (via stapdyn)
void emit_module_dyninst_decls (systemtap_session& s);
void emit_module_dyninst_init (systemtap_session& s);
void emit_module_dyninst_exit (systemtap_session& s);
// Perf support
unsigned max_perf_counters;
void emit_module_perf_read_handlers (systemtap_session& s);
public:
uprobe_derived_probe_group(): max_perf_counters(0) {}
void emit_module_decls (systemtap_session& s);
void emit_module_init (systemtap_session& s);
void emit_module_refresh (systemtap_session& s);
void emit_module_exit (systemtap_session& s);
// on-the-fly only supported for inode-uprobes
bool otf_supported (systemtap_session& s)
{ return !s.runtime_usermode_p()
&& kernel_supports_inode_uprobes(s); }
// workqueue manipulation is safe in uprobes
bool otf_safe_context (systemtap_session& s)
{ return otf_supported(s); }
friend bool sort_for_bpf(systemtap_session& s,
uprobe_derived_probe_group *upg,
sort_for_bpf_probe_arg_vector &v);
};
void
uprobe_derived_probe::join_group (systemtap_session& s)
{
if (! s.uprobe_derived_probes)
s.uprobe_derived_probes = new uprobe_derived_probe_group ();
s.uprobe_derived_probes->enroll (this);
this->group = s.uprobe_derived_probes;
if (s.runtime_usermode_p())
enable_dynprobes(s);
else
enable_task_finder(s);
// Ask buildrun.cxx to build extra module if needed, and
// signal staprun to load that module. If we're using the builtin
// inode-uprobes, we still need to know that it is required.
s.need_uprobes = true;
}
void
uprobe_derived_probe::getargs(std::list<std::string> &arg_set) const
{
dwarf_derived_probe::getargs(arg_set);
arg_set.insert(arg_set.end(), args.begin(), args.end());
}
void
uprobe_derived_probe::saveargs(int nargs)
{
for (int i = 1; i <= nargs; i++)
args.push_back("$arg" + lex_cast (i) + ":long");
}
void
uprobe_derived_probe::emit_privilege_assertion (translator_output* o)
{
// These probes are allowed for unprivileged users, but only in the
// context of processes which they own.
emit_process_owner_assertion (o);
}
void
uprobe_derived_probe::emit_perf_read_handler (systemtap_session &s,
unsigned idx)
{
if (perf_counter_refs.size())
{
unsigned ref_idx = 0;
s.op->newline() << "static void stap_perf_read_handler_" << idx
<< "(long *values) {";
s.op->indent(1);
for (auto pcii = perf_counter_refs.begin();
pcii != perf_counter_refs.end();
pcii++)
{
// Find the associated perf.counter probe
unsigned i = 0;
for (auto it=s.perf_counters.begin() ;
it != s.perf_counters.end();
it++, i++)
{
if ((*it).first == (*pcii))
{
s.op->newline() << "values[" << ref_idx
<< "] = _stp_perf_read(smp_processor_id(),"
<< i << ");";
ref_idx++;
break;
}
}
}
s.op->newline() << "return;";
s.op->newline(-1) << "}";
}
}
struct uprobe_builder: public derived_probe_builder
{
uprobe_builder() {}
virtual void build(systemtap_session & sess,
probe * base,
probe_point * location,
literal_map_t const & parameters,
vector<derived_probe *> & finished_results)
{
int64_t process, address;
if (kernel_supports_inode_uprobes(sess))
throw SEMANTIC_ERROR (_("absolute process probes not available [man error::inode-uprobes]"));
bool b1 = get_param (parameters, TOK_PROCESS, process);
(void) b1;
bool b2 = get_param (parameters, TOK_STATEMENT, address);
(void) b2;
bool rr = has_null_param (parameters, TOK_RETURN);
assert (b1 && b2); // by pattern_root construction
finished_results.push_back(new uprobe_derived_probe(base, location, process, address, rr));
}
virtual string name() { return "uprobe builder"; }
};
void
uprobe_derived_probe_group::emit_module_maxuprobes (systemtap_session& s)
{
// We'll probably need at least this many:
unsigned minuprobes = probes.size();
// .. but we don't want so many that .bss is inflated (PR10507):
unsigned uprobesize = 64;
unsigned maxuprobesmem = 10*1024*1024; // 10 MB
unsigned maxuprobes = maxuprobesmem / uprobesize;
// Let's choose a value on the geometric middle. This should end up
// between minuprobes and maxuprobes. It's OK if this number turns
// out to be < minuprobes or > maxuprobes. At worst, we get a
// run-time error of one kind (too few: missed uprobe registrations)
// or another (too many: vmalloc errors at module load time).
unsigned default_maxuprobes = (unsigned)sqrt((double)minuprobes * (double)maxuprobes);
s.op->newline() << "#ifndef MAXUPROBES";
s.op->newline() << "#define MAXUPROBES " << default_maxuprobes;
s.op->newline() << "#endif";
}
void
uprobe_derived_probe_group::emit_module_perf_read_handlers (systemtap_session& s)
{
// If we're using perf counters, output the handler function(s)
// before the actual uprobe probe handler function.
for (unsigned i=0; i<probes.size(); i++)
{
uprobe_derived_probe *p = probes[i];
p->emit_perf_read_handler(s, i);
}
}
void
udpg_entryfn_prologue_declaration_callback (systemtap_session& s, void* data)
{
unsigned nvalues = (unsigned)(unsigned long)data;
if (nvalues > 0)
{
// Note that only gurus can exceed the maximum number of perf
// values used in 1 probe. Since we store the perf values on
// the stack, we can't have too many.
if (!s.guru_mode && nvalues > 16)
throw SEMANTIC_ERROR(_F("Too many simultaneous uses of perf values (%d is greater than 16)",
nvalues));
s.op->newline() << "long perf_read_values[" << nvalues << "];";
}
}
void
udpg_entryfn_prologue_pre_context_callback (systemtap_session& s, void* data)
{
unsigned nvalues = (unsigned)(unsigned long)data;
if (nvalues == 0 || s.runtime_usermode_p())
return;
if (kernel_supports_inode_uprobes (s))
{
s.op->newline() << "if (sup->perf_read_handler)";
s.op->newline(1) << "sup->perf_read_handler(perf_read_values);";
s.op->indent(-1);
}
else
{
s.op->newline() << "if (sups->perf_read_handler)";
s.op->newline(1) << "sups->perf_read_handler(perf_read_values);";
s.op->indent(-1);
}
}
void
uprobe_derived_probe_group::emit_module_utrace_decls (systemtap_session& s)
{
if (probes.empty()) return;
s.op->newline() << "/* ---- utrace uprobes ---- */";
// If uprobes isn't in the kernel, pull it in from the runtime.
s.op->newline() << "#if defined(CONFIG_UPROBES) || defined(CONFIG_UPROBES_MODULE)";
s.op->newline() << "#include <linux/uprobes.h>";
s.op->newline() << "#else";
s.op->newline() << "#include \"linux/uprobes/uprobes.h\"";
s.op->newline() << "#endif";
s.op->newline() << "#ifndef UPROBES_API_VERSION";
s.op->newline() << "#define UPROBES_API_VERSION 1";
s.op->newline() << "#endif";
emit_module_maxuprobes (s);
emit_module_perf_read_handlers(s);
// Forward decls
s.op->newline() << "#include \"linux/uprobes-common.h\"";
// In .bss, the shared pool of uprobe/uretprobe structs. These are
// too big to embed in the initialized .data stap_uprobe_spec array.
// XXX: consider a slab cache or somesuch for stap_uprobes
s.op->newline() << "static struct stap_uprobe stap_uprobes [MAXUPROBES];";
s.op->newline() << "static DEFINE_MUTEX(stap_uprobes_lock);"; // protects against concurrent registration/unregistration
s.op->assert_0_indent();
// Assign task-finder numbers as we build up the stap_uprobe_tf table.
// This means we process probes[] in two passes.
map <string,unsigned> module_index;
unsigned module_index_ctr = 0;
// not const since embedded task_finder_target struct changes
s.op->newline() << "static struct stap_uprobe_tf stap_uprobe_finders[] = {";
s.op->indent(1);
for (unsigned i=0; i<probes.size(); i++)
{
uprobe_derived_probe *p = probes[i];
string pbmkey = make_pbm_key (p);
if (module_index.find (pbmkey) == module_index.end())
{
module_index[pbmkey] = module_index_ctr++;
s.op->newline() << "{";
// NB: it's essential that make_pbm_key() use all of and
// only the same fields as we're about to emit.
s.op->line() << " .finder={";
s.op->line() << " .purpose=\"uprobes\",";
if (p->pid != 0)
s.op->line() << " .pid=" << p->pid << ",";
if (p->section == "") // .statement(addr).absolute
s.op->line() << " .callback=&stap_uprobe_process_found,";
else if (p->section == ".absolute") // proxy for ET_EXEC -> exec()'d program
{
s.op->line() << " .procname=" << lex_cast_qstring(p->module) << ",";
s.op->line() << " .callback=&stap_uprobe_process_found,";
}
else if (p->section != ".absolute") // ET_DYN
{
// XXX: process("buildid").library("buildid") not supported?
if (p->has_library)
s.op->line() << " .procname=\"" << p->path << "\", ";
s.op->line() << " .mmap_callback=&stap_uprobe_mmap_found, ";
s.op->line() << " .munmap_callback=&stap_uprobe_munmap_found, ";
s.op->line() << " .callback=&stap_uprobe_process_munmap,";
}
s.op->line() << " },";
if (p->module != "")
s.op->line() << " .pathname=" << lex_cast_qstring(p->module) << ", ";
s.op->line() << " },";
}
else
{ } // skip it in this pass, already have a suitable stap_uprobe_tf slot for it.
}
s.op->newline(-1) << "};";
s.op->assert_0_indent();
unsigned pci;
for (pci=0; pci<probes.size(); pci++)
{
// List of perf counters used by each probe
// This list is an index into struct stap_perf_probe,
uprobe_derived_probe *p = probes[pci];
s.op->newline() << "long perf_counters_" + lex_cast(pci) + "[] = {";
for (auto pcii = p->perf_counter_refs.begin();
pcii != p->perf_counter_refs.end(); pcii++)
{
unsigned i = 0;
// Find the associated perf.counter probe
for (auto it = s.perf_counters.begin();
it != s.perf_counters.end(); it++, i++)
if ((*it).first == (*pcii))
break;
s.op->line() << lex_cast(i) << ", ";
}
s.op->newline() << "};";
}
// NB: read-only structure
s.op->newline() << "static const struct stap_uprobe_spec stap_uprobe_specs [] = {";
s.op->indent(1);
for (unsigned i =0; i<probes.size(); i++)
{
uprobe_derived_probe* p = probes[i];
s.op->newline() << "{";
string key = make_pbm_key (p);
unsigned value = module_index[key];
if (value != 0)
s.op->line() << " .tfi=" << value << ",";
s.op->line() << " .address=(unsigned long)0x" << hex << p->addr << dec << "ULL,";
s.op->line() << " .probe=" << common_probe_init (p) << ",";
if (p->sdt_semaphore_addr != 0)
s.op->line() << " .sdt_sem_offset=(unsigned long)0x"
<< hex << p->sdt_semaphore_addr << dec << "ULL,";
// Don't bother emit if array is empty.
if (p->perf_counter_refs.size())
{
s.op->line() << " .perf_counters_dim=ARRAY_SIZE(perf_counters_" << lex_cast(i) << "),";
// List of perf counters used by a probe from above
s.op->line() << " .perf_counters=perf_counters_" + lex_cast(i) + ",";
s.op->line() << " .perf_read_handler=&stap_perf_read_handler_"
+ lex_cast(i) + ",";
}
if (p->has_return)
s.op->line() << " .return_p=1,";
s.op->line() << " },";
}
s.op->newline(-1) << "};";
s.op->assert_0_indent();
s.op->newline() << "static void enter_uprobe_probe (struct uprobe *inst, struct pt_regs *regs) {";
s.op->newline(1) << "struct stap_uprobe *sup = container_of(inst, struct stap_uprobe, up);";
s.op->newline() << "const struct stap_uprobe_spec *sups = &stap_uprobe_specs [sup->spec_index];";
common_probe_entryfn_prologue (s, "STAP_SESSION_RUNNING", "", "sups->probe",
"stp_probe_type_uprobe", true,
udpg_entryfn_prologue_declaration_callback,
udpg_entryfn_prologue_pre_context_callback,
(void *)(unsigned long)max_perf_counters);
s.op->newline() << "if (sup->spec_index < 0 || "
<< "sup->spec_index >= " << probes.size() << ") {";
s.op->newline(1) << "_stp_error (\"bad spec_index %d (max " << probes.size()
<< "): %s\", sup->spec_index, c->probe_point);";
s.op->newline() << "goto probe_epilogue;";
s.op->newline(-1) << "}";
s.op->newline() << "c->uregs = regs;";
s.op->newline() << "c->user_mode_p = 1;";
// assign values to something in context
if (s.perf_counters.size())
s.op->newline() << "c->perf_read_values = perf_read_values;";
// Make it look like the IP is set as it would in the actual user
// task when calling real probe handler. Reset IP regs on return, so
// we don't confuse uprobes. PR10458
s.op->newline() << "{";
s.op->indent(1);
s.op->newline() << "unsigned long uprobes_ip = REG_IP(c->uregs);";
s.op->newline() << "SET_REG_IP(regs, inst->vaddr);";
s.op->newline() << "(*sups->probe->ph) (c);";
s.op->newline() << "SET_REG_IP(regs, uprobes_ip);";
s.op->newline(-1) << "}";
common_probe_entryfn_epilogue (s, true, otf_safe_context(s));
s.op->newline(-1) << "}";
s.op->newline() << "static void enter_uretprobe_probe (struct uretprobe_instance *inst, struct pt_regs *regs) {";
s.op->newline(1) << "struct stap_uprobe *sup = container_of(inst->rp, struct stap_uprobe, urp);";
s.op->newline() << "const struct stap_uprobe_spec *sups = &stap_uprobe_specs [sup->spec_index];";
common_probe_entryfn_prologue (s, "STAP_SESSION_RUNNING", "", "sups->probe",
"stp_probe_type_uretprobe", true,
udpg_entryfn_prologue_declaration_callback,
udpg_entryfn_prologue_pre_context_callback,
(void *)(unsigned long)max_perf_counters);
s.op->newline() << "c->ips.ri = inst;";
s.op->newline() << "if (sup->spec_index < 0 || "
<< "sup->spec_index >= " << probes.size() << ") {";
s.op->newline(1) << "_stp_error (\"bad spec_index %d (max " << probes.size()
<< "): %s\", sup->spec_index, c->probe_point);";
s.op->newline() << "goto probe_epilogue;";
s.op->newline(-1) << "}";
s.op->newline() << "c->uregs = regs;";
s.op->newline() << "c->user_mode_p = 1;";
// assign values to something in context
if (s.perf_counters.size())
s.op->newline() << "c->perf_read_values = perf_read_values;";
// Make it look like the IP is set as it would in the actual user
// task when calling real probe handler. Reset IP regs on return, so
// we don't confuse uprobes. PR10458
s.op->newline() << "{";
s.op->indent(1);
s.op->newline() << "unsigned long uprobes_ip = REG_IP(c->uregs);";
s.op->newline() << "SET_REG_IP(regs, inst->ret_addr);";
s.op->newline() << "(*sups->probe->ph) (c);";
s.op->newline() << "SET_REG_IP(regs, uprobes_ip);";
s.op->newline(-1) << "}";
common_probe_entryfn_epilogue (s, true, otf_safe_context(s));
s.op->newline(-1) << "}";
s.op->newline();
s.op->newline() << "#include \"linux/uprobes-common.c\"";
s.op->newline();
}
void
uprobe_derived_probe_group::emit_module_utrace_init (systemtap_session& s)
{
if (probes.empty()) return;
s.op->newline() << "/* ---- utrace uprobes ---- */";
s.op->newline() << "for (j=0; j<MAXUPROBES; j++) {";
s.op->newline(1) << "struct stap_uprobe *sup = & stap_uprobes[j];";
s.op->newline() << "sup->spec_index = -1;"; // free slot
// NB: we assume the rest of the struct (specificaly, sup->up) is
// initialized to zero. This is so that we can use
// sup->up->kdata = NULL for "really free!" PR 6829.
s.op->newline(-1) << "}";
s.op->newline() << "mutex_init (& stap_uprobes_lock);";
// Set up the task_finders
s.op->newline() << "for (i=0; i<sizeof(stap_uprobe_finders)/sizeof(stap_uprobe_finders[0]); i++) {";
s.op->newline(1) << "struct stap_uprobe_tf *stf = & stap_uprobe_finders[i];";
s.op->newline() << "probe_point = stf->pathname;"; // for error messages; XXX: would prefer pp() or something better
s.op->newline() << "rc = stap_register_task_finder_target (& stf->finder);";
// NB: if (rc), there is no need (XXX: nor any way) to clean up any
// finders already registered, since mere registration does not
// cause any utrace or memory allocation actions. That happens only
// later, once the task finder engine starts running. So, for a
// partial initialization requiring unwind, we need do nothing.
s.op->newline() << "if (rc) break;";
s.op->newline(-1) << "}";
}
void
uprobe_derived_probe_group::emit_module_utrace_exit (systemtap_session& s)
{
if (probes.empty()) return;
s.op->newline() << "/* ---- utrace uprobes ---- */";
// NB: there is no stap_unregister_task_finder_target call;
// important stuff like utrace cleanups are done by
// __stp_task_finder_cleanup() via stap_stop_task_finder().
//
// This function blocks until all callbacks are completed, so there
// is supposed to be no possibility of any registration-related code starting
// to run in parallel with our shutdown here. So we don't need to protect the
// stap_uprobes[] array with the mutex.
s.op->newline() << "for (j=0; j<MAXUPROBES; j++) {";
s.op->newline(1) << "struct stap_uprobe *sup = & stap_uprobes[j];";
s.op->newline() << "const struct stap_uprobe_spec *sups = &stap_uprobe_specs [sup->spec_index];";
s.op->newline() << "if (sup->spec_index < 0) continue;"; // free slot
// PR10655: decrement that ENABLED semaphore
s.op->newline() << "if (sup->sdt_sem_address) {";
s.op->newline(1) << "unsigned short sdt_semaphore;"; // NB: fixed size
s.op->newline() << "pid_t pid = (sups->return_p ? sup->urp.u.pid : sup->up.pid);";
s.op->newline() << "struct task_struct *tsk;";
s.op->newline() << "rcu_read_lock();";
// Do a pid->task_struct* lookup. For 2.6.24+, this code assumes
// that the pid is always in the global namespace, not in any
// private namespace.
// We'd like to call find_task_by_pid_ns() here, but it isn't
// exported. So, we call what it calls...
s.op->newline() << " tsk = pid_task(find_pid_ns(pid, &init_pid_ns), PIDTYPE_PID);";
s.op->newline() << "if (tsk) {"; // just in case the thing exited while we weren't watching
s.op->newline(1) << "if (__access_process_vm_noflush(tsk, sup->sdt_sem_address, &sdt_semaphore, sizeof(sdt_semaphore), 0)) {";
s.op->newline(1) << "sdt_semaphore --;";
s.op->newline() << "#ifdef DEBUG_UPROBES";
s.op->newline() << "_stp_dbug (__FUNCTION__,__LINE__, \"-semaphore %#x @ %#lx\\n\", sdt_semaphore, sup->sdt_sem_address);";
s.op->newline() << "#endif";
s.op->newline() << "__access_process_vm_noflush(tsk, sup->sdt_sem_address, &sdt_semaphore, sizeof(sdt_semaphore), 1);";
s.op->newline(-1) << "}";
// XXX: need to analyze possibility of race condition
s.op->newline(-1) << "}";
s.op->newline() << "rcu_read_unlock();";
s.op->newline(-1) << "}";
s.op->newline() << "if (sups->return_p) {";
s.op->newline(1) << "#ifdef DEBUG_UPROBES";
s.op->newline() << "_stp_dbug (__FUNCTION__,__LINE__, \"-uretprobe spec %d index %d pid %d addr %p\\n\", sup->spec_index, j, sup->up.pid, (void*) sup->up.vaddr);";
s.op->newline() << "#endif";
// NB: PR6829 does not change that we still need to unregister at
// *this* time -- when the script as a whole exits.
s.op->newline() << "unregister_uretprobe (& sup->urp);";
s.op->newline(-1) << "} else {";
s.op->newline(1) << "#ifdef DEBUG_UPROBES";
s.op->newline() << "_stp_dbug (__FUNCTION__,__LINE__, \"-uprobe spec %d index %d pid %d addr %p\\n\", sup->spec_index, j, sup->up.pid, (void*) sup->up.vaddr);";
s.op->newline() << "#endif";
s.op->newline() << "unregister_uprobe (& sup->up);";
s.op->newline(-1) << "}";
s.op->newline() << "sup->spec_index = -1;";
// XXX: uprobe missed counts?
s.op->newline(-1) << "}";
s.op->newline() << "mutex_destroy (& stap_uprobes_lock);";
}
void
uprobe_derived_probe_group::emit_module_inode_decls (systemtap_session& s)
{
if (probes.empty()) return;
s.op->newline() << "/* ---- inode uprobes ---- */";
emit_module_maxuprobes (s);
s.op->newline() << "#include \"linux/uprobes-inode.c\"";
emit_module_perf_read_handlers(s);
// Write the probe handler.
s.op->newline() << "static int stapiu_probe_handler "
<< "(struct stapiu_consumer *sup, struct pt_regs *regs) {";
s.op->newline(1);
// Since we're sharing the entry function, we have to dynamically choose the probe_type
string probe_type = "(sup->return_p ? stp_probe_type_uretprobe : stp_probe_type_uprobe)";
common_probe_entryfn_prologue (s, "STAP_SESSION_RUNNING", "", "sup->probe",
probe_type, true,
udpg_entryfn_prologue_declaration_callback,
udpg_entryfn_prologue_pre_context_callback,
(void *)(unsigned long)max_perf_counters);
s.op->newline() << "c->uregs = regs;";
s.op->newline() << "c->user_mode_p = 1;";
// assign values to something in context
if (s.perf_counters.size())
s.op->newline() << "c->perf_read_values = perf_read_values;";
// NB: IP is already set by stapiu_probe_prehandler in uprobes-inode.c
s.op->newline() << "(*sup->probe->ph) (c);";
common_probe_entryfn_epilogue (s, true, otf_safe_context(s));
s.op->newline() << "return 0;";
s.op->newline(-1) << "}";
s.op->assert_0_indent();
// Declare the actual probes.
unsigned pci;
for (pci=0; pci<probes.size(); pci++)
{
// List of perf counters used by each probe
// This list is an index into struct stap_perf_probe,
uprobe_derived_probe *p = probes[pci];
if (p->perf_counter_refs.size() == 0)
continue;
s.op->newline() << "long perf_counters_" + lex_cast(pci) + "[] = {";
for (auto pcii = p->perf_counter_refs.begin();
pcii != p->perf_counter_refs.end(); pcii++)
{
unsigned i = 0;
// Find the associated perf.counter probe
for (auto it = s.perf_counters.begin();
it != s.perf_counters.end(); it++, i++)
if ((*it).first == (*pcii))
break;
s.op->line() << lex_cast(i) << ", ";
}
s.op->newline() << "};";
}
s.op->newline() << "static struct stapiu_consumer "
<< "stap_inode_uprobe_consumers[] = {";
s.op->indent(1);
for (unsigned i=0; i<probes.size(); i++)
{
uprobe_derived_probe *p = probes[i];
s.op->newline() << "{";
if (p->has_return)
s.op->line() << " .return_p=1,";
// emit the task_finder info for this uprobe
// This will be duplicated amongst multiple uprobes for the same file,
// so there will be some iteration within task-finder.
s.op->line() << " .finder={";
s.op->line() << " .purpose=\"inode-uprobes\",";
if (p->pid != 0)
s.op->line() << " .pid=" << p->pid << ",";
if (p->section == "" || // .statement(addr).absolute XXX?
p->section == ".absolute") // ET_EXEC
{
s.op->line() << " .callback=&stapiu_process_found,";
if (!p->build_id_val.empty())
{
s.op->line() << " .build_id=\"" << p->build_id_val << "\",";
s.op->line() << " .build_id_len=" << p->build_id_val.size() << ",";
s.op->line() << " .build_id_vaddr=" << p->build_id_vaddr << "ULL,";
}
else
{
s.op->line() << " .build_id_len=0,";
s.op->line() << " .procname=" << lex_cast_qstring(p->module) << ",";
}
}
else if (p->section != ".absolute") // ET_DYN
{
// XXX: process("buildid1").library("buildid2") probably not quite right yet
s.op->line() << " .mmap_callback=&stapiu_mmap_found, ";
s.op->line() << " .munmap_callback=&stapiu_munmap_found, ";
s.op->line() << " .callback=&stapiu_process_munmap,";
}
s.op->line() << " },"; // finished with the task-finder object
// for shared library probing, we need to configure the stapiu_consumer
// rather than (just) the stapiu_consumer.finder (which deals with
// tasks only).
if (p->section != "" && p->section != ".absolute") // shared library or similar
{
if (p->build_id_val.empty())
s.op->line() << " .solib_pathname=" << lex_cast_qstring(p->module) << ",";
else
{
s.op->line() << " .solib_build_id=\"" << p->build_id_val << "\",";
s.op->line() << " .solib_build_id_len=" << p->build_id_val.size() << ",";
s.op->line() << " .solib_build_id_vaddr=" << p->build_id_vaddr << ",";
}
}
// add the _stp_modules[].name key
s.op->line() << " .module_name=" << lex_cast_qstring(p->module) << ",";
// add the per-uprobe addresses
s.op->line() << " .offset=(loff_t)0x" << hex << p->addr << dec << "ULL,";
if (p->sdt_semaphore_addr)
s.op->line() << " .sdt_sem_offset=(loff_t)0x"
<< hex << p->sdt_semaphore_addr << dec << "ULL,";
// Don't bother emit if array is empty.
if (p->perf_counter_refs.size())
{
s.op->line() << " .perf_counters_dim=ARRAY_SIZE(perf_counters_" << lex_cast(i) << "),";
// List of perf counters used by a probe from above
s.op->line() << " .perf_counters=perf_counters_" + lex_cast(i) + ",";
s.op->line() << " .perf_read_handler=&stap_perf_read_handler_"
+ lex_cast(i) + ",";
}
s.op->line() << " .probe=" << common_probe_init (p) << ",";
s.op->line() << " },";
}
s.op->newline(-1) << "};";
s.op->assert_0_indent();
}
void
uprobe_derived_probe_group::emit_module_inode_init (systemtap_session& s)
{
if (probes.empty()) return;
s.op->newline() << "/* ---- inode uprobes ---- */";
// Let stapiu_init() handle reporting errors by setting probe_point
// to NULL.
s.op->newline() << "probe_point = NULL;";
s.op->newline() << "rc = stapiu_init ("
<< "stap_inode_uprobe_consumers, "
<< "ARRAY_SIZE(stap_inode_uprobe_consumers));";
}
void
uprobe_derived_probe_group::emit_module_inode_refresh (systemtap_session& s)
{
if (probes.empty()) return;
s.op->newline() << "/* ---- inode uprobes ---- */";
s.op->newline() << "stapiu_refresh ("
<< "stap_inode_uprobe_consumers, "
<< "ARRAY_SIZE(stap_inode_uprobe_consumers));";
}
void
uprobe_derived_probe_group::emit_module_inode_exit (systemtap_session& s)
{
if (probes.empty()) return;
s.op->newline() << "/* ---- inode uprobes ---- */";
s.op->newline() << "stapiu_exit ("
<< "stap_inode_uprobe_consumers, "
<< "ARRAY_SIZE(stap_inode_uprobe_consumers));";
}
void
uprobe_derived_probe_group::emit_module_dyninst_decls (systemtap_session& s)
{
if (probes.empty()) return;
s.op->newline() << "/* ---- dyninst uprobes ---- */";
emit_module_maxuprobes (s);
s.op->newline() << "#include \"dyninst/uprobes.h\"";
// Let the dynprobe_derived_probe_group handle outputting targets
// and probes. This allows us to merge different types of probes.
s.op->newline() << "static struct stapdu_probe stapdu_probes[];";
for (unsigned i = 0; i < probes.size(); i++)
{
uprobe_derived_probe *p = probes[i];
dynprobe_add_uprobe(s, p->module, p->addr, p->sdt_semaphore_addr,
(p->has_return ? "STAPDYN_PROBE_FLAG_RETURN" : "0"),
common_probe_init(p));
}
// loc2c-generated code assumes pt_regs are available, so use this to make
// sure we always have *something* for it to dereference...
s.op->newline() << "static struct pt_regs stapdu_dummy_uregs;";
// Write the probe handler.
// NB: not static, so dyninst can find it
s.op->newline() << "int enter_dyninst_uprobe "
<< "(uint64_t index, struct pt_regs *regs) {";
s.op->newline(1) << "struct stapdu_probe *sup = &stapdu_probes[index];";
// Since we're sharing the entry function, we have to dynamically choose the probe_type
string probe_type = "((sup->flags & STAPDYN_PROBE_FLAG_RETURN) ?"
" stp_probe_type_uretprobe : stp_probe_type_uprobe)";
common_probe_entryfn_prologue (s, "STAP_SESSION_RUNNING", "", "sup->probe",
probe_type);
s.op->newline() << "c->uregs = regs ?: &stapdu_dummy_uregs;";
s.op->newline() << "c->user_mode_p = 1;";
// XXX: once we have regs, check how dyninst sets the IP
// XXX: the way that dyninst rewrites stuff is probably going to be
// ... very confusing to our backtracer (at least if we stay in process)
s.op->newline() << "(*sup->probe->ph) (c);";
common_probe_entryfn_epilogue (s, true, otf_safe_context(s));
s.op->newline() << "return 0;";
s.op->newline(-1) << "}";
s.op->newline() << "#include \"dyninst/uprobes-regs.c\"";
s.op->assert_0_indent();
}
void
uprobe_derived_probe_group::emit_module_dyninst_init (systemtap_session& s)
{
if (probes.empty()) return;
/* stapdyn handles the dirty work via dyninst */
s.op->newline() << "/* ---- dyninst uprobes ---- */";
s.op->newline() << "/* this section left intentionally blank */";
}
void
uprobe_derived_probe_group::emit_module_dyninst_exit (systemtap_session& s)
{
if (probes.empty()) return;
/* stapdyn handles the dirty work via dyninst */
s.op->newline() << "/* ---- dyninst uprobes ---- */";
s.op->newline() << "/* this section left intentionally blank */";
}
void
uprobe_derived_probe_group::emit_module_decls (systemtap_session& s)
{
// Here we need to figure out the max number of perf counters used
// per probe.
for (unsigned i=0; i<probes.size(); i++)
{
uprobe_derived_probe *p = probes[i];
if (max_perf_counters < p->perf_counter_refs.size())
max_perf_counters = p->perf_counter_refs.size();
}
if (s.runtime_usermode_p())
emit_module_dyninst_decls (s);
else if (kernel_supports_inode_uprobes (s))
emit_module_inode_decls (s);
else
emit_module_utrace_decls (s);
}
void
uprobe_derived_probe_group::emit_module_init (systemtap_session& s)
{
if (s.runtime_usermode_p())
emit_module_dyninst_init (s);
else if (kernel_supports_inode_uprobes (s))
emit_module_inode_init (s);
else
emit_module_utrace_init (s);
}
void
uprobe_derived_probe_group::emit_module_refresh (systemtap_session& s)
{
if (!s.runtime_usermode_p() && kernel_supports_inode_uprobes (s))
emit_module_inode_refresh (s);
}
void
uprobe_derived_probe_group::emit_module_exit (systemtap_session& s)
{
if (s.runtime_usermode_p())
emit_module_dyninst_exit (s);
else if (kernel_supports_inode_uprobes (s))
emit_module_inode_exit (s);
else
emit_module_utrace_exit (s);
}
bool
sort_for_bpf(systemtap_session& s __attribute__ ((unused)),
uprobe_derived_probe_group *upg, sort_for_bpf_probe_arg_vector &v)
{
if (!upg)
return false;
for (auto i = upg->probes.begin(); i != upg->probes.end(); ++i)
{
uprobe_derived_probe *p = *i;
if (p->module.empty())
throw SEMANTIC_ERROR(_("binary path required for BPF runtime"), p->tok);
if (p->has_library)
throw SEMANTIC_ERROR(_("probe not compatible with BPF runtime"), p->tok);
std::stringstream o;
// format of section name: uprobe/<type>/<pid>/<offset><binary path>
o << "uprobe/"
<< (p->has_return ? "r" : "p") << "/"
<< p->pid << "/"
<< p->addr
<< p->module;
v.push_back(std::pair<derived_probe *, std::string>(p, o.str()));
}
return true;
}
// ------------------------------------------------------------------------
// Dwarfless kprobe derived probes
// ------------------------------------------------------------------------
static const string TOK_KPROBE("kprobe");
struct kprobe_derived_probe: public generic_kprobe_derived_probe
{
kprobe_derived_probe (systemtap_session& sess,
vector<derived_probe *> & results,
probe *base,
probe_point *location,
interned_string module,
interned_string name,
int64_t stmt_addr,
bool has_call,
bool has_return,
bool has_statement,
bool has_maxactive,
bool has_path,
bool has_library,
int64_t maxactive_val,
const string& path,
const string& library
);
bool has_call;
bool has_statement;
bool has_path;
bool has_library;
string path;
string library;
bool access_var;
void printsig (std::ostream &o) const;
void join_group (systemtap_session& s);
};
struct kprobe_var_expanding_visitor: public var_expanding_visitor
{
block *add_block;
block *add_call_probe; // synthesized from .return probes with saved $vars
bool add_block_tid, add_call_probe_tid;
bool has_return;
kprobe_var_expanding_visitor(systemtap_session& sess, bool has_return):
var_expanding_visitor(sess), add_block(NULL), add_call_probe(NULL),
add_block_tid(false), add_call_probe_tid(false),
has_return(has_return) {}
void visit_entry_op (entry_op* e);
};
kprobe_derived_probe::kprobe_derived_probe (systemtap_session& sess,
vector<derived_probe *> & results,
probe *base,
probe_point *location,
interned_string module,
interned_string name,
int64_t stmt_addr,
bool has_call,
bool has_return,
bool has_statement,
bool has_maxactive,
bool has_path,
bool has_library,
int64_t maxactive_val,
const string& path,
const string& library
):
generic_kprobe_derived_probe (base, location,
module, "" /* FIXME: * section */,
stmt_addr, has_return,
has_maxactive, maxactive_val,
name),
has_call (has_call), has_statement (has_statement),
has_path (has_path), has_library (has_library),
path (path), library (library)
{
this->tok = base->tok;
this->access_var = false;
#ifndef USHRT_MAX
#define USHRT_MAX 32767
#endif
// Expansion of $target variables in the probe body produces an error during
// translate phase, since we're not using debuginfo
vector<probe_point::component*> comps;
comps.push_back (new probe_point::component(TOK_KPROBE));
if (has_statement)
{
comps.push_back (new probe_point::component(TOK_STATEMENT,
new literal_number(addr, true)));
comps.push_back (new probe_point::component(TOK_ABSOLUTE));
}
else
{
size_t pos = name.find(':');
if (pos != string::npos)
{
interned_string module = name.substr(0, pos);
interned_string function = name.substr(pos + 1);
comps.push_back (new probe_point::component(TOK_MODULE, new literal_string(module)));
comps.push_back (new probe_point::component(TOK_FUNCTION, new literal_string(function)));
}
else
comps.push_back (new probe_point::component(TOK_FUNCTION, new literal_string(name)));
}
if (has_call)
comps.push_back (new probe_point::component(TOK_CALL));
if (has_return)
comps.push_back (new probe_point::component(TOK_RETURN));
if (has_maxactive)
comps.push_back (new probe_point::component(TOK_MAXACTIVE, new literal_number(maxactive_val)));
kprobe_var_expanding_visitor v (sess, has_return);
// PR25841: no need for this as kprobe.* probes don't support $context vars at all
// if (sess.symbol_resolver)
// sess.symbol_resolver->current_probe = this;
var_expand_const_fold_loop (sess, this->body, v);
// If during target-variable-expanding the probe, we added a new block
// of code, add it to the start of the probe.
if (v.add_block)
this->body = new block(v.add_block, this->body);
// If when target-variable-expanding the probe, we need to
// synthesize a sibling function-entry probe. We don't go through
// the whole probe derivation business (PR10642) that could lead to
// wildcard/alias resolution, or for that dwarf-induced duplication.
//
// XXX: The dwarf_kprobe_derived_probe class has a different method
// to handle these synthesized probes. It might be possible to use
// the same method.
if (v.add_call_probe)
{
assert (has_return);
// We temporarily replace base.
statement* old_body = base->body;
base->body = v.add_call_probe;
derived_probe *entry_handler
= new kprobe_derived_probe (sess, results, base, location,
module, name, 0, true /* has_call */,
false /* has_return */,
has_statement, has_maxactive, has_path,
has_library, maxactive_val, path, library);
entry_handler->synthetic = true;
results.push_back (entry_handler);
base->body = old_body;
}
this->sole_location()->components = comps;
}
void kprobe_derived_probe::printsig (ostream& o) const
{
sole_location()->print (o);
o << " /* " << " name = " << symbol_name << "*/";
printsig_nested (o);
}
void kprobe_derived_probe::join_group (systemtap_session& s)
{
if (! s.generic_kprobe_derived_probes)
s.generic_kprobe_derived_probes = new generic_kprobe_derived_probe_group ();
s.generic_kprobe_derived_probes->enroll (this);
this->group = s.generic_kprobe_derived_probes;
}
struct kprobe_builder: public derived_probe_builder
{
public:
kprobe_builder() {}
void build_no_more (systemtap_session &) {}
virtual void build(systemtap_session & sess,
probe * base,
probe_point * location,
literal_map_t const & parameters,
vector<derived_probe *> & finished_results);
virtual string name() { return "kprobe builder"; }
};
string
suggest_kernel_functions(const systemtap_session& session, interned_string function)
{
const set<interned_string>& kernel_functions = session.kernel_functions;
if (function.empty() || kernel_functions.empty() || session.suppress_costly_diagnostics)
return "";
// PR18577: There isn't any point in generating a suggestion list if
// we're not going to display it.
if ((session.dump_mode == systemtap_session::dump_matched_probes
|| session.dump_mode == systemtap_session::dump_matched_probes_vars)
&& session.verbose < 2)
return "";
if (session.verbose > 2)
clog << "suggesting " << kernel_functions.size() << " kernel functions" << endl;
return levenshtein_suggest(function, kernel_functions, 5); // print top 5 only
}
void
kprobe_builder::build(systemtap_session & sess,
probe * base,
probe_point * location,
literal_map_t const & parameters,
vector<derived_probe *> & finished_results)
{
interned_string function_string_val, module_string_val;
interned_string path, library, path_tgt, library_tgt;
int64_t statement_num_val = 0, maxactive_val = 0;
bool has_function_str, has_module_str, has_statement_num;
bool has_absolute, has_call, has_return, has_maxactive;
bool has_path, has_library;
has_function_str = get_param(parameters, TOK_FUNCTION, function_string_val);
has_module_str = get_param(parameters, TOK_MODULE, module_string_val);
has_call = has_null_param (parameters, TOK_CALL);
has_return = has_null_param (parameters, TOK_RETURN);
has_maxactive = get_param(parameters, TOK_MAXACTIVE, maxactive_val);
has_statement_num = get_param(parameters, TOK_STATEMENT, statement_num_val);
has_absolute = has_null_param (parameters, TOK_ABSOLUTE);
has_path = get_param (parameters, TOK_PROCESS, path);
has_library = get_param (parameters, TOK_LIBRARY, library);
if (has_module_str)
{
// The TOK_MODULE value can be a module name, relative path to a
// module filename, or an absolute path to a module
// filename. Handle all those details.
handle_module_token(sess, module_string_val);
// If we've got a fullpath to the kernel module, then get the
// simple name.
if (module_string_val[0] == '/')
module_string_val = modname_from_path(module_string_val);
}
if (has_path)
{
path = find_executable (path, sess.sysroot, sess.sysenv);
path_tgt = path_remove_sysroot(sess, path);
}
if (has_library)
{
library = find_executable (library, sess.sysroot, sess.sysenv,
"LD_LIBRARY_PATH");
library_tgt = path_remove_sysroot(sess, library);
}
if (has_function_str)
{
if (has_module_str)
{
function_string_val = (string)module_string_val + ":" + (string)function_string_val;
derived_probe *dp
= new kprobe_derived_probe (sess, finished_results, base,
location, module_string_val,
function_string_val,
0, has_call, has_return,
has_statement_num, has_maxactive,
has_path, has_library, maxactive_val,
path_tgt, library_tgt);
finished_results.push_back (dp);
}
else
{
vector<interned_string> matches;
// Simple names can be found directly
if (function_string_val.find_first_of("*?[{") == string::npos)
{
if (sess.kernel_functions.count(function_string_val))
matches.push_back(function_string_val);
}
else // Search function name list for matching names
{
const string& val = csh_to_ksh(function_string_val);
for (auto it = sess.kernel_functions.cbegin();
it != sess.kernel_functions.cend(); it++)
{
// fnmatch returns zero for matching.
if (fnmatch(val.c_str(), it->to_string().c_str(), FNM_EXTMATCH) == 0)
matches.push_back(*it);
}
}
if (matches.empty())
{
string sugs = suggest_kernel_functions(sess, function_string_val);
if (!sugs.empty())
throw SEMANTIC_ERROR (_NF("no match (similar function: %s)",
"no match (similar functions: %s)",
sugs.find(',') == string::npos,
sugs.c_str()));
}
for (auto it = matches.cbegin(); it != matches.cend(); it++)
{
derived_probe *dp
= new kprobe_derived_probe (sess, finished_results, base,
location, "", *it, 0, has_call,
has_return, has_statement_num,
has_maxactive, has_path,
has_library, maxactive_val,
path_tgt, library_tgt);
finished_results.push_back (dp);
}
}
}
else
{
// assert guru mode for absolute probes
if ( has_statement_num && has_absolute && !base->privileged )
throw SEMANTIC_ERROR (_("absolute statement probe in unprivileged script; need stap -g"), base->tok);
finished_results.push_back (new kprobe_derived_probe (sess,
finished_results,
base,
location,
module_string_val,
"",
statement_num_val,
has_call,
has_return,
has_statement_num,
has_maxactive,
has_path,
has_library,
maxactive_val,
path_tgt,
library_tgt));
}
}
void
kprobe_var_expanding_visitor::visit_entry_op (entry_op *e)
{
expression *repl = e;
if (has_return)
{
// see also PR20416
// XXX it would be nice to use gen_kretprobe_saved_return when
// available, but it requires knowing the types already, which is
// problematic for arbitrary expressons.
repl = gen_mapped_saved_return (sess, e->operand, "entry",
add_block, add_block_tid,
add_call_probe, add_call_probe_tid);
}
provide (repl);
}
// ------------------------------------------------------------------------
// Hardware breakpoint based probes.
// ------------------------------------------------------------------------
static const string TOK_HWBKPT("data");
static const string TOK_HWBKPT_WRITE("write");
static const string TOK_HWBKPT_RW("rw");
static const string TOK_LENGTH("length");
#define HWBKPT_READ 0
#define HWBKPT_WRITE 1
#define HWBKPT_RW 2
struct hwbkpt_derived_probe: public derived_probe
{
hwbkpt_derived_probe (probe *base,
probe_point *location,
uint64_t addr,
string symname,
unsigned int len,
bool has_only_read_access,
bool has_only_write_access,
bool has_rw_access,
bool is_kernel
);
Dwarf_Addr hwbkpt_addr;
string symbol_name;
unsigned int hwbkpt_access,hwbkpt_len;
bool kernel_p;
void printsig (std::ostream &o) const;
void join_group (systemtap_session& s);
};
struct hwbkpt_derived_probe_group: public derived_probe_group
{
private:
vector<hwbkpt_derived_probe*> hwbkpt_probes;
public:
void enroll (hwbkpt_derived_probe* probe, systemtap_session& s);
void emit_module_decls (systemtap_session& s);
void emit_module_init (systemtap_session& s);
void emit_module_exit (systemtap_session& s);
friend void warn_for_bpf(systemtap_session& s,
hwbkpt_derived_probe_group *dpg,
const std::string& kind);
};
hwbkpt_derived_probe::hwbkpt_derived_probe (probe *base,
probe_point *location,
uint64_t addr,
string symname,
unsigned int len,
bool has_only_read_access,
bool has_only_write_access,
bool,
bool is_kernel):
derived_probe (base, location, true /* .components soon rewritten */ ),
hwbkpt_addr (addr),
symbol_name (symname),
hwbkpt_len (len),
kernel_p(is_kernel)
{
this->tok = base->tok;
vector<probe_point::component*> comps;
comps.push_back (new probe_point::component(TOK_KERNEL));
if (hwbkpt_addr)
comps.push_back (new probe_point::component (TOK_HWBKPT,
new literal_number(hwbkpt_addr, true)));
else if (symbol_name.size())
comps.push_back (new probe_point::component (TOK_HWBKPT, new literal_string(symbol_name)));
comps.push_back (new probe_point::component (TOK_LENGTH, new literal_number(hwbkpt_len)));
if (has_only_read_access)
this->hwbkpt_access = HWBKPT_READ ;
//TODO add code for comps.push_back for read, since this flag is not for x86
else
{
if (has_only_write_access)
{
this->hwbkpt_access = HWBKPT_WRITE ;
comps.push_back (new probe_point::component(TOK_HWBKPT_WRITE));
}
else
{
this->hwbkpt_access = HWBKPT_RW ;
comps.push_back (new probe_point::component(TOK_HWBKPT_RW));
}
}
this->sole_location()->components = comps;
}
void hwbkpt_derived_probe::printsig (ostream& o) const
{
sole_location()->print (o);
printsig_nested (o);
}
void hwbkpt_derived_probe::join_group (systemtap_session& s)
{
if (! s.hwbkpt_derived_probes)
s.hwbkpt_derived_probes = new hwbkpt_derived_probe_group ();
s.hwbkpt_derived_probes->enroll (this, s);
this->group = s.hwbkpt_derived_probes;
}
void hwbkpt_derived_probe_group::enroll (hwbkpt_derived_probe* p, systemtap_session&)
{
hwbkpt_probes.push_back (p);
}
void
hwbkpt_derived_probe_group::emit_module_decls (systemtap_session& s)
{
if (hwbkpt_probes.empty()) return;
s.op->newline() << "/* ---- hwbkpt-based probes ---- */";
s.op->newline() << "#include <linux/perf_event.h>";
s.op->newline() << "#include <linux/hw_breakpoint.h>";
s.op->newline() << "#include <linux/stap-hw-breakpoint.h>";
s.op->newline();
// Forward declare the main entry functions
s.op->newline() << "#ifdef STAPCONF_PERF_HANDLER_NMI";
s.op->newline() << "static void enter_hwbkpt_probe (struct perf_event *bp,";
s.op->line() << " int nmi,";
s.op->line() << " struct perf_sample_data *data,";
s.op->line() << " struct pt_regs *regs);";
s.op->newline() << "#else";
s.op->newline() << "static void enter_hwbkpt_probe (struct perf_event *bp,";
s.op->line() << " struct perf_sample_data *data,";
s.op->line() << " struct pt_regs *regs);";
s.op->newline() << "#endif";
// Emit the actual probe list.
s.op->newline() << "static struct perf_event_attr ";
s.op->newline() << "stap_hwbkpt_probe_array[" << hwbkpt_probes.size() << "];";
s.op->newline() << "static void *";
s.op->newline() << "stap_hwbkpt_ret_array[" << hwbkpt_probes.size() << "];";
s.op->newline() << "static struct stap_hwbkpt_probe stap_hwbkpt_probes[] = {";
s.op->indent(1);
for (unsigned int it = 0; it < hwbkpt_probes.size(); it++)
{
hwbkpt_derived_probe* p = hwbkpt_probes.at(it);
s.op->newline() << "{";
if (p->kernel_p)
s.op->line() << " .kernel_p=1" << ",";
if (p->symbol_name.size())
s.op->line() << " .address=(unsigned long)0x0" << "ULL,";
else
s.op->line() << " .address=(unsigned long)0x" << hex << p->hwbkpt_addr << dec << "ULL,";
switch(p->hwbkpt_access){
case HWBKPT_READ:
s.op->line() << " .atype=HW_BREAKPOINT_R ,";
break;
case HWBKPT_WRITE:
s.op->line() << " .atype=HW_BREAKPOINT_W ,";
break;
case HWBKPT_RW:
s.op->line() << " .atype=HW_BREAKPOINT_R|HW_BREAKPOINT_W ,";
break;
};
s.op->line() << " .len=" << p->hwbkpt_len << ",";
s.op->line() << " .probe=" << common_probe_init (p) << ",";
s.op->line() << " .symbol=\"" << p->symbol_name << "\",";
s.op->line() << " },";
}
s.op->newline(-1) << "};";
// Emit the hwbkpt callback function
s.op->newline() ;
s.op->newline() << "#ifdef STAPCONF_PERF_HANDLER_NMI";
s.op->newline() << "static void enter_hwbkpt_probe (struct perf_event *bp,";
s.op->line() << " int nmi,";
s.op->line() << " struct perf_sample_data *data,";
s.op->line() << " struct pt_regs *regs) {";
s.op->newline() << "#else";
s.op->newline() << "static void enter_hwbkpt_probe (struct perf_event *bp,";
s.op->line() << " struct perf_sample_data *data,";
s.op->line() << " struct pt_regs *regs) {";
s.op->newline() << "#endif";
s.op->newline(1) << "unsigned int i;";
s.op->newline() << "if (bp->attr.type != PERF_TYPE_BREAKPOINT) return;";
s.op->newline() << "for (i=0; i<" << hwbkpt_probes.size() << "; i++) {";
s.op->newline(1) << "struct perf_event_attr *hp = & stap_hwbkpt_probe_array[i];";
// XXX: why not match stap_hwbkpt_ret_array[i] against bp instead?
s.op->newline() << "if (bp->attr.bp_addr==hp->bp_addr && bp->attr.bp_type==hp->bp_type && bp->attr.bp_len==hp->bp_len) {";
s.op->newline(1) << "struct stap_hwbkpt_probe *skp = &stap_hwbkpt_probes[i];";
common_probe_entryfn_prologue (s, "STAP_SESSION_RUNNING", "", "skp->probe",
"stp_probe_type_hwbkpt");
s.op->newline() << "if (user_mode(regs)) {";
s.op->newline(1)<< "c->user_mode_p = 1;";
s.op->newline() << "c->uregs = regs;";
s.op->newline(-1) << "} else {";
s.op->newline(1) << "c->kregs = regs;";
s.op->newline(-1) << "}";
s.op->newline() << "(*skp->probe->ph) (c);";
common_probe_entryfn_epilogue (s, true, otf_safe_context(s));
s.op->newline(-1) << "}";
s.op->newline(-1) << "}";
s.op->newline() << "return;";
s.op->newline(-1) << "}";
}
void
hwbkpt_derived_probe_group::emit_module_init (systemtap_session& s)
{
s.op->newline() << "rc = stap_hwbkpt_init(&enter_hwbkpt_probe, stap_hwbkpt_probes, "
<< hwbkpt_probes.size() << ", stap_hwbkpt_probe_array, "
<< "stap_hwbkpt_ret_array, &probe_point);";
}
void
hwbkpt_derived_probe_group::emit_module_exit (systemtap_session& s)
{
//Unregister hwbkpt probes.
s.op->newline() << "stap_hwbkpt_exit(stap_hwbkpt_probes, "
<< hwbkpt_probes.size() << ", stap_hwbkpt_ret_array);";
}
// PR26234: Not supported by stapbpf.
void
warn_for_bpf(systemtap_session& s, hwbkpt_derived_probe_group *hpg,
const std::string& kind)
{
for (unsigned int i = 0; i < hpg->hwbkpt_probes.size(); i++)
{
s.print_warning(_F("%s will be ignored by bpf backend",
kind.c_str()),
hpg->hwbkpt_probes[i]->tok);
}
}
struct hwbkpt_builder: public derived_probe_builder
{
bool kernel_p;
hwbkpt_builder(bool is_kernel): kernel_p(is_kernel) {}
virtual void build(systemtap_session & sess,
probe * base,
probe_point * location,
literal_map_t const & parameters,
vector<derived_probe *> & finished_results);
virtual string name() { return "hwbkpt builder"; }
};
void
hwbkpt_builder::build(systemtap_session & sess,
probe * base,
probe_point * location,
literal_map_t const & parameters,
vector<derived_probe *> & finished_results)
{
interned_string symbol_str_val;
int64_t hwbkpt_address, len;
bool has_addr, has_symbol_str, has_write, has_rw, has_len;
if (! (sess.kernel_config["CONFIG_PERF_EVENTS"] == string("y")))
throw SEMANTIC_ERROR (_("CONFIG_PERF_EVENTS not available on this kernel"),
location->components[0]->tok);
if (! (sess.kernel_config["CONFIG_HAVE_HW_BREAKPOINT"] == string("y")))
throw SEMANTIC_ERROR (_("CONFIG_HAVE_HW_BREAKPOINT not available on this kernel"),
location->components[0]->tok);
// See BZ1431263 (on aarch64, running the hw_watch_addr.stp
// systemtap examples cause a stuck CPU).
if (sess.architecture == string("arm64"))
throw SEMANTIC_ERROR (_F("%s.data probes are not supported on arm64 kernels",
kernel_p ? "kernel" : "process"),
location->components[0]->tok);
has_addr = get_param (parameters, TOK_HWBKPT, hwbkpt_address);
has_symbol_str = get_param (parameters, TOK_HWBKPT, symbol_str_val);
has_len = get_param (parameters, TOK_LENGTH, len);
has_write = (parameters.find(TOK_HWBKPT_WRITE) != parameters.end());
has_rw = (parameters.find(TOK_HWBKPT_RW) != parameters.end());
// Make an intermediate pp that is well-formed. It's pretty much the same as
// the user-provided one, except that the addr literal is well-typed.
probe_point* well_formed_loc = new probe_point(*location);
well_formed_loc->well_formed = true;
vector<probe_point::component*> well_formed_comps;
for (auto it = location->components.begin();
it != location->components.end(); ++it)
if ((*it)->functor == TOK_HWBKPT && has_addr)
well_formed_comps.push_back(new probe_point::component(TOK_HWBKPT,
new literal_number(hwbkpt_address, true /* hex */ )));
else
well_formed_comps.push_back(*it);
well_formed_loc->components = well_formed_comps;
probe *new_base = new probe (base, well_formed_loc);
if (!has_len)
len = 1;
if (has_addr)
finished_results.push_back (new hwbkpt_derived_probe (new_base,
location,
hwbkpt_address,
"",len,0,
has_write,
has_rw,
kernel_p));
else if (has_symbol_str)
finished_results.push_back (new hwbkpt_derived_probe (new_base,
location,
0,
symbol_str_val,len,0,
has_write,
has_rw,
kernel_p));
else
assert (0);
}
// ------------------------------------------------------------------------
// statically inserted kernel-tracepoint derived probes
// ------------------------------------------------------------------------
struct tracepoint_arg
{
string name, c_type, c_decl, typecast;
bool usable, used, isptr;
Dwarf_Die type_die;
tracepoint_arg(const string& tracepoint_name, Dwarf_Die *arg);
// used with --runtime=bpf
int size;
int offset;
bool is_signed;
};
struct tracepoint_derived_probe: public derived_probe
{
tracepoint_derived_probe (systemtap_session& s,
dwflpp& dw, Dwarf_Die& func_die,
const string& tracepoint_system,
const string& tracepoint_name,
probe* base_probe, probe_point* location);
systemtap_session& sess;
string tracepoint_system, tracepoint_name, header;
vector <struct tracepoint_arg> args;
void build_args(dwflpp& dw, Dwarf_Die& func_die);
void build_args_for_bpf(dwflpp& dw, Dwarf_Die& struct_die);
void getargs (std::list<std::string> &arg_set) const;
void join_group (systemtap_session& s);
void print_dupe_stamp(ostream& o);
};
struct tracepoint_derived_probe_group: public generic_dpg<tracepoint_derived_probe>
{
friend bool sort_for_bpf(systemtap_session& s,
tracepoint_derived_probe_group *t,
sort_for_bpf_probe_arg_vector &v);
void emit_module_decls (systemtap_session& s);
void emit_module_init (systemtap_session& s);
void emit_module_exit (systemtap_session& s);
};
struct tracepoint_var_expanding_visitor: public var_expanding_visitor
{
tracepoint_var_expanding_visitor(dwflpp& dw,
vector <struct tracepoint_arg>& args):
var_expanding_visitor (dw.sess),
dw (dw), args (args) {}
dwflpp& dw;
vector <struct tracepoint_arg>& args;
void visit_target_symbol (target_symbol* e);
void visit_target_symbol_arg (target_symbol* e);
void visit_target_symbol_context (target_symbol* e);
};
void
tracepoint_var_expanding_visitor::visit_target_symbol_arg (target_symbol* e)
{
string argname = e->sym_name();
string en = e->name;
// search for a tracepoint parameter matching this name
tracepoint_arg *arg = NULL;
for (unsigned i = 0; i < args.size(); ++i)
if (args[i].usable && args[i].name == argname)
{
arg = &args[i];
arg->used = true;
break;
}
if (arg == NULL)
{
set<string> vars;
for (unsigned i = 0; i < args.size(); ++i)
vars.insert("$" + args[i].name);
vars.insert("$$name");
vars.insert("$$parms");
vars.insert("$$vars");
string sugs = levenshtein_suggest(en, vars); // no need to limit, there's not that many
// We hope that this value ends up not being referenced after all, so it
// can be optimized out quietly.
throw SEMANTIC_ERROR(_F("unable to find tracepoint variable '%s'%s",
en.c_str(), sugs.empty() ? "" :
(_(" (alternatives: ") + sugs + ")").c_str()), e->tok);
// NB: we use 'alternatives' because we list all
// NB: we can have multiple errors, since a target variable
// may be expanded in several different contexts:
// trace ("*") { $foo->bar }
}
// make sure we're not dereferencing base types or void
bool deref_p = arg->isptr && !null_die(&arg->type_die);
if (!deref_p)
e->assert_no_components("tracepoint", true);
// we can only write to dereferenced fields, and only if guru mode is on
bool lvalue = is_active_lvalue(e);
if (lvalue && (!dw.sess.guru_mode || e->components.empty()))
throw SEMANTIC_ERROR(_F("write to tracepoint variable '%s' not permitted; need stap -g", en.c_str()), e->tok);
// XXX: if a struct/union arg is passed by value, then writing to its fields
// is also meaningless until you dereference past a pointer member. It's
// harder to detect and prevent that though...
if (e->components.empty())
{
if (e->addressof)
throw SEMANTIC_ERROR(_("cannot take address of tracepoint variable"), e->tok);
// Just grab the value from the probe locals
symbol* sym = new symbol;
sym->tok = e->tok;
sym->name = "__tracepoint_arg_" + arg->name;
sym->type_details = make_shared<exp_type_dwarf>(&dw, &arg->type_die, false, false);
if (sess.runtime_mode == systemtap_session::bpf_runtime)
{
bpf_context_vardecl *v = new bpf_context_vardecl;
v->size = arg->size;
v->offset = arg->offset;
v->is_signed = arg->is_signed;
sym->referent = v;
}
provide (sym);
}
else
{
// make a copy of the original as a bare target symbol for the tracepoint
// value, which will be passed into the dwarf dereferencing code
target_symbol* e2 = deep_copy_visitor::deep_copy(e);
e2->components.clear();
if (e->check_pretty_print (lvalue))
{
dwarf_pretty_print dpp(dw, &arg->type_die, e2, deref_p, false,
*e, lvalue);
dpp.expand()->visit (this);
return;
}
bool userspace_p = false;
location_context ctx(e, e2);
ctx.userspace_p = userspace_p;
if (dw.sess.runtime_mode == systemtap_session::bpf_runtime)
ctx.adapt_pointer_to_bpf(arg->size, arg->offset, arg->is_signed);
Dwarf_Die endtype;
dw.literal_stmt_for_pointer (ctx, &arg->type_die, ctx.e, lvalue, &endtype);
string fname = (string(lvalue ? "_tracepoint_tvar_set"
: "_tracepoint_tvar_get")
+ "_" + e->sym_name()
+ "_" + lex_cast(tick++));
functioncall* n = synthetic_embedded_deref_call(dw, ctx, fname, &endtype,
userspace_p, lvalue, e2);
if (lvalue)
provide_lvalue_call (n);
provide(n); // allow recursion to $var1[$var2] subexpressions
}
}
void
tracepoint_var_expanding_visitor::visit_target_symbol_context (target_symbol* e)
{
if (e->addressof)
throw SEMANTIC_ERROR(_("cannot take address of context variable"), e->tok);
if (is_active_lvalue (e))
throw SEMANTIC_ERROR(_F("write to tracepoint '%s' not permitted",
e->name.to_string().c_str()), e->tok);
if (e->name == "$$name" || e->name == "$$system")
{
e->assert_no_components("tracepoint");
string member = (e->name == "$$name") ? "c->ips.tp.tracepoint_name"
: "c->ips.tp.tracepoint_system";
// Synthesize an embedded expression.
embedded_expr *expr = new embedded_expr;
expr->tok = e->tok;
expr->code = string("/* string */ /* pure */ " +
member + " ? " + member + " : \"\"");
provide (expr);
}
else if (e->name == "$$vars" || e->name == "$$parms")
{
e->assert_no_components("tracepoint", true);
print_format* pf = print_format::create(e->tok, "sprintf");
for (unsigned i = 0; i < args.size(); ++i)
{
if (!args[i].usable)
continue;
if (i > 0)
pf->raw_components += " ";
pf->raw_components += args[i].name;
target_symbol *tsym = new target_symbol;
tsym->tok = e->tok;
tsym->name = "$" + args[i].name;
tsym->components = e->components;
// every variable should always be accessible!
tsym->saved_conversion_error = 0;
expression *texp = require<expression> (tsym); // NB: throws nothing ...
if (tsym->saved_conversion_error) // ... but this is how we know it happened.
{
if (dw.sess.verbose>2)
for (const semantic_error *c = tsym->saved_conversion_error;
c != 0; c = c->get_chain())
clog << _("variable location problem [man error::dwarf]: ") << c->what() << endl;
pf->raw_components += "=?";
continue;
}
if (e->check_pretty_print ())
pf->raw_components += "=%s";
else
pf->raw_components += args[i].isptr ? "=%p" : "=%#x";
pf->args.push_back(texp);
}
pf->components = print_format::string_to_components(pf->raw_components);
provide (pf);
}
else
assert(0); // shouldn't get here
}
void
tracepoint_var_expanding_visitor::visit_target_symbol (target_symbol* e)
{
try
{
assert(e->name.size() > 0 && e->name[0] == '$');
if (e->name == "$$name" || e->name == "$$system"
|| e->name == "$$parms" || e->name == "$$vars")
visit_target_symbol_context (e);
else
visit_target_symbol_arg (e);
}
catch (const semantic_error &er)
{
if (sess.verbose > 3)
clog << "chaining to " << *e->tok << endl
<< sess.build_error_msg(er) << endl;
e->chain (er);
provide (e);
}
}
tracepoint_derived_probe::tracepoint_derived_probe (systemtap_session& s,
dwflpp& dw, Dwarf_Die& func_die,
const string& tracepoint_system,
const string& tracepoint_name,
probe* base, probe_point* loc):
derived_probe (base, loc, true /* .components soon rewritten */), sess (s),
tracepoint_system (tracepoint_system), tracepoint_name (tracepoint_name)
{
// create synthetic probe point name; preserve condition
vector<probe_point::component*> comps;
comps.push_back (new probe_point::component (TOK_KERNEL));
// tag on system to the final name unless we're in compatibility mode so that
// e.g. pn() returns just the name as before
string final_name = tracepoint_name;
if (!tracepoint_system.empty()
&& strverscmp(s.compatible.c_str(), "2.6") > 0)
final_name = tracepoint_system + ":" + final_name;
comps.push_back (new probe_point::component (TOK_TRACE,
new literal_string(final_name)));
this->sole_location()->components = comps;
// fill out the available arguments in this tracepoint
if (s.runtime_mode == systemtap_session::bpf_runtime)
build_args_for_bpf(dw, func_die);
else
build_args(dw, func_die);
// determine which header defined this tracepoint
string decl_file = dwarf_decl_file(&func_die);
header = decl_file;
// tracepoints from FOO_event_types.h should really be included from FOO.h
// XXX can dwarf tell us the include hierarchy? it would be better to
// ... walk up to see which one was directly included by tracequery.c
// XXX: see also PR9993.
size_t header_pos = header.find("_event_types");
if (header_pos != string::npos)
header.erase(header_pos, 12);
// Now expand the local variables in the probe body
tracepoint_var_expanding_visitor v (dw, args);
// PR25841 -- not yet, need to put tracepoint parameters somewhere else, so
// function context code can access it.
// if (sess.symbol_resolver)
// sess.symbol_resolver->current_probe = this;
var_expand_const_fold_loop (sess, this->body, v);
for (unsigned i = 0; i < args.size(); i++)
{
if (!args[i].used)
continue;
if (s.runtime_mode == systemtap_session::bpf_runtime)
{
bpf_context_vardecl* v = new bpf_context_vardecl;
v->name = "__tracepoint_arg_" + args[i].name;
v->tok = this->tok;
v->set_arity(0, this->tok);
v->type = pe_long;
v->synthetic = true;
v->size = args[i].size;
v->offset = args[i].offset;
this->locals.push_back(v);
}
else
{
vardecl* v = new vardecl;
v->name = v->unmangled_name = "__tracepoint_arg_" + args[i].name;
v->tok = this->tok;
v->set_arity(0, this->tok);
v->type = pe_long;
v->synthetic = true;
this->locals.push_back (v);
}
}
if (sess.verbose > 2)
clog << "tracepoint-based " << name() << " tracepoint='" << tracepoint_name << "'" << endl;
}
static bool
resolve_pointer_type(Dwarf_Die& die, bool& isptr)
{
if (null_die(&die))
{
isptr = true;
return true;
}
Dwarf_Die type;
switch (dwarf_tag(&die))
{
case DW_TAG_typedef:
case DW_TAG_const_type:
case DW_TAG_volatile_type:
case DW_TAG_restrict_type:
// iterate on the referent type
return (dwarf_attr_die(&die, DW_AT_type, &die)
&& resolve_pointer_type(die, isptr));
case DW_TAG_base_type:
case DW_TAG_enumeration_type:
case DW_TAG_structure_type:
case DW_TAG_union_type:
// base types will simply be treated as script longs
// structs/unions must be referenced by pointer elsewhere
isptr = false;
return true;
case DW_TAG_array_type:
case DW_TAG_pointer_type:
case DW_TAG_reference_type:
case DW_TAG_rvalue_reference_type:
// pointer-like types can be treated as script longs,
// and if we know their type, they can also be dereferenced
isptr = true;
type = die;
while (dwarf_attr_die(&type, DW_AT_type, &type))
{
// It still might be a non-type, e.g. const void,
// so we need to strip away all qualifiers.
int tag = dwarf_tag(&type);
if (tag != DW_TAG_typedef &&
tag != DW_TAG_const_type &&
tag != DW_TAG_volatile_type &&
tag != DW_TAG_restrict_type)
{
die = type;
return true;
}
}
// otherwise use a null_die to indicate void
std::memset(&die, 0, sizeof(die));
return true;
default:
// should we consider other types too?
return false;
}
}
static bool
is_signed_type(Dwarf_Die *die)
{
switch (dwarf_tag(die))
{
case DW_TAG_base_type:
{
Dwarf_Attribute attr;
Dwarf_Word encoding = (Dwarf_Word) -1;
dwarf_formudata (dwarf_attr_integrate (die, DW_AT_encoding, &attr),
&encoding);
return encoding == DW_ATE_signed || encoding == DW_ATE_signed_char;
}
case DW_TAG_typedef:
case DW_TAG_const_type:
case DW_TAG_volatile_type:
case DW_TAG_restrict_type:
// iterate on the referent type
return (dwarf_attr_die(die, DW_AT_type, die)
&& is_signed_type(die));
default:
// should we consider other types too?
return false;
}
}
static int
get_byte_size(Dwarf_Die *die, const char *probe_name)
{
Dwarf_Attribute attr;
Dwarf_Word size;
if (dwarf_attr(die, DW_AT_byte_size, &attr) == NULL)
{
Dwarf_Word count = 1;
Dwarf_Die type;
Dwarf_Die child;
if (dwarf_tag(die) == DW_TAG_array_type)
{
count = 0;
if (dwarf_child(die, &child) != 0)
throw SEMANTIC_ERROR(_F("cannot resolve size of array %s for probe %s",
dwarf_diename(die), probe_name));
do
if (dwarf_tag(&child) == DW_TAG_subrange_type)
{
if (dwarf_attr(&child, DW_AT_upper_bound, &attr) != NULL)
{
dwarf_formudata(&attr, &count);
count++;
}
else if (dwarf_attr(&child, DW_AT_count, &attr) != NULL)
dwarf_formudata(&attr, &count);
else
SEMANTIC_ERROR(_F("array %s for probe %s has unknown size",
dwarf_diename(die), probe_name));
}
while (dwarf_siblingof(&child, &child) == 0);
}
// Do any other types require special handling?
if (dwarf_attr_die(die, DW_AT_type, &type) == NULL)
throw (SEMANTIC_ERROR(
_F("cannot get byte size of type '%s' for tracepoint '%s'",
dwarf_diename(die), probe_name)));
return count * get_byte_size(&type, probe_name);
}
dwarf_formudata(&attr, &size);
return size;
}
static bool
resolve_tracepoint_arg_type(tracepoint_arg& arg)
{
if (!resolve_pointer_type(arg.type_die, arg.isptr))
return false;
if (arg.isptr)
arg.typecast = "(intptr_t)";
else if (dwarf_tag(&arg.type_die) == DW_TAG_structure_type ||
dwarf_tag(&arg.type_die) == DW_TAG_union_type)
{
// for structs/unions which are passed by value, we turn it into
// a pointer that can be dereferenced.
arg.isptr = true;
arg.typecast = "(intptr_t)&";
}
return true;
}
tracepoint_arg::tracepoint_arg(const string& tracepoint_name, Dwarf_Die *arg)
: usable(false), used(false), isptr(false), type_die(), size(-1),
offset(-1), is_signed(false)
{
name = dwarf_diename(arg) ?: "";
// read the type of this parameter
if (!dwarf_attr_die (arg, DW_AT_type, &type_die)
|| !dwarf_type_name(&type_die, c_type))
throw SEMANTIC_ERROR (_F("cannot get type of parameter '%s' of tracepoint '%s'",
name.c_str(), tracepoint_name.c_str()));
// build the C declaration
if (!dwarf_type_decl(&type_die, "__tracepoint_arg_" + name, c_decl))
throw SEMANTIC_ERROR (_F("cannot get declaration of parameter '%s' of tracepoint '%s'",
name.c_str(), tracepoint_name.c_str()));
usable = resolve_tracepoint_arg_type(*this);
}
void
tracepoint_derived_probe::build_args(dwflpp&, Dwarf_Die& func_die)
{
Dwarf_Die arg;
if (dwarf_child(&func_die, &arg) == 0)
do
if (dwarf_tag(&arg) == DW_TAG_formal_parameter)
{
// build a tracepoint_arg for this parameter
args.emplace_back(tracepoint_name, &arg);
if (sess.verbose > 4)
{
auto& tparg = args.back();
clog << _F("found parameter for tracepoint '%s': type:'%s' name:'%s' decl:'%s' %s",
tracepoint_name.c_str(), tparg.c_type.c_str(), tparg.name.c_str(),
tparg.c_decl.c_str(), tparg.usable ? "ok" : "unavailable") << endl;
}
}
while (dwarf_siblingof(&arg, &arg) == 0);
}
void
tracepoint_derived_probe::build_args_for_bpf(dwflpp&, Dwarf_Die& struct_die)
{
Dwarf_Die member;
int data_start = 0;
bool struct_found = false, more_members = true;
if (dwarf_child(&struct_die, &member) != 0) return;
// find the member struct inside the struct that actually has the information about the bpf arguments
while (!struct_found && more_members)
{
Dwarf_Die type;
Dwarf_Attribute attr;
Dwarf_Word off;
dwarf_attr_die(&member, DW_AT_type, &type);
if ((dwarf_tag(&type) == DW_TAG_structure_type)) {
if (dwarf_attr(&member, DW_AT_data_member_location, &attr) == NULL
|| dwarf_formudata(&attr, &off) != 0)
throw (SEMANTIC_ERROR
(_F("cannot get offset attribute for variable '%s' of tracepoint '%s'",
dwarf_diename(&member), tracepoint_name.c_str())));
data_start = off;
member = type;
struct_found = true;
} else {
more_members = (dwarf_siblingof(&member, &member) == 0);
}
}
if (dwarf_child(&member, &member) == 0)
do
if (dwarf_tag(&member) == DW_TAG_member)
{
Dwarf_Die type;
Dwarf_Attribute attr;
Dwarf_Word off;
tracepoint_arg arg(dwarf_diename(&member), &member);
if (dwarf_attr(&member, DW_AT_data_member_location, &attr) == NULL
|| dwarf_formudata(&attr, &off) != 0)
throw (SEMANTIC_ERROR
(_F("cannot get offset attribute for variable '%s' of tracepoint '%s'",
dwarf_diename(&member), tracepoint_name.c_str())));
dwarf_attr_die(&member, DW_AT_type, &type);
arg.is_signed = is_signed_type(&type);
arg.size = get_byte_size(&type, tracepoint_name.c_str());
arg.offset = off + data_start;
args.push_back(arg);
}
while (dwarf_siblingof(&member, &member) == 0);
}
void
tracepoint_derived_probe::getargs(std::list<std::string> &arg_set) const
{
for (unsigned i = 0; i < args.size(); ++i)
if (args[i].usable)
arg_set.push_back("$"+args[i].name+":"+args[i].c_type);
}
void
tracepoint_derived_probe::join_group (systemtap_session& s)
{
if (! s.tracepoint_derived_probes)
s.tracepoint_derived_probes = new tracepoint_derived_probe_group ();
s.tracepoint_derived_probes->enroll (this);
this->group = s.tracepoint_derived_probes;
}
void
tracepoint_derived_probe::print_dupe_stamp(ostream& o)
{
for (unsigned i = 0; i < args.size(); i++)
if (args[i].used)
o << "__tracepoint_arg_" << args[i].name << endl;
}
// Look for a particular header file in the build directory and the
// source directory (if it exists). Return true if the header file was
// found.
static bool header_exists(systemtap_session& s, const string& header)
{
if (file_exists(s.kernel_build_tree + header)
|| (!s.kernel_source_tree.empty()
&& file_exists(s.kernel_source_tree + header)))
return true;
return false;
}
static vector<string> tracepoint_extra_decls (systemtap_session& s,
const string& header,
const bool tracequery)
{
vector<string> they_live;
// Several headers end up including events/irq.h, events/kmem.h, and
// events/module.h on RHEL6 (since they include headers that include
// those headers). This causes stap to think the tracepoints from
// those files belong in multiple tracepoint subsystems. To get
// around this, we'll define the header guard macros for those
// tracepoints headers, troublesome header file, then undefine the
// macro. Then, later when a header includes linux/interrupt.h (for
// example), the events/irq.h file doesn't get included because of
// the header guard macro on linux/interrupt.h.
//
// Note that we only do this when building a tracequery module (to
// find all the tracepoints).
if (tracequery)
{
they_live.push_back ("#define _TRACE_KMEM_H");
they_live.push_back ("#define _TRACE_IRQ_H");
they_live.push_back ("#include <linux/interrupt.h>");
they_live.push_back ("#undef _TRACE_IRQ_H");
they_live.push_back ("#undef _TRACE_KMEM_H");
they_live.push_back ("#define _TRACE_MODULE_H");
they_live.push_back ("#include <linux/module.h>");
they_live.push_back ("#undef _TRACE_MODULE_H");
}
// PR 9993
// XXX: may need this to be configurable
they_live.push_back ("#include <linux/skbuff.h>");
// PR11649: conditional extra header
// for kvm tracepoints in 2.6.33ish
if (s.kernel_config["CONFIG_KVM"] != string("")) {
they_live.push_back ("#include <linux/kvm_host.h>");
}
if (header.find("xfs") != string::npos
&& s.kernel_config["CONFIG_XFS_FS"] != string("")) {
they_live.push_back ("#define XFS_BIG_BLKNOS 1");
// The xfs_types.h include file got moved from fs/xfs/xfs_types.h
// to fs/xfs/libxfs/xfs_types.h in upstream kernel 4.4, but that
// patch has gotten backported to RHEL7's 3.10, so we can't really
// depend on kernel version to know where that file is. We could
// add lots of typedefs here to get things to compile (like for
// xfs_agblock_t, xfs_agino_t, etc.), but the upstream kernel
// could change the types being mapped and we'd get a compile
// error when the types don't match. So, we'll try to find the
// xfs_types.h file in the kernel source tree.
if (header_exists(s, "/fs/xfs/xfs_linux.h"))
they_live.push_back ("#include \"fs/xfs/xfs_linux.h\"");
if (header_exists(s, "/fs/xfs/libxfs/xfs_types.h"))
they_live.push_back ("#include \"fs/xfs/libxfs/xfs_types.h\"");
else if (header_exists(s, "/fs/xfs/xfs_types.h"))
they_live.push_back ("#include \"fs/xfs/xfs_types.h\"");
// Kernel 4.7 needs xfs_format.h.
if (header_exists(s, "/fs/xfs/libxfs/xfs_format.h"))
they_live.push_back ("#include \"fs/xfs/libxfs/xfs_format.h\"");
// Kernel 4.10 needs several headers.
if (header_exists(s, "/fs/xfs/libxfs/xfs_trans_resv.h"))
they_live.push_back ("#include \"fs/xfs/libxfs/xfs_trans_resv.h\"");
if (header_exists(s, "/fs/xfs/xfs_mount.h"))
they_live.push_back ("#include \"fs/xfs/xfs_mount.h\"");
if (header_exists(s, "/fs/xfs/libxfs/xfs_log_format.h"))
they_live.push_back ("#include \"fs/xfs/libxfs/xfs_log_format.h\"");
// Sigh. xfs_types.h (no matter where it is), also needs
// xfs_linux.h. But, on newer kernels, xfs_linux.h includes
// xfs_types.h, but really needs a '-I' command to do so. So,
// we'll have to add a custom '-I' command.
if (file_exists(s.kernel_build_tree + "/fs/xfs/libxfs"))
s.kernel_extra_cflags.push_back ("-I" + s.kernel_build_tree
+ "/fs/xfs/libxfs");
else if (!s.kernel_source_tree.empty()
&& file_exists(s.kernel_source_tree + "/fs/xfs/libxfs"))
s.kernel_extra_cflags.push_back ("-I" + s.kernel_source_tree
+ "/fs/xfs/libxfs");
they_live.push_back ("struct xfs_mount;");
they_live.push_back ("struct xfs_inode;");
they_live.push_back ("struct xfs_buf;");
they_live.push_back ("struct xfs_bmbt_irec;");
they_live.push_back ("struct xfs_trans;");
they_live.push_back ("struct xfs_name;");
they_live.push_back ("struct xfs_icreate_log;");
}
if (header.find("nfs") != string::npos
&& s.kernel_config["CONFIG_NFSD"] != string("")) {
they_live.push_back ("struct rpc_task;");
they_live.push_back ("struct nfs_open_context;");
they_live.push_back ("struct nfs_client;");
they_live.push_back ("struct nfs_fattr;");
they_live.push_back ("struct nfs_fh;");
they_live.push_back ("struct nfs_server;");
they_live.push_back ("struct nfs_pgio_header;");
they_live.push_back ("struct nfs_commit_data;");
they_live.push_back ("struct nfs_closeres;");
they_live.push_back ("struct nfs_closeargs;");
they_live.push_back ("struct nfs_unlinkdata;");
they_live.push_back ("struct nfs_writeverf;");
they_live.push_back ("struct nfs4_sequence_args;");
they_live.push_back ("struct nfs4_sequence_res;");
they_live.push_back ("struct nfs4_session;");
they_live.push_back ("struct nfs4_state;");
they_live.push_back ("struct nfs4_delegreturnres;");
they_live.push_back ("struct nfs4_delegreturnargs;");
they_live.push_back ("struct pnfs_layout_hdr;");
they_live.push_back ("struct pnfs_layout_range;");
they_live.push_back ("struct pnfs_layout_segment;");
// We need a definition of a 'stateid_t', which is a typedef of an
// anonymous struct. So, we'll have to include the right kernel
// header file.
if (header_exists(s, "/fs/nfsd/state.h"))
they_live.push_back ("#include \"fs/nfsd/state.h\"");
// We need a definition of the pnfs_update_layout_reason enum, so
// we'll need the right kernel header file.
if (s.kernel_config["CONFIG_NFS_V4"] != string("")
&& header_exists(s, "/include/linux/nfs4.h"))
they_live.push_back ("#include \"linux/nfs4.h\"");
}
// RHEL6.3
if (header.find("rpc") != string::npos && s.kernel_config["CONFIG_NFSD"] != string("")) {
they_live.push_back ("struct rpc_clnt;");
they_live.push_back ("struct rpc_wait_queue;");
}
if (header.find("timer") != string::npos)
{
// Before including asm/cputime.h, we need to make sure it
// exists, which is tricky since we need the arch specific
// include directory.
string karch = s.architecture;
if (karch == "i386" || karch == "x86_64")
karch = "x86";
if (file_exists(s.kernel_build_tree + "/arch/" + karch
+ "/include/asm/cputime.h"))
they_live.push_back ("#include <asm/cputime.h>");
else if (!s.kernel_source_tree.empty()
&& file_exists(s.kernel_source_tree + "/arch/" + karch
+ "/include/asm/cputime.h"))
they_live.push_back ("#include <asm/cputime.h>");
}
// linux 3.0
they_live.push_back ("struct cpu_workqueue_struct;");
if (header.find("clk") != string::npos)
they_live.push_back ("struct clk_duty;");
if (header.find("fsi") != string::npos)
they_live.push_back ("struct fsi_master_acf;");
if (header.find("ib_") != string::npos) {
they_live.push_back ("struct ib_mad_hdr;");
they_live.push_back ("struct ib_user_mad_hdr;");
they_live.push_back ("struct ib_umad_file;");
if (header_exists(s, "/include/rdma/id_mad.h"))
they_live.push_back ("#include \"rdma/id_mad.h\"");
}
if (header.find("ext4") != string::npos
&& s.kernel_config["CONFIG_EXT4_FS"] != string("")
&& header_exists(s, "/fs/ext4/ext4.h"))
they_live.push_back ("#include \"fs/ext4/ext4.h\"");
if (header.find("ext3") != string::npos)
{
they_live.push_back ("struct ext3_reserve_window_node;");
they_live.push_back ("struct super_block;");
they_live.push_back ("struct dentry;");
}
if (header.find("workqueue") != string::npos)
{
they_live.push_back ("struct pool_workqueue;");
they_live.push_back ("struct work_struct;");
}
// Here we need the header file, since we need the snd_soc_dapm_path
// struct declared and the snd_soc_dapm_direction enum.
if (header.find("asoc") != string::npos)
{
if (header_exists(s, "/include/sound/soc.h"))
they_live.push_back ("#include \"sound/soc.h\"");
}
if (header.find("9p") != string::npos)
{
they_live.push_back ("struct p9_client;");
they_live.push_back ("struct p9_fcall;");
}
if (header.find("bcache") != string::npos)
{
they_live.push_back ("struct bkey;");
they_live.push_back ("struct btree;");
they_live.push_back ("struct cache_set;");
they_live.push_back ("struct cache;");
they_live.push_back ("struct bcache_device;");
}
if (header.find("f2fs") != string::npos)
{
// cannot get fs/f2fs/f2fs.h #included
they_live.push_back ("typedef u32 block_t;");
they_live.push_back ("typedef u32 nid_t;");
they_live.push_back ("struct f2fs_io_info;");
they_live.push_back ("struct f2fs_sb_info;");
they_live.push_back ("struct extent_info;");
they_live.push_back ("struct extent_node;");
they_live.push_back ("struct super_block;");
they_live.push_back ("struct buffer_head;");
they_live.push_back ("struct bio;");
}
if (header.find("radeon") != string::npos)
{
they_live.push_back ("struct radeon_bo;");
they_live.push_back ("struct radeon_bo_va;");
they_live.push_back ("struct radeon_cs_parser;");
they_live.push_back ("struct radeon_semaphore;");
}
// Argh, 3.11, i915_trace.h -> i915_drv.h -> i915_reg.h without
// -I. So, we have to add a custom -I flag.
if (header.find("i915_trace") != string::npos)
{
if (file_exists(s.kernel_build_tree + "/drivers/gpu/drm/i915"))
s.kernel_extra_cflags.push_back ("-I" + s.kernel_build_tree
+ "/drivers/gpu/drm/i915");
else if (!s.kernel_source_tree.empty()
&& file_exists(s.kernel_source_tree + "/drivers/gpu/drm/i915"))
s.kernel_extra_cflags.push_back ("-I" + s.kernel_source_tree
+ "/drivers/gpu/drm/i915");
if (file_exists(s.kernel_build_tree + "/drivers/gpu/drm/i915/gt"))
s.kernel_extra_cflags.push_back ("-I" + s.kernel_build_tree
+ "/drivers/gpu/drm/i915/gt");
else if (!s.kernel_source_tree.empty()
&& file_exists(s.kernel_source_tree + "/drivers/gpu/drm/i915/gt"))
s.kernel_extra_cflags.push_back ("-I" + s.kernel_source_tree
+ "/drivers/gpu/drm/i915/gt");
}
if (header.find("/ath/") != string::npos)
they_live.push_back ("struct ath5k_hw;");
if (header.find("nilfs2") != string::npos)
they_live.push_back ("struct nilfs_transaction_info;");
if (header.find("spi") != string::npos)
{
they_live.push_back ("struct spi_master;");
they_live.push_back ("struct spi_message;");
they_live.push_back ("struct spi_transfer;");
they_live.push_back ("struct spi_controller;");
}
if (header.find("thermal_power_allocator") != string::npos)
they_live.push_back ("struct thermal_zone_device;");
if (header.find("brcms_trace_brcmsmac") != string::npos)
they_live.push_back ("struct brcms_timer;");
if (header.find("hda_intel_trace") != string::npos)
they_live.push_back ("struct azx;");
if (header.find("v4l2") != string::npos)
they_live.push_back ("struct v4l2_buffer;");
if (header.find("pcm_trace") != string::npos
|| header.find("pcm_param_trace") != string::npos)
{
they_live.push_back ("struct snd_pcm_substream;");
they_live.push_back ("#include <sound/asound.h>");
}
// Here we need the header file, since we need the migrate_mode enum.
if (header.find("migrate") != string::npos
|| header.find("compaction") != string::npos)
{
if (header_exists(s, "/include/linux/migrate_mode.h"))
they_live.push_back ("#include <linux/migrate_mode.h>");
}
// include/trace/events/module.h is odd. If CREATE_TRACE_POINTS
// isn't defined, it doesn't define TRACE_SYSTEM, which means we
// we'll find the module tracepoints (like 'module_load'), but not
// realize they belong in the module subsystem (like
// 'module:module_load'). We'd like to define CREATE_TRACE_POINTS,
// but that causes compilation errors. So, we'll just define
// TRACE_SYSTEM ourselves.
if (header.find("events/module.h") != string::npos)
they_live.push_back ("#define TRACE_SYSTEM module");
if (header.find("events/net.h") != string::npos)
they_live.push_back ("struct ndmsg;");
if (header.find("iwl") != string::npos)
{
they_live.push_back ("struct iwl_cmd_header_wide;");
they_live.push_back ("struct iwl_host_cmd;");
they_live.push_back ("struct iwl_trans;");
they_live.push_back ("struct iwl_rx_packet;");
}
if (header.find("mdio") != string::npos)
{
if (header_exists(s, "/include/linux/phy.h"))
they_live.push_back ("#include <linux/phy.h>");
}
if (header.find("intel_iommu") != string::npos && s.architecture != "x86_64" && s.architecture != "i386")
{
// need asm/cacheflush.h for clflush_cache_range() used in that header,
// but this function does not exist on e.g. ppc
they_live.push_back ("#error nope");
}
if (header.find("wbt") != string::npos)
{
// blk-wbt.h gets included as "../../../block/blk-wbt.h", so we
// need an include path that is 3 levels deep. Note we can't use
// "include/linux/events", since its headers conflict with ours.
if (file_exists(s.kernel_build_tree + "/block/blk-wbt.h")
&& file_exists(s.kernel_build_tree + "/fs/xfs/libxfs"))
s.kernel_extra_cflags.push_back ("-I" + s.kernel_build_tree
+ "/fs/xfs/libxfs");
else if (!s.kernel_source_tree.empty()
&& file_exists(s.kernel_source_tree + "/block/blk-wbt.h")
&& file_exists(s.kernel_source_tree + "/fs/xfs/libxfs"))
s.kernel_extra_cflags.push_back ("-I" + s.kernel_source_tree
+ "/fs/xfs/libxfs");
if (header_exists(s, "/include/linux/blk_types.h"))
they_live.push_back ("#include <linux/blk_types.h>");
if (header_exists(s, "/include/linux/blkdev.h"))
they_live.push_back ("#include <linux/blkdev.h>");
}
if (header.find("swiotlb") != string::npos)
{
if (header_exists(s, "/include/linux/swiotlb.h"))
they_live.push_back ("#include <linux/swiotlb.h>");
}
if (header.find("afs") != string::npos)
{
if (header_exists (s, "/fs/afs/internal.h"))
they_live.push_back ("#include \"fs/afs/internal.h\"");
they_live.push_back ("struct afs_call;");
}
if (header.find("rxrpc") != string::npos)
{
they_live.push_back ("struct rxrpc_call;");
they_live.push_back ("struct rxrpc_connection;");
they_live.push_back ("struct rxrpc_seq_t;");
they_live.push_back ("struct rxrpc_serial_t;");
they_live.push_back ("struct rxrpc_skb_priv;");
// We need a definition of a 'rxrpc_seq_t', which is a typedef.
// So, we'll have to include the right kernel header file.
if (header_exists(s, "/net/rxrpc/protocol.h"))
they_live.push_back ("#include \"net/rxrpc/protocol.h\"");
if (header_exists (s, "/net/rxrpc/ar-internal.h"))
they_live.push_back ("#include \"net/rxrpc/ar-internal.h\"");
}
if (header.find("xdp") != string::npos)
{
they_live.push_back ("struct bpf_map;");
}
if (header.find("bridge") != string::npos)
{
// br_private.h gets included as
// "../../../net/bridge/br_private.h", so we need an include
// path that is 3 levels deep.
if (file_exists(s.kernel_build_tree + "/net/bridge/br_private.h")
&& file_exists(s.kernel_build_tree + "/fs/xfs/libxfs"))
s.kernel_extra_cflags.push_back ("-I" + s.kernel_build_tree
+ "/fs/xfs/libxfs");
else if (!s.kernel_source_tree.empty()
&& file_exists(s.kernel_source_tree + "/net/bridge/br_private.h")
&& file_exists(s.kernel_source_tree + "/fs/xfs/libxfs"))
s.kernel_extra_cflags.push_back ("-I" + s.kernel_source_tree
+ "/fs/xfs/libxfs");
}
if (header.find("fsi") != string::npos)
{
they_live.push_back ("struct fsi_master;");
they_live.push_back ("struct fsi_master_gpio;");
}
if (header.find("drm") != string::npos)
{
they_live.push_back ("struct drm_file;");
}
if (header.find("cachefiles") != string::npos ||
header.find("fscache") != string::npos)
{
they_live.push_back ("#include <linux/fscache.h>");
they_live.push_back ("#include <linux/fscache-cache.h>");
they_live.push_back ("struct cachefiles_object;"); // fs/cachefiles/internal.h
}
#if 0
/* This doesn't work as of 4.17ish, because it interferes with subsequent tracepoints
coming in from other trace headers. e.g. module:module_put vs mei:module_put. */
if (header_exists(s, "/drivers/misc/mei/mei-trace.h"))
they_live.push_back ("#include \"drivers/misc/mei/mei-trace.h\"");
#endif
if (header.find("gpu_scheduler") != string::npos)
{
they_live.push_back("#include <drm/gpu_scheduler.h>");
}
if (header.find("siox.h") != string::npos)
{
they_live.push_back ("struct siox_device;"); // #include "drivers/siox/siox.h"
they_live.push_back ("struct siox_master;"); // #include "drivers/siox/siox.h"
they_live.push_back ("struct rxrpc_local;"); // #include "drivers/siox/siox.h"
}
return they_live;
}
void
tracepoint_derived_probe_group::emit_module_decls (systemtap_session& s)
{
if (probes.empty())
return;
s.op->newline() << "/* ---- tracepoint probes ---- */";
s.op->newline() << "#include <linux/stp_tracepoint.h>" << endl;
s.op->newline();
// We create a MODULE_aux_N.c file for each tracepoint header, to allow them
// to be separately compiled. That's because kernel tracepoint headers sometimes
// conflict. PR13155.
map<string,translator_output*> per_header_aux;
// GC NB: the translator_output* structs are owned/retained by the systemtap_session.
for (unsigned i = 0; i < probes.size(); ++i)
{
tracepoint_derived_probe *p = probes[i];
string header = p->header;
// We cache the auxiliary output files on a per-header basis. We don't
// need one aux file per tracepoint, only one per tracepoint-header.
translator_output *tpop = per_header_aux[header];
if (tpop == 0)
{
tpop = s.op_create_auxiliary();
per_header_aux[header] = tpop;
// PR9993: Add extra headers to work around undeclared types in individual
// include/trace/foo.h files
const vector<string>& extra_decls = tracepoint_extra_decls (s, header,
false);
for (unsigned z=0; z<extra_decls.size(); z++)
tpop->newline() << extra_decls[z] << "\n";
// strip include/ substring, the same way as done in get_tracequery_module()
size_t root_pos = header.rfind("include/");
header = ((root_pos != string::npos) ? header.substr(root_pos + 8) : header);
tpop->newline() << "#include <linux/stp_tracepoint.h>" << endl;
tpop->newline() << "#include <" << header << ">";
}
// collect the args that are actually in use
vector<const tracepoint_arg*> used_args;
for (unsigned j = 0; j < p->args.size(); ++j)
if (p->args[j].used)
used_args.push_back(&p->args[j]);
// forward-declare the generated-side tracepoint callback, and define the
// generated-side tracepoint callback in the main translator-output
string enter_real_fn = "enter_real_tracepoint_probe_" + lex_cast(i);
if (used_args.empty())
{
tpop->newline() << "STP_TRACE_ENTER_REAL_NOARGS(" << enter_real_fn << ");";
s.op->newline() << "STP_TRACE_ENTER_REAL_NOARGS(" << enter_real_fn << ");";
s.op->newline() << "STP_TRACE_ENTER_REAL_NOARGS(" << enter_real_fn << ")";
}
else
{
tpop->newline() << "STP_TRACE_ENTER_REAL(" << enter_real_fn;
s.op->newline() << "STP_TRACE_ENTER_REAL(" << enter_real_fn;
s.op->indent(2);
for (unsigned j = 0; j < used_args.size(); ++j)
{
tpop->line() << ", int64_t";
s.op->newline() << ", int64_t __tracepoint_arg_" << used_args[j]->name;
}
tpop->line() << ");";
s.op->newline() << ");";
s.op->indent(-2);
s.op->newline() << "STP_TRACE_ENTER_REAL(" << enter_real_fn;
s.op->indent(2);
for (unsigned j = 0; j < used_args.size(); ++j)
{
s.op->newline() << ", int64_t __tracepoint_arg_" << used_args[j]->name;
}
s.op->newline() << ")";
s.op->indent(-2);
}
s.op->newline() << "{";
s.op->newline(1) << "const struct stap_probe * const probe = "
<< common_probe_init (p) << ";";
common_probe_entryfn_prologue (s, "STAP_SESSION_RUNNING", "", "probe",
"stp_probe_type_tracepoint");
s.op->newline() << "c->ips.tp.tracepoint_system = "
<< lex_cast_qstring (p->tracepoint_system)
<< ";";
s.op->newline() << "c->ips.tp.tracepoint_name = "
<< lex_cast_qstring (p->tracepoint_name)
<< ";";
for (unsigned j = 0; j < used_args.size(); ++j)
{
s.op->newline() << "c->probe_locals." << p->name()
<< "." + s.up->c_localname("__tracepoint_arg_" + used_args[j]->name)
<< " = __tracepoint_arg_" << used_args[j]->name << ";";
}
s.op->newline() << "(*probe->ph) (c);";
common_probe_entryfn_epilogue (s, true, otf_safe_context(s));
s.op->newline(-1) << "}";
// define the real tracepoint callback function
string enter_fn = "enter_tracepoint_probe_" + lex_cast(i);
if (p->args.empty())
tpop->newline() << "static STP_TRACE_ENTER_NOARGS(" << enter_fn << ")";
else
{
tpop->newline() << "static STP_TRACE_ENTER(" << enter_fn;
s.op->indent(2);
for (unsigned j = 0; j < p->args.size(); ++j)
tpop->newline() << ", " << p->args[j].c_decl;
tpop->newline() << ")";
s.op->indent(-2);
}
tpop->newline() << "{";
tpop->newline(1) << enter_real_fn << "(";
tpop->indent(2);
for (unsigned j = 0; j < used_args.size(); ++j)
{
if (j > 0)
tpop->line() << ", ";
tpop->newline() << "(int64_t)" << used_args[j]->typecast
<< "__tracepoint_arg_" << used_args[j]->name;
}
tpop->newline() << ");";
tpop->newline(-3) << "}";
// emit normalized registration functions
s.op->newline() << "int register_tracepoint_probe_" << i << "(void);";
tpop->newline() << "int register_tracepoint_probe_" << i << "(void);" << endl;
tpop->newline() << "int register_tracepoint_probe_" << i << "(void) {";
tpop->newline(1) << "return STP_TRACE_REGISTER(" << p->tracepoint_name
<< ", " << enter_fn << ");";
tpop->newline(-1) << "}";
// NB: we're not prepared to deal with unreg failures. However, failures
// can only occur if the tracepoint doesn't exist (yet?), or if we
// weren't even registered. The former should be OKed by the initial
// registration call, and the latter is safe to ignore.
// declare normalized registration functions
s.op->newline() << "void unregister_tracepoint_probe_" << i << "(void);";
tpop->newline() << "void unregister_tracepoint_probe_" << i << "(void);" << endl;
tpop->newline() << "void unregister_tracepoint_probe_" << i << "(void) {";
tpop->newline(1) << "(void) STP_TRACE_UNREGISTER(" << p->tracepoint_name
<< ", " << enter_fn << ");";
tpop->newline(-1) << "}";
tpop->newline();
tpop->assert_0_indent();
}
// emit an array of registration functions for easy init/shutdown
s.op->newline() << "static struct stap_tracepoint_probe {";
s.op->newline(1) << "int (*reg)(void);";
s.op->newline(0) << "void (*unreg)(void);";
s.op->newline(-1) << "} stap_tracepoint_probes[] = {";
s.op->indent(1);
for (unsigned i = 0; i < probes.size(); ++i)
{
s.op->newline () << "{";
s.op->line() << " .reg=®ister_tracepoint_probe_" << i << ",";
s.op->line() << " .unreg=&unregister_tracepoint_probe_" << i;
s.op->line() << " },";
}
s.op->newline(-1) << "};";
s.op->newline();
}
void
tracepoint_derived_probe_group::emit_module_init (systemtap_session &s)
{
if (probes.size () == 0)
return;
s.op->newline() << "/* init tracepoint probes */";
s.op->newline() << "for (i=0; i<" << probes.size() << "; i++) {";
s.op->newline(1) << "rc = stap_tracepoint_probes[i].reg();";
s.op->newline() << "if (rc) {";
s.op->newline(1) << "for (j=i-1; j>=0; j--)"; // partial rollback
s.op->newline(1) << "stap_tracepoint_probes[j].unreg();";
s.op->newline(-1) << "break;"; // don't attempt to register any more probes
s.op->newline(-1) << "}";
s.op->newline(-1) << "}";
// Modern kernels' tracepoint implementation makes use of SRCU and
// their tracepoint_synchronize_unregister() function calls
// synchronize_srcu(&tracepoint_srcu) right before calling synchronize_rcu().
// So it's safer to always call tracepoint_synchronize_unregister() to avoid
// any risks.
s.op->newline() << "if (rc)";
s.op->newline(1) << "tracepoint_synchronize_unregister();";
s.op->indent(-1);
}
void
tracepoint_derived_probe_group::emit_module_exit (systemtap_session& s)
{
if (probes.empty())
return;
s.op->newline() << "/* deregister tracepoint probes */";
s.op->newline() << "for (i=0; i<" << probes.size() << "; i++)";
s.op->newline(1) << "stap_tracepoint_probes[i].unreg();";
s.op->indent(-1);
// This is necessary: see above.
s.op->newline() << "tracepoint_synchronize_unregister();";
}
struct tracepoint_query : public base_query
{
probe * base_probe;
probe_point * base_loc;
vector<derived_probe *> & results;
set<string> probed_names;
void handle_query_module();
int handle_query_cu(Dwarf_Die * cudie);
int handle_query_func(Dwarf_Die * func);
int handle_query_type(Dwarf_Die * type);
int handle_query_type_syscall_events(Dwarf_Die * cudie);
void query_library (const char *) {}
void query_plt (const char *, size_t) {}
static int tracepoint_query_cu (Dwarf_Die * cudie, tracepoint_query * q);
static int tracepoint_query_func (Dwarf_Die * func, tracepoint_query * q);
static int tracepoint_query_type (Dwarf_Die * type,
bool has_inner_types,
const std::string& prefix,
tracepoint_query * q);
tracepoint_query(dwflpp & dw, const string & tracepoint,
probe * base_probe, probe_point * base_loc,
vector<derived_probe *> & results):
base_query(dw, "*"), base_probe(base_probe),
base_loc(base_loc), results(results)
{
// The user may have specified the system to probe, e.g. all of the
// following are possible:
//
// sched_switch --> tracepoint named sched_switch
// sched:sched_switch --> tracepoint named sched_switch in the sched system
// sch*:sched_* --> system starts with sch and tracepoint starts with sched_
// sched:* --> all tracepoints in system sched
// *:sched_switch --> same as just sched_switch
size_t sys_pos = tracepoint.find(':');
if (sys_pos == string::npos)
{
this->system = "";
this->tracepoint = tracepoint;
}
else
{
if (strverscmp(sess.compatible.c_str(), "2.6") <= 0)
throw SEMANTIC_ERROR (_("SYSTEM:TRACEPOINT syntax not supported "
"with --compatible <= 2.6"));
this->system = tracepoint.substr(0, sys_pos);
this->tracepoint = tracepoint.substr(sys_pos+1);
}
// make sure we have something to query (filters out e.g. "" and ":")
if (this->tracepoint.empty())
throw SEMANTIC_ERROR (_("invalid tracepoint string provided"));
}
private:
string system; // target subsystem(s) to query
string tracepoint; // target tracepoint(s) to query
string current_system; // subsystem of module currently being visited
string retrieve_trace_system();
};
// name of section where TRACE_SYSTEM is stored
// (see tracepoint_builder::get_tracequery_modules())
#define STAP_TRACE_SYSTEM ".stap_trace_system"
string
tracepoint_query::retrieve_trace_system()
{
Dwarf_Addr bias;
Elf* elf = dwfl_module_getelf(dw.module, &bias);
if (!elf)
return "";
size_t shstrndx;
if (elf_getshdrstrndx(elf, &shstrndx))
return "";
Elf_Scn *scn = NULL;
GElf_Shdr shdr_mem;
while ((scn = elf_nextscn(elf, scn)))
{
if (gelf_getshdr(scn, &shdr_mem) == NULL)
return "";
const char *name = elf_strptr(elf, shstrndx, shdr_mem.sh_name);
if (name == NULL)
return "";
if (strcmp(name, STAP_TRACE_SYSTEM) == 0)
break;
}
if (scn == NULL)
return "";
// Extract saved TRACE_SYSTEM in section
Elf_Data *data = elf_getdata(scn, NULL);
if (!data)
return "";
return string((char*)data->d_buf);
}
void
tracepoint_query::handle_query_module()
{
// Get the TRACE_SYSTEM for this module, if any. It will be found in the
// STAP_TRACE_SYSTEM section if it exists.
current_system = retrieve_trace_system();
// check if user wants a specific system
if (!system.empty())
{
// don't need to go further if module has no system or doesn't
// match the one we want
if (current_system.empty()
|| !dw.function_name_matches_pattern(current_system, system))
return;
}
// look for the tracepoints in each CU
dw.iterate_over_cus(tracepoint_query_cu, this, false);
}
int
tracepoint_query::handle_query_cu(Dwarf_Die * cudie)
{
dw.focus_on_cu (cudie);
dw.mod_info->get_symtab();
// look at each type to see if it's a tracepoint
if (dw.sess.runtime_mode == dw.sess.systemtap_session::bpf_runtime)
{
if (0 && current_system == "raw_syscalls")
// In BPF / trace_events world, syscalls are abstracted from
// the TRACE_EVENT_FN() (pure callbacks), via
// kernel/trace/trace_syscalls.stp into a family of trace
// events (demultiplexed by syscall id#). There is a
// standardized event-field structure that does -not- show up
// in these header files, nor in the vmlinux file, but are
// synthesized/registered at kernel boot time.
return handle_query_type_syscall_events (cudie);
else
return dwflpp::iterate_over_globals (cudie, tracepoint_query_type, this);
}
// look at each function to see if it's a tracepoint
string function = "stapprobe_" + tracepoint;
return dw.iterate_over_functions (tracepoint_query_func, this, function);
}
int
tracepoint_query::handle_query_func(Dwarf_Die * func)
{
dw.focus_on_function (func);
assert(startswith(dw.function_name, "stapprobe_"));
string tracepoint_instance = dw.function_name.substr(10);
// check for duplicates -- sometimes tracepoint headers may be indirectly
// included in more than one of our tracequery modules.
if (!probed_names.insert(tracepoint_instance).second)
return DWARF_CB_OK;
// PR17126: blocklist
if (!sess.guru_mode)
{
if ((sess.architecture.substr(0,3) == "ppc" ||
sess.architecture.substr(0,7) == "powerpc") &&
(tracepoint_instance == "hcall_entry" ||
tracepoint_instance == "hcall_exit" ||
tracepoint_instance == "hash_fault"))
{
sess.print_warning(_F("tracepoint %s is blocklisted on architecture %s",
tracepoint_instance.c_str(), sess.architecture.c_str()));
return DWARF_CB_OK;
}
}
derived_probe *dp = new tracepoint_derived_probe (dw.sess, dw, *func,
current_system,
tracepoint_instance,
base_probe, base_loc);
results.push_back (dp);
return DWARF_CB_OK;
}
int
tracepoint_query::handle_query_type(Dwarf_Die * type)
{
Dwarf_Die struct_die = *type;
if (!dwarf_hasattr(type, DW_AT_name))
return DWARF_CB_OK;
std::string name(dwarf_diename(type) ?: "<unknown type>");
if (!dw.function_name_matches_pattern(name, "stapprobe_" + tracepoint)
|| startswith(name, "stapprobe_template_"))
return DWARF_CB_OK;
name = name.substr(10);
// get the corresponding structure die
while (dwarf_tag(&struct_die) == DW_TAG_typedef)
{
if (dwarf_attr_die(&struct_die, DW_AT_type, &struct_die) == NULL)
throw SEMANTIC_ERROR(_F("Unable to resolve base type of %s for probe %s\n",
name.c_str(), tracepoint.c_str()));
}
assert(dwarf_tag(&struct_die) == DW_TAG_structure_type);
// check for duplicates -- sometimes tracepoint headers may be indirectly
// included in more than one of our tracequery modules.
if (!probed_names.insert(name).second)
return DWARF_CB_OK;
derived_probe *dp = new tracepoint_derived_probe(dw.sess, dw, struct_die,
current_system, name,
base_probe, base_loc);
results.push_back(dp);
return DWARF_CB_OK;
}
int
tracepoint_query::handle_query_type_syscall_events(Dwarf_Die * cudie)
{
(void) cudie;
return DWARF_CB_OK;
}
int
tracepoint_query::tracepoint_query_cu (Dwarf_Die * cudie, tracepoint_query * q)
{
if (pending_interrupts) return DWARF_CB_ABORT;
return q->handle_query_cu(cudie);
}
int
tracepoint_query::tracepoint_query_func (Dwarf_Die * func, tracepoint_query * q)
{
if (pending_interrupts) return DWARF_CB_ABORT;
return q->handle_query_func(func);
}
int
tracepoint_query::tracepoint_query_type (Dwarf_Die *type, bool has_inner_types,
const std::string& prefix, tracepoint_query *q)
{
// needed to match signature of dwflpp::iterate_over_globals callback
(void) has_inner_types;
(void) prefix;
if (pending_interrupts) return DWARF_CB_ABORT;
return q->handle_query_type(type);
}
struct tracepoint_builder: public derived_probe_builder
{
private:
dwflpp *dw;
bool init_dw(systemtap_session& s);
void get_tracequery_modules(systemtap_session& s,
const vector<string>& headers,
vector<string>& modules);
public:
tracepoint_builder(): dw(0) {}
~tracepoint_builder() { delete dw; }
void build_no_more (systemtap_session& s)
{
if (dw && s.verbose > 3)
clog << _("tracepoint_builder releasing dwflpp") << endl;
delete dw;
dw = NULL;
delete_session_module_cache (s);
}
void build(systemtap_session& s,
probe *base, probe_point *location,
literal_map_t const& parameters,
vector<derived_probe*>& finished_results);
virtual string name() { return "tracepoint builder"; }
};
// Create (or cache) one or more tracequery .o modules, based upon the
// tracepoint-related header files given. Return the generated or cached
// modules[].
void
tracepoint_builder::get_tracequery_modules(systemtap_session& s,
const vector<string>& headers,
vector<string>& modules)
{
if (s.verbose > 2)
{
clog << _F("Pass 2: getting a tracepoint query for %zu headers: ", headers.size()) << endl;
for (size_t i = 0; i < headers.size(); ++i)
clog << " " << headers[i] << endl;
}
map<string,string> headers_cache_obj; // header name -> cache/.../tracequery_hash.o file name
// Map the headers to cache .o names. Note that this has side-effects of
// creating the $SYSTEMTAP_DIR/.cache/XX/... directory and the hash-log file,
// so we prefer not to repeat this.
vector<string> uncached_headers;
for (size_t i=0; i<headers.size(); i++)
headers_cache_obj[headers[i]] = find_tracequery_hash(s, headers[i]);
// They may be in the cache already.
if (s.use_cache && !s.poison_cache)
for (size_t i=0; i<headers.size(); i++)
{
// see if the cached module exists
const string& tracequery_path = headers_cache_obj[headers[i]];
if (!tracequery_path.empty() && file_exists(tracequery_path))
{
if (s.verbose > 2)
clog << _F("Pass 2: using cached %s", tracequery_path.c_str()) << endl;
// an empty file is a cached failure
if (get_file_size(tracequery_path) > 0)
modules.push_back (tracequery_path);
}
else
uncached_headers.push_back(headers[i]);
}
else
uncached_headers = headers;
// If we have nothing left to search for, quit
if (uncached_headers.empty()) return;
map<string,string> headers_tracequery_src; // header -> C-source code mapping
// We could query several subsets of headers[] to make this go
// faster, but let's KISS and do one at a time.
for (size_t i=0; i<uncached_headers.size(); i++)
{
const string& header = uncached_headers[i];
// create a tracequery source file
ostringstream osrc;
// PR9993: Add extra headers to work around undeclared types in individual
// include/trace/foo.h files
vector<string> short_decls = tracepoint_extra_decls(s, header, true);
// add each requested tracepoint header
size_t root_pos = header.rfind("include/");
short_decls.push_back(string("#include <") +
((root_pos != string::npos) ? header.substr(root_pos + 8) : header) +
string(">"));
osrc << "#ifdef CONFIG_TRACEPOINTS" << endl;
osrc << "#include <linux/tracepoint.h>" << endl;
// BPF raw tracepoint macros for creating the multiple fields
// of the data struct that describes the raw tracepoint.
// These macros counts up to 12. Any more, it will return 13th argument.
// These macros will likely have issues with raw tracepoints with more than 12 arguments.
osrc << "#define __COUNT_ARGS(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _n, X...) _n" << endl;
osrc << "#define COUNT_ARGS(X...) __COUNT_ARGS(, ##X, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0)" << endl;
osrc << "#define __CONCAT(a, b) a ## b" << endl;
osrc << "#define CONCATENATE(a, b) __CONCAT(a, b)" << endl;
osrc << "#define __FIELD_ENTRY(x) x __attribute__ ((aligned (8)))" << endl;
osrc << "#define __FIELD1(a,...) __FIELD_ENTRY(a);" << endl;
osrc << "#define __FIELD2(a,...) __FIELD_ENTRY(a); __FIELD1(__VA_ARGS__)" << endl;
osrc << "#define __FIELD3(a,...) __FIELD_ENTRY(a); __FIELD2(__VA_ARGS__)" << endl;
osrc << "#define __FIELD4(a,...) __FIELD_ENTRY(a); __FIELD3(__VA_ARGS__)" << endl;
osrc << "#define __FIELD5(a,...) __FIELD_ENTRY(a); __FIELD4(__VA_ARGS__)" << endl;
osrc << "#define __FIELD6(a,...) __FIELD_ENTRY(a); __FIELD5(__VA_ARGS__)" << endl;
osrc << "#define __FIELD7(a,...) __FIELD_ENTRY(a); __FIELD6(__VA_ARGS__)" << endl;
osrc << "#define __FIELD8(a,...) __FIELD_ENTRY(a); __FIELD7(__VA_ARGS__)" << endl;
osrc << "#define __FIELD9(a,...) __FIELD_ENTRY(a); __FIELD8(__VA_ARGS__)" << endl;
osrc << "#define __FIELD10(a,...) __FIELD_ENTRY(a); __FIELD9(__VA_ARGS__)" << endl;
osrc << "#define __FIELD11(a,...) __FIELD_ENTRY(a); __FIELD10(__VA_ARGS__)" << endl;
osrc << "#define __FIELD12(a,...) __FIELD_ENTRY(a); __FIELD11(__VA_ARGS__)" << endl;
osrc << "#define FIELDS(...) CONCATENATE(__FIELD, COUNT_ARGS(__VA_ARGS__))(__VA_ARGS__)" << endl;
// The following PARAMS and DECLARE_TRACE_* macros are used
// by both linux kernel module and bpf raw tracepoints.
// The kernel has changed this naming a few times, previously TPPROTO,
// TP_PROTO, TPARGS, TP_ARGS, etc. so let's just dupe the latest.
osrc << "#ifndef PARAMS" << endl;
osrc << "#define PARAMS(args...) args" << endl;
osrc << "#endif" << endl;
// 2.6.35 added the NOARGS variant, but it's the same for us
osrc << "#undef DECLARE_TRACE_NOARGS" << endl;
osrc << "#define DECLARE_TRACE_NOARGS(name) \\" << endl;
osrc << " DECLARE_TRACE(name, void, )" << endl;
// 2.6.38 added the CONDITION variant, which can also just redirect
osrc << "#undef DECLARE_TRACE_CONDITION" << endl;
osrc << "#define DECLARE_TRACE_CONDITION(name, proto, args, cond) \\" << endl;
osrc << " DECLARE_TRACE(name, PARAMS(proto), PARAMS(args))" << endl;
// older tracepoints used DEFINE_TRACE, so redirect that too
osrc << "#undef DEFINE_TRACE" << endl;
osrc << "#define DEFINE_TRACE(name, proto, args) \\" << endl;
osrc << " DECLARE_TRACE(name, PARAMS(proto), PARAMS(args))" << endl;
// Macros to help build the struct describing the older cooked bpf tracepoints
osrc << "#undef __field" << endl;
osrc << "#define __field(type, item) type item;" << endl;
osrc << "#undef __field_desc" << endl;
osrc << "#define __field_desc(type, container, item) type item;" << endl;
osrc << "#undef __array" << endl;
osrc << "#define __array(type, item, size) type item[size];" << endl;
osrc << "#undef __array_desc" << endl;
osrc << "#define __array_desc(type, container, item, size) type item[size];" << endl;
osrc << "#undef __dynamic_array" << endl;
osrc << "#define __dynamic_array(type, item, len) u32 item;" << endl;
osrc << "#undef __string" << endl;
osrc << "#define __string(item, src) __dynamic_array(char, item, -1)" << endl;
osrc << "#undef __bitmask" << endl;
osrc << "#define __bitmask(item, nr_bits) __dynamic_array(char, item, -1)" << endl;
osrc << "#undef TP_STRUCT__entry" << endl;
osrc << "#define TP_STRUCT__entry(args...) args" << endl;
if (s.runtime_mode != systemtap_session::bpf_runtime) {
// override DECLARE_TRACE to synthesize probe functions for us
osrc << "#undef DECLARE_TRACE" << endl;
osrc << "#define DECLARE_TRACE(name, proto, args) \\" << endl;
osrc << " void stapprobe_##name(proto); \\" << endl;
osrc << " void stapprobe_##name(proto) {}" << endl;
} else {
if (s.use_bpf_raw_tracepoint) {
// override DECLARE_TRACE to synthesize struct for the bpf raw tracepoint
osrc << "#undef DECLARE_TRACE" << endl;
osrc << "#define DECLARE_TRACE(name, proto, args) \\" << endl;
osrc << " struct stapprobe_##name { struct { FIELDS(proto) } data; } stapprobe_##name;" << endl;
} else {
// Macros to create structure for older cooked bpf tracepoints
// Similar to above, but instantiates structs instead of functions.
// The members will become tracepoint args.
osrc << "#undef DECLARE_EVENT_CLASS" << endl;
osrc << "#define DECLARE_EVENT_CLASS(name, proto, args, tstruct, assign, print) \\" << endl;
osrc << " struct stapprobe_template_##name { unsigned long long pad; struct { tstruct } data; };" << endl;
// typedef helps us access template's debuginfo when given name's debuginfo
osrc << "#undef DEFINE_EVENT" << endl;
osrc << "#define DEFINE_EVENT(template, name, proto, args) \\" << endl;
osrc << " typedef struct stapprobe_template_##template stapprobe_##name; \\" << endl;
osrc << " stapprobe_##name stapprobe_inst_##name;" << endl;
osrc << "#undef TRACE_EVENT" << endl;
osrc << "#define TRACE_EVENT(name, proto, args, tstruct, assign, print) \\" << endl;
osrc << " struct stapprobe_##name { unsigned long long pad; struct { tstruct } data; } stapprobe_##name;" << endl;
osrc << "#undef TRACE_EVENT_FN" << endl;
osrc << "#define TRACE_EVENT_FN(name, proto, args, tstruct, assign, print, reg, unreg) \\" << endl;
osrc << " struct stapprobe_##name { unsigned long long pad; struct { tstruct } data; } stapprobe_##name;" << endl;
osrc << "#undef TRACE_EVENT_CONDITION" << endl;
osrc << "#define TRACE_EVENT_CONDITION(name, proto, args, cond, tstruct, assign, print) \\" << endl;
osrc << " struct stapprobe_##name { unsigned long long pad; struct { tstruct } data; } stapprobe_##name;" << endl;
}
}
// add the specified decls/#includes
for (unsigned z=0; z<short_decls.size(); z++)
osrc << "#undef TRACE_INCLUDE_FILE\n"
<< "#undef TRACE_INCLUDE_PATH\n"
<< short_decls[z] << "\n";
// create a section that will hold the TRACE_SYSTEM for this header
osrc << "#ifdef TRACE_SYSTEM" << endl;
osrc << "const char stap_trace_system[]" << endl;
osrc << " __attribute__((section(\"" STAP_TRACE_SYSTEM "\")))" << endl;
osrc << " = __stringify(TRACE_SYSTEM);" << endl;
osrc << "#endif" << endl;
// finish up the module source
osrc << "#endif /* CONFIG_TRACEPOINTS */" << endl;
// save the source file away
headers_tracequery_src[header] = osrc.str();
}
// now build them all together
map<string,string> tracequery_objs = make_tracequeries(s, headers_tracequery_src);
// now extend the modules list, and maybe plop them into the cache
for (size_t i=0; i<uncached_headers.size(); i++)
{
const string& header = uncached_headers[i];
const string& tracequery_obj = tracequery_objs[header];
const string& tracequery_path = headers_cache_obj[header];
if (tracequery_obj !="" && file_exists(tracequery_obj))
{
modules.push_back (tracequery_obj);
if (s.use_cache)
copy_file(tracequery_obj, tracequery_path, s.verbose > 2);
}
else if (s.use_cache)
// cache an empty file for failures
copy_file("/dev/null", tracequery_path, s.verbose > 2);
}
}
bool
tracepoint_builder::init_dw(systemtap_session& s)
{
if (dw != NULL)
return true;
vector<string> tracequery_modules;
vector<string> system_headers;
glob_t trace_glob;
// find kernel_source_tree from DW_AT_comp_dir
if (s.kernel_source_tree == "")
{
unsigned found;
Dwfl *dwfl = setup_dwfl_kernel ("kernel", &found, s);
if (found)
{
Dwarf_Die *cudie = 0;
Dwarf_Addr bias;
while ((cudie = dwfl_nextcu (dwfl, cudie, &bias)) != NULL)
{
assert_no_interrupts();
Dwarf_Attribute attr;
const char* name = dwarf_formstring (dwarf_attr (cudie, DW_AT_comp_dir, &attr));
if (name)
{
// Before we try to use it, check that the path actually
// exists locally and is distinct from the build tree.
if (!file_exists(name))
{
if (s.verbose > 2)
clog << _F("Ignoring inaccessible kernel source tree (DW_AT_comp_dir) at '%s'", name) << endl;
}
else if (resolve_path(name) == resolve_path(s.kernel_build_tree))
{
if (s.verbose > 2)
clog << _F("Ignoring duplicate kernel source tree (DW_AT_comp_dir) at '%s'", name) << endl;
}
else
{
if (s.verbose > 2)
clog << _F("Located kernel source tree (DW_AT_comp_dir) at '%s'", name) << endl;
s.kernel_source_tree = name;
}
break; // skip others; modern Kbuild uses same comp_dir for them all
}
}
}
dwfl_end (dwfl);
}
// find kernel_source_tree from a source link, when different from build
if (s.kernel_source_tree == "")
{
vector<string> source_trees;
// vendor kernel (e.g. Fedora): the source link is in the same dir
// as the build tree
if (endswith(s.kernel_build_tree, "/build"))
{
string source_tree = s.kernel_build_tree;
source_tree.replace(source_tree.length() - 5, 5, "source");
source_trees.push_back(source_tree);
}
// vanilla kernel: the source link is in the build tree
source_trees.push_back(s.kernel_build_tree + "/source");
for (unsigned i = 0; i < source_trees.size(); i++)
{
string source_tree = source_trees[i];
if (dir_exists(source_tree) &&
resolve_path(source_tree) != resolve_path(s.kernel_build_tree))
{
if (s.verbose > 2)
clog << _F("Located kernel source tree at '%s'", source_tree.c_str()) << endl;
s.kernel_source_tree = source_tree;
break;
}
}
}
// prefixes
vector<string> glob_prefixes;
glob_prefixes.push_back (s.kernel_build_tree);
if (s.kernel_source_tree != "")
glob_prefixes.push_back (s.kernel_source_tree);
// suffixes
vector<string> glob_suffixes;
glob_suffixes.push_back("include/trace/events/*.h");
glob_suffixes.push_back("include/trace/*.h");
glob_suffixes.push_back("include/ras/*_event.h");
glob_suffixes.push_back("arch/x86/entry/vsyscall/*trace.h");
glob_suffixes.push_back("arch/x86/kernel/*trace.h");
glob_suffixes.push_back("arch/*/include/asm/*trace*.h");
glob_suffixes.push_back("arch/*/include/asm/trace/*.h");
glob_suffixes.push_back("arch/*/kvm/*trace.h");
glob_suffixes.push_back("fs/xfs/linux-*/xfs_tr*.h");
glob_suffixes.push_back("fs/*/*trace*.h");
glob_suffixes.push_back("net/*/*trace*.h");
glob_suffixes.push_back("sound/core/*_trace.h");
glob_suffixes.push_back("sound/hda/*trace*.h");
glob_suffixes.push_back("sound/pci/hda/*_trace.h");
glob_suffixes.push_back("drivers/base/regmap/*trace*.h");
glob_suffixes.push_back("drivers/gpu/drm/*_trace.h");
glob_suffixes.push_back("drivers/gpu/drm/*/*_trace.h");
glob_suffixes.push_back("drivers/net/wireless/*/*/*trace*.h");
glob_suffixes.push_back("drivers/usb/host/*trace*.h");
glob_suffixes.push_back("virt/kvm/*/*trace*.h");
// see also tracepoint_extra_decls above
// compute cartesian product
vector<string> globs;
for (unsigned i=0; i<glob_prefixes.size(); i++)
for (unsigned j=0; j<glob_suffixes.size(); j++)
globs.push_back (glob_prefixes[i]+string("/")+glob_suffixes[j]);
set<string> duped_headers;
for (unsigned z = 0; z < globs.size(); z++)
{
string glob_str = globs[z];
if (s.verbose > 3)
clog << _("Checking tracepoint glob ") << glob_str << endl;
int r = glob(glob_str.c_str(), 0, NULL, &trace_glob);
if (r == GLOB_NOSPACE || r == GLOB_ABORTED)
throw runtime_error("Error globbing tracepoint");
for (unsigned i = 0; i < trace_glob.gl_pathc; ++i)
{
string header(trace_glob.gl_pathv[i]);
// filter out a few known "internal-only" headers
if (endswith(header, "/define_trace.h") ||
endswith(header, "/ftrace.h") ||
endswith(header, "/trace_events.h") ||
endswith(header, "/perf.h") ||
endswith(header, "_event_types.h"))
continue;
// Skip identical headers from the build and source trees.
// NB: For the moment these are only compared by reduced path, since
// get_tracequery_modules and emit_module_decls also reduce the path
// like this for their #includes. If we want to get fancier, like
// comparing file contents, then those functions will also have to be
// more precise in how they #include.
size_t root_pos = header.rfind("include/");
if (root_pos != string::npos &&
!duped_headers.insert(header.substr(root_pos + 8)).second)
continue;
system_headers.push_back(header);
}
globfree(&trace_glob);
}
// Build tracequery modules
get_tracequery_modules(s, system_headers, tracequery_modules);
// TODO: consider other sources of tracepoint headers too, like from
// a command-line parameter or some environment or .systemtaprc
dw = new dwflpp(s, tracequery_modules, true);
return true;
}
void
tracepoint_builder::build(systemtap_session& s,
probe *base, probe_point *location,
literal_map_t const& parameters,
vector<derived_probe*>& finished_results)
{
if (s.runtime_mode == systemtap_session::bpf_runtime &&
strverscmp(s.compatible.c_str(), "4.2") >= 0) {
s.use_bpf_raw_tracepoint =
(s.kernel_functions.count("bpf_raw_tracepoint_release") > 0) ||
(s.kernel_functions.count("bpf_raw_tp_link_release") > 0);
if (!s.use_bpf_raw_tracepoint)
throw SEMANTIC_ERROR (_("SYSTEM: new BPF TRACEPOINT behavior not supported "
"by target kernel (or use --compatible=4.1 option)"));
}
if (!init_dw(s))
return;
interned_string tracepoint;
assert(get_param (parameters, TOK_TRACE, tracepoint));
tracepoint_query q(*dw, tracepoint, base, location, finished_results);
unsigned results_pre = finished_results.size();
dw->iterate_over_modules<base_query>(&query_module, &q);
unsigned results_post = finished_results.size();
// Did we fail to find a match? Let's suggest something!
if (results_pre == results_post)
{
size_t pos;
string sugs = suggest_dwarf_functions(s, q.visited_modules, tracepoint);
while ((pos = sugs.find("stapprobe_")) != string::npos)
sugs.erase(pos, string("stapprobe_").size());
if (!sugs.empty())
throw SEMANTIC_ERROR (_NF("no match (similar tracepoint: %s)",
"no match (similar tracepoints: %s)",
sugs.find(',') == string::npos,
sugs.c_str()));
}
}
bool
sort_for_bpf(systemtap_session& s,
tracepoint_derived_probe_group *t,
sort_for_bpf_probe_arg_vector &v)
{
string tracepoint_flavor = (s.runtime_mode == systemtap_session::bpf_runtime && s.use_bpf_raw_tracepoint) ? "raw_trace/" : "trace/";
if (!t)
return false;
for (auto i = t->probes.begin(); i != t->probes.end(); ++i)
{
tracepoint_derived_probe *p = *i;
v.push_back(std::pair<derived_probe *, std::string>
(p, tracepoint_flavor + p->tracepoint_system + "/" + p->tracepoint_name));
}
return true;
}
// ------------------------------------------------------------------------
// Standard tapset registry.
// ------------------------------------------------------------------------
void
register_standard_tapsets(systemtap_session & s)
{
register_tapset_been(s);
register_tapset_mark(s);
register_tapset_procfs(s);
register_tapset_timers(s);
register_tapset_netfilter(s);
register_tapset_utrace(s);
register_tapset_debuginfod(s);
// dwarf-based kprobe/uprobe parts
dwarf_derived_probe::register_patterns(s);
// XXX: user-space starter set
s.pattern_root->bind_num(TOK_PROCESS)
->bind_num(TOK_STATEMENT)->bind(TOK_ABSOLUTE)
->bind_privilege(pr_all)
->bind(new uprobe_builder ());
s.pattern_root->bind_num(TOK_PROCESS)
->bind_num(TOK_STATEMENT)->bind(TOK_ABSOLUTE)->bind(TOK_RETURN)
->bind_privilege(pr_all)
->bind(new uprobe_builder ());
// kernel tracepoint probes
s.pattern_root->bind(TOK_KERNEL)->bind_str(TOK_TRACE)
->bind(new tracepoint_builder());
// Kprobe based probe
s.pattern_root->bind(TOK_KPROBE)->bind_str(TOK_FUNCTION)
->bind(new kprobe_builder());
s.pattern_root->bind(TOK_KPROBE)->bind_str(TOK_FUNCTION)->bind(TOK_CALL)
->bind(new kprobe_builder());
s.pattern_root->bind(TOK_KPROBE)->bind_str(TOK_MODULE)
->bind_str(TOK_FUNCTION)->bind(new kprobe_builder());
s.pattern_root->bind(TOK_KPROBE)->bind_str(TOK_MODULE)
->bind_str(TOK_FUNCTION)->bind(TOK_CALL)->bind(new kprobe_builder());
s.pattern_root->bind(TOK_KPROBE)->bind_str(TOK_FUNCTION)->bind(TOK_RETURN)
->bind(new kprobe_builder());
s.pattern_root->bind(TOK_KPROBE)->bind_str(TOK_FUNCTION)->bind(TOK_RETURN)
->bind_num(TOK_MAXACTIVE)->bind(new kprobe_builder());
s.pattern_root->bind(TOK_KPROBE)->bind_str(TOK_MODULE)
->bind_str(TOK_FUNCTION)->bind(TOK_RETURN)->bind(new kprobe_builder());
s.pattern_root->bind(TOK_KPROBE)->bind_str(TOK_MODULE)
->bind_str(TOK_FUNCTION)->bind(TOK_RETURN)
->bind_num(TOK_MAXACTIVE)->bind(new kprobe_builder());
s.pattern_root->bind(TOK_KPROBE)->bind_num(TOK_STATEMENT)
->bind(TOK_ABSOLUTE)->bind(new kprobe_builder());
//Hwbkpt based kernel probe
// NB: we formerly registered the probe point types only if the kernel configuration
// allowed it. However, we get better error messages if we allow probes to resolve.
s.pattern_root->bind(TOK_KERNEL)->bind_num(TOK_HWBKPT)
->bind(TOK_HWBKPT_WRITE)->bind(new hwbkpt_builder(true));
s.pattern_root->bind(TOK_KERNEL)->bind_str(TOK_HWBKPT)
->bind(TOK_HWBKPT_WRITE)->bind(new hwbkpt_builder(true));
s.pattern_root->bind(TOK_KERNEL)->bind_num(TOK_HWBKPT)
->bind(TOK_HWBKPT_RW)->bind(new hwbkpt_builder(true));
s.pattern_root->bind(TOK_KERNEL)->bind_str(TOK_HWBKPT)
->bind(TOK_HWBKPT_RW)->bind(new hwbkpt_builder(true));
s.pattern_root->bind(TOK_KERNEL)->bind_num(TOK_HWBKPT)
->bind_num(TOK_LENGTH)->bind(TOK_HWBKPT_WRITE)->bind(new hwbkpt_builder(true));
s.pattern_root->bind(TOK_KERNEL)->bind_num(TOK_HWBKPT)
->bind_num(TOK_LENGTH)->bind(TOK_HWBKPT_RW)->bind(new hwbkpt_builder(true));
// length supported with address only, not symbol names
//Hwbkpt based process probe
// NB: we don't support symbol names in the probe spec (yet).
s.pattern_root->bind(TOK_PROCESS)->bind_num(TOK_HWBKPT)
->bind(TOK_HWBKPT_WRITE)->bind(new hwbkpt_builder(false));
s.pattern_root->bind(TOK_PROCESS)->bind_num(TOK_HWBKPT)
->bind(TOK_HWBKPT_RW)->bind(new hwbkpt_builder(false));
s.pattern_root->bind(TOK_PROCESS)->bind_num(TOK_HWBKPT)
->bind_num(TOK_LENGTH)->bind(TOK_HWBKPT_WRITE)->bind(new hwbkpt_builder(false));
s.pattern_root->bind(TOK_PROCESS)->bind_num(TOK_HWBKPT)
->bind_num(TOK_LENGTH)->bind(TOK_HWBKPT_RW)->bind(new hwbkpt_builder(false));
//perf event based probe
register_tapset_perf(s);
register_tapset_java(s);
register_tapset_python(s);
}
vector<derived_probe_group*>
all_session_groups(systemtap_session& s)
{
vector<derived_probe_group*> g;
#define DOONE(x) \
if (s. x##_derived_probes) \
g.push_back ((derived_probe_group*)(s. x##_derived_probes))
// Note that order *is* important here. We want to make sure we
// register (actually run) begin probes before any other probe type
// is run. Similarly, when unregistering probes, we want to
// unregister (actually run) end probes after every other probe type
// has be unregistered. To do the latter,
// c_unparser::emit_module_exit() will run this list backwards.
DOONE(vma_tracker);
DOONE(be);
DOONE(generic_kprobe);
DOONE(uprobe);
DOONE(timer);
DOONE(profile);
DOONE(mark);
DOONE(tracepoint);
DOONE(hwbkpt);
DOONE(perf);
DOONE(hrtimer);
// Another "order is important" item. Python probes create synthetic
// procfs probes and the python probes' emit_module_decls() needs to
// be called first.
DOONE(python);
DOONE(procfs);
DOONE(netfilter);
// Another "order is important" item. We want to make sure we
// "register" the dummy task_finder probe group after all probe
// groups that use the task_finder.
DOONE(utrace);
DOONE(itrace);
DOONE(dynprobe);
DOONE(task_finder);
#undef DOONE
return g;
}
/* vim: set sw=2 ts=8 cino=>4,n-2,{2,^-2,t0,(0,u0,w1,M1 : */
|