Loading...
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 | /* * Copyright (c) 2017 Apple Inc. All rights reserved. * * @APPLE_LICENSE_HEADER_START@ * * This file contains Original Code and/or Modifications of Original Code * as defined in and that are subject to the Apple Public Source License * Version 2.0 (the 'License'). You may not use this file except in * compliance with the License. Please obtain a copy of the License at * http://www.opensource.apple.com/apsl/ and read it before using this * file. * * The Original Code and all software distributed under the License are * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. * Please see the License for the specific language governing rights and * limitations under the License. * * @APPLE_LICENSE_HEADER_END@ */ #include <TargetConditionals.h> #include "Defines.h" #if !TARGET_OS_EXCLAVEKIT #include <sys/types.h> #include <sys/fcntl.h> #include <sys/mman.h> #include <mach/mach.h> #include <unistd.h> #endif #if SUPPORT_CLASSIC_RELOCS #include <mach-o/reloc.h> #include <mach-o/x86_64/reloc.h> #endif #include <assert.h> #include <limits.h> #include <stdlib.h> #include <string.h> #include <mach-o/nlist.h> #include <ptrauth.h> #include "MachOAnalyzer.h" #include "CodeSigningTypes.h" #include "Array.h" // FIXME: We should get this from cctools #define DYLD_CACHE_ADJ_V2_FORMAT 0x7F namespace dyld3 { bool MachOAnalyzer::isValidMainExecutable(Diagnostics& diag, const char* path, uint64_t sliceLength, const GradedArchs& archs, Platform platform) const { if ( !this->validMachOForArchAndPlatform(diag, (size_t)sliceLength, path, archs, platform, true) ) return false; if ( !this->isDynamicExecutable() ) { diag.error("could not use '%s' because it is not an executable, filetype=0x%08X", path, this->filetype); return false; } if ( !this->validLinkedit(diag, path) ) return false; return true; } #if !TARGET_OS_EXCLAVEKIT bool MachOAnalyzer::loadFromBuffer(Diagnostics& diag, const closure::FileSystem& fileSystem, const char* path, const GradedArchs& archs, Platform platform, closure::LoadedFileInfo& info) { // if fat, remap just slice needed bool fatButMissingSlice; const FatFile* fh = (FatFile*)info.fileContent; uint64_t sliceOffset = info.sliceOffset; uint64_t sliceLen = info.sliceLen; if ( fh->isFatFileWithSlice(diag, info.fileContentLen, archs, info.isOSBinary, sliceOffset, sliceLen, fatButMissingSlice) ) { // unmap anything before slice fileSystem.unloadPartialFile(info, sliceOffset, sliceLen); // Update the info to keep track of the new slice offset. info.sliceOffset = sliceOffset; info.sliceLen = sliceLen; } else if ( diag.hasError() ) { // We must have generated an error in the fat file parsing so use that error fileSystem.unloadFile(info); return false; } else if ( fatButMissingSlice ) { diag.error("missing compatible arch in %s", path); fileSystem.unloadFile(info); return false; } const MachOAnalyzer* mh = (MachOAnalyzer*)info.fileContent; // validate is mach-o of requested arch and platform if ( !mh->validMachOForArchAndPlatform(diag, (size_t)info.sliceLen, path, archs, platform, info.isOSBinary) ) { fileSystem.unloadFile(info); return false; } // if has zero-fill expansion, re-map if ( !mh->isPreload() ) mh = mh->remapIfZeroFill(diag, fileSystem, info); // on error, remove mappings and return nullptr if ( diag.hasError() ) { fileSystem.unloadFile(info); return false; } // now that LINKEDIT is at expected offset, finish validation if ( !mh->isPreload() ) mh->validLinkedit(diag, path); // on error, remove mappings and return nullptr if ( diag.hasError() ) { fileSystem.unloadFile(info); return false; } return true; } closure::LoadedFileInfo MachOAnalyzer::load(Diagnostics& diag, const closure::FileSystem& fileSystem, const char* path, const GradedArchs& archs, Platform platform, char realerPath[PATH_MAX]) { // FIXME: This should probably be an assert, but if we happen to have a diagnostic here then something is wrong // above us and we should quickly return instead of doing unnecessary work. if (diag.hasError()) return closure::LoadedFileInfo(); closure::LoadedFileInfo info; void (^fileErrorLog)(const char *format, ...) __printflike(1, 2) = ^(const char *format, ...) __printflike(1, 2) { va_list list; va_start(list, format); diag.error(format, list); va_end(list); }; if ( !fileSystem.loadFile(path, info, realerPath, fileErrorLog) ) { return closure::LoadedFileInfo(); } // If we now have an error, but succeeded, then we must have tried multiple paths, one of which errored, but // then succeeded on a later path. So clear the error. if (diag.hasError()) diag.clearError(); bool loaded = loadFromBuffer(diag, fileSystem, path, archs, platform, info); if (!loaded) return {}; return info; } // for use with already mmap()ed file bool MachOAnalyzer::isOSBinary(int fd, uint64_t sliceOffset, uint64_t sliceSize) const { #ifdef F_GETSIGSINFO if ( fd == -1 ) return false; uint32_t sigOffset; uint32_t sigSize; if ( !this->hasCodeSignature(sigOffset, sigSize) ) return false; // register code signature fsignatures_t sigreg; sigreg.fs_file_start = sliceOffset; // start of mach-o slice in fat file sigreg.fs_blob_start = (void*)(long)sigOffset; // start of CD in mach-o file sigreg.fs_blob_size = sigSize; // size of CD if ( ::fcntl(fd, F_ADDFILESIGS_RETURN, &sigreg) == -1 ) return false; // ask if code signature is for something in the OS fgetsigsinfo siginfo = { (off_t)sliceOffset, GETSIGSINFO_PLATFORM_BINARY, 0 }; if ( ::fcntl(fd, F_GETSIGSINFO, &siginfo) == -1 ) return false; return (siginfo.fg_sig_is_platform); #else return false; #endif } // for use when just the fat_header has been read bool MachOAnalyzer::sliceIsOSBinary(int fd, uint64_t sliceOffset, uint64_t sliceSize) { if ( fd == -1 ) return false; // need to mmap() slice so we can find the code signature void* mappedSlice = ::mmap(nullptr, (size_t)sliceSize, PROT_READ, MAP_PRIVATE, fd, sliceOffset); if ( mappedSlice == MAP_FAILED ) return false; const MachOAnalyzer* ma = (MachOAnalyzer*)mappedSlice; bool result = ma->isOSBinary(fd, sliceOffset, sliceSize); ::munmap(mappedSlice, (size_t)sliceSize); return result; } #endif // !TARGET_OS_EXCLAVEKIT #if DEBUG // only used in debug builds of cache builder to verify segment moves are valid void MachOAnalyzer::validateDyldCacheDylib(Diagnostics& diag, const char* path) const { validLinkedit(diag, path); validSegments(diag, path, 0xffffffff); } #endif bool MachOAnalyzer::validMachOForArchAndPlatform(Diagnostics& diag, size_t sliceLength, const char* path, const GradedArchs& archs, Platform reqPlatform, bool isOSBinary, bool internalInstall) const { // must start with mach-o magic value if ( (this->magic != MH_MAGIC) && (this->magic != MH_MAGIC_64) ) { diag.error("could not use '%s' because it is not a mach-o file: 0x%08X 0x%08X", path, this->magic, this->cputype); return false; } if ( !archs.grade(this->cputype, this->cpusubtype, isOSBinary) ) { diag.error("could not use '%s' because it is not a compatible arch", path); return false; } // must be a filetype dyld can load switch ( this->filetype ) { case MH_EXECUTE: case MH_DYLIB: case MH_BUNDLE: case MH_DYLINKER: break; #if BUILDING_DYLDINFO || BUILDING_APP_CACHE_UTIL || BUILDING_RUN_STATIC // Allow offline tools to analyze binaries dyld doesn't load case MH_KEXT_BUNDLE: case MH_FILESET: case MH_PRELOAD: break; #endif default: diag.error("could not use '%s' because it is not a dylib, bundle, or executable, filetype=0x%08X", path, this->filetype); return false; } // validate load commands structure if ( !this->validLoadCommands(diag, path, sliceLength) ) { return false; } // filter out static executables if ( (this->filetype == MH_EXECUTE) && !isDynamicExecutable() ) { #if !BUILDING_DYLDINFO && !BUILDING_APP_CACHE_UTIL // dyldinfo should be able to inspect static executables such as the kernel diag.error("could not use '%s' because it is a static executable", path); return false; #endif } // HACK: If we are asking for no platform, then make sure the binary doesn't have one #if BUILDING_DYLDINFO || BUILDING_APP_CACHE_UTIL if ( isFileSet() ) { // A statically linked kernel collection should contain a 0 platform __block bool foundPlatform = false; __block bool foundBadPlatform = false; forEachSupportedPlatform(^(Platform platform, uint32_t minOS, uint32_t sdk) { foundPlatform = true; if ( platform != Platform::unknown ) { foundBadPlatform = true; } }); if (!foundPlatform) { diag.error("could not use '%s' because we expected it to have a platform", path); return false; } if (foundBadPlatform) { diag.error("could not use '%s' because is has the wrong platform", path); return false; } } else if ( reqPlatform == Platform::unknown ) { // This is handled elsewhere in the kernel collection builder, where we have access // to the kernel binary and can infer its platform } else #endif if ( !this->loadableIntoProcess(reqPlatform, path, internalInstall) ) { diag.error("could not use '%s' because it was not built for platform %s", path, MachOFile::platformName(reqPlatform)); return false; } // validate dylib loads if ( !validEmbeddedPaths(diag, reqPlatform, path, internalInstall) ) return false; // validate segments if ( !validSegments(diag, path, sliceLength) ) return false; // validate entry if ( this->filetype == MH_EXECUTE ) { if ( !validMain(diag, path) ) return false; } // further validations done in validLinkedit() return true; } bool MachOAnalyzer::validLinkedit(Diagnostics& diag, const char* path) const { // validate LINKEDIT layout if ( !validLinkeditLayout(diag, path) ) return false; // rdar://75492733 (enforce that binaries built against Fall2021 SDK have a LC_UUID) if ( enforceFormat(Malformed::noUUID) ) { if ( !hasLoadCommand(LC_UUID) ) { diag.error("missing LC_UUID"); return false; } } if ( hasLoadCommand(LC_DYLD_CHAINED_FIXUPS) ) { if ( !validChainedFixupsInfo(diag, path) ) return false; } #if SUPPORT_ARCH_arm64e else if ( (this->cputype == CPU_TYPE_ARM64) && (this->maskedCpuSubtype() == CPU_SUBTYPE_ARM64E) ) { if ( !validChainedFixupsInfoOldArm64e(diag, path) ) return false; } #endif else { // validate rebasing info if ( !validRebaseInfo(diag, path) ) return false; // validate binding info if ( !validBindInfo(diag, path) ) return false; } return true; } bool MachOAnalyzer::validLoadCommands(Diagnostics& diag, const char* path, size_t fileLen) const { // check load command don't exceed file length if ( this->sizeofcmds + machHeaderSize() > fileLen ) { diag.error("in '%s' load commands exceed length of file", path); return false; } // walk all load commands and sanity check them Diagnostics walkDiag; forEachLoadCommand(walkDiag, ^(const load_command* cmd, bool& stop) {}); if ( walkDiag.hasError() ) { #if BUILDING_CACHE_BUILDER || BUILDING_UNIT_TESTS || BUILDING_CACHE_BUILDER_UNIT_TESTS diag.error("in '%s' %s", path, walkDiag.errorMessage().c_str()); #else diag.error("in '%s' %s", path, walkDiag.errorMessage()); #endif return false; } // check load commands fit in TEXT segment __block bool foundTEXT = false; forEachSegment(^(const SegmentInfo& info, bool& stop) { if ( strcmp(info.segName, "__TEXT") == 0 ) { foundTEXT = true; if ( this->sizeofcmds + machHeaderSize() > info.fileSize ) { diag.error("in '%s' load commands exceed length of __TEXT segment", path); } if ( (info.fileOffset != 0) && !this->isPreload() ) { diag.error("in '%s' __TEXT segment not start of mach-o", path); } stop = true; } }); if ( !diag.noError() && !foundTEXT ) { diag.error("in '%s' __TEXT segment not found", path); return false; } return true; } #if !TARGET_OS_EXCLAVEKIT const MachOAnalyzer* MachOAnalyzer::remapIfZeroFill(Diagnostics& diag, const closure::FileSystem& fileSystem, closure::LoadedFileInfo& info) const { uint64_t vmSpaceRequired; bool hasZeroFill; analyzeSegmentsLayout(vmSpaceRequired, hasZeroFill); if ( hasZeroFill ) { vm_address_t newMappedAddr; if ( ::vm_allocate(mach_task_self(), &newMappedAddr, (size_t)vmSpaceRequired, VM_FLAGS_ANYWHERE) != 0 ) { diag.error("vm_allocate failure"); return nullptr; } // re-map each segment read-only, with runtime layout #if BUILDING_APP_CACHE_UTIL // The auxKC is mapped with __DATA first, so we need to get either the __DATA or __TEXT depending on what is earliest __block uint64_t baseAddress = ~0ULL; forEachSegment(^(const SegmentInfo& segmentInfo, bool& stop) { baseAddress = std::min(baseAddress, segmentInfo.vmAddr); }); uint64_t textSegVMAddr = preferredLoadAddress(); #else uint64_t baseAddress = preferredLoadAddress(); #endif forEachSegment(^(const SegmentInfo& segmentInfo, bool& stop) { if ( (segmentInfo.fileSize != 0) && (segmentInfo.vmSize != 0) ) { kern_return_t r = vm_copy(mach_task_self(), (vm_address_t)((long)info.fileContent+segmentInfo.fileOffset), (vm_size_t)segmentInfo.fileSize, (vm_address_t)(newMappedAddr+segmentInfo.vmAddr-baseAddress)); if ( r != KERN_SUCCESS ) { diag.error("vm_copy() failure"); stop = true; } } }); if ( diag.noError() ) { // remove original mapping and return new mapping fileSystem.unloadFile(info); // make the new mapping read-only ::vm_protect(mach_task_self(), newMappedAddr, (vm_size_t)vmSpaceRequired, false, VM_PROT_READ); #if BUILDING_APP_CACHE_UTIL if ( textSegVMAddr != baseAddress ) { info.unload = [](const closure::LoadedFileInfo& info) { // Unloading binaries where __DATA is first requires working out the real range of the binary // The fileContent points at the mach_header, not the actaul start of the file content, unfortunately. const MachOAnalyzer* ma = (const MachOAnalyzer*)info.fileContent; __block uint64_t baseAddress = ~0ULL; ma->forEachSegment(^(const SegmentInfo& segInfo, bool& stop) { baseAddress = std::min(baseAddress, segInfo.vmAddr); }); uint64_t textSegVMAddr = ma->preferredLoadAddress(); uint64_t basePointerOffset = textSegVMAddr - baseAddress; uint8_t* bufferStart = (uint8_t*)info.fileContent - basePointerOffset; ::vm_deallocate(mach_task_self(), (vm_address_t)bufferStart, (size_t)info.fileContentLen); }; // And update the file content to the new location info.fileContent = (const void*)(newMappedAddr + textSegVMAddr - baseAddress); info.fileContentLen = vmSpaceRequired; return (const MachOAnalyzer*)info.fileContent; } #endif // Set vm_deallocate as the unload method. info.unload = [](const closure::LoadedFileInfo& info) { ::vm_deallocate(mach_task_self(), (vm_address_t)info.fileContent, (size_t)info.fileContentLen); }; // And update the file content to the new location info.fileContent = (const void*)newMappedAddr; info.fileContentLen = vmSpaceRequired; return (const MachOAnalyzer*)info.fileContent; } else { // new mapping failed, return old mapping with an error in diag ::vm_deallocate(mach_task_self(), newMappedAddr, (size_t)vmSpaceRequired); return nullptr; } } return this; } #endif // !TARGET_OS_EXCLAVEKIT bool MachOAnalyzer::validEmbeddedPaths(Diagnostics& diag, Platform platform, const char* path, bool internalInstall) const { __block int index = 1; __block bool allGood = true; __block int dependentsCount = 0; __block const char* installName = nullptr; forEachLoadCommand(diag, ^(const load_command* cmd, bool& stop) { const dylib_command* dylibCmd; const rpath_command* rpathCmd; switch ( cmd->cmd ) { case LC_ID_DYLIB: case LC_LOAD_DYLIB: case LC_LOAD_WEAK_DYLIB: case LC_REEXPORT_DYLIB: case LC_LOAD_UPWARD_DYLIB: dylibCmd = (dylib_command*)cmd; if ( dylibCmd->dylib.name.offset > cmd->cmdsize ) { diag.error("in '%s' load command #%d name offset (%u) outside its size (%u)", path, index, dylibCmd->dylib.name.offset, cmd->cmdsize); stop = true; allGood = false; } else { bool foundEnd = false; const char* start = (char*)dylibCmd + dylibCmd->dylib.name.offset; const char* end = (char*)dylibCmd + cmd->cmdsize; for (const char* s=start; s < end; ++s) { if ( *s == '\0' ) { foundEnd = true; break; } } if ( !foundEnd ) { diag.error("in '%s' load command #%d string extends beyond end of load command", path, index); stop = true; allGood = false; } } if ( cmd->cmd == LC_ID_DYLIB ) installName = (char*)dylibCmd + dylibCmd->dylib.name.offset; else ++dependentsCount; break; case LC_RPATH: rpathCmd = (rpath_command*)cmd; if ( rpathCmd->path.offset > cmd->cmdsize ) { diag.error("in '%s' load command #%d path offset (%u) outside its size (%u)", path, index, rpathCmd->path.offset, cmd->cmdsize); stop = true; allGood = false; } else { bool foundEnd = false; const char* start = (char*)rpathCmd + rpathCmd->path.offset; const char* end = (char*)rpathCmd + cmd->cmdsize; for (const char* s=start; s < end; ++s) { if ( *s == '\0' ) { foundEnd = true; break; } } if ( !foundEnd ) { diag.error("in '%s' load command #%d string extends beyond end of load command", path, index); stop = true; allGood = false; } } break; } ++index; }); if ( !allGood ) return false; if ( this->filetype == MH_DYLIB ) { if ( installName == nullptr ) { diag.error("in '%s' MH_DYLIB is missing LC_ID_DYLIB", path); return false; } if ( this->enforceFormat(MachOAnalyzer::Malformed::loaderPathsAreReal) ) { // new binary, so check that part after @xpath/ is real (not symlinks) if ( (strncmp(installName, "@loader_path/", 13) == 0) || (strncmp(installName, "@executable_path/", 17) == 0) ) { if ( const char* s = strchr(installName, '/') ) { while (strncmp(s, "/..", 3) == 0) s += 3; const char* trailingInstallPath = s; const char* trailingRealPath = &path[strlen(path)-strlen(trailingInstallPath)]; if (strcmp(trailingRealPath, trailingInstallPath) != 0 ) { diag.error("install name '%s' contains symlinks", installName); return false; } } } } } else { if ( installName != nullptr ) { diag.error("in '%s' LC_ID_DYLIB found in non-MH_DYLIB", path); return false; } } // all new binaries must link with something else if ( (dependentsCount == 0) && enforceFormat(Malformed::noLinkedDylibs) ) { const char* libSystemDir = this->builtForPlatform(Platform::driverKit, true) ? "/System/DriverKit/usr/lib/system/" : "/usr/lib/system/"; // except for dylibs in libSystem.dylib which are ok to link with nothing (they are on bottom) bool isNotLibSystem = (installName == nullptr) || (strncmp(installName, libSystemDir, strlen(libSystemDir)) != 0); if ( internalInstall && (this->builtForPlatform(Platform::macOSExclaveKit, true) || this->builtForPlatform(Platform::iOSExclaveKit, true) || this->builtForPlatform(Platform::tvOSExclaveKit, true)) ) { // The path of ExclaveKit libSystem libraries starts with /System/ExclaveKit const size_t prefixLength = 18; isNotLibSystem = true; if ( installName != nullptr && strlen(installName) > prefixLength ) if ( strncmp(installName + prefixLength, "/usr/lib/system/", 16) == 0 ) isNotLibSystem = false; } if ( this->isDyldManaged() && isNotLibSystem ) { diag.error("in '%s' missing LC_LOAD_DYLIB (must link with at least libSystem.dylib)", path); return false; } } return true; } bool MachOAnalyzer::validMain(Diagnostics& diag, const char* path) const { if ( this->inDyldCache() && MachOAnalyzer::enforceFormat(Malformed::mainExecInDyldCache) ) { diag.error("MH_EXECUTE is in dyld shared cache"); return false; } __block int mainCount = 0; __block int threadCount = 0; forEachLoadCommand(diag, ^(const load_command* cmd, bool& stop) { switch (cmd->cmd) { case LC_MAIN: { ++mainCount; entry_point_command* mainCmd = (entry_point_command*)cmd; uint64_t startAddress = preferredLoadAddress() + mainCmd->entryoff; __block bool foundSegment = false; forEachSegment(^(const SegmentInfo& info, bool& stopSegment) { // Skip segments which don't contain this address if ( (startAddress < info.vmAddr) || (startAddress >= info.vmAddr+info.vmSize) ) return; foundSegment = true; if ( (info.protections & VM_PROT_EXECUTE) == 0 ) diag.error("LC_MAIN points to non-executable segment"); stopSegment = true; }); if (!foundSegment) diag.error("LC_MAIN entryoff is out of range"); stop = true; break; } case LC_UNIXTHREAD: { ++threadCount; uint64_t startAddress = entryAddrFromThreadCmd((thread_command*)cmd); if ( startAddress == 0 ) { diag.error("LC_UNIXTHREAD not valid for arch %s", archName()); stop = true; } else { __block bool foundSegment = false; forEachSegment(^(const SegmentInfo& info, bool& stopSegment) { // Skip segments which don't contain this address if ( (startAddress < info.vmAddr) || (startAddress >= info.vmAddr+info.vmSize) ) return; foundSegment = true; if ( (info.protections & VM_PROT_EXECUTE) == 0 ) { // Suppress this error for the x86_64 kernel if ( !this->isStaticExecutable() ) diag.error("LC_UNIXTHREAD points to non-executable segment"); } stopSegment = true; }); if (!foundSegment) diag.error("LC_UNIXTHREAD entry is out of range"); stop = true; } break; } } }); if ( diag.hasError() ) return false; if ( this->builtForPlatform(Platform::driverKit) ) { if ( mainCount + threadCount == 0 ) return true; diag.error("LC_MAIN not allowed for driverkit"); return false; } if ( mainCount+threadCount == 1 ) return true; if ( mainCount + threadCount == 0 ) diag.error("missing LC_MAIN or LC_UNIXTHREAD"); else diag.error("only one LC_MAIN or LC_UNIXTHREAD is allowed"); return false; } namespace { struct LinkEditContentChunk { const char* name; uint32_t alignment; uint32_t fileOffsetStart; uint32_t size; // only have a few chunks, so bubble sort is ok. Don't use libc's qsort because it may call malloc static void sort(LinkEditContentChunk array[], unsigned long count) { for (unsigned i=0; i < count-1; ++i) { bool done = true; for (unsigned j=0; j < count-i-1; ++j) { if ( array[j].fileOffsetStart > array[j+1].fileOffsetStart ) { LinkEditContentChunk temp = array[j]; array[j] = array[j+1]; array[j+1] = temp; done = false; } } if ( done ) break; } } }; } // anonymous namespace bool MachOAnalyzer::validLinkeditLayout(Diagnostics& diag, const char* path) const { __block bool result = false; this->withVMLayout(diag, ^(const mach_o::Layout &layout) { result = layout.isValidLinkeditLayout(diag, path); }); return result; } bool MachOAnalyzer::invalidRebaseState(Diagnostics& diag, const char* opcodeName, const char* path, const LinkEditInfo& leInfo, const SegmentInfo segments[], bool segIndexSet, uint32_t ptrSize, uint8_t segmentIndex, uint64_t segmentOffset, Rebase kind) const { if ( !segIndexSet ) { diag.error("in '%s' %s missing preceding REBASE_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB", path, opcodeName); return true; } if ( segmentIndex >= leInfo.layout.linkeditSegIndex ) { diag.error("in '%s' %s segment index %d too large", path, opcodeName, segmentIndex); return true; } if ( segmentOffset > (segments[segmentIndex].vmSize-ptrSize) ) { diag.error("in '%s' %s current segment offset 0x%08llX beyond segment size (0x%08llX)", path, opcodeName, segmentOffset, segments[segmentIndex].vmSize); return true; } switch ( kind ) { case Rebase::pointer32: case Rebase::pointer64: if ( !segments[segmentIndex].writable() && enforceFormat(Malformed::writableData) ) { diag.error("in '%s' %s pointer rebase is in non-writable segment", path, opcodeName); return true; } if ( segments[segmentIndex].executable() && enforceFormat(Malformed::executableData) ) { diag.error("in '%s' %s pointer rebase is in executable segment", path, opcodeName); return true; } break; case Rebase::textAbsolute32: case Rebase::textPCrel32: if ( !segments[segmentIndex].textRelocs ) { diag.error("in '%s' %s text rebase is in segment that does not support text relocations", path, opcodeName); return true; } if ( segments[segmentIndex].writable() ) { diag.error("in '%s' %s text rebase is in writable segment", path, opcodeName); return true; } if ( !segments[segmentIndex].executable() ) { diag.error("in '%s' %s pointer rebase is in non-executable segment", path, opcodeName); return true; } break; case Rebase::unknown: diag.error("in '%s' %s unknown rebase type", path, opcodeName); return true; } return false; } void MachOAnalyzer::getAllSegmentsInfos(Diagnostics& diag, SegmentInfo segments[]) const { forEachSegment(^(const SegmentInfo& info, bool& stop) { segments[info.segIndex] = info; }); } bool MachOAnalyzer::validRebaseInfo(Diagnostics& diag, const char* path) const { forEachRebase(diag, ^(const char* opcodeName, const LinkEditInfo& leInfo, const SegmentInfo segments[], bool segIndexSet, uint32_t ptrSize, uint8_t segmentIndex, uint64_t segmentOffset, Rebase kind, bool& stop) { if ( invalidRebaseState(diag, opcodeName, path, leInfo, segments, segIndexSet, ptrSize, segmentIndex, segmentOffset, kind) ) stop = true; }); return diag.noError(); } void MachOAnalyzer::forEachTextRebase(Diagnostics& diag, void (^handler)(uint64_t runtimeOffset, bool& stop)) const { __block bool startVmAddrSet = false; __block uint64_t startVmAddr = 0; forEachRebase(diag, ^(const char* opcodeName, const LinkEditInfo& leInfo, const SegmentInfo segments[], bool segIndexSet, uint32_t ptrSize, uint8_t segmentIndex, uint64_t segmentOffset, Rebase kind, bool& stop) { if ( kind != Rebase::textAbsolute32 ) return; if ( !startVmAddrSet ) { for (int i=0; i <= segmentIndex; ++i) { if ( strcmp(segments[i].segName, "__TEXT") == 0 ) { startVmAddr = segments[i].vmAddr; startVmAddrSet = true; break; } } } uint64_t rebaseVmAddr = segments[segmentIndex].vmAddr + segmentOffset; uint64_t runtimeOffset = rebaseVmAddr - startVmAddr; handler(runtimeOffset, stop); }); } void MachOAnalyzer::forEachRebase(Diagnostics& diag, void (^callback)(uint64_t runtimeOffset, bool isLazyPointerRebase, bool& stop)) const { __block bool startVmAddrSet = false; __block uint64_t startVmAddr = 0; __block uint64_t lpVmAddr = 0; __block uint64_t lpEndVmAddr = 0; __block uint64_t shVmAddr = 0; __block uint64_t shEndVmAddr = 0; forEachSection(^(const dyld3::MachOAnalyzer::SectionInfo& info, bool malformedSectionRange, bool &stop) { if ( (info.sectFlags & SECTION_TYPE) == S_LAZY_SYMBOL_POINTERS ) { lpVmAddr = info.sectAddr; lpEndVmAddr = info.sectAddr + info.sectSize; } else if ( (info.sectFlags & S_ATTR_PURE_INSTRUCTIONS) && (strcmp(info.sectName, "__stub_helper") == 0) ) { shVmAddr = info.sectAddr; shEndVmAddr = info.sectAddr + info.sectSize; } }); forEachRebase(diag, ^(const char* opcodeName, const LinkEditInfo& leInfo, const SegmentInfo segments[], bool segIndexSet, uint32_t ptrSize, uint8_t segmentIndex, uint64_t segmentOffset, Rebase kind, bool& stop) { switch ( kind ) { case Rebase::unknown: return; case Rebase::pointer32: case Rebase::pointer64: // We only handle these kinds for now. break; case Rebase::textPCrel32: case Rebase::textAbsolute32: return; } if ( !startVmAddrSet ) { for (int i=0; i < segmentIndex; ++i) { if ( strcmp(segments[i].segName, "__TEXT") == 0 ) { startVmAddr = segments[i].vmAddr; startVmAddrSet = true; break; } } } uint64_t rebaseVmAddr = segments[segmentIndex].vmAddr + segmentOffset; bool isLazyPointerRebase = false; if ( (rebaseVmAddr >= lpVmAddr) && (rebaseVmAddr < lpEndVmAddr) ) { // rebase is in lazy pointer section uint64_t lpValue = 0; if ( ptrSize == 8 ) lpValue = *((uint64_t*)(rebaseVmAddr-startVmAddr+(uint8_t*)this)); else lpValue = *((uint32_t*)(rebaseVmAddr-startVmAddr+(uint8_t*)this)); if ( (lpValue >= shVmAddr) && (lpValue < shEndVmAddr) ) { // content is into stub_helper section uint64_t lpTargetImageOffset = lpValue - startVmAddr; const uint8_t* helperContent = (uint8_t*)this + lpTargetImageOffset; bool isLazyStub = contentIsRegularStub(helperContent); // ignore rebases for normal lazy pointers, but leave rebase for resolver helper stub if ( isLazyStub ) isLazyPointerRebase = true; } else { // if lazy pointer does not point into stub_helper, then it points to weak-def symbol and we need rebase } } uint64_t runtimeOffset = rebaseVmAddr - startVmAddr; callback(runtimeOffset, isLazyPointerRebase, stop); }); } void MachOAnalyzer::forEachRebase(Diagnostics& diag, bool ignoreLazyPointers, void (^handler)(uint64_t runtimeOffset, bool& stop)) const { forEachRebase(diag, ^(uint64_t runtimeOffset, bool isLazyPointerRebase, bool& stop) { if ( isLazyPointerRebase && ignoreLazyPointers ) return; handler(runtimeOffset, stop); }); } bool MachOAnalyzer::contentIsRegularStub(const uint8_t* helperContent) const { switch (this->cputype) { case CPU_TYPE_X86_64: return ( (helperContent[0] == 0x68) && (helperContent[5] == 0xE9) ); // push $xxx / JMP pcRel case CPU_TYPE_I386: return ( (helperContent[0] == 0x68) && (helperContent[5] == 0xFF) && (helperContent[2] == 0x26) ); // push $xxx / JMP *pcRel case CPU_TYPE_ARM: return ( (helperContent[0] == 0x00) && (helperContent[1] == 0xC0) && (helperContent[2] == 0x9F) && (helperContent[3] == 0xE5) ); // ldr ip, [pc, #0] case CPU_TYPE_ARM64: return ( (helperContent[0] == 0x50) && (helperContent[1] == 0x00) && (helperContent[2] == 0x00) && (helperContent[3] == 0x18) ); // ldr w16, L0 } return false; } void MachOAnalyzer::forEachRebase(Diagnostics& diag, void (^handler)(const char* opcodeName, const LinkEditInfo& leInfo, const SegmentInfo segments[], bool segIndexSet, uint32_t ptrSize, uint8_t segmentIndex, uint64_t segmentOffset, Rebase kind, bool& stop)) const { LinkEditInfo leInfo; getLinkEditPointers(diag, leInfo); if ( diag.hasError() ) return; BLOCK_ACCCESSIBLE_ARRAY(SegmentInfo, segmentsInfo, leInfo.layout.lastSegIndex+1); getAllSegmentsInfos(diag, segmentsInfo); if ( diag.hasError() ) return; const Rebase pointerRebaseKind = is64() ? Rebase::pointer64 : Rebase::pointer32; if ( leInfo.dyldInfo != nullptr ) { const uint8_t* const start = getLinkEditContent(leInfo.layout, leInfo.dyldInfo->rebase_off); const uint8_t* const end = start + leInfo.dyldInfo->rebase_size; const uint8_t* p = start; const uint32_t ptrSize = pointerSize(); Rebase kind = Rebase::unknown; int segIndex = 0; uint64_t segOffset = 0; uint64_t count; uint64_t skip; bool segIndexSet = false; bool stop = false; while ( !stop && diag.noError() && (p < end) ) { uint8_t immediate = *p & REBASE_IMMEDIATE_MASK; uint8_t opcode = *p & REBASE_OPCODE_MASK; ++p; switch (opcode) { case REBASE_OPCODE_DONE: // Allow some padding, in case rebases were somehow aligned to 16-bytes in size if ( (end - p) > 15 ) diag.error("rebase opcodes terminated early at offset %d of %d", (int)(p-start), (int)(end-start)); stop = true; break; case REBASE_OPCODE_SET_TYPE_IMM: switch ( immediate ) { case REBASE_TYPE_POINTER: kind = pointerRebaseKind; break; case REBASE_TYPE_TEXT_ABSOLUTE32: kind = Rebase::textAbsolute32; break; case REBASE_TYPE_TEXT_PCREL32: kind = Rebase::textPCrel32; break; default: kind = Rebase::unknown; break; } break; case REBASE_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB: segIndex = immediate; segOffset = read_uleb128(diag, p, end); segIndexSet = true; break; case REBASE_OPCODE_ADD_ADDR_ULEB: segOffset += read_uleb128(diag, p, end); break; case REBASE_OPCODE_ADD_ADDR_IMM_SCALED: segOffset += immediate*ptrSize; break; case REBASE_OPCODE_DO_REBASE_IMM_TIMES: for (int i=0; i < immediate; ++i) { handler("REBASE_OPCODE_DO_REBASE_IMM_TIMES", leInfo, segmentsInfo, segIndexSet, ptrSize, segIndex, segOffset, kind, stop); segOffset += ptrSize; if ( stop ) break; } break; case REBASE_OPCODE_DO_REBASE_ULEB_TIMES: count = read_uleb128(diag, p, end); for (uint32_t i=0; i < count; ++i) { handler("REBASE_OPCODE_DO_REBASE_ADD_ADDR_ULEB", leInfo, segmentsInfo, segIndexSet, ptrSize, segIndex, segOffset, kind, stop); segOffset += ptrSize; if ( stop ) break; } break; case REBASE_OPCODE_DO_REBASE_ADD_ADDR_ULEB: handler("REBASE_OPCODE_DO_REBASE_ADD_ADDR_ULEB", leInfo, segmentsInfo, segIndexSet, ptrSize, segIndex, segOffset, kind, stop); segOffset += read_uleb128(diag, p, end) + ptrSize; break; case REBASE_OPCODE_DO_REBASE_ULEB_TIMES_SKIPPING_ULEB: count = read_uleb128(diag, p, end); if ( diag.hasError() ) break; skip = read_uleb128(diag, p, end); for (uint32_t i=0; i < count; ++i) { handler("REBASE_OPCODE_DO_REBASE_ULEB_TIMES_SKIPPING_ULEB", leInfo, segmentsInfo, segIndexSet, ptrSize, segIndex, segOffset, kind, stop); segOffset += skip + ptrSize; if ( stop ) break; } break; default: diag.error("unknown rebase opcode 0x%02X", opcode); } } return; } if ( leInfo.chainedFixups != nullptr ) { // binary uses chained fixups, so do nothing // The kernel collections need to support both chained and classic relocations // If we are anything other than a kernel collection, then return here as we won't have // anything else to do. if ( !isFileSet() ) return; } #if SUPPORT_CLASSIC_RELOCS if ( leInfo.dynSymTab != nullptr ) { // old binary, walk relocations const uint64_t relocsStartAddress = localRelocBaseAddress(segmentsInfo, leInfo.layout.linkeditSegIndex); const relocation_info* const relocsStart = (relocation_info*)getLinkEditContent(leInfo.layout, leInfo.dynSymTab->locreloff); const relocation_info* const relocsEnd = &relocsStart[leInfo.dynSymTab->nlocrel]; bool stop = false; const uint8_t relocSize = (is64() ? 3 : 2); const uint8_t ptrSize = pointerSize(); STACK_ALLOC_OVERFLOW_SAFE_ARRAY(relocation_info, relocs, 2048); for (const relocation_info* reloc=relocsStart; (reloc < relocsEnd) && !stop; ++reloc) { if ( reloc->r_length != relocSize ) { bool shouldEmitError = true; #if BUILDING_APP_CACHE_UTIL || BUILDING_DYLDINFO if ( usesClassicRelocationsInKernelCollection() && (reloc->r_length == 2) && (relocSize == 3) ) shouldEmitError = false; #endif if ( shouldEmitError ) { diag.error("local relocation has wrong r_length"); break; } } if ( reloc->r_type != 0 ) { // 0 == X86_64_RELOC_UNSIGNED == GENERIC_RELOC_VANILLA == ARM64_RELOC_UNSIGNED diag.error("local relocation has wrong r_type"); break; } relocs.push_back(*reloc); } if ( !relocs.empty() ) { sortRelocations(relocs); for (relocation_info reloc : relocs) { uint32_t addrOff = reloc.r_address; uint32_t segIndex = 0; uint64_t segOffset = 0; uint64_t addr = 0; #if BUILDING_APP_CACHE_UTIL || BUILDING_DYLDINFO // xnu for x86_64 has __HIB mapped before __DATA, so offsets appear to be // negative if ( isStaticExecutable() || isFileSet() ) { addr = relocsStartAddress + (int32_t)addrOff; } else { addr = relocsStartAddress + addrOff; } #else addr = relocsStartAddress + addrOff; #endif if ( segIndexAndOffsetForAddress(addr, segmentsInfo, leInfo.layout.linkeditSegIndex, segIndex, segOffset) ) { Rebase kind = (reloc.r_length == 2) ? Rebase::pointer32 : Rebase::pointer64; if ( this->cputype == CPU_TYPE_I386 ) { if ( segmentsInfo[segIndex].executable() ) kind = Rebase::textAbsolute32; } handler("local relocation", leInfo, segmentsInfo, true, ptrSize, segIndex, segOffset, kind, stop); } else { diag.error("local relocation has out of range r_address"); break; } } } // then process indirect symbols forEachIndirectPointer(diag, false, ^(uint64_t address, bool bind, int bindLibOrdinal, const char* bindSymbolName, bool bindWeakImport, bool bindLazy, bool selfModifyingStub, bool& indStop) { if ( bind ) return; uint32_t segIndex = 0; uint64_t segOffset = 0; if ( segIndexAndOffsetForAddress(address, segmentsInfo, leInfo.layout.linkeditSegIndex, segIndex, segOffset) ) { handler("local relocation", leInfo, segmentsInfo, true, ptrSize, segIndex, segOffset, pointerRebaseKind, indStop); } else { diag.error("local relocation has out of range r_address"); indStop = true; } }); } #endif // SUPPORT_CLASSIC_RELOCS } bool MachOAnalyzer::segIndexAndOffsetForAddress(uint64_t addr, const SegmentInfo segmentsInfos[], uint32_t segCount, uint32_t& segIndex, uint64_t& segOffset) const { for (uint32_t i=0; i < segCount; ++i) { if ( (segmentsInfos[i].vmAddr <= addr) && (addr < segmentsInfos[i].vmAddr+segmentsInfos[i].vmSize) ) { segIndex = i; segOffset = addr - segmentsInfos[i].vmAddr; return true; } } return false; } uint64_t MachOAnalyzer::localRelocBaseAddress(const SegmentInfo segmentsInfos[], uint32_t segCount) const { if ( isArch("x86_64") || isArch("x86_64h") ) { #if BUILDING_APP_CACHE_UTIL || BUILDING_DYLDINFO if ( isKextBundle() ) { // for kext bundles the reloc base address starts at __TEXT segment return segmentsInfos[0].vmAddr; } #endif // for all other kinds, the x86_64 reloc base address starts at first writable segment (usually __DATA) for (uint32_t i=0; i < segCount; ++i) { if ( segmentsInfos[i].writable() ) return segmentsInfos[i].vmAddr; } } // reloc base address is start of TEXT segment if ( this->isMainExecutable() && (segmentsInfos[0].protections == 0) ) return segmentsInfos[1].vmAddr; else return segmentsInfos[0].vmAddr; } uint64_t MachOAnalyzer::externalRelocBaseAddress(const SegmentInfo segmentsInfos[], uint32_t segCount) const { // Dyld caches are too large for a raw r_address, so everything is an offset from the base address if ( inDyldCache() ) { return preferredLoadAddress(); } #if BUILDING_APP_CACHE_UTIL || BUILDING_DYLDINFO if ( isKextBundle() ) { // for kext bundles the reloc base address starts at __TEXT segment return preferredLoadAddress(); } #endif if ( isArch("x86_64") || isArch("x86_64h") ) { // for x86_64 reloc base address starts at first writable segment (usually __DATA) for (uint32_t i=0; i < segCount; ++i) { if ( segmentsInfos[i].writable() ) return segmentsInfos[i].vmAddr; } } // For everyone else we start at 0 return 0; } void MachOAnalyzer::forEachIndirectPointer(Diagnostics& diag, bool supportPrivateExternsWorkaround, void (^handler)(uint64_t pointerAddress, bool bind, int bindLibOrdinal, const char* bindSymbolName, bool bindWeakImport, bool bindLazy, bool selfModifyingStub, bool& stop)) const { LinkEditInfo leInfo; getLinkEditPointers(diag, leInfo); if ( diag.hasError() ) return; // find lazy and non-lazy pointer sections const bool is64Bit = is64(); const uint32_t* const indirectSymbolTable = (uint32_t*)getLinkEditContent(leInfo.layout, leInfo.dynSymTab->indirectsymoff); const uint32_t indirectSymbolTableCount = leInfo.dynSymTab->nindirectsyms; const uint32_t ptrSize = pointerSize(); const void* symbolTable = getLinkEditContent(leInfo.layout, leInfo.symTab->symoff); const struct nlist_64* symbols64 = (nlist_64*)symbolTable; const struct nlist* symbols32 = (struct nlist*)symbolTable; const char* stringPool = (char*)getLinkEditContent(leInfo.layout, leInfo.symTab->stroff); uint32_t symCount = leInfo.symTab->nsyms; uint32_t poolSize = leInfo.symTab->strsize; __block bool stop = false; // Old kexts put S_LAZY_SYMBOL_POINTERS on the __got section, even if they didn't have indirect symbols to prcess. // In that case, skip the loop as there shouldn't be anything to process if ( (indirectSymbolTableCount == 0) && isKextBundle() ) return; forEachSection(^(const dyld3::MachOAnalyzer::SectionInfo& sectInfo, bool malformedSectionRange, bool& sectionStop) { uint8_t sectionType = (sectInfo.sectFlags & SECTION_TYPE); bool selfModifyingStub = (sectionType == S_SYMBOL_STUBS) && (sectInfo.sectFlags & S_ATTR_SELF_MODIFYING_CODE) && (sectInfo.reserved2 == 5) && (this->cputype == CPU_TYPE_I386); if ( (sectionType != S_LAZY_SYMBOL_POINTERS) && (sectionType != S_NON_LAZY_SYMBOL_POINTERS) && !selfModifyingStub ) return; if ( (flags & S_ATTR_SELF_MODIFYING_CODE) && !selfModifyingStub ) { diag.error("S_ATTR_SELF_MODIFYING_CODE section type only valid in old i386 binaries"); sectionStop = true; return; } uint32_t elementSize = selfModifyingStub ? sectInfo.reserved2 : ptrSize; uint32_t elementCount = (uint32_t)(sectInfo.sectSize/elementSize); if ( greaterThanAddOrOverflow(sectInfo.reserved1, elementCount, indirectSymbolTableCount) ) { diag.error("section %s overflows indirect symbol table", sectInfo.sectName); sectionStop = true; return; } for (uint32_t i=0; (i < elementCount) && !stop; ++i) { uint32_t symNum = indirectSymbolTable[sectInfo.reserved1 + i]; if ( symNum == INDIRECT_SYMBOL_ABS ) continue; if ( symNum == INDIRECT_SYMBOL_LOCAL ) { handler(sectInfo.sectAddr+i*elementSize, false, 0, "", false, false, false, stop); continue; } if ( symNum > symCount ) { diag.error("indirect symbol[%d] = %d which is invalid symbol index", sectInfo.reserved1 + i, symNum); sectionStop = true; return; } uint16_t n_desc = is64Bit ? symbols64[symNum].n_desc : symbols32[symNum].n_desc; uint8_t n_type = is64Bit ? symbols64[symNum].n_type : symbols32[symNum].n_type; uint32_t libOrdinal = libOrdinalFromDesc(n_desc); uint32_t strOffset = is64Bit ? symbols64[symNum].n_un.n_strx : symbols32[symNum].n_un.n_strx; if ( strOffset > poolSize ) { diag.error("symbol[%d] string offset out of range", sectInfo.reserved1 + i); sectionStop = true; return; } const char* symbolName = stringPool + strOffset; bool weakImport = (n_desc & N_WEAK_REF); bool lazy = (sectionType == S_LAZY_SYMBOL_POINTERS); #if BUILDING_DYLD && TARGET_OS_OSX && __x86_64__ if ( lazy && ((n_type & N_PEXT) != 0) ) { // don't know why the static linker did not eliminate the internal reference to a private extern definition // As this is private extern, we know the symbol lookup will fail. We also know that this is a lazy-bind, and so // there is a corresponding rebase. The rebase will be run later, and will slide whatever value is in here. // So lets change the value in this slot, and let the existing rebase slide it for us // Note we only want to change the value in memory once, before rebases are applied. We don't want to accidentally // change it again later. if ( supportPrivateExternsWorkaround ) { uintptr_t* ptr = (uintptr_t*)((uint8_t*)(sectInfo.sectAddr+i*elementSize) + this->getSlide()); uint64_t n_value = is64Bit ? symbols64[symNum].n_value : symbols32[symNum].n_value; *ptr = (uintptr_t)n_value; } continue; } #endif // Handle defined weak def symbols which need to get a special ordinal if ( ((n_type & N_TYPE) == N_SECT) && ((n_type & N_EXT) != 0) && ((n_desc & N_WEAK_DEF) != 0) ) libOrdinal = BIND_SPECIAL_DYLIB_WEAK_LOOKUP; handler(sectInfo.sectAddr+i*elementSize, true, libOrdinal, symbolName, weakImport, lazy, selfModifyingStub, stop); } sectionStop = stop; }); } int MachOAnalyzer::libOrdinalFromDesc(uint16_t n_desc) const { // -flat_namespace is always flat lookup if ( (this->flags & MH_TWOLEVEL) == 0 ) return BIND_SPECIAL_DYLIB_FLAT_LOOKUP; // extract byte from undefined symbol entry int libIndex = GET_LIBRARY_ORDINAL(n_desc); switch ( libIndex ) { case SELF_LIBRARY_ORDINAL: return BIND_SPECIAL_DYLIB_SELF; case DYNAMIC_LOOKUP_ORDINAL: return BIND_SPECIAL_DYLIB_FLAT_LOOKUP; case EXECUTABLE_ORDINAL: return BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE; } return libIndex; } bool MachOAnalyzer::validBindInfo(Diagnostics& diag, const char* path) const { forEachBind(diag, ^(const char* opcodeName, const LinkEditInfo& leInfo, const SegmentInfo segments[], bool segIndexSet, bool libraryOrdinalSet, uint32_t dylibCount, int libOrdinal, uint32_t ptrSize, uint8_t segmentIndex, uint64_t segmentOffset, uint8_t type, const char* symbolName, bool weakImport, bool lazyBind, uint64_t addend, bool& stop) { if ( invalidBindState(diag, opcodeName, path, leInfo, segments, segIndexSet, libraryOrdinalSet, dylibCount, libOrdinal, ptrSize, segmentIndex, segmentOffset, type, symbolName) ) { stop = true; } }, ^(const char* symbolName) { }); return diag.noError(); } bool MachOAnalyzer::invalidBindState(Diagnostics& diag, const char* opcodeName, const char* path, const LinkEditInfo& leInfo, const SegmentInfo segments[], bool segIndexSet, bool libraryOrdinalSet, uint32_t dylibCount, int libOrdinal, uint32_t ptrSize, uint8_t segmentIndex, uint64_t segmentOffset, uint8_t type, const char* symbolName) const { if ( !segIndexSet ) { diag.error("in '%s' %s missing preceding BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB", path, opcodeName); return true; } if ( segmentIndex >= leInfo.layout.linkeditSegIndex ) { diag.error("in '%s' %s segment index %d too large", path, opcodeName, segmentIndex); return true; } if ( segmentOffset > (segments[segmentIndex].vmSize-ptrSize) ) { diag.error("in '%s' %s current segment offset 0x%08llX beyond segment size (0x%08llX)", path, opcodeName, segmentOffset, segments[segmentIndex].vmSize); return true; } if ( symbolName == NULL ) { diag.error("in '%s' %s missing preceding BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM", path, opcodeName); return true; } if ( !libraryOrdinalSet ) { diag.error("in '%s' %s missing preceding BIND_OPCODE_SET_DYLIB_ORDINAL", path, opcodeName); return true; } if ( libOrdinal > (int)dylibCount ) { diag.error("in '%s' %s has library ordinal too large (%d) max (%d)", path, opcodeName, libOrdinal, dylibCount); return true; } if ( libOrdinal < BIND_SPECIAL_DYLIB_WEAK_LOOKUP ) { diag.error("in '%s' %s has unknown library special ordinal (%d)", path, opcodeName, libOrdinal); return true; } switch ( type ) { case BIND_TYPE_POINTER: if ( !segments[segmentIndex].writable() ) { diag.error("in '%s' %s pointer bind is in non-writable segment", path, opcodeName); return true; } if ( segments[segmentIndex].executable() && enforceFormat(Malformed::executableData) ) { diag.error("in '%s' %s pointer bind is in executable segment", path, opcodeName); return true; } break; case BIND_TYPE_TEXT_ABSOLUTE32: case BIND_TYPE_TEXT_PCREL32: { // Text relocations are permitted in x86_64 kexts bool forceAllowTextRelocs = false; #if BUILDING_APP_CACHE_UTIL || BUILDING_DYLDINFO if ( isKextBundle() && (isArch("x86_64") || isArch("x86_64h")) ) forceAllowTextRelocs = true; #endif if ( !forceAllowTextRelocs && !segments[segmentIndex].textRelocs ) { diag.error("in '%s' %s text bind is in segment that does not support text relocations", path, opcodeName); return true; } if ( segments[segmentIndex].writable() ) { diag.error("in '%s' %s text bind is in writable segment", path, opcodeName); return true; } if ( !segments[segmentIndex].executable() ) { diag.error("in '%s' %s pointer bind is in non-executable segment", path, opcodeName); return true; } break; } default: diag.error("in '%s' %s unknown bind type %d", path, opcodeName, type); return true; } return false; } void MachOAnalyzer::forEachBind(Diagnostics& diag, void (^handler)(uint64_t runtimeOffset, int libOrdinal, uint8_t type, const char* symbolName, bool weakImport, bool lazyBind, uint64_t addend, bool& stop), void (^strongHandler)(const char* symbolName)) const { __block bool startVmAddrSet = false; __block uint64_t startVmAddr = 0; forEachBind(diag, ^(const char* opcodeName, const LinkEditInfo& leInfo, const SegmentInfo segments[], bool segIndexSet, bool libraryOrdinalSet, uint32_t dylibCount, int libOrdinal, uint32_t ptrSize, uint8_t segmentIndex, uint64_t segmentOffset, uint8_t type, const char* symbolName, bool weakImport, bool lazyBind, uint64_t addend, bool& stop) { if ( !startVmAddrSet ) { for (int i=0; i <= segmentIndex; ++i) { if ( strcmp(segments[i].segName, "__TEXT") == 0 ) { startVmAddr = segments[i].vmAddr; startVmAddrSet = true; break; } } } uint64_t bindVmOffset = segments[segmentIndex].vmAddr + segmentOffset; uint64_t runtimeOffset = bindVmOffset - startVmAddr; handler(runtimeOffset, libOrdinal, type, symbolName, weakImport, lazyBind, addend, stop); }, ^(const char* symbolName) { strongHandler(symbolName); }); } void MachOAnalyzer::forEachBind(Diagnostics& diag, void (^handler)(uint64_t runtimeOffset, int libOrdinal, const char* symbolName, bool weakImport, bool lazyBind, uint64_t addend, bool& stop), void (^strongHandler)(const char* symbolName)) const { forEachBind(diag, ^(uint64_t runtimeOffset, int libOrdinal, uint8_t type, const char* symbolName, bool weakImport, bool lazyBind, uint64_t addend, bool &stop) { handler(runtimeOffset, libOrdinal, symbolName, weakImport, lazyBind, addend, stop); }, strongHandler); } void MachOAnalyzer::forEachBind(Diagnostics& diag, void (^handler)(const char* opcodeName, const LinkEditInfo& leInfo, const SegmentInfo segments[], bool segIndexSet, bool libraryOrdinalSet, uint32_t dylibCount, int libOrdinal, uint32_t ptrSize, uint8_t segmentIndex, uint64_t segmentOffset, uint8_t type, const char* symbolName, bool weakImport, bool lazyBind, uint64_t addend, bool& stop), void (^strongHandler)(const char* symbolName)) const { const uint32_t ptrSize = this->pointerSize(); bool stop = false; LinkEditInfo leInfo; getLinkEditPointers(diag, leInfo); if ( diag.hasError() ) return; BLOCK_ACCCESSIBLE_ARRAY(SegmentInfo, segmentsInfo, leInfo.layout.lastSegIndex+1); getAllSegmentsInfos(diag, segmentsInfo); if ( diag.hasError() ) return; const uint32_t dylibCount = dependentDylibCount(); if ( leInfo.dyldInfo != nullptr ) { // process bind opcodes const uint8_t* p = getLinkEditContent(leInfo.layout, leInfo.dyldInfo->bind_off); const uint8_t* end = p + leInfo.dyldInfo->bind_size; uint8_t type = 0; uint64_t segmentOffset = 0; uint8_t segmentIndex = 0; const char* symbolName = NULL; int libraryOrdinal = 0; bool segIndexSet = false; bool libraryOrdinalSet = false; int64_t addend = 0; uint64_t count; uint64_t skip; bool weakImport = false; while ( !stop && diag.noError() && (p < end) ) { uint8_t immediate = *p & BIND_IMMEDIATE_MASK; uint8_t opcode = *p & BIND_OPCODE_MASK; ++p; switch (opcode) { case BIND_OPCODE_DONE: stop = true; break; case BIND_OPCODE_SET_DYLIB_ORDINAL_IMM: libraryOrdinal = immediate; libraryOrdinalSet = true; break; case BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB: libraryOrdinal = (int)read_uleb128(diag, p, end); libraryOrdinalSet = true; break; case BIND_OPCODE_SET_DYLIB_SPECIAL_IMM: // the special ordinals are negative numbers if ( immediate == 0 ) libraryOrdinal = 0; else { int8_t signExtended = BIND_OPCODE_MASK | immediate; libraryOrdinal = signExtended; } libraryOrdinalSet = true; break; case BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM: weakImport = ( (immediate & BIND_SYMBOL_FLAGS_WEAK_IMPORT) != 0 ); symbolName = (char*)p; while (*p != '\0') ++p; ++p; break; case BIND_OPCODE_SET_TYPE_IMM: type = immediate; break; case BIND_OPCODE_SET_ADDEND_SLEB: addend = read_sleb128(diag, p, end); break; case BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB: segmentIndex = immediate; segmentOffset = read_uleb128(diag, p, end); segIndexSet = true; break; case BIND_OPCODE_ADD_ADDR_ULEB: segmentOffset += read_uleb128(diag, p, end); break; case BIND_OPCODE_DO_BIND: handler("BIND_OPCODE_DO_BIND", leInfo, segmentsInfo, segIndexSet, libraryOrdinalSet, dylibCount, libraryOrdinal, ptrSize, segmentIndex, segmentOffset, type, symbolName, weakImport, false, addend, stop); segmentOffset += ptrSize; break; case BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB: handler("BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB", leInfo, segmentsInfo, segIndexSet, libraryOrdinalSet, dylibCount, libraryOrdinal, ptrSize, segmentIndex, segmentOffset, type, symbolName, weakImport, false, addend, stop); segmentOffset += read_uleb128(diag, p, end) + ptrSize; break; case BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED: handler("BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED", leInfo, segmentsInfo, segIndexSet, libraryOrdinalSet, dylibCount, libraryOrdinal, ptrSize, segmentIndex, segmentOffset, type, symbolName, weakImport, false, addend, stop); segmentOffset += immediate*ptrSize + ptrSize; break; case BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB: count = read_uleb128(diag, p, end); skip = read_uleb128(diag, p, end); for (uint32_t i=0; i < count; ++i) { handler("BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB", leInfo, segmentsInfo, segIndexSet, libraryOrdinalSet, dylibCount, libraryOrdinal, ptrSize, segmentIndex, segmentOffset, type, symbolName, weakImport, false, addend, stop); segmentOffset += skip + ptrSize; if ( stop ) break; } break; default: diag.error("bad bind opcode 0x%02X", *p); } } if ( diag.hasError() ) return; // process lazy bind opcodes uint32_t lazyDoneCount = 0; uint32_t lazyBindCount = 0; if ( leInfo.dyldInfo->lazy_bind_size != 0 ) { p = getLinkEditContent(leInfo.layout, leInfo.dyldInfo->lazy_bind_off); end = p + leInfo.dyldInfo->lazy_bind_size; type = BIND_TYPE_POINTER; segmentOffset = 0; segmentIndex = 0; symbolName = NULL; libraryOrdinal = 0; segIndexSet = false; libraryOrdinalSet= false; addend = 0; weakImport = false; stop = false; while ( !stop && diag.noError() && (p < end) ) { uint8_t immediate = *p & BIND_IMMEDIATE_MASK; uint8_t opcode = *p & BIND_OPCODE_MASK; ++p; switch (opcode) { case BIND_OPCODE_DONE: // this opcode marks the end of each lazy pointer binding ++lazyDoneCount; break; case BIND_OPCODE_SET_DYLIB_ORDINAL_IMM: libraryOrdinal = immediate; libraryOrdinalSet = true; break; case BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB: libraryOrdinal = (int)read_uleb128(diag, p, end); libraryOrdinalSet = true; break; case BIND_OPCODE_SET_DYLIB_SPECIAL_IMM: // the special ordinals are negative numbers if ( immediate == 0 ) libraryOrdinal = 0; else { int8_t signExtended = BIND_OPCODE_MASK | immediate; libraryOrdinal = signExtended; } libraryOrdinalSet = true; break; case BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM: weakImport = ( (immediate & BIND_SYMBOL_FLAGS_WEAK_IMPORT) != 0 ); symbolName = (char*)p; while (*p != '\0') ++p; ++p; break; case BIND_OPCODE_SET_ADDEND_SLEB: addend = read_sleb128(diag, p, end); break; case BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB: segmentIndex = immediate; segmentOffset = read_uleb128(diag, p, end); segIndexSet = true; break; case BIND_OPCODE_DO_BIND: handler("BIND_OPCODE_DO_BIND", leInfo, segmentsInfo, segIndexSet, libraryOrdinalSet, dylibCount, libraryOrdinal, ptrSize, segmentIndex, segmentOffset, type, symbolName, weakImport, true, addend, stop); segmentOffset += ptrSize; ++lazyBindCount; break; case BIND_OPCODE_SET_TYPE_IMM: case BIND_OPCODE_ADD_ADDR_ULEB: case BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB: case BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED: case BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB: default: diag.error("bad lazy bind opcode 0x%02X", opcode); break; } } if ( lazyDoneCount > lazyBindCount+7 ) { // diag.error("lazy bind opcodes missing binds"); } } if ( diag.hasError() ) return; // process weak bind info if ( leInfo.dyldInfo->weak_bind_size != 0 ) { p = getLinkEditContent(leInfo.layout, leInfo.dyldInfo->weak_bind_off); end = p + leInfo.dyldInfo->weak_bind_size; type = BIND_TYPE_POINTER; segmentOffset = 0; segmentIndex = 0; symbolName = NULL; libraryOrdinal = BIND_SPECIAL_DYLIB_WEAK_LOOKUP; segIndexSet = false; libraryOrdinalSet= true; addend = 0; weakImport = false; stop = false; while ( !stop && diag.noError() && (p < end) ) { uint8_t immediate = *p & BIND_IMMEDIATE_MASK; uint8_t opcode = *p & BIND_OPCODE_MASK; ++p; switch (opcode) { case BIND_OPCODE_DONE: stop = true; break; case BIND_OPCODE_SET_DYLIB_ORDINAL_IMM: case BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB: case BIND_OPCODE_SET_DYLIB_SPECIAL_IMM: diag.error("unexpected dylib ordinal in weak_bind"); break; case BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM: weakImport = ( (immediate & BIND_SYMBOL_FLAGS_WEAK_IMPORT) != 0 ); symbolName = (char*)p; while (*p != '\0') ++p; ++p; if ( immediate & BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION ) { strongHandler(symbolName); } break; case BIND_OPCODE_SET_TYPE_IMM: type = immediate; break; case BIND_OPCODE_SET_ADDEND_SLEB: addend = read_sleb128(diag, p, end); break; case BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB: segmentIndex = immediate; segmentOffset = read_uleb128(diag, p, end); segIndexSet = true; break; case BIND_OPCODE_ADD_ADDR_ULEB: segmentOffset += read_uleb128(diag, p, end); break; case BIND_OPCODE_DO_BIND: handler("BIND_OPCODE_DO_BIND", leInfo, segmentsInfo, segIndexSet, libraryOrdinalSet, dylibCount, libraryOrdinal, ptrSize, segmentIndex, segmentOffset, type, symbolName, weakImport, false, addend, stop); segmentOffset += ptrSize; break; case BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB: handler("BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB", leInfo, segmentsInfo, segIndexSet, libraryOrdinalSet, dylibCount, libraryOrdinal, ptrSize, segmentIndex, segmentOffset, type, symbolName, weakImport, false, addend, stop); segmentOffset += read_uleb128(diag, p, end) + ptrSize; break; case BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED: handler("BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED", leInfo, segmentsInfo, segIndexSet, libraryOrdinalSet, dylibCount, libraryOrdinal, ptrSize, segmentIndex, segmentOffset, type, symbolName, weakImport, false, addend, stop); segmentOffset += immediate*ptrSize + ptrSize; break; case BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB: count = read_uleb128(diag, p, end); skip = read_uleb128(diag, p, end); for (uint32_t i=0; i < count; ++i) { handler("BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB", leInfo, segmentsInfo, segIndexSet, libraryOrdinalSet, dylibCount, libraryOrdinal, ptrSize, segmentIndex, segmentOffset, type, symbolName, weakImport, false, addend, stop); segmentOffset += skip + ptrSize; if ( stop ) break; } break; default: diag.error("bad bind opcode 0x%02X", *p); } } } } else if ( leInfo.chainedFixups != nullptr ) { // binary uses chained fixups, so do nothing } #if SUPPORT_CLASSIC_RELOCS else if ( leInfo.dynSymTab != nullptr ) { // old binary, process external relocations const uint64_t relocsStartAddress = externalRelocBaseAddress(segmentsInfo, leInfo.layout.linkeditSegIndex); const relocation_info* const relocsStart = (relocation_info*)getLinkEditContent(leInfo.layout, leInfo.dynSymTab->extreloff); const relocation_info* const relocsEnd = &relocsStart[leInfo.dynSymTab->nextrel]; bool is64Bit = is64() ; const uint8_t relocSize = (is64Bit ? 3 : 2); const void* symbolTable = getLinkEditContent(leInfo.layout, leInfo.symTab->symoff); const struct nlist_64* symbols64 = (nlist_64*)symbolTable; const struct nlist* symbols32 = (struct nlist*)symbolTable; const char* stringPool = (char*)getLinkEditContent(leInfo.layout, leInfo.symTab->stroff); uint32_t symCount = leInfo.symTab->nsyms; uint32_t poolSize = leInfo.symTab->strsize; for (const relocation_info* reloc=relocsStart; (reloc < relocsEnd) && !stop; ++reloc) { bool isBranch = false; #if BUILDING_APP_CACHE_UTIL || BUILDING_DYLDINFO if ( isKextBundle() ) { // kext's may have other kinds of relocations, eg, branch relocs. Skip them if ( isArch("x86_64") || isArch("x86_64h") ) { if ( reloc->r_type == X86_64_RELOC_BRANCH ) { if ( reloc->r_length != 2 ) { diag.error("external relocation has wrong r_length"); break; } if ( reloc->r_pcrel != true ) { diag.error("external relocation should be pcrel"); break; } isBranch = true; } } } #endif if ( !isBranch ) { if ( reloc->r_length != relocSize ) { diag.error("external relocation has wrong r_length"); break; } if ( reloc->r_type != 0 ) { // 0 == X86_64_RELOC_UNSIGNED == GENERIC_RELOC_VANILLA == ARM64_RELOC_UNSIGNED diag.error("external relocation has wrong r_type"); break; } } uint32_t segIndex = 0; uint64_t segOffset = 0; if ( segIndexAndOffsetForAddress(relocsStartAddress+reloc->r_address, segmentsInfo, leInfo.layout.linkeditSegIndex, segIndex, segOffset) ) { uint32_t symbolIndex = reloc->r_symbolnum; if ( symbolIndex > symCount ) { diag.error("external relocation has out of range r_symbolnum"); break; } else { uint32_t strOffset = is64Bit ? symbols64[symbolIndex].n_un.n_strx : symbols32[symbolIndex].n_un.n_strx; uint16_t n_desc = is64Bit ? symbols64[symbolIndex].n_desc : symbols32[symbolIndex].n_desc; uint8_t n_type = is64Bit ? symbols64[symbolIndex].n_type : symbols32[symbolIndex].n_type; uint32_t libOrdinal = libOrdinalFromDesc(n_desc); if ( strOffset >= poolSize ) { diag.error("external relocation has r_symbolnum=%d which has out of range n_strx", symbolIndex); break; } else { const char* symbolName = stringPool + strOffset; bool weakImport = (n_desc & N_WEAK_REF); const uint8_t* content = (uint8_t*)this + segmentsInfo[segIndex].vmAddr - leInfo.layout.textUnslidVMAddr + segOffset; uint64_t addend = (reloc->r_length == 3) ? *((uint64_t*)content) : *((uint32_t*)content); // Handle defined weak def symbols which need to get a special ordinal if ( ((n_type & N_TYPE) == N_SECT) && ((n_type & N_EXT) != 0) && ((n_desc & N_WEAK_DEF) != 0) ) libOrdinal = BIND_SPECIAL_DYLIB_WEAK_LOOKUP; uint8_t type = isBranch ? BIND_TYPE_TEXT_PCREL32 : BIND_TYPE_POINTER; handler("external relocation", leInfo, segmentsInfo, true, true, dylibCount, libOrdinal, ptrSize, segIndex, segOffset, type, symbolName, weakImport, false, addend, stop); } } } else { diag.error("local relocation has out of range r_address"); break; } } // then process indirect symbols forEachIndirectPointer(diag, false, ^(uint64_t address, bool bind, int bindLibOrdinal, const char* bindSymbolName, bool bindWeakImport, bool bindLazy, bool selfModifyingStub, bool& indStop) { if ( !bind ) return; uint32_t segIndex = 0; uint64_t segOffset = 0; if ( segIndexAndOffsetForAddress(address, segmentsInfo, leInfo.layout.linkeditSegIndex, segIndex, segOffset) ) { handler("indirect symbol", leInfo, segmentsInfo, true, true, dylibCount, bindLibOrdinal, ptrSize, segIndex, segOffset, BIND_TYPE_POINTER, bindSymbolName, bindWeakImport, bindLazy, 0, indStop); } else { diag.error("indirect symbol has out of range address"); indStop = true; } }); } #endif // SUPPORT_CLASSIC_RELOCS } bool MachOAnalyzer::validChainedFixupsInfo(Diagnostics& diag, const char* path) const { LinkEditInfo leInfo; getLinkEditPointers(diag, leInfo); if ( diag.hasError() ) return false; BLOCK_ACCCESSIBLE_ARRAY(SegmentInfo, segmentsInfo, leInfo.layout.lastSegIndex+1); getAllSegmentsInfos(diag, segmentsInfo); if ( diag.hasError() ) return false; // validate dyld_chained_fixups_header const dyld_chained_fixups_header* chainsHeader = (dyld_chained_fixups_header*)getLinkEditContent(leInfo.layout, leInfo.chainedFixups->dataoff); if ( chainsHeader->fixups_version != 0 ) { diag.error("chained fixups, unknown header version"); return false; } if ( chainsHeader->starts_offset >= leInfo.chainedFixups->datasize ) { diag.error("chained fixups, starts_offset exceeds LC_DYLD_CHAINED_FIXUPS size"); return false; } if ( chainsHeader->imports_offset > leInfo.chainedFixups->datasize ) { diag.error("chained fixups, imports_offset exceeds LC_DYLD_CHAINED_FIXUPS size"); return false; } uint32_t formatEntrySize; switch ( chainsHeader->imports_format ) { case DYLD_CHAINED_IMPORT: formatEntrySize = sizeof(dyld_chained_import); break; case DYLD_CHAINED_IMPORT_ADDEND: formatEntrySize = sizeof(dyld_chained_import_addend); break; case DYLD_CHAINED_IMPORT_ADDEND64: formatEntrySize = sizeof(dyld_chained_import_addend64); break; default: diag.error("chained fixups, unknown imports_format"); return false; } if ( greaterThanAddOrOverflow(chainsHeader->imports_offset, (formatEntrySize * chainsHeader->imports_count), chainsHeader->symbols_offset) ) { diag.error("chained fixups, imports array overlaps symbols"); return false; } if ( chainsHeader->symbols_format != 0 ) { diag.error("chained fixups, symbols_format unknown"); return false; } // validate dyld_chained_starts_in_image const dyld_chained_starts_in_image* startsInfo = (dyld_chained_starts_in_image*)((uint8_t*)chainsHeader + chainsHeader->starts_offset); if ( startsInfo->seg_count != leInfo.layout.linkeditSegIndex+1 ) { // We can have fewer segments than the count, so long as those we are missing have no relocs // This can happen because __CTF is inserted by ctf_insert after linking, and between __DATA and __LINKEDIT, but has no relocs // ctf_insert updates the load commands to put __CTF between __DATA and __LINKEDIT, but doesn't update the chained fixups data structures if ( startsInfo->seg_count > (leInfo.layout.linkeditSegIndex + 1) ) { diag.error("chained fixups, seg_count exceeds number of segments"); return false; } // We can have fewer segments than the count, so long as those we are missing have no relocs uint32_t numNoRelocSegments = 0; uint32_t numExtraSegments = (leInfo.layout.lastSegIndex + 1) - startsInfo->seg_count; for (unsigned i = 0; i != numExtraSegments; ++i) { // Check each extra segment before linkedit const SegmentInfo& segInfo = segmentsInfo[leInfo.layout.linkeditSegIndex - (i + 1)]; if ( segInfo.vmSize == 0 ) ++numNoRelocSegments; } if ( numNoRelocSegments != numExtraSegments ) { diag.error("chained fixups, seg_count does not match number of segments"); return false; } } const uint64_t baseAddress = preferredLoadAddress(); uint32_t maxValidPointerSeen = 0; uint16_t pointer_format_for_all = 0; bool pointer_format_found = false; const uint8_t* endOfStarts = (uint8_t*)chainsHeader + chainsHeader->imports_offset; for (uint32_t i=0; i < startsInfo->seg_count; ++i) { uint32_t segInfoOffset = startsInfo->seg_info_offset[i]; // 0 offset means this segment has no fixups if ( segInfoOffset == 0 ) continue; const dyld_chained_starts_in_segment* segInfo = (dyld_chained_starts_in_segment*)((uint8_t*)startsInfo + segInfoOffset); if ( segInfo->size > (endOfStarts - (uint8_t*)segInfo) ) { diag.error("chained fixups, dyld_chained_starts_in_segment for segment #%d overruns imports table", i); return false; } // validate dyld_chained_starts_in_segment if ( (segInfo->page_size != 0x1000) && (segInfo->page_size != 0x4000) ) { diag.error("chained fixups, page_size not 4KB or 16KB in segment #%d", i); return false; } if ( segInfo->pointer_format > 13 ) { diag.error("chained fixups, unknown pointer_format in segment #%d", i); return false; } if ( !pointer_format_found ) { pointer_format_for_all = segInfo->pointer_format; pointer_format_found = true; } if ( segInfo->pointer_format != pointer_format_for_all) { diag.error("chained fixups, pointer_format not same for all segments %d and %d", segInfo->pointer_format, pointer_format_for_all); return false; } if ( segInfo->segment_offset != (segmentsInfo[i].vmAddr - baseAddress) ) { diag.error("chained fixups, segment_offset does not match vmaddr from LC_SEGMENT in segment #%d", i); return false; } if ( segInfo->max_valid_pointer != 0 ) { if ( maxValidPointerSeen == 0 ) { // record max_valid_pointer values seen maxValidPointerSeen = segInfo->max_valid_pointer; } else if ( maxValidPointerSeen != segInfo->max_valid_pointer ) { diag.error("chained fixups, different max_valid_pointer values seen in different segments"); return false; } } // validate starts table in segment if ( offsetof(dyld_chained_starts_in_segment, page_start[segInfo->page_count]) > segInfo->size ) { diag.error("chained fixups, page_start array overflows size"); return false; } uint32_t maxOverflowIndex = (uint32_t)(segInfo->size - offsetof(dyld_chained_starts_in_segment, page_start[0]))/sizeof(uint16_t); for (int pageIndex=0; pageIndex < segInfo->page_count; ++pageIndex) { uint16_t offsetInPage = segInfo->page_start[pageIndex]; if ( offsetInPage == DYLD_CHAINED_PTR_START_NONE ) continue; if ( (offsetInPage & DYLD_CHAINED_PTR_START_MULTI) == 0 ) { // this is the offset into the page where the first fixup is if ( offsetInPage > segInfo->page_size ) { diag.error("chained fixups, in segment #%d page_start[%d]=0x%04X exceeds page size", i, pageIndex, offsetInPage); } } else { // this is actually an index into chain_starts[] uint32_t overflowIndex = offsetInPage & ~DYLD_CHAINED_PTR_START_MULTI; // now verify all starts are within the page and in ascending order uint16_t lastOffsetInPage = 0; do { if ( overflowIndex > maxOverflowIndex ) { diag.error("chain overflow index out of range %d (max=%d) in segment %s", overflowIndex, maxOverflowIndex, segmentName(i)); return false; } offsetInPage = (segInfo->page_start[overflowIndex] & ~DYLD_CHAINED_PTR_START_LAST); if ( offsetInPage > segInfo->page_size ) { diag.error("chained fixups, in segment #%d overflow page_start[%d]=0x%04X exceeds page size", i, overflowIndex, offsetInPage); return false; } if ( (offsetInPage <= lastOffsetInPage) && (lastOffsetInPage != 0) ) { diag.error("chained fixups, in segment #%d overflow page_start[%d]=0x%04X is before previous at 0x%04X\n", i, overflowIndex, offsetInPage, lastOffsetInPage); return false; } lastOffsetInPage = offsetInPage; ++overflowIndex; } while ( (segInfo->page_start[overflowIndex] & DYLD_CHAINED_PTR_START_LAST) == 0 ); } } } // validate import table size can fit if ( chainsHeader->imports_count != 0 ) { uint32_t maxBindOrdinal = 0; switch (pointer_format_for_all) { case DYLD_CHAINED_PTR_32: maxBindOrdinal = 0x0FFFFF; // 20-bits break; case DYLD_CHAINED_PTR_ARM64E: case DYLD_CHAINED_PTR_ARM64E_USERLAND: case DYLD_CHAINED_PTR_ARM64E_OFFSET: maxBindOrdinal = 0x00FFFF; // 16-bits break; case DYLD_CHAINED_PTR_64: case DYLD_CHAINED_PTR_64_OFFSET: case DYLD_CHAINED_PTR_ARM64E_USERLAND24: maxBindOrdinal = 0xFFFFFF; // 24 bits break; } if ( chainsHeader->imports_count >= maxBindOrdinal ) { diag.error("chained fixups, imports_count (%d) exceeds max of %d", chainsHeader->imports_count, maxBindOrdinal); return false; } } // validate max_valid_pointer is larger than last segment if ( (maxValidPointerSeen != 0) && !inDyldCache() ) { uint64_t lastSegmentLastVMAddr = segmentsInfo[leInfo.layout.linkeditSegIndex-1].vmAddr + segmentsInfo[leInfo.layout.linkeditSegIndex-1].vmSize; if ( maxValidPointerSeen < lastSegmentLastVMAddr ) { diag.error("chained fixups, max_valid_pointer too small for image"); return false; } } return diag.noError(); } bool MachOAnalyzer::validChainedFixupsInfoOldArm64e(Diagnostics& diag, const char* path) const { __block uint32_t maxTargetCount = 0; __block uint32_t currentTargetCount = 0; parseOrgArm64eChainedFixups(diag, ^(uint32_t totalTargets, bool& stop) { maxTargetCount = totalTargets; }, ^(const LinkEditInfo& leInfo, const SegmentInfo segments[], bool libraryOrdinalSet, uint32_t dylibCount, int libOrdinal, uint8_t type, const char* symbolName, uint64_t addend, bool weakImport, bool& stop) { if ( symbolName == NULL ) { diag.error("in '%s' missing BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM", path); } else if ( !libraryOrdinalSet ) { diag.error("in '%s' missing BIND_OPCODE_SET_DYLIB_ORDINAL", path); } else if ( libOrdinal > (int)dylibCount ) { diag.error("in '%s' has library ordinal too large (%d) max (%d)", path, libOrdinal, dylibCount); } else if ( libOrdinal < BIND_SPECIAL_DYLIB_WEAK_LOOKUP ) { diag.error("in '%s' has unknown library special ordinal (%d)", path, libOrdinal); } else if ( type != BIND_TYPE_POINTER ) { diag.error("in '%s' unknown bind type %d", path, type); } else if ( currentTargetCount > maxTargetCount ) { diag.error("in '%s' chained target counts exceeds BIND_SUBOPCODE_THREADED_SET_BIND_ORDINAL_TABLE_SIZE_ULEB", path); } ++currentTargetCount; if ( diag.hasError() ) stop = true; }, ^(const LinkEditInfo& leInfo, const SegmentInfo segments[], uint8_t segmentIndex, bool segIndexSet, uint64_t segmentOffset, uint16_t format, bool& stop) { if ( !segIndexSet ) { diag.error("in '%s' missing BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB", path); } else if ( segmentIndex >= leInfo.layout.linkeditSegIndex ) { diag.error("in '%s' segment index %d too large", path, segmentIndex); } else if ( segmentOffset > (segments[segmentIndex].vmSize-8) ) { diag.error("in '%s' current segment offset 0x%08llX beyond segment size (0x%08llX)", path, segmentOffset, segments[segmentIndex].vmSize); } else if ( !segments[segmentIndex].writable() ) { diag.error("in '%s' pointer bind is in non-writable segment", path); } else if ( segments[segmentIndex].executable() ) { diag.error("in '%s' pointer bind is in executable segment", path); } if ( diag.hasError() ) stop = true; } ); return diag.noError(); } void MachOAnalyzer::parseOrgArm64eChainedFixups(Diagnostics& diag, void (^targetCount)(uint32_t totalTargets, bool& stop), void (^addTarget)(const LinkEditInfo& leInfo, const SegmentInfo segments[], bool libraryOrdinalSet, uint32_t dylibCount, int libOrdinal, uint8_t type, const char* symbolName, uint64_t addend, bool weakImport, bool& stop), void (^addChainStart)(const LinkEditInfo& leInfo, const SegmentInfo segments[], uint8_t segmentIndex, bool segIndexSet, uint64_t segmentOffset, uint16_t format, bool& stop)) const { bool stop = false; LinkEditInfo leInfo; getLinkEditPointers(diag, leInfo); if ( diag.hasError() ) return; BLOCK_ACCCESSIBLE_ARRAY(SegmentInfo, segmentsInfo, leInfo.layout.lastSegIndex+1); getAllSegmentsInfos(diag, segmentsInfo); if ( diag.hasError() ) return; const uint32_t dylibCount = dependentDylibCount(); if ( leInfo.dyldInfo != nullptr ) { // process bind opcodes const uint8_t* p = getLinkEditContent(leInfo.layout, leInfo.dyldInfo->bind_off); const uint8_t* end = p + leInfo.dyldInfo->bind_size; uint8_t type = 0; uint64_t segmentOffset = 0; uint8_t segmentIndex = 0; const char* symbolName = NULL; int libraryOrdinal = 0; bool segIndexSet = false; bool libraryOrdinalSet = false; uint64_t targetTableCount; uint64_t addend = 0; bool weakImport = false; while ( !stop && diag.noError() && (p < end) ) { uint8_t immediate = *p & BIND_IMMEDIATE_MASK; uint8_t opcode = *p & BIND_OPCODE_MASK; ++p; switch (opcode) { case BIND_OPCODE_DONE: stop = true; break; case BIND_OPCODE_SET_DYLIB_ORDINAL_IMM: libraryOrdinal = immediate; libraryOrdinalSet = true; break; case BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB: libraryOrdinal = (int)read_uleb128(diag, p, end); libraryOrdinalSet = true; break; case BIND_OPCODE_SET_DYLIB_SPECIAL_IMM: // the special ordinals are negative numbers if ( immediate == 0 ) libraryOrdinal = 0; else { int8_t signExtended = BIND_OPCODE_MASK | immediate; libraryOrdinal = signExtended; } libraryOrdinalSet = true; break; case BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM: weakImport = ( (immediate & BIND_SYMBOL_FLAGS_WEAK_IMPORT) != 0 ); symbolName = (char*)p; while (*p != '\0') ++p; ++p; break; case BIND_OPCODE_SET_TYPE_IMM: type = immediate; break; case BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB: segmentIndex = immediate; segmentOffset = read_uleb128(diag, p, end); segIndexSet = true; break; case BIND_OPCODE_SET_ADDEND_SLEB: addend = read_sleb128(diag, p, end); break; case BIND_OPCODE_DO_BIND: if ( addTarget ) addTarget(leInfo, segmentsInfo, libraryOrdinalSet, dylibCount, libraryOrdinal, type, symbolName, addend, weakImport, stop); break; case BIND_OPCODE_THREADED: switch (immediate) { case BIND_SUBOPCODE_THREADED_SET_BIND_ORDINAL_TABLE_SIZE_ULEB: targetTableCount = read_uleb128(diag, p, end); if ( targetTableCount > 65535 ) { diag.error("BIND_SUBOPCODE_THREADED_SET_BIND_ORDINAL_TABLE_SIZE_ULEB size too large"); stop = true; } else { if ( targetCount ) targetCount((uint32_t)targetTableCount, stop); } break; case BIND_SUBOPCODE_THREADED_APPLY: if ( addChainStart ) addChainStart(leInfo, segmentsInfo, segmentIndex, segIndexSet, segmentOffset, DYLD_CHAINED_PTR_ARM64E, stop); break; default: diag.error("bad BIND_OPCODE_THREADED sub-opcode 0x%02X", immediate); } break; default: diag.error("bad bind opcode 0x%02X", immediate); } } if ( diag.hasError() ) return; } } void MachOAnalyzer::forEachChainedFixupTarget(Diagnostics& diag, void (^callback)(int libOrdinal, const char* symbolName, uint64_t addend, bool weakImport, bool& stop)) const { LinkEditInfo leInfo; getLinkEditPointers(diag, leInfo); if ( diag.hasError() ) return; BLOCK_ACCCESSIBLE_ARRAY(SegmentInfo, segmentsInfo, leInfo.layout.lastSegIndex+1); getAllSegmentsInfos(diag, segmentsInfo); if ( diag.hasError() ) return; if ( leInfo.dyldInfo != nullptr ) { parseOrgArm64eChainedFixups(diag, nullptr, ^(const LinkEditInfo& leInfo2, const SegmentInfo segments[], bool libraryOrdinalSet, uint32_t dylibCount, int libOrdinal, uint8_t type, const char* symbolName, uint64_t fixAddend, bool weakImport, bool& stopChain) { callback(libOrdinal, symbolName, fixAddend, weakImport, stopChain); }, nullptr); } else if ( leInfo.chainedFixups != nullptr ) { const dyld_chained_fixups_header* header = (dyld_chained_fixups_header*)getLinkEditContent(leInfo.layout, leInfo.chainedFixups->dataoff); MachOFile::forEachChainedFixupTarget(diag, header, leInfo.chainedFixups, callback); } } bool MachOAnalyzer::hasProgramVars(uint32_t& progVarsOffset, bool& crtRunsInitializers, DyldLookFunc*& dyldLookupFuncAddr) const { crtRunsInitializers = false; if ( this->filetype != MH_EXECUTE ) return false; // macOS 10.8+ program uses LC_MAIN and ProgramVars are in libdyld.dylib // macOS 10.6 -> 10.7 ProgramVars are in __program_vars section in main executable // macOS 10.5 ProgramVars are in __dyld section in main executable and 7 pointers in size // macOS 10.4 and earlier ProgramVars need to be looked up by name in nlist of main executable uint64_t offset; bool usesCRT; if ( getEntry(offset, usesCRT) && usesCRT ) { // is pre-10.8 program uint64_t sectionSize; if ( const void* progVarsSection = findSectionContent("__DATA", "__program_vars", sectionSize) ) { // macOS 10.6 or 10.7 binary progVarsOffset = (uint32_t)((uint8_t*)progVarsSection - (uint8_t*)this); return true; } else if ( const void* dyldSection = findSectionContent("__DATA", "__dyld", sectionSize) ) { #if SUPPPORT_PRE_LC_MAIN if ( sectionSize >= 2*pointerSize() ) { dyldLookupFuncAddr = (DyldLookFunc*)((uint8_t*)dyldSection + pointerSize()); } #endif if ( sectionSize >= 7*pointerSize() ) { // macOS 10.5 binary progVarsOffset = (uint32_t)((uint8_t*)dyldSection - (uint8_t*)this) + 2*pointerSize(); return true; } else { // macOS 10.4 binary crtRunsInitializers = true; } } return false; } return false; } // Convert from a (possibly) live pointer to a vmAddr uint64_t MachOAnalyzer::VMAddrConverter::convertToVMAddr(uint64_t value, const Array<uint64_t>& bindTargets) const { if ( contentRebased ) { if ( value == 0 ) return 0; // The value may have been signed. Strip the signature if that is the case #if __has_feature(ptrauth_calls) value = (uint64_t)__builtin_ptrauth_strip((void*)value, ptrauth_key_asia); #endif value -= slide; return value; } if ( chainedPointerFormat != 0 ) { // We try to only use the VMAddrConverter on locations which are pointers, but we don't know // for sure if the location contains a rebase or not. Eg, it can be called on a NULL Protocol ISA field. // If we see a 0, then its extremely likely that this is not a rebase, as we only use VMAddrConverter // for initializers, terminators, and objc. None of those have any reason to point to offset 0 in the binary, // ie, no reason to point to the mach_header if ( value == 0 ) return 0; auto* chainedValue = (MachOAnalyzer::ChainedFixupPointerOnDisk*)&value; uint64_t targetRuntimeOffset; if ( chainedValue->isRebase(chainedPointerFormat, preferredLoadAddress, targetRuntimeOffset) ) { value = preferredLoadAddress + targetRuntimeOffset; } #if !BUILDING_DYLD // Patchable objc classes use binds to self. Support them in offline tools uint32_t bindOrdinal = 0; int64_t addend = 0; if ( !bindTargets.empty() && chainedValue->isBind(chainedPointerFormat, bindOrdinal, addend)) value = bindTargets[bindOrdinal] + addend; #endif return value; } #if !(BUILDING_LIBDYLD || BUILDING_DYLD) typedef MachOAnalyzer::VMAddrConverter VMAddrConverter; if ( sharedCacheChainedPointerFormat != VMAddrConverter::SharedCacheFormat::none ) { switch ( sharedCacheChainedPointerFormat ) { case VMAddrConverter::SharedCacheFormat::none: assert(false); case VMAddrConverter::SharedCacheFormat::v1: { // Nothing to do here. We don't have chained fixup bits to remove, or a value_add to apply break; } case VMAddrConverter::SharedCacheFormat::v2_x86_64_tbi: { const uint64_t deltaMask = 0x00FFFF0000000000; const uint64_t valueMask = ~deltaMask; const uint64_t valueAdd = preferredLoadAddress; value = (value & valueMask); if ( value != 0 ) { value += valueAdd; } break; } case VMAddrConverter::SharedCacheFormat::v3: { // Just use the chained pointer format for arm64e auto* chainedValue = (MachOAnalyzer::ChainedFixupPointerOnDisk*)&value; uint64_t targetRuntimeOffset; if ( chainedValue->isRebase(DYLD_CHAINED_PTR_ARM64E, preferredLoadAddress, targetRuntimeOffset) ) { value = preferredLoadAddress + targetRuntimeOffset; } break; } case VMAddrConverter::SharedCacheFormat::v4: { const uint64_t deltaMask = 0x00000000C0000000; const uint64_t valueMask = ~deltaMask; const uint64_t valueAdd = preferredLoadAddress; value = (value & valueMask); if ( value != 0 ) { value += valueAdd; } break; } case VMAddrConverter::SharedCacheFormat::v5: { // Just use the chained pointer format for arm64e if ( value == 0 ) return 0; auto* chainedValue = (MachOAnalyzer::ChainedFixupPointerOnDisk*)&value; uint64_t targetRuntimeOffset; if ( chainedValue->isRebase(DYLD_CHAINED_PTR_ARM64E_SHARED_CACHE, preferredLoadAddress, targetRuntimeOffset) ) { value = preferredLoadAddress + targetRuntimeOffset; } break; } } return value; } #endif return value; } uint64_t MachOAnalyzer::VMAddrConverter::convertToVMAddr(uint64_t v) const { return this->convertToVMAddr(v, {}); } MachOAnalyzer::VMAddrConverter MachOAnalyzer::makeVMAddrConverter(bool contentRebased) const { MachOAnalyzer::VMAddrConverter vmAddrConverter; vmAddrConverter.preferredLoadAddress = preferredLoadAddress(); vmAddrConverter.slide = getSlide(); vmAddrConverter.chainedPointerFormat = hasChainedFixups() ? chainedPointerFormat() : 0; vmAddrConverter.contentRebased = contentRebased; return vmAddrConverter; } struct VIS_HIDDEN SegmentRanges { struct SegmentRange { uint64_t vmAddrStart; uint64_t vmAddrEnd; uint32_t fileSize; }; bool contains(uint64_t vmAddr) const { for (const SegmentRange& range : segments) { if ( (range.vmAddrStart <= vmAddr) && (vmAddr < range.vmAddrEnd) ) return true; } return false; } private: SegmentRange localAlloc[1]; public: dyld3::OverflowSafeArray<SegmentRange> segments { localAlloc, sizeof(localAlloc) / sizeof(localAlloc[0]) }; }; void MachOAnalyzer::forEachInitializer(Diagnostics& diag, const VMAddrConverter& vmAddrConverter, void (^callback)(uint32_t offset), const void* dyldCache) const { __block SegmentRanges executableSegments; forEachSegment(^(const SegmentInfo& info, bool& stop) { if ( (info.protections & VM_PROT_EXECUTE) != 0 ) { executableSegments.segments.push_back({ info.vmAddr, info.vmAddr + info.vmSize, (uint32_t)info.fileSize }); } }); if (executableSegments.segments.empty()) { diag.error("no exeutable segments"); return; } uint64_t loadAddress = preferredLoadAddress(); intptr_t slide = getSlide(); // if dylib linked with -init linker option, that initializer is first forEachLoadCommand(diag, ^(const load_command* cmd, bool& stop) { if ( cmd->cmd == LC_ROUTINES ) { const routines_command* routines = (routines_command*)cmd; uint64_t dashInit = routines->init_address; if ( executableSegments.contains(dashInit) ) callback((uint32_t)(dashInit - loadAddress)); else diag.error("-init does not point within __TEXT segment"); } else if ( cmd->cmd == LC_ROUTINES_64 ) { const routines_command_64* routines = (routines_command_64*)cmd; uint64_t dashInit = routines->init_address; if ( executableSegments.contains(dashInit) ) callback((uint32_t)(dashInit - loadAddress)); else diag.error("-init does not point within __TEXT segment"); } }); // next any function pointers in mod-init section const unsigned ptrSize = pointerSize(); forEachInitializerPointerSection(diag, ^(uint32_t sectionOffset, uint32_t sectionSize, bool& stop) { const uint8_t* content = (uint8_t*)this + sectionOffset; if ( ptrSize == 8 ) { const uint64_t* initsStart = (uint64_t*)content; const uint64_t* initsEnd = (uint64_t*)((uint8_t*)content + sectionSize); for (const uint64_t* p=initsStart; p < initsEnd; ++p) { uint64_t anInit = vmAddrConverter.convertToVMAddr(*p); if ( !executableSegments.contains(anInit) ) { diag.error("initializer 0x%0llX does not point within executable segment", anInit); stop = true; break; } callback((uint32_t)(anInit - loadAddress)); } } else { const uint32_t* initsStart = (uint32_t*)content; const uint32_t* initsEnd = (uint32_t*)((uint8_t*)content + sectionSize); for (const uint32_t* p=initsStart; p < initsEnd; ++p) { uint32_t anInit = (uint32_t)vmAddrConverter.convertToVMAddr(*p); if ( !executableSegments.contains(anInit) ) { diag.error("initializer 0x%0X does not point within executable segment", anInit); stop = true; break; } callback(anInit - (uint32_t)loadAddress); } } }); forEachSection(^(const SectionInfo& info, bool malformedSectionRange, bool& stop) { if ( (info.sectFlags & SECTION_TYPE) != S_INIT_FUNC_OFFSETS ) return; const uint8_t* content = (uint8_t*)(info.sectAddr + slide); if ( info.segInfo.writable() ) { diag.error("initializer offsets section %s/%s must be in read-only segment", info.segInfo.segName, info.sectName); stop = true; return; } if ( (info.sectSize % 4) != 0 ) { diag.error("initializer offsets section %s/%s has bad size", info.segInfo.segName, info.sectName); stop = true; return; } if ( malformedSectionRange ) { diag.error("initializer offsets section %s/%s extends beyond the end of the segment", info.segInfo.segName, info.sectName); stop = true; return; } if ( (info.sectAddr % 4) != 0 ) { diag.error("initializer offsets section %s/%s is not 4-byte aligned", info.segInfo.segName, info.sectName); stop = true; return; } const uint32_t* initsStart = (uint32_t*)content; const uint32_t* initsEnd = (uint32_t*)((uint8_t*)content + info.sectSize); for (const uint32_t* p=initsStart; p < initsEnd; ++p) { uint32_t anInitOffset = *p; if ( !executableSegments.contains(loadAddress + anInitOffset) ) { diag.error("initializer 0x%08X is not an offset to an executable segment", anInitOffset); stop = true; break; } callback(anInitOffset); } }); } bool MachOAnalyzer::hasTerminators(Diagnostics& diag, const VMAddrConverter& vmAddrConverter) const { __block bool result = false; forEachTerminator(diag, vmAddrConverter, ^(uint32_t offset) { result = true; }); return result; } void MachOAnalyzer::forEachTerminator(Diagnostics& diag, const VMAddrConverter& vmAddrConverter, void (^callback)(uint32_t offset)) const { __block SegmentRanges executableSegments; forEachSegment(^(const SegmentInfo& info, bool& stop) { if ( (info.protections & VM_PROT_EXECUTE) != 0 ) { executableSegments.segments.push_back({ info.vmAddr, info.vmAddr + info.vmSize, (uint32_t)info.fileSize }); } }); if (executableSegments.segments.empty()) { diag.error("no exeutable segments"); return; } uint64_t loadAddress = preferredLoadAddress(); intptr_t slide = getSlide(); // next any function pointers in mod-term section const unsigned ptrSize = pointerSize(); forEachSection(^(const SectionInfo& info, bool malformedSectionRange, bool& stop) { if ( (info.sectFlags & SECTION_TYPE) == S_MOD_TERM_FUNC_POINTERS ) { const uint8_t* content; content = (uint8_t*)(info.sectAddr + slide); if ( (info.sectSize % ptrSize) != 0 ) { diag.error("terminator section %s/%s has bad size", info.segInfo.segName, info.sectName); stop = true; return; } if ( malformedSectionRange ) { diag.error("terminator section %s/%s extends beyond its segment", info.segInfo.segName, info.sectName); stop = true; return; } if ( ((long)content % ptrSize) != 0 ) { diag.error("terminator section %s/%s is not pointer aligned", info.segInfo.segName, info.sectName); stop = true; return; } if ( ptrSize == 8 ) { const uint64_t* initsStart = (uint64_t*)content; const uint64_t* initsEnd = (uint64_t*)((uint8_t*)content + info.sectSize); for (const uint64_t* p=initsStart; p < initsEnd; ++p) { uint64_t rawContent = *p; #if __has_feature(ptrauth_calls) rawContent = (uint64_t)__builtin_ptrauth_strip((void*)rawContent, ptrauth_key_asia); #endif uint64_t anInit = vmAddrConverter.convertToVMAddr(rawContent); if ( !executableSegments.contains(anInit) ) { diag.error("terminator 0x%0llX does not point within executable segment", anInit); stop = true; break; } callback((uint32_t)(anInit - loadAddress)); } } else { const uint32_t* initsStart = (uint32_t*)content; const uint32_t* initsEnd = (uint32_t*)((uint8_t*)content + info.sectSize); for (const uint32_t* p=initsStart; p < initsEnd; ++p) { uint32_t anInit = (uint32_t)vmAddrConverter.convertToVMAddr(*p); if ( !executableSegments.contains(anInit) ) { diag.error("terminator 0x%0X does not point within executable segment", anInit); stop = true; break; } callback(anInit - (uint32_t)loadAddress); } } } }); } bool MachOAnalyzer::hasSwiftOrObjC(bool* hasSwift) const { struct objc_image_info { int32_t version; uint32_t flags; }; if ( hasSwift != nullptr ) *hasSwift = false; uintptr_t slide = getSlide(); __block bool result = false; forEachSection(^(const SectionInfo& sectInfo, bool malformedSectionRange, bool& stop) { if ( (strcmp(sectInfo.sectName, "__objc_imageinfo") == 0) && (strncmp(sectInfo.segInfo.segName, "__DATA", 6) == 0) ) { if ( hasSwift != nullptr ) { objc_image_info* info = (objc_image_info*)((uintptr_t)sectInfo.sectAddr + slide); uint32_t swiftVersion = ((info->flags >> 8) & 0xFF); if ( swiftVersion ) *hasSwift = true; } result = true; stop = true; } if ( (this->cputype == CPU_TYPE_I386) && (strcmp(sectInfo.sectName, "__image_info") == 0) && (strcmp(sectInfo.segInfo.segName, "__OBJC") == 0) ) { result = true; stop = true; } }); return result; } bool MachOAnalyzer::hasSwift() const { bool hasSwift = false; this->hasSwiftOrObjC(&hasSwift); return hasSwift; } bool MachOAnalyzer::usesObjCGarbageCollection() const { __block bool result = false; forEachSection(^(const SectionInfo& info, bool malformedSectionRange, bool& stop) { if ( (strcmp(info.sectName, "__objc_imageinfo") == 0) && (strncmp(info.segInfo.segName, "__DATA", 6) == 0) ) { const uint64_t slide = (uint64_t)this - preferredLoadAddress(); const uint32_t* flags = (uint32_t*)(info.sectAddr + slide); if ( flags[1] & 4 ) result = true; stop = true; } }); return result; } bool MachOAnalyzer::hasPlusLoadMethod(Diagnostics& diag) const { __block bool result = false; if ( (this->cputype == CPU_TYPE_I386) && this->builtForPlatform(Platform::macOS) ) { // old objc runtime has no special section for +load methods, scan for string uintptr_t slide = getSlide(); forEachSection(^(const SectionInfo& info, bool malformedSectionRange, bool& stop) { if ( ( (info.sectFlags & SECTION_TYPE) == S_CSTRING_LITERALS ) ) { if ( malformedSectionRange ) { diag.error("cstring section %s/%s extends beyond the end of the segment", info.segInfo.segName, info.sectName); stop = true; return; } const uint8_t* content = (uint8_t*)((uintptr_t)info.sectAddr + slide); const char* s = (char*)content; const char* end = s + info.sectSize; while ( s < end ) { if ( strcmp(s, "load") == 0 ) { result = true; stop = true; return; } while (*s != '\0' ) ++s; ++s; } } }); return result; } return MachOFile::hasPlusLoadMethod(diag); } const void* MachOAnalyzer::getRebaseOpcodes(uint32_t& size) const { Diagnostics diag; LinkEditInfo leInfo; getLinkEditPointers(diag, leInfo); if ( diag.hasError() || (leInfo.dyldInfo == nullptr) ) return nullptr; size = leInfo.dyldInfo->rebase_size; return getLinkEditContent(leInfo.layout, leInfo.dyldInfo->rebase_off); } const void* MachOAnalyzer::getBindOpcodes(uint32_t& size) const { Diagnostics diag; LinkEditInfo leInfo; getLinkEditPointers(diag, leInfo); if ( diag.hasError() || (leInfo.dyldInfo == nullptr) ) return nullptr; size = leInfo.dyldInfo->bind_size; return getLinkEditContent(leInfo.layout, leInfo.dyldInfo->bind_off); } const void* MachOAnalyzer::getLazyBindOpcodes(uint32_t& size) const { Diagnostics diag; LinkEditInfo leInfo; getLinkEditPointers(diag, leInfo); if ( diag.hasError() || (leInfo.dyldInfo == nullptr) ) return nullptr; size = leInfo.dyldInfo->lazy_bind_size; return getLinkEditContent(leInfo.layout, leInfo.dyldInfo->lazy_bind_off); } const void* MachOAnalyzer::getSplitSeg(uint32_t& size) const { Diagnostics diag; LinkEditInfo leInfo; getLinkEditPointers(diag, leInfo); if ( diag.hasError() || (leInfo.splitSegInfo == nullptr) ) return nullptr; size = leInfo.splitSegInfo->datasize; return getLinkEditContent(leInfo.layout, leInfo.splitSegInfo->dataoff); } bool MachOAnalyzer::hasSplitSeg() const { uint32_t splitSegSize = 0; const void* splitSegStart = getSplitSeg(splitSegSize); return splitSegStart != nullptr; } bool MachOAnalyzer::isSplitSegV1() const { uint32_t splitSegSize = 0; const void* splitSegStart = getSplitSeg(splitSegSize); if (!splitSegStart) return false; return (*(const uint8_t*)splitSegStart) != DYLD_CACHE_ADJ_V2_FORMAT; } bool MachOAnalyzer::isSplitSegV2() const { uint32_t splitSegSize = 0; const void* splitSegStart = getSplitSeg(splitSegSize); if (!splitSegStart) return false; return (*(const uint8_t*)splitSegStart) == DYLD_CACHE_ADJ_V2_FORMAT; } uint64_t MachOAnalyzer::segAndOffsetToRuntimeOffset(uint8_t targetSegIndex, uint64_t targetSegOffset) const { __block uint64_t textVmAddr = 0; __block uint64_t result = 0; forEachSegment(^(const SegmentInfo& info, bool& stop) { if ( strcmp(info.segName, "__TEXT") == 0 ) textVmAddr = info.vmAddr; if ( info.segIndex == targetSegIndex ) { result = (info.vmAddr - textVmAddr) + targetSegOffset; } }); return result; } bool MachOAnalyzer::hasLazyPointers(uint32_t& runtimeOffset, uint32_t& size) const { size = 0; forEachSection(^(const dyld3::MachOAnalyzer::SectionInfo& info, bool malformedSectionRange, bool &stop) { if ( (info.sectFlags & SECTION_TYPE) == S_LAZY_SYMBOL_POINTERS ) { runtimeOffset = (uint32_t)(info.sectAddr - preferredLoadAddress()); size = (uint32_t)info.sectSize; stop = true; } }); return (size != 0); } #if !TARGET_OS_EXCLAVEKIT void MachOAnalyzer::forEachCDHash(void (^handler)(const uint8_t cdHash[20])) const { Diagnostics diag; LinkEditInfo leInfo; getLinkEditPointers(diag, leInfo); if ( diag.hasError() || (leInfo.codeSig == nullptr) ) return; forEachCDHashOfCodeSignature(getLinkEditContent(leInfo.layout, leInfo.codeSig->dataoff), leInfo.codeSig->datasize, handler); } bool MachOAnalyzer::usesLibraryValidation() const { Diagnostics diag; LinkEditInfo leInfo; getLinkEditPointers(diag, leInfo); if ( diag.hasError() || (leInfo.codeSig == nullptr) ) return false; // check for CS_REQUIRE_LV in CS_CodeDirectory.flags __block bool requiresLV = false; forEachCodeDirectoryBlob(getLinkEditContent(leInfo.layout, leInfo.codeSig->dataoff), leInfo.codeSig->datasize, ^(const void *cdBuffer) { const CS_CodeDirectory* cd = (const CS_CodeDirectory*)cdBuffer; requiresLV |= (htonl(cd->flags) & CS_REQUIRE_LV); }); return requiresLV; } #endif // !TARGET_OS_EXCLAVEKIT bool MachOAnalyzer::canHavePrecomputedDlopenClosure(const char* path, void (^failureReason)(const char*)) const { if (!MachOFile::canHavePrecomputedDlopenClosure(path, failureReason)) return false; // prebuilt closures use the cdhash of the dylib to verify that the dylib is still the same // at runtime as when the shared cache processed it. We must have a code signature to record this information uint32_t codeSigFileOffset; uint32_t codeSigSize; if ( !hasCodeSignature(codeSigFileOffset, codeSigSize) ) { failureReason("no code signature"); return false; } __block bool retval = true; // images that use dynamic_lookup, bundle_loader, or have weak-defs cannot have dlopen closure pre-computed Diagnostics diag; auto checkBind = ^(int libOrdinal, bool& stop) { switch (libOrdinal) { case BIND_SPECIAL_DYLIB_WEAK_LOOKUP: failureReason("has weak externals"); retval = false; stop = true; break; case BIND_SPECIAL_DYLIB_FLAT_LOOKUP: failureReason("has dynamic_lookup binds"); retval = false; stop = true; break; case BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE: failureReason("has reference to main executable (bundle loader)"); retval = false; stop = true; break; } }; if (hasChainedFixups()) { forEachChainedFixupTarget(diag, ^(int libOrdinal, const char *symbolName, uint64_t addend, bool weakImport, bool &stop) { checkBind(libOrdinal, stop); }); } else { forEachBind(diag, ^(uint64_t runtimeOffset, int libOrdinal, const char* symbolName, bool weakImport, bool lazyBind, uint64_t addend, bool& stop) { checkBind(libOrdinal, stop); }, ^(const char* symbolName) { }); } return retval; } bool MachOAnalyzer::hasUnalignedPointerFixups() const { // only look at 64-bit architectures if ( pointerSize() == 4 ) return false; __block Diagnostics diag; __block bool result = false; if ( hasChainedFixups() ) { withChainStarts(diag, chainStartsOffset(), ^(const dyld_chained_starts_in_image* startsInfo) { forEachFixupInAllChains(diag, startsInfo, false, ^(MachOLoaded::ChainedFixupPointerOnDisk* fixupLoc, const dyld_chained_starts_in_segment* segInfo, bool& fixupsStop) { if ( ((long)(fixupLoc) & 7) != 0 ) { result = true; fixupsStop = true; } }); }); } else { forEachBind(diag, ^(uint64_t runtimeOffset, int libOrdinal, const char* symbolName, bool weakImport, bool lazyBind, uint64_t addend, bool& stop) { if ( (runtimeOffset & 7) != 0 ) { result = true; stop = true; } }, ^(const char* symbolName) { }); forEachRebase(diag, true, ^(uint64_t runtimeOffset, bool& stop) { if ( (runtimeOffset & 7) != 0 ) { result = true; stop = true; } }); } return result; } void MachOAnalyzer::recurseTrie(Diagnostics& diag, const uint8_t* const start, const uint8_t* p, const uint8_t* const end, OverflowSafeArray<char>& cummulativeString, int curStrOffset, bool& stop, ExportsCallback callback) const { if ( p >= end ) { diag.error("malformed trie, node past end"); return; } const uint64_t terminalSize = read_uleb128(diag, p, end); const uint8_t* children = p + terminalSize; if ( terminalSize != 0 ) { uint64_t imageOffset = 0; uint64_t flags = read_uleb128(diag, p, end); uint64_t other = 0; const char* importName = nullptr; if ( flags & EXPORT_SYMBOL_FLAGS_REEXPORT ) { other = read_uleb128(diag, p, end); // dylib ordinal importName = (char*)p; } else { imageOffset = read_uleb128(diag, p, end); if ( flags & EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER ) other = read_uleb128(diag, p, end); else other = 0; } if ( diag.hasError() ) return; callback(cummulativeString.begin(), imageOffset, flags, other, importName, stop); if ( stop ) return; } if ( children > end ) { diag.error("malformed trie, terminalSize extends beyond trie data"); return; } const uint8_t childrenCount = *children++; const uint8_t* s = children; for (uint8_t i=0; i < childrenCount; ++i) { int edgeStrLen = 0; while (*s != '\0') { cummulativeString.resize(curStrOffset+edgeStrLen + 1); cummulativeString[curStrOffset+edgeStrLen] = *s++; ++edgeStrLen; if ( s > end ) { diag.error("malformed trie node, child node extends past end of trie\n"); return; } } cummulativeString.resize(curStrOffset+edgeStrLen + 1); cummulativeString[curStrOffset+edgeStrLen] = *s++; uint64_t childNodeOffset = read_uleb128(diag, s, end); if (childNodeOffset == 0) { diag.error("malformed trie, childNodeOffset==0"); return; } recurseTrie(diag, start, start+childNodeOffset, end, cummulativeString, curStrOffset+edgeStrLen, stop, callback); if ( diag.hasError() || stop ) return; } } void MachOAnalyzer::forEachExportedSymbol(Diagnostics& diag, ExportsCallback callback) const { LinkEditInfo leInfo; getLinkEditPointers(diag, leInfo); if ( diag.hasError() ) return; uint64_t trieSize; if ( const uint8_t* trieStart = getExportsTrie(leInfo, trieSize) ) { const uint8_t* trieEnd = trieStart + trieSize; // We still emit empty export trie load commands just as a placeholder to show we have // no exports. In that case, don't start recursing as we'll immediately think we ran // of the end of the buffer if ( trieSize == 0 ) return; bool stop = false; STACK_ALLOC_OVERFLOW_SAFE_ARRAY(char, cummulativeString, 4096); recurseTrie(diag, trieStart, trieStart, trieEnd, cummulativeString, 0, stop, callback); } } bool MachOAnalyzer::neverUnload() const { bool hasSwift = false; if ( this->hasSwiftOrObjC(&hasSwift) ) { // Policy: images with ObjC or Swift are never unloaded // except MH_BUNDLE *without* Swift can be unloaded if ( hasSwift || !this->isBundle() ) { return true; } } if ( this->hasThreadLocalVariables() ) { return true; } else { // record if image has DOF sections __block bool hasDOFs = false; Diagnostics diag; this->forEachDOFSection(diag, ^(uint32_t offset) { hasDOFs = true; }); if ( diag.noError() && hasDOFs ) return true; } return false; } #if BUILDING_APP_CACHE_UTIL bool MachOAnalyzer::canBePlacedInKernelCollection(const char* path, void (^failureReason)(const char*)) const { if (!MachOFile::canBePlacedInKernelCollection(path, failureReason)) return false; // App caches reguire that everything be built with split seg v2 // This is because v1 can't move anything other than __TEXT and __DATA // but kernels have __TEXT_EXEC and other segments if ( isKextBundle() ) { // x86_64 kext's might not have split seg if ( !isArch("x86_64") && !isArch("x86_64h") ) { if ( !isSplitSegV2() ) { failureReason("Missing split seg v2"); return false; } } } else if ( isStaticExecutable() ) { // The kernel must always have split seg V2 if ( !isSplitSegV2() ) { failureReason("Missing split seg v2"); return false; } // The kernel should have __TEXT and __TEXT_EXEC __block bool foundText = false; __block bool foundTextExec = false; __block bool foundHIB = false; __block uint64_t hibernateVMAddr = 0; __block uint64_t hibernateVMSize = 0; forEachSegment(^(const SegmentInfo &segmentInfo, bool &stop) { if ( strcmp(segmentInfo.segName, "__TEXT") == 0 ) { foundText = true; } if ( strcmp(segmentInfo.segName, "__TEXT_EXEC") == 0 ) { foundTextExec = true; } if ( strcmp(segmentInfo.segName, "__HIB") == 0 ) { foundHIB = true; hibernateVMAddr = segmentInfo.vmAddr; hibernateVMSize = segmentInfo.vmSize; } }); if (!foundText) { failureReason("Expected __TEXT segment"); return false; } if ( foundTextExec && foundHIB ) { failureReason("Expected __TEXT_EXEC or __HIB segment, but found both"); return false; } if ( !foundTextExec && !foundHIB ) { failureReason("Expected __TEXT_EXEC or __HIB segment, but found neither"); return false; } // The hibernate segment should be mapped before the base address if ( foundHIB ) { uint64_t baseAddress = preferredLoadAddress(); if ( greaterThanAddOrOverflow(hibernateVMAddr, hibernateVMSize, baseAddress) ) { failureReason("__HIB segment should be mapped before base address"); return false; } } } // Don't allow kext's to have load addresses if ( isKextBundle() && (preferredLoadAddress() != 0) ) { failureReason("Has load address"); return false; } // All kexts with an executable must have a kmod_info if ( isKextBundle() ) { __block bool found = false; __block Diagnostics diag; // Check for a global first FoundSymbol foundInfo; found = findExportedSymbol(diag, "_kmod_info", true, foundInfo, nullptr); if ( !found ) { // And fall back to a local if we need to forEachLocalSymbol(diag, ^(const char* aSymbolName, uint64_t n_value, uint8_t n_type, uint8_t n_sect, uint16_t n_desc, bool& stop) { if ( strcmp(aSymbolName, "_kmod_info") == 0 ) { found = true; stop = true; } }); } if ( !found ) { failureReason("kexts must have a _kmod_info symbol"); return false; } } if (hasChainedFixups()) { if ( usesClassicRelocationsInKernelCollection() ) { failureReason("Cannot use fixup chains with binary expecting classic relocations"); return false; } __block bool fixupsOk = true; __block Diagnostics diag; withChainStarts(diag, 0, ^(const dyld_chained_starts_in_image* starts) { forEachFixupInAllChains(diag, starts, false, ^(dyld3::MachOLoaded::ChainedFixupPointerOnDisk* fixupLoc, const dyld_chained_starts_in_segment* segInfo, bool& stop) { // We only support inputs from a few pointer format types, so that we don't need to handle them all later switch (segInfo->pointer_format) { case DYLD_CHAINED_PTR_ARM64E: case DYLD_CHAINED_PTR_64: case DYLD_CHAINED_PTR_32: case DYLD_CHAINED_PTR_32_CACHE: case DYLD_CHAINED_PTR_32_FIRMWARE: failureReason("unsupported chained fixups pointer format"); fixupsOk = false; stop = true; return; case DYLD_CHAINED_PTR_64_OFFSET: // arm64 kernel and kexts use this format break; case DYLD_CHAINED_PTR_ARM64E_KERNEL: // arm64e kexts use this format break; case DYLD_CHAINED_PTR_64_KERNEL_CACHE: case DYLD_CHAINED_PTR_X86_64_KERNEL_CACHE: failureReason("unsupported chained fixups pointer format"); fixupsOk = false; stop = true; return; default: failureReason("unknown chained fixups pointer format"); fixupsOk = false; stop = true; return; } uint64_t vmOffset = (uint8_t*)fixupLoc - (uint8_t*)this; // Error if the fixup location is anything other than 4/8 byte aligned if ( (vmOffset & 0x3) != 0 ) { failureReason("fixup value is not 4-byte aligned"); fixupsOk = false; stop = true; return; } // We also must only need 30-bits for the chain format of the resulting cache if ( vmOffset >= (1 << 30) ) { failureReason("fixup value does not fit in 30-bits"); fixupsOk = false; stop = true; return; } }); }); if (!fixupsOk) return false; } else { // x86_64 xnu will have unaligned text/data fixups and fixups inside __HIB __text. // We allow these as xnu is emitted with classic relocations bool canHaveUnalignedFixups = usesClassicRelocationsInKernelCollection(); canHaveUnalignedFixups |= ( isArch("x86_64") || isArch("x86_64h") ); __block bool rebasesOk = true; Diagnostics diag; forEachRebase(diag, false, ^(uint64_t runtimeOffset, bool &stop) { // Error if the rebase location is anything other than 4/8 byte aligned if ( !canHaveUnalignedFixups && ((runtimeOffset & 0x3) != 0) ) { failureReason("rebase value is not 4-byte aligned"); rebasesOk = false; stop = true; return; } #if BUILDING_APP_CACHE_UTIL // xnu for x86_64 has __HIB mapped before __DATA, so offsets appear to be // negative. Adjust the fixups so that we don't think they are out of // range of the number of bits we have if ( isStaticExecutable() ) { __block uint64_t baseAddress = ~0ULL; forEachSegment(^(const SegmentInfo& sinfo, bool& segStop) { baseAddress = std::min(baseAddress, sinfo.vmAddr); }); uint64_t textSegVMAddr = preferredLoadAddress(); runtimeOffset = (textSegVMAddr + runtimeOffset) - baseAddress; } #endif // We also must only need 30-bits for the chain format of the resulting cache if ( runtimeOffset >= (1 << 30) ) { failureReason("rebase value does not fit in 30-bits"); rebasesOk = false; stop = true; return; } }); if (!rebasesOk) return false; __block bool bindsOk = true; forEachBind(diag, ^(uint64_t runtimeOffset, int libOrdinal, uint8_t type, const char *symbolName, bool weakImport, bool lazyBind, uint64_t addend, bool &stop) { // Don't validate branch fixups as we'll turn then in to direct jumps instead if ( type == BIND_TYPE_TEXT_PCREL32 ) return; // Error if the bind location is anything other than 4/8 byte aligned if ( !canHaveUnalignedFixups && ((runtimeOffset & 0x3) != 0) ) { failureReason("bind value is not 4-byte aligned"); bindsOk = false; stop = true; return; } // We also must only need 30-bits for the chain format of the resulting cache if ( runtimeOffset >= (1 << 30) ) { failureReason("bind value does not fit in 30-bits"); rebasesOk = false; stop = true; return; } }, ^(const char *symbolName) { }); if (!bindsOk) return false; } return true; } #endif uint64_t MachOAnalyzer::chainStartsOffset() const { const dyld_chained_fixups_header* header = chainedFixupsHeader(); // old arm64e binary has no dyld_chained_fixups_header if ( header == nullptr ) return 0; return header->starts_offset + ((uint8_t*)header - (uint8_t*)this); } const dyld_chained_fixups_header* MachOAnalyzer::chainedFixupsHeader() const { Diagnostics diag; LinkEditInfo leInfo; getLinkEditPointers(diag, leInfo); if ( diag.hasError() || (leInfo.chainedFixups == nullptr) ) return nullptr; return (dyld_chained_fixups_header*)getLinkEditContent(leInfo.layout, leInfo.chainedFixups->dataoff); } uint16_t MachOAnalyzer::chainedPointerFormat() const { const dyld_chained_fixups_header* header = chainedFixupsHeader(); if ( header != nullptr ) { // get pointer format from chain info struct in LINKEDIT return MachOFile::chainedPointerFormat(header); } assert(this->cputype == CPU_TYPE_ARM64 && (this->maskedCpuSubtype() == CPU_SUBTYPE_ARM64E) && "chainedPointerFormat() called on non-chained binary"); return DYLD_CHAINED_PTR_ARM64E; } #if (BUILDING_DYLD || BUILDING_LIBDYLD) && !__arm64e__ #define SUPPORT_OLD_ARM64E_FORMAT 0 #else #define SUPPORT_OLD_ARM64E_FORMAT 1 #endif // find dyld_chained_starts_in_image* in image // if old arm64e binary, synthesize dyld_chained_starts_in_image* void MachOAnalyzer::withChainStarts(Diagnostics& diag, uint64_t startsStructOffsetHint, void (^callback)(const dyld_chained_starts_in_image*)) const { if ( startsStructOffsetHint != 0 ) { // we have a pre-computed offset into LINKEDIT for dyld_chained_starts_in_image callback((dyld_chained_starts_in_image*)((uint8_t*)this + startsStructOffsetHint)); return; } LinkEditInfo leInfo; getLinkEditPointers(diag, leInfo); if ( diag.hasError() ) return; if ( leInfo.chainedFixups != nullptr ) { // find dyld_chained_starts_in_image from dyld_chained_fixups_header const dyld_chained_fixups_header* header = (dyld_chained_fixups_header*)getLinkEditContent(leInfo.layout, leInfo.chainedFixups->dataoff); callback((dyld_chained_starts_in_image*)((uint8_t*)header + header->starts_offset)); } #if SUPPORT_OLD_ARM64E_FORMAT // don't want this code in non-arm64e dyld because it causes a stack protector which dereferences a GOT pointer before GOT is set up else if ( (leInfo.dyldInfo != nullptr) && (this->cputype == CPU_TYPE_ARM64) && (this->maskedCpuSubtype() == CPU_SUBTYPE_ARM64E) ) { // old arm64e binary, create a dyld_chained_starts_in_image for caller uint64_t baseAddress = preferredLoadAddress(); uint64_t imagePageCount = this->mappedSize()/0x1000; size_t bufferSize = leInfo.dyldInfo->bind_size + (size_t)imagePageCount*sizeof(uint16_t) + 512; BLOCK_ACCCESSIBLE_ARRAY(uint8_t, buffer, bufferSize); uint8_t* bufferEnd = &buffer[bufferSize]; dyld_chained_starts_in_image* header = (dyld_chained_starts_in_image*)buffer; header->seg_count = leInfo.layout.linkeditSegIndex; for (uint32_t i=0; i < header->seg_count; ++i) header->seg_info_offset[i] = 0; __block uint8_t curSegIndex = 0; __block dyld_chained_starts_in_segment* curSeg = (dyld_chained_starts_in_segment*)(&(header->seg_info_offset[header->seg_count])); parseOrgArm64eChainedFixups(diag, nullptr, nullptr, ^(const LinkEditInfo& leInfo2, const SegmentInfo segments[], uint8_t segmentIndex, bool segIndexSet, uint64_t segmentOffset, uint16_t format, bool& stop) { uint32_t pageIndex = (uint32_t)(segmentOffset/0x1000); if ( segmentIndex != curSegIndex ) { if ( curSegIndex == 0 ) { header->seg_info_offset[segmentIndex] = (uint32_t)((uint8_t*)curSeg - buffer); } else { header->seg_info_offset[segmentIndex] = (uint32_t)((uint8_t*)(&curSeg->page_start[curSeg->page_count]) - buffer); curSeg = (dyld_chained_starts_in_segment*)((uint8_t*)header+header->seg_info_offset[segmentIndex]); assert((uint8_t*)curSeg < bufferEnd); } curSeg->page_count = 0; curSegIndex = segmentIndex; } while ( curSeg->page_count != pageIndex ) { assert((uint8_t*)(&curSeg->page_start[curSeg->page_count]) < bufferEnd); curSeg->page_start[curSeg->page_count] = 0xFFFF; curSeg->page_count++; } curSeg->size = (uint32_t)((uint8_t*)(&curSeg->page_start[pageIndex]) - (uint8_t*)curSeg); curSeg->page_size = 0x1000; // old arm64e encoding used 4KB pages curSeg->pointer_format = DYLD_CHAINED_PTR_ARM64E; curSeg->segment_offset = segments[segmentIndex].vmAddr - baseAddress; curSeg->max_valid_pointer = 0; curSeg->page_count = pageIndex+1; assert((uint8_t*)(&curSeg->page_start[pageIndex]) < bufferEnd); curSeg->page_start[pageIndex] = segmentOffset & 0xFFF; //fprintf(stderr, "segment_offset=0x%llX, vmAddr=0x%llX\n", curSeg->segment_offset, segments[segmentIndex].vmAddr ); //printf("segIndex=%d, segOffset=0x%08llX, page_start[%d]=0x%04X, page_start[%d]=0x%04X\n", // segmentIndex, segmentOffset, pageIndex, curSeg->page_start[pageIndex], pageIndex-1, pageIndex ? curSeg->page_start[pageIndex-1] : 0); }); callback(header); } #endif else { diag.error("image does not use chained fixups"); } } struct OldThreadsStartSection { uint32_t padding : 31, stride8 : 1; uint32_t chain_starts[1]; }; // ld64 can't sometimes determine the size of __thread_starts accurately, // because these sections have to be given a size before everything is laid out, // and you don't know the actual size of the chains until everything is // laid out. In order to account for this, the linker puts trailing 0xFFFFFFFF at // the end of the section, that must be ignored when walking the chains. This // patch adjust the section size accordingly. static uint32_t adjustStartsCount(uint32_t startsCount, const uint32_t* starts) { for ( int i = startsCount; i > 0; --i ) { if ( starts[i - 1] == 0xFFFFFFFF ) startsCount--; else break; } return startsCount; } bool MachOAnalyzer::hasFirmwareChainStarts(uint16_t* pointerFormat, uint32_t* startsCount, const uint32_t** starts) const { if ( !this->isPreload() && !this->isStaticExecutable() ) return false; uint64_t sectionSize; if (const dyld_chained_starts_offsets* sect = (dyld_chained_starts_offsets*)this->findSectionContent("__TEXT", "__chain_starts", sectionSize) ) { *pointerFormat = sect->pointer_format; *startsCount = sect->starts_count; *starts = §->chain_starts[0]; return true; } if (const OldThreadsStartSection* sect = (OldThreadsStartSection*)this->findSectionContent("__TEXT", "__thread_starts", sectionSize) ) { *pointerFormat = sect->stride8 ? DYLD_CHAINED_PTR_ARM64E : DYLD_CHAINED_PTR_ARM64E_FIRMWARE; *startsCount = adjustStartsCount((uint32_t)(sectionSize/4) - 1, sect->chain_starts); *starts = sect->chain_starts; return true; } return false; } bool MachOAnalyzer::hasRebaseRuns(const void** runs, size_t* runsSize) const { if ( !this->isPreload() ) return false; uint64_t sectionSize; if (const void* sect = this->findSectionContent("__TEXT", "__rebase_info", sectionSize) ) { *runs = sect; *runsSize = (size_t)sectionSize; return true; } return false; } struct RebaseRuns { uint32_t startAddress; uint8_t runs[]; // value of even indexes is how many pointers in a row are rebases, value of odd indexes times 4 is memory to skip over // two zero values in a row signals the end of the run }; void MachOAnalyzer::forEachRebaseRunAddress(const void* runs, size_t runsSize, void (^handler)(uint32_t address)) const { const RebaseRuns* rr = (RebaseRuns*)runs; const RebaseRuns* end = (RebaseRuns*)((uint8_t*)runs + runsSize); while ( rr < end ) { uint32_t address = rr->startAddress; int index = 0; bool done = false; while ( !done ) { uint8_t count = rr->runs[index]; if ( count == 0 ) { // two 0x00 in a row mean the run is complete if ( rr->runs[index+1] == 0 ) { ++index; done = true; } } else { if ( index & 1 ) { // odd runs index => how much to jump forward address += ((count-1) * 4); } else { // even runs index => how many pointers in a row that need rebasing for (int i=0; i < count; ++i) { handler(address); address += 4; } } } ++index; } // 4-byte align for next run index = (index+3) & (-4); rr = (RebaseRuns*)(&rr->runs[index]); } } MachOAnalyzer::ObjCInfo MachOAnalyzer::getObjCInfo() const { __block ObjCInfo result; result.selRefCount = 0; result.classDefCount = 0; result.protocolDefCount = 0; const uint32_t ptrSize = pointerSize(); forEachSection(^(const SectionInfo& sectInfo, bool malformedSectionRange, bool& stop) { if ( strncmp(sectInfo.segInfo.segName, "__DATA", 6) == 0 ) { if ( strcmp(sectInfo.sectName, "__objc_selrefs") == 0 ) result.selRefCount += (sectInfo.sectSize/ptrSize); else if ( strcmp(sectInfo.sectName, "__objc_classlist") == 0 ) result.classDefCount += (sectInfo.sectSize/ptrSize); else if ( strcmp(sectInfo.sectName, "__objc_protolist") == 0 ) result.protocolDefCount += (sectInfo.sectSize/ptrSize); } else if ( (this->cputype == CPU_TYPE_I386) && (strcmp(sectInfo.segInfo.segName, "__OBJC") == 0) ) { if ( strcmp(sectInfo.sectName, "__message_refs") == 0 ) result.selRefCount += (sectInfo.sectSize/4); else if ( strcmp(sectInfo.sectName, "__class") == 0 ) result.classDefCount += (sectInfo.sectSize/48); else if ( strcmp(sectInfo.sectName, "__protocol") == 0 ) result.protocolDefCount += (sectInfo.sectSize/20); } }); return result; } uint64_t MachOAnalyzer::ObjCClassInfo::getReadOnlyDataField(ObjCClassInfo::ReadOnlyDataField field, uint32_t pointerSize) const { if (pointerSize == 8) { typedef uint64_t PtrTy; struct class_ro_t { uint32_t flags; uint32_t instanceStart; // Note there is 4-bytes of alignment padding between instanceSize and ivarLayout // on 64-bit archs, but no padding on 32-bit archs. // This union is a way to model that. union { uint32_t instanceSize; PtrTy pad; } instanceSize; PtrTy ivarLayoutVMAddr; PtrTy nameVMAddr; PtrTy baseMethodsVMAddr; PtrTy baseProtocolsVMAddr; PtrTy ivarsVMAddr; PtrTy weakIvarLayoutVMAddr; PtrTy basePropertiesVMAddr; }; const class_ro_t* classData = (const class_ro_t*)(dataVMAddr + vmAddrConverter.slide); switch (field) { case ObjCClassInfo::ReadOnlyDataField::name: return vmAddrConverter.convertToVMAddr(classData->nameVMAddr); case ObjCClassInfo::ReadOnlyDataField::baseProtocols: return vmAddrConverter.convertToVMAddr(classData->baseProtocolsVMAddr); case ObjCClassInfo::ReadOnlyDataField::baseMethods: return vmAddrConverter.convertToVMAddr(classData->baseMethodsVMAddr); case ObjCClassInfo::ReadOnlyDataField::baseProperties: return vmAddrConverter.convertToVMAddr(classData->basePropertiesVMAddr); case ObjCClassInfo::ReadOnlyDataField::flags: return classData->flags; } } else { typedef uint32_t PtrTy; struct class_ro_t { uint32_t flags; uint32_t instanceStart; // Note there is 4-bytes of alignment padding between instanceSize and ivarLayout // on 64-bit archs, but no padding on 32-bit archs. // This union is a way to model that. union { uint32_t instanceSize; PtrTy pad; } instanceSize; PtrTy ivarLayoutVMAddr; PtrTy nameVMAddr; PtrTy baseMethodsVMAddr; PtrTy baseProtocolsVMAddr; PtrTy ivarsVMAddr; PtrTy weakIvarLayoutVMAddr; PtrTy basePropertiesVMAddr; }; const class_ro_t* classData = (const class_ro_t*)(dataVMAddr + vmAddrConverter.slide); switch (field) { case ObjCClassInfo::ReadOnlyDataField::name: return vmAddrConverter.convertToVMAddr(classData->nameVMAddr); case ObjCClassInfo::ReadOnlyDataField::baseProtocols: return vmAddrConverter.convertToVMAddr(classData->baseProtocolsVMAddr); case ObjCClassInfo::ReadOnlyDataField::baseMethods: return vmAddrConverter.convertToVMAddr(classData->baseMethodsVMAddr); case ObjCClassInfo::ReadOnlyDataField::baseProperties: return vmAddrConverter.convertToVMAddr(classData->basePropertiesVMAddr); case ObjCClassInfo::ReadOnlyDataField::flags: return classData->flags; } } } const char* MachOAnalyzer::getPrintableString(uint64_t stringVMAddr, MachOAnalyzer::PrintableStringResult& result) const { uint32_t fairplayTextOffsetStart; uint32_t fairplayTextOffsetEnd; uint32_t fairplaySize; if ( isFairPlayEncrypted(fairplayTextOffsetStart, fairplaySize) ) { fairplayTextOffsetEnd = fairplayTextOffsetStart + fairplaySize; } else { fairplayTextOffsetEnd = 0; } result = PrintableStringResult::UnknownSection; forEachSection(^(const MachOAnalyzer::SectionInfo §Info, bool malformedSectionRange, bool &stop) { if ( stringVMAddr < sectInfo.sectAddr ) { return; } if ( stringVMAddr >= ( sectInfo.sectAddr + sectInfo.sectSize) ) { return; } // We can't scan this section if its protected if ( sectInfo.segInfo.isProtected ) { result = PrintableStringResult::ProtectedSection; stop = true; return; } // We can't scan this section if it overlaps with the fairplay range if ( fairplayTextOffsetEnd < sectInfo.sectFileOffset ) { // Fairplay range ends before section } else if ( fairplayTextOffsetStart > (sectInfo.sectFileOffset + sectInfo.sectSize) ) { // Fairplay range starts after section } else { // Must overlap result = PrintableStringResult::FairPlayEncrypted; stop = true; return; } result = PrintableStringResult::CanPrint; stop = true; }); #if BUILDING_SHARED_CACHE_UTIL || BUILDING_DYLDINFO // The shared cache coalesces strings in to their own section. // Assume its a valid pointer if (result == PrintableStringResult::UnknownSection && this->inDyldCache()) { result = PrintableStringResult::CanPrint; return (const char*)(stringVMAddr + getSlide()); } #endif if (result == PrintableStringResult::CanPrint) return (const char*)(stringVMAddr + getSlide()); return nullptr; } void MachOAnalyzer::forEachObjCClass(uint64_t classListRuntimeOffset, uint64_t classListCount, const VMAddrConverter& vmAddrConverter, ClassCallback& callback) const { #if !BUILDING_DYLD // ObjC patching needs the bind targets for interposable references to the classes // build targets table STACK_ALLOC_OVERFLOW_SAFE_ARRAY(uint64_t, bindTargets, 32); if ( this->hasChainedFixups() ) { intptr_t slide = this->getSlide(); Diagnostics diag; this->forEachBindTarget(diag, false, ^(const BindTargetInfo& info, bool& stop) { if ( diag.hasError() ) { stop = true; return; } if ( info.libOrdinal == BIND_SPECIAL_DYLIB_SELF ) { void* result = nullptr; bool resultPointsToInstructions = false; if ( this->hasExportedSymbol(info.symbolName, nullptr, &result, &resultPointsToInstructions) ) { uint64_t resultVMAddr = (uint64_t)result - (uint64_t)slide; bindTargets.push_back(resultVMAddr); } else { bindTargets.push_back(0); } } else { bindTargets.push_back(0); } }, ^(const MachOAnalyzer::BindTargetInfo& info, bool& stop) { }); } #else // dyld always analyzes objc after fixups, so we don't need the bind targets Array<uint64_t> bindTargets; #endif const uint64_t ptrSize = pointerSize(); const uint8_t* arrayBase = (uint8_t*)this + classListRuntimeOffset; if ( ptrSize == 8 ) { typedef uint64_t PtrTy; __block bool stop = false; for ( uint64_t i = 0; i != classListCount; ++i ) { uint64_t classVMAddr = vmAddrConverter.convertToVMAddr(*(PtrTy*)(arrayBase + (i * sizeof(PtrTy))), bindTargets); parseObjCClass(vmAddrConverter, classVMAddr, bindTargets, ^(uint64_t classSuperclassVMAddr, uint64_t classDataVMAddr, const ObjCClassInfo& objcClass) { callback(classVMAddr, classSuperclassVMAddr, classDataVMAddr, objcClass, false, stop); if ( stop ) return; // Then parse and call for the metaclass uint64_t isaVMAddr = objcClass.isaVMAddr; parseObjCClass(vmAddrConverter, isaVMAddr, bindTargets, ^(uint64_t metaclassSuperclassVMAddr, uint64_t metaclassDataVMAddr, const ObjCClassInfo& objcMetaclass) { callback(isaVMAddr, metaclassSuperclassVMAddr, metaclassDataVMAddr, objcMetaclass, true, stop); }); }); if ( stop ) break; } } else { typedef uint32_t PtrTy; __block bool stop = false; for ( uint64_t i = 0; i != classListCount; ++i ) { uint64_t classVMAddr = vmAddrConverter.convertToVMAddr(*(PtrTy*)(arrayBase + (i * sizeof(PtrTy))), bindTargets); parseObjCClass(vmAddrConverter, classVMAddr, bindTargets, ^(uint64_t classSuperclassVMAddr, uint64_t classDataVMAddr, const ObjCClassInfo& objcClass) { callback(classVMAddr, classSuperclassVMAddr, classDataVMAddr, objcClass, false, stop); if ( stop ) return; // Then parse and call for the metaclass uint64_t isaVMAddr = objcClass.isaVMAddr; parseObjCClass(vmAddrConverter, isaVMAddr, bindTargets, ^(uint64_t metaclassSuperclassVMAddr, uint64_t metaclassDataVMAddr, const ObjCClassInfo& objcMetaclass) { callback(isaVMAddr, metaclassSuperclassVMAddr, metaclassDataVMAddr, objcMetaclass, true, stop); }); }); if ( stop ) break; } } } void MachOAnalyzer::forEachObjCClass(Diagnostics& diag, const VMAddrConverter& vmAddrConverter, ClassCallback& callback) const { uint64_t classListRuntimeOffset; uint64_t classListSize; bool foundSection = findObjCDataSection("__objc_classlist", classListRuntimeOffset, classListSize); if ( !foundSection ) return; const uint64_t ptrSize = pointerSize(); if ( (classListSize % ptrSize) != 0 ) { diag.error("Invalid objc class section size"); return; } forEachObjCClass(classListRuntimeOffset, classListSize / ptrSize, vmAddrConverter, callback); } void MachOAnalyzer::parseObjCClass(const VMAddrConverter& vmAddrConverter, uint64_t classVMAddr, const Array<uint64_t>& bindTargets, void (^handler)(uint64_t classSuperclassVMAddr, uint64_t classDataVMAddr, const ObjCClassInfo& objcClass)) const { const uint64_t ptrSize = pointerSize(); intptr_t slide = getSlide(); uint64_t classSuperclassVMAddr = 0; uint64_t classDataVMAddr = 0; ObjCClassInfo objcClass; if ( ptrSize == 8 ) { struct objc_class_t { uint64_t isaVMAddr; uint64_t superclassVMAddr; uint64_t methodCacheBuckets; uint64_t methodCacheProperties; uint64_t dataVMAddrAndFastFlags; }; // This matches "struct TargetClassMetadata" from Metadata.h in Swift struct swift_class_metadata_t : objc_class_t { uint32_t swiftClassFlags; }; enum : uint64_t { FAST_DATA_MASK = 0x00007ffffffffff8ULL }; classSuperclassVMAddr = classVMAddr + offsetof(objc_class_t, superclassVMAddr); classDataVMAddr = classVMAddr + offsetof(objc_class_t, dataVMAddrAndFastFlags); // First call the handler on the class const objc_class_t* classPtr = (const objc_class_t*)(classVMAddr + slide); const swift_class_metadata_t* swiftClassPtr = (const swift_class_metadata_t*)classPtr; objcClass.isaVMAddr = vmAddrConverter.convertToVMAddr(classPtr->isaVMAddr, bindTargets); objcClass.superclassVMAddr = vmAddrConverter.convertToVMAddr(classPtr->superclassVMAddr); objcClass.methodCacheVMAddr = classPtr->methodCacheProperties == 0 ? 0 : vmAddrConverter.convertToVMAddr(classPtr->methodCacheProperties); objcClass.dataVMAddr = vmAddrConverter.convertToVMAddr(classPtr->dataVMAddrAndFastFlags) & FAST_DATA_MASK; objcClass.vmAddrConverter = vmAddrConverter; objcClass.isSwiftLegacy = classPtr->dataVMAddrAndFastFlags & ObjCClassInfo::FAST_IS_SWIFT_LEGACY; objcClass.isSwiftStable = classPtr->dataVMAddrAndFastFlags & ObjCClassInfo::FAST_IS_SWIFT_STABLE; // The Swift class flags are only present if the class is swift objcClass.swiftClassFlags = (objcClass.isSwiftLegacy || objcClass.isSwiftStable) ? swiftClassPtr->swiftClassFlags : 0; } else { struct objc_class_t { uint32_t isaVMAddr; uint32_t superclassVMAddr; uint32_t methodCacheBuckets; uint32_t methodCacheProperties; uint32_t dataVMAddrAndFastFlags; }; // This matches "struct TargetClassMetadata" from Metadata.h in Swift struct swift_class_metadata_t : objc_class_t { uint32_t swiftClassFlags; }; enum : uint32_t { FAST_DATA_MASK = 0xfffffffcUL }; classSuperclassVMAddr = classVMAddr + offsetof(objc_class_t, superclassVMAddr); classDataVMAddr = classVMAddr + offsetof(objc_class_t, dataVMAddrAndFastFlags); // First call the handler on the class const objc_class_t* classPtr = (const objc_class_t*)(classVMAddr + slide); const swift_class_metadata_t* swiftClassPtr = (const swift_class_metadata_t*)classPtr; objcClass.isaVMAddr = vmAddrConverter.convertToVMAddr(classPtr->isaVMAddr, bindTargets); objcClass.superclassVMAddr = vmAddrConverter.convertToVMAddr(classPtr->superclassVMAddr); objcClass.methodCacheVMAddr = classPtr->methodCacheProperties == 0 ? 0 : vmAddrConverter.convertToVMAddr(classPtr->methodCacheProperties); objcClass.dataVMAddr = vmAddrConverter.convertToVMAddr(classPtr->dataVMAddrAndFastFlags) & FAST_DATA_MASK; objcClass.vmAddrConverter = vmAddrConverter; objcClass.isSwiftLegacy = classPtr->dataVMAddrAndFastFlags & ObjCClassInfo::FAST_IS_SWIFT_LEGACY; objcClass.isSwiftStable = classPtr->dataVMAddrAndFastFlags & ObjCClassInfo::FAST_IS_SWIFT_STABLE; // The Swift class flags are only present if the class is swift objcClass.swiftClassFlags = (objcClass.isSwiftLegacy || objcClass.isSwiftStable) ? swiftClassPtr->swiftClassFlags : 0; } handler(classSuperclassVMAddr, classDataVMAddr, objcClass); } bool MachOAnalyzer::isSwiftClass(const void* classLocation) const { const uint64_t ptrSize = pointerSize(); if ( ptrSize == 8 ) { struct objc_class_t { uint64_t isaVMAddr; uint64_t superclassVMAddr; uint64_t methodCacheBuckets; uint64_t methodCacheProperties; uint64_t dataVMAddrAndFastFlags; }; enum : uint64_t { FAST_DATA_MASK = 0x00007ffffffffff8ULL }; const objc_class_t* classPtr = (const objc_class_t*)classLocation; bool isSwiftLegacy = classPtr->dataVMAddrAndFastFlags & ObjCClassInfo::FAST_IS_SWIFT_LEGACY; bool isSwiftStable = classPtr->dataVMAddrAndFastFlags & ObjCClassInfo::FAST_IS_SWIFT_STABLE; // The Swift class flags are only present if the class is swift return (isSwiftLegacy || isSwiftStable); } else { struct objc_class_t { uint32_t isaVMAddr; uint32_t superclassVMAddr; uint32_t methodCacheBuckets; uint32_t methodCacheProperties; uint32_t dataVMAddrAndFastFlags; }; enum : uint32_t { FAST_DATA_MASK = 0xfffffffcUL }; const objc_class_t* classPtr = (const objc_class_t*)classLocation; bool isSwiftLegacy = classPtr->dataVMAddrAndFastFlags & ObjCClassInfo::FAST_IS_SWIFT_LEGACY; bool isSwiftStable = classPtr->dataVMAddrAndFastFlags & ObjCClassInfo::FAST_IS_SWIFT_STABLE; // The Swift class flags are only present if the class is swift return (isSwiftLegacy || isSwiftStable); } } void MachOAnalyzer::forEachObjCCategory(uint64_t categoryListRuntimeOffset, uint64_t categoryListCount, const VMAddrConverter& vmAddrConverter, CategoryCallback& callback) const { const uint64_t ptrSize = pointerSize(); intptr_t slide = getSlide(); const uint8_t* arrayBase = (uint8_t*)this + categoryListRuntimeOffset; if ( ptrSize == 8 ) { typedef uint64_t PtrTy; struct objc_category_t { PtrTy nameVMAddr; PtrTy clsVMAddr; PtrTy instanceMethodsVMAddr; PtrTy classMethodsVMAddr; PtrTy protocolsVMAddr; PtrTy instancePropertiesVMAddr; }; __block bool stop = false; for ( uint64_t i = 0; i != categoryListCount; ++i ) { uint64_t categoryVMAddr = vmAddrConverter.convertToVMAddr(*(PtrTy*)(arrayBase + (i * sizeof(PtrTy)))); const objc_category_t* categoryPtr = (const objc_category_t*)(categoryVMAddr + slide); ObjCCategory objCCategory; objCCategory.nameVMAddr = vmAddrConverter.convertToVMAddr(categoryPtr->nameVMAddr); objCCategory.clsVMAddr = vmAddrConverter.convertToVMAddr(categoryPtr->clsVMAddr); objCCategory.instanceMethodsVMAddr = vmAddrConverter.convertToVMAddr(categoryPtr->instanceMethodsVMAddr); objCCategory.classMethodsVMAddr = vmAddrConverter.convertToVMAddr(categoryPtr->classMethodsVMAddr); objCCategory.protocolsVMAddr = vmAddrConverter.convertToVMAddr(categoryPtr->protocolsVMAddr); objCCategory.instancePropertiesVMAddr = vmAddrConverter.convertToVMAddr(categoryPtr->instancePropertiesVMAddr); callback(categoryVMAddr, objCCategory, stop); if ( stop ) break; } } else { typedef uint32_t PtrTy; struct objc_category_t { PtrTy nameVMAddr; PtrTy clsVMAddr; PtrTy instanceMethodsVMAddr; PtrTy classMethodsVMAddr; PtrTy protocolsVMAddr; PtrTy instancePropertiesVMAddr; }; __block bool stop = false; for ( uint64_t i = 0; i != categoryListCount; ++i ) { uint64_t categoryVMAddr = vmAddrConverter.convertToVMAddr(*(PtrTy*)(arrayBase + (i * sizeof(PtrTy)))); const objc_category_t* categoryPtr = (const objc_category_t*)(categoryVMAddr + slide); ObjCCategory objCCategory; objCCategory.nameVMAddr = vmAddrConverter.convertToVMAddr(categoryPtr->nameVMAddr); objCCategory.clsVMAddr = vmAddrConverter.convertToVMAddr(categoryPtr->clsVMAddr); objCCategory.instanceMethodsVMAddr = vmAddrConverter.convertToVMAddr(categoryPtr->instanceMethodsVMAddr); objCCategory.classMethodsVMAddr = vmAddrConverter.convertToVMAddr(categoryPtr->classMethodsVMAddr); objCCategory.protocolsVMAddr = vmAddrConverter.convertToVMAddr(categoryPtr->protocolsVMAddr); objCCategory.instancePropertiesVMAddr = vmAddrConverter.convertToVMAddr(categoryPtr->instancePropertiesVMAddr); callback(categoryVMAddr, objCCategory, stop); if ( stop ) break; } } } void MachOAnalyzer::forEachObjCCategory(Diagnostics& diag, const VMAddrConverter& vmAddrConverter, CategoryCallback& callback) const { uint64_t categoryListRuntimeOffset; uint64_t categoryListSize; bool foundSection = findObjCDataSection("__objc_catlist", categoryListRuntimeOffset, categoryListSize); if ( !foundSection ) return; const uint64_t ptrSize = pointerSize(); if ( (categoryListSize % ptrSize) != 0 ) { diag.error("Invalid objc category section size"); return; } forEachObjCCategory(categoryListRuntimeOffset, categoryListSize / ptrSize, vmAddrConverter, callback); } void MachOAnalyzer::forEachObjCProtocol(uint64_t protocolListRuntimeOffset, uint64_t protocolListCount, const VMAddrConverter& vmAddrConverter, ProtocolCallback& callback) const { const uint64_t ptrSize = pointerSize(); intptr_t slide = getSlide(); const uint8_t* arrayBase = (uint8_t*)this + protocolListRuntimeOffset; if ( ptrSize == 8 ) { typedef uint64_t PtrTy; struct protocol_t { PtrTy isaVMAddr; PtrTy nameVMAddr; PtrTy protocolsVMAddr; PtrTy instanceMethodsVMAddr; PtrTy classMethodsVMAddr; PtrTy optionalInstanceMethodsVMAddr; PtrTy optionalClassMethodsVMAddr; PtrTy instancePropertiesVMAddr; uint32_t size; uint32_t flags; // Fields below this point are not always present on disk. PtrTy extendedMethodTypesVMAddr; PtrTy demangledNameVMAddr; PtrTy classPropertiesVMAddr; }; __block bool stop = false; for ( uint64_t i = 0; i != protocolListCount; ++i ) { uint64_t protocolVMAddr = vmAddrConverter.convertToVMAddr(*(PtrTy*)(arrayBase + (i * sizeof(PtrTy)))); const protocol_t* protocolPtr = (const protocol_t*)(protocolVMAddr + slide); ObjCProtocol objCProtocol; objCProtocol.isaVMAddr = vmAddrConverter.convertToVMAddr(protocolPtr->isaVMAddr); objCProtocol.nameVMAddr = vmAddrConverter.convertToVMAddr(protocolPtr->nameVMAddr); objCProtocol.protocolsVMAddr = vmAddrConverter.convertToVMAddr(protocolPtr->protocolsVMAddr); objCProtocol.instanceMethodsVMAddr = vmAddrConverter.convertToVMAddr(protocolPtr->instanceMethodsVMAddr); objCProtocol.classMethodsVMAddr = vmAddrConverter.convertToVMAddr(protocolPtr->classMethodsVMAddr); objCProtocol.optionalInstanceMethodsVMAddr = vmAddrConverter.convertToVMAddr(protocolPtr->optionalInstanceMethodsVMAddr); objCProtocol.optionalClassMethodsVMAddr = vmAddrConverter.convertToVMAddr(protocolPtr->optionalClassMethodsVMAddr); callback(protocolVMAddr, objCProtocol, stop); if ( stop ) break; } } else { typedef uint32_t PtrTy; struct protocol_t { PtrTy isaVMAddr; PtrTy nameVMAddr; PtrTy protocolsVMAddr; PtrTy instanceMethodsVMAddr; PtrTy classMethodsVMAddr; PtrTy optionalInstanceMethodsVMAddr; PtrTy optionalClassMethodsVMAddr; PtrTy instancePropertiesVMAddr; uint32_t size; uint32_t flags; // Fields below this point are not always present on disk. PtrTy extendedMethodTypesVMAddr; PtrTy demangledNameVMAddr; PtrTy classPropertiesVMAddr; }; __block bool stop = false; for ( uint64_t i = 0; i != protocolListCount; ++i ) { uint64_t protocolVMAddr = vmAddrConverter.convertToVMAddr(*(PtrTy*)(arrayBase + (i * sizeof(PtrTy)))); const protocol_t* protocolPtr = (const protocol_t*)(protocolVMAddr + slide); ObjCProtocol objCProtocol; objCProtocol.isaVMAddr = vmAddrConverter.convertToVMAddr(protocolPtr->isaVMAddr); objCProtocol.nameVMAddr = vmAddrConverter.convertToVMAddr(protocolPtr->nameVMAddr); objCProtocol.protocolsVMAddr = vmAddrConverter.convertToVMAddr(protocolPtr->protocolsVMAddr); objCProtocol.instanceMethodsVMAddr = vmAddrConverter.convertToVMAddr(protocolPtr->instanceMethodsVMAddr); objCProtocol.classMethodsVMAddr = vmAddrConverter.convertToVMAddr(protocolPtr->classMethodsVMAddr); objCProtocol.optionalInstanceMethodsVMAddr = vmAddrConverter.convertToVMAddr(protocolPtr->optionalInstanceMethodsVMAddr); objCProtocol.optionalClassMethodsVMAddr = vmAddrConverter.convertToVMAddr(protocolPtr->optionalClassMethodsVMAddr); callback(protocolVMAddr, objCProtocol, stop); if ( stop ) break; } } } void MachOAnalyzer::forEachObjCProtocol(Diagnostics& diag, const VMAddrConverter& vmAddrConverter, ProtocolCallback& callback) const { uint64_t protocolListRuntimeOffset; uint64_t protocolListSize; bool foundSection = findObjCDataSection("__objc_protolist", protocolListRuntimeOffset, protocolListSize); if ( !foundSection ) return; const uint64_t ptrSize = pointerSize(); if ( (protocolListSize % ptrSize) != 0 ) { diag.error("Invalid objc protocol section size"); return; } forEachObjCProtocol(protocolListRuntimeOffset, protocolListSize / ptrSize, vmAddrConverter, callback); } static void ignorePreoptimizedListsOfLists(uint64_t& listVMAddr, intptr_t slide) { // If this is a list of lists, then we likely just want the class list. So go to the end which is where // we emitted it if ( listVMAddr & 1 ) { struct ListOfListsEntry { union { struct { uint64_t imageIndex: 16; int64_t offset: 48; }; struct { uint32_t entsize; uint32_t count; }; }; }; listVMAddr = listVMAddr & ~1; const ListOfListsEntry* listHeader = (const ListOfListsEntry*)(listVMAddr + slide); if ( listHeader->count != 0 ) { const ListOfListsEntry& listEntry = (listHeader + 1)[listHeader->count - 1]; // The list entry is a relative offset to the target // Work out the VMAddress of that target uint64_t listEntryVMOffset{(uint64_t)&listEntry - (uint64_t)listHeader}; uint64_t listEntryVMAddr = listVMAddr + listEntryVMOffset; listVMAddr = listEntryVMAddr + (uint64_t)listEntry.offset; } } } void MachOAnalyzer::forEachObjCMethod(uint64_t methodListVMAddr, const VMAddrConverter& vmAddrConverter, uint64_t sharedCacheRelativeSelectorBaseVMAddress, void (^handler)(uint64_t methodVMAddr, const ObjCMethod& method, bool& stop)) const { if ( methodListVMAddr == 0 ) return; const uint64_t ptrSize = pointerSize(); intptr_t slide = getSlide(); ignorePreoptimizedListsOfLists(methodListVMAddr, slide); if ( ptrSize == 8 ) { typedef uint64_t PtrTy; struct method_list_t { uint32_t entsize; uint32_t count; PtrTy methodArrayBase; // Note this is the start the array method_t[0] uint32_t getEntsize() const { return entsize & ObjCMethodList::methodListSizeMask; } bool usesDirectOffsetsToSelectors() const { return (entsize & 0x40000000) != 0; } bool usesRelativeOffsets() const { return (entsize & 0x80000000) != 0; } }; struct method_t { PtrTy nameVMAddr; // SEL PtrTy typesVMAddr; // const char * PtrTy impVMAddr; // IMP }; struct relative_method_t { int32_t nameOffset; // SEL* int32_t typesOffset; // const char * int32_t impOffset; // IMP }; const method_list_t* methodList = (const method_list_t*)(methodListVMAddr + slide); if ( methodList == nullptr ) return; bool relativeMethodListsAreOffsetsToSelectors = methodList->usesDirectOffsetsToSelectors(); uint64_t methodListArrayBaseVMAddr = methodListVMAddr + offsetof(method_list_t, methodArrayBase); for (unsigned i = 0; i != methodList->count; ++i) { uint64_t methodEntryOffset = i * methodList->getEntsize(); uint64_t methodVMAddr = methodListArrayBaseVMAddr + methodEntryOffset; ObjCMethod method; if ( methodList->usesRelativeOffsets() ) { const relative_method_t* methodPtr = (const relative_method_t*)(methodVMAddr + slide); if ( relativeMethodListsAreOffsetsToSelectors ) { if ( sharedCacheRelativeSelectorBaseVMAddress != 0 ) { // // New shared caches use an offset from a magic selector for relative method lists method.nameVMAddr = sharedCacheRelativeSelectorBaseVMAddress + methodPtr->nameOffset; } else { method.nameVMAddr = methodVMAddr + offsetof(relative_method_t, nameOffset) + methodPtr->nameOffset; } } else { PtrTy* nameLocation = (PtrTy*)((uint8_t*)&methodPtr->nameOffset + methodPtr->nameOffset); method.nameVMAddr = vmAddrConverter.convertToVMAddr(*nameLocation); } method.typesVMAddr = methodVMAddr + offsetof(relative_method_t, typesOffset) + methodPtr->typesOffset; method.impVMAddr = methodVMAddr + offsetof(relative_method_t, impOffset) + methodPtr->impOffset; method.nameLocationVMAddr = methodVMAddr + offsetof(relative_method_t, nameOffset) + methodPtr->nameOffset; } else { const method_t* methodPtr = (const method_t*)(methodVMAddr + slide); method.nameVMAddr = vmAddrConverter.convertToVMAddr(methodPtr->nameVMAddr); method.typesVMAddr = vmAddrConverter.convertToVMAddr(methodPtr->typesVMAddr); method.impVMAddr = vmAddrConverter.convertToVMAddr(methodPtr->impVMAddr); method.nameLocationVMAddr = methodVMAddr + offsetof(method_t, nameVMAddr); } bool stop = false; handler(methodVMAddr, method, stop); if ( stop ) break; } } else { typedef uint32_t PtrTy; struct method_list_t { uint32_t entsize; uint32_t count; PtrTy methodArrayBase; // Note this is the start the array method_t[0] uint32_t getEntsize() const { return entsize & ObjCMethodList::methodListSizeMask; } bool usesDirectOffsetsToSelectors() const { return (entsize & 0x40000000) != 0; } bool usesRelativeOffsets() const { return (entsize & 0x80000000) != 0; } }; struct method_t { PtrTy nameVMAddr; // SEL PtrTy typesVMAddr; // const char * PtrTy impVMAddr; // IMP }; struct relative_method_t { int32_t nameOffset; // SEL* int32_t typesOffset; // const char * int32_t impOffset; // IMP }; const method_list_t* methodList = (const method_list_t*)(methodListVMAddr + slide); if ( methodList == nullptr ) return; bool relativeMethodListsAreOffsetsToSelectors = methodList->usesDirectOffsetsToSelectors(); uint64_t methodListArrayBaseVMAddr = methodListVMAddr + offsetof(method_list_t, methodArrayBase); for (unsigned i = 0; i != methodList->count; ++i) { uint64_t methodEntryOffset = i * methodList->getEntsize(); uint64_t methodVMAddr = methodListArrayBaseVMAddr + methodEntryOffset; ObjCMethod method; if ( methodList->usesRelativeOffsets() ) { const relative_method_t* methodPtr = (const relative_method_t*)(methodVMAddr + slide); if ( relativeMethodListsAreOffsetsToSelectors ) { if ( sharedCacheRelativeSelectorBaseVMAddress != 0 ) { // // New shared caches use an offset from a magic selector for relative method lists method.nameVMAddr = sharedCacheRelativeSelectorBaseVMAddress + methodPtr->nameOffset; } else { method.nameVMAddr = methodVMAddr + offsetof(relative_method_t, nameOffset) + methodPtr->nameOffset; } } else { PtrTy* nameLocation = (PtrTy*)((uint8_t*)&methodPtr->nameOffset + methodPtr->nameOffset); method.nameVMAddr = vmAddrConverter.convertToVMAddr(*nameLocation); } method.typesVMAddr = methodVMAddr + offsetof(relative_method_t, typesOffset) + methodPtr->typesOffset; method.impVMAddr = methodVMAddr + offsetof(relative_method_t, impOffset) + methodPtr->impOffset; method.nameLocationVMAddr = methodVMAddr + offsetof(relative_method_t, nameOffset) + methodPtr->nameOffset; } else { const method_t* methodPtr = (const method_t*)(methodVMAddr + slide); method.nameVMAddr = vmAddrConverter.convertToVMAddr(methodPtr->nameVMAddr); method.typesVMAddr = vmAddrConverter.convertToVMAddr(methodPtr->typesVMAddr); method.impVMAddr = vmAddrConverter.convertToVMAddr(methodPtr->impVMAddr); method.nameLocationVMAddr = methodVMAddr + offsetof(method_t, nameVMAddr); } bool stop = false; handler(methodVMAddr, method, stop); if ( stop ) break; } } } bool MachOAnalyzer::objcMethodListIsRelative(uint64_t methodListRuntimeOffset) const { if ( methodListRuntimeOffset == 0 ) return false; struct method_list_t { uint32_t entsize; uint32_t count; bool usesRelativeOffsets() const { return (entsize & 0x80000000) != 0; } }; const method_list_t* methodList = (const method_list_t*)((const uint8_t*)this + methodListRuntimeOffset); return methodList->usesRelativeOffsets(); } void MachOAnalyzer::forEachObjCProperty(uint64_t propertyListVMAddr, const VMAddrConverter& vmAddrConverter, void (^handler)(uint64_t propertyVMAddr, const ObjCProperty& property)) const { if ( propertyListVMAddr == 0 ) return; const uint64_t ptrSize = pointerSize(); intptr_t slide = getSlide(); ignorePreoptimizedListsOfLists(propertyListVMAddr, slide); if ( ptrSize == 8 ) { typedef uint64_t PtrTy; struct property_list_t { uint32_t entsize; uint32_t count; PtrTy propertyArrayBase; // Note this is the start the array property_t[0] uint32_t getEntsize() const { return (entsize) & ~(uint32_t)3; } }; struct property_t { PtrTy nameVMAddr; // SEL PtrTy attributesVMAddr; // const char * }; const property_list_t* propertyList = (const property_list_t*)(propertyListVMAddr + slide); uint64_t propertyListArrayBaseVMAddr = propertyListVMAddr + offsetof(property_list_t, propertyArrayBase); for (unsigned i = 0; i != propertyList->count; ++i) { uint64_t propertyEntryOffset = i * propertyList->getEntsize(); uint64_t propertyVMAddr = propertyListArrayBaseVMAddr + propertyEntryOffset; const property_t* propertyPtr = (const property_t*)(propertyVMAddr + slide); ObjCProperty property; property.nameVMAddr = vmAddrConverter.convertToVMAddr(propertyPtr->nameVMAddr); property.attributesVMAddr = vmAddrConverter.convertToVMAddr(propertyPtr->attributesVMAddr); handler(propertyVMAddr, property); } } else { typedef uint32_t PtrTy; struct property_list_t { uint32_t entsize; uint32_t count; PtrTy propertyArrayBase; // Note this is the start the array property_t[0] uint32_t getEntsize() const { return (entsize) & ~(uint32_t)3; } }; struct property_t { PtrTy nameVMAddr; // SEL PtrTy attributesVMAddr; // const char * }; const property_list_t* propertyList = (const property_list_t*)(propertyListVMAddr + slide); uint64_t propertyListArrayBaseVMAddr = propertyListVMAddr + offsetof(property_list_t, propertyArrayBase); for (unsigned i = 0; i != propertyList->count; ++i) { uint64_t propertyEntryOffset = i * propertyList->getEntsize(); uint64_t propertyVMAddr = propertyListArrayBaseVMAddr + propertyEntryOffset; const property_t* propertyPtr = (const property_t*)(propertyVMAddr + slide); ObjCProperty property; property.nameVMAddr = vmAddrConverter.convertToVMAddr(propertyPtr->nameVMAddr); property.attributesVMAddr = vmAddrConverter.convertToVMAddr(propertyPtr->attributesVMAddr); handler(propertyVMAddr, property); } } } void MachOAnalyzer::forEachObjCProtocol(uint64_t protocolListVMAddr, const VMAddrConverter& vmAddrConverter, void (^handler)(uint64_t protocolRefVMAddr, const ObjCProtocol&)) const { if ( protocolListVMAddr == 0 ) return; auto ptrSize = pointerSize(); intptr_t slide = getSlide(); ignorePreoptimizedListsOfLists(protocolListVMAddr, slide); if ( ptrSize == 8 ) { typedef uint64_t PtrTy; struct protocol_ref_t { PtrTy refVMAddr; }; struct protocol_list_t { PtrTy count; protocol_ref_t array[]; }; struct protocol_t { PtrTy isaVMAddr; PtrTy nameVMAddr; PtrTy protocolsVMAddr; PtrTy instanceMethodsVMAddr; PtrTy classMethodsVMAddr; PtrTy optionalInstanceMethodsVMAddr; PtrTy optionalClassMethodsVMAddr; PtrTy instancePropertiesVMAddr; uint32_t size; uint32_t flags; // Fields below this point are not always present on disk. PtrTy extendedMethodTypesVMAddr; PtrTy demangledNameVMAddr; PtrTy classPropertiesVMAddr; }; const protocol_list_t* protoList = (const protocol_list_t*)(protocolListVMAddr + slide); for (PtrTy i = 0; i != protoList->count; ++i) { uint64_t protocolVMAddr = vmAddrConverter.convertToVMAddr(protoList->array[i].refVMAddr); const protocol_t* protocolPtr = (const protocol_t*)(protocolVMAddr + slide); ObjCProtocol objCProtocol; objCProtocol.isaVMAddr = vmAddrConverter.convertToVMAddr(protocolPtr->isaVMAddr); objCProtocol.nameVMAddr = vmAddrConverter.convertToVMAddr(protocolPtr->nameVMAddr); objCProtocol.protocolsVMAddr = vmAddrConverter.convertToVMAddr(protocolPtr->protocolsVMAddr); objCProtocol.instanceMethodsVMAddr = vmAddrConverter.convertToVMAddr(protocolPtr->instanceMethodsVMAddr); objCProtocol.classMethodsVMAddr = vmAddrConverter.convertToVMAddr(protocolPtr->classMethodsVMAddr); objCProtocol.optionalInstanceMethodsVMAddr = vmAddrConverter.convertToVMAddr(protocolPtr->optionalInstanceMethodsVMAddr); objCProtocol.optionalClassMethodsVMAddr = vmAddrConverter.convertToVMAddr(protocolPtr->optionalClassMethodsVMAddr); handler(protocolVMAddr, objCProtocol); } } else { typedef uint32_t PtrTy; struct protocol_ref_t { PtrTy refVMAddr; }; struct protocol_list_t { PtrTy count; protocol_ref_t array[]; }; struct protocol_t { PtrTy isaVMAddr; PtrTy nameVMAddr; PtrTy protocolsVMAddr; PtrTy instanceMethodsVMAddr; PtrTy classMethodsVMAddr; PtrTy optionalInstanceMethodsVMAddr; PtrTy optionalClassMethodsVMAddr; PtrTy instancePropertiesVMAddr; uint32_t size; uint32_t flags; // Fields below this point are not always present on disk. PtrTy extendedMethodTypesVMAddr; PtrTy demangledNameVMAddr; PtrTy classPropertiesVMAddr; }; const protocol_list_t* protoList = (const protocol_list_t*)(protocolListVMAddr + slide); for (PtrTy i = 0; i != protoList->count; ++i) { uint64_t protocolVMAddr = vmAddrConverter.convertToVMAddr(protoList->array[i].refVMAddr); const protocol_t* protocolPtr = (const protocol_t*)(protocolVMAddr + slide); ObjCProtocol objCProtocol; objCProtocol.isaVMAddr = vmAddrConverter.convertToVMAddr(protocolPtr->isaVMAddr); objCProtocol.nameVMAddr = vmAddrConverter.convertToVMAddr(protocolPtr->nameVMAddr); objCProtocol.protocolsVMAddr = vmAddrConverter.convertToVMAddr(protocolPtr->protocolsVMAddr); objCProtocol.instanceMethodsVMAddr = vmAddrConverter.convertToVMAddr(protocolPtr->instanceMethodsVMAddr); objCProtocol.classMethodsVMAddr = vmAddrConverter.convertToVMAddr(protocolPtr->classMethodsVMAddr); objCProtocol.optionalInstanceMethodsVMAddr = vmAddrConverter.convertToVMAddr(protocolPtr->optionalInstanceMethodsVMAddr); objCProtocol.optionalClassMethodsVMAddr = vmAddrConverter.convertToVMAddr(protocolPtr->optionalClassMethodsVMAddr); handler(protocolVMAddr, objCProtocol); } } } void MachOAnalyzer::forEachObjCSelectorReference(uint64_t selRefsRuntimeOffset, uint64_t selRefsCount, const VMAddrConverter& vmAddrConverter, void (^handler)(uint64_t selRefVMAddr, uint64_t selRefTargetVMAddr, bool& stop)) const { uint64_t baseAddress = preferredLoadAddress(); const uint64_t ptrSize = pointerSize(); const uint8_t* selRefs = (uint8_t*)this + selRefsRuntimeOffset; if ( ptrSize == 8 ) { typedef uint64_t PtrTy; bool stop = false; for ( uint64_t i = 0; i != selRefsCount; ++i ) { uint64_t selRefVMAddr = baseAddress + selRefsRuntimeOffset + (i * sizeof(PtrTy)); uint64_t selRefTargetVMAddr = vmAddrConverter.convertToVMAddr(*(PtrTy*)(selRefs + (i * sizeof(PtrTy)))); handler(selRefVMAddr, selRefTargetVMAddr, stop); if ( stop ) break; } } else { typedef uint32_t PtrTy; bool stop = false; for ( uint64_t i = 0; i != selRefsCount; ++i ) { uint64_t selRefVMAddr = baseAddress + selRefsRuntimeOffset + (i * sizeof(PtrTy)); uint64_t selRefTargetVMAddr = vmAddrConverter.convertToVMAddr(*(PtrTy*)(selRefs + (i * sizeof(PtrTy)))); handler(selRefVMAddr, selRefTargetVMAddr, stop); if ( stop ) break; } } } void MachOAnalyzer::forEachObjCSelectorReference(Diagnostics& diag, const VMAddrConverter& vmAddrConverter, void (^handler)(uint64_t selRefVMAddr, uint64_t selRefTargetVMAddr, bool& stop)) const { uint64_t selRefsRuntimeOffset; uint64_t selRefsSize; bool foundSection = findObjCDataSection("__objc_selrefs", selRefsRuntimeOffset, selRefsSize); if ( !foundSection ) return; const uint64_t ptrSize = pointerSize(); if ( (selRefsSize % ptrSize) != 0 ) { diag.error("Invalid sel ref section size"); return; } forEachObjCSelectorReference(selRefsRuntimeOffset, selRefsSize / ptrSize, vmAddrConverter, handler); } void MachOAnalyzer::forEachObjCMethodName(void (^handler)(const char* methodName)) const { intptr_t slide = getSlide(); forEachSection(^(const dyld3::MachOAnalyzer::SectionInfo& sectInfo, bool malformedSectionRange, bool& stop) { if ( strcmp(sectInfo.segInfo.segName, "__TEXT") != 0 ) return; if ( strcmp(sectInfo.sectName, "__objc_methname") != 0 ) return; if ( sectInfo.segInfo.isProtected || ( (sectInfo.sectFlags & SECTION_TYPE) != S_CSTRING_LITERALS ) ) { stop = true; return; } if ( malformedSectionRange ) { stop = true; return; } const char* content = (const char*)(sectInfo.sectAddr + slide); uint64_t sectionSize = sectInfo.sectSize; const char* s = (const char*)content; const char* end = s + sectionSize; while ( s < end ) { handler(s); s += strlen(s) + 1; } }); } #if BUILDING_DYLD || BUILDING_UNIT_TESTS void MachOAnalyzer::forEachObjCDuplicateClassToIgnore(void (^handler)(const char* className)) const { const uint32_t pointerSize = this->pointerSize(); uint64_t sectionSize = 0; const void* section = findSectionContent("__DATA", "__objc_dupclass", sectionSize); if ( !section ) return; // Ignore sections which are the wrong size if ( (sectionSize % pointerSize) != 0 ) return; // Copied from objc-abi.h typedef struct _objc_duplicate_class { uint32_t version; uint32_t flags; const char name[64]; } objc_duplicate_class; for (uint64_t offset = 0; offset != sectionSize; offset += pointerSize) { uintptr_t pointerValue = *(uintptr_t*)((uint64_t)section + offset); const objc_duplicate_class* duplicateClass = (const objc_duplicate_class*)pointerValue; handler(duplicateClass->name); } } #endif const MachOAnalyzer::ObjCImageInfo* MachOAnalyzer::objcImageInfo() const { uintptr_t slide = getSlide(); __block bool foundInvalidObjCImageInfo = false; __block const ObjCImageInfo* imageInfo = nullptr; forEachSection(^(const dyld3::MachOAnalyzer::SectionInfo& sectionInfo, bool malformedSectionRange, bool& stop) { if ( strncmp(sectionInfo.segInfo.segName, "__DATA", 6) != 0 ) return; if (strcmp(sectionInfo.sectName, "__objc_imageinfo") != 0) return; if ( malformedSectionRange ) { stop = true; return; } if ( sectionInfo.sectSize != 8 ) { stop = true; return; } imageInfo = (const ObjCImageInfo*)((uintptr_t)sectionInfo.sectAddr + slide); if ( (imageInfo->flags & ObjCImageInfo::dyldPreoptimized) != 0 ) { foundInvalidObjCImageInfo = true; stop = true; return; } stop = true; }); if ( foundInvalidObjCImageInfo ) return nullptr; return imageInfo; } void MachOAnalyzer::forEachWeakDef(Diagnostics& diag, void (^handler)(const char* symbolName, uint64_t imageOffset, bool isFromExportTrie)) const { uint64_t baseAddress = preferredLoadAddress(); forEachGlobalSymbol(diag, ^(const char *symbolName, uint64_t n_value, uint8_t n_type, uint8_t n_sect, uint16_t n_desc, bool &stop) { if ( (n_desc & N_WEAK_DEF) != 0 ) { handler(symbolName, n_value - baseAddress, false); } }); forEachExportedSymbol(diag, ^(const char *symbolName, uint64_t imageOffset, uint64_t flags, uint64_t other, const char *importName, bool &stop) { if ( (flags & EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION ) == 0 ) return; // Skip resolvers and re-exports if ( (flags & EXPORT_SYMBOL_FLAGS_REEXPORT ) != 0 ) return; if ( (flags & EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER ) != 0 ) return; handler(symbolName, imageOffset, true); }); } template<typename P> void MachOAnalyzer::forEachThreadLocalVariableInSection(Diagnostics& diag, const MachOAnalyzer::SectionInfo& sectInfo, void (^handler)(TLV_ResolverPtr tlvThunkAddr, uintptr_t* keyAddr)) const { uintptr_t baseAddress = (uintptr_t)this->preferredLoadAddress(); intptr_t slide = (uintptr_t)this - baseAddress; const uint8_t* content = (uint8_t*)((uintptr_t)sectInfo.sectAddr + slide); unsigned count = (unsigned)(sectInfo.sectSize / sizeof(MachOAnalyzer::FixedSizeTLVThunk<P>)); FixedSizeTLVThunk<P>* slotsStart = (FixedSizeTLVThunk<P>*)content; FixedSizeTLVThunk<P>* slotsEnd = &slotsStart[count]; for (FixedSizeTLVThunk<P>* p=slotsStart; p < slotsEnd; ++p) { handler((TLV_ResolverPtr)&(p->thunk), (uintptr_t*)&(p->key)); } } MachOAnalyzer::TLV_InitialContent MachOAnalyzer::forEachThreadLocalVariable(Diagnostics& diag, void (^handler)(TLV_ResolverPtr tlvThunkAddr, uintptr_t* keyAddr)) const { __block TLV_InitialContent result = { 0, 0 }; // most images don't use thread locals, so quickly skip those if ( !this->hasThreadLocalVariables() ) return result; uintptr_t baseAddress = (uintptr_t)this->preferredLoadAddress(); this->forEachSection(^(const SectionInfo& sectInfo, bool malformedSectionRange, bool& stop) { switch (sectInfo.sectFlags & SECTION_TYPE) { case S_THREAD_LOCAL_VARIABLES: { if (is64()) { forEachThreadLocalVariableInSection<int64_t>(diag, sectInfo, handler); } else { forEachThreadLocalVariableInSection<int32_t>(diag, sectInfo, handler); } } break; case S_THREAD_LOCAL_ZEROFILL: case S_THREAD_LOCAL_REGULAR: if ( result.runtimeOffset == 0 ) { // first of N contiguous TLV template sections, record as if this was only section result.runtimeOffset = sectInfo.sectAddr - baseAddress; result.size = sectInfo.sectSize; } else { // non-first of N contiguous TLV template sections, accumlate values result.size = sectInfo.sectAddr + sectInfo.sectSize - baseAddress - result.runtimeOffset; } break; } }); return result; } void MachOAnalyzer::forEachBindTarget(Diagnostics& diag, bool allowLazyBinds, void (^handler)(const BindTargetInfo& info, bool& stop), void (^overrideHandler)(const BindTargetInfo& info, bool& stop)) const { if ( this->isPreload() ) return; if ( this->hasChainedFixups() ) this->forEachBindTarget_ChainedFixups(diag, handler); else if ( this->hasOpcodeFixups() ) this->forEachBindTarget_Opcodes(diag, allowLazyBinds, handler, overrideHandler); #if SUPPORT_CLASSIC_RELOCS else this->forEachBindTarget_Relocations(diag, handler); #endif } struct WeakBindInfo { uint64_t segIndex : 8, segOffset : 56; }; // walk through all binds, unifying weak, lazy, and regular binds void MachOAnalyzer::forEachBindUnified_Opcodes(Diagnostics& diag, bool allowLazyBinds, void (^handler)(uint64_t runtimeOffset, const BindTargetInfo& targetInfo, bool& stop), void (^overrideHandler)(uint64_t runtimeOffset, const BindTargetInfo& targetInfo, bool& stop)) const { LinkEditInfo leInfo; getLinkEditPointers(diag, leInfo); if ( diag.hasError() ) return; BLOCK_ACCCESSIBLE_ARRAY(SegmentInfo, segmentsInfo, leInfo.layout.lastSegIndex+1); getAllSegmentsInfos(diag, segmentsInfo); if ( diag.hasError() ) return; { __block unsigned targetIndex = 0; __block BindTargetInfo targetInfo; BindDetailedHandler binder = ^(const char* opcodeName, const LinkEditInfo&, const SegmentInfo segments[], bool segIndexSet, bool libraryOrdinalSet, uint32_t dylibCount, int libOrdinal, uint32_t pointerSize, uint8_t segmentIndex, uint64_t segmentOffset, uint8_t type, const char* symbolName, bool weakImport, bool lazyBind, uint64_t addend, bool targetOrAddendChanged, bool& stop) { uint64_t bindVmOffset = segments[segmentIndex].vmAddr + segmentOffset; uint64_t runtimeOffset = bindVmOffset - leInfo.layout.textUnslidVMAddr; if ( targetOrAddendChanged ) { targetInfo.targetIndex = targetIndex++; targetInfo.libOrdinal = libOrdinal; targetInfo.symbolName = symbolName; targetInfo.addend = addend; targetInfo.weakImport = weakImport; targetInfo.lazyBind = lazyBind && allowLazyBinds; } handler(runtimeOffset, targetInfo, stop); }; bool stopped = this->forEachBind_OpcodesRegular(diag, leInfo, segmentsInfo, binder); if ( stopped ) return; stopped = this->forEachBind_OpcodesLazy(diag, leInfo, segmentsInfo, binder); if ( stopped ) return; } // Opcode based weak-binds effectively override other binds/rebases. Process them last // To match dyld2, they are allowed to fail to find a target, in which case the normal rebase/bind will // not be overridden. { __block unsigned weakTargetIndex = 0; __block BindTargetInfo weakTargetInfo; BindDetailedHandler weakBinder = ^(const char* opcodeName, const LinkEditInfo&, const SegmentInfo segments[], bool segIndexSet, bool libraryOrdinalSet, uint32_t dylibCount, int libOrdinal, uint32_t pointerSize, uint8_t segmentIndex, uint64_t segmentOffset, uint8_t type, const char* symbolName, bool weakImport, bool lazyBind, uint64_t addend, bool targetOrAddendChanged, bool& stop) { uint64_t bindVmOffset = segmentsInfo[segmentIndex].vmAddr + segmentOffset; uint64_t runtimeOffset = bindVmOffset - leInfo.layout.textUnslidVMAddr; if ( (symbolName != weakTargetInfo.symbolName) || (strcmp(symbolName, weakTargetInfo.symbolName) != 0) || (weakTargetInfo.addend != addend) ) { weakTargetInfo.targetIndex = weakTargetIndex++; weakTargetInfo.libOrdinal = BIND_SPECIAL_DYLIB_WEAK_LOOKUP; weakTargetInfo.symbolName = symbolName; weakTargetInfo.addend = addend; weakTargetInfo.weakImport = false; weakTargetInfo.lazyBind = false; } overrideHandler(runtimeOffset, weakTargetInfo, stop); }; auto strongHandler = ^(const char* strongName) { }; this->forEachBind_OpcodesWeak(diag, leInfo, segmentsInfo, weakBinder, strongHandler); } } void MachOAnalyzer::forEachBindTarget_Opcodes(Diagnostics& diag, bool allowLazyBinds, void (^handler)(const BindTargetInfo& info, bool& stop), void (^overrideHandler)(const BindTargetInfo& info, bool& stop)) const { __block unsigned lastTargetIndex = -1; __block unsigned lastWeakBindTargetIndex = -1; this->forEachBindUnified_Opcodes(diag, allowLazyBinds, ^(uint64_t runtimeOffset, const BindTargetInfo& targetInfo, bool& stop) { // Regular/lazy binds if ( lastTargetIndex != targetInfo.targetIndex) { handler(targetInfo, stop); lastTargetIndex = targetInfo.targetIndex; } }, ^(uint64_t runtimeOffset, const BindTargetInfo& targetInfo, bool& stop) { // Weak binds if ( lastWeakBindTargetIndex != targetInfo.targetIndex) { overrideHandler(targetInfo, stop); lastWeakBindTargetIndex = targetInfo.targetIndex; } }); } void MachOAnalyzer::forEachBindTarget_ChainedFixups(Diagnostics& diag, void (^handler)(const BindTargetInfo& info, bool& stop)) const { __block unsigned targetIndex = 0; this->forEachChainedFixupTarget(diag, ^(int libOrdinal, const char* symbolName, uint64_t addend, bool weakImport, bool& stop) { BindTargetInfo info; info.targetIndex = targetIndex; info.libOrdinal = libOrdinal; info.symbolName = symbolName; info.addend = addend; info.weakImport = weakImport; info.lazyBind = false; handler(info, stop); ++targetIndex; }); // The C++ spec says main executables can define non-weak functions which override weak-defs in dylibs // This happens automatically for anything bound at launch, but the dyld cache is pre-bound so we need // to patch any binds that are overridden by this non-weak in the main executable. if ( diag.noError() && this->isMainExecutable() && this->hasWeakDefs() ) { MachOAnalyzer::forEachTreatAsWeakDef(^(const char* symbolName) { BindTargetInfo info; info.targetIndex = targetIndex; info.libOrdinal = BIND_SPECIAL_DYLIB_WEAK_LOOKUP; info.symbolName = symbolName; info.addend = 0; info.weakImport = false; info.lazyBind = false; bool stop = false; handler(info, stop); ++targetIndex; }); } } #if SUPPORT_CLASSIC_RELOCS // old binary, walk external relocations and indirect symbol table void MachOAnalyzer::forEachBindTarget_Relocations(Diagnostics& diag, void (^handler)(const BindTargetInfo& info, bool& stop)) const { LinkEditInfo leInfo; getLinkEditPointers(diag, leInfo); if ( diag.hasError() ) return; BLOCK_ACCCESSIBLE_ARRAY(SegmentInfo, segmentsInfo, leInfo.layout.lastSegIndex+1); getAllSegmentsInfos(diag, segmentsInfo); if ( diag.hasError() ) return; __block unsigned targetIndex = 0; this->forEachBind_Relocations(diag, leInfo, segmentsInfo, true, ^(const char* opcodeName, const LinkEditInfo&, const SegmentInfo segments[], bool segIndexSet, bool libraryOrdinalSet, uint32_t dylibCount, int libOrdinal, uint32_t pointerSize, uint8_t segmentIndex, uint64_t segmentOffset, uint8_t type, const char* symbolName, bool weakImport, bool lazyBind, uint64_t addend, bool targetOrAddendChanged, bool& stop) { if ( targetOrAddendChanged ) { BindTargetInfo info; info.targetIndex = targetIndex; info.libOrdinal = libOrdinal; info.symbolName = symbolName; info.addend = addend; info.weakImport = weakImport; info.lazyBind = lazyBind; handler(info, stop); ++targetIndex; } }); } #endif // SUPPORT_CLASSIC_RELOCS void MachOAnalyzer::forEachBindLocation_Relocations(Diagnostics& diag, void (^handler)(uint64_t runtimeOffset, unsigned targetIndex, bool& stop)) const { LinkEditInfo leInfo; getLinkEditPointers(diag, leInfo); if ( diag.hasError() ) return; BLOCK_ACCCESSIBLE_ARRAY(SegmentInfo, segmentsInfo, leInfo.layout.lastSegIndex+1); getAllSegmentsInfos(diag, segmentsInfo); if ( diag.hasError() ) return; __block int targetIndex = -1; this->forEachBind_Relocations(diag, leInfo, segmentsInfo, false, ^(const char* opcodeName, const LinkEditInfo&, const SegmentInfo segments[], bool segIndexSet, bool libraryOrdinalSet, uint32_t dylibCount, int libOrdinal, uint32_t pointerSize, uint8_t segmentIndex, uint64_t segmentOffset, uint8_t type, const char* symbolName, bool weakImport, bool lazyBind, uint64_t addend, bool targetOrAddendChanged, bool& stop) { if ( targetOrAddendChanged ) ++targetIndex; uint64_t bindVmOffset = segments[segmentIndex].vmAddr + segmentOffset; uint64_t runtimeOffset = bindVmOffset - leInfo.layout.textUnslidVMAddr; handler(runtimeOffset, targetIndex, stop); }); } #if SUPPORT_CLASSIC_RELOCS bool MachOAnalyzer::forEachBind_Relocations(Diagnostics& diag, const LinkEditInfo& leInfo, const SegmentInfo segmentsInfo[], bool supportPrivateExternsWorkaround, BindDetailedHandler handler) const { // Firmare binaries won't have a dynSymTab if ( leInfo.dynSymTab == nullptr ) return false; const uint64_t relocsStartAddress = externalRelocBaseAddress(segmentsInfo, leInfo.layout.linkeditSegIndex); const relocation_info* const relocsStart = (relocation_info*)getLinkEditContent(leInfo.layout, leInfo.dynSymTab->extreloff); const relocation_info* const relocsEnd = &relocsStart[leInfo.dynSymTab->nextrel]; bool is64Bit = is64() ; const uint32_t ptrSize = pointerSize(); const uint32_t dylibCount = dependentDylibCount(); const uint8_t relocSize = (is64Bit ? 3 : 2); const void* symbolTable = getLinkEditContent(leInfo.layout, leInfo.symTab->symoff); const struct nlist_64* symbols64 = (nlist_64*)symbolTable; const struct nlist* symbols32 = (struct nlist*)symbolTable; const char* stringPool = (char*)getLinkEditContent(leInfo.layout, leInfo.symTab->stroff); uint32_t symCount = leInfo.symTab->nsyms; uint32_t poolSize = leInfo.symTab->strsize; uint32_t lastSymIndx = -1; uint64_t lastAddend = 0; bool stop = false; for (const relocation_info* reloc=relocsStart; (reloc < relocsEnd) && !stop; ++reloc) { bool isBranch = false; #if BUILDING_APP_CACHE_UTIL || BUILDING_DYLDINFO if ( isKextBundle() ) { // kext's may have other kinds of relocations, eg, branch relocs. Skip them if ( isArch("x86_64") || isArch("x86_64h") ) { if ( reloc->r_type == X86_64_RELOC_BRANCH ) { if ( reloc->r_length != 2 ) { diag.error("external relocation has wrong r_length"); break; } if ( reloc->r_pcrel != true ) { diag.error("external relocation should be pcrel"); break; } isBranch = true; } } } #endif if ( !isBranch ) { if ( reloc->r_length != relocSize ) { diag.error("external relocation has wrong r_length"); break; } if ( reloc->r_type != 0 ) { // 0 == X86_64_RELOC_UNSIGNED == GENERIC_RELOC_VANILLA == ARM64_RELOC_UNSIGNED diag.error("external relocation has wrong r_type"); break; } } uint32_t segIndex = 0; uint64_t segOffset = 0; if ( segIndexAndOffsetForAddress(relocsStartAddress+reloc->r_address, segmentsInfo, leInfo.layout.linkeditSegIndex, segIndex, segOffset) ) { uint32_t symbolIndex = reloc->r_symbolnum; if ( symbolIndex > symCount ) { diag.error("external relocation has out of range r_symbolnum"); break; } else { uint32_t strOffset = is64Bit ? symbols64[symbolIndex].n_un.n_strx : symbols32[symbolIndex].n_un.n_strx; uint16_t n_desc = is64Bit ? symbols64[symbolIndex].n_desc : symbols32[symbolIndex].n_desc; uint8_t n_type = is64Bit ? symbols64[symbolIndex].n_type : symbols32[symbolIndex].n_type; uint32_t libOrdinal = libOrdinalFromDesc(n_desc); if ( strOffset >= poolSize ) { diag.error("external relocation has r_symbolnum=%d which has out of range n_strx", symbolIndex); break; } else { const char* symbolName = stringPool + strOffset; bool weakImport = (n_desc & N_WEAK_REF); const uint8_t* content = (uint8_t*)this + segmentsInfo[segIndex].vmAddr - leInfo.layout.textUnslidVMAddr + segOffset; uint64_t addend = (reloc->r_length == 3) ? *((uint64_t*)content) : *((uint32_t*)content); // Handle defined weak def symbols which need to get a special ordinal if ( ((n_type & N_TYPE) == N_SECT) && ((n_type & N_EXT) != 0) && ((n_desc & N_WEAK_DEF) != 0) ) libOrdinal = BIND_SPECIAL_DYLIB_WEAK_LOOKUP; uint8_t type = isBranch ? BIND_TYPE_TEXT_PCREL32 : BIND_TYPE_POINTER; bool targetOrAddendChanged = (lastSymIndx != symbolIndex) || (lastAddend != addend); handler("external relocation", leInfo, segmentsInfo, true, true, dylibCount, libOrdinal, ptrSize, segIndex, segOffset, type, symbolName, weakImport, false, addend, targetOrAddendChanged, stop); lastSymIndx = symbolIndex; lastAddend = addend; } } } else { diag.error("local relocation has out of range r_address"); break; } } // then process indirect symbols forEachIndirectPointer(diag, supportPrivateExternsWorkaround, ^(uint64_t address, bool bind, int bindLibOrdinal, const char* bindSymbolName, bool bindWeakImport, bool bindLazy, bool selfModifyingStub, bool& indStop) { if ( !bind ) return; uint32_t segIndex = 0; uint64_t segOffset = 0; if ( segIndexAndOffsetForAddress(address, segmentsInfo, leInfo.layout.linkeditSegIndex, segIndex, segOffset) ) { handler("indirect symbol", leInfo, segmentsInfo, true, true, dylibCount, bindLibOrdinal, ptrSize, segIndex, segOffset, BIND_TYPE_POINTER, bindSymbolName, bindWeakImport, bindLazy, 0, true, indStop); } else { diag.error("indirect symbol has out of range address"); indStop = true; } }); return false; } #endif void MachOAnalyzer::forEachBindLocation_Opcodes(Diagnostics& diag, void (^handler)(uint64_t runtimeOffset, unsigned targetIndex, bool& stop), void (^overrideHandler)(uint64_t runtimeOffset, unsigned overrideBindTargetIndex, bool& stop)) const { this->forEachBindUnified_Opcodes(diag, false, ^(uint64_t runtimeOffset, const BindTargetInfo& targetInfo, bool& stop) { handler(runtimeOffset, targetInfo.targetIndex, stop); }, ^(uint64_t runtimeOffset, const BindTargetInfo& weakTargetInfo, bool& stop) { overrideHandler(runtimeOffset, weakTargetInfo.targetIndex, stop); }); } bool MachOAnalyzer::forEachBind_OpcodesLazy(Diagnostics& diag, const LinkEditInfo& leInfo, const SegmentInfo segmentsInfo[], BindDetailedHandler handler) const { if ( (leInfo.dyldInfo == nullptr) || (leInfo.dyldInfo->lazy_bind_size == 0) ) return false; uint32_t lazyDoneCount = 0; uint32_t lazyBindCount = 0; const uint32_t ptrSize = this->pointerSize(); bool stop = false; const uint32_t dylibCount = dependentDylibCount(); const uint8_t* p = getLinkEditContent(leInfo.layout, leInfo.dyldInfo->lazy_bind_off); const uint8_t* end = p + leInfo.dyldInfo->lazy_bind_size; uint8_t type = BIND_TYPE_POINTER; uint64_t segmentOffset = 0; uint8_t segmentIndex = 0; const char* symbolName = NULL; int libraryOrdinal = 0; bool segIndexSet = false; bool libraryOrdinalSet = false; int64_t addend = 0; bool weakImport = false; while ( !stop && diag.noError() && (p < end) ) { uint8_t immediate = *p & BIND_IMMEDIATE_MASK; uint8_t opcode = *p & BIND_OPCODE_MASK; ++p; switch (opcode) { case BIND_OPCODE_DONE: // this opcode marks the end of each lazy pointer binding ++lazyDoneCount; break; case BIND_OPCODE_SET_DYLIB_ORDINAL_IMM: libraryOrdinal = immediate; libraryOrdinalSet = true; break; case BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB: libraryOrdinal = (int)read_uleb128(diag, p, end); libraryOrdinalSet = true; break; case BIND_OPCODE_SET_DYLIB_SPECIAL_IMM: // the special ordinals are negative numbers if ( immediate == 0 ) libraryOrdinal = 0; else { int8_t signExtended = BIND_OPCODE_MASK | immediate; libraryOrdinal = signExtended; } libraryOrdinalSet = true; break; case BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM: weakImport = ( (immediate & BIND_SYMBOL_FLAGS_WEAK_IMPORT) != 0 ); symbolName = (char*)p; while (*p != '\0') ++p; ++p; break; case BIND_OPCODE_SET_ADDEND_SLEB: addend = read_sleb128(diag, p, end); break; case BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB: segmentIndex = immediate; segmentOffset = read_uleb128(diag, p, end); segIndexSet = true; break; case BIND_OPCODE_DO_BIND: handler("BIND_OPCODE_DO_BIND", leInfo, segmentsInfo, segIndexSet, libraryOrdinalSet, dylibCount, libraryOrdinal, ptrSize, segmentIndex, segmentOffset, type, symbolName, weakImport, true, addend, true, stop); segmentOffset += ptrSize; ++lazyBindCount; break; case BIND_OPCODE_SET_TYPE_IMM: case BIND_OPCODE_ADD_ADDR_ULEB: case BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB: case BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED: case BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB: default: diag.error("bad lazy bind opcode 0x%02X", opcode); break; } } if ( lazyDoneCount > lazyBindCount+7 ) { // diag.error("lazy bind opcodes missing binds"); } return stop; } bool MachOAnalyzer::forEachBind_OpcodesWeak(Diagnostics& diag, const LinkEditInfo& leInfo, const SegmentInfo segmentsInfo[], BindDetailedHandler handler, void (^strongHandler)(const char* symbolName)) const { if ( (leInfo.dyldInfo == nullptr) || (leInfo.dyldInfo->weak_bind_size == 0) ) return false; const uint32_t ptrSize = this->pointerSize(); bool stop = false; const uint32_t dylibCount = dependentDylibCount(); const uint8_t* p = getLinkEditContent(leInfo.layout, leInfo.dyldInfo->weak_bind_off); const uint8_t* end = p + leInfo.dyldInfo->weak_bind_size; uint8_t type = BIND_TYPE_POINTER; uint64_t segmentOffset = 0; uint8_t segmentIndex = 0; const char* symbolName = NULL; int libraryOrdinal = BIND_SPECIAL_DYLIB_WEAK_LOOKUP; bool segIndexSet = false; bool libraryOrdinalSet = true; int64_t addend = 0; bool weakImport = false; bool targetOrAddendChanged = true; bool done = false; uint64_t count; uint64_t skip; while ( !stop && diag.noError() && (p < end) && !done ) { uint8_t immediate = *p & BIND_IMMEDIATE_MASK; uint8_t opcode = *p & BIND_OPCODE_MASK; ++p; switch (opcode) { case BIND_OPCODE_DONE: done = true; break; case BIND_OPCODE_SET_DYLIB_ORDINAL_IMM: case BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB: case BIND_OPCODE_SET_DYLIB_SPECIAL_IMM: diag.error("unexpected dylib ordinal in weak_bind"); break; case BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM: weakImport = ( (immediate & BIND_SYMBOL_FLAGS_WEAK_IMPORT) != 0 ); symbolName = (char*)p; while (*p != '\0') ++p; ++p; if ( immediate & BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION ) { strongHandler(symbolName); } targetOrAddendChanged = true; break; case BIND_OPCODE_SET_TYPE_IMM: type = immediate; break; case BIND_OPCODE_SET_ADDEND_SLEB: addend = read_sleb128(diag, p, end); targetOrAddendChanged = true; break; case BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB: segmentIndex = immediate; segmentOffset = read_uleb128(diag, p, end); segIndexSet = true; break; case BIND_OPCODE_ADD_ADDR_ULEB: segmentOffset += read_uleb128(diag, p, end); break; case BIND_OPCODE_DO_BIND: handler("BIND_OPCODE_DO_BIND", leInfo, segmentsInfo, segIndexSet, libraryOrdinalSet, dylibCount, libraryOrdinal, ptrSize, segmentIndex, segmentOffset, type, symbolName, weakImport, false, addend, targetOrAddendChanged, stop); segmentOffset += ptrSize; targetOrAddendChanged = false; break; case BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB: handler("BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB", leInfo, segmentsInfo, segIndexSet, libraryOrdinalSet, dylibCount, libraryOrdinal, ptrSize, segmentIndex, segmentOffset, type, symbolName, weakImport, false, addend, targetOrAddendChanged, stop); segmentOffset += read_uleb128(diag, p, end) + ptrSize; targetOrAddendChanged = false; break; case BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED: handler("BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED", leInfo, segmentsInfo, segIndexSet, libraryOrdinalSet, dylibCount, libraryOrdinal, ptrSize, segmentIndex, segmentOffset, type, symbolName, weakImport, false, addend, targetOrAddendChanged, stop); segmentOffset += immediate*ptrSize + ptrSize; targetOrAddendChanged = false; break; case BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB: count = read_uleb128(diag, p, end); skip = read_uleb128(diag, p, end); for (uint32_t i=0; i < count; ++i) { handler("BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB", leInfo, segmentsInfo, segIndexSet, libraryOrdinalSet, dylibCount, libraryOrdinal, ptrSize, segmentIndex, segmentOffset, type, symbolName, weakImport, false, addend, targetOrAddendChanged, stop); segmentOffset += skip + ptrSize; targetOrAddendChanged = false; if ( stop ) break; } break; default: diag.error("bad bind opcode 0x%02X", *p); } } return stop; } bool MachOAnalyzer::forEachBind_OpcodesRegular(Diagnostics& diag, const LinkEditInfo& leInfo, const SegmentInfo segmentsInfo[], BindDetailedHandler handler) const { if ( (leInfo.dyldInfo == nullptr) || (leInfo.dyldInfo->bind_size == 0) ) return false; const uint32_t ptrSize = this->pointerSize(); bool stop = false; const uint32_t dylibCount = dependentDylibCount(); const uint8_t* p = getLinkEditContent(leInfo.layout, leInfo.dyldInfo->bind_off); const uint8_t* end = p + leInfo.dyldInfo->bind_size; uint8_t type = 0; uint64_t segmentOffset = 0; uint8_t segmentIndex = 0; const char* symbolName = NULL; int libraryOrdinal = 0; bool segIndexSet = false; bool libraryOrdinalSet = false; bool targetOrAddendChanged = false; bool done = false; int64_t addend = 0; uint64_t count; uint64_t skip; bool weakImport = false; while ( !stop && diag.noError() && (p < end) && !done ) { uint8_t immediate = *p & BIND_IMMEDIATE_MASK; uint8_t opcode = *p & BIND_OPCODE_MASK; ++p; switch (opcode) { case BIND_OPCODE_DONE: done = true; break; case BIND_OPCODE_SET_DYLIB_ORDINAL_IMM: libraryOrdinal = immediate; libraryOrdinalSet = true; break; case BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB: libraryOrdinal = (int)read_uleb128(diag, p, end); libraryOrdinalSet = true; break; case BIND_OPCODE_SET_DYLIB_SPECIAL_IMM: // the special ordinals are negative numbers if ( immediate == 0 ) libraryOrdinal = 0; else { int8_t signExtended = BIND_OPCODE_MASK | immediate; libraryOrdinal = signExtended; } libraryOrdinalSet = true; break; case BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM: weakImport = ( (immediate & BIND_SYMBOL_FLAGS_WEAK_IMPORT) != 0 ); symbolName = (char*)p; while (*p != '\0') ++p; ++p; targetOrAddendChanged = true; break; case BIND_OPCODE_SET_TYPE_IMM: type = immediate; break; case BIND_OPCODE_SET_ADDEND_SLEB: addend = read_sleb128(diag, p, end); targetOrAddendChanged = true; break; case BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB: segmentIndex = immediate; segmentOffset = read_uleb128(diag, p, end); segIndexSet = true; break; case BIND_OPCODE_ADD_ADDR_ULEB: segmentOffset += read_uleb128(diag, p, end); break; case BIND_OPCODE_DO_BIND: handler("BIND_OPCODE_DO_BIND", leInfo, segmentsInfo, segIndexSet, libraryOrdinalSet, dylibCount, libraryOrdinal, ptrSize, segmentIndex, segmentOffset, type, symbolName, weakImport, false, addend, targetOrAddendChanged, stop); segmentOffset += ptrSize; targetOrAddendChanged = false; break; case BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB: handler("BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB", leInfo, segmentsInfo, segIndexSet, libraryOrdinalSet, dylibCount, libraryOrdinal, ptrSize, segmentIndex, segmentOffset, type, symbolName, weakImport, false, addend, targetOrAddendChanged, stop); segmentOffset += read_uleb128(diag, p, end) + ptrSize; targetOrAddendChanged = false; break; case BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED: handler("BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED", leInfo, segmentsInfo, segIndexSet, libraryOrdinalSet, dylibCount, libraryOrdinal, ptrSize, segmentIndex, segmentOffset, type, symbolName, weakImport, false, addend, targetOrAddendChanged, stop); segmentOffset += immediate*ptrSize + ptrSize; targetOrAddendChanged = false; break; case BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB: count = read_uleb128(diag, p, end); skip = read_uleb128(diag, p, end); for (uint32_t i=0; i < count; ++i) { handler("BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB", leInfo, segmentsInfo, segIndexSet, libraryOrdinalSet, dylibCount, libraryOrdinal, ptrSize, segmentIndex, segmentOffset, type, symbolName, weakImport, false, addend, targetOrAddendChanged, stop); segmentOffset += skip + ptrSize; targetOrAddendChanged = false; if ( stop ) break; } break; default: diag.error("bad bind opcode 0x%02X", *p); } } return stop; } bool MachOAnalyzer::forEachRebaseLocation_Opcodes(Diagnostics& diag, void (^handler)(uint64_t runtimeOffset, bool& stop)) const { LinkEditInfo leInfo; getLinkEditPointers(diag, leInfo); if ( diag.hasError() ) return false; BLOCK_ACCCESSIBLE_ARRAY(SegmentInfo, segmentsInfo, leInfo.layout.lastSegIndex+1); getAllSegmentsInfos(diag, segmentsInfo); if ( diag.hasError() ) return false; return this->forEachRebase_Opcodes(diag, leInfo, segmentsInfo, ^(const char* opcodeName, const LinkEditInfo& rleInfo, const SegmentInfo segments[], bool segIndexSet, uint32_t pointerSize, uint8_t segmentIndex, uint64_t segmentOffset, Rebase kind, bool& stop) { uint64_t rebaseVmOffset = segments[segmentIndex].vmAddr + segmentOffset; uint64_t runtimeOffset = rebaseVmOffset - leInfo.layout.textUnslidVMAddr; handler(runtimeOffset, stop); }); } bool MachOAnalyzer::forEachRebase_Opcodes(Diagnostics& diag, const LinkEditInfo& leInfo, const SegmentInfo segmentsInfo[], RebaseDetailHandler handler) const { const Rebase pointerRebaseKind = is64() ? Rebase::pointer64 : Rebase::pointer32; assert(leInfo.dyldInfo != nullptr); const uint8_t* const start = getLinkEditContent(leInfo.layout, leInfo.dyldInfo->rebase_off); const uint8_t* const end = start + leInfo.dyldInfo->rebase_size; const uint8_t* p = start; const uint32_t ptrSize = pointerSize(); Rebase kind = Rebase::unknown; int segIndex = 0; uint64_t segOffset = 0; uint64_t count; uint64_t skip; bool segIndexSet = false; bool stop = false; while ( !stop && diag.noError() && (p < end) ) { uint8_t immediate = *p & REBASE_IMMEDIATE_MASK; uint8_t opcode = *p & REBASE_OPCODE_MASK; ++p; switch (opcode) { case REBASE_OPCODE_DONE: // Allow some padding, in case rebases were somehow aligned to 16-bytes in size if ( (end - p) > 15 ) diag.error("rebase opcodes terminated early at offset %d of %d", (int)(p-start), (int)(end-start)); stop = true; break; case REBASE_OPCODE_SET_TYPE_IMM: switch ( immediate ) { case REBASE_TYPE_POINTER: kind = pointerRebaseKind; break; case REBASE_TYPE_TEXT_ABSOLUTE32: kind = Rebase::textAbsolute32; break; case REBASE_TYPE_TEXT_PCREL32: kind = Rebase::textPCrel32; break; default: kind = Rebase::unknown; break; } break; case REBASE_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB: segIndex = immediate; segOffset = read_uleb128(diag, p, end); segIndexSet = true; break; case REBASE_OPCODE_ADD_ADDR_ULEB: segOffset += read_uleb128(diag, p, end); break; case REBASE_OPCODE_ADD_ADDR_IMM_SCALED: segOffset += immediate*ptrSize; break; case REBASE_OPCODE_DO_REBASE_IMM_TIMES: for (int i=0; i < immediate; ++i) { handler("REBASE_OPCODE_DO_REBASE_IMM_TIMES", leInfo, segmentsInfo, segIndexSet, ptrSize, segIndex, segOffset, kind, stop); segOffset += ptrSize; if ( stop ) break; } break; case REBASE_OPCODE_DO_REBASE_ULEB_TIMES: count = read_uleb128(diag, p, end); for (uint32_t i=0; i < count; ++i) { handler("REBASE_OPCODE_DO_REBASE_ULEB_TIMES", leInfo, segmentsInfo, segIndexSet, ptrSize, segIndex, segOffset, kind, stop); segOffset += ptrSize; if ( stop ) break; } break; case REBASE_OPCODE_DO_REBASE_ADD_ADDR_ULEB: handler("REBASE_OPCODE_DO_REBASE_ADD_ADDR_ULEB", leInfo, segmentsInfo, segIndexSet, ptrSize, segIndex, segOffset, kind, stop); segOffset += read_uleb128(diag, p, end) + ptrSize; break; case REBASE_OPCODE_DO_REBASE_ULEB_TIMES_SKIPPING_ULEB: count = read_uleb128(diag, p, end); if ( diag.hasError() ) break; skip = read_uleb128(diag, p, end); for (uint32_t i=0; i < count; ++i) { handler("REBASE_OPCODE_DO_REBASE_ULEB_TIMES_SKIPPING_ULEB", leInfo, segmentsInfo, segIndexSet, ptrSize, segIndex, segOffset, kind, stop); segOffset += skip + ptrSize; if ( stop ) break; } break; default: diag.error("unknown rebase opcode 0x%02X", opcode); } } return stop; } #if SUPPORT_CLASSIC_RELOCS bool MachOAnalyzer::forEachRebaseLocation_Relocations(Diagnostics& diag, void (^handler)(uint64_t runtimeOffset, bool& stop)) const { LinkEditInfo leInfo; getLinkEditPointers(diag, leInfo); if ( diag.hasError() ) return false; BLOCK_ACCCESSIBLE_ARRAY(SegmentInfo, segmentsInfo, leInfo.layout.lastSegIndex+1); getAllSegmentsInfos(diag, segmentsInfo); if ( diag.hasError() ) return false; return this->forEachRebase_Relocations(diag, leInfo, segmentsInfo, ^(const char* opcodeName, const LinkEditInfo& rleInfo, const SegmentInfo segments[], bool segIndexSet, uint32_t pointerSize, uint8_t segmentIndex, uint64_t segmentOffset, Rebase kind, bool& stop) { uint64_t rebaseVmOffset = segments[segmentIndex].vmAddr + segmentOffset; uint64_t runtimeOffset = rebaseVmOffset - leInfo.layout.textUnslidVMAddr; handler(runtimeOffset, stop); }); } // relocs are normally sorted, we don't want to use qsort because it may switch to mergesort which uses malloc void MachOAnalyzer::sortRelocations(Array<relocation_info>& relocs) const { // The kernel linker has malloc, and old-style relocations are extremely common. So use qsort #if BUILDING_APP_CACHE_UTIL || BUILDING_DYLDINFO ::qsort(&relocs[0], (size_t)relocs.count(), sizeof(relocation_info), [](const void* l, const void* r) -> int { if ( ((relocation_info*)l)->r_address < ((relocation_info*)r)->r_address ) return -1; else return 1; }); #else uint64_t count = relocs.count(); for (uint64_t i=0; i < count-1; ++i) { bool done = true; for (uint64_t j=0; j < count-i-1; ++j) { if ( relocs[j].r_address > relocs[j+1].r_address ) { relocation_info temp = relocs[j]; relocs[j] = relocs[j+1]; relocs[j+1] = temp; done = false; } } if ( done ) break; } #endif } bool MachOAnalyzer::forEachRebase_Relocations(Diagnostics& diag, const LinkEditInfo& leInfo, const SegmentInfo segmentsInfo[], RebaseDetailHandler handler) const { // old binary, walk relocations const uint64_t relocsStartAddress = localRelocBaseAddress(segmentsInfo, leInfo.layout.linkeditSegIndex); const relocation_info* const relocsStart = (relocation_info*)getLinkEditContent(leInfo.layout, leInfo.dynSymTab->locreloff); const relocation_info* const relocsEnd = &relocsStart[leInfo.dynSymTab->nlocrel]; const uint8_t relocSize = (is64() ? 3 : 2); const uint8_t ptrSize = pointerSize(); bool stop = false; STACK_ALLOC_OVERFLOW_SAFE_ARRAY(relocation_info, relocs, 2048); for (const relocation_info* reloc=relocsStart; (reloc < relocsEnd) && !stop; ++reloc) { if ( reloc->r_length != relocSize ) { bool shouldEmitError = true; #if BUILDING_APP_CACHE_UTIL || BUILDING_DYLDINFO if ( usesClassicRelocationsInKernelCollection() && (reloc->r_length == 2) && (relocSize == 3) ) shouldEmitError = false; #endif if ( shouldEmitError ) { diag.error("local relocation has wrong r_length"); break; } } if ( reloc->r_type != 0 ) { // 0 == X86_64_RELOC_UNSIGNED == GENERIC_RELOC_VANILLA == ARM64_RELOC_UNSIGNED diag.error("local relocation has wrong r_type"); break; } relocs.push_back(*reloc); } if ( !relocs.empty() ) { sortRelocations(relocs); for (relocation_info reloc : relocs) { uint32_t addrOff = reloc.r_address; uint32_t segIndex = 0; uint64_t segOffset = 0; uint64_t addr = 0; #if BUILDING_APP_CACHE_UTIL || BUILDING_DYLDINFO // xnu for x86_64 has __HIB mapped before __DATA, so offsets appear to be // negative if ( isStaticExecutable() || isFileSet() ) { addr = relocsStartAddress + (int32_t)addrOff; } else { addr = relocsStartAddress + addrOff; } #else addr = relocsStartAddress + addrOff; #endif if ( segIndexAndOffsetForAddress(addr, segmentsInfo, leInfo.layout.linkeditSegIndex, segIndex, segOffset) ) { Rebase kind = (reloc.r_length == 2) ? Rebase::pointer32 : Rebase::pointer64; if ( this->cputype == CPU_TYPE_I386 ) { if ( segmentsInfo[segIndex].executable() ) kind = Rebase::textAbsolute32; } handler("local relocation", leInfo, segmentsInfo, true, ptrSize, segIndex, segOffset, kind, stop); } else { diag.error("local relocation has out of range r_address"); break; } } } // then process indirect symbols const Rebase pointerRebaseKind = is64() ? Rebase::pointer64 : Rebase::pointer32; forEachIndirectPointer(diag, false, ^(uint64_t address, bool bind, int bindLibOrdinal, const char* bindSymbolName, bool bindWeakImport, bool bindLazy, bool selfModifyingStub, bool& indStop) { if ( bind ) return; uint32_t segIndex = 0; uint64_t segOffset = 0; if ( segIndexAndOffsetForAddress(address, segmentsInfo, leInfo.layout.linkeditSegIndex, segIndex, segOffset) ) { handler("local relocation", leInfo, segmentsInfo, true, ptrSize, segIndex, segOffset, pointerRebaseKind, indStop); } else { diag.error("local relocation has out of range r_address"); indStop = true; } }); return stop; } #endif // SUPPORT_CLASSIC_RELOCS bool MachOAnalyzer::getLinkeditLayout(Diagnostics& diag, uint64_t linkeditFileOffset, const uint8_t* linkeditStartAddr, mach_o::LinkeditLayout& layout) const { // Note, in VM layout all linkedit offsets are adjusted from file offsets. // It is essential no-one calls this on an object in file layout. It must be in VM layout auto getLinkEditContent = [&](uint32_t fileOffset) { uint64_t offsetInLinkedit = fileOffset - linkeditFileOffset; return linkeditStartAddr + offsetInLinkedit; }; // FIXME: Other load commands this->forEachLoadCommand(diag, ^(const load_command *cmd, bool &stop) { switch ( cmd->cmd ) { case LC_SYMTAB: { const symtab_command* symTabCmd = (const symtab_command*)cmd; // Record that we found a LC_SYMTAB layout.hasSymTab = true; // NList uint64_t nlistEntrySize = this->is64() ? sizeof(struct nlist_64) : sizeof(struct nlist); layout.symbolTable.fileOffset = symTabCmd->symoff; layout.symbolTable.buffer = getLinkEditContent(symTabCmd->symoff); layout.symbolTable.bufferSize = (uint32_t)(symTabCmd->nsyms * nlistEntrySize); layout.symbolTable.entryCount = symTabCmd->nsyms; layout.symbolTable.hasLinkedit = true; // Symbol strings layout.symbolStrings.fileOffset = symTabCmd->stroff; layout.symbolStrings.buffer = getLinkEditContent(symTabCmd->stroff); layout.symbolStrings.bufferSize = symTabCmd->strsize; layout.symbolStrings.hasLinkedit = true; break; } case LC_DYSYMTAB: { const dysymtab_command* dynSymTabCmd = (const dysymtab_command*)cmd; // Record that we found a LC_DYSYMTAB layout.hasDynSymTab = true; // Local relocs layout.localRelocs.fileOffset = dynSymTabCmd->locreloff; layout.localRelocs.buffer = getLinkEditContent(dynSymTabCmd->locreloff); layout.localRelocs.bufferSize = 0; // Use entryCount instead layout.localRelocs.entryIndex = 0; // Use buffer instead layout.localRelocs.entryCount = dynSymTabCmd->nlocrel; layout.localRelocs.hasLinkedit = true; // Extern relocs layout.externRelocs.fileOffset = dynSymTabCmd->extreloff; layout.externRelocs.buffer = getLinkEditContent(dynSymTabCmd->extreloff); layout.externRelocs.bufferSize = 0; // Use entryCount instead layout.externRelocs.entryIndex = 0; // Use buffer instead layout.externRelocs.entryCount = dynSymTabCmd->nextrel; layout.externRelocs.hasLinkedit = true; // Indirect symbol table layout.indirectSymbolTable.fileOffset = dynSymTabCmd->indirectsymoff; layout.indirectSymbolTable.buffer = getLinkEditContent(dynSymTabCmd->indirectsymoff); layout.indirectSymbolTable.bufferSize = 0; // Use entryCount instead layout.indirectSymbolTable.entryIndex = 0; // Use buffer instead layout.indirectSymbolTable.entryCount = dynSymTabCmd->nindirectsyms; layout.indirectSymbolTable.hasLinkedit = true; // Locals layout.localSymbolTable.fileOffset = 0; // unused layout.localSymbolTable.buffer = nullptr; // Use entryIndex instead layout.localSymbolTable.bufferSize = 0; // Use entryCount instead layout.localSymbolTable.entryIndex = dynSymTabCmd->ilocalsym; layout.localSymbolTable.entryCount = dynSymTabCmd->nlocalsym; layout.localSymbolTable.hasLinkedit = true; // Globals layout.globalSymbolTable.fileOffset = 0; // unused layout.globalSymbolTable.buffer = nullptr; // Use entryIndex instead layout.globalSymbolTable.bufferSize = 0; // Use entryCount instead layout.globalSymbolTable.entryIndex = dynSymTabCmd->iextdefsym; layout.globalSymbolTable.entryCount = dynSymTabCmd->nextdefsym; layout.globalSymbolTable.hasLinkedit = true; // Imports layout.undefSymbolTable.fileOffset = 0; // unused layout.undefSymbolTable.buffer = nullptr; // Use entryIndex instead layout.undefSymbolTable.bufferSize = 0; // Use entryCount instead layout.undefSymbolTable.entryIndex = dynSymTabCmd->iundefsym; layout.undefSymbolTable.entryCount = dynSymTabCmd->nundefsym; layout.undefSymbolTable.hasLinkedit = true; break; } case LC_DYLD_INFO: case LC_DYLD_INFO_ONLY: { const dyld_info_command* linkeditCmd = (const dyld_info_command*)cmd; // Record what kind of DYLD_INFO we found layout.dyldInfoCmd = cmd->cmd; // Rebase layout.rebaseOpcodes.fileOffset = linkeditCmd->rebase_off; layout.rebaseOpcodes.buffer = getLinkEditContent(linkeditCmd->rebase_off); layout.rebaseOpcodes.bufferSize = linkeditCmd->rebase_size; layout.rebaseOpcodes.hasLinkedit = true; // Bind layout.regularBindOpcodes.fileOffset = linkeditCmd->bind_off; layout.regularBindOpcodes.buffer = getLinkEditContent(linkeditCmd->bind_off); layout.regularBindOpcodes.bufferSize = linkeditCmd->bind_size; layout.regularBindOpcodes.hasLinkedit = true; // Lazy bind layout.lazyBindOpcodes.fileOffset = linkeditCmd->lazy_bind_off; layout.lazyBindOpcodes.buffer = getLinkEditContent(linkeditCmd->lazy_bind_off); layout.lazyBindOpcodes.bufferSize = linkeditCmd->lazy_bind_size; layout.lazyBindOpcodes.hasLinkedit = true; // Weak bind layout.weakBindOpcodes.fileOffset = linkeditCmd->weak_bind_off; layout.weakBindOpcodes.buffer = getLinkEditContent(linkeditCmd->weak_bind_off); layout.weakBindOpcodes.bufferSize = linkeditCmd->weak_bind_size; layout.weakBindOpcodes.hasLinkedit = true; // Export trie layout.exportsTrie.fileOffset = linkeditCmd->export_off; layout.exportsTrie.buffer = getLinkEditContent(linkeditCmd->export_off); layout.exportsTrie.bufferSize = linkeditCmd->export_size; layout.exportsTrie.hasLinkedit = true; break; } case LC_DYLD_CHAINED_FIXUPS: { const linkedit_data_command* linkeditCmd = (const linkedit_data_command*)cmd; layout.chainedFixups.fileOffset = linkeditCmd->dataoff; layout.chainedFixups.buffer = getLinkEditContent(linkeditCmd->dataoff); layout.chainedFixups.bufferSize = linkeditCmd->datasize; layout.chainedFixups.entryCount = 0; // Not needed here layout.chainedFixups.hasLinkedit = true; layout.chainedFixups.cmd = linkeditCmd; break; } case LC_DYLD_EXPORTS_TRIE: { const linkedit_data_command* linkeditCmd = (const linkedit_data_command*)cmd; layout.exportsTrie.fileOffset = linkeditCmd->dataoff; layout.exportsTrie.buffer = getLinkEditContent(linkeditCmd->dataoff); layout.exportsTrie.bufferSize = linkeditCmd->datasize; layout.exportsTrie.entryCount = 0; // Not needed here layout.exportsTrie.hasLinkedit = true; break; } case LC_SEGMENT_SPLIT_INFO: { const linkedit_data_command* linkeditCmd = (const linkedit_data_command*)cmd; layout.splitSegInfo.fileOffset = linkeditCmd->dataoff; layout.splitSegInfo.buffer = getLinkEditContent(linkeditCmd->dataoff); layout.splitSegInfo.bufferSize = linkeditCmd->datasize; layout.splitSegInfo.entryCount = 0; // Not needed here layout.splitSegInfo.hasLinkedit = true; break; } case LC_FUNCTION_STARTS: { const linkedit_data_command* linkeditCmd = (const linkedit_data_command*)cmd; layout.functionStarts.fileOffset = linkeditCmd->dataoff; layout.functionStarts.buffer = getLinkEditContent(linkeditCmd->dataoff); layout.functionStarts.bufferSize = linkeditCmd->datasize; layout.functionStarts.entryCount = 0; // Not needed here layout.functionStarts.hasLinkedit = true; break; } case LC_DATA_IN_CODE: { const linkedit_data_command* linkeditCmd = (const linkedit_data_command*)cmd; layout.dataInCode.fileOffset = linkeditCmd->dataoff; layout.dataInCode.buffer = getLinkEditContent(linkeditCmd->dataoff); layout.dataInCode.bufferSize = linkeditCmd->datasize; layout.dataInCode.entryCount = 0; // Not needed here layout.dataInCode.hasLinkedit = true; break; } case LC_CODE_SIGNATURE: { const linkedit_data_command* linkeditCmd = (const linkedit_data_command*)cmd; layout.codeSignature.fileOffset = linkeditCmd->dataoff; layout.codeSignature.buffer = getLinkEditContent(linkeditCmd->dataoff); layout.codeSignature.bufferSize = linkeditCmd->datasize; layout.codeSignature.entryCount = 0; // Not needed here layout.codeSignature.hasLinkedit = true; break; } } }); return true; } void MachOAnalyzer::withVMLayout(Diagnostics &diag, void (^callback)(const mach_o::Layout &layout)) const { intptr_t slide = this->getSlide(); __block uint64_t linkeditFileOffset = 0; __block const uint8_t* linkeditStartAddr = nullptr; uint32_t numSegments = this->segmentCount(); BLOCK_ACCCESSIBLE_ARRAY(mach_o::SegmentLayout, segmentLayout, numSegments); this->forEachSegment(^(const SegmentInfo &info, bool &stop) { mach_o::SegmentLayout segment; segment.vmAddr = info.vmAddr; segment.vmSize = info.vmSize; segment.fileOffset = info.fileOffset; segment.fileSize = info.fileSize; segment.buffer = (uint8_t*)(info.vmAddr + slide); segment.protections = info.protections; segment.kind = mach_o::SegmentLayout::Kind::unknown; if ( !strcmp(info.segName, "__TEXT") ) { segment.kind = mach_o::SegmentLayout::Kind::text; } else if ( !strcmp(info.segName, "__LINKEDIT") ) { segment.kind = mach_o::SegmentLayout::Kind::linkedit; linkeditFileOffset = info.fileOffset; linkeditStartAddr = segment.buffer; } segmentLayout[info.segIndex] = segment; }); mach_o::LinkeditLayout linkedit; if ( !this->getLinkeditLayout(diag, linkeditFileOffset, linkeditStartAddr, linkedit) ) { diag.error("Couldn't get dylib layout"); return; } mach_o::Layout layout(this, { &segmentLayout[0], &segmentLayout[numSegments] }, linkedit); callback(layout); } } // dyld3 |