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 | /* * 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 <stdlib.h> #include <assert.h> #include <string.h> #include <strings.h> #include <stdio.h> #include <TargetConditionals.h> #include "Defines.h" #if TARGET_OS_EXCLAVEKIT #define OSSwapBigToHostInt32 __builtin_bswap32 #define OSSwapBigToHostInt64 __builtin_bswap64 #define htonl __builtin_bswap32 #else #include <sys/stat.h> #include <sys/types.h> #include <sys/errno.h> #include <sys/fcntl.h> #include <unistd.h> #include <mach/host_info.h> #include <mach/mach.h> #include <mach/mach_host.h> #if SUPPORT_CLASSIC_RELOCS #include <mach-o/reloc.h> #include <mach-o/x86_64/reloc.h> #endif extern "C" { #include <corecrypto/ccdigest.h> #include <corecrypto/ccsha1.h> #include <corecrypto/ccsha2.h> } #endif #include "Defines.h" #include <mach-o/nlist.h> #if !BUILDING_DYLD #include <vector> #endif // !BUILDING_DYLD #include "Array.h" #include "MachOFile.h" #include "SupportedArchs.h" #include "CodeSigningTypes.h" #include "ObjC.h" #if (BUILDING_DYLD || BUILDING_LIBDYLD) && !TARGET_OS_EXCLAVEKIT #include <subsystem.h> #endif #if !BUILDING_DYLD #include "ObjCVisitor.h" #endif namespace dyld3 { #if !TARGET_OS_EXCLAVEKIT //////////////////////////// posix wrappers //////////////////////////////////////// // <rdar://problem/10111032> wrap calls to stat() with check for EAGAIN int stat(const char* path, struct stat* buf) { int result; do { #if BUILDING_DYLD result = ::stat_with_subsystem(path, buf); #else result = ::stat(path, buf); #endif } while ((result == -1) && ((errno == EAGAIN) || (errno == EINTR))); return result; } // <rdar://problem/10111032> wrap calls to stat() with check for EAGAIN int fstatat(int fd, const char *path, struct stat *buf, int flag) { int result; do { result = ::fstatat(fd, path, buf, flag); } while ((result == -1) && ((errno == EAGAIN) || (errno == EINTR))); return result; } // <rdar://problem/13805025> dyld should retry open() if it gets an EGAIN int open(const char* path, int flag, int other) { int result; do { #if BUILDING_DYLD if (flag & O_CREAT) result = ::open(path, flag, other); else result = ::open_with_subsystem(path, flag); #else result = ::open(path, flag, other); #endif } while ((result == -1) && ((errno == EAGAIN) || (errno == EINTR))); return result; } #endif // !TARGET_OS_EXCLAVEKIT //////////////////////////// FatFile //////////////////////////////////////// const FatFile* FatFile::isFatFile(const void* fileStart) { const FatFile* fileStartAsFat = (FatFile*)fileStart; if ( (fileStartAsFat->magic == OSSwapBigToHostInt32(FAT_MAGIC)) || (fileStartAsFat->magic == OSSwapBigToHostInt32(FAT_MAGIC_64)) ) return fileStartAsFat; else return nullptr; } bool FatFile::isValidSlice(Diagnostics& diag, uint64_t fileLen, uint32_t sliceIndex, uint32_t sliceCpuType, uint32_t sliceCpuSubType, uint64_t sliceOffset, uint64_t sliceLen) const { if ( greaterThanAddOrOverflow(sliceOffset, sliceLen, fileLen) ) { diag.error("slice %d extends beyond end of file", sliceIndex); return false; } const dyld3::MachOFile* mf = (const dyld3::MachOFile*)((uint8_t*)this+sliceOffset); if (!mf->isMachO(diag, sliceLen)) return false; if ( mf->cputype != (cpu_type_t)sliceCpuType ) { diag.error("cpu type in slice (0x%08X) does not match fat header (0x%08X)", mf->cputype, sliceCpuType); return false; } else if ( (mf->cpusubtype & ~CPU_SUBTYPE_MASK) != (sliceCpuSubType & ~CPU_SUBTYPE_MASK) ) { diag.error("cpu subtype in slice (0x%08X) does not match fat header (0x%08X)", mf->cpusubtype, sliceCpuSubType); return false; } uint32_t pageSizeMask = mf->uses16KPages() ? 0x3FFF : 0xFFF; if ( (sliceOffset & pageSizeMask) != 0 ) { // slice not page aligned if ( strncmp((char*)this+sliceOffset, "!<arch>", 7) == 0 ) diag.error("file is static library"); else diag.error("slice is not page aligned"); return false; } return true; } void FatFile::forEachSlice(Diagnostics& diag, uint64_t fileLen, bool validate, void (^callback)(uint32_t sliceCpuType, uint32_t sliceCpuSubType, const void* sliceStart, uint64_t sliceSize, bool& stop)) const { if ( this->magic == OSSwapBigToHostInt32(FAT_MAGIC) ) { const uint64_t maxArchs = ((4096 - sizeof(fat_header)) / sizeof(fat_arch)); const uint32_t numArchs = OSSwapBigToHostInt32(nfat_arch); if ( numArchs > maxArchs ) { diag.error("fat header too large: %u entries", numArchs); return; } // <rdar://90700132> make sure architectures list doesn't exceed the file size // We can’t overflow due to maxArch check // Check numArchs+1 to cover the extra read after the loop if ( (sizeof(fat_header) + ((numArchs + 1) * sizeof(fat_arch))) > fileLen ) { diag.error("fat header malformed, architecture slices extend beyond end of file"); return; } bool stop = false; const fat_arch* const archs = (fat_arch*)(((char*)this)+sizeof(fat_header)); for (uint32_t i=0; i < numArchs; ++i) { uint32_t cpuType = OSSwapBigToHostInt32(archs[i].cputype); uint32_t cpuSubType = OSSwapBigToHostInt32(archs[i].cpusubtype); uint32_t offset = OSSwapBigToHostInt32(archs[i].offset); uint32_t len = OSSwapBigToHostInt32(archs[i].size); Diagnostics sliceDiag; if ( !validate || isValidSlice(sliceDiag, fileLen, i, cpuType, cpuSubType, offset, len) ) callback(cpuType, cpuSubType, (uint8_t*)this+offset, len, stop); if ( stop ) break; if ( sliceDiag.hasError() ) diag.appendError("%s, ", sliceDiag.errorMessageCStr()); } // Look for one more slice if ( numArchs != maxArchs ) { uint32_t cpuType = OSSwapBigToHostInt32(archs[numArchs].cputype); uint32_t cpuSubType = OSSwapBigToHostInt32(archs[numArchs].cpusubtype); uint32_t offset = OSSwapBigToHostInt32(archs[numArchs].offset); uint32_t len = OSSwapBigToHostInt32(archs[numArchs].size); if ((cpuType == CPU_TYPE_ARM64) && ((cpuSubType == CPU_SUBTYPE_ARM64_ALL || cpuSubType == CPU_SUBTYPE_ARM64_V8))) { if ( !validate || isValidSlice(diag, fileLen, numArchs, cpuType, cpuSubType, offset, len) ) callback(cpuType, cpuSubType, (uint8_t*)this+offset, len, stop); } } } else if ( this->magic == OSSwapBigToHostInt32(FAT_MAGIC_64) ) { const uint32_t numArchs = OSSwapBigToHostInt32(nfat_arch); if ( numArchs > ((4096 - sizeof(fat_header)) / sizeof(fat_arch_64)) ) { diag.error("fat header too large: %u entries", OSSwapBigToHostInt32(nfat_arch)); return; } // <rdar://90700132> make sure architectures list doesn't exceed the file size // We can’t overflow due to maxArch check if ( (sizeof(fat_header) + (numArchs * sizeof(fat_arch_64))) > fileLen ) { diag.error("fat header malformed, architecture slices extend beyond end of file"); return; } bool stop = false; const fat_arch_64* const archs = (fat_arch_64*)(((char*)this)+sizeof(fat_header)); for (uint32_t i=0; i < numArchs; ++i) { uint32_t cpuType = OSSwapBigToHostInt32(archs[i].cputype); uint32_t cpuSubType = OSSwapBigToHostInt32(archs[i].cpusubtype); uint64_t offset = OSSwapBigToHostInt64(archs[i].offset); uint64_t len = OSSwapBigToHostInt64(archs[i].size); if ( !validate || isValidSlice(diag, fileLen, i, cpuType, cpuSubType, offset, len) ) callback(cpuType, cpuSubType, (uint8_t*)this+offset, len, stop); if ( stop ) break; } } else { diag.error("not a fat file"); } } void FatFile::forEachSlice(Diagnostics& diag, uint64_t fileLen, void (^callback)(uint32_t sliceCpuType, uint32_t sliceCpuSubType, const void* sliceStart, uint64_t sliceSize, bool& stop)) const { forEachSlice(diag, fileLen, true, callback); } const char* FatFile::archNames(char strBuf[256], uint64_t fileLen) const { strBuf[0] = '\0'; Diagnostics diag; __block bool needComma = false; this->forEachSlice(diag, fileLen, false, ^(uint32_t sliceCpuType, uint32_t sliceCpuSubType, const void* sliceStart, uint64_t sliceSize, bool& stop) { if ( needComma ) strlcat(strBuf, ",", 256); strlcat(strBuf, MachOFile::archName(sliceCpuType, sliceCpuSubType), 256); needComma = true; }); return strBuf; } bool FatFile::isFatFileWithSlice(Diagnostics& diag, uint64_t fileLen, const GradedArchs& archs, bool isOSBinary, uint64_t& sliceOffset, uint64_t& sliceLen, bool& missingSlice) const { missingSlice = false; if ( (this->magic != OSSwapBigToHostInt32(FAT_MAGIC)) && (this->magic != OSSwapBigToHostInt32(FAT_MAGIC_64)) ) return false; __block int bestGrade = 0; forEachSlice(diag, fileLen, ^(uint32_t sliceCpuType, uint32_t sliceCpuSubType, const void* sliceStart, uint64_t sliceSize, bool& stop) { if (int sliceGrade = archs.grade(sliceCpuType, sliceCpuSubType, isOSBinary)) { if ( sliceGrade > bestGrade ) { sliceOffset = (char*)sliceStart - (char*)this; sliceLen = sliceSize; bestGrade = sliceGrade; } } }); if ( diag.hasError() ) return false; if ( bestGrade == 0 ) missingSlice = true; return (bestGrade != 0); } //////////////////////////// GradedArchs //////////////////////////////////////// #define GRADE_i386 CPU_TYPE_I386, CPU_SUBTYPE_I386_ALL, false #define GRADE_x86_64 CPU_TYPE_X86_64, CPU_SUBTYPE_X86_64_ALL, false #define GRADE_x86_64h CPU_TYPE_X86_64, CPU_SUBTYPE_X86_64_H, false #define GRADE_armv7 CPU_TYPE_ARM, CPU_SUBTYPE_ARM_V7, false #define GRADE_armv7s CPU_TYPE_ARM, CPU_SUBTYPE_ARM_V7S, false #define GRADE_armv7k CPU_TYPE_ARM, CPU_SUBTYPE_ARM_V7K, false #define GRADE_armv6m CPU_TYPE_ARM, CPU_SUBTYPE_ARM_V6M, false #define GRADE_armv7m CPU_TYPE_ARM, CPU_SUBTYPE_ARM_V7M, false #define GRADE_armv7em CPU_TYPE_ARM, CPU_SUBTYPE_ARM_V7EM, false #define GRADE_armv8m CPU_TYPE_ARM, CPU_SUBTYPE_ARM_V8M, false #define GRADE_arm64 CPU_TYPE_ARM64, CPU_SUBTYPE_ARM64_ALL, false #define GRADE_arm64e CPU_TYPE_ARM64, CPU_SUBTYPE_ARM64E, false #define GRADE_arm64e_pb CPU_TYPE_ARM64, CPU_SUBTYPE_ARM64E, true #define GRADE_arm64_32 CPU_TYPE_ARM64_32, CPU_SUBTYPE_ARM64_32_V8, false const GradedArchs GradedArchs::i386 = GradedArchs({GRADE_i386, 1}); const GradedArchs GradedArchs::x86_64 = GradedArchs({GRADE_x86_64, 1}); const GradedArchs GradedArchs::x86_64h = GradedArchs({GRADE_x86_64h, 2}, {GRADE_x86_64, 1}); const GradedArchs GradedArchs::arm64 = GradedArchs({GRADE_arm64, 1}); #if SUPPORT_ARCH_arm64e const GradedArchs GradedArchs::arm64e_keysoff = GradedArchs({GRADE_arm64e, 2}, {GRADE_arm64, 1}); const GradedArchs GradedArchs::arm64e_keysoff_pb = GradedArchs({GRADE_arm64e_pb, 2}, {GRADE_arm64, 1}); const GradedArchs GradedArchs::arm64e = GradedArchs({GRADE_arm64e, 1}); const GradedArchs GradedArchs::arm64e_pb = GradedArchs({GRADE_arm64e_pb, 1}); #endif const GradedArchs GradedArchs::armv7 = GradedArchs({GRADE_armv7, 1}); const GradedArchs GradedArchs::armv7s = GradedArchs({GRADE_armv7s, 2}, {GRADE_armv7, 1}); const GradedArchs GradedArchs::armv7k = GradedArchs({GRADE_armv7k, 1}); const GradedArchs GradedArchs::armv7m = GradedArchs({GRADE_armv7m, 1}); const GradedArchs GradedArchs::armv7em = GradedArchs({GRADE_armv7em, 1}); #if SUPPORT_ARCH_arm64_32 const GradedArchs GradedArchs::arm64_32 = GradedArchs({GRADE_arm64_32, 1}); #endif #if BUILDING_LIBDYLD || BUILDING_UNIT_TESTS const GradedArchs GradedArchs::launch_AS = GradedArchs({GRADE_arm64e, 3}, {GRADE_arm64, 2}, {GRADE_x86_64, 1}); const GradedArchs GradedArchs::launch_AS_Sim = GradedArchs({GRADE_arm64, 2}, {GRADE_x86_64, 1}); const GradedArchs GradedArchs::launch_Intel_h = GradedArchs({GRADE_x86_64h, 3}, {GRADE_x86_64, 2}, {GRADE_i386, 1}); const GradedArchs GradedArchs::launch_Intel = GradedArchs({GRADE_x86_64, 2}, {GRADE_i386, 1}); const GradedArchs GradedArchs::launch_Intel_Sim = GradedArchs({GRADE_x86_64, 2}, {GRADE_i386, 1}); #endif int GradedArchs::grade(uint32_t cputype, uint32_t cpusubtype, bool isOSBinary) const { for (const auto& p : _orderedCpuTypes) { if (p.type == 0) { break; } if ( (p.type == cputype) && (p.subtype == (cpusubtype & ~CPU_SUBTYPE_MASK)) ) { if ( p.osBinary ) { if ( isOSBinary ) return p.grade; } else { return p.grade; } } } return 0; } const char* GradedArchs::name() const { return MachOFile::archName(_orderedCpuTypes[0].type, _orderedCpuTypes[0].subtype); } void GradedArchs::forEachArch(bool platformBinariesOnly, void (^handler)(const char*)) const { for (const auto& p : _orderedCpuTypes) { if (p.type == 0) break; if ( p.osBinary && !platformBinariesOnly ) continue; handler(MachOFile::archName(p.type, p.subtype)); } } bool GradedArchs::checksOSBinary() const { for (const auto& p : _orderedCpuTypes) { if (p.type == 0) { return false; } if ( p.osBinary ) { return true; } } __builtin_unreachable(); } bool GradedArchs::supports64() const { return (_orderedCpuTypes.front().type & CPU_ARCH_ABI64) != 0; } #if __x86_64__ static bool isHaswell() { // FIXME: figure out a commpage way to check this struct host_basic_info info; mach_msg_type_number_t count = HOST_BASIC_INFO_COUNT; mach_port_t hostPort = mach_host_self(); kern_return_t result = host_info(hostPort, HOST_BASIC_INFO, (host_info_t)&info, &count); mach_port_deallocate(mach_task_self(), hostPort); return (result == KERN_SUCCESS) && (info.cpu_subtype == CPU_SUBTYPE_X86_64_H); } #endif const GradedArchs& GradedArchs::forCurrentOS(bool keysOff, bool osBinariesOnly) { #if __arm64e__ if ( osBinariesOnly ) return (keysOff ? arm64e_keysoff_pb : arm64e_pb); else return (keysOff ? arm64e_keysoff : arm64e); #elif __ARM64_ARCH_8_32__ return arm64_32; #elif __arm64__ return arm64; #elif __x86_64__ #if TARGET_OS_SIMULATOR return x86_64; #else return isHaswell() ? x86_64h : x86_64; #endif #else #error unknown platform #endif } #if BUILDING_LIBDYLD || BUILDING_UNIT_TESTS const GradedArchs& GradedArchs::launchCurrentOS(const char* simArches) { #if TARGET_OS_SIMULATOR // on Apple Silicon, there is both an arm64 and an x86_64 (under rosetta) simulators // You cannot tell if you are running under rosetta, so CoreSimulator sets SIMULATOR_ARCHS if ( strcmp(simArches, "arm64 x86_64") == 0 ) return launch_AS_Sim; else return x86_64; #elif TARGET_OS_OSX #if __arm64__ return launch_AS; #else return isHaswell() ? launch_Intel_h : launch_Intel; #endif #else // all other platforms use same grading for executables as dylibs return forCurrentOS(true, false); #endif } #endif // BUILDING_LIBDYLD const GradedArchs& GradedArchs::forName(const char* archName, bool keysOff) { if (strcmp(archName, "x86_64h") == 0 ) return x86_64h; else if (strcmp(archName, "x86_64") == 0 ) return x86_64; #if SUPPORT_ARCH_arm64e else if (strcmp(archName, "arm64e") == 0 ) return keysOff ? arm64e_keysoff : arm64e; #endif else if (strcmp(archName, "arm64") == 0 ) return arm64; else if (strcmp(archName, "armv7k") == 0 ) return armv7k; else if (strcmp(archName, "armv7s") == 0 ) return armv7s; else if (strcmp(archName, "armv7") == 0 ) return armv7; else if (strcmp(archName, "armv7m") == 0 ) return armv7m; else if (strcmp(archName, "armv7em") == 0 ) return armv7em; #if SUPPORT_ARCH_arm64_32 else if (strcmp(archName, "arm64_32") == 0 ) return arm64_32; #endif else if (strcmp(archName, "i386") == 0 ) return i386; assert(0 && "unknown arch name"); } //////////////////////////// MachOFile //////////////////////////////////////// const MachOFile::ArchInfo MachOFile::_s_archInfos[] = { { "x86_64", CPU_TYPE_X86_64, CPU_SUBTYPE_X86_64_ALL }, { "x86_64h", CPU_TYPE_X86_64, CPU_SUBTYPE_X86_64_H }, { "i386", CPU_TYPE_I386, CPU_SUBTYPE_I386_ALL }, { "arm64", CPU_TYPE_ARM64, CPU_SUBTYPE_ARM64_ALL }, #if SUPPORT_ARCH_arm64e { "arm64e", CPU_TYPE_ARM64, CPU_SUBTYPE_ARM64E }, #endif #if SUPPORT_ARCH_arm64_32 { "arm64_32", CPU_TYPE_ARM64_32, CPU_SUBTYPE_ARM64_32_V8 }, #endif { "armv7k", CPU_TYPE_ARM, CPU_SUBTYPE_ARM_V7K }, { "armv7s", CPU_TYPE_ARM, CPU_SUBTYPE_ARM_V7S }, { "armv7", CPU_TYPE_ARM, CPU_SUBTYPE_ARM_V7 }, { "armv6m", CPU_TYPE_ARM, CPU_SUBTYPE_ARM_V6M }, { "armv7m", CPU_TYPE_ARM, CPU_SUBTYPE_ARM_V7M }, { "armv7em", CPU_TYPE_ARM, CPU_SUBTYPE_ARM_V7EM }, { "armv8m", CPU_TYPE_ARM, CPU_SUBTYPE_ARM_V8M }, }; const MachOFile::PlatformInfo MachOFile::_s_platformInfos[] = { { "macOS", Platform::macOS, LC_VERSION_MIN_MACOSX }, { "iOS", Platform::iOS, LC_VERSION_MIN_IPHONEOS }, { "tvOS", Platform::tvOS, LC_VERSION_MIN_TVOS }, { "watchOS", Platform::watchOS, LC_VERSION_MIN_WATCHOS }, { "bridgeOS", Platform::bridgeOS, LC_BUILD_VERSION }, { "MacCatalyst", Platform::iOSMac, LC_BUILD_VERSION }, { "iOS-sim", Platform::iOS_simulator, LC_BUILD_VERSION }, { "tvOS-sim", Platform::tvOS_simulator, LC_BUILD_VERSION }, { "watchOS-sim", Platform::watchOS_simulator, LC_BUILD_VERSION }, { "driverKit", Platform::driverKit, LC_BUILD_VERSION }, { "visionOS", Platform::visionOS, LC_BUILD_VERSION }, { "visionOS-sim", Platform::visionOS_simulator, LC_BUILD_VERSION }, { "macOSExclaveCore", Platform::macOSExclaveCore, LC_BUILD_VERSION }, { "macOSExclaveKit", Platform::macOSExclaveKit, LC_BUILD_VERSION }, { "iOSExclaveCore", Platform::iOSExclaveCore, LC_BUILD_VERSION }, { "iOSExclaveKit", Platform::iOSExclaveKit, LC_BUILD_VERSION }, { "tvOSExclaveCore", Platform::tvOSExclaveCore, LC_BUILD_VERSION }, { "tvOSExclaveKit", Platform::tvOSExclaveKit, LC_BUILD_VERSION }, }; bool MachOFile::is64() const { return (this->magic == MH_MAGIC_64); } size_t MachOFile::machHeaderSize() const { return is64() ? sizeof(mach_header_64) : sizeof(mach_header); } uint32_t MachOFile::maskedCpuSubtype() const { return (this->cpusubtype & ~CPU_SUBTYPE_MASK); } uint32_t MachOFile::pointerSize() const { if (this->magic == MH_MAGIC_64) return 8; else return 4; } bool MachOFile::uses16KPages() const { switch (this->cputype) { case CPU_TYPE_ARM64: case CPU_TYPE_ARM64_32: return true; case CPU_TYPE_ARM: // iOS is 16k aligned for armv7/armv7s and watchOS armv7k is 16k aligned // HACK: Pretend armv7k kexts are 4k aligned if ( this->isKextBundle() ) return false; return this->cpusubtype == CPU_SUBTYPE_ARM_V7K; default: return false; } } bool MachOFile::isArch(const char* aName) const { return (strcmp(aName, archName(this->cputype, this->cpusubtype)) == 0); } const char* MachOFile::archName(uint32_t cputype, uint32_t cpusubtype) { for (const ArchInfo& info : _s_archInfos) { if ( (cputype == info.cputype) && ((cpusubtype & ~CPU_SUBTYPE_MASK) == info.cpusubtype) ) { return info.name; } } return "unknown"; } bool MachOFile::cpuTypeFromArchName(const char* archName, cpu_type_t* cputype, cpu_subtype_t* cpusubtype) { for (const ArchInfo& info : _s_archInfos) { if ( strcmp(archName, info.name) == 0 ) { *cputype = info.cputype; *cpusubtype = info.cpusubtype; return true; } } return false; } const char* MachOFile::archName() const { return archName(this->cputype, this->cpusubtype); } static void appendDigit(char*& s, unsigned& num, unsigned place, bool& startedPrinting) { if ( num >= place ) { unsigned dig = (num/place); *s++ = '0' + dig; num -= (dig*place); startedPrinting = true; } else if ( startedPrinting ) { *s++ = '0'; } } static void appendNumber(char*& s, unsigned num) { assert(num < 99999); bool startedPrinting = false; appendDigit(s, num, 10000, startedPrinting); appendDigit(s, num, 1000, startedPrinting); appendDigit(s, num, 100, startedPrinting); appendDigit(s, num, 10, startedPrinting); appendDigit(s, num, 1, startedPrinting); if ( !startedPrinting ) *s++ = '0'; } void MachOFile::packedVersionToString(uint32_t packedVersion, char versionString[32]) { // sprintf(versionString, "%d.%d.%d", (packedVersion >> 16), ((packedVersion >> 8) & 0xFF), (packedVersion & 0xFF)); char* s = versionString; appendNumber(s, (packedVersion >> 16)); *s++ = '.'; appendNumber(s, (packedVersion >> 8) & 0xFF); if ( (packedVersion & 0xFF) != 0 ) { *s++ = '.'; appendNumber(s, (packedVersion & 0xFF)); } *s++ = '\0'; } bool MachOFile::builtForPlatform(Platform reqPlatform, bool onlyOnePlatform) const { __block bool foundRequestedPlatform = false; __block bool foundOtherPlatform = false; forEachSupportedPlatform(^(Platform platform, uint32_t minOS, uint32_t sdk) { if ( platform == reqPlatform ) foundRequestedPlatform = true; else foundOtherPlatform = true; }); // if checking that this binary is built for exactly one platform, fail if more if ( foundOtherPlatform && onlyOnePlatform ) return false; if ( foundRequestedPlatform ) return true; // binary has no explict load command to mark platform // could be an old macOS binary, look at arch if ( !foundOtherPlatform && (reqPlatform == Platform::macOS) ) { if ( this->cputype == CPU_TYPE_X86_64 ) return true; if ( this->cputype == CPU_TYPE_I386 ) return true; } #if BUILDING_DYLDINFO // Allow offline tools to analyze binaries dyld doesn't load, ie, those with platforms if ( !foundOtherPlatform && (reqPlatform == Platform::unknown) ) return true; #endif return false; } bool MachOFile::loadableIntoProcess(Platform processPlatform, const char* path, bool internalInstall) const { if ( this->builtForPlatform(processPlatform) ) return true; // Some host macOS dylibs can be loaded into simulator processes if ( MachOFile::isSimulatorPlatform(processPlatform) && this->builtForPlatform(Platform::macOS)) { static const char* const macOSHost[] = { "/usr/lib/system/libsystem_kernel.dylib", "/usr/lib/system/libsystem_platform.dylib", "/usr/lib/system/libsystem_pthread.dylib", "/usr/lib/system/libsystem_platform_debug.dylib", "/usr/lib/system/libsystem_pthread_debug.dylib", "/usr/lib/system/host/liblaunch_sim.dylib", }; for (const char* libPath : macOSHost) { if (strcmp(libPath, path) == 0) return true; } } // If this is being called on main executable where we expect a macOS program, Catalyst programs are also runnable if ( (this->filetype == MH_EXECUTE) && (processPlatform == Platform::macOS) && this->builtForPlatform(Platform::iOSMac, true) ) return true; #if (TARGET_OS_OSX && TARGET_CPU_ARM64) if ( (this->filetype == MH_EXECUTE) && (processPlatform == Platform::macOS) && this->builtForPlatform(Platform::iOS, true) ) return true; #endif // allow iOS executables to use visionOS dylibs if ( (processPlatform == Platform::iOS) && this->builtForPlatform(Platform::visionOS, true) ) return true; // allow iOS_Sim executables to use visionOS_Sim dylibs if ( (processPlatform == Platform::iOS_simulator) && this->builtForPlatform(Platform::visionOS_simulator, true) ) return true; bool iOSonMac = (processPlatform == Platform::iOSMac); #if (TARGET_OS_OSX && TARGET_CPU_ARM64) // allow iOS binaries in iOSApp if ( processPlatform == Platform::iOS ) { // can load Catalyst binaries into iOS process if ( this->builtForPlatform(Platform::iOSMac) ) return true; iOSonMac = true; } #endif // macOS dylibs can be loaded into iOSMac processes if ( (iOSonMac) && this->builtForPlatform(Platform::macOS, true) ) return true; return false; } bool MachOFile::isZippered() const { __block bool macOS = false; __block bool iOSMac = false; forEachSupportedPlatform(^(Platform platform, uint32_t minOS, uint32_t sdk) { if ( platform == Platform::macOS ) macOS = true; else if ( platform == Platform::iOSMac ) iOSMac = true; }); return macOS && iOSMac; } bool MachOFile::inDyldCache() const { return (this->flags & MH_DYLIB_IN_CACHE); } Platform MachOFile::currentPlatform() { #if TARGET_OS_SIMULATOR #if TARGET_OS_WATCH return Platform::watchOS_simulator; #elif TARGET_OS_TV return Platform::tvOS_simulator; #elif TARGET_OS_VISION return Platform::visionOS_simulator; #elif TARGET_OS_IOS return Platform::iOS_simulator; #endif #elif TARGET_OS_BRIDGE return Platform::bridgeOS; #elif TARGET_OS_WATCH return Platform::watchOS; #elif TARGET_OS_TV return Platform::tvOS; #elif TARGET_OS_IOS return Platform::iOS; #elif TARGET_OS_OSX return Platform::macOS; #elif TARGET_OS_DRIVERKIT return Platform::driverKit; #elif TARGET_OS_VISION return Platform::visionOS; #else #if TARGET_OS_EXCLAVECORE #if __is_target_os(macos) return Platform::macOSExclaveCore #elif __is_target_os(ios) return Platform::iOSExclaveCore; #elif __is_target_os(tvos) return Platform::tvOSExclaveCore; #else #error unknown platform #endif #elif TARGET_OS_EXCLAVEKIT #if __is_target_os(macos) return Platform::macOSExclaveKit; #elif __is_target_os(ios) return Platform::iOSExclaveKit; #elif __is_target_os(tvos) return Platform::tvOSExclaveKit; #else #error unknown platform #endif #else #error unknown platform #endif #endif } Platform MachOFile::basePlatform(dyld3::Platform reqPlatform) { switch(reqPlatform) { case Platform::unknown: return Platform::unknown; case Platform::macOS: return Platform::macOS; case Platform::iOS: return Platform::iOS; case Platform::tvOS: return Platform::tvOS; case Platform::watchOS: return Platform::watchOS; case Platform::bridgeOS: return Platform::bridgeOS; case Platform::iOSMac: return Platform::iOS; case Platform::iOS_simulator: return Platform::iOS; case Platform::tvOS_simulator: return Platform::tvOS; case Platform::watchOS_simulator: return Platform::watchOS; case Platform::driverKit: return Platform::driverKit; case Platform::visionOS: return Platform::visionOS; case Platform::visionOS_simulator: return Platform::visionOS; case Platform::macOSExclaveCore: return Platform::macOSExclaveCore; case Platform::macOSExclaveKit: return Platform::macOSExclaveKit; case Platform::iOSExclaveCore: return Platform::iOSExclaveCore; case Platform::iOSExclaveKit: return Platform::iOSExclaveKit; case Platform::tvOSExclaveCore: return Platform::tvOSExclaveCore; case Platform::tvOSExclaveKit: return Platform::tvOSExclaveKit; default: return reqPlatform; } } const char* MachOFile::currentArchName() { #if __arm64e__ return "arm64e"; #elif __arm64__ #if __LP64__ return "arm64"; #else return "arm64_32"; #endif #elif __x86_64__ return isHaswell() ? "x86_64h" : "x86_64"; #else #error unknown arch #endif } bool MachOFile::isExclaveKitPlatform(Platform platform, Platform* basePlatform) { switch ( platform ) { case Platform::macOSExclaveKit: if ( basePlatform ) *basePlatform = Platform::macOS; return true; case Platform::iOSExclaveKit: if ( basePlatform ) *basePlatform = Platform::iOS; return true; case Platform::tvOSExclaveKit: if ( basePlatform ) *basePlatform = Platform::tvOS; return true; default: return false; } } bool MachOFile::isSimulatorPlatform(Platform platform, Platform* basePlatform) { switch ( platform ) { case Platform::iOS_simulator: if ( basePlatform ) *basePlatform = Platform::iOS; return true; case Platform::watchOS_simulator: if ( basePlatform ) *basePlatform = Platform::watchOS; return true; case Platform::tvOS_simulator: if ( basePlatform ) *basePlatform = Platform::tvOS; return true; case Platform::visionOS_simulator: if ( basePlatform ) *basePlatform = Platform::visionOS; return true; default: return false; } } bool MachOFile::isBuiltForSimulator() const { __block bool result = false; this->forEachSupportedPlatform(^(Platform platform, uint32_t minOS, uint32_t sdk) { switch ( platform ) { case Platform::iOS_simulator: case Platform::watchOS_simulator: case Platform::tvOS_simulator: case Platform::visionOS_simulator: result = true; break; default: break; } }); return result; } bool MachOFile::isDyld() const { return (this->filetype == MH_DYLINKER); } bool MachOFile::isDyldManaged() const { switch ( this->filetype ) { case MH_BUNDLE: case MH_EXECUTE: case MH_DYLIB: return true; default: break; } return false; } bool MachOFile::isDylib() const { return (this->filetype == MH_DYLIB); } bool MachOFile::isBundle() const { return (this->filetype == MH_BUNDLE); } bool MachOFile::isMainExecutable() const { return (this->filetype == MH_EXECUTE); } bool MachOFile::isDynamicExecutable() const { if ( this->filetype != MH_EXECUTE ) return false; // static executables do not have dyld load command return hasLoadCommand(LC_LOAD_DYLINKER); } bool MachOFile::isStaticExecutable() const { if ( this->filetype != MH_EXECUTE ) return false; // static executables do not have dyld load command return !hasLoadCommand(LC_LOAD_DYLINKER); } bool MachOFile::isKextBundle() const { return (this->filetype == MH_KEXT_BUNDLE); } bool MachOFile::isFileSet() const { return (this->filetype == MH_FILESET); } bool MachOFile::isPIE() const { return (this->flags & MH_PIE); } bool MachOFile::isPreload() const { return (this->filetype == MH_PRELOAD); } const char* MachOFile::platformName(Platform reqPlatform) { for (const PlatformInfo& info : _s_platformInfos) { if ( info.platform == reqPlatform ) return info.name; } return "unknown"; } void MachOFile::forEachSupportedPlatform(void (^handler)(Platform platform, uint32_t minOS, uint32_t sdk)) const { Diagnostics diag; __block bool foundPlatform = false; forEachLoadCommand(diag, ^(const load_command* cmd, bool& stop) { const build_version_command* buildCmd = (build_version_command *)cmd; const version_min_command* versCmd = (version_min_command*)cmd; uint32_t sdk; switch ( cmd->cmd ) { case LC_BUILD_VERSION: handler((Platform)(buildCmd->platform), buildCmd->minos, buildCmd->sdk); foundPlatform = true; break; case LC_VERSION_MIN_MACOSX: sdk = versCmd->sdk; // The original LC_VERSION_MIN_MACOSX did not have an sdk field, assume sdk is same as minOS for those old binaries if ( sdk == 0 ) sdk = versCmd->version; handler(Platform::macOS, versCmd->version, sdk); foundPlatform = true; break; case LC_VERSION_MIN_IPHONEOS: if ( (this->cputype == CPU_TYPE_X86_64) || (this->cputype == CPU_TYPE_I386) ) handler(Platform::iOS_simulator, versCmd->version, versCmd->sdk); // old sim binary else handler(Platform::iOS, versCmd->version, versCmd->sdk); foundPlatform = true; break; case LC_VERSION_MIN_TVOS: if ( this->cputype == CPU_TYPE_X86_64 ) handler(Platform::tvOS_simulator, versCmd->version, versCmd->sdk); // old sim binary else handler(Platform::tvOS, versCmd->version, versCmd->sdk); foundPlatform = true; break; case LC_VERSION_MIN_WATCHOS: if ( (this->cputype == CPU_TYPE_X86_64) || (this->cputype == CPU_TYPE_I386) ) handler(Platform::watchOS_simulator, versCmd->version, versCmd->sdk); // old sim binary else handler(Platform::watchOS, versCmd->version, versCmd->sdk); foundPlatform = true; break; } }); if ( !foundPlatform ) { // old binary with no explicit platform #if (BUILDING_DYLD || BUILDING_CLOSURE_UTIL) && TARGET_OS_OSX if ( this->cputype == CPU_TYPE_X86_64 ) handler(Platform::macOS, 0x000A0500, 0x000A0500); // guess it is a macOS 10.5 binary // <rdar://problem/75343399> // The Go linker emits non-standard binaries without a platform and we have to live with it. if ( this->cputype == CPU_TYPE_ARM64 ) handler(Platform::macOS, 0x000B0000, 0x000B0000); // guess it is a macOS 11.0 binary #endif } diag.assertNoError(); // any malformations in the file should have been caught by earlier validate() call } void MachOFile::forEachSupportedBuildTool(void (^handler)(Platform platform, uint32_t tool, uint32_t version)) const { Diagnostics diag; forEachLoadCommand(diag, ^(const load_command* cmd, bool& stop) { switch ( cmd->cmd ) { case LC_BUILD_VERSION: { const build_version_command* buildCmd = (build_version_command *)cmd; for ( uint32_t i = 0; i != buildCmd->ntools; ++i ) { uint32_t offset = sizeof(build_version_command) + (i * sizeof(build_tool_version)); if ( offset >= cmd->cmdsize ) break; const build_tool_version* firstTool = (const build_tool_version*)(&buildCmd[1]); handler((Platform)(buildCmd->platform), firstTool[i].tool, firstTool[i].version); } } } }); diag.assertNoError(); // any malformations in the file should have been caught by earlier validate() call } bool MachOFile::isMachO(Diagnostics& diag, uint64_t fileSize) const { if ( fileSize < sizeof(mach_header) ) { diag.error("MachO header exceeds file length"); return false; } if ( !hasMachOMagic() ) { // old PPC slices are not currently valid "mach-o" but should not cause an error if ( !hasMachOBigEndianMagic() ) diag.error("file does not start with MH_MAGIC[_64]"); return false; } if ( this->sizeofcmds + machHeaderSize() > fileSize ) { diag.error("load commands exceed length of first segment"); return false; } forEachLoadCommand(diag, ^(const load_command* cmd, bool& stop) { }); return diag.noError(); } const MachOFile* MachOFile::isMachO(const void* content) { const MachOFile* mf = (MachOFile*)content; if ( mf->hasMachOMagic() ) return mf; return nullptr; } bool MachOFile::hasMachOMagic() const { return ( (this->magic == MH_MAGIC) || (this->magic == MH_MAGIC_64) ); } bool MachOFile::hasMachOBigEndianMagic() const { return ( (this->magic == MH_CIGAM) || (this->magic == MH_CIGAM_64) ); } void MachOFile::forEachLoadCommand(Diagnostics& diag, void (^callback)(const load_command* cmd, bool& stop)) const { bool stop = false; const load_command* startCmds = nullptr; if ( this->magic == MH_MAGIC_64 ) startCmds = (load_command*)((char *)this + sizeof(mach_header_64)); else if ( this->magic == MH_MAGIC ) startCmds = (load_command*)((char *)this + sizeof(mach_header)); else if ( hasMachOBigEndianMagic() ) return; // can't process big endian mach-o else { const uint32_t* h = (uint32_t*)this; diag.error("file does not start with MH_MAGIC[_64]: 0x%08X 0x%08X", h[0], h [1]); return; // not a mach-o file } if ( this->filetype > 12 ) { diag.error("unknown mach-o filetype (%u)", this->filetype); return; } const load_command* const cmdsEnd = (load_command*)((char*)startCmds + this->sizeofcmds); const load_command* const cmdsLast = (load_command*)((char*)startCmds + this->sizeofcmds - sizeof(load_command)); const load_command* cmd = startCmds; for (uint32_t i = 0; i < this->ncmds; ++i) { if ( cmd > cmdsLast ) { diag.error("malformed load command #%u of %u at %p with mh=%p, extends past sizeofcmds", i, this->ncmds, cmd, this); return; } uint32_t cmdsize = cmd->cmdsize; if ( cmdsize < 8 ) { diag.error("malformed load command #%u of %u at %p with mh=%p, size (0x%X) too small", i, this->ncmds, cmd, this, cmd->cmdsize); return; } if ( (cmdsize % 4) != 0 ) { // FIXME: on 64-bit mach-o, should be 8-byte aligned, (might reveal bin-compat issues) diag.error("malformed load command #%u of %u at %p with mh=%p, size (0x%X) not multiple of 4", i, this->ncmds, cmd, this, cmd->cmdsize); return; } const load_command* nextCmd = (load_command*)((char *)cmd + cmdsize); if ( (nextCmd > cmdsEnd) || (nextCmd < startCmds) ) { diag.error("malformed load command #%u of %u at %p with mh=%p, size (0x%X) is too large, load commands end at %p", i, this->ncmds, cmd, this, cmd->cmdsize, cmdsEnd); return; } callback(cmd, stop); if ( stop ) return; cmd = nextCmd; } } void MachOFile::removeLoadCommand(Diagnostics& diag, void (^callback)(const load_command* cmd, bool& remove, bool& stop)) { bool stop = false; const load_command* startCmds = nullptr; if ( this->magic == MH_MAGIC_64 ) startCmds = (load_command*)((char *)this + sizeof(mach_header_64)); else if ( this->magic == MH_MAGIC ) startCmds = (load_command*)((char *)this + sizeof(mach_header)); else if ( hasMachOBigEndianMagic() ) return; // can't process big endian mach-o else { const uint32_t* h = (uint32_t*)this; diag.error("file does not start with MH_MAGIC[_64]: 0x%08X 0x%08X", h[0], h [1]); return; // not a mach-o file } const load_command* const cmdsEnd = (load_command*)((char*)startCmds + this->sizeofcmds); auto cmd = (load_command*)startCmds; const uint32_t origNcmds = this->ncmds; unsigned bytesRemaining = this->sizeofcmds; for (uint32_t i = 0; i < origNcmds; ++i) { bool remove = false; auto nextCmd = (load_command*)((char *)cmd + cmd->cmdsize); if ( cmd->cmdsize < 8 ) { diag.error("malformed load command #%d of %d at %p with mh=%p, size (0x%X) too small", i, this->ncmds, cmd, this, cmd->cmdsize); return; } if ( (nextCmd > cmdsEnd) || (nextCmd < startCmds) ) { diag.error("malformed load command #%d of %d at %p with mh=%p, size (0x%X) is too large, load commands end at %p", i, this->ncmds, cmd, this, cmd->cmdsize, cmdsEnd); return; } callback(cmd, remove, stop); if ( remove ) { this->sizeofcmds -= cmd->cmdsize; ::memmove((void*)cmd, (void*)nextCmd, bytesRemaining); this->ncmds--; } else { bytesRemaining -= cmd->cmdsize; cmd = nextCmd; } if ( stop ) break; } if ( cmd ) ::bzero(cmd, bytesRemaining); } bool MachOFile::hasObjC() 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) ) { result = true; stop = true; } if ( (this->cputype == CPU_TYPE_I386) && (strcmp(info.sectName, "__image_info") == 0) && (strcmp(info.segInfo.segName, "__OBJC") == 0) ) { result = true; stop = true; } }); return result; } bool MachOFile::hasConstObjCSection() const { return hasSection("__DATA_CONST", "__objc_selrefs") || hasSection("__DATA_CONST", "__objc_classrefs") || hasSection("__DATA_CONST", "__objc_protorefs") || hasSection("__DATA_CONST", "__objc_superrefs"); } bool MachOFile::hasSection(const char* segName, const char* sectName) const { __block bool result = false; forEachSection(^(const SectionInfo& info, bool malformedSectionRange, bool& stop) { if ( (strcmp(info.segInfo.segName, segName) == 0) && (strcmp(info.sectName, sectName) == 0) ) { result = true; stop = true; } }); return result; } const char* MachOFile::installName() const { const char* name; uint32_t compatVersion; uint32_t currentVersion; if ( getDylibInstallName(&name, &compatVersion, ¤tVersion) ) return name; return nullptr; } bool MachOFile::getDylibInstallName(const char** installName, uint32_t* compatVersion, uint32_t* currentVersion) const { Diagnostics diag; __block bool found = false; forEachLoadCommand(diag, ^(const load_command* cmd, bool& stop) { if ( (cmd->cmd == LC_ID_DYLIB) || (cmd->cmd == LC_ID_DYLINKER) ) { const dylib_command* dylibCmd = (dylib_command*)cmd; *compatVersion = dylibCmd->dylib.compatibility_version; *currentVersion = dylibCmd->dylib.current_version; *installName = (char*)dylibCmd + dylibCmd->dylib.name.offset; found = true; stop = true; } }); diag.assertNoError(); // any malformations in the file should have been caught by earlier validate() call return found; } bool MachOFile::getUuid(uuid_t uuid) const { Diagnostics diag; __block bool found = false; forEachLoadCommand(diag, ^(const load_command* cmd, bool& stop) { if ( cmd->cmd == LC_UUID ) { const uuid_command* uc = (const uuid_command*)cmd; memcpy(uuid, uc->uuid, sizeof(uuid_t)); found = true; stop = true; } }); diag.assertNoError(); // any malformations in the file should have been caught by earlier validate() call if ( !found ) bzero(uuid, sizeof(uuid_t)); return found; } UUID MachOFile::uuid() const { Diagnostics diag; __block UUID result; forEachLoadCommand(diag, ^(const load_command* cmd, bool& stop) { if ( cmd->cmd == LC_UUID ) { const uuid_command* uc = (const uuid_command*)cmd; result = UUID(uc->uuid); stop = true; } }); diag.assertNoError(); return result; } void MachOFile::forEachDependentDylib(void (^callback)(const char* loadPath, bool isWeak, bool isReExport, bool isUpward, uint32_t compatVersion, uint32_t curVersion, bool& stop)) const { Diagnostics diag; __block unsigned count = 0; __block bool stopped = false; forEachLoadCommand(diag, ^(const load_command* cmd, bool& stop) { switch ( cmd->cmd ) { case LC_LOAD_DYLIB: case LC_LOAD_WEAK_DYLIB: case LC_REEXPORT_DYLIB: case LC_LOAD_UPWARD_DYLIB: { const dylib_command* dylibCmd = (dylib_command*)cmd; const char* loadPath = (char*)dylibCmd + dylibCmd->dylib.name.offset; callback(loadPath, (cmd->cmd == LC_LOAD_WEAK_DYLIB), (cmd->cmd == LC_REEXPORT_DYLIB), (cmd->cmd == LC_LOAD_UPWARD_DYLIB), dylibCmd->dylib.compatibility_version, dylibCmd->dylib.current_version, stop); ++count; if ( stop ) stopped = true; } break; } }); (void)count; (void)stopped; #if !BUILDING_SHARED_CACHE_UTIL && !BUILDING_DYLDINFO && !BUILDING_UNIT_TESTS // everything must link with something if ( (count == 0) && !stopped ) { // The dylibs that make up libSystem can link with nothing // except for dylibs in libSystem.dylib which are ok to link with nothing (they are on bottom) #if TARGET_OS_EXCLAVEKIT if ( !this->isDylib() || (strncmp(this->installName(), "/System/ExclaveKit/usr/lib/system/", 34) != 0) ) callback("/System/ExclaveKit/usr/lib/libSystem.dylib", false, false, false, 0x00010000, 0x00010000, stopped); #else if ( this->builtForPlatform(Platform::driverKit, true) ) { if ( !this->isDylib() || (strncmp(this->installName(), "/System/DriverKit/usr/lib/system/", 33) != 0) ) callback("/System/DriverKit/usr/lib/libSystem.B.dylib", false, false, false, 0x00010000, 0x00010000, stopped); } else if ( this->builtForPlatform(Platform::macOSExclaveKit, true) || this->builtForPlatform(Platform::iOSExclaveKit, true) || this->builtForPlatform(Platform::tvOSExclaveKit, true) ) { // do nothing for ExclaveKit dylibs // FIXME: only allow this behavior on internal builds } else { if ( !this->isDylib() || (strncmp(this->installName(), "/usr/lib/system/", 16) != 0) ) callback("/usr/lib/libSystem.B.dylib", false, false, false, 0x00010000, 0x00010000, stopped); } #endif // TARGET_OS_EXCLAVEKIT } #endif // !BUILDING_SHARED_CACHE_UTIL && !BUILDING_DYLDINFO && !BUILDING_UNIT_TESTS diag.assertNoError(); // any malformations in the file should have been caught by earlier validate() call } void MachOFile::forDyldEnv(void (^callback)(const char* envVar, bool& stop)) const { Diagnostics diag; forEachLoadCommand(diag, ^(const load_command* cmd, bool& stop) { if ( cmd->cmd == LC_DYLD_ENVIRONMENT ) { const dylinker_command* envCmd = (dylinker_command*)cmd; const char* keyEqualsValue = (char*)envCmd + envCmd->name.offset; // only process variables that start with DYLD_ if ( (strncmp(keyEqualsValue, "DYLD_", 5) == 0) ) { const char* equals = strchr(keyEqualsValue, '='); if ( equals != NULL ) { callback(keyEqualsValue, stop); } } } }); diag.assertNoError(); // any malformations in the file should have been caught by earlier validate() call } bool MachOFile::enforceCompatVersion() const { __block bool result = true; forEachSupportedPlatform(^(Platform platform, uint32_t minOS, uint32_t sdk) { switch ( platform ) { case Platform::macOS: if ( minOS >= 0x000A0E00 ) // macOS 10.14 result = false; break; case Platform::iOS: case Platform::tvOS: case Platform::iOS_simulator: case Platform::tvOS_simulator: if ( minOS >= 0x000C0000 ) // iOS 12.0 result = false; break; case Platform::watchOS: case Platform::watchOS_simulator: if ( minOS >= 0x00050000 ) // watchOS 5.0 result = false; break; case Platform::bridgeOS: if ( minOS >= 0x00030000 ) // bridgeOS 3.0 result = false; break; case Platform::driverKit: case Platform::iOSMac: result = false; break; case Platform::visionOS: case Platform::visionOS_simulator: result = false; break; case Platform::macOSExclaveCore: case Platform::macOSExclaveKit: case Platform::iOSExclaveCore: case Platform::iOSExclaveKit: case Platform::tvOSExclaveCore: case Platform::tvOSExclaveKit: result = false; break; case Platform::unknown: break; } }); return result; } const thread_command* MachOFile::unixThreadLoadCommand() const { Diagnostics diag; __block const thread_command* command = nullptr; forEachLoadCommand(diag, ^(const load_command* cmd, bool& stop) { if ( cmd->cmd == LC_UNIXTHREAD ) { command = (const thread_command*)cmd; stop = true; } }); return command; } const linkedit_data_command* MachOFile::chainedFixupsCmd() const { Diagnostics diag; __block const linkedit_data_command* command = nullptr; forEachLoadCommand(diag, ^(const load_command* cmd, bool& stop) { if ( cmd->cmd == LC_DYLD_CHAINED_FIXUPS ) { command = (const linkedit_data_command*)cmd; stop = true; } }); return command; } uint32_t MachOFile::entryAddrRegisterIndexForThreadCmd() const { switch ( this->cputype ) { case CPU_TYPE_I386: return 10; // i386_thread_state_t.eip case CPU_TYPE_X86_64: return 16; // x86_thread_state64_t.rip case CPU_TYPE_ARM: return 15; // arm_thread_state_t.pc case CPU_TYPE_ARM64: case CPU_TYPE_ARM64_32: return 32; // arm_thread_state64_t.__pc } return ~0U; } bool MachOFile::use64BitEntryRegs() const { return is64() || isArch("arm64_32"); } uint64_t MachOFile::entryAddrFromThreadCmd(const thread_command* cmd) const { assert(cmd->cmd == LC_UNIXTHREAD); const uint32_t* regs32 = (uint32_t*)(((char*)cmd) + 16); const uint64_t* regs64 = (uint64_t*)(((char*)cmd) + 16); uint32_t index = entryAddrRegisterIndexForThreadCmd(); if (index == ~0U) return 0; return use64BitEntryRegs() ? regs64[index] : regs32[index]; } bool MachOFile::getEntry(uint64_t& offset, bool& usesCRT) const { Diagnostics diag; offset = 0; forEachLoadCommand(diag, ^(const load_command* cmd, bool& stop) { if ( cmd->cmd == LC_MAIN ) { entry_point_command* mainCmd = (entry_point_command*)cmd; usesCRT = false; offset = mainCmd->entryoff; stop = true; } else if ( cmd->cmd == LC_UNIXTHREAD ) { stop = true; usesCRT = true; uint64_t startAddress = entryAddrFromThreadCmd((thread_command*)cmd); offset = startAddress - preferredLoadAddress(); } }); return (offset != 0); } void MachOFile::forEachSegment(void (^callback)(const SegmentInfo& info, bool& stop)) const { Diagnostics diag; const bool intel32 = (this->cputype == CPU_TYPE_I386); __block uint32_t segIndex = 0; forEachLoadCommand(diag, ^(const load_command* cmd, bool& stop) { if ( cmd->cmd == LC_SEGMENT_64 ) { const segment_command_64* segCmd = (segment_command_64*)cmd; uint64_t sizeOfSections = segCmd->vmsize; uint8_t p2align = 0; const section_64* const sectionsStart = (section_64*)((char*)segCmd + sizeof(struct segment_command_64)); const section_64* const sectionsEnd = §ionsStart[segCmd->nsects]; for (const section_64* sect=sectionsStart; sect < sectionsEnd; ++sect) { sizeOfSections = sect->addr + sect->size - segCmd->vmaddr; if ( sect->align > p2align ) p2align = sect->align; } SegmentInfo info; info.fileOffset = segCmd->fileoff; info.fileSize = segCmd->filesize; info.vmAddr = segCmd->vmaddr; info.vmSize = segCmd->vmsize; info.sizeOfSections = sizeOfSections; info.segName = segCmd->segname; info.loadCommandOffset = (uint32_t)((uint8_t*)segCmd - (uint8_t*)this); info.protections = segCmd->initprot; info.textRelocs = false; info.readOnlyData = ((segCmd->flags & SG_READ_ONLY) != 0); info.isProtected = (segCmd->flags & SG_PROTECTED_VERSION_1) ? 1 : 0; info.hasZeroFill = (segCmd->initprot == 3) && (segCmd->filesize < segCmd->vmsize); info.p2align = p2align; info.segIndex = segIndex; callback(info, stop); ++segIndex; } else if ( cmd->cmd == LC_SEGMENT ) { const segment_command* segCmd = (segment_command*)cmd; uint64_t sizeOfSections = segCmd->vmsize; uint8_t p2align = 0; bool hasTextRelocs = false; const section* const sectionsStart = (section*)((char*)segCmd + sizeof(struct segment_command)); const section* const sectionsEnd = §ionsStart[segCmd->nsects]; for (const section* sect=sectionsStart; sect < sectionsEnd; ++sect) { sizeOfSections = sect->addr + sect->size - segCmd->vmaddr; if ( sect->align > p2align ) p2align = sect->align; if ( sect->flags & (S_ATTR_EXT_RELOC|S_ATTR_LOC_RELOC) ) hasTextRelocs = true; } SegmentInfo info; info.fileOffset = segCmd->fileoff; info.fileSize = segCmd->filesize; info.vmAddr = segCmd->vmaddr; info.vmSize = segCmd->vmsize; info.sizeOfSections = sizeOfSections; info.segName = segCmd->segname; info.loadCommandOffset = (uint32_t)((uint8_t*)segCmd - (uint8_t*)this); info.protections = segCmd->initprot; info.textRelocs = intel32 && !info.writable() && hasTextRelocs; info.readOnlyData = ((segCmd->flags & SG_READ_ONLY) != 0); info.isProtected = (segCmd->flags & SG_PROTECTED_VERSION_1) ? 1 : 0; info.hasZeroFill = (segCmd->initprot == 3) && (segCmd->filesize < segCmd->vmsize); info.p2align = p2align; info.segIndex = segIndex; callback(info, stop); ++segIndex; } }); diag.assertNoError(); // any malformations in the file should have been caught by earlier validate() call } uint64_t MachOFile::preferredLoadAddress() const { __block uint64_t textVmAddr = 0; forEachSegment(^(const SegmentInfo& info, bool& stop) { if ( strcmp(info.segName, "__TEXT") == 0 ) { textVmAddr = info.vmAddr; stop = true; } }); return textVmAddr; } void MachOFile::forEachSection(void (^callback)(const SectionInfo& sectInfo, bool malformedSectionRange, bool& stop)) const { Diagnostics diag; BLOCK_ACCCESSIBLE_ARRAY(char, sectNameCopy, 20); // read as: char sectNameCopy[20]; const bool intel32 = (this->cputype == CPU_TYPE_I386); __block uint32_t segIndex = 0; forEachLoadCommand(diag, ^(const load_command* cmd, bool& stop) { SectionInfo sectInfo; if ( cmd->cmd == LC_SEGMENT_64 ) { const segment_command_64* segCmd = (segment_command_64*)cmd; uint64_t sizeOfSections = segCmd->vmsize; uint8_t p2align = 0; const section_64* const sectionsStart = (section_64*)((char*)segCmd + sizeof(struct segment_command_64)); const section_64* const sectionsEnd = §ionsStart[segCmd->nsects]; for (const section_64* sect=sectionsStart; sect < sectionsEnd; ++sect) { sizeOfSections = sect->addr + sect->size - segCmd->vmaddr; if ( sect->align > p2align ) p2align = sect->align; } sectInfo.segInfo.fileOffset = segCmd->fileoff; sectInfo.segInfo.fileSize = segCmd->filesize; sectInfo.segInfo.vmAddr = segCmd->vmaddr; sectInfo.segInfo.vmSize = segCmd->vmsize; sectInfo.segInfo.sizeOfSections = sizeOfSections; sectInfo.segInfo.segName = segCmd->segname; sectInfo.segInfo.loadCommandOffset = (uint32_t)((uint8_t*)segCmd - (uint8_t*)this); sectInfo.segInfo.protections = segCmd->initprot; sectInfo.segInfo.textRelocs = false; sectInfo.segInfo.readOnlyData = ((segCmd->flags & SG_READ_ONLY) != 0); sectInfo.segInfo.isProtected = (segCmd->flags & SG_PROTECTED_VERSION_1) ? 1 : 0; sectInfo.segInfo.p2align = p2align; sectInfo.segInfo.segIndex = segIndex; for (const section_64* sect=sectionsStart; !stop && (sect < sectionsEnd); ++sect) { const char* sectName = sect->sectname; if ( sectName[15] != '\0' ) { strlcpy(sectNameCopy, sectName, 17); sectName = sectNameCopy; } bool malformedSectionRange = (sect->addr < segCmd->vmaddr) || greaterThanAddOrOverflow(sect->addr, sect->size, segCmd->vmaddr + segCmd->filesize); sectInfo.sectName = sectName; sectInfo.sectFileOffset = sect->offset; sectInfo.sectFlags = sect->flags; sectInfo.sectAddr = sect->addr; sectInfo.sectSize = sect->size; sectInfo.sectAlignP2 = sect->align; sectInfo.reserved1 = sect->reserved1; sectInfo.reserved2 = sect->reserved2; callback(sectInfo, malformedSectionRange, stop); } ++segIndex; } else if ( cmd->cmd == LC_SEGMENT ) { const segment_command* segCmd = (segment_command*)cmd; uint64_t sizeOfSections = segCmd->vmsize; uint8_t p2align = 0; bool hasTextRelocs = false; const section* const sectionsStart = (section*)((char*)segCmd + sizeof(struct segment_command)); const section* const sectionsEnd = §ionsStart[segCmd->nsects]; for (const section* sect=sectionsStart; sect < sectionsEnd; ++sect) { sizeOfSections = sect->addr + sect->size - segCmd->vmaddr; if ( sect->align > p2align ) p2align = sect->align; if ( sect->flags & (S_ATTR_EXT_RELOC|S_ATTR_LOC_RELOC) ) hasTextRelocs = true; } sectInfo.segInfo.fileOffset = segCmd->fileoff; sectInfo.segInfo.fileSize = segCmd->filesize; sectInfo.segInfo.vmAddr = segCmd->vmaddr; sectInfo.segInfo.vmSize = segCmd->vmsize; sectInfo.segInfo.sizeOfSections = sizeOfSections; sectInfo.segInfo.segName = segCmd->segname; sectInfo.segInfo.loadCommandOffset = (uint32_t)((uint8_t*)segCmd - (uint8_t*)this); sectInfo.segInfo.protections = segCmd->initprot; sectInfo.segInfo.textRelocs = intel32 && !sectInfo.segInfo.writable() && hasTextRelocs; sectInfo.segInfo.readOnlyData = ((segCmd->flags & SG_READ_ONLY) != 0); sectInfo.segInfo.isProtected = (segCmd->flags & SG_PROTECTED_VERSION_1) ? 1 : 0; sectInfo.segInfo.p2align = p2align; sectInfo.segInfo.segIndex = segIndex; for (const section* sect=sectionsStart; !stop && (sect < sectionsEnd); ++sect) { const char* sectName = sect->sectname; if ( sectName[15] != '\0' ) { strlcpy(sectNameCopy, sectName, 17); sectName = sectNameCopy; } bool malformedSectionRange = (sect->addr < segCmd->vmaddr) || greaterThanAddOrOverflow(sect->addr, sect->size, segCmd->vmaddr + segCmd->filesize); sectInfo.sectName = sectName; sectInfo.sectFileOffset = sect->offset; sectInfo.sectFlags = sect->flags; sectInfo.sectAddr = sect->addr; sectInfo.sectSize = sect->size; sectInfo.sectAlignP2 = sect->align; sectInfo.reserved1 = sect->reserved1; sectInfo.reserved2 = sect->reserved2; callback(sectInfo, malformedSectionRange, stop); } ++segIndex; } }); diag.assertNoError(); // any malformations in the file should have been caught by earlier validate() call } void MachOFile::forEachInterposingSection(Diagnostics& diag, void (^handler)(uint64_t vmOffset, uint64_t vmSize, bool& stop)) const { const unsigned ptrSize = pointerSize(); const unsigned entrySize = 2 * ptrSize; forEachSection(^(const MachOFile::SectionInfo& info, bool malformedSectionRange, bool &stop) { if ( ((info.sectFlags & SECTION_TYPE) == S_INTERPOSING) || ((strcmp(info.sectName, "__interpose") == 0) && ((strncmp(info.segInfo.segName, "__DATA", 6) == 0) || strncmp(info.segInfo.segName, "__AUTH", 6) == 0)) ) { if ( info.sectSize % entrySize != 0 ) { diag.error("interposing section %s/%s has bad size", info.segInfo.segName, info.sectName); stop = true; return; } if ( malformedSectionRange ) { diag.error("interposing section %s/%s extends beyond the end of the segment", info.segInfo.segName, info.sectName); stop = true; return; } if ( (info.sectAddr % ptrSize) != 0 ) { diag.error("interposing section %s/%s is not pointer aligned", info.segInfo.segName, info.sectName); stop = true; return; } handler(info.sectAddr - preferredLoadAddress(), info.sectSize, stop); } }); } bool MachOFile::isRestricted() const { __block bool result = false; forEachSection(^(const MachOFile::SectionInfo& info, bool malformedSectionRange, bool &stop) { if ( (strcmp(info.segInfo.segName, "__RESTRICT") == 0) && (strcmp(info.sectName, "__restrict") == 0) ) { result = true; stop = true; } }); return result; } bool MachOFile::hasWeakDefs() const { return (this->flags & MH_WEAK_DEFINES); } bool MachOFile::usesWeakDefs() const { return (this->flags & MH_BINDS_TO_WEAK); } bool MachOFile::hasThreadLocalVariables() const { return (this->flags & MH_HAS_TLV_DESCRIPTORS); } #if BUILDING_CACHE_BUILDER || BUILDING_CACHE_BUILDER_UNIT_TESTS || BUILDING_UNIT_TESTS || BUILDING_DYLD_SYMBOLS_CACHE static bool endsWith(const char* str, const char* suffix) { size_t strLen = strlen(str); size_t suffixLen = strlen(suffix); if ( strLen < suffixLen ) return false; return (strcmp(&str[strLen-suffixLen], suffix) == 0); } bool MachOFile::isSharedCacheEligiblePath(const char* dylibName) { return ( (strncmp(dylibName, "/usr/lib/", 9) == 0) || (strncmp(dylibName, "/System/Library/", 16) == 0) || (strncmp(dylibName, "/System/iOSSupport/usr/lib/", 27) == 0) || (strncmp(dylibName, "/System/iOSSupport/System/Library/", 34) == 0) || (strncmp(dylibName, "/Library/Apple/usr/lib/", 23) == 0) || (strncmp(dylibName, "/Library/Apple/System/Library/", 30) == 0) || (strncmp(dylibName, "/System/DriverKit/", 18) == 0) || (strncmp(dylibName, "/System/Cryptexes/OS/usr/lib/", 29) == 0) || (strncmp(dylibName, "/System/Cryptexes/OS/System/Library/", 36) == 0) || (strncmp(dylibName, "/System/Cryptexes/OS/System/iOSSupport/usr/lib/", 47) == 0) || (strncmp(dylibName, "/System/Cryptexes/OS/System/iOSSupport/System/Library/", 54) == 0) || (strncmp(dylibName, "/System/ExclaveKit/usr/lib/", 27) == 0) || (strncmp(dylibName, "/System/ExclaveKit/System/Library/", 34) == 0)); } static bool startsWith(const char* buffer, const char* valueToFind) { return strncmp(buffer, valueToFind, strlen(valueToFind)) == 0; } static bool platformExcludesSharedCache_macOS(const char* installName) { // Note: This function basically matches dontCache() from update dyld shared cache if ( startsWith(installName, "/usr/lib/system/introspection/") ) return true; if ( startsWith(installName, "/System/Library/QuickTime/") ) return true; if ( startsWith(installName, "/System/Library/Tcl/") ) return true; if ( startsWith(installName, "/System/Library/Perl/") ) return true; if ( startsWith(installName, "/System/Library/MonitorPanels/") ) return true; if ( startsWith(installName, "/System/Library/Accessibility/") ) return true; if ( startsWith(installName, "/usr/local/") ) return true; if ( startsWith(installName, "/usr/lib/pam/") ) return true; // We no longer support ROSP, so skip all paths which start with the special prefix if ( startsWith(installName, "/System/Library/Templates/Data/") ) return true; // anything inside a .app bundle is specific to app, so should not be in shared cache if ( strstr(installName, ".app/") != NULL ) return true; // Depends on UHASHelloExtensionPoint-macOS which is not always cache eligible if ( !strcmp(installName, "/System/Library/PrivateFrameworks/HelloWorldMacHelper.framework/Versions/A/HelloWorldMacHelper") ) return true; return false; } static bool platformExcludesSharedCache_iOS(const char* installName) { if ( strcmp(installName, "/System/Library/Caches/com.apple.xpc/sdk.dylib") == 0 ) return true; if ( strcmp(installName, "/System/Library/Caches/com.apple.xpcd/xpcd_cache.dylib") == 0 ) return true; return false; } // Returns true if the current platform requires that this install name be excluded from the shared cache // Note that this overrides any exclusion from anywhere else. static bool platformExcludesSharedCache(Platform platform, const char* installName) { if ( (platform == dyld3::Platform::macOS) || (platform == dyld3::Platform::iOSMac) ) return platformExcludesSharedCache_macOS(installName); // Everything else is based on iOS so just use that value return platformExcludesSharedCache_iOS(installName); } #if !BUILDING_DYLD bool MachOFile::addendsExceedPatchTableLimit(Diagnostics& diag, mach_o::Fixups fixups) const { // rdar://122906481 (Shared cache builder - explicitly model dylibs without a need for a patch table) if ( strcmp(installName(), "/usr/lib/libswiftPrespecialized.dylib") == 0 ) return false; const bool is64bit = is64(); const uint64_t tooLargeRegularAddend = 1 << 23; const uint64_t tooLargeAuthAddend = 1 << 5; __block bool addendTooLarge = false; if ( this->hasChainedFixups() ) { // with chained fixups, addends can be in the import table or embedded in a bind pointer __block std::vector<uint64_t> targetAddends; fixups.forEachChainedFixupTarget(diag, ^(int libOrdinal, const char* symbolName, uint64_t addend, bool weakImport, bool& stop) { if ( is64bit ) addend &= 0x00FFFFFFFFFFFFFF; // ignore TBI targetAddends.push_back(addend); }); // check each pointer for embedded addend fixups.withChainStarts(diag, ^(const dyld_chained_starts_in_image* starts) { fixups.forEachFixupInAllChains(diag, starts, false, ^(mach_o::ChainedFixupPointerOnDisk* fixupLoc, uint64_t fixupSegmentOffset, const dyld_chained_starts_in_segment* segInfo, bool& stop) { switch (segInfo->pointer_format) { case DYLD_CHAINED_PTR_ARM64E: case DYLD_CHAINED_PTR_ARM64E_USERLAND: if ( fixupLoc->arm64e.bind.bind ) { uint64_t ordinal = fixupLoc->arm64e.bind.ordinal; uint64_t addend = (ordinal < targetAddends.size()) ? targetAddends[ordinal] : 0; if ( fixupLoc->arm64e.bind.auth ) { if ( addend >= tooLargeAuthAddend ) { addendTooLarge = true; stop = true; } } else { addend += fixupLoc->arm64e.signExtendedAddend(); if ( addend >= tooLargeRegularAddend ) { addendTooLarge = true; stop = true; } } } break; case DYLD_CHAINED_PTR_ARM64E_USERLAND24: if ( fixupLoc->arm64e.bind24.bind ) { uint64_t ordinal = fixupLoc->arm64e.bind24.ordinal; uint64_t addend = (ordinal < targetAddends.size()) ? targetAddends[ordinal] : 0; if ( fixupLoc->arm64e.bind24.auth ) { if ( addend >= tooLargeAuthAddend ) { addendTooLarge = true; stop = true; } } else { addend += fixupLoc->arm64e.signExtendedAddend(); if ( addend >= tooLargeRegularAddend ) { addendTooLarge = true; stop = true; } } } break; case DYLD_CHAINED_PTR_64: case DYLD_CHAINED_PTR_64_OFFSET: { if ( fixupLoc->generic64.rebase.bind ) { uint64_t ordinal = fixupLoc->generic64.bind.ordinal; uint64_t addend = (ordinal < targetAddends.size()) ? targetAddends[ordinal] : 0; addend += fixupLoc->generic64.bind.addend; if ( addend >= tooLargeRegularAddend ) { addendTooLarge = true; stop = true; } } break; } case DYLD_CHAINED_PTR_32: if ( fixupLoc->generic32.bind.bind ) { uint64_t ordinal = fixupLoc->generic32.bind.ordinal; uint64_t addend = (ordinal < targetAddends.size()) ? targetAddends[ordinal] : 0; addend += fixupLoc->generic32.bind.addend; if ( addend >= tooLargeRegularAddend ) { addendTooLarge = true; stop = true; } } break; } }); }); } else { // scan bind opcodes for large addend auto handler = ^(const mach_o::Fixups::BindTargetInfo &info, bool &stop) { uint64_t addend = info.addend; if ( is64bit ) addend &= 0x00FFFFFFFFFFFFFF; // ignore TBI if ( addend >= tooLargeRegularAddend ) { addendTooLarge = true; stop = true; } }; fixups.forEachBindTarget_Opcodes(diag, true, handler, handler); } return addendTooLarge; } bool MachOFile::canBePlacedInDyldCache(const char* path, void (^failureReason)(const char* format, ...)) const { if ( !isSharedCacheEligiblePath(path) ) { // Dont spam the user with an error about paths when we know these are never eligible. return false; } // only dylibs can go in cache if ( !this->isDylib() && !this->isDyld() ) { failureReason("Not MH_DYLIB"); return false; // cannot continue, installName() will assert() if not a dylib } const char* dylibName = installName(); if ( dylibName[0] != '/' ) { failureReason("install name not an absolute path"); // Don't continue as we don't want to spam the log with errors we don't need. return false; } else if ( strcmp(dylibName, path) != 0 ) { failureReason("install path does not match install name"); return false; } else if ( strstr(dylibName, "//") != 0 ) { failureReason("install name should not include //"); return false; } else if ( strstr(dylibName, "./") != 0 ) { failureReason("install name should not include ./"); return false; } __block bool platformExcludedFile = false; forEachSupportedPlatform(^(Platform platform, uint32_t minOS, uint32_t sdk) { if ( platformExcludedFile ) return; if ( platformExcludesSharedCache(platform, dylibName) ) { platformExcludedFile = true; return; } }); if ( platformExcludedFile ) { failureReason("install name is not shared cache eligible on platform"); return false; } // flat namespace files cannot go in cache if ( (this->flags & MH_TWOLEVEL) == 0 ) { failureReason("Not built with two level namespaces"); return false; } // don't put debug variants into dyld cache if ( endsWith(path, "_profile.dylib") || endsWith(path, "_debug.dylib") || endsWith(path, "_asan.dylib") || endsWith(path, "_profile") || endsWith(path, "_debug") || endsWith(path, "/CoreADI") ) { failureReason("Variant image"); return false; } // dylib must have extra info for moving DATA and TEXT segments apart __block bool hasExtraInfo = false; __block bool hasSplitSegMarker = false; __block bool hasDyldInfo = false; __block bool hasExportTrie = false; __block Diagnostics diag; forEachLoadCommand(diag, ^(const load_command* cmd, bool& stop) { if ( cmd->cmd == LC_SEGMENT_SPLIT_INFO ) { const linkedit_data_command* sigCmd = (linkedit_data_command*)cmd; if ( sigCmd->datasize == 0 ) hasSplitSegMarker = true; else hasExtraInfo = true; } if ( cmd->cmd == LC_DYLD_INFO_ONLY ) hasDyldInfo = true; if ( cmd->cmd == LC_DYLD_EXPORTS_TRIE ) hasExportTrie = true; }); if ( !hasExtraInfo ) { std::string_view ignorePaths[] = { "/usr/lib/libobjc-trampolines.dylib", "/usr/lib/libffi-trampolines.dylib" }; for ( std::string_view ignorePath : ignorePaths ) { if ( ignorePath == path ) return false; } if ( hasSplitSegMarker ) failureReason("Dylib explicitly linked with '-not_for_dyld_shared_cache'"); else failureReason("Missing split seg info"); return false; } if ( !hasDyldInfo && !hasExportTrie ) { failureReason("Old binary, missing dyld info or export trie"); return false; } // dylib can only depend on other dylibs in the shared cache __block const char* badDep = nullptr; forEachDependentDylib(^(const char* loadPath, bool isWeak, bool isReExport, bool isUpward, uint32_t compatVersion, uint32_t curVersion, bool& stop) { // Skip weak links. They are allowed to be missing if ( isWeak ) return; if ( !isSharedCacheEligiblePath(loadPath) ) { badDep = loadPath; stop = true; } }); if ( badDep != nullptr ) { failureReason("Depends on dylibs ineligible for dyld cache '%s'. (cache dylibs must start /usr/lib or /System/Library or similar)", badDep); return false; } // dylibs with interposing info cannot be in cache if ( hasInterposingTuples() ) { failureReason("Has interposing tuples"); return false; } // Temporarily kick out swift binaries out of dyld cache on watchOS simulators as they have missing split seg if ( (this->cputype == CPU_TYPE_I386) && builtForPlatform(Platform::watchOS_simulator) ) { if ( strncmp(dylibName, "/usr/lib/swift/", 15) == 0 ) { failureReason("i386 swift binary"); return false; } } // These used to be in MachOAnalyzer __block bool passedLinkeditChecks = false; this->withFileLayout(diag, ^(const mach_o::Layout &layout) { mach_o::SplitSeg splitSeg(layout); mach_o::Fixups fixups(layout); // arm64e requires split seg v2 as the split seg code can't handle chained fixups for split seg v1 if ( isArch("arm64e") ) { if ( !splitSeg.isV2() ) { failureReason("chained fixups requires split seg v2"); return; } } // evict swift dylibs with split seg v1 info if ( layout.isSwiftLibrary() && splitSeg.isV1() ) return; // arm64e requires signed class ROs if ( isArch("arm64e") ) { if ( std::optional<uint32_t> flags = layout.getObjcInfoFlags(); flags.has_value() ) { if ( (flags.value() & mach_o::ObjCImageInfo::OBJC_IMAGE_SIGNED_CLASS_RO) == 0 ) { failureReason("arm64e binaries must have signed Objective-C class_ro_t pointers"); return; } } } if ( splitSeg.isV1() ) { // Split seg v1 can only support 1 __DATA, and no other writable segments __block bool foundBadSegment = false; forEachSegment(^(const SegmentInfo& info, bool& stop) { if ( info.protections == (VM_PROT_READ | VM_PROT_WRITE) ) { if ( strcmp(info.segName, "__DATA") == 0 ) return; failureReason("RW segments other than __DATA requires split seg v2"); foundBadSegment = true; stop = true; } }); if ( foundBadSegment ) return; } // <rdar://problem/57769033> dyld_cache_patchable_location only supports addend in range 0..31 // rdar://96164956 (dyld needs to support arbitrary addends in cache patch table) bool addendTooLarge = addendsExceedPatchTableLimit(diag, fixups); if ( addendTooLarge ) { failureReason("bind addend too large"); return; } if ( (isArch("x86_64") || isArch("x86_64h")) ) { __block bool rebasesOk = true; uint64_t startVMAddr = preferredLoadAddress(); uint64_t endVMAddr = startVMAddr + mappedSize(); fixups.forEachRebase(diag, ^(uint64_t runtimeOffset, uint64_t rebasedValue, bool &stop) { // We allow TBI for x86_64 dylibs, but then require that the remainder of the offset // is a 32-bit offset from the mach-header. rebasedValue &= 0x00FFFFFFFFFFFFFFULL; if ( (rebasedValue < startVMAddr) || (rebasedValue >= endVMAddr) ) { failureReason("rebase value out of range of dylib"); rebasesOk = false; stop = true; return; } // Also error if the rebase location is anything other than 4/8 byte aligned if ( (runtimeOffset & 0x3) != 0 ) { failureReason("rebase value is not 4-byte aligned"); rebasesOk = false; stop = true; return; } // Error if the fixup will cross a page if ( (runtimeOffset & 0xFFF) == 0xFFC ) { failureReason("rebase value crosses page boundary"); rebasesOk = false; stop = true; return; } }); if ( !rebasesOk ) return; if ( this->hasChainedFixups() ) { fixups.withChainStarts(diag, ^(const dyld_chained_starts_in_image* starts) { fixups.forEachFixupInAllChains(diag, starts, false, ^(mach_o::ChainedFixupPointerOnDisk* fixupLoc, uint64_t fixupSegmentOffset, const dyld_chained_starts_in_segment* segInfo, bool& stop) { if ( (fixupSegmentOffset & 0xFFF) == 0xFFC ) { failureReason("chained fixup crosses page boundary"); rebasesOk = false; stop = true; return; } }); }); } if ( !rebasesOk ) return; } // Check that shared cache dylibs don't use undefined lookup { __block bool bindsOk = true; auto checkBind = ^(int libOrdinal, bool& stop) { if ( libOrdinal == BIND_SPECIAL_DYLIB_FLAT_LOOKUP ) { failureReason("has dynamic_lookup binds"); bindsOk = false; stop = true; } }; if (hasChainedFixups()) { fixups.forEachChainedFixupTarget(diag, ^(int libOrdinal, const char* symbolName, uint64_t addend, bool weakImport, bool& stop) { checkBind(libOrdinal, stop); }); } else { auto handler = ^(const mach_o::Fixups::BindTargetInfo &info, bool &stop) { checkBind(info.libOrdinal, stop); }; fixups.forEachBindTarget_Opcodes(diag, true, handler, handler); } if ( !bindsOk ) return; } passedLinkeditChecks = true; }); if ( !passedLinkeditChecks ) return false; // Check there are no pointer based objc method lists in CONST segments #if BUILDING_CACHE_BUILDER || BUILDING_CACHE_BUILDER_UNIT_TESTS { typedef std::pair<VMAddress, VMAddress> Range; __block std::vector<Range> constRanges; this->forEachSegment(^(const SegmentInfo& info, bool& stop) { if ( info.vmSize == 0 ) return; if ( !strcmp(info.segName, "__DATA_CONST") || !strcmp(info.segName, "__AUTH_CONST") ) constRanges.push_back({ VMAddress(info.vmAddr), VMAddress(info.vmAddr + info.vmSize) }); }); if ( !constRanges.empty() ) { __block objc_visitor::Visitor objcVisitor = this->makeObjCVisitor(diag); if ( diag.hasError() ) return false; // Returns true if the method list is bad, ie, a pointer based method list in _CONST segment auto isConstPointerBasedMethodList = ^(const objc_visitor::MethodList& methodList) { if ( (methodList.numMethods() == 0) || methodList.usesRelativeOffsets() ) return false; VMAddress methodListVMAddr = methodList.getVMAddress().value(); for ( const Range& range : constRanges ) { if ( (methodListVMAddr >= range.first) && (methodListVMAddr < range.second) ) return true; } return false; }; __block bool hasPointerMethodList = false; objcVisitor.forEachClassAndMetaClass(^(const objc_visitor::Class& objcClass, bool& stopClass) { if ( isConstPointerBasedMethodList(objcClass.getBaseMethods(objcVisitor)) ) { failureReason("has pointer based objc class method list in _CONST segment"); hasPointerMethodList = true; stopClass = true; } }); if ( hasPointerMethodList ) return false; objcVisitor.forEachCategory(^(const objc_visitor::Category& objcCategory, bool& stopCategory) { if ( isConstPointerBasedMethodList(objcCategory.getInstanceMethods(objcVisitor)) ) { failureReason("has pointer based objc category instance method list in _CONST segment"); hasPointerMethodList = true; stopCategory = true; } if ( isConstPointerBasedMethodList(objcCategory.getClassMethods(objcVisitor)) ) { failureReason("has pointer based objc category class method list in _CONST segment"); hasPointerMethodList = true; stopCategory = true; } }); if ( hasPointerMethodList ) return false; } } #endif // BUILDING_CACHE_BUILDER || BUILDING_CACHE_BUILDER_UNIT_TESTS return true; } #if BUILDING_CACHE_BUILDER || BUILDING_CACHE_BUILDER_UNIT_TESTS objc_visitor::Visitor MachOFile::makeObjCVisitor(Diagnostics& diag) const { VMAddress dylibBaseAddress(this->preferredLoadAddress()); __block std::vector<metadata_visitor::Segment> segments; __block std::vector<uint64_t> bindTargets; this->withFileLayout(diag, ^(const mach_o::Layout &layout) { for ( uint32_t segIndex = 0; segIndex != layout.segments.size(); ++segIndex ) { const auto& layoutSegment = layout.segments[segIndex]; metadata_visitor::Segment segment { .startVMAddr = VMAddress(layoutSegment.vmAddr), .endVMAddr = VMAddress(layoutSegment.vmAddr + layoutSegment.vmSize), .bufferStart = (uint8_t*)layoutSegment.buffer, .onDiskDylibChainedPointerFormat = 0, .segIndex = segIndex }; segments.push_back(std::move(segment)); } // Add chained fixup info to each segment, if we have it if ( this->hasChainedFixups() ) { mach_o::Fixups fixups(layout); fixups.withChainStarts(diag, ^(const dyld_chained_starts_in_image* starts) { mach_o::Fixups::forEachFixupChainSegment(diag, starts, ^(const dyld_chained_starts_in_segment *segInfo, uint32_t segIndex, bool &stop) { segments[segIndex].onDiskDylibChainedPointerFormat = segInfo->pointer_format; }); }); } // ObjC patching needs the bind targets for interposable references to the classes // build targets table if ( this->hasChainedFixupsLoadCommand() ) { mach_o::Fixups fixups(layout); fixups.forEachBindTarget_ChainedFixups(diag, ^(const mach_o::Fixups::BindTargetInfo &info, bool &stop) { if ( info.libOrdinal != BIND_SPECIAL_DYLIB_SELF ) { bindTargets.push_back(0); return; } mach_o::Layout::FoundSymbol foundInfo; if ( !layout.findExportedSymbol(diag, info.symbolName, info.weakImport, foundInfo) ) { bindTargets.push_back(0); return; } // We only support header offsets in this dylib, as we are looking for self binds // which are likely only to classes if ( (foundInfo.kind != mach_o::Layout::FoundSymbol::Kind::headerOffset) || (foundInfo.foundInDylib.value() != this) ) { bindTargets.push_back(0); return; } uint64_t vmAddr = layout.textUnslidVMAddr() + foundInfo.value; bindTargets.push_back(vmAddr); }); } }); std::optional<VMAddress> selectorStringsBaseAddress; objc_visitor::Visitor objcVisitor(dylibBaseAddress, this, std::move(segments), selectorStringsBaseAddress, std::move(bindTargets)); return objcVisitor; } #endif // BUILDING_CACHE_BUILDER || BUILDING_CACHE_BUILDER_UNIT_TESTS #endif // !BUILDING_DYLD // Returns true if the executable path is eligible for a PrebuiltLoader on the given platform. bool MachOFile::canHavePrebuiltExecutableLoader(dyld3::Platform platform, const std::string_view& path, void (^failureReason)(const char*)) const { // For now we can't build prebuilt loaders for the simulator if ( isSimulatorPlatform(platform) ) { // Don't spam with tons of messages about executables return false; } if ( (platform == dyld3::Platform::macOS) || (platform == dyld3::Platform::iOSMac) ) { // We no longer support ROSP, so skip all paths which start with the special prefix if ( path.starts_with("/System/Library/Templates/Data/") ) { // Dont spam the user with an error about paths when we know these are never eligible. return false; } static const char* sAllowedPrefixes[] = { "/bin/", "/sbin/", "/usr/", "/System/", "/Library/Apple/System/", "/Library/Apple/usr/", "/System/Applications/Safari.app/", "/Library/CoreMediaIO/Plug-Ins/DAL/" // temp until plugins moved or closured working }; bool inSearchDir = false; for ( const char* searchDir : sAllowedPrefixes ) { if ( path.starts_with(searchDir) ) { inSearchDir = true; break; } } if ( !inSearchDir ) { failureReason("path not eligible"); return false; } } else { // On embedded, only staged apps are excluded. They will run from a different location at runtime if ( path.find("/staged_system_apps/") != std::string::npos ) { // Dont spam the user with an error about paths when we know these are never eligible. return false; } } if ( !hasCodeSignature() ) { failureReason("missing code signature"); return false; } return true; } #endif #if BUILDING_APP_CACHE_UTIL bool MachOFile::canBePlacedInKernelCollection(const char* path, void (^failureReason)(const char*)) const { // only dylibs and the kernel itself can go in cache if ( this->filetype == MH_EXECUTE ) { // xnu } else if ( this->isKextBundle() ) { // kext's } else { failureReason("Not MH_KEXT_BUNDLE"); return false; } if ( this->filetype == MH_EXECUTE ) { // xnu // two-level namespace binaries cannot go in cache if ( (this->flags & MH_TWOLEVEL) != 0 ) { failureReason("Built with two level namespaces"); return false; } // xnu kernel cannot have a page zero __block bool foundPageZero = false; forEachSegment(^(const SegmentInfo &segmentInfo, bool &stop) { if ( strcmp(segmentInfo.segName, "__PAGEZERO") == 0 ) { foundPageZero = true; stop = true; } }); if (foundPageZero) { failureReason("Has __PAGEZERO"); return false; } // xnu must have an LC_UNIXTHREAD to point to the entry point __block bool foundMainLC = false; __block bool foundUnixThreadLC = false; Diagnostics diag; forEachLoadCommand(diag, ^(const load_command* cmd, bool& stop) { if ( cmd->cmd == LC_MAIN ) { foundMainLC = true; stop = true; } else if ( cmd->cmd == LC_UNIXTHREAD ) { foundUnixThreadLC = true; } }); if (foundMainLC) { failureReason("Found LC_MAIN"); return false; } if (!foundUnixThreadLC) { failureReason("Expected LC_UNIXTHREAD"); return false; } if (diag.hasError()) { failureReason("Error parsing load commands"); return false; } // The kernel should be a static executable, not a dynamic one if ( !isStaticExecutable() ) { failureReason("Expected static executable"); return false; } // The kernel must be built with -pie if ( !isPIE() ) { failureReason("Expected pie"); return false; } } if ( isArch("arm64e") && isKextBundle() && !hasChainedFixups() ) { failureReason("Missing fixup information"); return false; } // dylibs with interposing info cannot be in cache if ( hasInterposingTuples() ) { failureReason("Has interposing tuples"); return false; } // Only x86_64 is allowed to have RWX segments if ( !isArch("x86_64") && !isArch("x86_64h") ) { __block bool foundBadSegment = false; forEachSegment(^(const SegmentInfo &info, bool &stop) { if ( (info.protections & (VM_PROT_WRITE | VM_PROT_EXECUTE)) == (VM_PROT_WRITE | VM_PROT_EXECUTE) ) { failureReason("Segments are not allowed to be both writable and executable"); foundBadSegment = true; stop = true; } }); if ( foundBadSegment ) return false; } return true; } #endif // BUILDING_APP_CACHE_UTIL #if BUILDING_APP_CACHE_UTIL || BUILDING_DYLDINFO bool MachOFile::usesClassicRelocationsInKernelCollection() const { // The xnu x86_64 static executable needs to do the i386->x86_64 transition // so will be emitted with classic relocations if ( isArch("x86_64") || isArch("x86_64h") ) { return isStaticExecutable() || isFileSet(); } return false; } #endif // BUILDING_APP_CACHE_UTIL || BUILDING_DYLDINFO #if BUILDING_CACHE_BUILDER || BUILDING_CACHE_BUILDER_UNIT_TESTS static bool platformExcludesPrebuiltClosure_macOS(const char* path) { // We no longer support ROSP, so skip all paths which start with the special prefix if ( startsWith(path, "/System/Library/Templates/Data/") ) return true; // anything inside a .app bundle is specific to app, so should not get a prebuilt closure if ( strstr(path, ".app/") != NULL ) return true; return false; } static bool platformExcludesPrebuiltClosure_iOS(const char* path) { if ( strcmp(path, "/System/Library/Caches/com.apple.xpc/sdk.dylib") == 0 ) return true; if ( strcmp(path, "/System/Library/Caches/com.apple.xpcd/xpcd_cache.dylib") == 0 ) return true; return false; } // Returns true if the current platform requires that this install name be excluded from the shared cache // Note that this overrides any exclusion from anywhere else. static bool platformExcludesPrebuiltClosure(Platform platform, const char* path) { if ( MachOFile::isSimulatorPlatform(platform) ) return false; if ( (platform == dyld3::Platform::macOS) || (platform == dyld3::Platform::iOSMac) ) return platformExcludesPrebuiltClosure_macOS(path); // Everything else is based on iOS so just use that value return platformExcludesPrebuiltClosure_iOS(path); } bool MachOFile::canHavePrecomputedDlopenClosure(const char* path, void (^failureReason)(const char*)) const { __block bool retval = true; // only dylibs can go in cache if ( (this->filetype != MH_DYLIB) && (this->filetype != MH_BUNDLE) ) { retval = false; failureReason("not MH_DYLIB or MH_BUNDLE"); } // flat namespace files cannot go in cache if ( (this->flags & MH_TWOLEVEL) == 0 ) { retval = false; failureReason("not built with two level namespaces"); } // can only depend on other dylibs with absolute paths __block bool allDepPathsAreGood = true; forEachDependentDylib(^(const char* loadPath, bool isWeak, bool isReExport, bool isUpward, uint32_t compatVersion, uint32_t curVersion, bool& stop) { if ( loadPath[0] != '/' ) { allDepPathsAreGood = false; stop = true; } }); if ( !allDepPathsAreGood ) { retval = false; failureReason("depends on dylibs that are not absolute paths"); } __block bool platformExcludedFile = false; forEachSupportedPlatform(^(Platform platform, uint32_t minOS, uint32_t sdk) { if ( platformExcludedFile ) return; if ( platformExcludesPrebuiltClosure(platform, path) ) { platformExcludedFile = true; return; } }); if ( platformExcludedFile ) { failureReason("file cannot get a prebuilt closure on this platform"); return false; } // dylibs with interposing info cannot have dlopen closure pre-computed if ( hasInterposingTuples() ) { retval = false; failureReason("has interposing tuples"); } // special system dylib overrides cannot have closure pre-computed if ( strncmp(path, "/usr/lib/system/introspection/", 30) == 0 ) { retval = false; failureReason("override of OS dylib"); } return retval; } #endif bool MachOFile::hasInterposingTuples() const { __block bool hasInterposing = false; Diagnostics diag; forEachInterposingSection(diag, ^(uint64_t vmOffset, uint64_t vmSize, bool &stop) { hasInterposing = true; stop = true; }); return hasInterposing; } bool MachOFile::isFairPlayEncrypted(uint32_t& textOffset, uint32_t& size) const { if ( const encryption_info_command* encCmd = findFairPlayEncryptionLoadCommand() ) { if ( encCmd->cryptid == 1 ) { // Note: cryptid is 0 in just-built apps. The AppStore sets cryptid to 1 textOffset = encCmd->cryptoff; size = encCmd->cryptsize; return true; } } textOffset = 0; size = 0; return false; } bool MachOFile::canBeFairPlayEncrypted() const { return (findFairPlayEncryptionLoadCommand() != nullptr); } const encryption_info_command* MachOFile::findFairPlayEncryptionLoadCommand() const { __block const encryption_info_command* result = nullptr; Diagnostics diag; forEachLoadCommand(diag, ^(const load_command* cmd, bool& stop) { if ( (cmd->cmd == LC_ENCRYPTION_INFO) || (cmd->cmd == LC_ENCRYPTION_INFO_64) ) { result = (encryption_info_command*)cmd; stop = true; } }); if ( diag.noError() ) return result; else return nullptr; } bool MachOFile::hasLoadCommand(uint32_t cmdNum) const { __block bool hasLC = false; Diagnostics diag; forEachLoadCommand(diag, ^(const load_command* cmd, bool& stop) { if ( cmd->cmd == cmdNum ) { hasLC = true; stop = true; } }); return hasLC; } bool MachOFile::allowsAlternatePlatform() const { __block bool result = false; forEachSection(^(const SectionInfo& info, bool malformedSectionRange, bool& stop) { if ( (strcmp(info.sectName, "__allow_alt_plat") == 0) && (strncmp(info.segInfo.segName, "__DATA", 6) == 0) ) { result = true; stop = true; } }); return result; } bool MachOFile::hasChainedFixups() const { #if SUPPORT_ARCH_arm64e // arm64e always uses chained fixups if ( (this->cputype == CPU_TYPE_ARM64) && (this->maskedCpuSubtype() == CPU_SUBTYPE_ARM64E) ) { // Not all binaries have fixups at all so check for the load commands return hasLoadCommand(LC_DYLD_INFO_ONLY) || hasLoadCommand(LC_DYLD_CHAINED_FIXUPS); } #endif return hasLoadCommand(LC_DYLD_CHAINED_FIXUPS); } bool MachOFile::hasChainedFixupsLoadCommand() const { return hasLoadCommand(LC_DYLD_CHAINED_FIXUPS); } bool MachOFile::hasOpcodeFixups() const { return hasLoadCommand(LC_DYLD_INFO_ONLY) || hasLoadCommand(LC_DYLD_INFO) ; } uint16_t MachOFile::chainedPointerFormat(const dyld_chained_fixups_header* header) { const dyld_chained_starts_in_image* startsInfo = (dyld_chained_starts_in_image*)((uint8_t*)header + header->starts_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->page_count != 0 ) return segInfo->pointer_format; } return 0; // no chains (perhaps no __DATA segment) } // find dyld_chained_starts_in_image* in image // if old arm64e binary, synthesize dyld_chained_starts_in_image* void MachOFile::withChainStarts(Diagnostics& diag, const dyld_chained_fixups_header* chainHeader, void (^callback)(const dyld_chained_starts_in_image*)) { if ( chainHeader == nullptr ) { diag.error("Must pass in a chain header"); return; } // we have a pre-computed offset into LINKEDIT for dyld_chained_starts_in_image callback((dyld_chained_starts_in_image*)((uint8_t*)chainHeader + chainHeader->starts_offset)); } void MachOFile::forEachFixupChainSegment(Diagnostics& diag, const dyld_chained_starts_in_image* starts, void (^handler)(const dyld_chained_starts_in_segment* segInfo, uint32_t segIndex, bool& stop)) { bool stopped = false; for (uint32_t segIndex=0; segIndex < starts->seg_count && !stopped; ++segIndex) { if ( starts->seg_info_offset[segIndex] == 0 ) continue; const dyld_chained_starts_in_segment* segInfo = (dyld_chained_starts_in_segment*)((uint8_t*)starts + starts->seg_info_offset[segIndex]); handler(segInfo, segIndex, stopped); } } bool MachOFile::walkChain(Diagnostics& diag, ChainedFixupPointerOnDisk* chain, uint16_t pointer_format, bool notifyNonPointers, uint32_t max_valid_pointer, void (^handler)(ChainedFixupPointerOnDisk* fixupLocation, bool& stop)) { const unsigned stride = ChainedFixupPointerOnDisk::strideSize(pointer_format); bool stop = false; bool chainEnd = false; while (!stop && !chainEnd) { // copy chain content, in case handler modifies location to final value ChainedFixupPointerOnDisk chainContent = *chain; handler(chain, stop); if ( !stop ) { switch (pointer_format) { case DYLD_CHAINED_PTR_ARM64E: case DYLD_CHAINED_PTR_ARM64E_KERNEL: case DYLD_CHAINED_PTR_ARM64E_USERLAND: case DYLD_CHAINED_PTR_ARM64E_USERLAND24: case DYLD_CHAINED_PTR_ARM64E_FIRMWARE: if ( chainContent.arm64e.rebase.next == 0 ) chainEnd = true; else chain = (ChainedFixupPointerOnDisk*)((uint8_t*)chain + chainContent.arm64e.rebase.next*stride); break; case DYLD_CHAINED_PTR_ARM64E_SHARED_CACHE: if ( chainContent.cache64e.regular.next == 0 ) chainEnd = true; else chain = (ChainedFixupPointerOnDisk*)((uint8_t*)chain + chainContent.cache64e.regular.next*stride); break; case DYLD_CHAINED_PTR_64: case DYLD_CHAINED_PTR_64_OFFSET: if ( chainContent.generic64.rebase.next == 0 ) chainEnd = true; else chain = (ChainedFixupPointerOnDisk*)((uint8_t*)chain + chainContent.generic64.rebase.next*4); break; case DYLD_CHAINED_PTR_32: if ( chainContent.generic32.rebase.next == 0 ) chainEnd = true; else { chain = (ChainedFixupPointerOnDisk*)((uint8_t*)chain + chainContent.generic32.rebase.next*4); if ( !notifyNonPointers ) { while ( (chain->generic32.rebase.bind == 0) && (chain->generic32.rebase.target > max_valid_pointer) ) { // not a real pointer, but a non-pointer co-opted into chain chain = (ChainedFixupPointerOnDisk*)((uint8_t*)chain + chain->generic32.rebase.next*4); } } } break; case DYLD_CHAINED_PTR_64_KERNEL_CACHE: case DYLD_CHAINED_PTR_X86_64_KERNEL_CACHE: if ( chainContent.kernel64.next == 0 ) chainEnd = true; else chain = (ChainedFixupPointerOnDisk*)((uint8_t*)chain + chainContent.kernel64.next*stride); break; case DYLD_CHAINED_PTR_32_FIRMWARE: if ( chainContent.firmware32.next == 0 ) chainEnd = true; else chain = (ChainedFixupPointerOnDisk*)((uint8_t*)chain + chainContent.firmware32.next*4); break; default: diag.error("unknown pointer format 0x%04X", pointer_format); stop = true; } } } return stop; } void MachOFile::forEachFixupInSegmentChains(Diagnostics& diag, const dyld_chained_starts_in_segment* segInfo, bool notifyNonPointers, uint8_t* segmentContent, void (^handler)(ChainedFixupPointerOnDisk* fixupLocation, bool& stop)) { bool stopped = false; for (uint32_t pageIndex=0; pageIndex < segInfo->page_count && !stopped; ++pageIndex) { uint16_t offsetInPage = segInfo->page_start[pageIndex]; if ( offsetInPage == DYLD_CHAINED_PTR_START_NONE ) continue; if ( offsetInPage & DYLD_CHAINED_PTR_START_MULTI ) { // 32-bit chains which may need multiple starts per page uint32_t overflowIndex = offsetInPage & ~DYLD_CHAINED_PTR_START_MULTI; bool chainEnd = false; while (!stopped && !chainEnd) { chainEnd = (segInfo->page_start[overflowIndex] & DYLD_CHAINED_PTR_START_LAST); offsetInPage = (segInfo->page_start[overflowIndex] & ~DYLD_CHAINED_PTR_START_LAST); uint8_t* pageContentStart = segmentContent + (pageIndex * segInfo->page_size); ChainedFixupPointerOnDisk* chain = (ChainedFixupPointerOnDisk*)(pageContentStart+offsetInPage); stopped = walkChain(diag, chain, segInfo->pointer_format, notifyNonPointers, segInfo->max_valid_pointer, handler); ++overflowIndex; } } else { // one chain per page uint8_t* pageContentStart = segmentContent + (pageIndex * segInfo->page_size); ChainedFixupPointerOnDisk* chain = (ChainedFixupPointerOnDisk*)(pageContentStart+offsetInPage); stopped = walkChain(diag, chain, segInfo->pointer_format, notifyNonPointers, segInfo->max_valid_pointer, handler); } } } void MachOFile::forEachChainedFixupTarget(Diagnostics& diag, const dyld_chained_fixups_header* header, const linkedit_data_command* chainedFixups, void (^callback)(int libOrdinal, const char* symbolName, uint64_t addend, bool weakImport, bool& stop)) { if ( (header->imports_offset > chainedFixups->datasize) || (header->symbols_offset > chainedFixups->datasize) ) { diag.error("malformed import table"); return; } bool stop = false; const dyld_chained_import* imports; const dyld_chained_import_addend* importsA32; const dyld_chained_import_addend64* importsA64; const char* symbolsPool = (char*)header + header->symbols_offset; uint32_t maxSymbolOffset = chainedFixups->datasize - header->symbols_offset; int libOrdinal; switch (header->imports_format) { case DYLD_CHAINED_IMPORT: imports = (dyld_chained_import*)((uint8_t*)header + header->imports_offset); for (uint32_t i=0; i < header->imports_count && !stop; ++i) { const char* symbolName = &symbolsPool[imports[i].name_offset]; if ( imports[i].name_offset > maxSymbolOffset ) { diag.error("malformed import table, string overflow"); return; } uint8_t libVal = imports[i].lib_ordinal; if ( libVal > 0xF0 ) libOrdinal = (int8_t)libVal; else libOrdinal = libVal; callback(libOrdinal, symbolName, 0, imports[i].weak_import, stop); if ( stop ) return; } break; case DYLD_CHAINED_IMPORT_ADDEND: importsA32 = (dyld_chained_import_addend*)((uint8_t*)header + header->imports_offset); for (uint32_t i=0; i < header->imports_count && !stop; ++i) { const char* symbolName = &symbolsPool[importsA32[i].name_offset]; if ( importsA32[i].name_offset > maxSymbolOffset ) { diag.error("malformed import table, string overflow"); return; } uint8_t libVal = importsA32[i].lib_ordinal; if ( libVal > 0xF0 ) libOrdinal = (int8_t)libVal; else libOrdinal = libVal; callback(libOrdinal, symbolName, importsA32[i].addend, importsA32[i].weak_import, stop); if ( stop ) return; } break; case DYLD_CHAINED_IMPORT_ADDEND64: importsA64 = (dyld_chained_import_addend64*)((uint8_t*)header + header->imports_offset); for (uint32_t i=0; i < header->imports_count && !stop; ++i) { const char* symbolName = &symbolsPool[importsA64[i].name_offset]; if ( importsA64[i].name_offset > maxSymbolOffset ) { diag.error("malformed import table, string overflow"); return; } uint16_t libVal = importsA64[i].lib_ordinal; if ( libVal > 0xFFF0 ) libOrdinal = (int16_t)libVal; else libOrdinal = libVal; callback(libOrdinal, symbolName, importsA64[i].addend, importsA64[i].weak_import, stop); if ( stop ) return; } break; default: diag.error("unknown imports format"); return; } } uint64_t MachOFile::read_uleb128(Diagnostics& diag, const uint8_t*& p, const uint8_t* end) { uint64_t result = 0; int bit = 0; do { if ( p == end ) { diag.error("malformed uleb128"); break; } uint64_t slice = *p & 0x7f; if ( bit > 63 ) { diag.error("uleb128 too big for uint64"); break; } else { result |= (slice << bit); bit += 7; } } while (*p++ & 0x80); return result; } int64_t MachOFile::read_sleb128(Diagnostics& diag, const uint8_t*& p, const uint8_t* end) { int64_t result = 0; int bit = 0; uint8_t byte = 0; do { if ( p == end ) { diag.error("malformed sleb128"); break; } byte = *p++; result |= (((int64_t)(byte & 0x7f)) << bit); bit += 7; } while (byte & 0x80); // sign extend negative numbers if ( ((byte & 0x40) != 0) && (bit < 64) ) result |= (~0ULL) << bit; return result; } static void getArchNames(const GradedArchs& archs, bool isOSBinary, char buffer[256]) { buffer[0] = '\0'; archs.forEachArch(isOSBinary, ^(const char* archName) { if ( buffer[0] != '\0' ) strlcat(buffer, "' or '", 256); strlcat(buffer, archName, 256); }); } const MachOFile* MachOFile::compatibleSlice(Diagnostics& diag, uint64_t& sliceLenOut, const void* fileContent, size_t contentSize, const char* path, Platform platform, bool isOSBinary, const GradedArchs& archs, bool internalInstall) { const MachOFile* mf = nullptr; if ( const dyld3::FatFile* ff = dyld3::FatFile::isFatFile(fileContent) ) { uint64_t sliceOffset; uint64_t sliceLen; bool missingSlice; if ( ff->isFatFileWithSlice(diag, contentSize, archs, isOSBinary, sliceOffset, sliceLen, missingSlice) ) { mf = (MachOFile*)((long)fileContent + sliceOffset); sliceLenOut = sliceLen; } else { BLOCK_ACCCESSIBLE_ARRAY(char, gradedArchsBuf, 256); getArchNames(archs, isOSBinary, gradedArchsBuf); char strBuf[256]; diag.error("fat file, but missing compatible architecture (have '%s', need '%s')", ff->archNames(strBuf, contentSize), gradedArchsBuf); return nullptr; } } else { mf = (MachOFile*)fileContent; sliceLenOut = contentSize; } if ( !mf->hasMachOMagic() || !mf->isMachO(diag, contentSize) ) { if ( diag.noError() ) diag.error("not a mach-o file"); return nullptr; } if ( archs.grade(mf->cputype, mf->cpusubtype, isOSBinary) == 0 ) { BLOCK_ACCCESSIBLE_ARRAY(char, gradedArchsBuf, 256); getArchNames(archs, isOSBinary, gradedArchsBuf); diag.error("mach-o file, but is an incompatible architecture (have '%s', need '%s')", mf->archName(), gradedArchsBuf); return nullptr; } if ( !mf->loadableIntoProcess(platform, path, internalInstall) ) { __block Platform havePlatform = Platform::unknown; mf->forEachSupportedPlatform(^(Platform aPlat, uint32_t minOS, uint32_t sdk) { havePlatform = aPlat; }); diag.error("mach-o file (%s), but incompatible platform (have '%s', need '%s')", path, MachOFile::platformName(havePlatform), MachOFile::platformName(platform)); return nullptr; } return mf; } const uint8_t* MachOFile::trieWalk(Diagnostics& diag, const uint8_t* start, const uint8_t* end, const char* symbol) { STACK_ALLOC_OVERFLOW_SAFE_ARRAY(uint32_t, visitedNodeOffsets, 128); visitedNodeOffsets.push_back(0); const uint8_t* p = start; while ( p < end ) { uint64_t terminalSize = *p++; if ( terminalSize > 127 ) { // except for re-export-with-rename, all terminal sizes fit in one byte --p; terminalSize = read_uleb128(diag, p, end); if ( diag.hasError() ) return nullptr; } if ( (*symbol == '\0') && (terminalSize != 0) ) { return p; } const uint8_t* children = p + terminalSize; if ( children > end ) { //diag.error("malformed trie node, terminalSize=0x%llX extends past end of trie\n", terminalSize); return nullptr; } uint8_t childrenRemaining = *children++; p = children; uint64_t nodeOffset = 0; for (; childrenRemaining > 0; --childrenRemaining) { const char* ss = symbol; bool wrongEdge = false; // scan whole edge to get to next edge // if edge is longer than target symbol name, don't read past end of symbol name char c = *p; while ( c != '\0' ) { if ( !wrongEdge ) { if ( c != *ss ) wrongEdge = true; ++ss; } ++p; c = *p; } if ( wrongEdge ) { // advance to next child ++p; // skip over zero terminator // skip over uleb128 until last byte is found while ( (*p & 0x80) != 0 ) ++p; ++p; // skip over last byte of uleb128 if ( p > end ) { diag.error("malformed trie node, child node extends past end of trie\n"); return nullptr; } } else { // the symbol so far matches this edge (child) // so advance to the child's node ++p; nodeOffset = read_uleb128(diag, p, end); if ( diag.hasError() ) return nullptr; if ( (nodeOffset == 0) || ( &start[nodeOffset] > end) ) { diag.error("malformed trie child, nodeOffset=0x%llX out of range\n", nodeOffset); return nullptr; } symbol = ss; break; } } if ( nodeOffset != 0 ) { if ( nodeOffset > (uint64_t)(end-start) ) { diag.error("malformed trie child, nodeOffset=0x%llX out of range\n", nodeOffset); return nullptr; } // check for cycles for (uint32_t aVisitedNodeOffset : visitedNodeOffsets) { if ( aVisitedNodeOffset == nodeOffset ) { diag.error("malformed trie child, cycle to nodeOffset=0x%llX\n", nodeOffset); return nullptr; } } visitedNodeOffsets.push_back((uint32_t)nodeOffset); p = &start[nodeOffset]; } else p = end; } return nullptr; } void MachOFile::forEachRPath(void (^callback)(const char* rPath, bool& stop)) const { Diagnostics diag; forEachLoadCommand(diag, ^(const load_command* cmd, bool& stop) { if ( cmd->cmd == LC_RPATH ) { const char* rpath = (char*)cmd + ((struct rpath_command*)cmd)->path.offset; callback(rpath, stop); } }); diag.assertNoError(); // any malformations in the file should have been caught by earlier validate() call } bool MachOFile::inCodeSection(uint32_t runtimeOffset) const { // only needed for arm64e code to know to sign pointers if ( (this->cputype != CPU_TYPE_ARM64) || (this->maskedCpuSubtype() != CPU_SUBTYPE_ARM64E) ) return false; __block bool result = false; uint64_t baseAddress = this->preferredLoadAddress(); this->forEachSection(^(const SectionInfo& sectInfo, bool malformedSectionRange, bool& stop) { if ( ((sectInfo.sectAddr-baseAddress) <= runtimeOffset) && (runtimeOffset < (sectInfo.sectAddr+sectInfo.sectSize-baseAddress)) ) { result = ( (sectInfo.sectFlags & S_ATTR_PURE_INSTRUCTIONS) || (sectInfo.sectFlags & S_ATTR_SOME_INSTRUCTIONS) ); stop = true; } }); return result; } uint32_t MachOFile::dependentDylibCount(bool* allDepsAreNormalPtr) const { __block uint32_t count = 0; __block bool allDepsAreNormal = true; forEachDependentDylib(^(const char* loadPath, bool isWeak, bool isReExport, bool isUpward, uint32_t compatVersion, uint32_t curVersion, bool& stop) { ++count; if ( isWeak || isReExport || isUpward ) allDepsAreNormal = false; }); if ( allDepsAreNormalPtr != nullptr ) *allDepsAreNormalPtr = allDepsAreNormal; return count; } bool MachOFile::hasPlusLoadMethod(Diagnostics& diag) const { __block bool result = false; // in new objc runtime compiler puts classes/categories with +load method in specical section forEachSection(^(const SectionInfo& info, bool malformedSectionRange, bool& stop) { if ( strncmp(info.segInfo.segName, "__DATA", 6) != 0 ) return; if ( (strcmp(info.sectName, "__objc_nlclslist") == 0) || (strcmp(info.sectName, "__objc_nlcatlist") == 0)) { result = true; stop = true; } }); return result; } uint32_t MachOFile::getFixupsLoadCommandFileOffset() const { Diagnostics diag; __block uint32_t fileOffset = 0; this->forEachLoadCommand(diag, ^(const load_command* cmd, bool& stop) { switch ( cmd->cmd ) { case LC_DYLD_INFO: case LC_DYLD_INFO_ONLY: fileOffset = (uint32_t)( (uint8_t*)cmd - (uint8_t*)this ); break; case LC_DYLD_CHAINED_FIXUPS: fileOffset = (uint32_t)( (uint8_t*)cmd - (uint8_t*)this ); break; } }); if ( diag.hasError() ) return 0; return fileOffset; } bool MachOFile::hasInitializer(Diagnostics& diag) const { __block bool result = false; // if dylib linked with -init linker option, that initializer is first forEachLoadCommand(diag, ^(const load_command* cmd, bool& stop) { if ( (cmd->cmd == LC_ROUTINES) || (cmd->cmd == LC_ROUTINES_64) ) { result = true; stop = true; } }); if ( result ) return true; // next any function pointers in mod-init section forEachInitializerPointerSection(diag, ^(uint32_t sectionOffset, uint32_t sectionSize, bool& stop) { result = true; stop = true; }); if ( result ) return true; forEachSection(^(const SectionInfo& info, bool malformedSectionRange, bool& stop) { if ( (info.sectFlags & SECTION_TYPE) != S_INIT_FUNC_OFFSETS ) return; result = true; stop = true; }); return result; } void MachOFile::forEachInitializerPointerSection(Diagnostics& diag, void (^callback)(uint32_t sectionOffset, uint32_t sectionSize, bool& stop)) const { const unsigned ptrSize = pointerSize(); const uint64_t baseAddress = preferredLoadAddress(); forEachSection(^(const SectionInfo& info, bool malformedSectionRange, bool& sectStop) { if ( (info.sectFlags & SECTION_TYPE) == S_MOD_INIT_FUNC_POINTERS ) { if ( (info.sectSize % ptrSize) != 0 ) { diag.error("initializer section %s/%s has bad size", info.segInfo.segName, info.sectName); sectStop = true; return; } if ( malformedSectionRange ) { diag.error("initializer section %s/%s extends beyond its segment", info.segInfo.segName, info.sectName); sectStop = true; return; } if ( (info.sectAddr % ptrSize) != 0 ) { diag.error("initializer section %s/%s is not pointer aligned", info.segInfo.segName, info.sectName); sectStop = true; return; } callback((uint32_t)(info.sectAddr - baseAddress), (uint32_t)info.sectSize, sectStop); } }); } bool MachOFile::hasCodeSignature() const { return this->hasLoadCommand(LC_CODE_SIGNATURE); } bool MachOFile::hasCodeSignature(uint32_t& fileOffset, uint32_t& size) const { fileOffset = 0; size = 0; Diagnostics diag; forEachLoadCommand(diag, ^(const load_command* cmd, bool& stop) { if ( cmd->cmd == LC_CODE_SIGNATURE ) { const linkedit_data_command* sigCmd = (linkedit_data_command*)cmd; fileOffset = sigCmd->dataoff; size = sigCmd->datasize; stop = true; } }); diag.assertNoError(); // any malformations in the file should have been caught by earlier validate() call // early exist if no LC_CODE_SIGNATURE if ( fileOffset == 0 ) return false; // <rdar://problem/13622786> ignore code signatures in macOS binaries built with pre-10.9 tools if ( (this->cputype == CPU_TYPE_X86_64) || (this->cputype == CPU_TYPE_I386) ) { __block bool foundPlatform = false; __block bool badSignature = false; forEachSupportedPlatform(^(Platform platform, uint32_t minOS, uint32_t sdk) { foundPlatform = true; if ( (platform == Platform::macOS) && (sdk < 0x000A0900) ) badSignature = true; }); return foundPlatform && !badSignature; } return true; } uint64_t MachOFile::mappedSize() const { uint64_t vmSpace; bool hasZeroFill; analyzeSegmentsLayout(vmSpace, hasZeroFill); return vmSpace; } void MachOFile::analyzeSegmentsLayout(uint64_t& vmSpace, bool& hasZeroFill) const { __block bool writeExpansion = false; __block uint64_t lowestVmAddr = 0xFFFFFFFFFFFFFFFFULL; __block uint64_t highestVmAddr = 0; __block uint64_t sumVmSizes = 0; forEachSegment(^(const SegmentInfo& segmentInfo, bool& stop) { if ( strcmp(segmentInfo.segName, "__PAGEZERO") == 0 ) return; if ( segmentInfo.writable() && (segmentInfo.fileSize != segmentInfo.vmSize) ) writeExpansion = true; // zerofill at end of __DATA if ( segmentInfo.vmSize == 0 ) { // Always zero fill if we have zero-sized segments writeExpansion = true; } if ( segmentInfo.vmAddr < lowestVmAddr ) lowestVmAddr = segmentInfo.vmAddr; if ( segmentInfo.vmAddr+segmentInfo.vmSize > highestVmAddr ) highestVmAddr = segmentInfo.vmAddr+segmentInfo.vmSize; sumVmSizes += segmentInfo.vmSize; }); uint64_t totalVmSpace = (highestVmAddr - lowestVmAddr); // LINKEDIT vmSize is not required to be a multiple of page size. Round up if that is the case const uint64_t pageSize = uses16KPages() ? 0x4000 : 0x1000; totalVmSpace = (totalVmSpace + (pageSize - 1)) & ~(pageSize - 1); bool hasHole = (totalVmSpace != sumVmSizes); // segments not contiguous // The aux KC may have __DATA first, in which case we always want to vm_copy to the right place bool hasOutOfOrderSegments = false; #if BUILDING_APP_CACHE_UTIL || BUILDING_DYLDINFO uint64_t textSegVMAddr = preferredLoadAddress(); hasOutOfOrderSegments = textSegVMAddr != lowestVmAddr; #endif vmSpace = totalVmSpace; hasZeroFill = writeExpansion || hasHole || hasOutOfOrderSegments; } uint32_t MachOFile::segmentCount() const { __block uint32_t count = 0; forEachSegment(^(const SegmentInfo& info, bool& stop) { ++count; }); return count; } void MachOFile::forEachDOFSection(Diagnostics& diag, void (^callback)(uint32_t offset)) const { forEachSection(^(const SectionInfo& info, bool malformedSectionRange, bool &stop) { if ( ( (info.sectFlags & SECTION_TYPE) == S_DTRACE_DOF ) && !malformedSectionRange ) { callback((uint32_t)(info.sectAddr - info.segInfo.vmAddr)); } }); } bool MachOFile::hasExportTrie(uint32_t& runtimeOffset, uint32_t& size) const { __block uint64_t textUnslidVMAddr = 0; __block uint64_t linkeditUnslidVMAddr = 0; __block uint64_t linkeditFileOffset = 0; forEachSegment(^(const SegmentInfo& info, bool& stop) { if ( strcmp(info.segName, "__TEXT") == 0 ) { textUnslidVMAddr = info.vmAddr; } else if ( strcmp(info.segName, "__LINKEDIT") == 0 ) { linkeditUnslidVMAddr = info.vmAddr; linkeditFileOffset = info.fileOffset; stop = true; } }); Diagnostics diag; __block uint32_t fileOffset = ~0U; this->forEachLoadCommand(diag, ^(const load_command* cmd, bool& stop) { switch ( cmd->cmd ) { case LC_DYLD_INFO: case LC_DYLD_INFO_ONLY: { const auto* dyldInfo = (const dyld_info_command*)cmd; fileOffset = dyldInfo->export_off; size = dyldInfo->export_size; break; } case LC_DYLD_EXPORTS_TRIE: { const auto* linkeditCmd = (const linkedit_data_command*)cmd; fileOffset = linkeditCmd->dataoff; size = linkeditCmd->datasize; break; } } }); if ( diag.hasError() ) return false; if ( fileOffset == ~0U ) return false; runtimeOffset = (uint32_t)((fileOffset - linkeditFileOffset) + (linkeditUnslidVMAddr - textUnslidVMAddr)); return true; } #if !TARGET_OS_EXCLAVEKIT // Note, this has to match the kernel static const uint32_t hashPriorities[] = { CS_HASHTYPE_SHA1, CS_HASHTYPE_SHA256_TRUNCATED, CS_HASHTYPE_SHA256, CS_HASHTYPE_SHA384, }; static unsigned int hash_rank(const CS_CodeDirectory *cd) { uint32_t type = cd->hashType; for (uint32_t n = 0; n < sizeof(hashPriorities) / sizeof(hashPriorities[0]); ++n) { if (hashPriorities[n] == type) return n + 1; } /* not supported */ return 0; } // Note, this does NOT match the kernel. // On watchOS, in main executables, we will record all cd hashes then make sure // one of the ones we record matches the kernel. // This list is only for dylibs where we embed the cd hash in the closure instead of the // mod time and inode // This is sorted so that we choose sha1 first when checking dylibs static const uint32_t hashPriorities_watchOS_dylibs[] = { CS_HASHTYPE_SHA256_TRUNCATED, CS_HASHTYPE_SHA256, CS_HASHTYPE_SHA384, CS_HASHTYPE_SHA1 }; static unsigned int hash_rank_watchOS_dylibs(const CS_CodeDirectory *cd) { uint32_t type = cd->hashType; for (uint32_t n = 0; n < sizeof(hashPriorities_watchOS_dylibs) / sizeof(hashPriorities_watchOS_dylibs[0]); ++n) { if (hashPriorities_watchOS_dylibs[n] == type) return n + 1; } /* not supported */ return 0; } // This calls the callback for all code directories required for a given platform/binary combination. // On watchOS main executables this is all cd hashes. // On watchOS dylibs this is only the single cd hash we need (by rank defined by dyld, not the kernel). // On all other platforms this always returns a single best cd hash (ranked to match the kernel). // Note the callback parameter is really a CS_CodeDirectory. void MachOFile::forEachCodeDirectoryBlob(const void* codeSigStart, size_t codeSignLen, void (^callback)(const void* cd)) const { // verify min length of overall code signature if ( codeSignLen < sizeof(CS_SuperBlob) ) return; // verify magic at start const CS_SuperBlob* codeSuperBlob = (CS_SuperBlob*)codeSigStart; if ( codeSuperBlob->magic != htonl(CSMAGIC_EMBEDDED_SIGNATURE) ) return; // verify count of sub-blobs not too large uint32_t subBlobCount = htonl(codeSuperBlob->count); if ( (codeSignLen-sizeof(CS_SuperBlob))/sizeof(CS_BlobIndex) < subBlobCount ) return; // Note: The kernel sometimes chooses sha1 on watchOS, and sometimes sha256. // Embed all of them so that we just need to match any of them const bool isWatchOS = this->builtForPlatform(Platform::watchOS); const bool isMainExecutable = this->isMainExecutable(); auto hashRankFn = isWatchOS ? &hash_rank_watchOS_dylibs : &hash_rank; // walk each sub blob, looking at ones with type CSSLOT_CODEDIRECTORY const CS_CodeDirectory* bestCd = nullptr; for (uint32_t i=0; i < subBlobCount; ++i) { if ( codeSuperBlob->index[i].type == htonl(CSSLOT_CODEDIRECTORY) ) { // Ok, this is the regular code directory } else if ( codeSuperBlob->index[i].type >= htonl(CSSLOT_ALTERNATE_CODEDIRECTORIES) && codeSuperBlob->index[i].type <= htonl(CSSLOT_ALTERNATE_CODEDIRECTORY_LIMIT)) { // Ok, this is the alternative code directory } else { continue; } uint32_t cdOffset = htonl(codeSuperBlob->index[i].offset); // verify offset is not out of range if ( cdOffset > (codeSignLen - sizeof(CS_CodeDirectory)) ) continue; const CS_CodeDirectory* cd = (CS_CodeDirectory*)((uint8_t*)codeSuperBlob + cdOffset); uint32_t cdLength = htonl(cd->length); // verify code directory length not out of range if ( cdLength > (codeSignLen - cdOffset) ) continue; // The watch main executable wants to know about all cd hashes if ( isWatchOS && isMainExecutable ) { callback(cd); continue; } if ( cd->magic == htonl(CSMAGIC_CODEDIRECTORY) ) { if ( !bestCd || (hashRankFn(cd) > hashRankFn(bestCd)) ) bestCd = cd; } } // Note this callback won't happen on watchOS as that one was done in the loop if ( bestCd != nullptr ) callback(bestCd); } void MachOFile::forEachCDHashOfCodeSignature(const void* codeSigStart, size_t codeSignLen, void (^callback)(const uint8_t cdHash[20])) const { forEachCodeDirectoryBlob(codeSigStart, codeSignLen, ^(const void *cdBuffer) { const CS_CodeDirectory* cd = (const CS_CodeDirectory*)cdBuffer; uint32_t cdLength = htonl(cd->length); uint8_t cdHash[20]; if ( cd->hashType == CS_HASHTYPE_SHA384 ) { uint8_t digest[CCSHA384_OUTPUT_SIZE]; const struct ccdigest_info* di = ccsha384_di(); ccdigest_di_decl(di, tempBuf); // declares tempBuf array in stack ccdigest_init(di, tempBuf); ccdigest_update(di, tempBuf, cdLength, cd); ccdigest_final(di, tempBuf, digest); ccdigest_di_clear(di, tempBuf); // cd-hash of sigs that use SHA384 is the first 20 bytes of the SHA384 of the code digest memcpy(cdHash, digest, 20); callback(cdHash); return; } else if ( (cd->hashType == CS_HASHTYPE_SHA256) || (cd->hashType == CS_HASHTYPE_SHA256_TRUNCATED) ) { uint8_t digest[CCSHA256_OUTPUT_SIZE]; const struct ccdigest_info* di = ccsha256_di(); ccdigest_di_decl(di, tempBuf); // declares tempBuf array in stack ccdigest_init(di, tempBuf); ccdigest_update(di, tempBuf, cdLength, cd); ccdigest_final(di, tempBuf, digest); ccdigest_di_clear(di, tempBuf); // cd-hash of sigs that use SHA256 is the first 20 bytes of the SHA256 of the code digest memcpy(cdHash, digest, 20); callback(cdHash); return; } else if ( cd->hashType == CS_HASHTYPE_SHA1 ) { // compute hash directly into return buffer const struct ccdigest_info* di = ccsha1_di(); ccdigest_di_decl(di, tempBuf); // declares tempBuf array in stack ccdigest_init(di, tempBuf); ccdigest_update(di, tempBuf, cdLength, cd); ccdigest_final(di, tempBuf, cdHash); ccdigest_di_clear(di, tempBuf); callback(cdHash); return; } }); } #endif // !TARGET_OS_EXCLAVEKIT // These are mangled symbols for all the variants of operator new and delete // which a main executable can define (non-weak) and override the // weak-def implementation in the OS. static const char* const sTreatAsWeak[] = { "__Znwm", "__ZnwmRKSt9nothrow_t", "__Znam", "__ZnamRKSt9nothrow_t", "__ZdlPv", "__ZdlPvRKSt9nothrow_t", "__ZdlPvm", "__ZdaPv", "__ZdaPvRKSt9nothrow_t", "__ZdaPvm", "__ZnwmSt11align_val_t", "__ZnwmSt11align_val_tRKSt9nothrow_t", "__ZnamSt11align_val_t", "__ZnamSt11align_val_tRKSt9nothrow_t", "__ZdlPvSt11align_val_t", "__ZdlPvSt11align_val_tRKSt9nothrow_t", "__ZdlPvmSt11align_val_t", "__ZdaPvSt11align_val_t", "__ZdaPvSt11align_val_tRKSt9nothrow_t", "__ZdaPvmSt11align_val_t", "__ZnwmSt19__type_descriptor_t", "__ZnamSt19__type_descriptor_t" }; void MachOFile::forEachTreatAsWeakDef(void (^handler)(const char* symbolName)) { for (const char* sym : sTreatAsWeak) handler(sym); } MachOFile::PointerMetaData::PointerMetaData() { this->diversity = 0; this->high8 = 0; this->authenticated = 0; this->key = 0; this->usesAddrDiversity = 0; } MachOFile::PointerMetaData::PointerMetaData(const ChainedFixupPointerOnDisk* fixupLoc, uint16_t pointer_format) { this->diversity = 0; this->high8 = 0; this->authenticated = 0; this->key = 0; this->usesAddrDiversity = 0; switch ( pointer_format ) { case DYLD_CHAINED_PTR_ARM64E: case DYLD_CHAINED_PTR_ARM64E_KERNEL: case DYLD_CHAINED_PTR_ARM64E_USERLAND: case DYLD_CHAINED_PTR_ARM64E_FIRMWARE: case DYLD_CHAINED_PTR_ARM64E_USERLAND24: this->authenticated = fixupLoc->arm64e.authRebase.auth; if ( this->authenticated ) { this->key = fixupLoc->arm64e.authRebase.key; this->usesAddrDiversity = fixupLoc->arm64e.authRebase.addrDiv; this->diversity = fixupLoc->arm64e.authRebase.diversity; } else if ( fixupLoc->arm64e.bind.bind == 0 ) { this->high8 = fixupLoc->arm64e.rebase.high8; } break; case DYLD_CHAINED_PTR_ARM64E_SHARED_CACHE: this->authenticated = fixupLoc->cache64e.auth.auth; if ( this->authenticated ) { this->key = fixupLoc->cache64e.auth.keyIsData ? 2 : 0; // true -> DA (2), false -> IA (0) this->usesAddrDiversity = fixupLoc->cache64e.auth.addrDiv; this->diversity = fixupLoc->cache64e.auth.diversity; } else { this->high8 = fixupLoc->cache64e.regular.high8; } break; case DYLD_CHAINED_PTR_64: case DYLD_CHAINED_PTR_64_OFFSET: if ( fixupLoc->generic64.bind.bind == 0 ) this->high8 = fixupLoc->generic64.rebase.high8; break; } } bool MachOFile::PointerMetaData::operator==(const PointerMetaData& other) const { return (this->diversity == other.diversity) && (this->high8 == other.high8) && (this->authenticated == other.authenticated) && (this->key == other.key) && (this->usesAddrDiversity == other.usesAddrDiversity); } #if !SUPPORT_VM_LAYOUT || BUILDING_UNIT_TESTS || BUILDING_DYLD_SYMBOLS_CACHE bool MachOFile::getLinkeditLayout(Diagnostics& diag, mach_o::LinkeditLayout& layout) const { // Note, in file layout all linkedit offsets are just file offsets. // It is essential no-one calls this on a MachOLoaded or MachOAnalyzer // 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 = (uint8_t*)this + 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 = (uint8_t*)this + 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 = (uint8_t*)this + 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 = (uint8_t*)this + 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 = (uint8_t*)this + 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 = (uint8_t*)this + linkeditCmd->rebase_off; layout.rebaseOpcodes.bufferSize = linkeditCmd->rebase_size; layout.rebaseOpcodes.hasLinkedit = true; // Bind layout.regularBindOpcodes.fileOffset = linkeditCmd->bind_off; layout.regularBindOpcodes.buffer = (uint8_t*)this + 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 = (uint8_t*)this + 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 = (uint8_t*)this + 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 = (uint8_t*)this + 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 = (uint8_t*)this + 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 = (uint8_t*)this + 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 = (uint8_t*)this + 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 = (uint8_t*)this + 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 = (uint8_t*)this + 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 = (uint8_t*)this + linkeditCmd->dataoff; layout.codeSignature.bufferSize = linkeditCmd->datasize; layout.codeSignature.entryCount = 0; // Not needed here layout.codeSignature.hasLinkedit = true; break; } } }); return true; } void MachOFile::withFileLayout(Diagnostics &diag, void (^callback)(const mach_o::Layout &layout)) const { // Use the fixups from the source dylib mach_o::LinkeditLayout linkedit; if ( !this->getLinkeditLayout(diag, linkedit) ) { diag.error("Couldn't get dylib layout"); return; } 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*)this + info.fileOffset; 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; } segmentLayout[info.segIndex] = segment; }); mach_o::Layout layout(this, { &segmentLayout[0], &segmentLayout[numSegments] }, linkedit); callback(layout); } #endif // !SUPPORT_VM_LAYOUT bool MachOFile::hasObjCMessageReferences() const { __block bool foundSection = false; forEachSection(^(const SectionInfo& sectInfo, bool malformedSectionRange, bool& stop) { if ( strncmp(sectInfo.segInfo.segName, "__DATA", 6) != 0 ) return; if ( strcmp(sectInfo.sectName, "__objc_msgrefs") != 0 ) return; foundSection = true; stop = true; }); return foundSection; } uint32_t MachOFile::loadCommandsFreeSpace() const { __block uint32_t firstSectionFileOffset = 0; __block uint32_t firstSegmentFileOffset = 0; forEachSection(^(const SectionInfo& sectInfo, bool malformedSectionRange, bool& stop) { firstSectionFileOffset = sectInfo.sectFileOffset; firstSegmentFileOffset = (uint32_t)sectInfo.segInfo.fileOffset; stop = true; }); uint32_t headerSize = (this->magic == MH_MAGIC_64) ? sizeof(mach_header_64) : sizeof(mach_header); uint32_t existSpaceUsed = this->sizeofcmds + headerSize; return firstSectionFileOffset - firstSegmentFileOffset - existSpaceUsed; } bool MachOFile::findObjCDataSection(const char *sectionName, uint64_t& sectionRuntimeOffset, uint64_t& sectionSize) const { uint64_t baseAddress = preferredLoadAddress(); __block bool foundSection = false; forEachSection(^(const SectionInfo& sectInfo, bool malformedSectionRange, bool& stop) { if ( (strcmp(sectInfo.segInfo.segName, "__DATA") != 0) && (strcmp(sectInfo.segInfo.segName, "__DATA_CONST") != 0) && (strcmp(sectInfo.segInfo.segName, "__DATA_DIRTY") != 0) ) return; if ( strcmp(sectInfo.sectName, sectionName) != 0 ) return; foundSection = true; sectionRuntimeOffset = sectInfo.sectAddr - baseAddress; sectionSize = sectInfo.sectSize; stop = true; }); return foundSection; } bool MachOFile::enforceFormat(Malformed kind) const { // TODO: Add a mapping from generic releases to platform versions #if BUILDING_DYLDINFO || BUILDING_APP_CACHE_UTIL || BUILDING_RUN_STATIC // HACK: If we are the kernel, we have a different format to enforce if ( isFileSet() ) { bool result = false; switch (kind) { case Malformed::linkeditOrder: case Malformed::linkeditAlignment: case Malformed::dyldInfoAndlocalRelocs: result = true; break; case Malformed::segmentOrder: // The aux KC has __DATA first result = false; break; case Malformed::linkeditPermissions: case Malformed::executableData: case Malformed::writableData: case Malformed::codeSigAlignment: case Malformed::sectionsAddrRangeWithinSegment: case Malformed::loaderPathsAreReal: case Malformed::mainExecInDyldCache: result = true; break; case Malformed::noLinkedDylibs: case Malformed::textPermissions: // The kernel has its own __TEXT_EXEC for executable memory result = false; break; case Malformed::noUUID: case Malformed::zerofillSwiftMetadata: case Malformed::sdkOnOrAfter2021: case Malformed::sdkOnOrAfter2022: result = true; break; } return result; } if ( isStaticExecutable() ) { bool result = false; switch (kind) { case Malformed::linkeditOrder: case Malformed::linkeditAlignment: case Malformed::dyldInfoAndlocalRelocs: result = true; break; case Malformed::segmentOrder: case Malformed::textPermissions: result = false; break; case Malformed::linkeditPermissions: case Malformed::executableData: case Malformed::codeSigAlignment: case Malformed::sectionsAddrRangeWithinSegment: case Malformed::loaderPathsAreReal: case Malformed::mainExecInDyldCache: result = true; break; case Malformed::noLinkedDylibs: case Malformed::writableData: case Malformed::noUUID: case Malformed::zerofillSwiftMetadata: case Malformed::sdkOnOrAfter2021: case Malformed::sdkOnOrAfter2022: // The kernel has __DATA_CONST marked as r/o result = false; break; } return result; } #endif __block bool result = false; forEachSupportedPlatform(^(Platform platform, uint32_t minOS, uint32_t sdk) { switch (platform) { case Platform::macOS: switch (kind) { case Malformed::linkeditOrder: case Malformed::linkeditAlignment: case Malformed::dyldInfoAndlocalRelocs: // enforce these checks on new binaries only if (sdk >= 0x000A0E00) // macOS 10.14 result = true; break; case Malformed::segmentOrder: case Malformed::linkeditPermissions: case Malformed::textPermissions: case Malformed::executableData: case Malformed::writableData: case Malformed::codeSigAlignment: // enforce these checks on new binaries only if (sdk >= 0x000A0F00) // macOS 10.15 result = true; break; case Malformed::sectionsAddrRangeWithinSegment: // enforce these checks on new binaries only if (sdk >= 0x000A1000) // macOS 10.16 result = true; break; case Malformed::noLinkedDylibs: case Malformed::loaderPathsAreReal: case Malformed::mainExecInDyldCache: case Malformed::zerofillSwiftMetadata: case Malformed::sdkOnOrAfter2021: // enforce these checks on new binaries only if (sdk >= 0x000D0000) // macOS 13.0 result = true; break; case Malformed::noUUID: case Malformed::sdkOnOrAfter2022: if (sdk >= 0x000E0000) // macOS 14.0 FIXME result = true; break; } break; case Platform::iOS: case Platform::tvOS: case Platform::iOSMac: switch (kind) { case Malformed::linkeditOrder: case Malformed::dyldInfoAndlocalRelocs: case Malformed::textPermissions: case Malformed::executableData: case Malformed::writableData: result = true; break; case Malformed::linkeditAlignment: case Malformed::segmentOrder: case Malformed::linkeditPermissions: case Malformed::codeSigAlignment: // enforce these checks on new binaries only if (sdk >= 0x000D0000) // iOS 13 result = true; break; case Malformed::sectionsAddrRangeWithinSegment: // enforce these checks on new binaries only if (sdk >= 0x000E0000) // iOS 14 result = true; break; case Malformed::noLinkedDylibs: case Malformed::loaderPathsAreReal: case Malformed::mainExecInDyldCache: case Malformed::zerofillSwiftMetadata: case Malformed::sdkOnOrAfter2021: // enforce these checks on new binaries only if (sdk >= 0x00100000) // iOS 16 result = true; break; case Malformed::noUUID: case Malformed::sdkOnOrAfter2022: if (sdk >= 0x00110000) // iOS 17.0 FIXME result = true; break; } break; case Platform::watchOS: switch (kind) { case Malformed::linkeditOrder: case Malformed::dyldInfoAndlocalRelocs: case Malformed::textPermissions: case Malformed::executableData: case Malformed::writableData: result = true; break; case Malformed::linkeditAlignment: case Malformed::segmentOrder: case Malformed::linkeditPermissions: case Malformed::codeSigAlignment: case Malformed::sectionsAddrRangeWithinSegment: case Malformed::noLinkedDylibs: case Malformed::loaderPathsAreReal: case Malformed::mainExecInDyldCache: case Malformed::zerofillSwiftMetadata: case Malformed::sdkOnOrAfter2021: // enforce these checks on new binaries only if (sdk >= 0x00090000) // watchOS 9 result = true; break; case Malformed::noUUID: case Malformed::sdkOnOrAfter2022: if (sdk >= 0x000A0000) // watchOS 10 FIXME result = true; break; } break; case Platform::driverKit: result = true; break; case Platform::visionOS: case Platform::visionOS_simulator: result = true; // do all checks by default if ( kind == Malformed::sdkOnOrAfter2022 ) { if (sdk < 0x00020000) // visionOS 2.0 FIXME result = false; } break; default: result = true; break; } }); // if binary is so old, there is no platform info, don't enforce malformed errors return result; } bool MachOFile::validSegments(Diagnostics& diag, const char* path, size_t fileLen) const { // check segment load command size __block bool badSegmentLoadCommand = false; forEachLoadCommand(diag, ^(const load_command* cmd, bool& stop) { if ( cmd->cmd == LC_SEGMENT_64 ) { const segment_command_64* seg = (segment_command_64*)cmd; int32_t sectionsSpace = cmd->cmdsize - sizeof(segment_command_64); if ( sectionsSpace < 0 ) { diag.error("in '%s' load command size too small for LC_SEGMENT_64", path); badSegmentLoadCommand = true; stop = true; } else if ( (sectionsSpace % sizeof(section_64)) != 0 ) { diag.error("in '%s' segment load command size 0x%X will not fit whole number of sections", path, cmd->cmdsize); badSegmentLoadCommand = true; stop = true; } else if ( sectionsSpace != (int32_t)(seg->nsects * sizeof(section_64)) ) { diag.error("in '%s' load command size 0x%X does not match nsects %d", path, cmd->cmdsize, seg->nsects); badSegmentLoadCommand = true; stop = true; } else if ( greaterThanAddOrOverflow(seg->fileoff, seg->filesize, fileLen) ) { diag.error("in '%s' segment load command content extends beyond end of file", path); badSegmentLoadCommand = true; stop = true; } else if ( (seg->filesize > seg->vmsize) && ((seg->vmsize != 0) || ((seg->flags & SG_NORELOC) == 0)) ) { // <rdar://problem/19986776> dyld should support non-allocatable __LLVM segment diag.error("in '%s' segment '%s' filesize exceeds vmsize", path, seg->segname); badSegmentLoadCommand = true; stop = true; } } else if ( cmd->cmd == LC_SEGMENT ) { const segment_command* seg = (segment_command*)cmd; int32_t sectionsSpace = cmd->cmdsize - sizeof(segment_command); if ( sectionsSpace < 0 ) { diag.error("in '%s' load command size too small for LC_SEGMENT", path); badSegmentLoadCommand = true; stop = true; } else if ( (sectionsSpace % sizeof(section)) != 0 ) { diag.error("in '%s' segment load command size 0x%X will not fit whole number of sections", path, cmd->cmdsize); badSegmentLoadCommand = true; stop = true; } else if ( sectionsSpace != (int32_t)(seg->nsects * sizeof(section)) ) { diag.error("in '%s' load command size 0x%X does not match nsects %d", path, cmd->cmdsize, seg->nsects); badSegmentLoadCommand = true; stop = true; } else if ( (seg->filesize > seg->vmsize) && ((seg->vmsize != 0) || ((seg->flags & SG_NORELOC) == 0)) ) { // <rdar://problem/19986776> dyld should support non-allocatable __LLVM segment diag.error("in '%s' segment '%s' filesize exceeds vmsize", path, seg->segname); badSegmentLoadCommand = true; stop = true; } } }); if ( badSegmentLoadCommand ) return false; // check mapping permissions of segments __block bool badPermissions = false; __block bool badSize = false; __block bool hasTEXT = false; __block bool hasLINKEDIT = false; forEachSegment(^(const SegmentInfo& info, bool& stop) { if ( strcmp(info.segName, "__TEXT") == 0 ) { if ( (info.protections != (VM_PROT_READ|VM_PROT_EXECUTE)) && enforceFormat(Malformed::textPermissions) ) { diag.error("in '%s' __TEXT segment permissions is not 'r-x'", path); badPermissions = true; stop = true; } hasTEXT = true; } else if ( strcmp(info.segName, "__LINKEDIT") == 0 ) { if ( (info.protections != VM_PROT_READ) && enforceFormat(Malformed::linkeditPermissions) ) { diag.error("in '%s' __LINKEDIT segment permissions is not 'r--'", path); badPermissions = true; stop = true; } hasLINKEDIT = true; } else if ( (info.protections & 0xFFFFFFF8) != 0 ) { diag.error("in '%s' %s segment permissions has invalid bits set", path, info.segName); badPermissions = true; stop = true; } if ( greaterThanAddOrOverflow(info.fileOffset, info.fileSize, fileLen) ) { diag.error("in '%s' %s segment content extends beyond end of file", path, info.segName); badSize = true; stop = true; } if ( is64() ) { if ( info.vmAddr+info.vmSize < info.vmAddr ) { diag.error("in '%s' %s segment vm range wraps", path, info.segName); badSize = true; stop = true; } } else { if ( (uint32_t)(info.vmAddr+info.vmSize) < (uint32_t)(info.vmAddr) ) { diag.error("in '%s' %s segment vm range wraps", path, info.segName); badSize = true; stop = true; } } }); if ( badPermissions || badSize ) return false; if ( !hasTEXT ) { diag.error("in '%s' missing __TEXT segment", path); return false; } if ( !hasLINKEDIT && !this->isPreload() ) { diag.error("in '%s' missing __LINKEDIT segment", path); return false; } // check for overlapping segments __block bool badSegments = false; forEachSegment(^(const SegmentInfo& info1, bool& stop1) { uint64_t seg1vmEnd = info1.vmAddr + info1.vmSize; uint64_t seg1FileEnd = info1.fileOffset + info1.fileSize; forEachSegment(^(const SegmentInfo& info2, bool& stop2) { if ( info1.segIndex == info2.segIndex ) return; uint64_t seg2vmEnd = info2.vmAddr + info2.vmSize; uint64_t seg2FileEnd = info2.fileOffset + info2.fileSize; if ( ((info2.vmAddr <= info1.vmAddr) && (seg2vmEnd > info1.vmAddr) && (seg1vmEnd > info1.vmAddr )) || ((info2.vmAddr >= info1.vmAddr ) && (info2.vmAddr < seg1vmEnd) && (seg2vmEnd > info2.vmAddr)) ) { diag.error("in '%s' segment %s vm range overlaps segment %s", path, info1.segName, info2.segName); badSegments = true; stop1 = true; stop2 = true; } if ( ((info2.fileOffset <= info1.fileOffset) && (seg2FileEnd > info1.fileOffset) && (seg1FileEnd > info1.fileOffset)) || ((info2.fileOffset >= info1.fileOffset) && (info2.fileOffset < seg1FileEnd) && (seg2FileEnd > info2.fileOffset )) ) { if ( !inDyldCache() ) { // HACK: Split shared caches might put the __TEXT in a SubCache, then the __DATA in a later SubCache. // The file offsets are in to each SubCache file, which means that they might overlap // For now we have no choice but to disable this error diag.error("in '%s' segment %s file content overlaps segment %s", path, info1.segName, info2.segName); badSegments = true; stop1 = true; stop2 = true; } } if ( (info1.segIndex < info2.segIndex) && !stop1 ) { if ( (info1.vmAddr > info2.vmAddr) || ((info1.fileOffset > info2.fileOffset ) && (info1.fileOffset != 0) && (info2.fileOffset != 0)) ){ if ( !inDyldCache() && enforceFormat(Malformed::segmentOrder) && !isStaticExecutable() ) { // <rdar://80084852> whitelist go libraries __DWARF segments if ( (strcmp(info1.segName, "__DWARF") != 0 && strcmp(info2.segName, "__DWARF") != 0) ) { // dyld cache __DATA_* segments are moved around // The static kernel also has segments with vmAddr's before __TEXT diag.error("in '%s' segment load commands out of order with respect to layout for %s and %s", path, info1.segName, info2.segName); badSegments = true; stop1 = true; stop2 = true; } } } } }); }); if ( badSegments ) return false; // check sections are within segment __block bool badSections = false; forEachLoadCommand(diag, ^(const load_command* cmd, bool& stop) { if ( cmd->cmd == LC_SEGMENT_64 ) { const segment_command_64* seg = (segment_command_64*)cmd; const section_64* const sectionsStart = (section_64*)((char*)seg + sizeof(struct segment_command_64)); const section_64* const sectionsEnd = §ionsStart[seg->nsects]; for (const section_64* sect=sectionsStart; (sect < sectionsEnd); ++sect) { if ( (int64_t)(sect->size) < 0 ) { diag.error("in '%s' section '%s' size too large 0x%llX", path, sect->sectname, sect->size); badSections = true; } else if ( sect->addr < seg->vmaddr ) { diag.error("in '%s' section '%s' start address 0x%llX is before containing segment's address 0x%0llX", path, sect->sectname, sect->addr, seg->vmaddr); badSections = true; } else if ( sect->addr+sect->size > seg->vmaddr+seg->vmsize ) { bool ignoreError = !enforceFormat(Malformed::sectionsAddrRangeWithinSegment); #if BUILDING_APP_CACHE_UTIL || BUILDING_DYLDINFO if ( (seg->vmsize == 0) && !strcmp(seg->segname, "__CTF") ) ignoreError = true; #endif if ( !ignoreError ) { diag.error("in '%s' section '%s' end address 0x%llX is beyond containing segment's end address 0x%0llX", path, sect->sectname, sect->addr+sect->size, seg->vmaddr+seg->vmsize); badSections = true; } } } } else if ( cmd->cmd == LC_SEGMENT ) { const segment_command* seg = (segment_command*)cmd; const section* const sectionsStart = (section*)((char*)seg + sizeof(struct segment_command)); const section* const sectionsEnd = §ionsStart[seg->nsects]; for (const section* sect=sectionsStart; !stop && (sect < sectionsEnd); ++sect) { if ( (int64_t)(sect->size) < 0 ) { diag.error("in '%s' section %s size too large 0x%X", path, sect->sectname, sect->size); badSections = true; } else if ( sect->addr < seg->vmaddr ) { diag.error("in '%s' section %s start address 0x%X is before containing segment's address 0x%0X", path, sect->sectname, sect->addr, seg->vmaddr); badSections = true; } else if ( sect->addr+sect->size > seg->vmaddr+seg->vmsize ) { diag.error("in '%s' section %s end address 0x%X is beyond containing segment's end address 0x%0X", path, sect->sectname, sect->addr+sect->size, seg->vmaddr+seg->vmsize); badSections = true; } } } }); return !badSections; } void MachOFile::forEachSingletonPatch(Diagnostics& diag, void (^handler)(SingletonPatchKind kind, uint64_t runtimeOffset)) const { uint32_t ptrSize = this->pointerSize(); uint32_t elementSize = (2 * ptrSize); uint64_t loadAddress = this->preferredLoadAddress(); this->forEachSection(^(const SectionInfo §Info, bool malformedSectionRange, bool &stop) { if ( strcmp(sectInfo.sectName, "__const_cfobj2") != 0 ) return; stop = true; if ( (sectInfo.sectSize % elementSize) != 0 ) { diag.error("Incorrect patching size (%lld). Should be a multiple of (2 * ptrSize)", sectInfo.sectSize); return; } if ( sectInfo.reserved2 != elementSize ) { // ld64 must have rejected one or more of the elements in the section, so // didn't set the reserved2 to let us patch diag.error("reserved2 is unsupported value %d. Expected %d", sectInfo.reserved2, elementSize); return; } for ( uint64_t offset = 0; offset != sectInfo.sectSize; offset += elementSize ) { uint64_t targetRuntimeOffset = (sectInfo.sectAddr + offset) - loadAddress; handler(SingletonPatchKind::cfObj2, targetRuntimeOffset); } }); } } // namespace dyld3 |