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
|
/* -*- mode: C; c-basic-offset: 3; -*- */
/*--------------------------------------------------------------------*/
/*--- Wrappers for generic Unix system calls ---*/
/*--- syswrap-generic.c ---*/
/*--------------------------------------------------------------------*/
/*
This file is part of Valgrind, a dynamic binary instrumentation
framework.
Copyright (C) 2000-2017 Julian Seward
jseward@acm.org
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, see <http://www.gnu.org/licenses/>.
The GNU General Public License is contained in the file COPYING.
*/
#if defined(VGO_linux) || defined(VGO_darwin) || defined(VGO_solaris) || defined(VGO_freebsd)
#include "pub_core_basics.h"
#include "pub_core_vki.h"
#include "pub_core_vkiscnums.h"
#include "pub_core_threadstate.h"
#include "pub_core_debuginfo.h" // VG_(di_notify_*)
#include "pub_core_aspacemgr.h"
#include "pub_core_transtab.h" // VG_(discard_translations)
#include "pub_core_xarray.h"
#include "pub_core_clientstate.h" // VG_(brk_base), VG_(brk_limit)
#include "pub_core_debuglog.h"
#include "pub_core_errormgr.h" // For VG_(maybe_record_error)
#include "pub_core_gdbserver.h" // VG_(gdbserver)
#include "pub_core_libcbase.h"
#include "pub_core_libcassert.h"
#include "pub_core_libcfile.h"
#include "pub_core_libcprint.h"
#include "pub_core_libcproc.h"
#include "pub_core_libcsignal.h"
#include "pub_core_machine.h" // VG_(get_SP)
#include "pub_core_mallocfree.h"
#include "pub_core_options.h"
#include "pub_core_scheduler.h"
#include "pub_core_signals.h"
#include "pub_core_stacktrace.h" // For VG_(get_and_pp_StackTrace)()
#include "pub_core_syscall.h"
#include "pub_core_syswrap.h"
#include "pub_core_tooliface.h"
#include "pub_core_ume.h"
#include "pub_core_stacks.h"
#include "priv_types_n_macros.h"
#include "priv_syswrap-generic.h"
#include "config.h"
static
HChar *getsockdetails(Int fd, UInt len, HChar *buf);
void ML_(guess_and_register_stack) (Addr sp, ThreadState* tst)
{
Bool debug = False;
NSegment const* seg;
/* We don't really know where the client stack is, because its
allocated by the client. The best we can do is look at the
memory mappings and try to derive some useful information. We
assume that sp starts near its highest possible value, and can
only go down to the start of the mmaped segment. */
seg = VG_(am_find_nsegment)(sp);
if (seg
&& VG_(am_is_valid_for_client)(sp, 1, VKI_PROT_READ | VKI_PROT_WRITE)) {
tst->client_stack_highest_byte = (Addr)VG_PGROUNDUP(sp)-1;
tst->client_stack_szB = tst->client_stack_highest_byte - seg->start + 1;
tst->os_state.stk_id
= VG_(register_stack)(seg->start, tst->client_stack_highest_byte);
if (debug)
VG_(printf)("tid %u: guessed client stack range [%#lx-%#lx]"
" as stk_id %lu\n",
tst->tid, seg->start, tst->client_stack_highest_byte,
tst->os_state.stk_id);
} else {
VG_(message)(Vg_UserMsg,
"!? New thread %u starts with SP(%#lx) unmapped\n",
tst->tid, sp);
tst->client_stack_highest_byte = 0;
tst->client_stack_szB = 0;
}
}
/* Returns True iff address range is something the client can
plausibly mess with: all of it is either already belongs to the
client or is free or a reservation. */
Bool ML_(valid_client_addr)(Addr start, SizeT size, ThreadId tid,
const HChar *syscallname)
{
Bool ret;
if (size == 0)
return True;
ret = VG_(am_is_valid_for_client_or_free_or_resvn)
(start,size,VKI_PROT_NONE);
if (0)
VG_(printf)("%s: test=%#lx-%#lx ret=%d\n",
syscallname, start, start+size-1, (Int)ret);
if (!ret && syscallname != NULL) {
VG_(message)(Vg_UserMsg, "Warning: client syscall %s tried "
"to modify addresses %#lx-%#lx\n",
syscallname, start, start+size-1);
if (VG_(clo_verbosity) > 1) {
VG_(get_and_pp_StackTrace)(tid, VG_(clo_backtrace_size));
}
}
return ret;
}
Bool ML_(client_signal_OK)(Int sigNo)
{
/* signal 0 is OK for kill */
Bool ret = sigNo >= 0 && sigNo <= VG_SIGVGRTUSERMAX;
//VG_(printf)("client_signal_OK(%d) -> %d\n", sigNo, ret);
return ret;
}
/* Handy small function to help stop wrappers from segfaulting when
presented with bogus client addresses. Is not used for generating
user-visible errors. */
Bool ML_(safe_to_deref) ( const void *start, SizeT size )
{
return VG_(am_is_valid_for_client)( (Addr)start, size, VKI_PROT_READ );
}
/* ---------------------------------------------------------------------
Doing mmap, mremap
------------------------------------------------------------------ */
/* AFAICT from kernel sources (mm/mprotect.c) and general experimentation,
munmap, mprotect (and mremap??) work at the page level. So addresses
and lengths must be adjusted for this. */
/* Mash around start and length so that the area exactly covers
an integral number of pages. If we don't do that, memcheck's
idea of addressible memory diverges from that of the
kernel's, which causes the leak detector to crash. */
static
void page_align_addr_and_len( Addr* a, SizeT* len)
{
Addr ra;
ra = VG_PGROUNDDN(*a);
*len = VG_PGROUNDUP(*a + *len) - ra;
*a = ra;
}
static void notify_core_of_mmap(Addr a, SizeT len, UInt prot,
UInt flags, Int fd, Off64T offset)
{
Bool d;
/* 'a' is the return value from a real kernel mmap, hence: */
vg_assert(VG_IS_PAGE_ALIGNED(a));
/* whereas len is whatever the syscall supplied. So: */
len = VG_PGROUNDUP(len);
d = VG_(am_notify_client_mmap)( a, len, prot, flags, fd, offset );
if (d)
VG_(discard_translations)( a, (ULong)len,
"notify_core_of_mmap" );
}
static void notify_tool_of_mmap(Addr a, SizeT len, UInt prot, ULong di_handle)
{
Bool rr, ww, xx;
/* 'a' is the return value from a real kernel mmap, hence: */
vg_assert(VG_IS_PAGE_ALIGNED(a));
/* whereas len is whatever the syscall supplied. So: */
len = VG_PGROUNDUP(len);
rr = toBool(prot & VKI_PROT_READ);
ww = toBool(prot & VKI_PROT_WRITE);
xx = toBool(prot & VKI_PROT_EXEC);
VG_TRACK( new_mem_mmap, a, len, rr, ww, xx, di_handle );
}
/* When a client mmap has been successfully done, this function must
be called. It notifies both aspacem and the tool of the new
mapping.
JRS 2008-Aug-14: But notice this is *very* obscure. The only place
it is called from is POST(sys_io_setup). In particular,
ML_(generic_PRE_sys_mmap), in m_syswrap, is the "normal case" handler for
client mmap. But it doesn't call this function; instead it does the
relevant notifications itself. Here, we just pass di_handle=0 to
notify_tool_of_mmap as we have no better information. But really this
function should be done away with; problem is I don't understand what
POST(sys_io_setup) does or how it works.
[However, this function is used lots for Darwin, because
ML_(generic_PRE_sys_mmap) cannot be used for Darwin.]
*/
void
ML_(notify_core_and_tool_of_mmap) ( Addr a, SizeT len, UInt prot,
UInt flags, Int fd, Off64T offset )
{
// XXX: unlike the other notify_core_and_tool* functions, this one doesn't
// do anything with debug info (ie. it doesn't call VG_(di_notify_mmap)).
// Should it? --njn
notify_core_of_mmap(a, len, prot, flags, fd, offset);
notify_tool_of_mmap(a, len, prot, 0/*di_handle*/);
}
void
ML_(notify_core_and_tool_of_munmap) ( Addr a, SizeT len )
{
Bool d;
page_align_addr_and_len(&a, &len);
d = VG_(am_notify_munmap)(a, len);
VG_TRACK( die_mem_munmap, a, len );
VG_(di_notify_munmap)( a, len );
if (d)
VG_(discard_translations)( a, (ULong)len,
"ML_(notify_core_and_tool_of_munmap)" );
}
void
ML_(notify_core_and_tool_of_mprotect) ( Addr a, SizeT len, Int prot )
{
Bool rr = toBool(prot & VKI_PROT_READ);
Bool ww = toBool(prot & VKI_PROT_WRITE);
Bool xx = toBool(prot & VKI_PROT_EXEC);
Bool d;
page_align_addr_and_len(&a, &len);
d = VG_(am_notify_mprotect)(a, len, prot);
VG_TRACK( change_mem_mprotect, a, len, rr, ww, xx );
VG_(di_notify_mprotect)( a, len, prot );
if (d)
VG_(discard_translations)( a, (ULong)len,
"ML_(notify_core_and_tool_of_mprotect)" );
}
#if HAVE_MREMAP
/* Expand (or shrink) an existing mapping, potentially moving it at
the same time (controlled by the MREMAP_MAYMOVE flag). Nightmare.
*/
static
SysRes do_mremap( Addr old_addr, SizeT old_len,
Addr new_addr, SizeT new_len,
UWord flags, ThreadId tid )
{
# define MIN_SIZET(_aa,_bb) (_aa) < (_bb) ? (_aa) : (_bb)
Bool ok, d;
NSegment const* old_seg;
Addr advised;
Bool f_fixed = toBool(flags & VKI_MREMAP_FIXED);
Bool f_maymove = toBool(flags & VKI_MREMAP_MAYMOVE);
if (0)
VG_(printf)("do_remap (old %#lx %lu) (new %#lx %lu) %s %s\n",
old_addr,old_len,new_addr,new_len,
flags & VKI_MREMAP_MAYMOVE ? "MAYMOVE" : "",
flags & VKI_MREMAP_FIXED ? "FIXED" : "");
if (0)
VG_(am_show_nsegments)(0, "do_remap: before");
if (flags & ~(VKI_MREMAP_FIXED | VKI_MREMAP_MAYMOVE))
goto eINVAL;
if (!VG_IS_PAGE_ALIGNED(old_addr))
goto eINVAL;
old_len = VG_PGROUNDUP(old_len);
new_len = VG_PGROUNDUP(new_len);
if (new_len == 0)
goto eINVAL;
/* kernel doesn't reject this, but we do. */
if (old_len == 0)
goto eINVAL;
/* reject wraparounds */
if (old_addr + old_len < old_addr)
goto eINVAL;
if (f_fixed == True && new_addr + new_len < new_len)
goto eINVAL;
/* kernel rejects all fixed, no-move requests (which are
meaningless). */
if (f_fixed == True && f_maymove == False)
goto eINVAL;
/* Stay away from non-client areas. */
if (!ML_(valid_client_addr)(old_addr, old_len, tid, "mremap(old_addr)"))
goto eINVAL;
/* In all remaining cases, if the old range does not fall within a
single segment, fail. */
old_seg = VG_(am_find_nsegment)( old_addr );
if (old_addr < old_seg->start || old_addr+old_len-1 > old_seg->end)
goto eINVAL;
if (old_seg->kind != SkAnonC && old_seg->kind != SkFileC
&& old_seg->kind != SkShmC)
goto eINVAL;
vg_assert(old_len > 0);
vg_assert(new_len > 0);
vg_assert(VG_IS_PAGE_ALIGNED(old_len));
vg_assert(VG_IS_PAGE_ALIGNED(new_len));
vg_assert(VG_IS_PAGE_ALIGNED(old_addr));
/* There are 3 remaining cases:
* maymove == False
new space has to be at old address, so:
- shrink -> unmap end
- same size -> do nothing
- grow -> if can grow in-place, do so, else fail
* maymove == True, fixed == False
new space can be anywhere, so:
- shrink -> unmap end
- same size -> do nothing
- grow -> if can grow in-place, do so, else
move to anywhere large enough, else fail
* maymove == True, fixed == True
new space must be at new address, so:
- if new address is not page aligned, fail
- if new address range overlaps old one, fail
- if new address range cannot be allocated, fail
- else move to new address range with new size
- else fail
*/
if (f_maymove == False) {
/* new space has to be at old address */
if (new_len < old_len)
goto shrink_in_place;
if (new_len > old_len)
goto grow_in_place_or_fail;
goto same_in_place;
}
if (f_maymove == True && f_fixed == False) {
/* new space can be anywhere */
if (new_len < old_len)
goto shrink_in_place;
if (new_len > old_len)
goto grow_in_place_or_move_anywhere_or_fail;
goto same_in_place;
}
if (f_maymove == True && f_fixed == True) {
/* new space can only be at the new address */
if (!VG_IS_PAGE_ALIGNED(new_addr))
goto eINVAL;
if (new_addr+new_len-1 < old_addr || new_addr > old_addr+old_len-1) {
/* no overlap */
} else {
goto eINVAL;
}
if (new_addr == 0)
goto eINVAL;
/* VG_(am_get_advisory_client_simple) interprets zero to mean
non-fixed, which is not what we want */
advised = VG_(am_get_advisory_client_simple)(new_addr, new_len, &ok);
if (!ok || advised != new_addr)
goto eNOMEM;
ok = VG_(am_relocate_nooverlap_client)
( &d, old_addr, old_len, new_addr, new_len );
if (ok) {
VG_TRACK( copy_mem_remap, old_addr, new_addr,
MIN_SIZET(old_len,new_len) );
if (new_len > old_len)
VG_TRACK( new_mem_mmap, new_addr+old_len, new_len-old_len,
old_seg->hasR, old_seg->hasW, old_seg->hasX,
0/*di_handle*/ );
VG_TRACK(die_mem_munmap, old_addr, old_len);
if (d) {
VG_(discard_translations)( old_addr, old_len, "do_remap(1)" );
VG_(discard_translations)( new_addr, new_len, "do_remap(2)" );
}
return VG_(mk_SysRes_Success)( new_addr );
}
goto eNOMEM;
}
/* end of the 3 cases */
/*NOTREACHED*/ vg_assert(0);
grow_in_place_or_move_anywhere_or_fail:
{
/* try growing it in-place */
Addr needA = old_addr + old_len;
SSizeT needL = new_len - old_len;
vg_assert(needL > 0);
vg_assert(needA > 0);
advised = VG_(am_get_advisory_client_simple)( needA, needL, &ok );
if (ok) {
/* Fixes bug #129866. */
ok = VG_(am_covered_by_single_free_segment) ( needA, needL );
}
if (ok && advised == needA) {
const NSegment *new_seg = VG_(am_extend_map_client)( old_addr, needL );
if (new_seg) {
VG_TRACK( new_mem_mmap, needA, needL,
new_seg->hasR,
new_seg->hasW, new_seg->hasX,
0/*di_handle*/ );
return VG_(mk_SysRes_Success)( old_addr );
}
}
/* that failed. Look elsewhere. */
advised = VG_(am_get_advisory_client_simple)( 0, new_len, &ok );
if (ok) {
Bool oldR = old_seg->hasR;
Bool oldW = old_seg->hasW;
Bool oldX = old_seg->hasX;
/* assert new area does not overlap old */
vg_assert(advised+new_len-1 < old_addr
|| advised > old_addr+old_len-1);
ok = VG_(am_relocate_nooverlap_client)
( &d, old_addr, old_len, advised, new_len );
if (ok) {
VG_TRACK( copy_mem_remap, old_addr, advised,
MIN_SIZET(old_len,new_len) );
if (new_len > old_len)
VG_TRACK( new_mem_mmap, advised+old_len, new_len-old_len,
oldR, oldW, oldX, 0/*di_handle*/ );
VG_TRACK(die_mem_munmap, old_addr, old_len);
if (d) {
VG_(discard_translations)( old_addr, old_len, "do_remap(4)" );
VG_(discard_translations)( advised, new_len, "do_remap(5)" );
}
return VG_(mk_SysRes_Success)( advised );
}
}
goto eNOMEM;
}
/*NOTREACHED*/ vg_assert(0);
grow_in_place_or_fail:
{
Addr needA = old_addr + old_len;
SizeT needL = new_len - old_len;
vg_assert(needA > 0);
advised = VG_(am_get_advisory_client_simple)( needA, needL, &ok );
if (ok) {
/* Fixes bug #129866. */
ok = VG_(am_covered_by_single_free_segment) ( needA, needL );
}
if (!ok || advised != needA)
goto eNOMEM;
const NSegment *new_seg = VG_(am_extend_map_client)( old_addr, needL );
if (!new_seg)
goto eNOMEM;
VG_TRACK( new_mem_mmap, needA, needL,
new_seg->hasR, new_seg->hasW, new_seg->hasX,
0/*di_handle*/ );
return VG_(mk_SysRes_Success)( old_addr );
}
/*NOTREACHED*/ vg_assert(0);
shrink_in_place:
{
SysRes sres = VG_(am_munmap_client)( &d, old_addr+new_len, old_len-new_len );
if (sr_isError(sres))
return sres;
VG_TRACK( die_mem_munmap, old_addr+new_len, old_len-new_len );
if (d)
VG_(discard_translations)( old_addr+new_len, old_len-new_len,
"do_remap(7)" );
return VG_(mk_SysRes_Success)( old_addr );
}
/*NOTREACHED*/ vg_assert(0);
same_in_place:
return VG_(mk_SysRes_Success)( old_addr );
/*NOTREACHED*/ vg_assert(0);
eINVAL:
return VG_(mk_SysRes_Error)( VKI_EINVAL );
eNOMEM:
return VG_(mk_SysRes_Error)( VKI_ENOMEM );
# undef MIN_SIZET
}
#endif /* HAVE_MREMAP */
/* ---------------------------------------------------------------------
File-descriptor tracking
------------------------------------------------------------------ */
/* One of these is allocated for each open file descriptor. */
typedef struct OpenFd
{
Int fd; /* The file descriptor */
HChar *pathname; /* NULL if not a regular file or unknown */
HChar *description; /* Description saved before close */
ExeContext *where; /* NULL if inherited from parent */
ExeContext *where_closed; /* record the last close of fd */
Bool fd_closed;
struct OpenFd *next, *prev;
} OpenFd;
/* List of allocated file descriptors. */
static OpenFd *allocated_fds = NULL;
/* Count of open file descriptors. */
static Int fd_count = 0;
/* Close_range caller might want to close very wide range of file descriptors,
up to 0U. We want to avoid iterating through such a range in a normall
close_range, just up to any open file descriptor. Also, unlike
record_fd_close_range, we assume the user might deliberately double closes
any file descriptors in the range, so don't warn about double close here. */
void ML_(record_fd_close_range)(ThreadId tid, Int from_fd)
{
OpenFd *i = allocated_fds;
if (from_fd >= VG_(fd_hard_limit))
return; /* Valgrind internal */
while(i) {
// Assume the user doesn't want a warning if this came from
// close_range. Just record the file descriptors not yet closed here.
if (i->fd >= from_fd && !i->fd_closed
&& i->fd != VG_(log_output_sink).fd
&& i->fd != VG_(xml_output_sink).fd) {
i->fd_closed = True;
i->where_closed = ((tid == -1)
? NULL
: VG_(record_ExeContext)(tid,
0/*first_ip_delta*/));
fd_count--;
}
i = i->next;
}
}
struct BadCloseExtra {
Int fd; /* The file descriptor */
HChar *pathname; /* NULL if not a regular file or unknown */
HChar *description; /* Description of the file descriptor
might include the pathname */
ExeContext *where_closed; /* record the last close of fd */
ExeContext *where_opened; /* recordwhere the fd was opened */
};
struct FdBadUse {
Int fd; /* The file descriptor */
HChar *pathname; /* NULL if not a regular file or unknown */
HChar *description; /* Description of the file descriptor
might include the pathname */
ExeContext *where_closed; /* record the last close of fd */
ExeContext *where_opened; /* recordwhere the fd was opened */
};
struct NotClosedExtra {
Int fd;
HChar *pathname;
HChar *description;
};
/* Note the fact that a file descriptor was just closed. */
void ML_(record_fd_close)(ThreadId tid, Int fd)
{
OpenFd *i = allocated_fds;
if (fd >= VG_(fd_hard_limit))
return; /* Valgrind internal */
while(i) {
if (i->fd == fd) {
if (i->fd_closed) {
struct BadCloseExtra bce;
bce.fd = i->fd;
bce.pathname = i->pathname;
bce.description = i->description;
bce.where_opened = i->where;
bce.where_closed = i->where_closed;
VG_(maybe_record_error)(tid, FdBadClose, 0,
"file descriptor already closed", &bce);
} else {
i->fd_closed = True;
i->where_closed = ((tid == -1)
? NULL
: VG_(record_ExeContext)(tid,
0/*first_ip_delta*/));
/* Record path/socket name, etc. In case we want to print it later,
for example for double close. Note that record_fd_close is
actually called from the PRE syscall handler, so the file
description is about to be closed, but hasn't yet at this
point. */
if (!i->pathname) {
Int val;
Int len = sizeof(val);
if (VG_(getsockopt)(i->fd, VKI_SOL_SOCKET, VKI_SO_TYPE,
&val, &len) == -1) {
HChar *pathname = VG_(malloc)("vg.record_fd_close.fd", 30);
VG_(snprintf)(pathname, 30, "file descriptor %d", i->fd);
i->description = pathname;
} else {
HChar *name = VG_(malloc)("vg.record_fd_close.sock", 256);
i->description = getsockdetails(i->fd, 256, name);
}
} else {
i->description = VG_(strdup)("vg.record_fd_close.path",
i->pathname);
}
fd_count--;
}
break;
}
i = i->next;
}
}
/* Note the fact that a file descriptor was just opened. If the
tid is -1, this indicates an inherited fd. If the pathname is NULL,
this either indicates a non-standard file (i.e. a pipe or socket or
some such thing) or that we don't know the filename. If the fd is
already open, then we're probably doing a dup2() to an existing fd,
so just overwrite the existing one. */
void ML_(record_fd_open_with_given_name)(ThreadId tid, Int fd,
const HChar *pathname)
{
OpenFd *i;
if (fd >= VG_(fd_hard_limit))
return; /* Valgrind internal */
/* Check to see if this fd is already open (or closed, we will just
override it. */
i = allocated_fds;
while (i) {
if (i->fd == fd) {
if (i->pathname) {
VG_(free)(i->pathname);
i->pathname = NULL;
}
if (i->description) {
VG_(free)(i->description);
i->description = NULL;
}
if (i->fd_closed) /* now we will open it. */
fd_count++;
break;
}
i = i->next;
}
/* Not already one: allocate an OpenFd */
if (i == NULL) {
i = VG_(malloc)("syswrap.rfdowgn.1", sizeof(OpenFd));
i->prev = NULL;
i->next = allocated_fds;
if(allocated_fds) allocated_fds->prev = i;
allocated_fds = i;
fd_count++;
}
i->fd = fd;
i->pathname = VG_(strdup)("syswrap.rfdowgn.2", pathname);
i->description = NULL; /* Only set on close. */
i->where = (tid == -1) ? NULL : VG_(record_ExeContext)(tid, 0/*first_ip_delta*/);
i->fd_closed = False;
i->where_closed = NULL;
}
// Record opening of an fd, and find its name.
void ML_(record_fd_open_named)(ThreadId tid, Int fd)
{
const HChar* buf;
const HChar* name;
if (VG_(resolve_filename)(fd, &buf))
name = buf;
else
name = NULL;
ML_(record_fd_open_with_given_name)(tid, fd, name);
}
// Record opening of a nameless fd.
void ML_(record_fd_open_nameless)(ThreadId tid, Int fd)
{
ML_(record_fd_open_with_given_name)(tid, fd, NULL);
}
// Return if a given file descriptor is already recorded.
Bool ML_(fd_recorded)(Int fd)
{
OpenFd *i = allocated_fds;
while (i) {
if (i->fd == fd) {
if (i->fd_closed)
return False;
else
return True;
}
i = i->next;
}
return False;
}
/* Returned string must not be modified nor free'd. */
const HChar *ML_(find_fd_recorded_by_fd)(Int fd)
{
OpenFd *i = allocated_fds;
while (i) {
if (i->fd == fd) {
if (i->fd_closed)
return NULL;
else
return i->pathname;
}
i = i->next;
}
return NULL;
}
static
HChar *unix_to_name(struct vki_sockaddr_un *sa, UInt len, HChar *name)
{
if (sa == NULL || len == 0 || sa->sun_path[0] == '\0') {
VG_(sprintf)(name, "<unknown>");
} else {
VG_(sprintf)(name, "%s", sa->sun_path);
}
return name;
}
static
HChar *inet_to_name(struct vki_sockaddr_in *sa, UInt len, HChar *name)
{
if (sa == NULL || len == 0) {
VG_(sprintf)(name, "<unknown>");
} else if (sa->sin_port == 0) {
VG_(sprintf)(name, "<unbound>");
} else {
UInt addr = VG_(ntohl)(sa->sin_addr.s_addr);
VG_(sprintf)(name, "%u.%u.%u.%u:%u",
(addr>>24) & 0xFF, (addr>>16) & 0xFF,
(addr>>8) & 0xFF, addr & 0xFF,
VG_(ntohs)(sa->sin_port));
}
return name;
}
static
void inet6_format(HChar *s, const UChar ip[16])
{
static const unsigned char V4mappedprefix[12] = {0,0,0,0,0,0,0,0,0,0,0xff,0xff};
if (!VG_(memcmp)(ip, V4mappedprefix, 12)) {
const struct vki_in_addr *sin_addr =
(const struct vki_in_addr *)(ip + 12);
UInt addr = VG_(ntohl)(sin_addr->s_addr);
VG_(sprintf)(s, "::ffff:%u.%u.%u.%u",
(addr>>24) & 0xFF, (addr>>16) & 0xFF,
(addr>>8) & 0xFF, addr & 0xFF);
} else {
Bool compressing = False;
Bool compressed = False;
Int len = 0;
Int i;
for (i = 0; i < 16; i += 2) {
UInt word = ((UInt)ip[i] << 8) | (UInt)ip[i+1];
if (word == 0 && !compressed) {
compressing = True;
} else {
if (compressing) {
compressing = False;
compressed = True;
s[len++] = ':';
}
if (i > 0) {
s[len++] = ':';
}
len += VG_(sprintf)(s + len, "%x", word);
}
}
if (compressing) {
s[len++] = ':';
s[len++] = ':';
}
s[len++] = 0;
}
return;
}
static
HChar *inet6_to_name(struct vki_sockaddr_in6 *sa, UInt len, HChar *name)
{
if (sa == NULL || len == 0) {
VG_(sprintf)(name, "<unknown>");
} else if (sa->sin6_port == 0) {
VG_(sprintf)(name, "<unbound>");
} else {
HChar addr[100]; // large enough
inet6_format(addr, (void *)&(sa->sin6_addr));
VG_(sprintf)(name, "[%s]:%u", addr, VG_(ntohs)(sa->sin6_port));
}
return name;
}
/*
* Try get some details about a socket.
* Returns the given BUF with max length LEN.
*/
static
HChar *getsockdetails(Int fd, UInt len, HChar *buf)
{
union u {
struct vki_sockaddr a;
struct vki_sockaddr_in in;
struct vki_sockaddr_in6 in6;
struct vki_sockaddr_un un;
} laddr;
Int llen;
llen = sizeof(laddr);
VG_(memset)(&laddr, 0, llen);
if(VG_(getsockname)(fd, (struct vki_sockaddr *)&(laddr.a), &llen) != -1) {
switch(laddr.a.sa_family) {
case VKI_AF_INET: {
HChar lname[32]; // large enough
HChar pname[32]; // large enough
struct vki_sockaddr_in paddr;
Int plen = sizeof(struct vki_sockaddr_in);
if (VG_(getpeername)(fd, (struct vki_sockaddr *)&paddr, &plen) != -1) {
VG_(snprintf)(buf, len, "AF_INET socket %d: %s <-> %s", fd,
inet_to_name(&(laddr.in), llen, lname),
inet_to_name(&paddr, plen, pname));
return buf;
} else {
VG_(snprintf)(buf, len, "AF_INET socket %d: %s <-> <unbound>",
fd, inet_to_name(&(laddr.in), llen, lname));
return buf;
}
}
case VKI_AF_INET6: {
HChar lname[128]; // large enough
HChar pname[128]; // large enough
struct vki_sockaddr_in6 paddr;
Int plen = sizeof(struct vki_sockaddr_in6);
if (VG_(getpeername)(fd, (struct vki_sockaddr *)&paddr, &plen) != -1) {
VG_(snprintf)(buf, len, "AF_INET6 socket %d: %s <-> %s", fd,
inet6_to_name(&(laddr.in6), llen, lname),
inet6_to_name(&paddr, plen, pname));
return buf;
} else {
VG_(snprintf)(buf, len, "AF_INET6 socket %d: %s <-> <unbound>",
fd, inet6_to_name(&(laddr.in6), llen, lname));
return buf;
}
}
case VKI_AF_UNIX: {
static char lname[256];
VG_(snprintf)(buf, len, "AF_UNIX socket %d: %s", fd,
unix_to_name(&(laddr.un), llen, lname));
return buf;
}
default:
VG_(snprintf)(buf, len, "pf-%d socket %d",
laddr.a.sa_family, fd);
return buf;
}
}
VG_(snprintf)(buf, len, "socket %d", fd);
return buf;
}
/* Dump out a summary, and a more detailed list, of open file descriptors. */
void VG_(show_open_fds) (const HChar* when)
{
OpenFd *i;
int non_std = 0;
for (i = allocated_fds; i; i = i->next) {
if (i->fd > 2 && i->fd_closed != True)
non_std++;
}
/* If we are running quiet and there are either no open file descriptors
or not tracking all fds, then don't report anything. */
if ((fd_count == 0
|| ((non_std == 0) && (VG_(clo_track_fds) < 2)))
&& (VG_(clo_verbosity) == 0))
return;
if (!VG_(clo_xml)) {
VG_(umsg)("FILE DESCRIPTORS: %d open (%d std) %s.\n",
fd_count, fd_count - non_std, when);
}
for (i = allocated_fds; i; i = i->next) {
if (i->fd_closed)
continue;
if (i->fd <= 2 && VG_(clo_track_fds) < 2)
continue;
struct NotClosedExtra nce;
/* The file descriptor was not yet closed, so the description field was
also not yet set. Set it now as if the file descriptor was closed at
this point. */
i->description = VG_(malloc)("vg.notclosedextra.descriptor", 256);
if (i->pathname) {
VG_(snprintf) (i->description, 256, "file descriptor %d: %s",
i->fd, i->pathname);
} else {
Int val;
Int len = sizeof(val);
if (VG_(getsockopt)(i->fd, VKI_SOL_SOCKET, VKI_SO_TYPE, &val, &len)
== -1) {
/* Don't want the : at the end in xml */
const HChar *colon = VG_(clo_xml) ? "" : ":";
VG_(sprintf)(i->description, "file descriptor %d%s", i->fd, colon);
} else {
getsockdetails(i->fd, 256, i->description);
}
}
nce.fd = i->fd;
nce.pathname = i->pathname;
nce.description = i->description;
VG_(unique_error) (1 /* Fake ThreadId */,
FdNotClosed,
0, /* Addr */
"Still Open file descriptor",
&nce, /* extra */
i->where,
True, /* print_error */
False, /* allow_GDB_attach */
True /* count_error */);
}
if (!VG_(clo_xml))
VG_(message)(Vg_UserMsg, "\n");
}
/* If /proc/self/fd doesn't exist (e.g. you've got a Linux kernel that doesn't
have /proc support compiled in, or a non-Linux kernel), then we need to
find out what file descriptors we inherited from our parent process the
hard way - by checking each fd in turn. */
static
void init_preopened_fds_without_proc_self_fd(void)
{
struct vki_rlimit lim;
UInt count;
Int i;
if (VG_(getrlimit) (VKI_RLIMIT_NOFILE, &lim) == -1) {
/* Hmm. getrlimit() failed. Now we're screwed, so just choose
an arbitrarily high number. 1024 happens to be the limit in
the 2.4 Linux kernels. */
count = 1024;
} else {
count = lim.rlim_cur;
}
for (i = 0; i < count; i++)
if (VG_(fcntl)(i, VKI_F_GETFL, 0) != -1)
ML_(record_fd_open_named)(-1, i);
}
/* Initialize the list of open file descriptors with the file descriptors
we inherited from out parent process. */
void VG_(init_preopened_fds)(void)
{
// DDD: should probably use HAVE_PROC here or similar, instead.
#if defined(VGO_linux)
Int ret;
struct vki_dirent64 d;
SysRes f;
f = VG_(open)("/proc/self/fd", VKI_O_RDONLY, 0);
if (sr_isError(f)) {
init_preopened_fds_without_proc_self_fd();
return;
}
while ((ret = VG_(getdents64)(sr_Res(f), &d, sizeof(d))) != 0) {
if (ret == -1)
goto out;
if (VG_(strcmp)(d.d_name, ".") && VG_(strcmp)(d.d_name, "..")) {
HChar* s;
Int fno = VG_(strtoll10)(d.d_name, &s);
if (*s == '\0') {
if (fno != sr_Res(f))
if (VG_(clo_track_fds))
ML_(record_fd_open_named)(-1, fno);
} else {
VG_(message)(Vg_DebugMsg,
"Warning: invalid file name in /proc/self/fd: %s\n",
d.d_name);
}
}
VG_(lseek)(sr_Res(f), d.d_off, VKI_SEEK_SET);
}
out:
VG_(close)(sr_Res(f));
#elif defined(VGO_darwin) || defined(VGO_freebsd)
init_preopened_fds_without_proc_self_fd();
#elif defined(VGO_solaris)
Int ret;
Char buf[VKI_MAXGETDENTS_SIZE];
SysRes f;
f = VG_(open)("/proc/self/fd", VKI_O_RDONLY, 0);
if (sr_isError(f)) {
init_preopened_fds_without_proc_self_fd();
return;
}
while ((ret = VG_(getdents64)(sr_Res(f), (struct vki_dirent64 *) buf,
sizeof(buf))) > 0) {
Int i = 0;
while (i < ret) {
/* Proceed one entry. */
struct vki_dirent64 *d = (struct vki_dirent64 *) (buf + i);
if (VG_(strcmp)(d->d_name, ".") && VG_(strcmp)(d->d_name, "..")) {
HChar *s;
Int fno = VG_(strtoll10)(d->d_name, &s);
if (*s == '\0') {
if (fno != sr_Res(f))
if (VG_(clo_track_fds))
ML_(record_fd_open_named)(-1, fno);
} else {
VG_(message)(Vg_DebugMsg,
"Warning: invalid file name in /proc/self/fd: %s\n",
d->d_name);
}
}
/* Move on the next entry. */
i += d->d_reclen;
}
}
VG_(close)(sr_Res(f));
#else
# error Unknown OS
#endif
}
Bool fd_eq_Error (VgRes res, const Error *e1, const Error *e2)
{
// XXX should we compare the fds?
return False;
}
void fd_before_pp_Error (const Error *err)
{
// Nothing to do here
}
void fd_pp_Error (const Error *err)
{
const Bool xml = VG_(clo_xml);
const HChar* whatpre = VG_(clo_xml) ? " <what>" : "";
const HChar* whatpost = VG_(clo_xml) ? "</what>" : "";
const HChar* auxpre = VG_(clo_xml) ? " <auxwhat>" : " ";
const HChar* auxpost = VG_(clo_xml) ? "</auxwhat>" : "";
ExeContext *where = VG_(get_error_where)(err);
if (VG_(get_error_kind)(err) == FdBadClose) {
if (xml) VG_(emit)(" <kind>FdBadClose</kind>\n");
struct BadCloseExtra *bce = (struct BadCloseExtra *)
VG_(get_error_extra)(err);
vg_assert(bce);
if (xml) {
VG_(emit)(" <fd>%d</fd>\n", bce->fd);
if (bce->pathname)
VG_(emit)(" <path>%s</path>\n", bce->pathname);
}
VG_(emit)("%sFile descriptor %d: %s is already closed%s\n",
whatpre, bce->fd, bce->description, whatpost);
VG_(pp_ExeContext)( where );
VG_(emit)("%sPreviously closed%s\n", auxpre, auxpost);
VG_(pp_ExeContext)(bce->where_closed);
VG_(emit)("%sOriginally opened%s\n", auxpre, auxpost);
VG_(pp_ExeContext)(bce->where_opened);
} else if (VG_(get_error_kind)(err) == FdNotClosed) {
if (xml) VG_(emit)(" <kind>FdNotClosed</kind>\n");
struct NotClosedExtra *nce = (struct NotClosedExtra *)
VG_(get_error_extra)(err);
if (xml) {
VG_(emit)(" <fd>%d</fd>\n", nce->fd);
if (nce->pathname)
VG_(emit)(" <path>%s</path>\n", nce->pathname);
}
VG_(emit)("%sOpen %s%s\n", whatpre, nce->description, whatpost);
if (where != NULL) {
VG_(pp_ExeContext)(where);
if (!xml) VG_(message)(Vg_UserMsg, "\n");
} else if (!xml) {
VG_(message)(Vg_UserMsg, " <inherited from parent>\n");
VG_(message)(Vg_UserMsg, "\n");
}
} else if (VG_(get_error_kind)(err) == FdBadUse) {
if (xml) VG_(emit)(" <kind>FdBadUse</kind>\n");
struct FdBadUse *nce = (struct FdBadUse *)
VG_(get_error_extra)(err);
const char *error_string = VG_(get_error_string)(err);
if (xml) {
VG_(emit)(" <fd>%d</fd>\n", nce->fd);
if (nce->pathname)
VG_(emit)(" <path>%s</path>\n", nce->pathname);
}
VG_(emit)("%sFile descriptor %d %s%s\n", whatpre, nce->fd,
error_string, whatpost);
/* If the file descriptor was never created we won't have
where_closed and where_opened. Only print them in a
use after close case. */
if (nce->where_closed) {
VG_(emit)("%sPreviously closed%s\n", auxpre, auxpost);
VG_(pp_ExeContext)(nce->where_closed);
}
if (nce->where_opened) {
VG_(emit)("%sOriginally opened%s\n", auxpre, auxpost);
VG_(pp_ExeContext)(nce->where_opened);
}
VG_(pp_ExeContext)(where);
} else {
vg_assert2 (False, "Unknown error kind: %d",
VG_(get_error_kind)(err));
}
}
/* Called to see if there is any extra state to be saved with this
error. Must return the size of the extra struct. */
UInt fd_update_extra (const Error *err)
{
if (VG_(get_error_kind)(err) == FdBadClose)
return sizeof (struct BadCloseExtra);
else if (VG_(get_error_kind)(err) == FdNotClosed)
return sizeof (struct NotClosedExtra);
else if (VG_(get_error_kind)(err) == FdBadUse)
return sizeof (struct FdBadUse);
else {
vg_assert2 (False, "Unknown error kind: %d",
VG_(get_error_kind)(err));
}
}
static
void pre_mem_read_sendmsg ( ThreadId tid, Bool read,
const HChar *msg, Addr base, SizeT size )
{
HChar outmsg[VG_(strlen)(msg) + 10]; // large enough
VG_(sprintf)(outmsg, "sendmsg%s", msg);
PRE_MEM_READ( outmsg, base, size );
}
static
void pre_mem_write_recvmsg ( ThreadId tid, Bool read,
const HChar *msg, Addr base, SizeT size )
{
HChar outmsg[VG_(strlen)(msg) + 10]; // large enough
VG_(sprintf)(outmsg, "recvmsg%s", msg);
if ( read )
PRE_MEM_READ( outmsg, base, size );
else
PRE_MEM_WRITE( outmsg, base, size );
}
static
void post_mem_write_recvmsg ( ThreadId tid, Bool read,
const HChar *fieldName, Addr base, SizeT size )
{
if ( !read )
POST_MEM_WRITE( base, size );
}
static
void msghdr_foreachfield (
ThreadId tid,
const HChar *name,
struct vki_msghdr *msg,
UInt length,
void (*foreach_func)( ThreadId, Bool, const HChar *, Addr, SizeT ),
Bool rekv /* "recv" apparently shadows some header decl on OSX108 */
)
{
HChar fieldName[VG_(strlen)(name) + 32]; // large enough.
Addr a;
SizeT s;
if ( !msg )
return;
VG_(sprintf) ( fieldName, "(%s)", name );
/* FIELDPAIR helps the compiler do one call to foreach_func
for consecutive (no holes) fields. */
#define FIELDPAIR(f1,f2) \
if (offsetof(struct vki_msghdr, f1) + sizeof(msg->f1) \
== offsetof(struct vki_msghdr, f2)) \
s += sizeof(msg->f2); \
else { \
foreach_func (tid, True, fieldName, a, s); \
a = (Addr)&msg->f2; \
s = sizeof(msg->f2); \
}
a = (Addr)&msg->msg_name;
s = sizeof(msg->msg_name);
FIELDPAIR(msg_name, msg_namelen);
FIELDPAIR(msg_namelen, msg_iov);
FIELDPAIR(msg_iov, msg_iovlen);
FIELDPAIR(msg_iovlen, msg_control);
FIELDPAIR(msg_control, msg_controllen);
foreach_func ( tid, True, fieldName, a, s);
#undef FIELDPAIR
/* msg_flags is completely ignored for send_mesg, recv_mesg doesn't read
the field, but does write to it. */
if ( rekv )
foreach_func ( tid, False, fieldName, (Addr)&msg->msg_flags, sizeof( msg->msg_flags ) );
if ( ML_(safe_to_deref)(&msg->msg_name, sizeof (void *))
&& msg->msg_name ) {
VG_(sprintf) ( fieldName, "(%s.msg_name)", name );
foreach_func ( tid, False, fieldName,
(Addr)msg->msg_name, msg->msg_namelen );
}
if ( ML_(safe_to_deref)(&msg->msg_iov, sizeof (void *))
&& msg->msg_iov ) {
struct vki_iovec *iov = msg->msg_iov;
UInt i;
if (ML_(safe_to_deref)(&msg->msg_iovlen, sizeof (UInt))) {
VG_(sprintf) ( fieldName, "(%s.msg_iov)", name );
foreach_func ( tid, True, fieldName, (Addr)iov,
msg->msg_iovlen * sizeof( struct vki_iovec ) );
for ( i = 0; i < msg->msg_iovlen && length > 0; ++i, ++iov ) {
if (ML_(safe_to_deref)(&iov->iov_len, sizeof (UInt))) {
UInt iov_len = iov->iov_len <= length ? iov->iov_len : length;
VG_(sprintf) ( fieldName, "(%s.msg_iov[%u])", name, i );
foreach_func ( tid, False, fieldName,
(Addr)iov->iov_base, iov_len );
length = length - iov_len;
}
}
}
}
if ( ML_(safe_to_deref) (&msg->msg_control, sizeof (void *))
&& msg->msg_control ) {
VG_(sprintf) ( fieldName, "(%s.msg_control)", name );
foreach_func ( tid, False, fieldName,
(Addr)msg->msg_control, msg->msg_controllen );
}
}
static void check_cmsg_for_fds(ThreadId tid, struct vki_msghdr *msg)
{
struct vki_cmsghdr *cm = VKI_CMSG_FIRSTHDR(msg);
while (cm) {
if (cm->cmsg_level == VKI_SOL_SOCKET
&& cm->cmsg_type == VKI_SCM_RIGHTS ) {
Int *fds = (Int *) VKI_CMSG_DATA(cm);
Int fdc = (cm->cmsg_len - VKI_CMSG_ALIGN(sizeof(struct vki_cmsghdr)))
/ sizeof(int);
Int i;
for (i = 0; i < fdc; i++)
if(VG_(clo_track_fds))
// XXX: must we check the range on these fds with
// ML_(fd_allowed)()?
ML_(record_fd_open_named)(tid, fds[i]);
}
cm = VKI_CMSG_NXTHDR(msg, cm);
}
}
/* GrP kernel ignores sa_len (at least on Darwin); this checks the rest */
void ML_(pre_mem_read_sockaddr) ( ThreadId tid,
const HChar *description,
struct vki_sockaddr *sa, UInt salen )
{
HChar outmsg[VG_(strlen)( description ) + 30]; // large enough
struct vki_sockaddr_un* saun = (struct vki_sockaddr_un *)sa;
struct vki_sockaddr_in* sin = (struct vki_sockaddr_in *)sa;
struct vki_sockaddr_in6* sin6 = (struct vki_sockaddr_in6 *)sa;
# ifdef VKI_AF_BLUETOOTH
struct vki_sockaddr_rc* rc = (struct vki_sockaddr_rc *)sa;
# endif
# ifdef VKI_AF_NETLINK
struct vki_sockaddr_nl* nl = (struct vki_sockaddr_nl *)sa;
# endif
/* NULL/zero-length sockaddrs are legal */
if ( sa == NULL || salen == 0 ) return;
VG_(sprintf) ( outmsg, description, "sa_family" );
PRE_MEM_READ( outmsg, (Addr) &sa->sa_family, sizeof(vki_sa_family_t));
#if defined(VGO_freebsd)
VG_(sprintf) ( outmsg, description, "sa_len" );
PRE_MEM_READ( outmsg, (Addr) &sa->sa_len, sizeof(char));
#endif
/* Don't do any extra checking if we cannot determine the sa_family. */
if (! ML_(safe_to_deref) (&sa->sa_family, sizeof(vki_sa_family_t)))
return;
switch (sa->sa_family) {
case VKI_AF_UNIX:
if (ML_(safe_to_deref) (&saun->sun_path, sizeof (Addr))) {
VG_(sprintf) ( outmsg, description, "sun_path" );
PRE_MEM_RASCIIZ( outmsg, (Addr) saun->sun_path );
// GrP fixme max of sun_len-2? what about nul char?
}
break;
case VKI_AF_INET:
VG_(sprintf) ( outmsg, description, "sin_port" );
PRE_MEM_READ( outmsg, (Addr) &sin->sin_port, sizeof (sin->sin_port) );
VG_(sprintf) ( outmsg, description, "sin_addr" );
PRE_MEM_READ( outmsg, (Addr) &sin->sin_addr, sizeof (sin->sin_addr) );
break;
case VKI_AF_INET6:
VG_(sprintf) ( outmsg, description, "sin6_port" );
PRE_MEM_READ( outmsg,
(Addr) &sin6->sin6_port, sizeof (sin6->sin6_port) );
VG_(sprintf) ( outmsg, description, "sin6_flowinfo" );
PRE_MEM_READ( outmsg,
(Addr) &sin6->sin6_flowinfo, sizeof (sin6->sin6_flowinfo) );
VG_(sprintf) ( outmsg, description, "sin6_addr" );
PRE_MEM_READ( outmsg,
(Addr) &sin6->sin6_addr, sizeof (sin6->sin6_addr) );
VG_(sprintf) ( outmsg, description, "sin6_scope_id" );
PRE_MEM_READ( outmsg,
(Addr) &sin6->sin6_scope_id, sizeof (sin6->sin6_scope_id) );
break;
# ifdef VKI_AF_BLUETOOTH
case VKI_AF_BLUETOOTH:
VG_(sprintf) ( outmsg, description, "rc_bdaddr" );
PRE_MEM_READ( outmsg, (Addr) &rc->rc_bdaddr, sizeof (rc->rc_bdaddr) );
VG_(sprintf) ( outmsg, description, "rc_channel" );
PRE_MEM_READ( outmsg, (Addr) &rc->rc_channel, sizeof (rc->rc_channel) );
break;
# endif
# ifdef VKI_AF_NETLINK
case VKI_AF_NETLINK:
VG_(sprintf)(outmsg, description, "nl_pid");
PRE_MEM_READ(outmsg, (Addr)&nl->nl_pid, sizeof(nl->nl_pid));
VG_(sprintf)(outmsg, description, "nl_groups");
PRE_MEM_READ(outmsg, (Addr)&nl->nl_groups, sizeof(nl->nl_groups));
break;
# endif
# ifdef VKI_AF_UNSPEC
case VKI_AF_UNSPEC:
break;
# endif
default:
/* No specific information about this address family.
Let's just check the full data following the family.
Note that this can give false positive if this (unknown)
struct sockaddr_???? has padding bytes between its elements. */
VG_(sprintf) ( outmsg, description, "sa_data" );
PRE_MEM_READ( outmsg, (Addr)&sa->sa_family + sizeof(sa->sa_family),
salen - sizeof(sa->sa_family));
break;
}
}
/* Dereference a pointer to a UInt. */
static UInt deref_UInt ( ThreadId tid, Addr a, const HChar* s )
{
UInt* a_p = (UInt*)a;
PRE_MEM_READ( s, (Addr)a_p, sizeof(UInt) );
if (a_p == NULL || ! ML_(safe_to_deref) (a_p, sizeof(UInt)))
return 0;
else
return *a_p;
}
void ML_(buf_and_len_pre_check) ( ThreadId tid, Addr buf_p, Addr buflen_p,
const HChar* buf_s, const HChar* buflen_s )
{
if (VG_(tdict).track_pre_mem_write) {
UInt buflen_in = deref_UInt( tid, buflen_p, buflen_s);
if (buflen_in > 0) {
VG_(tdict).track_pre_mem_write(
Vg_CoreSysCall, tid, buf_s, buf_p, buflen_in );
}
}
}
void ML_(buf_and_len_post_check) ( ThreadId tid, SysRes res,
Addr buf_p, Addr buflen_p, const HChar* s )
{
if (!sr_isError(res) && VG_(tdict).track_post_mem_write) {
UInt buflen_out = deref_UInt( tid, buflen_p, s);
if (buflen_out > 0 && buf_p != (Addr)NULL) {
VG_(tdict).track_post_mem_write( Vg_CoreSysCall, tid, buf_p, buflen_out );
}
}
}
/* ---------------------------------------------------------------------
Data seg end, for brk()
------------------------------------------------------------------ */
/* +--------+------------+
| anon | resvn |
+--------+------------+
^ ^ ^
| | boundary is page aligned
| VG_(brk_limit) -- no alignment constraint
VG_(brk_base) -- page aligned -- does not move
Both the anon part and the reservation part are always at least
one page.
*/
/* Set the new data segment end to NEWBRK. If this succeeds, return
NEWBRK, else return the current data segment end. */
static Addr do_brk ( Addr newbrk, ThreadId tid )
{
NSegment const* aseg;
Addr newbrkP;
SizeT delta;
Bool debug = False;
if (debug)
VG_(printf)("\ndo_brk: brk_base=%#lx brk_limit=%#lx newbrk=%#lx\n",
VG_(brk_base), VG_(brk_limit), newbrk);
if (0) VG_(am_show_nsegments)(0, "in_brk");
if (newbrk < VG_(brk_base))
/* Clearly impossible. */
goto bad;
if (newbrk < VG_(brk_limit)) {
/* shrinking the data segment. Be lazy and don't munmap the
excess area. */
NSegment const * seg = VG_(am_find_nsegment)(newbrk);
vg_assert(seg);
if (seg->hasT)
VG_(discard_translations)( newbrk, VG_(brk_limit) - newbrk,
"do_brk(shrink)" );
/* Since we're being lazy and not unmapping pages, we have to
zero out the area, so that if the area later comes back into
circulation, it will be filled with zeroes, as if it really
had been unmapped and later remapped. Be a bit paranoid and
try hard to ensure we're not going to segfault by doing the
write - check both ends of the range are in the same segment
and that segment is writable. */
NSegment const * seg2;
seg2 = VG_(am_find_nsegment)( VG_(brk_limit) - 1 );
vg_assert(seg2);
if (seg == seg2 && seg->hasW)
VG_(memset)( (void*)newbrk, 0, VG_(brk_limit) - newbrk );
VG_(brk_limit) = newbrk;
return newbrk;
}
/* otherwise we're expanding the brk segment. */
if (VG_(brk_limit) > VG_(brk_base))
aseg = VG_(am_find_nsegment)( VG_(brk_limit)-1 );
else
aseg = VG_(am_find_nsegment)( VG_(brk_limit) );
/* These should be assured by setup_client_dataseg in m_main. */
vg_assert(aseg);
vg_assert(aseg->kind == SkAnonC);
if (newbrk <= aseg->end + 1) {
/* still fits within the anon segment. */
VG_(brk_limit) = newbrk;
return newbrk;
}
newbrkP = VG_PGROUNDUP(newbrk);
delta = newbrkP - (aseg->end + 1);
vg_assert(delta > 0);
vg_assert(VG_IS_PAGE_ALIGNED(delta));
Bool overflow = False;
if (! VG_(am_extend_into_adjacent_reservation_client)( aseg->start, delta,
&overflow)) {
if (overflow) {
static Bool alreadyComplained = False;
if (!alreadyComplained) {
alreadyComplained = True;
if (VG_(clo_verbosity) > 0) {
VG_(umsg)("brk segment overflow in thread #%u: "
"can't grow to %#lx\n",
tid, newbrkP);
VG_(umsg)("(see section Limitations in user manual)\n");
VG_(umsg)("NOTE: further instances of this message "
"will not be shown\n");
}
}
} else {
if (VG_(clo_verbosity) > 0) {
VG_(umsg)("Cannot map memory to grow brk segment in thread #%u "
"to %#lx\n", tid, newbrkP);
VG_(umsg)("(see section Limitations in user manual)\n");
}
}
goto bad;
}
VG_(brk_limit) = newbrk;
return newbrk;
bad:
return VG_(brk_limit);
}
static
const OpenFd *ML_(find_OpenFd)(Int fd)
{
OpenFd *i = allocated_fds;
while (i) {
if (i->fd == fd)
return i;
i = i->next;
}
return NULL;
}
/* ---------------------------------------------------------------------
Vet file descriptors for sanity
------------------------------------------------------------------ */
/*
> - what does the "Bool soft" parameter mean?
(Tom Hughes, 3 Oct 05):
Whether or not to consider a file descriptor invalid if it is above
the current soft limit.
Basically if we are testing whether a newly created file descriptor is
valid (in a post handler) then we set soft to true, and if we are
testing whether a file descriptor that is about to be used (in a pre
handler) is valid [viz, an already-existing fd] then we set it to false.
The point is that if the (virtual) soft limit is lowered then any
existing descriptors can still be read/written/closed etc (so long as
they are below the valgrind reserved descriptors) but no new
descriptors can be created above the new soft limit.
(jrs 4 Oct 05: in which case, I've renamed it "isNewFd")
*/
/* Return true if we're allowed to use or create this fd */
Bool ML_(fd_allowed)(Int fd, const HChar *syscallname, ThreadId tid,
Bool isNewFd)
{
Bool allowed = True;
/* hard limits always apply */
if (fd < 0 || fd >= VG_(fd_hard_limit))
allowed = False;
/* hijacking the output fds is never allowed */
if (fd == VG_(log_output_sink).fd || fd == VG_(xml_output_sink).fd)
allowed = False;
/* if creating a new fd (rather than using an existing one), the
soft limit must also be observed */
if (isNewFd && fd >= VG_(fd_soft_limit))
allowed = False;
/* this looks like it ought to be included, but causes problems: */
/*
if (fd == 2 && VG_(debugLog_getLevel)() > 0)
allowed = False;
*/
/* The difficulty is as follows: consider a program P which expects
to be able to mess with (redirect) its own stderr (fd 2).
Usually to deal with P we would issue command line flags to send
logging somewhere other than stderr, so as not to disrupt P.
The problem is that -d unilaterally hijacks stderr with no
consultation with P. And so, if this check is enabled, P will
work OK normally but fail if -d is issued.
Basically -d is a hack and you take your chances when using it.
It's very useful for low level debugging -- particularly at
startup -- and having its presence change the behaviour of the
client is exactly what we don't want. */
/* croak? */
if (VG_(clo_track_fds) && allowed
&& !isNewFd && (VG_(strcmp)("close", syscallname) != 0)) {
const OpenFd *openbadfd = ML_(find_OpenFd)(fd);
if (!openbadfd) {
/* File descriptor which was never created (or inherited). */
struct FdBadUse badfd;
badfd.fd = fd;
badfd.pathname = NULL;
badfd.description = NULL;
badfd.where_opened = NULL;
badfd.where_closed = NULL;
VG_(maybe_record_error)(tid, FdBadUse, 0,
"was never created", &badfd);
} else if (openbadfd->fd_closed) {
/* Already closed file descriptor is being used. */
struct FdBadUse badfd;
badfd.fd = fd;
badfd.pathname = openbadfd->pathname;
badfd.description = openbadfd->description;
badfd.where_opened = openbadfd->where;
badfd.where_closed = openbadfd->where_closed;
VG_(maybe_record_error)(tid, FdBadUse, 0,
"was closed already", &badfd);
}
}
if ((!allowed) && !isNewFd) {
if (VG_(clo_track_fds)) {
struct FdBadUse badfd;
badfd.fd = fd;
badfd.pathname = NULL;
badfd.description = NULL;
badfd.where_opened = NULL;
badfd.where_closed = NULL;
VG_(maybe_record_error)(tid, FdBadUse, 0,
"Invalid file descriptor", &badfd);
} else if (VG_(showing_core_warnings) ()) {
// XXX legacy warnings, will be removed eventually
VG_(message)(Vg_UserMsg,
"Warning: invalid file descriptor %d in syscall %s()\n",
fd, syscallname);
}
if (VG_(showing_core_warnings) ()) {
if (fd == VG_(log_output_sink).fd && VG_(log_output_sink).fd >= 0)
VG_(message)(Vg_UserMsg,
" Use --log-fd=<number> to select an alternative log fd.\n");
if (fd == VG_(xml_output_sink).fd && VG_(xml_output_sink).fd >= 0)
VG_(message)(Vg_UserMsg,
" Use --xml-fd=<number> to select an alternative XML "
"output fd.\n");
// XXX This is the legacy warning, will be removed eventually
if (VG_(clo_verbosity) > 1 && !VG_(clo_track_fds)) {
VG_(get_and_pp_StackTrace)(tid, VG_(clo_backtrace_size));
}
}
}
return allowed;
}
/* ---------------------------------------------------------------------
Deal with a bunch of socket-related syscalls
------------------------------------------------------------------ */
/* ------ */
void
ML_(generic_PRE_sys_socketpair) ( ThreadId tid,
UWord arg0, UWord arg1,
UWord arg2, UWord arg3 )
{
/* int socketpair(int d, int type, int protocol, int sv[2]); */
PRE_MEM_WRITE( "socketcall.socketpair(sv)",
arg3, 2*sizeof(int) );
}
SysRes
ML_(generic_POST_sys_socketpair) ( ThreadId tid,
SysRes res,
UWord arg0, UWord arg1,
UWord arg2, UWord arg3 )
{
SysRes r = res;
Int fd1 = ((Int*)arg3)[0];
Int fd2 = ((Int*)arg3)[1];
vg_assert(!sr_isError(res)); /* guaranteed by caller */
POST_MEM_WRITE( arg3, 2*sizeof(int) );
if (!ML_(fd_allowed)(fd1, "socketcall.socketpair", tid, True) ||
!ML_(fd_allowed)(fd2, "socketcall.socketpair", tid, True)) {
VG_(close)(fd1);
VG_(close)(fd2);
r = VG_(mk_SysRes_Error)( VKI_EMFILE );
} else {
POST_MEM_WRITE( arg3, 2*sizeof(int) );
if (VG_(clo_track_fds)) {
ML_(record_fd_open_nameless)(tid, fd1);
ML_(record_fd_open_nameless)(tid, fd2);
}
}
return r;
}
/* ------ */
SysRes
ML_(generic_POST_sys_socket) ( ThreadId tid, SysRes res )
{
SysRes r = res;
vg_assert(!sr_isError(res)); /* guaranteed by caller */
if (!ML_(fd_allowed)(sr_Res(res), "socket", tid, True)) {
VG_(close)(sr_Res(res));
r = VG_(mk_SysRes_Error)( VKI_EMFILE );
} else {
if (VG_(clo_track_fds))
ML_(record_fd_open_nameless)(tid, sr_Res(res));
}
return r;
}
/* ------ */
void
ML_(generic_PRE_sys_bind) ( ThreadId tid,
UWord arg0, UWord arg1, UWord arg2 )
{
/* int bind(int sockfd, struct sockaddr *my_addr,
int addrlen); */
ML_(pre_mem_read_sockaddr) (
tid, "socketcall.bind(my_addr.%s)",
(struct vki_sockaddr *) arg1, arg2
);
}
/* ------ */
void
ML_(generic_PRE_sys_accept) ( ThreadId tid,
UWord arg0, UWord arg1, UWord arg2 )
{
/* int accept(int s, struct sockaddr *addr, int *addrlen); */
Addr addr_p = arg1;
Addr addrlen_p = arg2;
if (addr_p != (Addr)NULL)
ML_(buf_and_len_pre_check) ( tid, addr_p, addrlen_p,
"socketcall.accept(addr)",
"socketcall.accept(addrlen_in)" );
}
SysRes
ML_(generic_POST_sys_accept) ( ThreadId tid,
SysRes res,
UWord arg0, UWord arg1, UWord arg2 )
{
SysRes r = res;
vg_assert(!sr_isError(res)); /* guaranteed by caller */
if (!ML_(fd_allowed)(sr_Res(res), "accept", tid, True)) {
VG_(close)(sr_Res(res));
r = VG_(mk_SysRes_Error)( VKI_EMFILE );
} else {
Addr addr_p = arg1;
Addr addrlen_p = arg2;
if (addr_p != (Addr)NULL)
ML_(buf_and_len_post_check) ( tid, res, addr_p, addrlen_p,
"socketcall.accept(addrlen_out)" );
if (VG_(clo_track_fds))
ML_(record_fd_open_nameless)(tid, sr_Res(res));
}
return r;
}
/* ------ */
void
ML_(generic_PRE_sys_sendto) ( ThreadId tid,
UWord arg0, UWord arg1, UWord arg2,
UWord arg3, UWord arg4, UWord arg5 )
{
/* int sendto(int s, const void *msg, int len,
unsigned int flags,
const struct sockaddr *to, int tolen); */
PRE_MEM_READ( "socketcall.sendto(msg)",
arg1, /* msg */
arg2 /* len */ );
ML_(pre_mem_read_sockaddr) (
tid, "socketcall.sendto(to.%s)",
(struct vki_sockaddr *) arg4, arg5
);
}
/* ------ */
void
ML_(generic_PRE_sys_send) ( ThreadId tid,
UWord arg0, UWord arg1, UWord arg2 )
{
/* int send(int s, const void *msg, size_t len, int flags); */
PRE_MEM_READ( "socketcall.send(msg)",
arg1, /* msg */
arg2 /* len */ );
}
/* ------ */
void
ML_(generic_PRE_sys_recvfrom) ( ThreadId tid,
UWord arg0, UWord arg1, UWord arg2,
UWord arg3, UWord arg4, UWord arg5 )
{
/* int recvfrom(int s, void *buf, int len, unsigned int flags,
struct sockaddr *from, int *fromlen); */
Addr buf_p = arg1;
Int len = arg2;
Addr from_p = arg4;
Addr fromlen_p = arg5;
PRE_MEM_WRITE( "socketcall.recvfrom(buf)", buf_p, len );
if (from_p != (Addr)NULL)
ML_(buf_and_len_pre_check) ( tid, from_p, fromlen_p,
"socketcall.recvfrom(from)",
"socketcall.recvfrom(fromlen_in)" );
}
void
ML_(generic_POST_sys_recvfrom) ( ThreadId tid,
SysRes res,
UWord arg0, UWord arg1, UWord arg2,
UWord arg3, UWord arg4, UWord arg5 )
{
Addr buf_p = arg1;
Int len = arg2;
Addr from_p = arg4;
Addr fromlen_p = arg5;
vg_assert(!sr_isError(res)); /* guaranteed by caller */
if (from_p != (Addr)NULL)
ML_(buf_and_len_post_check) ( tid, res, from_p, fromlen_p,
"socketcall.recvfrom(fromlen_out)" );
POST_MEM_WRITE( buf_p, len );
}
/* ------ */
void
ML_(generic_PRE_sys_recv) ( ThreadId tid,
UWord arg0, UWord arg1, UWord arg2 )
{
/* int recv(int s, void *buf, int len, unsigned int flags); */
/* man 2 recv says:
The recv call is normally used only on a connected socket
(see connect(2)) and is identical to recvfrom with a NULL
from parameter.
*/
PRE_MEM_WRITE( "socketcall.recv(buf)",
arg1, /* buf */
arg2 /* len */ );
}
void
ML_(generic_POST_sys_recv) ( ThreadId tid,
UWord res,
UWord arg0, UWord arg1, UWord arg2 )
{
if (arg1 != 0) {
POST_MEM_WRITE( arg1, /* buf */
arg2 /* len */ );
}
}
/* ------ */
void
ML_(generic_PRE_sys_connect) ( ThreadId tid,
UWord arg0, UWord arg1, UWord arg2 )
{
/* int connect(int sockfd,
struct sockaddr *serv_addr, int addrlen ); */
ML_(pre_mem_read_sockaddr) ( tid,
"socketcall.connect(serv_addr.%s)",
(struct vki_sockaddr *) arg1, arg2);
}
/* ------ */
void
ML_(generic_PRE_sys_setsockopt) ( ThreadId tid,
UWord arg0, UWord arg1, UWord arg2,
UWord arg3, UWord arg4 )
{
/* int setsockopt(int s, int level, int optname,
const void *optval, int optlen); */
PRE_MEM_READ( "socketcall.setsockopt(optval)",
arg3, /* optval */
arg4 /* optlen */ );
}
/* ------ */
void
ML_(generic_PRE_sys_getsockname) ( ThreadId tid,
UWord arg0, UWord arg1, UWord arg2 )
{
/* int getsockname(int s, struct sockaddr* name, int* namelen) */
Addr name_p = arg1;
Addr namelen_p = arg2;
/* Nb: name_p cannot be NULL */
ML_(buf_and_len_pre_check) ( tid, name_p, namelen_p,
"socketcall.getsockname(name)",
"socketcall.getsockname(namelen_in)" );
}
void
ML_(generic_POST_sys_getsockname) ( ThreadId tid,
SysRes res,
UWord arg0, UWord arg1, UWord arg2 )
{
Addr name_p = arg1;
Addr namelen_p = arg2;
vg_assert(!sr_isError(res)); /* guaranteed by caller */
ML_(buf_and_len_post_check) ( tid, res, name_p, namelen_p,
"socketcall.getsockname(namelen_out)" );
}
/* ------ */
void
ML_(generic_PRE_sys_getpeername) ( ThreadId tid,
UWord arg0, UWord arg1, UWord arg2 )
{
/* int getpeername(int s, struct sockaddr* name, int* namelen) */
Addr name_p = arg1;
Addr namelen_p = arg2;
/* Nb: name_p cannot be NULL */
ML_(buf_and_len_pre_check) ( tid, name_p, namelen_p,
"socketcall.getpeername(name)",
"socketcall.getpeername(namelen_in)" );
}
void
ML_(generic_POST_sys_getpeername) ( ThreadId tid,
SysRes res,
UWord arg0, UWord arg1, UWord arg2 )
{
Addr name_p = arg1;
Addr namelen_p = arg2;
vg_assert(!sr_isError(res)); /* guaranteed by caller */
ML_(buf_and_len_post_check) ( tid, res, name_p, namelen_p,
"socketcall.getpeername(namelen_out)" );
}
/* ------ */
void
ML_(generic_PRE_sys_sendmsg) ( ThreadId tid, const HChar *name,
struct vki_msghdr *msg )
{
msghdr_foreachfield ( tid, name, msg, ~0, pre_mem_read_sendmsg, False );
}
/* ------ */
void
ML_(generic_PRE_sys_recvmsg) ( ThreadId tid, const HChar *name,
struct vki_msghdr *msg )
{
msghdr_foreachfield ( tid, name, msg, ~0, pre_mem_write_recvmsg, True );
}
void
ML_(generic_POST_sys_recvmsg) ( ThreadId tid, const HChar *name,
struct vki_msghdr *msg, UInt length )
{
msghdr_foreachfield( tid, name, msg, length, post_mem_write_recvmsg, True );
check_cmsg_for_fds( tid, msg );
}
/* ---------------------------------------------------------------------
Deal with a bunch of IPC related syscalls
------------------------------------------------------------------ */
/* ------ */
void
ML_(generic_PRE_sys_semop) ( ThreadId tid,
UWord arg0, UWord arg1, UWord arg2 )
{
/* int semop(int semid, struct sembuf *sops, unsigned nsops); */
PRE_MEM_READ( "semop(sops)", arg1, arg2 * sizeof(struct vki_sembuf) );
}
/* ------ */
void
ML_(generic_PRE_sys_semtimedop) ( ThreadId tid,
UWord arg0, UWord arg1,
UWord arg2, UWord arg3 )
{
/* int semtimedop(int semid, struct sembuf *sops, unsigned nsops,
struct timespec *timeout); */
PRE_MEM_READ( "semtimedop(sops)", arg1, arg2 * sizeof(struct vki_sembuf) );
if (arg3 != 0)
PRE_MEM_READ( "semtimedop(timeout)", arg3, sizeof(struct vki_timespec) );
}
/* ------ */
static
UInt get_sem_count( Int semid )
{
union vki_semun arg;
SysRes res;
# if defined(__NR_semctl)
# if defined(VGO_darwin)
/* Darwin has no specific 64 bit semid_ds, but has __NR_semctl. */
struct vki_semid_ds buf;
arg.buf = &buf;
# else
struct vki_semid64_ds buf;
arg.buf64 = &buf;
# endif
res = VG_(do_syscall4)(__NR_semctl, semid, 0, VKI_IPC_STAT, *(UWord *)&arg);
if (sr_isError(res))
return 0;
return buf.sem_nsems;
# elif defined(__NR___semctl) /* FreeBSD */
struct vki_semid_ds buf;
arg.buf = &buf;
res = VG_(do_syscall4)(__NR___semctl, semid, 0, VKI_IPC_STAT, (RegWord)&arg);
if (sr_isError(res))
return 0;
// both clang-tidy and coverity complain about this but I think they are both wrong
return buf.sem_nsems;
# elif defined(__NR_semsys) /* Solaris */
struct vki_semid_ds buf;
arg.buf = &buf;
res = VG_(do_syscall5)(__NR_semsys, VKI_SEMCTL, semid, 0, VKI_IPC_STAT,
*(UWord *)&arg);
if (sr_isError(res))
return 0;
return buf.sem_nsems;
# else
struct vki_semid_ds buf;
arg.buf = &buf;
res = VG_(do_syscall5)(__NR_ipc, 3 /* IPCOP_semctl */, semid, 0,
VKI_IPC_STAT, (UWord)&arg);
if (sr_isError(res))
return 0;
return buf.sem_nsems;
# endif
}
void
ML_(generic_PRE_sys_semctl) ( ThreadId tid,
UWord arg0, UWord arg1,
UWord arg2, UWord arg3 )
{
/* int semctl(int semid, int semnum, int cmd, ...); */
union vki_semun arg = *(union vki_semun *)&arg3;
UInt nsems;
switch (arg2 /* cmd */) {
#if defined(VKI_IPC_INFO)
case VKI_IPC_INFO:
case VKI_SEM_INFO:
#if defined(VKI_IPC_64)
case VKI_IPC_INFO|VKI_IPC_64:
case VKI_SEM_INFO|VKI_IPC_64:
#endif
#if defined(VGO_freebsd)
PRE_MEM_WRITE( "semctl(IPC_INFO, arg.buf)",
(Addr)arg.buf, sizeof(struct vki_semid_ds) );
#else
PRE_MEM_WRITE( "semctl(IPC_INFO, arg.buf)",
(Addr)arg.buf, sizeof(struct vki_seminfo) );
#endif
break;
#endif
case VKI_IPC_STAT:
#if defined(VKI_SEM_STAT)
case VKI_SEM_STAT:
#endif
PRE_MEM_WRITE( "semctl(IPC_STAT, arg.buf)",
(Addr)arg.buf, sizeof(struct vki_semid_ds) );
break;
#if defined(VKI_IPC_64)
case VKI_IPC_STAT|VKI_IPC_64:
#if defined(VKI_SEM_STAT)
case VKI_SEM_STAT|VKI_IPC_64:
#endif
#endif
#if defined(VKI_IPC_STAT64)
case VKI_IPC_STAT64:
#endif
#if defined(VKI_IPC_64) || defined(VKI_IPC_STAT64)
PRE_MEM_WRITE( "semctl(IPC_STAT, arg.buf)",
(Addr)arg.buf, sizeof(struct vki_semid64_ds) );
break;
#endif
case VKI_IPC_SET:
PRE_MEM_READ( "semctl(IPC_SET, arg.buf)",
(Addr)arg.buf, sizeof(struct vki_semid_ds) );
break;
#if defined(VKI_IPC_64)
case VKI_IPC_SET|VKI_IPC_64:
#endif
#if defined(VKI_IPC_SET64)
case VKI_IPC_SET64:
#endif
#if defined(VKI_IPC64) || defined(VKI_IPC_SET64)
PRE_MEM_READ( "semctl(IPC_SET, arg.buf)",
(Addr)arg.buf, sizeof(struct vki_semid64_ds) );
break;
#endif
case VKI_GETALL:
#if defined(VKI_IPC_64)
case VKI_GETALL|VKI_IPC_64:
#endif
nsems = get_sem_count( arg0 );
PRE_MEM_WRITE( "semctl(IPC_GETALL, arg.array)",
(Addr)arg.array, sizeof(unsigned short) * nsems );
break;
case VKI_SETALL:
#if defined(VKI_IPC_64)
case VKI_SETALL|VKI_IPC_64:
#endif
nsems = get_sem_count( arg0 );
PRE_MEM_READ( "semctl(IPC_SETALL, arg.array)",
(Addr)arg.array, sizeof(unsigned short) * nsems );
break;
}
}
void
ML_(generic_POST_sys_semctl) ( ThreadId tid,
UWord res,
UWord arg0, UWord arg1,
UWord arg2, UWord arg3 )
{
union vki_semun arg = *(union vki_semun *)&arg3;
UInt nsems;
switch (arg2 /* cmd */) {
#if defined(VKI_IPC_INFO)
case VKI_IPC_INFO:
case VKI_SEM_INFO:
#if defined(VKI_IPC_64)
case VKI_IPC_INFO|VKI_IPC_64:
case VKI_SEM_INFO|VKI_IPC_64:
#endif
#if defined(VGO_freebsd)
POST_MEM_WRITE( (Addr)arg.buf, sizeof(struct vki_semid_ds) );
#else
POST_MEM_WRITE( (Addr)arg.buf, sizeof(struct vki_seminfo) );
#endif
break;
#endif
case VKI_IPC_STAT:
#if defined(VKI_SEM_STAT)
case VKI_SEM_STAT:
#endif
POST_MEM_WRITE( (Addr)arg.buf, sizeof(struct vki_semid_ds) );
break;
#if defined(VKI_IPC_64)
case VKI_IPC_STAT|VKI_IPC_64:
case VKI_SEM_STAT|VKI_IPC_64:
#endif
#if defined(VKI_IPC_STAT64)
case VKI_IPC_STAT64:
#endif
#if defined(VKI_IPC_64) || defined(VKI_IPC_STAT64)
POST_MEM_WRITE( (Addr)arg.buf, sizeof(struct vki_semid64_ds) );
break;
#endif
case VKI_GETALL:
#if defined(VKI_IPC_64)
case VKI_GETALL|VKI_IPC_64:
#endif
nsems = get_sem_count( arg0 );
POST_MEM_WRITE( (Addr)arg.array, sizeof(unsigned short) * nsems );
break;
}
}
/* ------ */
/* ------ */
static
SizeT get_shm_size ( Int shmid )
{
/*
* The excluded platforms below gained direct shmctl in Linux 5.1. Keep
* using ipc-multiplexed shmctl to keep compatibility with older kernel
* versions.
*/
#if defined(__NR_shmctl) && \
!defined(VGP_x86_linux) && !defined(VGP_mips32_linux) && \
!defined(VGP_ppc32_linux) && !defined(VGP_ppc64be_linux) && \
!defined(VGP_ppc64le_linux) && !defined(VGP_s390x_linux)
# ifdef VKI_IPC_64
struct vki_shmid64_ds buf;
/*
* On Linux, the following ABIs use old shmid_ds by default with direct
* shmctl and require IPC_64 for shmid64_ds (i.e. the direct syscall is
* mapped to sys_old_shmctl):
* alpha, arm, microblaze, mips n32/n64, xtensa
* Other Linux ABIs use shmid64_ds by default and do not recognize IPC_64
* with the direct shmctl syscall (but still recognize it for the
* ipc-multiplexed version if that exists for the ABI).
*/
# if defined(VGO_linux) && !defined(VGP_arm_linux) && !defined(VGP_mips64_linux)
SysRes __res = VG_(do_syscall3)(__NR_shmctl, shmid,
VKI_IPC_STAT, (UWord)&buf);
# else
SysRes __res = VG_(do_syscall3)(__NR_shmctl, shmid,
VKI_IPC_STAT|VKI_IPC_64, (UWord)&buf);
# endif
# else /* !def VKI_IPC_64 */
struct vki_shmid_ds buf;
SysRes __res = VG_(do_syscall3)(__NR_shmctl, shmid, VKI_IPC_STAT, (UWord)&buf);
# endif /* def VKI_IPC_64 */
#elif defined(__NR_shmsys) /* Solaris */
struct vki_shmid_ds buf;
SysRes __res = VG_(do_syscall4)(__NR_shmsys, VKI_SHMCTL, shmid, VKI_IPC_STAT,
(UWord)&buf);
#else
struct vki_shmid_ds buf;
SysRes __res = VG_(do_syscall5)(__NR_ipc, 24 /* IPCOP_shmctl */, shmid,
VKI_IPC_STAT, 0, (UWord)&buf);
#endif
if (sr_isError(__res))
return 0;
return (SizeT) buf.shm_segsz;
}
UWord
ML_(generic_PRE_sys_shmat) ( ThreadId tid,
UWord arg0, UWord arg1, UWord arg2 )
{
/* void *shmat(int shmid, const void *shmaddr, int shmflg); */
SizeT segmentSize = get_shm_size ( arg0 );
UWord tmp;
Bool ok;
if (arg1 == 0) {
/* arm-linux only: work around the fact that
VG_(am_get_advisory_client_simple) produces something that is
VKI_PAGE_SIZE aligned, whereas what we want is something
VKI_SHMLBA aligned, and VKI_SHMLBA >= VKI_PAGE_SIZE. Hence
increase the request size by VKI_SHMLBA - VKI_PAGE_SIZE and
then round the result up to the next VKI_SHMLBA boundary.
See bug 222545 comment 15. So far, arm-linux is the only
platform where this is known to be necessary. */
vg_assert(VKI_SHMLBA >= VKI_PAGE_SIZE);
if (VKI_SHMLBA > VKI_PAGE_SIZE) {
segmentSize += VKI_SHMLBA - VKI_PAGE_SIZE;
}
tmp = VG_(am_get_advisory_client_simple)(0, segmentSize, &ok);
if (ok) {
if (VKI_SHMLBA > VKI_PAGE_SIZE) {
arg1 = VG_ROUNDUP(tmp, VKI_SHMLBA);
} else {
arg1 = tmp;
}
}
}
else if (!ML_(valid_client_addr)(arg1, segmentSize, tid, "shmat"))
arg1 = 0;
return arg1;
}
void
ML_(generic_POST_sys_shmat) ( ThreadId tid,
UWord res,
UWord arg0, UWord arg1, UWord arg2 )
{
SizeT segmentSize = VG_PGROUNDUP(get_shm_size(arg0));
if ( segmentSize > 0 ) {
UInt prot = VKI_PROT_READ|VKI_PROT_WRITE;
Bool d;
if (arg2 & VKI_SHM_RDONLY)
prot &= ~VKI_PROT_WRITE;
/* It isn't exactly correct to pass 0 for the fd and offset
here. The kernel seems to think the corresponding section
does have dev/ino numbers:
04e52000-04ec8000 rw-s 00000000 00:06 1966090 /SYSV00000000 (deleted)
However there is no obvious way to find them. In order to
cope with the discrepancy, aspacem's sync checker omits the
dev/ino correspondence check in cases where V does not know
the dev/ino. */
d = VG_(am_notify_client_shmat)( res, segmentSize, prot );
/* we don't distinguish whether it's read-only or
* read-write -- it doesn't matter really. */
VG_TRACK( new_mem_mmap, res, segmentSize, True, True, False,
0/*di_handle*/ );
if (d)
VG_(discard_translations)( (Addr)res,
(ULong)VG_PGROUNDUP(segmentSize),
"ML_(generic_POST_sys_shmat)" );
}
}
/* ------ */
Bool
ML_(generic_PRE_sys_shmdt) ( ThreadId tid, UWord arg0 )
{
/* int shmdt(const void *shmaddr); */
return ML_(valid_client_addr)(arg0, 1, tid, "shmdt");
}
void
ML_(generic_POST_sys_shmdt) ( ThreadId tid, UWord res, UWord arg0 )
{
NSegment const* s = VG_(am_find_nsegment)(arg0);
if (s != NULL) {
Addr s_start = s->start;
SizeT s_len = s->end+1 - s->start;
Bool d;
vg_assert(s->kind == SkShmC);
vg_assert(s->start == arg0);
d = VG_(am_notify_munmap)(s_start, s_len);
s = NULL; /* s is now invalid */
VG_TRACK( die_mem_munmap, s_start, s_len );
if (d)
VG_(discard_translations)( s_start,
(ULong)s_len,
"ML_(generic_POST_sys_shmdt)" );
}
}
/* ------ */
void
ML_(generic_PRE_sys_shmctl) ( ThreadId tid,
UWord arg0, UWord arg1, UWord arg2 )
{
/* int shmctl(int shmid, int cmd, struct shmid_ds *buf); */
switch (arg1 /* cmd */) {
#if defined(VKI_IPC_INFO)
case VKI_IPC_INFO:
# if defined(VGO_freebsd)
PRE_MEM_WRITE( "shmctl(IPC_INFO, buf)",
arg2, sizeof(struct vki_shmid_ds) );
# else
PRE_MEM_WRITE( "shmctl(IPC_INFO, buf)",
arg2, sizeof(struct vki_shminfo) );
# endif
break;
#if defined(VKI_IPC_64)
case VKI_IPC_INFO|VKI_IPC_64:
PRE_MEM_WRITE( "shmctl(IPC_INFO, buf)",
arg2, sizeof(struct vki_shminfo64) );
break;
#endif
#endif
#if defined(VKI_SHM_INFO)
case VKI_SHM_INFO:
#if defined(VKI_IPC_64)
case VKI_SHM_INFO|VKI_IPC_64:
#endif
PRE_MEM_WRITE( "shmctl(SHM_INFO, buf)",
arg2, sizeof(struct vki_shm_info) );
break;
#endif
case VKI_IPC_STAT:
#if defined(VKI_SHM_STAT)
case VKI_SHM_STAT:
#endif
PRE_MEM_WRITE( "shmctl(IPC_STAT, buf)",
arg2, sizeof(struct vki_shmid_ds) );
break;
#if defined(VKI_IPC_64)
case VKI_IPC_STAT|VKI_IPC_64:
case VKI_SHM_STAT|VKI_IPC_64:
PRE_MEM_WRITE( "shmctl(IPC_STAT, arg.buf)",
arg2, sizeof(struct vki_shmid64_ds) );
break;
#endif
case VKI_IPC_SET:
PRE_MEM_READ( "shmctl(IPC_SET, arg.buf)",
arg2, sizeof(struct vki_shmid_ds) );
break;
#if defined(VKI_IPC_64)
case VKI_IPC_SET|VKI_IPC_64:
PRE_MEM_READ( "shmctl(IPC_SET, arg.buf)",
arg2, sizeof(struct vki_shmid64_ds) );
break;
#endif
}
}
void
ML_(generic_POST_sys_shmctl) ( ThreadId tid,
UWord res,
UWord arg0, UWord arg1, UWord arg2 )
{
switch (arg1 /* cmd */) {
#if defined(VKI_IPC_INFO)
case VKI_IPC_INFO:
# if defined(VGO_freebsd)
POST_MEM_WRITE( arg2, sizeof(struct vki_shmid_ds) );
# else
POST_MEM_WRITE( arg2, sizeof(struct vki_shminfo) );
# endif
break;
#if defined(VKI_IPC_64)
case VKI_IPC_INFO|VKI_IPC_64:
POST_MEM_WRITE( arg2, sizeof(struct vki_shminfo64) );
break;
#endif
#endif
#if defined(VKI_SHM_INFO)
case VKI_SHM_INFO:
case VKI_SHM_INFO|VKI_IPC_64:
POST_MEM_WRITE( arg2, sizeof(struct vki_shm_info) );
break;
#endif
case VKI_IPC_STAT:
#if defined(VKI_SHM_STAT)
case VKI_SHM_STAT:
#endif
POST_MEM_WRITE( arg2, sizeof(struct vki_shmid_ds) );
break;
#if defined(VKI_IPC_64)
case VKI_IPC_STAT|VKI_IPC_64:
case VKI_SHM_STAT|VKI_IPC_64:
POST_MEM_WRITE( arg2, sizeof(struct vki_shmid64_ds) );
break;
#endif
}
}
/* ---------------------------------------------------------------------
Generic handler for mmap
------------------------------------------------------------------ */
/*
* Although mmap is specified by POSIX and the argument are generally
* consistent across platforms the precise details of the low level
* argument passing conventions differ. For example:
*
* - On x86-linux there is mmap (aka old_mmap) which takes the
* arguments in a memory block and the offset in bytes; and
* mmap2 (aka sys_mmap2) which takes the arguments in the normal
* way and the offset in pages.
*
* - On ppc32-linux there is mmap (aka sys_mmap) which takes the
* arguments in the normal way and the offset in bytes; and
* mmap2 (aka sys_mmap2) which takes the arguments in the normal
* way and the offset in pages.
*
* - On amd64-linux everything is simple and there is just the one
* call, mmap (aka sys_mmap) which takes the arguments in the
* normal way and the offset in bytes.
*
* - On s390x-linux there is mmap (aka old_mmap) which takes the
* arguments in a memory block and the offset in bytes. mmap2
* is also available (but not exported via unistd.h) with
* arguments in a memory block and the offset in pages.
*
* To cope with all this we provide a generic handler function here
* and then each platform implements one or more system call handlers
* which call this generic routine after extracting and normalising
* the arguments.
*/
SysRes
ML_(generic_PRE_sys_mmap) ( ThreadId tid,
UWord arg1, UWord arg2, UWord arg3,
UWord arg4, UWord arg5, Off64T arg6 )
{
Addr advised;
SysRes sres;
MapRequest mreq;
Bool mreq_ok;
# if defined(VGO_darwin)
// Nb: we can't use this on Darwin, it has races:
// * needs to RETRY if advisory succeeds but map fails
// (could have been some other thread in a nonblocking call)
// * needs to not use fixed-position mmap() on Darwin
// (mmap will cheerfully smash whatever's already there, which might
// be a new mapping from some other thread in a nonblocking call)
VG_(core_panic)("can't use ML_(generic_PRE_sys_mmap) on Darwin");
# endif
if (arg2 == 0) {
/* SuSV3 says: If len is zero, mmap() shall fail and no mapping
shall be established. */
return VG_(mk_SysRes_Error)( VKI_EINVAL );
}
if (!VG_IS_PAGE_ALIGNED(arg1)) {
/* zap any misaligned addresses. */
/* SuSV3 says misaligned addresses only cause the MAP_FIXED case
to fail. Here, we catch them all. */
return VG_(mk_SysRes_Error)( VKI_EINVAL );
}
if (!VG_IS_PAGE_ALIGNED(arg6)) {
/* zap any misaligned offsets. */
/* SuSV3 says: The off argument is constrained to be aligned and
sized according to the value returned by sysconf() when
passed _SC_PAGESIZE or _SC_PAGE_SIZE. */
return VG_(mk_SysRes_Error)( VKI_EINVAL );
}
/* Figure out what kind of allocation constraints there are
(fixed/hint/any), and ask aspacem what we should do. */
mreq.start = arg1;
mreq.len = arg2;
if (arg4 & VKI_MAP_FIXED) {
mreq.rkind = MFixed;
} else
#if defined(VKI_MAP_ALIGN) /* Solaris specific */
if (arg4 & VKI_MAP_ALIGN) {
mreq.rkind = MAlign;
if (mreq.start == 0) {
mreq.start = VKI_PAGE_SIZE;
}
/* VKI_MAP_FIXED and VKI_MAP_ALIGN don't like each other. */
arg4 &= ~VKI_MAP_ALIGN;
} else
#endif
if (arg1 != 0) {
mreq.rkind = MHint;
} else {
mreq.rkind = MAny;
}
/* Enquire ... */
advised = VG_(am_get_advisory)( &mreq, True/*client*/, &mreq_ok );
if (!mreq_ok) {
/* Our request was bounced, so we'd better fail. */
return VG_(mk_SysRes_Error)( VKI_EINVAL );
}
# if defined(VKI_MAP_32BIT)
/* MAP_32BIT is royally unportable, so if the client asks for it, try our
best to make it work (but without complexifying aspacemgr).
If the user requested MAP_32BIT, the mmap-ed space must be in the
first 2GB of the address space. So, return ENOMEM if aspacemgr
advisory is above the first 2GB. If MAP_FIXED is also requested,
MAP_32BIT has to be ignored.
Assumption about aspacemgr behaviour: aspacemgr scans the address space
from low addresses to find a free segment. No special effort is done
to keep the first 2GB 'free' for this MAP_32BIT. So, this will often
fail once the program has already allocated significant memory. */
if ((arg4 & VKI_MAP_32BIT) && !(arg4 & VKI_MAP_FIXED)) {
if (advised + arg2 >= 0x80000000)
return VG_(mk_SysRes_Error)( VKI_ENOMEM );
}
# endif
/* Otherwise we're OK (so far). Install aspacem's choice of
address, and let the mmap go through. */
sres = VG_(am_do_mmap_NO_NOTIFY)(advised, arg2, arg3,
arg4 | VKI_MAP_FIXED,
arg5, arg6);
# if defined(VKI_MAP_32BIT)
/* No recovery trial if the advisory was not accepted. */
if ((arg4 & VKI_MAP_32BIT) && !(arg4 & VKI_MAP_FIXED)
&& sr_isError(sres)) {
return VG_(mk_SysRes_Error)( VKI_ENOMEM );
}
# endif
/* A refinement: it may be that the kernel refused aspacem's choice
of address. If we were originally asked for a hinted mapping,
there is still a last chance: try again at any address.
Hence: */
if (mreq.rkind == MHint && sr_isError(sres)) {
mreq.start = 0;
mreq.len = arg2;
mreq.rkind = MAny;
advised = VG_(am_get_advisory)( &mreq, True/*client*/, &mreq_ok );
if (!mreq_ok) {
/* Our request was bounced, so we'd better fail. */
return VG_(mk_SysRes_Error)( VKI_EINVAL );
}
/* and try again with the kernel */
sres = VG_(am_do_mmap_NO_NOTIFY)(advised, arg2, arg3,
arg4 | VKI_MAP_FIXED,
arg5, arg6);
}
/* Yet another refinement : sometimes valgrind chooses an address
which is not acceptable by the kernel. This at least happens
when mmap-ing huge pages, using the flag MAP_HUGETLB.
valgrind aspacem does not know about huge pages, and modifying
it to handle huge pages is not straightforward (e.g. need
to understand special file system mount options).
So, let's just redo an mmap, without giving any constraint to
the kernel. If that succeeds, check with aspacem that the returned
address is acceptable.
This will give a similar effect as if the user would have
hinted that address.
The aspacem state will be correctly updated afterwards.
We however cannot do this last refinement when the user asked
for a fixed mapping, as the user asked a specific address. */
if (sr_isError(sres) && !(arg4 & VKI_MAP_FIXED)) {
advised = 0;
/* try mmap with NULL address and without VKI_MAP_FIXED
to let the kernel decide. */
sres = VG_(am_do_mmap_NO_NOTIFY)(advised, arg2, arg3,
arg4,
arg5, arg6);
if (!sr_isError(sres)) {
/* The kernel is supposed to know what it is doing, but let's
do a last sanity check anyway, as if the chosen address had
been initially hinted by the client. The whole point of this
last try was to allow mmap of huge pages to succeed without
making aspacem understand them, on the other hand the kernel
does not know about valgrind reservations, so this mapping
can end up in free space and reservations. */
mreq.start = (Addr)sr_Res(sres);
mreq.len = arg2;
mreq.rkind = MHint;
advised = VG_(am_get_advisory)( &mreq, True/*client*/, &mreq_ok );
vg_assert(mreq_ok && advised == mreq.start);
}
}
if (!sr_isError(sres)) {
ULong di_handle;
/* Notify aspacem. */
notify_core_of_mmap(
(Addr)sr_Res(sres), /* addr kernel actually assigned */
arg2, /* length */
arg3, /* prot */
arg4, /* the original flags value */
arg5, /* fd */
arg6 /* offset */
);
/* Load symbols? */
di_handle = VG_(di_notify_mmap)( (Addr)sr_Res(sres),
False/*allow_SkFileV*/, (Int)arg5 );
/* Notify the tool. */
notify_tool_of_mmap(
(Addr)sr_Res(sres), /* addr kernel actually assigned */
arg2, /* length */
arg3, /* prot */
di_handle /* so the tool can refer to the read debuginfo later,
if it wants. */
);
}
/* Stay sane */
if (!sr_isError(sres) && (arg4 & VKI_MAP_FIXED))
vg_assert(sr_Res(sres) == arg1);
return sres;
}
/* ---------------------------------------------------------------------
The Main Entertainment ... syscall wrappers
------------------------------------------------------------------ */
/* Note: the PRE() and POST() wrappers are for the actual functions
implementing the system calls in the OS kernel. These mostly have
names like sys_write(); a few have names like old_mmap(). See the
comment for ML_(syscall_table)[] for important info about the __NR_foo
constants and their relationship to the sys_foo() functions.
Some notes about names used for syscalls and args:
- For the --trace-syscalls=yes output, we use the sys_foo() name to avoid
ambiguity.
- For error messages, we generally use a somewhat generic name
for the syscall (eg. "write" rather than "sys_write"). This should be
good enough for the average user to understand what is happening,
without confusing them with names like "sys_write".
- Also, for error messages the arg names are mostly taken from the man
pages (even though many of those man pages are really for glibc
functions of the same name), rather than from the OS kernel source,
for the same reason -- a user presented with a "bogus foo(bar)" arg
will most likely look at the "foo" man page to see which is the "bar"
arg.
Note that we use our own vki_* types. The one exception is in
PRE_REG_READn calls, where pointer types haven't been changed, because
they don't need to be -- eg. for "foo*" to be used, the type foo need not
be visible.
XXX: some of these are arch-specific, and should be factored out.
*/
#define PRE(name) DEFN_PRE_TEMPLATE(generic, name)
#define POST(name) DEFN_POST_TEMPLATE(generic, name)
PRE(sys_exit)
{
ThreadState* tst;
/* simple; just make this thread exit */
PRINT("exit( %ld )", SARG1);
PRE_REG_READ1(void, "exit", int, status);
tst = VG_(get_ThreadState)(tid);
/* Set the thread's status to be exiting, then claim that the
syscall succeeded. */
tst->exitreason = VgSrc_ExitThread;
tst->os_state.exitcode = ARG1;
SET_STATUS_Success(0);
}
PRE(sys_ni_syscall)
{
PRINT("unimplemented (by the kernel) syscall: %s! (ni_syscall)\n",
VG_SYSNUM_STRING(SYSNO));
PRE_REG_READ0(long, "ni_syscall");
SET_STATUS_Failure( VKI_ENOSYS );
}
PRE(sys_iopl)
{
PRINT("sys_iopl ( %" FMT_REGWORD "u )", ARG1);
PRE_REG_READ1(long, "iopl", unsigned long, level);
}
PRE(sys_fsync)
{
*flags |= SfMayBlock;
PRINT("sys_fsync ( %" FMT_REGWORD "u )", ARG1);
PRE_REG_READ1(long, "fsync", unsigned int, fd);
}
PRE(sys_fdatasync)
{
*flags |= SfMayBlock;
PRINT("sys_fdatasync ( %" FMT_REGWORD "u )", ARG1);
PRE_REG_READ1(long, "fdatasync", unsigned int, fd);
}
PRE(sys_msync)
{
*flags |= SfMayBlock;
PRINT("sys_msync ( %#" FMT_REGWORD "x, %" FMT_REGWORD "u, %#"
FMT_REGWORD "x )", ARG1, ARG2, ARG3);
PRE_REG_READ3(long, "msync",
unsigned long, start, vki_size_t, length, int, flags);
PRE_MEM_READ( "msync(start)", ARG1, ARG2 );
}
// Nb: getpmsg() and putpmsg() are special additional syscalls used in early
// versions of LiS (Linux Streams). They are not part of the kernel.
// Therefore, we have to provide this type ourself, rather than getting it
// from the kernel sources.
struct vki_pmsg_strbuf {
int maxlen; /* no. of bytes in buffer */
int len; /* no. of bytes returned */
vki_caddr_t buf; /* pointer to data */
};
PRE(sys_getpmsg)
{
/* LiS getpmsg from http://www.gcom.com/home/linux/lis/ */
struct vki_pmsg_strbuf *ctrl;
struct vki_pmsg_strbuf *data;
*flags |= SfMayBlock;
PRINT("sys_getpmsg ( %ld, %#" FMT_REGWORD "x, %#" FMT_REGWORD "x, %#"
FMT_REGWORD "x, %#" FMT_REGWORD "x )", SARG1,
ARG2, ARG3, ARG4, ARG5);
PRE_REG_READ5(int, "getpmsg",
int, fd, struct strbuf *, ctrl, struct strbuf *, data,
int *, bandp, int *, flagsp);
ctrl = (struct vki_pmsg_strbuf *)(Addr)ARG2;
data = (struct vki_pmsg_strbuf *)(Addr)ARG3;
if (ctrl && ctrl->maxlen > 0)
PRE_MEM_WRITE( "getpmsg(ctrl)", (Addr)ctrl->buf, ctrl->maxlen);
if (data && data->maxlen > 0)
PRE_MEM_WRITE( "getpmsg(data)", (Addr)data->buf, data->maxlen);
if (ARG4)
PRE_MEM_WRITE( "getpmsg(bandp)", (Addr)ARG4, sizeof(int));
if (ARG5)
PRE_MEM_WRITE( "getpmsg(flagsp)", (Addr)ARG5, sizeof(int));
}
POST(sys_getpmsg)
{
struct vki_pmsg_strbuf *ctrl;
struct vki_pmsg_strbuf *data;
vg_assert(SUCCESS);
ctrl = (struct vki_pmsg_strbuf *)(Addr)ARG2;
data = (struct vki_pmsg_strbuf *)(Addr)ARG3;
if (RES == 0 && ctrl && ctrl->len > 0) {
POST_MEM_WRITE( (Addr)ctrl->buf, ctrl->len);
}
if (RES == 0 && data && data->len > 0) {
POST_MEM_WRITE( (Addr)data->buf, data->len);
}
}
PRE(sys_putpmsg)
{
/* LiS putpmsg from http://www.gcom.com/home/linux/lis/ */
struct vki_pmsg_strbuf *ctrl;
struct vki_pmsg_strbuf *data;
*flags |= SfMayBlock;
PRINT("sys_putpmsg ( %ld, %#" FMT_REGWORD "x, %#" FMT_REGWORD
"x, %ld, %ld )", SARG1, ARG2, ARG3, SARG4, SARG5);
PRE_REG_READ5(int, "putpmsg",
int, fd, struct strbuf *, ctrl, struct strbuf *, data,
int, band, int, flags);
ctrl = (struct vki_pmsg_strbuf *)(Addr)ARG2;
data = (struct vki_pmsg_strbuf *)(Addr)ARG3;
if (ctrl && ctrl->len > 0)
PRE_MEM_READ( "putpmsg(ctrl)", (Addr)ctrl->buf, ctrl->len);
if (data && data->len > 0)
PRE_MEM_READ( "putpmsg(data)", (Addr)data->buf, data->len);
}
PRE(sys_getitimer)
{
struct vki_itimerval *value = (struct vki_itimerval*)(Addr)ARG2;
PRINT("sys_getitimer ( %ld, %#" FMT_REGWORD "x )", SARG1, ARG2);
PRE_REG_READ2(long, "getitimer", int, which, struct itimerval *, value);
PRE_timeval_WRITE( "getitimer(&value->it_interval)", &(value->it_interval));
PRE_timeval_WRITE( "getitimer(&value->it_value)", &(value->it_value));
}
POST(sys_getitimer)
{
if (ARG2 != (Addr)NULL) {
struct vki_itimerval *value = (struct vki_itimerval*)(Addr)ARG2;
POST_timeval_WRITE( &(value->it_interval) );
POST_timeval_WRITE( &(value->it_value) );
}
}
PRE(sys_setitimer)
{
PRINT("sys_setitimer ( %ld, %#" FMT_REGWORD "x, %#" FMT_REGWORD "x )",
SARG1, ARG2, ARG3);
PRE_REG_READ3(long, "setitimer",
int, which,
struct itimerval *, value, struct itimerval *, ovalue);
if (ARG2 != (Addr)NULL) {
struct vki_itimerval *value = (struct vki_itimerval*)(Addr)ARG2;
PRE_timeval_READ( "setitimer(&value->it_interval)",
&(value->it_interval));
PRE_timeval_READ( "setitimer(&value->it_value)",
&(value->it_value));
}
if (ARG3 != (Addr)NULL) {
struct vki_itimerval *ovalue = (struct vki_itimerval*)(Addr)ARG3;
PRE_timeval_WRITE( "setitimer(&ovalue->it_interval)",
&(ovalue->it_interval));
PRE_timeval_WRITE( "setitimer(&ovalue->it_value)",
&(ovalue->it_value));
}
}
POST(sys_setitimer)
{
if (ARG3 != (Addr)NULL) {
struct vki_itimerval *ovalue = (struct vki_itimerval*)(Addr)ARG3;
POST_timeval_WRITE( &(ovalue->it_interval) );
POST_timeval_WRITE( &(ovalue->it_value) );
}
}
PRE(sys_chroot)
{
PRINT("sys_chroot ( %#" FMT_REGWORD "x )", ARG1);
PRE_REG_READ1(long, "chroot", const char *, path);
PRE_MEM_RASCIIZ( "chroot(path)", ARG1 );
}
PRE(sys_madvise)
{
*flags |= SfMayBlock;
PRINT("sys_madvise ( %#" FMT_REGWORD "x, %" FMT_REGWORD "u, %ld )",
ARG1, ARG2, SARG3);
PRE_REG_READ3(long, "madvise",
unsigned long, start, vki_size_t, length, int, advice);
}
#if HAVE_MREMAP
PRE(sys_mremap)
{
// Nb: this is different to the glibc version described in the man pages,
// which lacks the fifth 'new_address' argument.
if (ARG4 & VKI_MREMAP_FIXED) {
PRINT("sys_mremap ( %#" FMT_REGWORD "x, %" FMT_REGWORD "u, %"
FMT_REGWORD "u, %#" FMT_REGWORD "x, %#" FMT_REGWORD "x )",
ARG1, ARG2, ARG3, ARG4, ARG5);
PRE_REG_READ5(unsigned long, "mremap",
unsigned long, old_addr, unsigned long, old_size,
unsigned long, new_size, unsigned long, flags,
unsigned long, new_addr);
} else {
PRINT("sys_mremap ( %#" FMT_REGWORD "x, %" FMT_REGWORD "u, %"
FMT_REGWORD "u, 0x%" FMT_REGWORD "x )",
ARG1, ARG2, ARG3, ARG4);
PRE_REG_READ4(unsigned long, "mremap",
unsigned long, old_addr, unsigned long, old_size,
unsigned long, new_size, unsigned long, flags);
}
SET_STATUS_from_SysRes(
do_mremap((Addr)ARG1, ARG2, (Addr)ARG5, ARG3, ARG4, tid)
);
}
#endif /* HAVE_MREMAP */
PRE(sys_nice)
{
PRINT("sys_nice ( %ld )", SARG1);
PRE_REG_READ1(long, "nice", int, inc);
}
PRE(sys_mlock2)
{
*flags |= SfMayBlock;
PRINT("sys_mlock2 ( %#" FMT_REGWORD "x, %" FMT_REGWORD "u, %" FMT_REGWORD "u )", ARG1, ARG2, ARG3);
PRE_REG_READ2(int, "mlock2", void*, addr, vki_size_t, len);
}
PRE(sys_mlock)
{
*flags |= SfMayBlock;
PRINT("sys_mlock ( %#" FMT_REGWORD "x, %" FMT_REGWORD "u )", ARG1, ARG2);
PRE_REG_READ2(long, "mlock", unsigned long, addr, vki_size_t, len);
}
PRE(sys_munlock)
{
*flags |= SfMayBlock;
PRINT("sys_munlock ( %#" FMT_REGWORD "x, %" FMT_REGWORD "u )", ARG1, ARG2);
PRE_REG_READ2(long, "munlock", unsigned long, addr, vki_size_t, len);
}
PRE(sys_mlockall)
{
*flags |= SfMayBlock;
PRINT("sys_mlockall ( %" FMT_REGWORD "x )", ARG1);
PRE_REG_READ1(long, "mlockall", int, flags);
}
PRE(sys_setpriority)
{
PRINT("sys_setpriority ( %ld, %ld, %ld )", SARG1, SARG2, SARG3);
PRE_REG_READ3(long, "setpriority", int, which, int, who, int, prio);
}
PRE(sys_getpriority)
{
PRINT("sys_getpriority ( %ld, %ld )", SARG1, SARG2);
PRE_REG_READ2(long, "getpriority", int, which, int, who);
}
#if !defined(VGO_freebsd)
PRE(sys_pwrite64)
{
*flags |= SfMayBlock;
#if VG_WORDSIZE == 4
PRINT("sys_pwrite64 ( %" FMT_REGWORD "u, %#" FMT_REGWORD "x, %"
FMT_REGWORD "u, %lld )", ARG1, ARG2, ARG3, (Long)MERGE64(ARG4,ARG5));
PRE_REG_READ5(ssize_t, "pwrite64",
unsigned int, fd, const char *, buf, vki_size_t, count,
vki_u32, MERGE64_FIRST(offset), vki_u32, MERGE64_SECOND(offset));
#elif VG_WORDSIZE == 8
PRINT("sys_pwrite64 ( %lu, %#lx, %lu, %ld )",
ARG1, ARG2, ARG3, SARG4);
PRE_REG_READ4(ssize_t, "pwrite64",
unsigned int, fd, const char *, buf, vki_size_t, count,
Word, offset);
#else
# error Unexpected word size
#endif
PRE_MEM_READ( "pwrite64(buf)", ARG2, ARG3 );
}
#endif
PRE(sys_sync)
{
*flags |= SfMayBlock;
PRINT("sys_sync ( )");
PRE_REG_READ0(long, "sync");
}
#if !defined(VGP_nanomips_linux)
PRE(sys_fstatfs)
{
FUSE_COMPATIBLE_MAY_BLOCK();
PRINT("sys_fstatfs ( %" FMT_REGWORD "u, %#" FMT_REGWORD "x )", ARG1, ARG2);
PRE_REG_READ2(long, "fstatfs",
unsigned int, fd, struct statfs *, buf);
PRE_MEM_WRITE( "fstatfs(buf)", ARG2, sizeof(struct vki_statfs) );
}
POST(sys_fstatfs)
{
POST_MEM_WRITE( ARG2, sizeof(struct vki_statfs) );
}
PRE(sys_fstatfs64)
{
FUSE_COMPATIBLE_MAY_BLOCK();
PRINT("sys_fstatfs64 ( %" FMT_REGWORD "u, %" FMT_REGWORD "u, %#"
FMT_REGWORD "x )", ARG1, ARG2, ARG3);
PRE_REG_READ3(long, "fstatfs64",
unsigned int, fd, vki_size_t, size, struct statfs64 *, buf);
PRE_MEM_WRITE( "fstatfs64(buf)", ARG3, ARG2 );
}
POST(sys_fstatfs64)
{
POST_MEM_WRITE( ARG3, ARG2 );
}
#endif
PRE(sys_getsid)
{
PRINT("sys_getsid ( %ld )", SARG1);
PRE_REG_READ1(long, "getsid", vki_pid_t, pid);
}
#if !defined(VGO_freebsd)
PRE(sys_pread64)
{
*flags |= SfMayBlock;
#if VG_WORDSIZE == 4
PRINT("sys_pread64 ( %" FMT_REGWORD "u, %#" FMT_REGWORD "x, %"
FMT_REGWORD "u, %lld )", ARG1, ARG2, ARG3, (Long)MERGE64(ARG4,ARG5));
PRE_REG_READ5(ssize_t, "pread64",
unsigned int, fd, char *, buf, vki_size_t, count,
vki_u32, MERGE64_FIRST(offset), vki_u32, MERGE64_SECOND(offset));
#elif VG_WORDSIZE == 8
PRINT("sys_pread64 ( %lu, %#lx, %lu, %ld )",
ARG1, ARG2, ARG3, SARG4);
PRE_REG_READ4(ssize_t, "pread64",
unsigned int, fd, char *, buf, vki_size_t, count,
Word, offset);
#else
# error Unexpected word size
#endif
PRE_MEM_WRITE( "pread64(buf)", ARG2, ARG3 );
}
POST(sys_pread64)
{
vg_assert(SUCCESS);
if (RES > 0) {
POST_MEM_WRITE( ARG2, RES );
}
}
#endif
PRE(sys_mknod)
{
FUSE_COMPATIBLE_MAY_BLOCK();
PRINT("sys_mknod ( %#" FMT_REGWORD "x(%s), %#" FMT_REGWORD "x, %#"
FMT_REGWORD "x )", ARG1, (HChar*)(Addr)ARG1, ARG2, ARG3 );
PRE_REG_READ3(long, "mknod",
const char *, pathname, int, mode, unsigned, dev);
PRE_MEM_RASCIIZ( "mknod(pathname)", ARG1 );
}
PRE(sys_flock)
{
*flags |= SfMayBlock;
PRINT("sys_flock ( %" FMT_REGWORD "u, %" FMT_REGWORD "u )", ARG1, ARG2 );
PRE_REG_READ2(long, "flock", unsigned int, fd, unsigned int, operation);
}
// Pre_read a char** argument.
void ML_(pre_argv_envp)(Addr a, ThreadId tid, const HChar *s1, const HChar *s2)
{
while (True) {
Addr a_deref;
Addr* a_p = (Addr*)a;
PRE_MEM_READ( s1, (Addr)a_p, sizeof(Addr) );
a_deref = *a_p;
if (0 == a_deref)
break;
PRE_MEM_RASCIIZ( s2, a_deref );
a += sizeof(char*);
}
}
static Bool i_am_the_only_thread ( void )
{
Int c = VG_(count_living_threads)();
vg_assert(c >= 1); /* stay sane */
return c == 1;
}
/* Wait until all other threads disappear. */
void VG_(reap_threads)(ThreadId self)
{
while (!i_am_the_only_thread()) {
/* Let other thread(s) run */
VG_(vg_yield)();
VG_(poll_signals)(self);
}
vg_assert(i_am_the_only_thread());
}
/* This handles the common part of the PRE macro for execve and execveat. */
void handle_pre_sys_execve(ThreadId tid, SyscallStatus *status, Addr pathname,
Addr arg_2, Addr arg_3, ExecveType execveType,
Bool check_pathptr)
{
HChar* path = NULL; /* path to executable */
HChar** envp = NULL;
HChar** argv = NULL;
HChar** arg2copy;
HChar* launcher_basename = NULL;
ThreadState* tst;
Int i, j, tot_args;
SysRes res;
Bool setuid_allowed, trace_this_child;
const char *str;
char str2[30], str3[30];
Addr arg_2_check = arg_2;
switch (execveType) {
case EXECVE:
str = "execve";
break;
case EXECVEAT:
str = "execveat";
break;
case FEXECVE:
str = "fexecve";
break;
default:
vg_assert(False);
}
VG_(strcpy)(str2, str);
VG_(strcpy)(str3, str);
VG_(strcat)(str2, "(argv)");
VG_(strcat)(str3, "(argv[0])");
/* argv[] should not be NULL and valid. */
PRE_MEM_READ(str2, arg_2_check, sizeof(Addr));
/* argv[0] should not be NULL and valid. */
if (ML_(safe_to_deref)((HChar **) (Addr)arg_2_check, sizeof(HChar *))) {
Addr argv0 = *(Addr*)arg_2_check;
PRE_MEM_RASCIIZ( str3, argv0 );
/* The rest of argv can be NULL or a valid string pointer. */
if (VG_(am_is_valid_for_client)(arg_2_check, sizeof(HChar), VKI_PROT_READ)) {
arg_2_check += sizeof(HChar*);
str3[VG_(strlen)(str)] = '\0';
VG_(strcat)(str3, "(argv[i])");
ML_(pre_argv_envp)( arg_2_check, tid, str2, str3 );
}
} else {
SET_STATUS_Failure(VKI_EFAULT);
return;
}
// Reset helper strings to syscall name.
str2[VG_(strlen)(str)] = '\0';
str3[VG_(strlen)(str)] = '\0';
if (arg_3 != 0) {
/* At least the terminating NULL must be addressable. */
if (!ML_(safe_to_deref)((HChar **) (Addr)arg_3, sizeof(HChar *))) {
SET_STATUS_Failure(VKI_EFAULT);
return;
}
VG_(strcat)(str2, "(envp)");
VG_(strcat)(str3, "(envp[i])");
ML_(pre_argv_envp)( arg_3, tid, str2, str3 );
}
vg_assert(VG_(is_valid_tid)(tid));
tst = VG_(get_ThreadState)(tid);
/* Erk. If the exec fails, then the following will have made a
mess of things which makes it hard for us to continue. The
right thing to do is piece everything together again in
POST(execve), but that's close to impossible. Instead, we make
an effort to check that the execve will work before actually
doing it. */
/* Check that the name at least begins in client-accessible storage.
If we didn't create it ourselves in execveat. */
if (check_pathptr
&& !VG_(am_is_valid_for_client)( pathname, 1, VKI_PROT_READ )) {
SET_STATUS_Failure( VKI_EFAULT );
return;
}
// debug-only printing
if (0) {
VG_(printf)("pathname = %p(%s)\n", (void*)(Addr)pathname, (HChar*)(Addr)pathname);
if (arg_2) {
VG_(printf)("arg_2 = ");
Int q;
HChar** vec = (HChar**)(Addr)arg_2;
for (q = 0; vec[q]; q++)
VG_(printf)("%p(%s) ", vec[q], vec[q]);
VG_(printf)("\n");
} else {
VG_(printf)("arg_2 = null\n");
}
}
// Decide whether or not we want to follow along
{ // Make 'child_argv' be a pointer to the child's arg vector
// (skipping the exe name)
const HChar** child_argv = (const HChar**)(Addr)arg_2;
if (child_argv && child_argv[0] == NULL)
child_argv = NULL;
trace_this_child = VG_(should_we_trace_this_child)( (HChar*)(Addr)pathname,
child_argv );
}
// Do the important checks: it is a file, is executable, permissions are
// ok, etc. We allow setuid executables to run only in the case when
// we are not simulating them, that is, they to be run natively.
setuid_allowed = trace_this_child ? False : True;
res = VG_(pre_exec_check)((const HChar *)(Addr)pathname, NULL, setuid_allowed);
if (sr_isError(res)) {
SET_STATUS_Failure( sr_Err(res) );
return;
}
/* If we're tracing the child, and the launcher name looks bogus
(possibly because launcher.c couldn't figure it out, see
comments therein) then we have no option but to fail. */
if (trace_this_child
&& (VG_(name_of_launcher) == NULL
|| VG_(name_of_launcher)[0] != '/')) {
SET_STATUS_Failure( VKI_ECHILD ); /* "No child processes" */
return;
}
/* After this point, we can't recover if the execve fails. */
VG_(debugLog)(1, "syswrap", "Exec of %s\n", (HChar*)(Addr)pathname);
// Terminate gdbserver if it is active.
if (VG_(clo_vgdb) != Vg_VgdbNo) {
// If the child will not be traced, we need to terminate gdbserver
// to cleanup the gdbserver resources (e.g. the FIFO files).
// If child will be traced, we also terminate gdbserver: the new
// Valgrind will start a fresh gdbserver after exec.
VG_(gdbserver) (0);
}
/* Resistance is futile. Nuke all other threads. POSIX mandates
this. (Really, nuke them all, since the new process will make
its own new thread.) */
VG_(nuke_all_threads_except)( tid, VgSrc_ExitThread );
VG_(reap_threads)(tid);
// Set up the child's exe path.
//
if (trace_this_child) {
// We want to exec the launcher. Get its pre-remembered path.
path = VG_(name_of_launcher);
// VG_(name_of_launcher) should have been acquired by m_main at
// startup.
vg_assert(path);
launcher_basename = VG_(strrchr)(path, '/');
if (launcher_basename == NULL || launcher_basename[1] == 0) {
launcher_basename = path; // hmm, tres dubious
} else {
launcher_basename++;
}
} else {
path = (HChar*)(Addr)pathname;
}
// Set up the child's environment.
//
// Remove the valgrind-specific stuff from the environment so the
// child doesn't get vgpreload_core.so, vgpreload_<tool>.so, etc.
// This is done unconditionally, since if we are tracing the child,
// the child valgrind will set up the appropriate client environment.
// Nb: we make a copy of the environment before trying to mangle it
// as it might be in read-only memory (this was bug #101881).
//
// Then, if tracing the child, set VALGRIND_LIB for it.
//
if (arg_3 == 0) {
envp = NULL;
} else {
envp = VG_(env_clone)( (HChar**)(Addr)arg_3 );
if (envp == NULL) goto hosed;
VG_(env_remove_valgrind_env_stuff)( envp, True /*ro_strings*/, NULL );
}
if (trace_this_child) {
// Set VALGRIND_LIB in arg_3 (the environment)
VG_(env_setenv)( &envp, VALGRIND_LIB, VG_(libdir));
}
// Set up the child's args. If not tracing it, they are
// simply arg_2. Otherwise, they are
//
// [launcher_basename] ++ VG_(args_for_valgrind) ++ [pathname] ++ arg_2[1..]
//
// except that the first VG_(args_for_valgrind_noexecpass) args
// are omitted.
//
if (!trace_this_child) {
argv = (HChar**)(Addr)arg_2;
} else {
vg_assert( VG_(args_for_valgrind) );
vg_assert( VG_(args_for_valgrind_noexecpass) >= 0 );
vg_assert( VG_(args_for_valgrind_noexecpass)
<= VG_(sizeXA)( VG_(args_for_valgrind) ) );
/* how many args in total will there be? */
// launcher basename
tot_args = 1;
// V's args
tot_args += VG_(sizeXA)( VG_(args_for_valgrind) );
tot_args -= VG_(args_for_valgrind_noexecpass);
// name of client exe
tot_args++;
// args for client exe, skipping [0]
arg2copy = (HChar**)(Addr)arg_2;
if (arg2copy && arg2copy[0]) {
for (i = 1; arg2copy[i]; i++)
tot_args++;
}
// allocate
argv = VG_(malloc)( "di.syswrap.pre_sys_execve.1",
(tot_args+1) * sizeof(HChar*) );
// copy
j = 0;
argv[j++] = launcher_basename;
for (i = 0; i < VG_(sizeXA)( VG_(args_for_valgrind) ); i++) {
if (i < VG_(args_for_valgrind_noexecpass))
continue;
argv[j++] = * (HChar**) VG_(indexXA)( VG_(args_for_valgrind), i );
}
argv[j++] = (HChar*)(Addr)pathname;
if (arg2copy && arg2copy[0])
for (i = 1; arg2copy[i]; i++)
argv[j++] = arg2copy[i];
argv[j++] = NULL;
// check
vg_assert(j == tot_args+1);
}
/*
Set the signal state up for exec.
We need to set the real signal state to make sure the exec'd
process gets SIG_IGN properly.
Also set our real sigmask to match the client's sigmask so that
the exec'd child will get the right mask. First we need to
clear out any pending signals so they they don't get delivered,
which would confuse things.
XXX This is a bug - the signals should remain pending, and be
delivered to the new process after exec. There's also a
race-condition, since if someone delivers us a signal between
the sigprocmask and the execve, we'll still get the signal. Oh
well.
*/
{
vki_sigset_t allsigs;
vki_siginfo_t info;
/* What this loop does: it queries SCSS (the signal state that
the client _thinks_ the kernel is in) by calling
VG_(do_sys_sigaction), and modifies the real kernel signal
state accordingly. */
for (i = 1; i < VG_(max_signal); i++) {
vki_sigaction_fromK_t sa_f;
vki_sigaction_toK_t sa_t;
VG_(do_sys_sigaction)(i, NULL, &sa_f);
VG_(convert_sigaction_fromK_to_toK)(&sa_f, &sa_t);
if (sa_t.ksa_handler == VKI_SIG_IGN)
VG_(sigaction)(i, &sa_t, NULL);
else {
sa_t.ksa_handler = VKI_SIG_DFL;
VG_(sigaction)(i, &sa_t, NULL);
}
}
VG_(sigfillset)(&allsigs);
while(VG_(sigtimedwait_zero)(&allsigs, &info) > 0)
;
VG_(sigprocmask)(VKI_SIG_SETMASK, &tst->sig_mask, NULL);
}
if (0) {
HChar **cpp;
VG_(printf)("exec: %s\n", path);
for (cpp = argv; cpp && *cpp; cpp++)
VG_(printf)("argv: %s\n", *cpp);
if (0)
for (cpp = envp; cpp && *cpp; cpp++)
VG_(printf)("env: %s\n", *cpp);
}
// always execute this because it's executing valgrind, not the "target" exe
SET_STATUS_from_SysRes(
VG_(do_syscall3)(__NR_execve, (UWord)path, (UWord)argv, (UWord)envp));
/* If we got here, then the execve failed. We've already made way
too much of a mess to continue, so we have to abort. */
hosed:
vg_assert(FAILURE);
VG_(message)(Vg_UserMsg, "execve(%#" FMT_REGWORD "x(%s), %#" FMT_REGWORD
"x, %#" FMT_REGWORD "x) failed, errno %lu\n",
pathname, (HChar*)(Addr)pathname, arg_2, arg_3, ERR);
VG_(message)(Vg_UserMsg, "EXEC FAILED: I can't recover from "
"execve() failing, so I'm dying.\n");
VG_(message)(Vg_UserMsg, "Add more stringent tests in PRE(sys_execve), "
"or work out how to recover.\n");
VG_(exit)(101);
}
// XXX: prototype here seemingly doesn't match the prototype for i386-linux,
// but it seems to work nonetheless...
PRE(sys_execve)
{
PRINT("sys_execve ( %#" FMT_REGWORD "x(%s), %#" FMT_REGWORD "x, %#"
FMT_REGWORD "x )", ARG1, (HChar*)(Addr)ARG1, ARG2, ARG3);
PRE_REG_READ3(vki_off_t, "execve",
char *, filename, char **, argv, char **, envp);
PRE_MEM_RASCIIZ( "execve(filename)", ARG1 );
char *pathname = (char *)ARG1;
Addr arg_2 = (Addr)ARG2;
Addr arg_3 = (Addr)ARG3;
handle_pre_sys_execve(tid, status, (Addr)pathname, arg_2, arg_3, EXECVE, True);
}
PRE(sys_access)
{
FUSE_COMPATIBLE_MAY_BLOCK();
PRINT("sys_access ( %#" FMT_REGWORD "x(%s), %ld )", ARG1,
(HChar*)(Addr)ARG1, SARG2);
PRE_REG_READ2(long, "access", const char *, pathname, int, mode);
PRE_MEM_RASCIIZ( "access(pathname)", ARG1 );
}
PRE(sys_alarm)
{
PRINT("sys_alarm ( %" FMT_REGWORD "u )", ARG1);
PRE_REG_READ1(unsigned long, "alarm", unsigned int, seconds);
}
PRE(sys_brk)
{
Addr brk_limit = VG_(brk_limit);
Addr brk_new;
/* libc says: int brk(void *end_data_segment);
kernel says: void* brk(void* end_data_segment); (more or less)
libc returns 0 on success, and -1 (and sets errno) on failure.
Nb: if you ask to shrink the dataseg end below what it
currently is, that always succeeds, even if the dataseg end
doesn't actually change (eg. brk(0)). Unless it seg faults.
Kernel returns the new dataseg end. If the brk() failed, this
will be unchanged from the old one. That's why calling (kernel)
brk(0) gives the current dataseg end (libc brk() just returns
zero in that case).
Both will seg fault if you shrink it back into a text segment.
*/
PRINT("sys_brk ( %#" FMT_REGWORD "x )", ARG1);
PRE_REG_READ1(unsigned long, "brk", unsigned long, end_data_segment);
brk_new = do_brk(ARG1, tid);
SET_STATUS_Success( brk_new );
if (brk_new == ARG1) {
/* brk() succeeded */
if (brk_new < brk_limit) {
/* successfully shrunk the data segment. */
VG_TRACK( die_mem_brk, (Addr)ARG1,
brk_limit-ARG1 );
} else
if (brk_new > brk_limit) {
/* successfully grew the data segment */
VG_TRACK( new_mem_brk, brk_limit,
ARG1-brk_limit, tid );
}
} else {
/* brk() failed */
vg_assert(brk_limit == brk_new);
}
}
PRE(sys_chdir)
{
FUSE_COMPATIBLE_MAY_BLOCK();
PRINT("sys_chdir ( %#" FMT_REGWORD "x(%s) )", ARG1,(char*)(Addr)ARG1);
PRE_REG_READ1(long, "chdir", const char *, path);
PRE_MEM_RASCIIZ( "chdir(path)", ARG1 );
}
PRE(sys_chmod)
{
FUSE_COMPATIBLE_MAY_BLOCK();
PRINT("sys_chmod ( %#" FMT_REGWORD "x(%s), %" FMT_REGWORD "u )", ARG1,
(HChar*)(Addr)ARG1, ARG2);
PRE_REG_READ2(long, "chmod", const char *, path, vki_mode_t, mode);
PRE_MEM_RASCIIZ( "chmod(path)", ARG1 );
}
PRE(sys_chown)
{
FUSE_COMPATIBLE_MAY_BLOCK();
PRINT("sys_chown ( %#" FMT_REGWORD "x(%s), 0x%" FMT_REGWORD "x, 0x%"
FMT_REGWORD "x )", ARG1,(char*)(Addr)ARG1,ARG2,ARG3);
PRE_REG_READ3(long, "chown",
const char *, path, vki_uid_t, owner, vki_gid_t, group);
PRE_MEM_RASCIIZ( "chown(path)", ARG1 );
}
PRE(sys_lchown)
{
FUSE_COMPATIBLE_MAY_BLOCK();
PRINT("sys_lchown ( %#" FMT_REGWORD "x(%s), 0x%" FMT_REGWORD "x, 0x%"
FMT_REGWORD "x )", ARG1,(char*)(Addr)ARG1,ARG2,ARG3);
PRE_REG_READ3(long, "lchown",
const char *, path, vki_uid_t, owner, vki_gid_t, group);
PRE_MEM_RASCIIZ( "lchown(path)", ARG1 );
}
PRE(sys_close)
{
FUSE_COMPATIBLE_MAY_BLOCK();
PRINT("sys_close ( %" FMT_REGWORD "u )", ARG1);
PRE_REG_READ1(long, "close", unsigned int, fd);
/* Detect and negate attempts by the client to close Valgrind's log fd */
if ( (!ML_(fd_allowed)(ARG1, "close", tid, False))
/* If doing -d style logging (which is to fd=2), don't
allow that to be closed either. */
|| (ARG1 == 2/*stderr*/ && VG_(debugLog_getLevel)() > 0) )
SET_STATUS_Failure( VKI_EBADF );
else {
/* We used to do close tracking in the POST handler, but that is
only called on success. Even if the close syscall fails the
file descriptor is still really closed/invalid. So we do the
recording and checking here. */
if (VG_(clo_track_fds)) ML_(record_fd_close)(tid, ARG1);
}
}
PRE(sys_dup)
{
PRINT("sys_dup ( %" FMT_REGWORD "u )", ARG1);
PRE_REG_READ1(long, "dup", unsigned int, oldfd);
}
POST(sys_dup)
{
vg_assert(SUCCESS);
if (!ML_(fd_allowed)(RES, "dup", tid, True)) {
VG_(close)(RES);
SET_STATUS_Failure( VKI_EMFILE );
} else {
if (VG_(clo_track_fds))
ML_(record_fd_open_named)(tid, RES);
}
}
PRE(sys_dup2)
{
PRINT("sys_dup2 ( %" FMT_REGWORD "u, %" FMT_REGWORD "u )", ARG1, ARG2);
PRE_REG_READ2(long, "dup2", unsigned int, oldfd, unsigned int, newfd);
if (!ML_(fd_allowed)(ARG2, "dup2", tid, True))
SET_STATUS_Failure( VKI_EBADF );
}
POST(sys_dup2)
{
vg_assert(SUCCESS);
if (VG_(clo_track_fds))
ML_(record_fd_open_named)(tid, RES);
}
PRE(sys_fchdir)
{
FUSE_COMPATIBLE_MAY_BLOCK();
PRINT("sys_fchdir ( %" FMT_REGWORD "u )", ARG1);
PRE_REG_READ1(long, "fchdir", unsigned int, fd);
}
PRE(sys_fchown)
{
FUSE_COMPATIBLE_MAY_BLOCK();
PRINT("sys_fchown ( %" FMT_REGWORD "u, %" FMT_REGWORD "u, %"
FMT_REGWORD "u )", ARG1, ARG2, ARG3);
PRE_REG_READ3(long, "fchown",
unsigned int, fd, vki_uid_t, owner, vki_gid_t, group);
}
PRE(sys_fchmod)
{
FUSE_COMPATIBLE_MAY_BLOCK();
PRINT("sys_fchmod ( %" FMT_REGWORD "u, %" FMT_REGWORD "u )", ARG1, ARG2);
PRE_REG_READ2(long, "fchmod", unsigned int, fildes, vki_mode_t, mode);
}
#if !defined(VGP_nanomips_linux) && !defined (VGO_freebsd)
PRE(sys_newfstat)
{
FUSE_COMPATIBLE_MAY_BLOCK();
PRINT("sys_newfstat ( %" FMT_REGWORD "u, %#" FMT_REGWORD "x )", ARG1, ARG2);
PRE_REG_READ2(long, "fstat", unsigned int, fd, struct stat *, buf);
PRE_MEM_WRITE( "fstat(buf)", ARG2, sizeof(struct vki_stat) );
}
POST(sys_newfstat)
{
POST_MEM_WRITE( ARG2, sizeof(struct vki_stat) );
}
#endif
#if !defined(VGO_solaris) && !defined(VGP_arm64_linux) && \
!defined(VGP_nanomips_linux)
static vki_sigset_t fork_saved_mask;
// In Linux, the sys_fork() function varies across architectures, but we
// ignore the various args it gets, and so it looks arch-neutral. Hmm.
PRE(sys_fork)
{
Bool is_child;
Int child_pid;
vki_sigset_t mask;
PRINT("sys_fork ( )");
PRE_REG_READ0(long, "fork");
/* Block all signals during fork, so that we can fix things up in
the child without being interrupted. */
VG_(sigfillset)(&mask);
VG_(sigprocmask)(VKI_SIG_SETMASK, &mask, &fork_saved_mask);
VG_(do_atfork_pre)(tid);
SET_STATUS_from_SysRes( VG_(do_syscall0)(__NR_fork) );
if (!SUCCESS) return;
#if defined(VGO_linux) || defined(VGO_freebsd)
// RES is 0 for child, non-0 (the child's PID) for parent.
is_child = ( RES == 0 ? True : False );
child_pid = ( is_child ? -1 : RES );
#elif defined(VGO_darwin)
// RES is the child's pid. RESHI is 1 for child, 0 for parent.
is_child = RESHI;
child_pid = RES;
#else
# error Unknown OS
#endif
if (is_child) {
VG_(do_atfork_child)(tid);
/* restore signal mask */
VG_(sigprocmask)(VKI_SIG_SETMASK, &fork_saved_mask, NULL);
} else {
VG_(do_atfork_parent)(tid);
PRINT(" fork: process %d created child %d\n", VG_(getpid)(), child_pid);
/* restore signal mask */
VG_(sigprocmask)(VKI_SIG_SETMASK, &fork_saved_mask, NULL);
}
}
#endif // !defined(VGO_solaris) && !defined(VGP_arm64_linux)
PRE(sys_ftruncate)
{
*flags |= SfMayBlock;
PRINT("sys_ftruncate ( %" FMT_REGWORD "u, %" FMT_REGWORD "u )", ARG1, ARG2);
PRE_REG_READ2(long, "ftruncate", unsigned int, fd, unsigned long, length);
}
PRE(sys_truncate)
{
*flags |= SfMayBlock;
PRINT("sys_truncate ( %#" FMT_REGWORD "x(%s), %" FMT_REGWORD "u )",
ARG1, (HChar*)(Addr)ARG1, ARG2);
PRE_REG_READ2(long, "truncate",
const char *, path, unsigned long, length);
PRE_MEM_RASCIIZ( "truncate(path)", ARG1 );
}
PRE(sys_ftruncate64)
{
*flags |= SfMayBlock;
#if VG_WORDSIZE == 4
PRINT("sys_ftruncate64 ( %" FMT_REGWORD "u, %llu )", ARG1,
MERGE64(ARG2,ARG3));
PRE_REG_READ3(long, "ftruncate64",
unsigned int, fd,
UWord, MERGE64_FIRST(length), UWord, MERGE64_SECOND(length));
#else
PRINT("sys_ftruncate64 ( %lu, %lu )", ARG1, ARG2);
PRE_REG_READ2(long, "ftruncate64",
unsigned int,fd, UWord,length);
#endif
}
PRE(sys_truncate64)
{
*flags |= SfMayBlock;
#if VG_WORDSIZE == 4
PRINT("sys_truncate64 ( %#" FMT_REGWORD "x, %lld )", ARG1,
(Long)MERGE64(ARG2, ARG3));
PRE_REG_READ3(long, "truncate64",
const char *, path,
UWord, MERGE64_FIRST(length), UWord, MERGE64_SECOND(length));
#else
PRINT("sys_truncate64 ( %#lx, %lld )", ARG1, (Long)ARG2);
PRE_REG_READ2(long, "truncate64",
const char *,path, UWord,length);
#endif
PRE_MEM_RASCIIZ( "truncate64(path)", ARG1 );
}
PRE(sys_getdents)
{
*flags |= SfMayBlock;
PRINT("sys_getdents ( %" FMT_REGWORD "u, %#" FMT_REGWORD "x, %" FMT_REGWORD
"u )", ARG1, ARG2, ARG3);
PRE_REG_READ3(long, "getdents",
unsigned int, fd, struct vki_dirent *, dirp,
unsigned int, count);
PRE_MEM_WRITE( "getdents(dirp)", ARG2, ARG3 );
}
POST(sys_getdents)
{
vg_assert(SUCCESS);
if (RES > 0)
POST_MEM_WRITE( ARG2, RES );
}
PRE(sys_getdents64)
{
*flags |= SfMayBlock;
PRINT("sys_getdents64 ( %" FMT_REGWORD "u, %#" FMT_REGWORD "x, %"
FMT_REGWORD "u )",ARG1, ARG2, ARG3);
PRE_REG_READ3(long, "getdents64",
unsigned int, fd, struct vki_dirent64 *, dirp,
unsigned int, count);
PRE_MEM_WRITE( "getdents64(dirp)", ARG2, ARG3 );
}
POST(sys_getdents64)
{
vg_assert(SUCCESS);
if (RES > 0)
POST_MEM_WRITE( ARG2, RES );
}
PRE(sys_getgroups)
{
PRINT("sys_getgroups ( %ld, %#" FMT_REGWORD "x )", SARG1, ARG2);
PRE_REG_READ2(long, "getgroups", int, size, vki_gid_t *, list);
if (ARG1 > 0)
PRE_MEM_WRITE( "getgroups(list)", ARG2, ARG1 * sizeof(vki_gid_t) );
}
POST(sys_getgroups)
{
vg_assert(SUCCESS);
if (ARG1 > 0 && RES > 0)
POST_MEM_WRITE( ARG2, RES * sizeof(vki_gid_t) );
}
PRE(sys_getcwd)
{
// Comment from linux/fs/dcache.c:
// NOTE! The user-level library version returns a character pointer.
// The kernel system call just returns the length of the buffer filled
// (which includes the ending '\0' character), or a negative error
// value.
// Is this Linux-specific? If so it should be moved to syswrap-linux.c.
PRINT("sys_getcwd ( %#" FMT_REGWORD "x, %llu )", ARG1,(ULong)ARG2);
PRE_REG_READ2(long, "getcwd", char *, buf, unsigned long, size);
PRE_MEM_WRITE( "getcwd(buf)", ARG1, ARG2 );
}
POST(sys_getcwd)
{
vg_assert(SUCCESS);
if (RES != (Addr)NULL)
POST_MEM_WRITE( ARG1, RES );
}
PRE(sys_geteuid)
{
PRINT("sys_geteuid ( )");
PRE_REG_READ0(long, "geteuid");
}
PRE(sys_getegid)
{
PRINT("sys_getegid ( )");
PRE_REG_READ0(long, "getegid");
}
PRE(sys_getgid)
{
PRINT("sys_getgid ( )");
PRE_REG_READ0(long, "getgid");
}
PRE(sys_getpid)
{
PRINT("sys_getpid ()");
PRE_REG_READ0(long, "getpid");
}
PRE(sys_getpgid)
{
PRINT("sys_getpgid ( %ld )", SARG1);
PRE_REG_READ1(long, "getpgid", vki_pid_t, pid);
}
PRE(sys_getpgrp)
{
PRINT("sys_getpgrp ()");
PRE_REG_READ0(long, "getpgrp");
}
PRE(sys_getppid)
{
PRINT("sys_getppid ()");
PRE_REG_READ0(long, "getppid");
}
static void common_post_getrlimit(ThreadId tid, UWord a1, UWord a2)
{
POST_MEM_WRITE( a2, sizeof(struct vki_rlimit) );
#ifdef _RLIMIT_POSIX_FLAG
// Darwin will sometimes set _RLIMIT_POSIX_FLAG on getrlimit calls.
// Unset it here to make the switch case below work correctly.
a1 &= ~_RLIMIT_POSIX_FLAG;
#endif
switch (a1) {
case VKI_RLIMIT_NOFILE:
((struct vki_rlimit *)a2)->rlim_cur = VG_(fd_soft_limit);
((struct vki_rlimit *)a2)->rlim_max = VG_(fd_hard_limit);
break;
case VKI_RLIMIT_DATA:
*((struct vki_rlimit *)a2) = VG_(client_rlimit_data);
break;
case VKI_RLIMIT_STACK:
*((struct vki_rlimit *)a2) = VG_(client_rlimit_stack);
break;
}
}
PRE(sys_old_getrlimit)
{
PRINT("sys_old_getrlimit ( %" FMT_REGWORD "u, %#" FMT_REGWORD "x )",
ARG1, ARG2);
PRE_REG_READ2(long, "old_getrlimit",
unsigned int, resource, struct rlimit *, rlim);
PRE_MEM_WRITE( "old_getrlimit(rlim)", ARG2, sizeof(struct vki_rlimit) );
}
POST(sys_old_getrlimit)
{
common_post_getrlimit(tid, ARG1, ARG2);
}
PRE(sys_getrlimit)
{
PRINT("sys_getrlimit ( %" FMT_REGWORD "u, %#" FMT_REGWORD "x )", ARG1, ARG2);
PRE_REG_READ2(long, "getrlimit",
unsigned int, resource, struct rlimit *, rlim);
PRE_MEM_WRITE( "getrlimit(rlim)", ARG2, sizeof(struct vki_rlimit) );
}
POST(sys_getrlimit)
{
common_post_getrlimit(tid, ARG1, ARG2);
}
PRE(sys_getrusage)
{
PRINT("sys_getrusage ( %ld, %#" FMT_REGWORD "x )", SARG1, ARG2);
PRE_REG_READ2(long, "getrusage", int, who, struct rusage *, usage);
PRE_MEM_WRITE( "getrusage(usage)", ARG2, sizeof(struct vki_rusage) );
}
POST(sys_getrusage)
{
vg_assert(SUCCESS);
if (RES == 0)
POST_MEM_WRITE( ARG2, sizeof(struct vki_rusage) );
}
PRE(sys_gettimeofday)
{
PRINT("sys_gettimeofday ( %#" FMT_REGWORD "x, %#" FMT_REGWORD "x )",
ARG1,ARG2);
PRE_REG_READ2(long, "gettimeofday",
struct timeval *, tv, struct timezone *, tz);
// GrP fixme does darwin write to *tz anymore?
if (ARG1 != 0)
PRE_timeval_WRITE( "gettimeofday(tv)", (Addr)ARG1 );
if (ARG2 != 0)
PRE_MEM_WRITE( "gettimeofday(tz)", ARG2, sizeof(struct vki_timezone) );
}
POST(sys_gettimeofday)
{
vg_assert(SUCCESS);
if (RES == 0) {
if (ARG1 != 0)
POST_timeval_WRITE( (Addr)ARG1 );
if (ARG2 != 0)
POST_MEM_WRITE( ARG2, sizeof(struct vki_timezone) );
}
}
PRE(sys_settimeofday)
{
PRINT("sys_settimeofday ( %#" FMT_REGWORD "x, %#" FMT_REGWORD "x )",
ARG1,ARG2);
PRE_REG_READ2(long, "settimeofday",
struct timeval *, tv, struct timezone *, tz);
if (ARG1 != 0)
PRE_timeval_READ( "settimeofday(tv)", (Addr)ARG1 );
if (ARG2 != 0) {
PRE_MEM_READ( "settimeofday(tz)", ARG2, sizeof(struct vki_timezone) );
/* maybe should warn if tz->tz_dsttime is non-zero? */
}
}
PRE(sys_getuid)
{
PRINT("sys_getuid ( )");
PRE_REG_READ0(long, "getuid");
}
void ML_(PRE_unknown_ioctl)(ThreadId tid, UWord request, UWord arg)
{
/* We don't have any specific information on it, so
try to do something reasonable based on direction and
size bits. The encoding scheme is described in
/usr/include/asm/ioctl.h or /usr/include/sys/ioccom.h .
According to Simon Hausmann, _IOC_READ means the kernel
writes a value to the ioctl value passed from the user
space and the other way around with _IOC_WRITE. */
#if defined(VGO_solaris)
/* Majority of Solaris ioctl requests does not honour direction hints. */
UInt dir = _VKI_IOC_NONE;
#else
UInt dir = _VKI_IOC_DIR(request);
#endif
UInt size = _VKI_IOC_SIZE(request);
if (SimHintiS(SimHint_lax_ioctls, VG_(clo_sim_hints))) {
/*
* Be very lax about ioctl handling; the only
* assumption is that the size is correct. Doesn't
* require the full buffer to be initialized when
* writing. Without this, using some device
* drivers with a large number of strange ioctl
* commands becomes very tiresome.
*/
} else if (dir == _VKI_IOC_NONE && size > 0) {
static UWord unknown_ioctl[10];
static Int moans = sizeof(unknown_ioctl) / sizeof(unknown_ioctl[0]);
if (moans > 0 && !VG_(clo_xml)) {
/* Check if have not already moaned for this request. */
UInt i;
for (i = 0; i < sizeof(unknown_ioctl)/sizeof(unknown_ioctl[0]); i++) {
if (unknown_ioctl[i] == request)
break;
if (unknown_ioctl[i] == 0) {
unknown_ioctl[i] = request;
moans--;
VG_(umsg)("Warning: noted but unhandled ioctl 0x%lx"
" with no direction hints.\n", request);
VG_(umsg)(" This could cause spurious value errors to appear.\n");
VG_(umsg)(" See README_MISSING_SYSCALL_OR_IOCTL for "
"guidance on writing a proper wrapper.\n" );
//VG_(get_and_pp_StackTrace)(tid, VG_(clo_backtrace_size));
return;
}
}
}
} else {
//VG_(message)(Vg_UserMsg, "UNKNOWN ioctl %#lx\n", request);
//VG_(get_and_pp_StackTrace)(tid, VG_(clo_backtrace_size));
if ((dir & _VKI_IOC_WRITE) && size > 0)
PRE_MEM_READ( "ioctl(generic)", arg, size);
if ((dir & _VKI_IOC_READ) && size > 0)
PRE_MEM_WRITE( "ioctl(generic)", arg, size);
}
}
void ML_(POST_unknown_ioctl)(ThreadId tid, UInt res, UWord request, UWord arg)
{
/* We don't have any specific information on it, so
try to do something reasonable based on direction and
size bits. The encoding scheme is described in
/usr/include/asm/ioctl.h or /usr/include/sys/ioccom.h .
According to Simon Hausmann, _IOC_READ means the kernel
writes a value to the ioctl value passed from the user
space and the other way around with _IOC_WRITE. */
UInt dir = _VKI_IOC_DIR(request);
UInt size = _VKI_IOC_SIZE(request);
if (size > 0 && (dir & _VKI_IOC_READ)
&& res == 0
&& arg != (Addr)NULL) {
POST_MEM_WRITE(arg, size);
}
}
/*
If we're sending a SIGKILL to one of our own threads, then simulate
it rather than really sending the signal, so that the target thread
gets a chance to clean up. Returns True if we did the killing (or
no killing is necessary), and False if the caller should use the
normal kill syscall.
"pid" is any pid argument which can be passed to kill; group kills
(< -1, 0), and owner kills (-1) are ignored, on the grounds that
they'll most likely hit all the threads and we won't need to worry
about cleanup. In truth, we can't fully emulate these multicast
kills.
"tgid" is a thread group id. If it is not -1, then the target
thread must be in that thread group.
*/
Bool ML_(do_sigkill)(Int pid, Int tgid)
{
ThreadState *tst;
ThreadId tid;
if (pid <= 0)
return False;
tid = VG_(lwpid_to_vgtid)(pid);
if (tid == VG_INVALID_THREADID)
return False; /* none of our threads */
tst = VG_(get_ThreadState)(tid);
if (tst == NULL || tst->status == VgTs_Empty)
return False; /* hm, shouldn't happen */
if (tgid != -1 && tst->os_state.threadgroup != tgid)
return False; /* not the right thread group */
/* Fatal SIGKILL sent to one of our threads.
"Handle" the signal ourselves, as trying to have tid
handling the signal causes termination problems (see #409367
and #409141).
Moreover, as a process cannot do anything when receiving SIGKILL,
it is not particularly crucial that "tid" does the work to
terminate the process. */
if (VG_(clo_trace_signals))
VG_(message)(Vg_DebugMsg,
"Thread %u %s being killed with SIGKILL, running tid: %u\n",
tst->tid, VG_(name_of_ThreadStatus) (tst->status), VG_(running_tid));
if (!VG_(is_running_thread)(tid))
tst = VG_(get_ThreadState)(VG_(running_tid));
VG_(nuke_all_threads_except) (VG_(running_tid), VgSrc_FatalSig);
VG_(reap_threads)(VG_(running_tid));
tst->exitreason = VgSrc_FatalSig;
tst->os_state.fatalsig = VKI_SIGKILL;
return True;
}
PRE(sys_kill)
{
PRINT("sys_kill ( %ld, %ld )", SARG1, SARG2);
PRE_REG_READ2(long, "kill", int, pid, int, signal);
if (!ML_(client_signal_OK)(ARG2)) {
SET_STATUS_Failure( VKI_EINVAL );
return;
}
/* If we're sending SIGKILL, check to see if the target is one of
our threads and handle it specially. */
if (ARG2 == VKI_SIGKILL && ML_(do_sigkill)(ARG1, -1))
SET_STATUS_Success(0);
else
/* re syscall3: Darwin has a 3rd arg, which is a flag (boolean)
affecting how posix-compliant the call is. I guess it is
harmless to pass the 3rd arg on other platforms; hence pass
it on all. */
SET_STATUS_from_SysRes( VG_(do_syscall3)(SYSNO, ARG1, ARG2, ARG3) );
if (VG_(clo_trace_signals))
VG_(message)(Vg_DebugMsg, "kill: sent signal %ld to pid %ld\n",
SARG2, SARG1);
/* This kill might have given us a pending signal. Ask for a check once
the syscall is done. */
*flags |= SfPollAfter;
}
PRE(sys_link)
{
*flags |= SfMayBlock;
PRINT("sys_link ( %#" FMT_REGWORD "x(%s), %#" FMT_REGWORD "x(%s) )", ARG1,
(char*)(Addr)ARG1,ARG2,(char*)(Addr)ARG2);
PRE_REG_READ2(long, "link", const char *, oldpath, const char *, newpath);
PRE_MEM_RASCIIZ( "link(oldpath)", ARG1);
PRE_MEM_RASCIIZ( "link(newpath)", ARG2);
}
#if !defined(VGP_nanomips_linux) && !defined(VGO_freebsd)
PRE(sys_newlstat)
{
PRINT("sys_newlstat ( %#" FMT_REGWORD "x(%s), %#" FMT_REGWORD "x )", ARG1,
(char*)(Addr)ARG1,ARG2);
PRE_REG_READ2(long, "lstat", char *, file_name, struct stat *, buf);
PRE_MEM_RASCIIZ( "lstat(file_name)", ARG1 );
PRE_MEM_WRITE( "lstat(buf)", ARG2, sizeof(struct vki_stat) );
}
POST(sys_newlstat)
{
vg_assert(SUCCESS);
POST_MEM_WRITE( ARG2, sizeof(struct vki_stat) );
}
#endif
PRE(sys_mkdir)
{
*flags |= SfMayBlock;
PRINT("sys_mkdir ( %#" FMT_REGWORD "x(%s), %ld )", ARG1,
(HChar*)(Addr)ARG1, SARG2);
PRE_REG_READ2(long, "mkdir", const char *, pathname, int, mode);
PRE_MEM_RASCIIZ( "mkdir(pathname)", ARG1 );
}
PRE(sys_mprotect)
{
PRINT("sys_mprotect ( %#" FMT_REGWORD "x, %" FMT_REGWORD "u, %"
FMT_REGWORD "u )", ARG1, ARG2, ARG3);
PRE_REG_READ3(long, "mprotect",
unsigned long, addr, vki_size_t, len, unsigned long, prot);
Addr addr = ARG1;
SizeT len = ARG2;
Int prot = ARG3;
handle_sys_mprotect (tid, status, &addr, &len, &prot);
ARG1 = addr;
ARG2 = len;
ARG3 = prot;
}
/* This will be called from the generic mprotect, or the linux specific
pkey_mprotect. Pass pointers to ARG1, ARG2 and ARG3 as addr, len and prot,
they might be adjusted and have to assigned back to ARG1, ARG2 and ARG3. */
void handle_sys_mprotect(ThreadId tid, SyscallStatus* status,
Addr *addr, SizeT *len, Int *prot)
{
if (!ML_(valid_client_addr)(*addr, *len, tid, "mprotect")) {
#if defined(VGO_freebsd)
SET_STATUS_Failure( VKI_EINVAL );
#else
SET_STATUS_Failure( VKI_ENOMEM );
#endif
}
#if defined(VKI_PROT_GROWSDOWN)
else
if (*prot & (VKI_PROT_GROWSDOWN|VKI_PROT_GROWSUP)) {
/* Deal with mprotects on growable stack areas.
The critical files to understand all this are mm/mprotect.c
in the kernel and sysdeps/unix/sysv/linux/dl-execstack.c in
glibc.
The kernel provides PROT_GROWSDOWN and PROT_GROWSUP which
round the start/end address of mprotect to the start/end of
the underlying vma and glibc uses that as an easy way to
change the protection of the stack by calling mprotect on the
last page of the stack with PROT_GROWSDOWN set.
The sanity check provided by the kernel is that the vma must
have the VM_GROWSDOWN/VM_GROWSUP flag set as appropriate. */
UInt grows = *prot & (VKI_PROT_GROWSDOWN|VKI_PROT_GROWSUP);
NSegment const *aseg = VG_(am_find_nsegment)(*addr);
NSegment const *rseg;
vg_assert(aseg);
if (grows == VKI_PROT_GROWSDOWN) {
rseg = VG_(am_next_nsegment)( aseg, False/*backwards*/ );
if (rseg
&& rseg->kind == SkResvn
&& rseg->smode == SmUpper
&& rseg->end+1 == aseg->start) {
Addr end = *addr + *len;
*addr = aseg->start;
*len = end - aseg->start;
*prot &= ~VKI_PROT_GROWSDOWN;
} else {
SET_STATUS_Failure( VKI_EINVAL );
}
} else if (grows == VKI_PROT_GROWSUP) {
rseg = VG_(am_next_nsegment)( aseg, True/*forwards*/ );
if (rseg
&& rseg->kind == SkResvn
&& rseg->smode == SmLower
&& aseg->end+1 == rseg->start) {
*len = aseg->end - *addr + 1;
*prot &= ~VKI_PROT_GROWSUP;
} else {
SET_STATUS_Failure( VKI_EINVAL );
}
} else {
/* both GROWSUP and GROWSDOWN */
SET_STATUS_Failure( VKI_EINVAL );
}
}
#endif // defined(VKI_PROT_GROWSDOWN)
}
POST(sys_mprotect)
{
Addr a = ARG1;
SizeT len = ARG2;
Int prot = ARG3;
ML_(notify_core_and_tool_of_mprotect)(a, len, prot);
}
PRE(sys_munmap)
{
if (0) VG_(printf)(" munmap( %#" FMT_REGWORD "x )\n", ARG1);
PRINT("sys_munmap ( %#" FMT_REGWORD "x, %llu )", ARG1,(ULong)ARG2);
PRE_REG_READ2(long, "munmap", unsigned long, start, vki_size_t, length);
if (!ML_(valid_client_addr)(ARG1, ARG2, tid, "munmap"))
SET_STATUS_Failure( VKI_EINVAL );
}
POST(sys_munmap)
{
Addr a = ARG1;
SizeT len = ARG2;
ML_(notify_core_and_tool_of_munmap)( a, len );
}
PRE(sys_mincore)
{
PRINT("sys_mincore ( %#" FMT_REGWORD "x, %llu, %#" FMT_REGWORD "x )",
ARG1, (ULong)ARG2, ARG3);
PRE_REG_READ3(long, "mincore",
unsigned long, start, vki_size_t, length,
unsigned char *, vec);
PRE_MEM_WRITE( "mincore(vec)", ARG3, VG_PGROUNDUP(ARG2) / VKI_PAGE_SIZE );
}
POST(sys_mincore)
{
POST_MEM_WRITE( ARG3, VG_PGROUNDUP(ARG2) / VKI_PAGE_SIZE );
}
PRE(sys_nanosleep)
{
*flags |= SfMayBlock|SfPostOnFail;
PRINT("sys_nanosleep ( %#" FMT_REGWORD "x, %#" FMT_REGWORD "x )", ARG1,ARG2);
PRE_REG_READ2(long, "nanosleep",
struct timespec *, req, struct timespec *, rem);
PRE_MEM_READ( "nanosleep(req)", ARG1, sizeof(struct vki_timespec) );
if (ARG2 != 0)
PRE_MEM_WRITE( "nanosleep(rem)", ARG2, sizeof(struct vki_timespec) );
}
POST(sys_nanosleep)
{
vg_assert(SUCCESS || FAILURE);
if (ARG2 != 0 && FAILURE && ERR == VKI_EINTR)
POST_MEM_WRITE( ARG2, sizeof(struct vki_timespec) );
}
#if defined(VGO_linux) || defined(VGO_solaris)
/* Handles the case where the open is of /proc/self/auxv or
/proc/<pid>/auxv, and just gives out a copy of the fd for the
fake file we cooked up at startup (in m_main). Also, seeks the
cloned fd back to the start.
Returns True if auxv open was handled (status is set). */
Bool ML_(handle_auxv_open)(SyscallStatus *status, const HChar *filename,
int flags)
{
HChar name[30]; // large enough
if (!ML_(safe_to_deref)((const void *) filename, 1))
return False;
/* Opening /proc/<pid>/auxv or /proc/self/auxv? */
VG_(sprintf)(name, "/proc/%d/auxv", VG_(getpid)());
if (!VG_STREQ(filename, name) && !VG_STREQ(filename, "/proc/self/auxv"))
return False;
/* Allow to open the file only for reading. */
if (flags & (VKI_O_WRONLY | VKI_O_RDWR)) {
SET_STATUS_Failure(VKI_EACCES);
return True;
}
# if defined(VGO_solaris)
VG_(sprintf)(name, "/proc/self/fd/%d", VG_(cl_auxv_fd));
SysRes sres = VG_(open)(name, flags, 0);
SET_STATUS_from_SysRes(sres);
# else
SysRes sres = VG_(dup)(VG_(cl_auxv_fd));
SET_STATUS_from_SysRes(sres);
if (!sr_isError(sres)) {
OffT off = VG_(lseek)(sr_Res(sres), 0, VKI_SEEK_SET);
if (off < 0)
SET_STATUS_Failure(VKI_EMFILE);
}
# endif
return True;
}
#endif // defined(VGO_linux) || defined(VGO_solaris)
#if defined(VGO_linux)
Bool ML_(handle_self_exe_open)(SyscallStatus *status, const HChar *filename,
int flags)
{
HChar name[30]; // large enough for /proc/<int>/exe
if (!ML_(safe_to_deref)((const void *) filename, 1))
return False;
/* Opening /proc/<pid>/exe or /proc/self/exe? */
VG_(sprintf)(name, "/proc/%d/exe", VG_(getpid)());
if (!VG_STREQ(filename, name) && !VG_STREQ(filename, "/proc/self/exe"))
return False;
/* Allow to open the file only for reading. */
if (flags & (VKI_O_WRONLY | VKI_O_RDWR)) {
SET_STATUS_Failure(VKI_EACCES);
return True;
}
SysRes sres = VG_(dup)(VG_(cl_exec_fd));
SET_STATUS_from_SysRes(sres);
if (!sr_isError(sres)) {
OffT off = VG_(lseek)(sr_Res(sres), 0, VKI_SEEK_SET);
if (off < 0)
SET_STATUS_Failure(VKI_EMFILE);
}
return True;
}
#endif // defined(VGO_linux)
PRE(sys_open)
{
if (ARG2 & VKI_O_CREAT) {
// 3-arg version
PRINT("sys_open ( %#" FMT_REGWORD "x(%s), %ld, %ld )",ARG1,
(HChar*)(Addr)ARG1, SARG2, SARG3);
PRE_REG_READ3(long, "open",
const char *, filename, int, flags, int, mode);
} else {
// 2-arg version
PRINT("sys_open ( %#" FMT_REGWORD "x(%s), %ld )",ARG1,
(HChar*)(Addr)ARG1, SARG2);
PRE_REG_READ2(long, "open",
const char *, filename, int, flags);
}
PRE_MEM_RASCIIZ( "open(filename)", ARG1 );
#if defined(VGO_linux)
/* Handle the case where the open is of /proc/self/cmdline or
/proc/<pid>/cmdline, and just give it a copy of the fd for the
fake file we cooked up at startup (in m_main). Also, seek the
cloned fd back to the start. */
{
HChar name[30]; // large enough
HChar* arg1s = (HChar*) (Addr)ARG1;
SysRes sres;
VG_(sprintf)(name, "/proc/%d/cmdline", VG_(getpid)());
if (ML_(safe_to_deref)( arg1s, 1 )
&& (VG_STREQ(arg1s, name) || VG_STREQ(arg1s, "/proc/self/cmdline"))) {
sres = VG_(dup)( VG_(cl_cmdline_fd) );
SET_STATUS_from_SysRes( sres );
if (!sr_isError(sres)) {
OffT off = VG_(lseek)( sr_Res(sres), 0, VKI_SEEK_SET );
if (off < 0)
SET_STATUS_Failure( VKI_EMFILE );
}
return;
}
}
/* Handle also the case of /proc/self/auxv or /proc/<pid>/auxv
or /proc/self/exe or /proc/<pid>/exe. */
if (ML_(handle_auxv_open)(status, (const HChar *)(Addr)ARG1, ARG2)
|| ML_(handle_self_exe_open)(status, (const HChar *)(Addr)ARG1, ARG2))
return;
#endif // defined(VGO_linux)
/* Otherwise handle normally */
*flags |= SfMayBlock;
}
POST(sys_open)
{
vg_assert(SUCCESS);
if (!ML_(fd_allowed)(RES, "open", tid, True)) {
VG_(close)(RES);
SET_STATUS_Failure( VKI_EMFILE );
} else {
if (VG_(clo_track_fds))
ML_(record_fd_open_with_given_name)(tid, RES, (HChar*)(Addr)ARG1);
}
}
PRE(sys_read)
{
*flags |= SfMayBlock;
PRINT("sys_read ( %" FMT_REGWORD "u, %#" FMT_REGWORD "x, %"
FMT_REGWORD "u )", ARG1, ARG2, ARG3);
PRE_REG_READ3(ssize_t, "read",
int, fd, char *, buf, vki_size_t, count);
if (!ML_(fd_allowed)(ARG1, "read", tid, False))
SET_STATUS_Failure( VKI_EBADF );
else
PRE_MEM_WRITE( "read(buf)", ARG2, ARG3 );
}
POST(sys_read)
{
vg_assert(SUCCESS);
POST_MEM_WRITE( ARG2, RES );
}
PRE(sys_write)
{
Bool ok;
*flags |= SfMayBlock;
PRINT("sys_write ( %" FMT_REGWORD "u, %#" FMT_REGWORD "x, %"
FMT_REGWORD "u )", ARG1, ARG2, ARG3);
PRE_REG_READ3(ssize_t, "write",
unsigned int, fd, const char *, buf, vki_size_t, count);
/* check to see if it is allowed. If not, try for an exemption from
--sim-hints=enable-outer (used for self hosting). */
ok = ML_(fd_allowed)(ARG1, "write", tid, False);
if (!ok && ARG1 == 2/*stderr*/
&& SimHintiS(SimHint_enable_outer, VG_(clo_sim_hints)))
ok = True;
#if defined(VGO_solaris)
if (!ok && VG_(vfork_fildes_addr) != NULL
&& *VG_(vfork_fildes_addr) >= 0 && *VG_(vfork_fildes_addr) == ARG1)
ok = True;
#endif
if (!ok)
SET_STATUS_Failure( VKI_EBADF );
else
PRE_MEM_READ( "write(buf)", ARG2, ARG3 );
}
PRE(sys_creat)
{
*flags |= SfMayBlock;
PRINT("sys_creat ( %#" FMT_REGWORD "x(%s), %ld )", ARG1,
(HChar*)(Addr)ARG1, SARG2);
PRE_REG_READ2(long, "creat", const char *, pathname, int, mode);
PRE_MEM_RASCIIZ( "creat(pathname)", ARG1 );
}
POST(sys_creat)
{
vg_assert(SUCCESS);
if (!ML_(fd_allowed)(RES, "creat", tid, True)) {
VG_(close)(RES);
SET_STATUS_Failure( VKI_EMFILE );
} else {
if (VG_(clo_track_fds))
ML_(record_fd_open_with_given_name)(tid, RES, (HChar*)(Addr)ARG1);
}
}
PRE(sys_poll)
{
/* struct pollfd {
int fd; -- file descriptor
short events; -- requested events
short revents; -- returned events
};
int poll(struct pollfd *ufds, unsigned int nfds, int timeout)
*/
UInt i;
struct vki_pollfd* ufds = (struct vki_pollfd *)(Addr)ARG1;
*flags |= SfMayBlock;
PRINT("sys_poll ( %#" FMT_REGWORD "x, %" FMT_REGWORD "u, %ld )\n",
ARG1, ARG2, SARG3);
PRE_REG_READ3(long, "poll",
struct vki_pollfd *, ufds, unsigned int, nfds, long, timeout);
for (i = 0; i < ARG2; i++) {
PRE_MEM_READ( "poll(ufds.fd)",
(Addr)(&ufds[i].fd), sizeof(ufds[i].fd) );
if (ML_(safe_to_deref)(&ufds[i].fd, sizeof(ufds[i].fd)) && ufds[i].fd >= 0) {
PRE_MEM_READ( "poll(ufds.events)",
(Addr)(&ufds[i].events), sizeof(ufds[i].events) );
}
PRE_MEM_WRITE( "poll(ufds.revents)",
(Addr)(&ufds[i].revents), sizeof(ufds[i].revents) );
}
}
POST(sys_poll)
{
if (SUCCESS) {
UInt i;
struct vki_pollfd* ufds = (struct vki_pollfd *)(Addr)ARG1;
for (i = 0; i < ARG2; i++)
POST_MEM_WRITE( (Addr)(&ufds[i].revents), sizeof(ufds[i].revents) );
}
}
PRE(sys_readlink)
{
FUSE_COMPATIBLE_MAY_BLOCK();
PRINT("sys_readlink ( %#" FMT_REGWORD "x(%s), %#" FMT_REGWORD "x, %llu )",
ARG1, (char*)(Addr)ARG1, ARG2, (ULong)ARG3);
PRE_REG_READ3(long, "readlink",
const char *, path, char *, buf, int, bufsiz);
PRE_MEM_RASCIIZ( "readlink(path)", ARG1 );
PRE_MEM_WRITE( "readlink(buf)", ARG2,ARG3 );
}
POST(sys_readlink)
{
#if defined(VGO_linux) || defined(VGO_solaris)
{
Word saved = SYSNO;
#if defined(VGO_linux)
#define PID_EXEPATH "/proc/%d/exe"
#define SELF_EXEPATH "/proc/self/exe"
#define SELF_EXEFD "/proc/self/fd/%d"
#elif defined(VGO_solaris)
#define PID_EXEPATH "/proc/%d/path/a.out"
#define SELF_EXEPATH "/proc/self/path/a.out"
#define SELF_EXEFD "/proc/self/path/%d"
#endif
/*
* Handle the case where readlink is looking at /proc/self/exe or
* /proc/<pid>/exe, or equivalent on Solaris.
*/
HChar name[30]; // large enough
HChar* arg1s = (HChar*) (Addr)ARG1;
VG_(sprintf)(name, PID_EXEPATH, VG_(getpid)());
if (ML_(safe_to_deref)(arg1s, 1)
&& (VG_STREQ(arg1s, name) || VG_STREQ(arg1s, SELF_EXEPATH))) {
VG_(sprintf)(name, SELF_EXEFD, VG_(cl_exec_fd));
SET_STATUS_from_SysRes( VG_(do_syscall3)(saved, (UWord)name,
ARG2, ARG3));
}
}
#endif
if (SUCCESS && RES > 0)
POST_MEM_WRITE( ARG2, RES );
}
PRE(sys_readv)
{
Int i;
struct vki_iovec * vec;
char buf[sizeof("readv(vector[])") + 11];
*flags |= SfMayBlock;
PRINT("sys_readv ( %" FMT_REGWORD "u, %#" FMT_REGWORD "x, %"
FMT_REGWORD "u )", ARG1, ARG2, ARG3);
PRE_REG_READ3(ssize_t, "readv",
unsigned long, fd, const struct iovec *, vector,
unsigned long, count);
if (!ML_(fd_allowed)(ARG1, "readv", tid, False)) {
SET_STATUS_Failure( VKI_EBADF );
} else {
if ((Int)ARG3 >= 0)
PRE_MEM_READ( "readv(vector)", ARG2, ARG3 * sizeof(struct vki_iovec) );
if (ML_(safe_to_deref)((const void*)ARG2, ARG3*sizeof(struct vki_iovec *))) {
vec = (struct vki_iovec *)(Addr)ARG2;
for (i = 0; i < (Int)ARG3; i++) {
VG_(sprintf)(buf, "readv(vector[%d])", i);
PRE_MEM_WRITE(buf, (Addr)vec[i].iov_base, vec[i].iov_len );
}
}
}
}
POST(sys_readv)
{
vg_assert(SUCCESS);
if (RES > 0) {
Int i;
struct vki_iovec * vec = (struct vki_iovec *)(Addr)ARG2;
Int remains = RES;
/* RES holds the number of bytes read. */
for (i = 0; i < (Int)ARG3; i++) {
Int nReadThisBuf = vec[i].iov_len;
if (nReadThisBuf > remains) nReadThisBuf = remains;
POST_MEM_WRITE( (Addr)vec[i].iov_base, nReadThisBuf );
remains -= nReadThisBuf;
if (remains < 0) VG_(core_panic)("readv: remains < 0");
}
}
}
PRE(sys_rename)
{
FUSE_COMPATIBLE_MAY_BLOCK();
PRINT("sys_rename ( %#" FMT_REGWORD "x(%s), %#" FMT_REGWORD "x(%s) )", ARG1,
(char*)(Addr)ARG1,ARG2,(char*)(Addr)ARG2);
PRE_REG_READ2(long, "rename", const char *, oldpath, const char *, newpath);
PRE_MEM_RASCIIZ( "rename(oldpath)", ARG1 );
PRE_MEM_RASCIIZ( "rename(newpath)", ARG2 );
}
PRE(sys_rmdir)
{
*flags |= SfMayBlock;
PRINT("sys_rmdir ( %#" FMT_REGWORD "x(%s) )", ARG1,(char*)(Addr)ARG1);
PRE_REG_READ1(long, "rmdir", const char *, pathname);
PRE_MEM_RASCIIZ( "rmdir(pathname)", ARG1 );
}
PRE(sys_select)
{
*flags |= SfMayBlock;
PRINT("sys_select ( %ld, %#" FMT_REGWORD "x, %#" FMT_REGWORD "x, %#"
FMT_REGWORD "x, %#" FMT_REGWORD "x )", SARG1, ARG2, ARG3, ARG4, ARG5);
PRE_REG_READ5(long, "select",
int, n, vki_fd_set *, readfds, vki_fd_set *, writefds,
vki_fd_set *, exceptfds, struct vki_timeval *, timeout);
// XXX: this possibly understates how much memory is read.
if (ARG2 != 0)
PRE_MEM_READ( "select(readfds)",
ARG2, ARG1/8 /* __FD_SETSIZE/8 */ );
if (ARG3 != 0)
PRE_MEM_READ( "select(writefds)",
ARG3, ARG1/8 /* __FD_SETSIZE/8 */ );
if (ARG4 != 0)
PRE_MEM_READ( "select(exceptfds)",
ARG4, ARG1/8 /* __FD_SETSIZE/8 */ );
if (ARG5 != 0)
PRE_timeval_READ( "select(timeout)", (Addr)ARG5 );
}
PRE(sys_setgid)
{
PRINT("sys_setgid ( %" FMT_REGWORD "u )", ARG1);
PRE_REG_READ1(long, "setgid", vki_gid_t, gid);
}
PRE(sys_setsid)
{
PRINT("sys_setsid ( )");
PRE_REG_READ0(long, "setsid");
}
PRE(sys_setgroups)
{
PRINT("setgroups ( %llu, %#" FMT_REGWORD "x )", (ULong)ARG1, ARG2);
PRE_REG_READ2(long, "setgroups", int, size, vki_gid_t *, list);
if (ARG1 > 0)
PRE_MEM_READ( "setgroups(list)", ARG2, ARG1 * sizeof(vki_gid_t) );
}
PRE(sys_setpgid)
{
PRINT("setpgid ( %ld, %ld )", SARG1, SARG2);
PRE_REG_READ2(long, "setpgid", vki_pid_t, pid, vki_pid_t, pgid);
}
PRE(sys_setregid)
{
PRINT("sys_setregid ( %" FMT_REGWORD "u, %" FMT_REGWORD "u )", ARG1, ARG2);
PRE_REG_READ2(long, "setregid", vki_gid_t, rgid, vki_gid_t, egid);
}
PRE(sys_setreuid)
{
PRINT("sys_setreuid ( 0x%" FMT_REGWORD "x, 0x%" FMT_REGWORD "x )",
ARG1, ARG2);
PRE_REG_READ2(long, "setreuid", vki_uid_t, ruid, vki_uid_t, euid);
}
PRE(sys_setrlimit)
{
UWord arg1 = ARG1;
PRINT("sys_setrlimit ( %" FMT_REGWORD "u, %#" FMT_REGWORD "x )", ARG1, ARG2);
PRE_REG_READ2(long, "setrlimit",
unsigned int, resource, struct rlimit *, rlim);
PRE_MEM_READ( "setrlimit(rlim)", ARG2, sizeof(struct vki_rlimit) );
#ifdef _RLIMIT_POSIX_FLAG
// Darwin will sometimes set _RLIMIT_POSIX_FLAG on setrlimit calls.
// Unset it here to make the if statements below work correctly.
arg1 &= ~_RLIMIT_POSIX_FLAG;
#endif
if (!VG_(am_is_valid_for_client)(ARG2, sizeof(struct vki_rlimit),
VKI_PROT_READ)) {
SET_STATUS_Failure( VKI_EFAULT );
}
else if (((struct vki_rlimit *)(Addr)ARG2)->rlim_cur
> ((struct vki_rlimit *)(Addr)ARG2)->rlim_max) {
#if defined(VGO_freebsd)
SET_STATUS_Failure( VKI_EPERM );
#else
SET_STATUS_Failure( VKI_EINVAL );
#endif
}
else if (arg1 == VKI_RLIMIT_NOFILE) {
if (((struct vki_rlimit *)(Addr)ARG2)->rlim_cur > VG_(fd_hard_limit) ||
((struct vki_rlimit *)(Addr)ARG2)->rlim_max != VG_(fd_hard_limit)) {
SET_STATUS_Failure( VKI_EPERM );
}
else {
VG_(fd_soft_limit) = ((struct vki_rlimit *)(Addr)ARG2)->rlim_cur;
SET_STATUS_Success( 0 );
}
}
else if (arg1 == VKI_RLIMIT_DATA) {
if (((struct vki_rlimit *)(Addr)ARG2)->rlim_cur
> VG_(client_rlimit_data).rlim_max ||
((struct vki_rlimit *)(Addr)ARG2)->rlim_max
> VG_(client_rlimit_data).rlim_max) {
SET_STATUS_Failure( VKI_EPERM );
}
else {
VG_(client_rlimit_data) = *(struct vki_rlimit *)(Addr)ARG2;
SET_STATUS_Success( 0 );
}
}
else if (arg1 == VKI_RLIMIT_STACK && tid == 1) {
if (((struct vki_rlimit *)(Addr)ARG2)->rlim_cur
> VG_(client_rlimit_stack).rlim_max ||
((struct vki_rlimit *)(Addr)ARG2)->rlim_max
> VG_(client_rlimit_stack).rlim_max) {
SET_STATUS_Failure( VKI_EPERM );
}
else {
/* Change the value of client_stack_szB to the rlim_cur value but
only if it is smaller than the size of the allocated stack for the
client.
TODO: All platforms should set VG_(clstk_max_size) as part of their
setup_client_stack(). */
if ((VG_(clstk_max_size) == 0)
|| (((struct vki_rlimit *) (Addr)ARG2)->rlim_cur <= VG_(clstk_max_size)))
VG_(threads)[tid].client_stack_szB = ((struct vki_rlimit *)(Addr)ARG2)->rlim_cur;
VG_(client_rlimit_stack) = *(struct vki_rlimit *)(Addr)ARG2;
SET_STATUS_Success( 0 );
}
}
}
PRE(sys_setuid)
{
PRINT("sys_setuid ( %" FMT_REGWORD "u )", ARG1);
PRE_REG_READ1(long, "setuid", vki_uid_t, uid);
}
#if !defined(VGP_nanomips_linux) && !defined(VGO_freebsd)
PRE(sys_newstat)
{
FUSE_COMPATIBLE_MAY_BLOCK();
PRINT("sys_newstat ( %#" FMT_REGWORD "x(%s), %#" FMT_REGWORD "x )",
ARG1,(char*)(Addr)ARG1,ARG2);
PRE_REG_READ2(long, "stat", char *, file_name, struct stat *, buf);
PRE_MEM_RASCIIZ( "stat(file_name)", ARG1 );
PRE_MEM_WRITE( "stat(buf)", ARG2, sizeof(struct vki_stat) );
}
POST(sys_newstat)
{
POST_MEM_WRITE( ARG2, sizeof(struct vki_stat) );
}
#endif
#if !defined(VGP_nanomips_linux)
PRE(sys_statfs)
{
FUSE_COMPATIBLE_MAY_BLOCK();
PRINT("sys_statfs ( %#" FMT_REGWORD "x(%s), %#" FMT_REGWORD "x )",
ARG1, (char*)(Addr)ARG1, ARG2);
PRE_REG_READ2(long, "statfs", const char *, path, struct statfs *, buf);
PRE_MEM_RASCIIZ( "statfs(path)", ARG1 );
PRE_MEM_WRITE( "statfs(buf)", ARG2, sizeof(struct vki_statfs) );
}
POST(sys_statfs)
{
POST_MEM_WRITE( ARG2, sizeof(struct vki_statfs) );
}
PRE(sys_statfs64)
{
FUSE_COMPATIBLE_MAY_BLOCK();
PRINT("sys_statfs64 ( %#" FMT_REGWORD "x(%s), %llu, %#" FMT_REGWORD "x )",
ARG1, (char*)(Addr)ARG1, (ULong)ARG2, ARG3);
PRE_REG_READ3(long, "statfs64",
const char *, path, vki_size_t, size, struct statfs64 *, buf);
PRE_MEM_RASCIIZ( "statfs64(path)", ARG1 );
PRE_MEM_WRITE( "statfs64(buf)", ARG3, ARG2 );
}
POST(sys_statfs64)
{
POST_MEM_WRITE( ARG3, ARG2 );
}
#endif
PRE(sys_symlink)
{
*flags |= SfMayBlock;
PRINT("sys_symlink ( %#" FMT_REGWORD "x(%s), %#" FMT_REGWORD "x(%s) )",
ARG1, (char*)(Addr)ARG1, ARG2, (char*)(Addr)ARG2);
PRE_REG_READ2(long, "symlink", const char *, oldpath, const char *, newpath);
PRE_MEM_RASCIIZ( "symlink(oldpath)", ARG1 );
PRE_MEM_RASCIIZ( "symlink(newpath)", ARG2 );
}
PRE(sys_time)
{
/* time_t time(time_t *t); */
PRINT("sys_time ( %#" FMT_REGWORD "x )",ARG1);
PRE_REG_READ1(long, "time", int *, t);
if (ARG1 != 0) {
PRE_MEM_WRITE( "time(t)", ARG1, sizeof(vki_time_t) );
}
}
POST(sys_time)
{
if (ARG1 != 0) {
POST_MEM_WRITE( ARG1, sizeof(vki_time_t) );
}
}
PRE(sys_times)
{
PRINT("sys_times ( %#" FMT_REGWORD "x )", ARG1);
PRE_REG_READ1(long, "times", struct tms *, buf);
if (ARG1 != 0) {
PRE_MEM_WRITE( "times(buf)", ARG1, sizeof(struct vki_tms) );
}
}
POST(sys_times)
{
if (ARG1 != 0) {
POST_MEM_WRITE( ARG1, sizeof(struct vki_tms) );
}
}
PRE(sys_umask)
{
PRINT("sys_umask ( %ld )", SARG1);
PRE_REG_READ1(long, "umask", int, mask);
}
PRE(sys_unlink)
{
*flags |= SfMayBlock;
PRINT("sys_unlink ( %#" FMT_REGWORD "x(%s) )", ARG1,(char*)(Addr)ARG1);
PRE_REG_READ1(long, "unlink", const char *, pathname);
PRE_MEM_RASCIIZ( "unlink(pathname)", ARG1 );
}
#if !defined(VGO_freebsd)
PRE(sys_newuname)
{
PRINT("sys_newuname ( %#" FMT_REGWORD "x )", ARG1);
PRE_REG_READ1(long, "uname", struct new_utsname *, buf);
PRE_MEM_WRITE( "uname(buf)", ARG1, sizeof(struct vki_new_utsname) );
}
POST(sys_newuname)
{
if (ARG1 != 0) {
POST_MEM_WRITE( ARG1, sizeof(struct vki_new_utsname) );
}
}
#endif
PRE(sys_waitpid)
{
*flags |= SfMayBlock;
PRINT("sys_waitpid ( %ld, %#" FMT_REGWORD "x, %ld )", SARG1, ARG2, SARG3);
PRE_REG_READ3(long, "waitpid",
vki_pid_t, pid, unsigned int *, status, int, options);
if (ARG2 != (Addr)NULL)
PRE_MEM_WRITE( "waitpid(status)", ARG2, sizeof(int) );
}
POST(sys_waitpid)
{
if (ARG2 != (Addr)NULL)
POST_MEM_WRITE( ARG2, sizeof(int) );
}
PRE(sys_wait4)
{
*flags |= SfMayBlock;
PRINT("sys_wait4 ( %ld, %#" FMT_REGWORD "x, %ld, %#" FMT_REGWORD "x )",
SARG1, ARG2, SARG3, ARG4);
PRE_REG_READ4(long, "wait4",
vki_pid_t, pid, unsigned int *, status, int, options,
struct rusage *, rusage);
if (ARG2 != (Addr)NULL)
PRE_MEM_WRITE( "wait4(status)", ARG2, sizeof(int) );
if (ARG4 != (Addr)NULL)
PRE_MEM_WRITE( "wait4(rusage)", ARG4, sizeof(struct vki_rusage) );
}
POST(sys_wait4)
{
if (ARG2 != (Addr)NULL)
POST_MEM_WRITE( ARG2, sizeof(int) );
if (ARG4 != (Addr)NULL)
POST_MEM_WRITE( ARG4, sizeof(struct vki_rusage) );
}
PRE(sys_writev)
{
Int i;
struct vki_iovec * vec;
char buf[sizeof("writev(vector[])") + 11];
*flags |= SfMayBlock;
PRINT("sys_writev ( %" FMT_REGWORD "u, %#" FMT_REGWORD "x, %"
FMT_REGWORD "u )", ARG1, ARG2, ARG3);
PRE_REG_READ3(ssize_t, "writev",
unsigned long, fd, const struct iovec *, vector,
unsigned long, count);
if (!ML_(fd_allowed)(ARG1, "writev", tid, False)) {
SET_STATUS_Failure( VKI_EBADF );
} else {
if ((Int)ARG3 >= 0)
PRE_MEM_READ( "writev(vector)",
ARG2, ARG3 * sizeof(struct vki_iovec) );
if (ML_(safe_to_deref)((const void*)ARG2, ARG3*sizeof(struct vki_iovec *))) {
vec = (struct vki_iovec *)(Addr)ARG2;
for (i = 0; i < (Int)ARG3; i++) {
VG_(sprintf)(buf, "writev(vector[%d])", i);
PRE_MEM_READ( buf, (Addr)vec[i].iov_base, vec[i].iov_len );
}
}
}
}
PRE(sys_utimes)
{
FUSE_COMPATIBLE_MAY_BLOCK();
PRINT("sys_utimes ( %#" FMT_REGWORD "x(%s), %#" FMT_REGWORD "x )",
ARG1, (char*)(Addr)ARG1, ARG2);
PRE_REG_READ2(long, "utimes", char *, filename, struct timeval *, tvp);
PRE_MEM_RASCIIZ( "utimes(filename)", ARG1 );
if (ARG2 != 0) {
PRE_timeval_READ( "utimes(tvp[0])", (Addr)ARG2 );
PRE_timeval_READ( "utimes(tvp[1])",
(Addr)ARG2+sizeof(struct vki_timeval) );
}
}
PRE(sys_acct)
{
PRINT("sys_acct ( %#" FMT_REGWORD "x(%s) )", ARG1,(char*)(Addr)ARG1);
PRE_REG_READ1(long, "acct", const char *, filename);
PRE_MEM_RASCIIZ( "acct(filename)", ARG1 );
}
PRE(sys_pause)
{
*flags |= SfMayBlock;
PRINT("sys_pause ( )");
PRE_REG_READ0(long, "pause");
}
PRE(sys_sigaltstack)
{
PRINT("sigaltstack ( %#" FMT_REGWORD "x, %#" FMT_REGWORD "x )",ARG1,ARG2);
PRE_REG_READ2(int, "sigaltstack",
const vki_stack_t *, ss, vki_stack_t *, oss);
if (ARG1 != 0) {
const vki_stack_t *ss = (vki_stack_t *)(Addr)ARG1;
PRE_MEM_READ( "sigaltstack(ss->ss_sp)", (Addr)&ss->ss_sp, sizeof(ss->ss_sp) );
PRE_MEM_READ( "sigaltstack(ss->ss_size)", (Addr)&ss->ss_size, sizeof(ss->ss_size) );
PRE_MEM_READ( "sigaltstack(ss->ss_flags)", (Addr)&ss->ss_flags, sizeof(ss->ss_flags) );
}
if (ARG2 != 0) {
PRE_MEM_WRITE( "sigaltstack(oss)", ARG2, sizeof(vki_stack_t) );
}
/* Be safe. */
if (ARG1 && !ML_(safe_to_deref((void*)(Addr)ARG1, sizeof(vki_stack_t)))) {
SET_STATUS_Failure(VKI_EFAULT);
return;
}
if (ARG2 && !ML_(safe_to_deref((void*)(Addr)ARG2, sizeof(vki_stack_t)))) {
SET_STATUS_Failure(VKI_EFAULT);
return;
}
SET_STATUS_from_SysRes(
VG_(do_sys_sigaltstack) (tid, (vki_stack_t*)(Addr)ARG1,
(vki_stack_t*)(Addr)ARG2)
);
}
POST(sys_sigaltstack)
{
vg_assert(SUCCESS);
if (RES == 0 && ARG2 != 0)
POST_MEM_WRITE( ARG2, sizeof(vki_stack_t));
}
PRE(sys_sethostname)
{
PRINT("sys_sethostname ( %#" FMT_REGWORD "x, %ld )", ARG1, SARG2);
PRE_REG_READ2(long, "sethostname", char *, name, int, len);
PRE_MEM_READ( "sethostname(name)", ARG1, ARG2 );
}
#undef PRE
#undef POST
#endif // defined(VGO_linux) || defined(VGO_darwin) || defined(VGO_solaris) || defined(VGO_freebsd)
/*--------------------------------------------------------------------*/
/*--- end ---*/
/*--------------------------------------------------------------------*/
|