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 | /* -*- mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*- * * 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 "Array.h" #include "BuilderConfig.h" #include "BuilderOptions.h" #include "CacheDylib.h" #include "Chunk.h" #include "MachOFile.h" #include "MachOFileAbstraction.hpp" #include "Header.h" #include "ObjCVisitor.h" #include "Optimizers.h" #include "OptimizerObjC.h" #include "StringUtils.h" #include "Trie.hpp" // mach_o #include "Header.h" #include "Image.h" #include "FunctionVariants.h" #include <CommonCrypto/CommonHMAC.h> #include <CommonCrypto/CommonDigest.h> #include <CommonCrypto/CommonDigestSPI.h> #include <optional> #include <vector> // mach_o_writer #include "HeaderWriter.h" // FIXME: We should get this from cctools #define DYLD_CACHE_ADJ_V2_FORMAT 0x7F #define DYLD_CACHE_ADJ_V2_POINTER_32 0x01 #define DYLD_CACHE_ADJ_V2_POINTER_64 0x02 #define DYLD_CACHE_ADJ_V2_DELTA_32 0x03 #define DYLD_CACHE_ADJ_V2_DELTA_64 0x04 #define DYLD_CACHE_ADJ_V2_ARM64_ADRP 0x05 #define DYLD_CACHE_ADJ_V2_ARM64_OFF12 0x06 #define DYLD_CACHE_ADJ_V2_ARM64_BR26 0x07 #define DYLD_CACHE_ADJ_V2_ARM_MOVW_MOVT 0x08 #define DYLD_CACHE_ADJ_V2_ARM_BR24 0x09 #define DYLD_CACHE_ADJ_V2_THUMB_MOVW_MOVT 0x0A #define DYLD_CACHE_ADJ_V2_THUMB_BR22 0x0B #define DYLD_CACHE_ADJ_V2_IMAGE_OFF_32 0x0C #define DYLD_CACHE_ADJ_V2_THREADED_POINTER_64 0x0D using namespace cache_builder; using dyld3::MachOFile; using error::Error; using mach_o::Header; using mach_o::Version32; using mach_o::Image; using mach_o::FunctionVariantFixups; // // MARK: --- cache_builder::CacheDylib methods --- // #if BUILDING_CACHE_BUILDER_UNIT_TESTS CacheDylib::CacheDylib() { } #endif CacheDylib::CacheDylib(InputFile& inputFile) : inputFile(&inputFile) , inputMF(inputFile.mf) , inputHdr((const Header*)inputFile.mf) , inputLoadAddress(this->inputHdr->preferredLoadAddress()) , installName(this->inputHdr->installName()) { if ( inputFile.mf ) inputImage = std::make_unique<mach_o::Image>(inputFile.mf, inputFile.size, Image::MappingKind::wholeSliceMapped); } CacheDylib::CacheDylib(std::string_view installName) : inputFile(nullptr) , inputMF(nullptr) , inputHdr(nullptr) , inputLoadAddress(0ull) , installName(installName) { } // If you want to watch a location, set a breakpoint here. The way to use this is to work out // the segment you want, and the address of the location in the *source* dylib. This will then // compute the equivalent location in the cache builder buffers #if DEBUG __attribute__((noinline)) void CacheDylib::watchMemory(const DylibSegmentChunk& segment, std::string_view dylibInstallName, std::string_view dylibSegmentName, uint64_t dylibAddressInSegment) const { if ( this->installName != dylibInstallName ) return; if ( segment.segmentName != dylibSegmentName ) return; printf("watchpoint set expression -w w -s 8 -- %p\n", segment.subCacheBuffer + dylibAddressInSegment - segment.inputVMAddress.rawValue()); printf("watchpoint set expression -w w -s 4 -- %p\n", segment.subCacheBuffer + dylibAddressInSegment - segment.inputVMAddress.rawValue()); printf(""); } #endif static bool hasUnalignedFixups(const MachOFile* mf) { // arm64e chained fixup formats are always 8-byte aligned if ( mf->isArch("arm64e") ) return false; uint32_t pointerMask = mf->pointerSize() - 1; __block Diagnostics diag; __block bool foundUnalignedFixup = false; mf->withFileLayout(diag, ^(const mach_o::Layout &layout) { mach_o::Fixups fixups(layout); if ( mf->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 & pointerMask) != 0 ) { foundUnalignedFixup = true; stop = true; return; } }); }); } else { fixups.forEachRebaseLocation_Opcodes(diag, ^(uint64_t runtimeOffset, uint32_t segmentIndex, bool &stop) { if ( (runtimeOffset & pointerMask) != 0 ) { foundUnalignedFixup = true; stop = true; return; } }); fixups.forEachBindLocation_Opcodes(diag, ^(uint64_t runtimeOffset, uint32_t segmentIndex, unsigned int targetIndex, bool &stop) { if ( (runtimeOffset & pointerMask) != 0 ) { foundUnalignedFixup = true; stop = true; return; } }, ^(uint64_t runtimeOffset, uint32_t segmentIndex, unsigned int overrideBindTargetIndex, bool &stop) { if ( (runtimeOffset & pointerMask) != 0 ) { foundUnalignedFixup = true; stop = true; return; } }); } }); diag.assertNoError(); return foundUnalignedFixup; } static const bool segmentHasAuthFixups(const MachOFile* mf, uint32_t segmentIndexToSearch) { // non-arm64e cannot have auth fixups if ( !mf->isArch("arm64e") ) return false; __block Diagnostics diag; __block bool foundAuthFixup = false; mf->withFileLayout(diag, ^(const mach_o::Layout &layout) { mach_o::Fixups fixups(layout); if ( mf->hasChainedFixups() ) { fixups.withChainStarts(diag, ^(const dyld_chained_starts_in_image* starts) { fixups.forEachFixupChainSegment(diag, starts, ^(const dyld_chained_starts_in_segment *segInfo, uint32_t segIndex, bool &stopSegment) { if ( segIndex != segmentIndexToSearch ) return; fixups.forEachFixupInSegmentChains(diag, segInfo, segIndex, true, ^(dyld3::MachOFile::ChainedFixupPointerOnDisk *fixupLocation, uint64_t fixupSegmentOffset, bool &stopChain) { if ( fixupLocation->arm64e.rebase.auth ) { foundAuthFixup = true; stopChain = true; stopSegment = true; } }); }); }); } // Move to auth if __objc_const or __objc_data is present. // This allows new method lists added by the category optimizer to be signed. // Note the linker eagerly moves these sections to AUTH, as of rdar://111858154, // so it is not expected that this code ever finds anything to move, but we'll keep it to be safe ((const Header*)mf)->forEachSection(^(const Header::SegmentInfo &segInfo, const Header::SectionInfo §Info, bool &stop) { if ( segInfo.segmentIndex != segmentIndexToSearch ) return; if ( (sectInfo.sectionName == "__objc_const") || (sectInfo.sectionName == "__objc_data") ) { foundAuthFixup = true; stop = true; } }); }); return foundAuthFixup; } void CacheDylib::categorizeSegments(const BuilderConfig& config, objc_visitor::Visitor& objcVisitor) { bool hasUnalignedFixups = ::hasUnalignedFixups(this->inputMF); this->inputHdr->forEachSegment(^(const Header::SegmentInfo& info, uint64_t sizeOfSections, uint32_t maxAlignOfSections, bool& stop) { auto addSegment = [&](DylibSegmentChunk::Kind kind) { // TODO: Cache VMSize/fileSize might be less than input VMSize if we deduplicate strings for example uint64_t inputFileSize = std::min((uint64_t)info.fileSize, sizeOfSections); uint64_t cacheFileSize = sizeOfSections; uint64_t vmSize = sizeOfSections; // LINKEDIT doesn't get space any more. Its individual chunks will get their own space if ( info.segmentName == "__LINKEDIT" ) { inputFileSize = 0; cacheFileSize = 0; vmSize = 0; } uint64_t minAlignment = 1 << maxAlignOfSections; // Always align __TEXT to a page as split seg can't handle less if ( info.segmentName == "__TEXT" ) minAlignment = config.layout.machHeaderAlignment; else if ( hasUnalignedFixups ) minAlignment = (this->inputHdr->uses16KPages() ? 0x4000 : 0x1000); DylibSegmentChunk segment(kind, minAlignment); segment.segmentName = info.segmentName; segment.inputFile = this->inputFile; segment.inputFileOffset = InputDylibFileOffset((uint64_t)info.fileOffset); segment.inputFileSize = InputDylibFileSize(inputFileSize); segment.inputVMAddress = InputDylibVMAddress(info.vmaddr); segment.inputVMSize = InputDylibVMSize(info.vmsize); segment.cacheVMSize = CacheVMSize(vmSize); segment.subCacheFileSize = CacheFileSize(cacheFileSize); // Santify check. The cache buffer adds zero fill so VMSize should always be the largest. assert(segment.inputFileSize.rawValue() <= segment.cacheVMSize.rawValue()); assert(segment.subCacheFileSize.rawValue() <= segment.cacheVMSize.rawValue()); this->segments.push_back(std::move(segment)); }; // __TEXT if ( info.initProt == (VM_PROT_READ | VM_PROT_EXECUTE) ) { addSegment(DylibSegmentChunk::Kind::dylibText); return; } // DATA* if ( info.initProt == (VM_PROT_READ | VM_PROT_WRITE) ) { // If we don't have split seg v2, then all __DATA* segments must look like __DATA so that they // stay contiguous __block bool isSplitSegV2 = false; Diagnostics diag; this->inputMF->withFileLayout(diag, ^(const mach_o::Layout& layout) { mach_o::SplitSeg splitSeg(layout); isSplitSegV2 = splitSeg.isV2(); }); diag.assertNoError(); if ( !isSplitSegV2 ) { addSegment(DylibSegmentChunk::Kind::dylibData); return; } if ( info.segmentName == "__TPRO_CONST" ) { addSegment(DylibSegmentChunk::Kind::tproDataConst); return; } if ( info.segmentName == "__OBJC_CONST" ) { // In arm64e, "__OBJC_CONST __objc_class_ro" contains authenticated values if ( config.layout.hasAuthRegion ) addSegment(DylibSegmentChunk::Kind::dylibAuthConst); else addSegment(DylibSegmentChunk::Kind::dylibDataConst); return; } if ( info.segmentName == "__DATA_DIRTY" ) { addSegment(DylibSegmentChunk::Kind::dylibDataDirty); return; } bool hasAuthFixups = false; if ( (info.segmentName == "__AUTH") || (info.segmentName == "__AUTH_CONST") ) { hasAuthFixups = true; } else if ( config.layout.hasAuthRegion ) { // HACK: Some dylibs don't get __AUTH segments. This matches ld64 hasAuthFixups = segmentHasAuthFixups(this->inputMF, info.segmentIndex); } bool isConst = info.segmentName.ends_with("_CONST"); if ( hasAuthFixups ) { // AUTH/AUTH_CONST if ( isConst ) { // AUTH_CONST addSegment(DylibSegmentChunk::Kind::dylibAuthConst); return; } else { // AUTH addSegment(DylibSegmentChunk::Kind::dylibAuth); return; } } else { // DATA/DATA_CONST if ( isConst ) { // DATA_CONST addSegment(DylibSegmentChunk::Kind::dylibDataConst); return; } else { // DATA addSegment(DylibSegmentChunk::Kind::dylibData); return; } } } // LINKEDIT/readOnly if ( info.initProt == (VM_PROT_READ) ) { if ( info.segmentName != "__LINKEDIT" ) { addSegment(DylibSegmentChunk::Kind::dylibReadOnly); return; } addSegment(DylibSegmentChunk::Kind::dylibLinkedit); return; } // Not text/data/linkedit. This should have been caught by canBePlacedInDyldCache() assert(0); }); } // The export trie might grow, as addresses outside of __TEXT will need more uleb bytes to encode when their // addresses grow. Estimate how much space we need to grow the given trie static uint32_t estimateExportTrieSize(const uint8_t* start, const uint8_t* end) { // FIXME: This is terrible. We could actually estimate the result, not just calculate it // Eg, just assume all nodes outside __TEXT will grow by however many bytes it takes to encode about 2GB std::vector<uint8_t> newTrieBytes; Diagnostics diag; if ( start == end ) return 0; // since export info addresses are offsets from mach_header, everything in __TEXT is fine // only __DATA addresses need to be updated std::vector<ExportInfoTrie::Entry> originalExports; if ( !ExportInfoTrie::parseTrie(start, end, originalExports) ) { diag.error("malformed exports trie in"); assert(0); return 0; } std::vector<ExportInfoTrie::Entry> newExports; newExports.reserve(originalExports.size()); // Assume dylibs start at 0, and will slide to 2GB uint64_t baseAddress = 0; uint64_t baseAddressSlide = 1ULL << 31; for ( auto& entry : originalExports ) { // remove symbols used by the static linker only // FIXME: This can result in the cache export-trie being smaller than the input dylib // But then the initial linkedit chunk doesn't contain the whole trie and adjustExportsTrie() fails // If we are going to allow a smaller true in the cache, then we need adjustExportsTrie() to consume the // trie from the input dylib, and emit a trie in to the cache. #if 0 if ( (strncmp(entry.name.c_str(), "$ld$", 4) == 0) || (strncmp(entry.name.c_str(), ".objc_class_name",16) == 0) || (strncmp(entry.name.c_str(), ".objc_category_name",19) == 0) ) { continue; } #endif // adjust symbols in slid segments if ( (entry.info.flags & EXPORT_SYMBOL_FLAGS_KIND_MASK) != EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE ) entry.info.address += (baseAddressSlide - baseAddress); newExports.push_back(entry); } // rebuild export trie newTrieBytes.reserve(end - start); ExportInfoTrie(newExports).emit(newTrieBytes); // align while ( (newTrieBytes.size() % sizeof(uint64_t)) != 0 ) newTrieBytes.push_back(0); // HACK: copyRawSegments() is going to first copy the original trie in to the buffer, so make // sure we have at least that much space size_t requiredSize = std::max((uint64_t)newTrieBytes.size(), (uint64_t)end - (uint64_t)start); return (uint32_t)requiredSize; } void CacheDylib::categorizeLinkedit(const BuilderConfig& config) { uint32_t pointerSize = config.layout.is64 ? 8 : 4; __block Diagnostics diag; this->inputMF->forEachLoadCommand(diag, ^(const load_command* cmd, bool& stop) { typedef Chunk::Kind Kind; auto addLinkedit = [&](Kind kind, InputDylibFileOffset inputFileOffset, InputDylibFileSize inputFileSize, CacheVMSize estimatedCacheVMSize, uint64_t minAlignment) { LinkeditDataChunk chunk(kind, minAlignment); chunk.inputFile = this->inputFile; chunk.inputFileOffset = inputFileOffset; chunk.inputFileSize = inputFileSize; chunk.cacheVMSize = estimatedCacheVMSize; chunk.subCacheFileSize = CacheFileSize(estimatedCacheVMSize.rawValue()); this->linkeditChunks.push_back(std::move(chunk)); }; switch ( cmd->cmd ) { case LC_SYMTAB: { const symtab_command* symTabCmd = (const symtab_command*)cmd; // NList uint64_t nlistEntrySize = config.layout.is64 ? sizeof(struct nlist_64) : sizeof(struct nlist); uint64_t symbolTableSize = symTabCmd->nsyms * nlistEntrySize; addLinkedit(Kind::linkeditSymbolNList, InputDylibFileOffset((uint64_t)symTabCmd->symoff), InputDylibFileSize(symbolTableSize), CacheVMSize(symbolTableSize), pointerSize); // Symbol strings addLinkedit(Kind::linkeditSymbolStrings, InputDylibFileOffset((uint64_t)symTabCmd->stroff), InputDylibFileSize((uint64_t)symTabCmd->strsize), CacheVMSize((uint64_t)symTabCmd->strsize), 1); break; } case LC_DYSYMTAB: { const dysymtab_command* dynSymTabCmd = (const dysymtab_command*)cmd; assert(dynSymTabCmd->tocoff == 0); assert(dynSymTabCmd->ntoc == 0); assert(dynSymTabCmd->modtaboff == 0); assert(dynSymTabCmd->nmodtab == 0); assert(dynSymTabCmd->extrefsymoff == 0); assert(dynSymTabCmd->nextrefsyms == 0); if ( dynSymTabCmd->indirectsymoff != 0 ) { assert(dynSymTabCmd->nindirectsyms != 0); // Indirect symbols uint64_t entrySize = sizeof(uint32_t); uint64_t tableSize = dynSymTabCmd->nindirectsyms * entrySize; addLinkedit(Kind::linkeditIndirectSymbols, InputDylibFileOffset((uint64_t)dynSymTabCmd->indirectsymoff), InputDylibFileSize(tableSize), CacheVMSize(tableSize), 4); } else { assert(dynSymTabCmd->nindirectsyms == 0); } assert(dynSymTabCmd->extreloff == 0); assert(dynSymTabCmd->nextrel == 0); assert(dynSymTabCmd->locreloff == 0); assert(dynSymTabCmd->nlocrel == 0); break; } case LC_DYLD_INFO: case LC_DYLD_INFO_ONLY: { // Most things should be chained fixups, but some old dylibs exist for back deployment const dyld_info_command* linkeditCmd = (const dyld_info_command*)cmd; this->inputMF->withFileLayout(diag, ^(const mach_o::Layout &layout) { this->inputDylibRebaseStart = layout.linkedit.rebaseOpcodes.buffer; this->inputDylibRebaseEnd = this->inputDylibRebaseStart + layout.linkedit.rebaseOpcodes.bufferSize; this->inputDylibBindStart = layout.linkedit.regularBindOpcodes.buffer; this->inputDylibBindEnd = this->inputDylibBindStart + layout.linkedit.regularBindOpcodes.bufferSize; this->inputDylibLazyBindStart = layout.linkedit.lazyBindOpcodes.buffer; this->inputDylibLazyBindEnd = this->inputDylibLazyBindStart + layout.linkedit.lazyBindOpcodes.bufferSize; this->inputDylibWeakBindStart = layout.linkedit.weakBindOpcodes.buffer; this->inputDylibWeakBindEnd = this->inputDylibWeakBindStart + layout.linkedit.weakBindOpcodes.bufferSize; // The export trie is going to change size, as it might grow/shrink based on removing elements // but addresses growing in size const uint8_t* trieStart = layout.linkedit.exportsTrie.buffer; const uint8_t* trieEnd = trieStart + layout.linkedit.exportsTrie.bufferSize; uint32_t estimatedSize = estimateExportTrieSize(trieStart, trieEnd); addLinkedit(Kind::linkeditExportTrie, InputDylibFileOffset((uint64_t)linkeditCmd->export_off), InputDylibFileSize((uint64_t)linkeditCmd->export_size), CacheVMSize((uint64_t)estimatedSize), pointerSize); }); break; } case LC_SEGMENT_SPLIT_INFO: { // The final cache dylib won't have split seg, but keep a pointer to the source dylib split seg, for use later this->inputMF->withFileLayout(diag, ^(const mach_o::Layout &layout) { this->inputDylibSplitSegStart = layout.linkedit.splitSegInfo.buffer; this->inputDylibSplitSegEnd = this->inputDylibSplitSegStart + layout.linkedit.splitSegInfo.bufferSize; }); break; } case LC_FUNCTION_STARTS: { const linkedit_data_command* linkeditCmd = (const linkedit_data_command*)cmd; addLinkedit(Kind::linkeditFunctionStarts, InputDylibFileOffset((uint64_t)linkeditCmd->dataoff), InputDylibFileSize((uint64_t)linkeditCmd->datasize), CacheVMSize((uint64_t)linkeditCmd->datasize), pointerSize); break; } case LC_DATA_IN_CODE: { const linkedit_data_command* linkeditCmd = (const linkedit_data_command*)cmd; addLinkedit(Kind::linkeditDataInCode, InputDylibFileOffset((uint64_t)linkeditCmd->dataoff), InputDylibFileSize((uint64_t)linkeditCmd->datasize), CacheVMSize((uint64_t)linkeditCmd->datasize), pointerSize); break; } case LC_DYLD_CHAINED_FIXUPS: { // Drop chained fixups break; } case LC_DYLD_EXPORTS_TRIE: { const linkedit_data_command* linkeditCmd = (const linkedit_data_command*)cmd; this->inputMF->withFileLayout(diag, ^(const mach_o::Layout &layout) { // The export trie is going to change size, as it might grow/shrink based on removing elements // but addresses growing in size const uint8_t* trieStart = layout.linkedit.exportsTrie.buffer; const uint8_t* trieEnd = trieStart + layout.linkedit.exportsTrie.bufferSize; uint32_t estimatedSize = estimateExportTrieSize(trieStart, trieEnd); addLinkedit(Kind::linkeditExportTrie, InputDylibFileOffset((uint64_t)linkeditCmd->dataoff), InputDylibFileSize((uint64_t)linkeditCmd->datasize), CacheVMSize((uint64_t)estimatedSize), pointerSize); }); break; } case LC_FUNCTION_VARIANTS: { const linkedit_data_command* linkeditCmd = (const linkedit_data_command*)cmd; addLinkedit(Kind::linkeditFunctionVariants, InputDylibFileOffset((uint64_t)linkeditCmd->dataoff), InputDylibFileSize((uint64_t)linkeditCmd->datasize), CacheVMSize((uint64_t)linkeditCmd->datasize), pointerSize); break; } } }); diag.assertNoError(); } void CacheDylib::copyRawSegments(const BuilderConfig& config, Timer::AggregateTimer& timer) { const bool log = config.log.printDebugCacheLayout; Timer::AggregateTimer::Scope timedScope(timer, "dylib copyRawSegments time"); for ( const DylibSegmentChunk& segment : this->segments ) { const uint8_t* srcSegment = (uint8_t*)segment.inputFile->mf + segment.inputFileOffset.rawValue(); if ( segment.subCacheBuffer == nullptr ) { // Note, Linkedit isn't copied here, so will have no buffer, even though it has a size assert( (segment.cacheVMSize == CacheVMSize(0ULL)) || (segment.segmentName == "__LINKEDIT") ); if ( log ) { config.log.log("Skipping empty segment %s\n", segment.segmentName.data()); } } else { if ( log ) { config.log.log("Copying %s from %p to (%p..%p)\n", segment.segmentName.data(), srcSegment, segment.subCacheBuffer, segment.subCacheBuffer + segment.inputFileSize.rawValue()); } memcpy(segment.subCacheBuffer, srcSegment, segment.inputFileSize.rawValue()); } #if DEBUG watchMemory(segment, "install name", "segment name", 0x0); #endif } // Also copy linkedit in to place for ( const LinkeditDataChunk& chunk : this->linkeditChunks ) { const uint8_t* srcChunk = (uint8_t*)chunk.inputFile->mf + chunk.inputFileOffset.rawValue(); if ( log ) { config.log.log("Copying from %p to (%p..%p)\n", srcChunk, chunk.subCacheBuffer, chunk.subCacheBuffer + chunk.inputFileSize.rawValue()); } memcpy(chunk.subCacheBuffer, srcChunk, chunk.inputFileSize.rawValue()); } // The nlist was optimized. Its not in the linkeditChunks if ( !this->optimizedSymbols.nlist64.empty() ) { memcpy(this->optimizedSymbols.subCacheBuffer, this->optimizedSymbols.nlist64.data(), sizeof(struct nlist_64) * this->optimizedSymbols.nlist64.size()); } else { memcpy(this->optimizedSymbols.subCacheBuffer, this->optimizedSymbols.nlist32.data(), sizeof(struct nlist) * this->optimizedSymbols.nlist32.size()); } } void CacheDylib::applySplitSegInfo(Diagnostics& diag, const BuilderOptions& options, const BuilderConfig& config, Timer::AggregateTimer& timer, UnmappedSymbolsOptimizer& unmappedSymbolsOptimizer) { Timer::AggregateTimer::Scope timedScope(timer, "dylib applySplitSegInfo time"); __block const uint8_t* chainedFixupsStart = nullptr; __block const uint8_t* chainedFixupsEnd = nullptr; __block const uint8_t* rebaseOpcodesStart = nullptr; __block const uint8_t* rebaseOpcodesEnd = nullptr; this->inputMF->withFileLayout(diag, ^(const mach_o::Layout &layout) { if ( layout.linkedit.regularBindOpcodes.hasValue() ) { rebaseOpcodesStart = layout.linkedit.rebaseOpcodes.buffer; rebaseOpcodesEnd = rebaseOpcodesStart + layout.linkedit.rebaseOpcodes.bufferSize; } else if ( layout.linkedit.chainedFixups.hasValue() ) { chainedFixupsStart = layout.linkedit.chainedFixups.buffer; chainedFixupsEnd = chainedFixupsStart + layout.linkedit.chainedFixups.bufferSize; } }); adjustor->adjustDylib(diag, config.layout.cacheBaseAddress, this->cacheMF, this->installName, chainedFixupsStart, chainedFixupsEnd, this->inputDylibSplitSegStart, this->inputDylibSplitSegEnd, rebaseOpcodesStart, rebaseOpcodesEnd, &this->optimizedSections); // Not strictly part of the dylib any more, but the unmapped locals also need adjusting if ( options.localSymbolsMode == cache_builder::LocalSymbolsMode::unmap ) { typedef UnmappedSymbolsOptimizer::LocalSymbolInfo LocalSymbolInfo; LocalSymbolInfo& symbolInfo = unmappedSymbolsOptimizer.symbolInfos[this->cacheIndex]; for ( uint32_t i = 0; i != symbolInfo.nlistCount; ++i ) { uint32_t symbolIndex = symbolInfo.nlistStartIndex + i; if ( config.layout.is64 ) { struct nlist_64& sym = unmappedSymbolsOptimizer.symbolNlistChunk.nlist64[symbolIndex]; InputDylibVMAddress inputVMAddr(sym.n_value); CacheVMAddress cacheVMAddr = adjustor->adjustVMAddr(inputVMAddr); sym.n_value = cacheVMAddr.rawValue(); } else { struct nlist& sym = unmappedSymbolsOptimizer.symbolNlistChunk.nlist32[symbolIndex]; InputDylibVMAddress inputVMAddr((uint64_t)sym.n_value); CacheVMAddress cacheVMAddr = adjustor->adjustVMAddr(inputVMAddr); sym.n_value = (uint32_t)cacheVMAddr.rawValue(); } } } } void CacheDylib::updateSymbolTables(Diagnostics& diag, const BuilderConfig& config, Timer::AggregateTimer& timer) { Timer::AggregateTimer::Scope timedScope(timer, "dylib updateSymbolTables time"); for ( LinkeditDataChunk& chunk : this->linkeditChunks ) { if ( !chunk.isIndirectSymbols() ) continue; // We found the indirect symbol table, now make sure the updated table we cached from earlier // is the correct size uint64_t newTableSize = this->indirectSymbolTable.size() * sizeof(uint32_t); if ( newTableSize != chunk.cacheVMSize.rawValue() ) { diag.error("Wrong indirect symbol table size (%lld != %lld)", newTableSize, chunk.cacheVMSize.rawValue()); return; } memcpy(chunk.subCacheBuffer, this->indirectSymbolTable.data(), newTableSize); } } std::optional<CacheDylib::BindTargetAndName> CacheDylib::findDyldMagicSymbolAddress(const char* fullSymbolName, std::string_view name) const { auto nextString = [&]() -> std::string_view { auto pos = name.find('$'); if ( pos == std::string_view::npos ) { auto str = name; name = ""; return str; } auto str = name.substr(0, pos); name = name.substr(pos + 1); return str; }; std::string_view type = nextString(); if ( type == "segment" ) { std::string_view segmentType = nextString(); std::string_view segmentName = nextString(); bool isStart = (segmentType == "start"); bool isEnd = (segmentType == "end"); __block std::optional<VMAddress> vmAddr; this->inputHdr->forEachSegment(^(const Header::SegmentInfo& info, bool& stop) { if ( info.segmentName == segmentName ) { if ( isStart ) vmAddr = VMAddress(info.vmaddr); else if ( isEnd ) vmAddr = VMAddress(info.vmaddr) + VMOffset(info.vmsize); stop = true; } }); if ( !vmAddr ) return std::nullopt; VMOffset vmOff = *vmAddr - VMAddress(inputLoadAddress.rawValue()); return std::make_pair(BindTarget{ BindTarget::Kind::inputImage, { .inputImage = { vmOff, this, /* weak def */ false } } }, std::string(fullSymbolName)); } return std::nullopt; } // FIXME: This was stolen from Loader. try unify them again CacheDylib::BindTargetAndName CacheDylib::resolveSymbol(Diagnostics& diag, int libOrdinal, const char* symbolName, bool weakImport, const std::vector<const CacheDylib*>& cacheDylibs) const { const CacheDylib* targetDylib = nullptr; BindTarget nullBindTarget = { BindTarget::Kind::absolute, { .absolute = { 0 } } }; if ( (libOrdinal > 0) && ((unsigned)libOrdinal <= this->inputDependents.size()) ) { targetDylib = this->inputDependents[libOrdinal - 1].dylib; } else if ( libOrdinal == BIND_SPECIAL_DYLIB_SELF ) { targetDylib = this; } else if ( libOrdinal == BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE ) { diag.error("shared cache dylibs bind to the main executable: %s\n Referenced from: %s", symbolName, this->installName.data()); return { nullBindTarget, "" }; } else if ( libOrdinal == BIND_SPECIAL_DYLIB_FLAT_LOOKUP ) { for ( const CacheDylib* cacheDylib : cacheDylibs ) { std::optional<BindTargetAndName> bindTargetAndName = cacheDylib->hasExportedSymbol(diag, symbolName, SearchMode::onlySelf); if ( bindTargetAndName.has_value() ) return bindTargetAndName.value(); } if ( weakImport ) { // ok to be missing, bind to NULL return { nullBindTarget, "" }; } // missing symbol, but not weak-import or lazy-bound, so error diag.error("symbol not found in flat namespace '%s'\n Referenced from: %s", symbolName, this->installName.data()); return { nullBindTarget, "" }; } else if ( libOrdinal == BIND_SPECIAL_DYLIB_WEAK_LOOKUP ) { // when dylibs in cache are build, we don't have real load order, so do weak binding differently // look first in /usr/lib/libc++, most will be here for ( const CacheDylib* cacheDylib : cacheDylibs ) { if ( cacheDylib->inputHdr->hasWeakDefs() && startsWith(cacheDylib->installName, "/usr/lib/libc++.") ) { std::optional<BindTargetAndName> bindTargetAndName = cacheDylib->hasExportedSymbol(diag, symbolName, SearchMode::onlySelf); if ( bindTargetAndName.has_value() ) return bindTargetAndName.value(); // We found libc++, but not this symbol. Break out of the loop as we don't need to look in other images break; } } // if not found, try looking in the images itself, most custom weak-def symbols have a copy in the image itself std::optional<BindTargetAndName> sellBindTargetAndName = this->hasExportedSymbol(diag, symbolName, SearchMode::onlySelf); if ( sellBindTargetAndName.has_value() ) return sellBindTargetAndName.value(); // if this image directly links with something that also defines this weak-def, use that because we know it will be loaded for ( const CacheDylib::DependentDylib& dependentDylib : this->inputDependents ) { if ( dependentDylib.kind == DependentDylib::Kind::upward ) continue; // Skip missing weak dylibs if ( dependentDylib.kind == DependentDylib::Kind::weakLink ) { if ( dependentDylib.dylib == nullptr ) continue; } std::optional<BindTargetAndName> bindTargetAndName = dependentDylib.dylib->hasExportedSymbol(diag, symbolName, SearchMode::selfAndReexports); if ( bindTargetAndName.has_value() ) return bindTargetAndName.value(); } // no impl?? diag.error("weak-def symbol (%s) not found in dyld cache\n Referenced from: %s", symbolName, this->installName.data()); return { nullBindTarget, "" }; } else { diag.error("unknown library ordinal %d in %s when binding '%s'", libOrdinal, this->installName.data(), symbolName); return { nullBindTarget, "" }; } if ( targetDylib != nullptr ) { if ( const char* dyldMagic = strstr(symbolName, "$dyld$") ) { std::string_view name = dyldMagic + 6; std::optional<BindTargetAndName> target; // only synthetic dylibs without a need for the patch table can use magic dyld symbols // dyld itself does not know about them so it won't be able to bind them if ( !needsPatchTable ) target = targetDylib->findDyldMagicSymbolAddress(symbolName, name); if ( target ) return target.value(); const char* expectedInDylib = "unknown"; if ( targetDylib != nullptr ) expectedInDylib = targetDylib->installName.data(); diag.error("Symbol not found: %s\n Referenced from: %s\n Expected in: %s", symbolName, this->installName.data(), expectedInDylib); return { nullBindTarget, "" }; } std::optional<BindTargetAndName> bindTargetAndName = targetDylib->hasExportedSymbol(diag, symbolName, SearchMode::selfAndReexports); if ( diag.hasError() ) return { nullBindTarget, "" }; if ( bindTargetAndName.has_value() ) return bindTargetAndName.value(); } if ( weakImport ) { // ok to be missing, bind to NULL return { nullBindTarget, "" }; } const char* expectedInDylib = "unknown"; if ( targetDylib != nullptr ) expectedInDylib = targetDylib->installName.data(); diag.error("Symbol not found: %s\n Referenced from: %s\n Expected in: %s", symbolName, this->installName.data(), expectedInDylib); return { nullBindTarget, "" }; } std::optional<CacheDylib::BindTargetAndName> CacheDylib::hasExportedSymbol(Diagnostics& diag, const char* symbolName, SearchMode mode) const { bool canSearchDependentReexports = false; bool searchSelf = false; switch ( mode ) { case SearchMode::onlySelf: canSearchDependentReexports = false; searchSelf = true; break; case SearchMode::selfAndReexports: canSearchDependentReexports = true; searchSelf = true; break; } __block const uint8_t* trieStart = nullptr; __block const uint8_t* trieEnd = nullptr; this->inputMF->withFileLayout(diag, ^(const mach_o::Layout &layout) { if ( layout.linkedit.exportsTrie.hasValue() ) { trieStart = layout.linkedit.exportsTrie.buffer; trieEnd = trieStart + layout.linkedit.exportsTrie.bufferSize; } }); if ( trieStart == nullptr ) { diag.error("shared cache dylibs must have an export trie"); return {}; } const uint8_t* node = MachOFile::trieWalk(diag, trieStart, trieEnd, symbolName); //state.log(" trieStart=%p, trieSize=0x%08X, node=%p, error=%s\n", trieStart, trieSize, node, diag.errorMessage()); if ( (node != nullptr) && searchSelf ) { const uint8_t* p = node; const uint64_t flags = MachOFile::read_uleb128(diag, p, trieEnd); if ( flags & EXPORT_SYMBOL_FLAGS_REEXPORT ) { // re-export from another dylib, lookup there const uint64_t ordinal = MachOFile::read_uleb128(diag, p, trieEnd); const char* importedName = (char*)p; if ( importedName[0] == '\0' ) { importedName = symbolName; } if ( (ordinal == 0) || (ordinal > this->inputDependents.size()) ) { diag.error("re-export ordinal %lld in %s out of range for %s", ordinal, this->installName.data(), symbolName); return {}; } uint32_t depIndex = (uint32_t)(ordinal - 1); if ( const CacheDylib* dependentDylib = this->inputDependents[depIndex].dylib ) return dependentDylib->hasExportedSymbol(diag, importedName, mode); // re-exported symbol from weak-linked dependent which is missing return {}; } else { if ( diag.hasError() ) return {}; bool isAbsoluteSymbol = ((flags & EXPORT_SYMBOL_FLAGS_KIND_MASK) == EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE); bool isWeakDef = (flags & EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION); bool isFuncVariant = (flags & EXPORT_SYMBOL_FLAGS_FUNCTION_VARIANT); uint64_t value = MachOFile::read_uleb128(diag, p, trieEnd); if ( isAbsoluteSymbol ) { BindTarget result = { BindTarget::Kind::absolute, { .absolute = { value } } }; return (BindTargetAndName) { result, symbolName }; } uint16_t fvTableIndex = 0; if ( isFuncVariant ) { // next uleb128 is func-variant table index fvTableIndex = (uint16_t)MachOFile::read_uleb128(diag, p, trieEnd); } // Bind to image BindTarget result = { BindTarget::Kind::inputImage, { .inputImage = { VMOffset(value), this, isWeakDef, isFuncVariant, fvTableIndex } } }; return (BindTargetAndName) { result, symbolName }; } } if ( canSearchDependentReexports ) { // Search re-exported dylibs for ( const CacheDylib::DependentDylib& dependentDylib : this->inputDependents ) { if ( dependentDylib.kind != DependentDylib::Kind::reexport ) continue; // No need for a weak check here as re-exports can't be weak std::optional<BindTargetAndName> bindTargetAndName = dependentDylib.dylib->hasExportedSymbol(diag, symbolName, mode); if ( diag.hasError() ) return {}; if ( bindTargetAndName.has_value() ) return bindTargetAndName.value(); } } return {}; } std::vector<Error> CacheDylib::calculateBindTargets(Diagnostics& diag, const BuilderConfig& config, Timer::AggregateTimer& timer, const std::vector<const CacheDylib*>& cacheDylibs, PatchInfo& dylibPatchInfo) { Timer::AggregateTimer::Scope timedScope(timer, "dylib calculateBindTargets time"); // As we are running in parallel, addresses in other dylibs may not have been shifted yet. We may also // race looking at the export trie in a target dylib, while it is being shifted by AdjustDylibSegments. // Given that, we'll do all the analysis on the input dylibs, with knowledge of where they'll shift to __block std::vector<Error> errors; auto handleBindTarget = ^(int libOrdinal, const char* symbolName, uint64_t addend, bool weakImport, bool& stop) { Diagnostics symbolDiag; BindTargetAndName bindTargetAndName = this->resolveSymbol(symbolDiag, libOrdinal, symbolName, weakImport, cacheDylibs); BindTarget& bindTarget = bindTargetAndName.first; if ( symbolDiag.hasError() ) { errors.push_back(Error("%s", symbolDiag.errorMessageCStr())); return; } bindTarget.addend = addend; bindTarget.isWeakImport = weakImport; #if DEBUG bindTarget.name = symbolName; #endif this->bindTargets.push_back(std::move(bindTarget)); dylibPatchInfo.bindTargetNames.push_back(std::move(bindTargetAndName.second)); }; if ( this->inputMF->hasChainedFixups() ) { // Ideally we'd just walk the chained fixups command, but the macOS simulator support dylibs use // the old threaded rebase format, not chained fixups this->inputMF->withFileLayout(diag, ^(const mach_o::Layout &layout) { mach_o::Fixups fixups(layout); fixups.forEachBindTarget(diag, false, 0, ^(const mach_o::Fixups::BindTargetInfo& info, bool& stop) { handleBindTarget(info.libOrdinal, info.symbolName, info.addend, info.weakImport, stop); }, ^(const mach_o::Fixups::BindTargetInfo& info, bool& stop) { // This should never happen on chained fixups assert(0); }); }); } else if ( this->inputMF->hasOpcodeFixups() ) { // Use the fixups from the source dylib this->inputMF->withFileLayout(diag, ^(const mach_o::Layout &layout) { mach_o::Fixups fixups(layout); bool allowLazyBinds = false; fixups.forEachBindTarget(diag, allowLazyBinds, 0, ^(const mach_o::Fixups::BindTargetInfo& info, bool& stop) { handleBindTarget(info.libOrdinal, info.symbolName, info.addend, info.weakImport, stop); }, ^(const mach_o::Fixups::BindTargetInfo& info, bool& stop) { if ( !this->weakBindTargetsStartIndex.has_value() ) this->weakBindTargetsStartIndex = this->bindTargets.size(); handleBindTarget(info.libOrdinal, info.symbolName, info.addend, info.weakImport, stop); }); }); } else { // Cache dylibs shouldn't use old style fixups. } if ( !errors.empty() ) diag.error("missing symbols"); return std::move(errors); } void CacheDylib::bindLocation(Diagnostics& diag, const BuilderConfig& config, const BindTarget& bindTarget, uint64_t addend, uint32_t bindOrdinal, uint32_t segIndex, dyld3::MachOFile::ChainedFixupPointerOnDisk* fixupLoc, CacheVMAddress fixupVMAddr, MachOFile::PointerMetaData pmd, CoalescedGOTsMap& coalescedGOTs, CoalescedGOTsMap& coalescedAuthGOTs, CoalescedGOTsMap& coalescedAuthPtrs, PatchInfo& dylibPatchInfo, FunctionVariantsOptimizer& functionVariantsOptimizer) { switch ( bindTarget.kind ) { case BindTarget::Kind::absolute: { uint64_t targetValue = bindTarget.absolute.value + addend; if ( config.layout.is64 ) { fixupLoc->raw64 = targetValue; } else { fixupLoc->raw32 = (uint32_t)targetValue; } // Tell the slide info emitter to ignore this location this->segments[segIndex].tracker.remove(fixupLoc); return; } case BindTarget::Kind::inputImage: { diag.error("Input binds should have been converted to cache binds in %s: %d", this->installName.data(), bindOrdinal); return; } case BindTarget::Kind::cacheImage: { CacheVMAddress targetDylibLoadAddress = bindTarget.cacheImage.targetDylib->cacheLoadAddress; CacheVMAddress targetVMAddr = targetDylibLoadAddress + bindTarget.cacheImage.targetRuntimeOffset; uint64_t finalVMAddrWithAddend = targetVMAddr.rawValue() + addend; if ( config.layout.is64 ) { uint64_t finalVMAddr = finalVMAddrWithAddend; uint8_t high8 = (uint8_t)(finalVMAddr >> 56); if ( high8 != 0 ) { // Remove high8 from the vmAddr finalVMAddr = finalVMAddr & 0x00FFFFFFFFFFFFFFULL; } Fixup::Cache64::setLocation(config.layout.cacheBaseAddress, fixupLoc, CacheVMAddress(finalVMAddr), high8, pmd.diversity, pmd.usesAddrDiversity, pmd.key, pmd.authenticated); } else { Fixup::Cache32::setLocation(config.layout.cacheBaseAddress, fixupLoc, CacheVMAddress(finalVMAddrWithAddend)); } // Tell the slide info emitter to slide this location this->segments[segIndex].tracker.add(fixupLoc); // Work out if the location we just wrote is a coalesced GOT. If so, NULL the current location and // note down the fixup to the GOT. We can't just apply the GOT fixup, as we might be running in parallel with // other threads all trying to do the same thing if( needsPatchTable ) { // The GOT map is keyed by the input VMAddr, so convert back to that VMOffset segmentVMOffset = fixupVMAddr - this->segments[segIndex].cacheVMAddress; InputDylibVMAddress inputFixupVMAddr = this->segments[segIndex].inputVMAddress + segmentVMOffset; auto checkGOTs = ^(CoalescedGOTsMap& gotMap) { auto gotIt = gotMap.find(inputFixupVMAddr); if ( gotIt != gotMap.end() ) { // NULL out this entry if ( config.layout.is64 ) { fixupLoc->raw64 = 0; } else { fixupLoc->raw32 = 0; } // Tell the slide info emitter to ignore this location this->segments[segIndex].tracker.remove(fixupLoc); return true; } return false; }; if ( checkGOTs(coalescedGOTs) || checkGOTs(coalescedAuthGOTs) || checkGOTs(coalescedAuthPtrs) ) { // normal GOT/auth GOT/auth ptr } else { // if target is a function variant, record that dyld may need to update pointer at launch if ( bindTarget.cacheImage.isFunctionVariant ) { uint64_t fvTableVmAddr = 0; uint32_t fvTableVmSize = 0; for ( const LinkeditDataChunk& chunk : bindTarget.cacheImage.targetDylib->linkeditChunks ) { if ( chunk.isFunctionVariantsTable() ) { fvTableVmAddr = chunk.cacheVMAddress.rawValue(); fvTableVmSize = (uint32_t)chunk.cacheVMSize.rawValue(); break; } } dyld_cache_function_variant_entry entry; entry.fixupLocVmAddr = fixupVMAddr.rawValue(); entry.functionVariantTableVmAddr = fvTableVmAddr; entry.functionVariantTableSizeDiv4 = fvTableVmSize/4; entry.dylibHeaderVmAddr = bindTarget.cacheImage.targetDylib->cacheLoadAddress.rawValue(); entry.variantIndex = bindTarget.cacheImage.functionVariantTableIndex; entry.pacAuth = pmd.authenticated; entry.pacAddress = pmd.usesAddrDiversity; entry.pacKey = pmd.key; entry.pacDiversity = pmd.diversity; entry.targetDylibIndex = bindTarget.cacheImage.targetDylib->cacheIndex; assert(entry.variantIndex == bindTarget.cacheImage.functionVariantTableIndex); functionVariantsOptimizer.infos.push_back(entry); } } } break; } } } void CacheDylib::bindWithChainedFixups(Diagnostics& diag, const BuilderConfig& config, CoalescedGOTsMap& coalescedGOTs, CoalescedGOTsMap& coalescedAuthGOTs, CoalescedGOTsMap& coalescedAuthPtrs, PatchInfo& dylibPatchInfo, FunctionVariantsOptimizer& functionVariantsOptimizer) { auto fixupHandler = ^(MachOFile::ChainedFixupPointerOnDisk* fixupLoc, uint16_t chainedFormat, uint32_t segIndex, CacheVMAddress fixupVMAddr, bool& stopChain) { MachOFile::PointerMetaData pmd(fixupLoc, chainedFormat); uint32_t bindOrdinal; int64_t embeddedAddend; if ( !fixupLoc->isBind(chainedFormat, bindOrdinal, embeddedAddend) ) { // Rebases might be stored in a side table from applying split seg. If so, we // can copy their values in to place now if ( config.layout.is64 ) { uint64_t targetVMAddr; if ( this->segments[segIndex].tracker.hasRebaseTarget64(fixupLoc, &targetVMAddr) ) { // The value is now stored in targetVMAddr. // We'll use it later // We should never get high8 from hasRebaseTarget64() uint64_t high8 = targetVMAddr >> 56; assert(high8 == 0); } else { uint64_t runtimeOffset; bool isRebase = fixupLoc->isRebase(chainedFormat, this->cacheLoadAddress.rawValue(), runtimeOffset); assert(isRebase); targetVMAddr = this->cacheLoadAddress.rawValue() + runtimeOffset; // Remove high8 if we have it. The PMD has it too uint64_t high8 = targetVMAddr >> 56; assert(pmd.high8 == high8); targetVMAddr &= 0x00FFFFFFFFFFFFFFULL; } CacheVMAddress targetCacheAddress(targetVMAddr); Fixup::Cache64::setLocation(config.layout.cacheBaseAddress, fixupLoc, targetCacheAddress, pmd.high8, pmd.diversity, pmd.usesAddrDiversity, pmd.key, pmd.authenticated); } else { uint32_t targetVMAddr; assert(this->segments[segIndex].tracker.hasRebaseTarget32(fixupLoc, &targetVMAddr) && "32-bit archs always store target in side table"); CacheVMAddress targetCacheAddress((uint64_t)targetVMAddr); Fixup::Cache32::setLocation(config.layout.cacheBaseAddress, fixupLoc, targetCacheAddress); } return; } if ( bindOrdinal >= this->bindTargets.size() ) { diag.error("out of range bind ordinal %d (max %lu)", bindOrdinal, this->bindTargets.size()); stopChain = true; return; } const BindTarget& targetInTable = this->bindTargets[bindOrdinal]; uint64_t addend = targetInTable.addend + embeddedAddend; this->bindLocation(diag, config, targetInTable, addend, bindOrdinal, segIndex, fixupLoc, fixupVMAddr, pmd, coalescedGOTs, coalescedAuthGOTs, coalescedAuthPtrs, dylibPatchInfo, functionVariantsOptimizer); }; this->inputMF->withFileLayout(diag, ^(const mach_o::Layout &layout) { mach_o::Fixups fixups(layout); // Use the chained fixups header from the input dylib fixups.withChainStarts(diag, ^(const dyld_chained_starts_in_image* starts) { MachOFile::forEachFixupChainSegment(diag, starts, ^(const dyld_chained_starts_in_segment* segInfo, uint32_t segIndex, bool& stopSegment) { // We now have the dyld_chained_starts_in_segment from the input dylib, but // we want to walk the chain in the cache dylib DylibSegmentChunk& segmentInfo = this->segments[segIndex]; uint8_t* cacheDylibSegment = segmentInfo.subCacheBuffer; auto adaptor = ^(MachOFile::ChainedFixupPointerOnDisk* fixupLocation, bool& stop) { uint64_t fixupOffsetInSegment = (uint64_t)fixupLocation - (uint64_t)cacheDylibSegment; CacheVMAddress fixupVMAddr = segmentInfo.cacheVMAddress + VMOffset(fixupOffsetInSegment); fixupHandler(fixupLocation, segInfo->pointer_format, segIndex, fixupVMAddr, stop); if ( stop ) stopSegment = true; }; MachOFile::forEachFixupInSegmentChains(diag, segInfo, false, cacheDylibSegment, adaptor); }); }); }); } void CacheDylib::bindWithOpcodeFixups(Diagnostics& diag, const BuilderConfig& config, CoalescedGOTsMap& coalescedGOTs, CoalescedGOTsMap& coalescedAuthGOTs, CoalescedGOTsMap& coalescedAuthPtrs, PatchInfo& dylibPatchInfo, FunctionVariantsOptimizer& functionVariantsOptimizer) { auto handleFixup = ^(uint64_t fixupRuntimeOffset, int bindOrdinal, uint32_t segmentIndex, bool& stopSegment) { DylibSegmentChunk& segmentInfo = this->segments[segmentIndex]; CacheVMAddress fixupVMAddr = this->cacheLoadAddress + VMOffset(fixupRuntimeOffset); VMOffset segmentOffset = fixupVMAddr - segmentInfo.cacheVMAddress; uint8_t* fixupLoc = segmentInfo.subCacheBuffer + segmentOffset.rawValue(); if ( bindOrdinal >= this->bindTargets.size() ) { diag.error("out of range bind ordinal %d (max %lu)", bindOrdinal, this->bindTargets.size()); stopSegment = true; return; } const BindTarget& targetInTable = this->bindTargets[bindOrdinal]; uint64_t addend = targetInTable.addend; this->bindLocation(diag, config, targetInTable, addend, bindOrdinal, segmentIndex, (dyld3::MachOFile::ChainedFixupPointerOnDisk*)fixupLoc, fixupVMAddr, dyld3::MachOFile::PointerMetaData(), coalescedGOTs, coalescedAuthGOTs, coalescedAuthPtrs, dylibPatchInfo, functionVariantsOptimizer); }; // Use the fixups from the source dylib mach_o::LinkeditLayout linkedit; if ( !this->inputMF->getLinkeditLayout(diag, linkedit) ) { diag.error("Couldn't get dylib layout"); return; } // Use the segment layout from the cache dylib so that VMAddresses are correct __block std::vector<mach_o::SegmentLayout> segmentLayout; segmentLayout.reserve(this->segments.size()); for ( const DylibSegmentChunk& dylibSegment : this->segments ) { mach_o::SegmentLayout segment; segment.vmAddr = dylibSegment.cacheVMAddress.rawValue(); segment.vmSize = dylibSegment.cacheVMSize.rawValue(); segment.fileOffset = dylibSegment.subCacheFileOffset.rawValue(); segment.fileSize = dylibSegment.subCacheFileSize.rawValue(); segment.buffer = dylibSegment.subCacheBuffer; segment.kind = mach_o::SegmentLayout::Kind::unknown; if ( dylibSegment.segmentName == "__TEXT" ) { segment.kind = mach_o::SegmentLayout::Kind::text; } else if ( dylibSegment.segmentName == "__LINKEDIT" ) { segment.kind = mach_o::SegmentLayout::Kind::linkedit; } segmentLayout.push_back(segment); } // The cache segments don't have the permissions. Get that from the load commands this->cacheHdr->forEachSegment(^(const Header::SegmentInfo& info, bool& stop) { segmentLayout[info.segmentIndex].protections = info.initProt; }); mach_o::Layout layout(this->inputMF, { segmentLayout.data(), segmentLayout.data() + segmentLayout.size() }, linkedit); mach_o::Fixups fixups(layout); fixups.forEachRebaseLocation_Opcodes(diag, ^(uint64_t fixupRuntimeOffset, uint32_t segmentIndex, bool& stop) { DylibSegmentChunk& segmentInfo = this->segments[segmentIndex]; uint64_t fixupCacheVMAddr = layout.textUnslidVMAddr() + fixupRuntimeOffset; uint64_t segmentOffset = fixupCacheVMAddr - segmentInfo.cacheVMAddress.rawValue(); uint8_t* fixupLoc = segmentInfo.subCacheBuffer + segmentOffset; // Convert from rebase vmAddr to the internal cache format if ( config.layout.is64 ) { uint64_t targetVMAddr = *(uint64_t*)fixupLoc; CacheVMAddress targetCacheAddress(targetVMAddr); uint8_t high8 = (uint8_t)(targetVMAddr >> 56); if ( high8 != 0 ) { // Remove high8 from the vmAddr targetVMAddr = targetVMAddr & 0x00FFFFFFFFFFFFFFULL; } // Unused PointerMetadata, but just use here to get all the fields dyld3::MachOFile::PointerMetaData pmd; Fixup::Cache64::setLocation(config.layout.cacheBaseAddress, fixupLoc, CacheVMAddress(targetVMAddr), high8, pmd.diversity, pmd.usesAddrDiversity, pmd.key, pmd.authenticated); } else { uint32_t targetVMAddr = *(uint32_t*)fixupLoc; CacheVMAddress targetCacheAddress((uint64_t)targetVMAddr); Fixup::Cache32::setLocation(config.layout.cacheBaseAddress, fixupLoc, CacheVMAddress((uint64_t)targetVMAddr)); } }); // Do binds after rebases, in case we have lazy binds which override the rebase fixups.forEachBindLocation_Opcodes(diag, ^(uint64_t runtimeOffset, uint32_t segmentIndex, unsigned int targetIndex, bool& stop) { handleFixup(runtimeOffset, targetIndex, segmentIndex, stop); }, ^(uint64_t runtimeOffset, uint32_t segmentIndex, unsigned int overrideBindTargetIndex, bool& stop) { assert(this->weakBindTargetsStartIndex.has_value()); handleFixup(runtimeOffset, this->weakBindTargetsStartIndex.value() + overrideBindTargetIndex, segmentIndex, stop); }); } void CacheDylib::calculateBindLocationPatchInfo(Diagnostics& diag, const BuilderConfig& config, const BindTarget& bindTarget, uint64_t addend, uint32_t bindOrdinal, uint32_t segIndex, InputDylibVMAddress fixupVMAddr, MachOFile::PointerMetaData pmd, CoalescedGOTsMap& coalescedGOTs, CoalescedGOTsMap& coalescedAuthGOTs, CoalescedGOTsMap& coalescedAuthPtrs, PatchInfo& dylibPatchInfo) { switch ( bindTarget.kind ) { case BindTarget::Kind::absolute: { uint64_t targetValue = bindTarget.absolute.value + addend; auto checkGOTs = ^(CoalescedGOTsMap& gotMap, std::vector<std::vector<PatchInfo::GOTInfo>>& gotInfo) { auto gotIt = gotMap.find(fixupVMAddr); if ( gotIt != gotMap.end() ) { // Probably a missing weak import. Rewrite the original GOT anyway, but also the coalesced one const ChunkPlusOffset gotPlusOffset = gotIt->second; DyldCachePatchableGOTLocation patchLoc(gotPlusOffset.first, gotPlusOffset.second, pmd, addend, bindTarget.isWeakImport); auto& gotUses = gotInfo[bindOrdinal]; gotUses.emplace_back((PatchInfo::GOTInfo){ patchLoc, targetValue }); return true; } return false; }; if ( checkGOTs(coalescedGOTs, dylibPatchInfo.bindGOTUses) ) { // normal GOT } else if ( checkGOTs(coalescedAuthGOTs, dylibPatchInfo.bindAuthGOTUses) ) { // auth GOT } else if ( checkGOTs(coalescedAuthPtrs, dylibPatchInfo.bindAuthPtrUses) ) { // auth ptr } return; } case BindTarget::Kind::inputImage: { InputDylibVMAddress targetDylibLoadAddress = bindTarget.inputImage.targetDylib->inputLoadAddress; InputDylibVMAddress targetVMAddr = targetDylibLoadAddress + bindTarget.inputImage.targetRuntimeOffset; uint64_t finalTargetVMAddrWithAddend = targetVMAddr.rawValue() + addend; // Work out if the location we just wrote is a coalesced GOT. If so, NULL the current location and // note down the fixup to the GOT. We can't just apply the GOT fixup, as we might be running in parallel with // other threads all trying to do the same thing uint64_t patchTableAddend = addend; MachOFile::PointerMetaData patchTablePMD = pmd; uint64_t addendHigh8 = addend >> 56; if ( addendHigh8 != 0 ) { // Put the high8 from the addend in to the high8 of the patch assert(patchTablePMD.high8 == 0); patchTablePMD.high8 = (uint32_t)addendHigh8; // Remove high8 from the addend patchTableAddend = patchTableAddend & 0x00FFFFFFFFFFFFFFULL; } InputDylibVMOffset finalTargetVMOffset = InputDylibVMAddress(finalTargetVMAddrWithAddend) - targetDylibLoadAddress; auto checkGOTs = ^(CoalescedGOTsMap& gotMap, std::vector<std::vector<PatchInfo::GOTInfo>>& gotInfo) { auto gotIt = gotMap.find(fixupVMAddr); if ( gotIt != gotMap.end() ) { const ChunkPlusOffset gotPlusOffset = gotIt->second; DyldCachePatchableGOTLocation patchLoc(gotPlusOffset.first, gotPlusOffset.second, patchTablePMD, patchTableAddend, bindTarget.isWeakImport); auto& gotUses = gotInfo[bindOrdinal]; DylibOffset dylibOffset = { bindTarget.inputImage.targetDylib, finalTargetVMOffset }; gotUses.emplace_back((PatchInfo::GOTInfo){ patchLoc, dylibOffset }); return true; } return false; }; if ( checkGOTs(coalescedGOTs, dylibPatchInfo.bindGOTUses) ) { // normal GOT } else if ( checkGOTs(coalescedAuthGOTs, dylibPatchInfo.bindAuthGOTUses) ) { // auth GOT } else if ( checkGOTs(coalescedAuthPtrs, dylibPatchInfo.bindAuthPtrUses) ) { // auth ptr } else { // Location wasn't coalesced. So add to the regular list of uses InputDylibVMOffset fixupVMOffset = fixupVMAddr - this->inputLoadAddress; DyldCachePatchableLocation patchLoc = { fixupVMOffset, patchTablePMD, patchTableAddend, bindTarget.isWeakImport }; dylibPatchInfo.bindUses[bindOrdinal].push_back(patchLoc); } break; } case BindTarget::Kind::cacheImage: { diag.error("Input binds should not have been converted to cache binds in %s: %d", this->installName.data(), bindOrdinal); return; } } } void CacheDylib::calcuatePatchInfo(Diagnostics& diag, const BuilderConfig& config, Timer::AggregateTimer& timer, PatchInfo& dylibPatchInfo) { Timer::AggregateTimer::Scope timedScope(timer, "dylib patch info calculation time"); __block CoalescedGOTsMap coalescedGOTs = optimizedSections.gots.getCoalescedGOTsMap(); __block CoalescedGOTsMap coalescedAuthGOTs = optimizedSections.auth_gots.getCoalescedGOTsMap(); __block CoalescedGOTsMap coalescedAuthPtrs = optimizedSections.auth_ptrs.getCoalescedGOTsMap(); // Track which locations this dylib uses in other dylibs. One per bindTarget dylibPatchInfo.bindUses.resize(this->bindTargets.size()); dylibPatchInfo.bindGOTUses.resize(this->bindTargets.size()); dylibPatchInfo.bindAuthGOTUses.resize(this->bindTargets.size()); dylibPatchInfo.bindAuthPtrUses.resize(this->bindTargets.size()); if ( !needsPatchTable ) return; auto handleFixup = ^(InputDylibVMAddress fixupVMAddr, int64_t embeddedAddend, int bindOrdinal, dyld3::MachOFile::PointerMetaData pmd, uint32_t segmentIndex, bool& stopSegment) { if ( bindOrdinal >= this->bindTargets.size() ) { diag.error("out of range bind ordinal %d (max %lu)", bindOrdinal, this->bindTargets.size()); stopSegment = true; return; } const BindTarget& targetInTable = this->bindTargets[bindOrdinal]; uint64_t addend = targetInTable.addend + embeddedAddend; this->calculateBindLocationPatchInfo(diag, config, targetInTable, addend, bindOrdinal, segmentIndex, fixupVMAddr, pmd, coalescedGOTs, coalescedAuthGOTs, coalescedAuthPtrs, dylibPatchInfo); }; this->inputMF->withFileLayout(diag, ^(const mach_o::Layout& layout) { mach_o::Fixups fixups(layout); if ( this->inputMF->hasChainedFixups() ) { fixups.withChainStarts(diag, ^(const dyld_chained_starts_in_image* starts) { fixups.forEachFixupChainSegment(diag, starts, ^(const dyld_chained_starts_in_segment *segInfo, uint32_t segIndex, bool &stopSegment) { InputDylibVMAddress segmentVMAddr = this->segments[segIndex].inputVMAddress; fixups.forEachFixupInSegmentChains(diag, segInfo, segIndex, true, ^(dyld3::MachOFile::ChainedFixupPointerOnDisk *fixupLocation, uint64_t fixupSegmentOffset, bool &stopChain) { uint32_t bindOrdinal = 0; int64_t embeddedAddend = 0; if ( fixupLocation->isBind(segInfo->pointer_format, bindOrdinal, embeddedAddend) ) { MachOFile::PointerMetaData pmd(fixupLocation, segInfo->pointer_format); handleFixup(segmentVMAddr + VMOffset(fixupSegmentOffset), embeddedAddend, bindOrdinal, pmd, segIndex, stopChain); } }); }); }); } else if ( this->inputMF->hasOpcodeFixups() ) { const dyld3::MachOFile::PointerMetaData pmd; fixups.forEachBindLocation_Opcodes(diag, ^(uint64_t runtimeOffset, uint32_t segmentIndex, unsigned int targetIndex, bool& stop) { InputDylibVMAddress fixupVMAddr = this->inputLoadAddress + VMOffset(runtimeOffset); handleFixup(fixupVMAddr, 0, targetIndex, pmd, segmentIndex, stop); }, ^(uint64_t runtimeOffset, uint32_t segmentIndex, unsigned int overrideBindTargetIndex, bool& stop) { assert(this->weakBindTargetsStartIndex.has_value()); InputDylibVMAddress fixupVMAddr = this->inputLoadAddress + VMOffset(runtimeOffset); handleFixup(fixupVMAddr, 0, this->weakBindTargetsStartIndex.value() + overrideBindTargetIndex, pmd, segmentIndex, stop); }); } else { // Cache dylibs shouldn't use old style fixups. } }); } void CacheDylib::bind(Diagnostics& diag, const BuilderConfig& config, Timer::AggregateTimer& timer, PatchInfo& dylibPatchInfo, FunctionVariantsOptimizer& functionVariantsOptimizer) { Timer::AggregateTimer::Scope timedScope(timer, "dylib bind time"); // As we are running in parallel, addresses in other dylibs may not have been shifted yet. We may also // race looking at the export trie in a target dylib, while it is being shifted by AdjustDylibSegments. // Given that, we'll look at our own cache dylib, but everyone elses input dylib, as those won't mutate CoalescedGOTsMap coalescedGOTs = optimizedSections.gots.getCoalescedGOTsMap(); CoalescedGOTsMap coalescedAuthGOTs = optimizedSections.auth_gots.getCoalescedGOTsMap(); CoalescedGOTsMap coalescedAuthPtrs = optimizedSections.auth_ptrs.getCoalescedGOTsMap(); if ( this->inputMF->hasChainedFixups() ) bindWithChainedFixups(diag, config, coalescedGOTs, coalescedAuthGOTs, coalescedAuthPtrs, dylibPatchInfo, functionVariantsOptimizer); else if ( this->inputMF->hasOpcodeFixups() ) { bindWithOpcodeFixups(diag, config, coalescedGOTs, coalescedAuthGOTs, coalescedAuthPtrs, dylibPatchInfo, functionVariantsOptimizer); } else { // Cache dylibs shouldn't use old style fixups. } // Now that we've bound this dylib, we can tell the ASLRTrackers on the segments to clear // any out of band maps for ( DylibSegmentChunk& segment : this->segments ) segment.tracker.clearRebaseTargetsMaps(); } void CacheDylib::updateObjCSelectorReferences(Diagnostics& diag, const BuilderConfig& config, Timer::AggregateTimer& timer, ObjCSelectorOptimizer& objcSelectorOptimizer) { if ( !this->inputHdr->hasObjC() ) return; Timer::AggregateTimer::Scope timedScope(timer, "dylib updateObjCSelectorReferences time"); __block objc_visitor::Visitor objcVisitor = this->makeCacheObjCVisitor(config, objcSelectorOptimizer.selectorStringsChunk, nullptr, nullptr); // Update every selector reference to point to the canonical selectors objcVisitor.forEachSelectorReference(^(metadata_visitor::ResolvedValue& selRefValue) { const char* selString = (const char*)objcVisitor.resolveRebase(selRefValue).value(); // Find the selector in the map auto it = objcSelectorOptimizer.selectorsMap.find(selString); assert(it != objcSelectorOptimizer.selectorsMap.end()); VMOffset newSelBufferOffset = it->second; assert(newSelBufferOffset.rawValue() < objcSelectorOptimizer.selectorStringsChunk->cacheVMSize.rawValue()); CacheVMAddress newSelCacheVMAddress = objcSelectorOptimizer.selectorStringsChunk->cacheVMAddress + newSelBufferOffset; objcVisitor.updateTargetVMAddress(selRefValue, newSelCacheVMAddress); }); objcVisitor.forEachMethodList(^(objc_visitor::MethodList& objcMethodList, std::optional<metadata_visitor::ResolvedValue> extendedMethodTypes) { // Set both relative and pointer based lists to uniqued. They will be after this method is done objcMethodList.setIsUniqued(); // Skip uniqing relative method lists. We know for sure they point to __objc_selrefs which were handled above if ( objcMethodList.usesRelativeOffsets() ) return; uint32_t numMethods = objcMethodList.numMethods(); for ( uint32_t i = 0; i != numMethods; ++i ) { objc_visitor::Method objcMethod = objcMethodList.getMethod(objcVisitor, i); // Get the selector reference which is implicit in the name field of the Method. metadata_visitor::ResolvedValue nameRef = objcMethod.getNameField(objcVisitor); const char* selString = (const char*)objcVisitor.resolveRebase(nameRef).value(); // Find the selector in the map auto it = objcSelectorOptimizer.selectorsMap.find(selString); assert(it != objcSelectorOptimizer.selectorsMap.end()); VMOffset newSelBufferOffset = it->second; CacheVMAddress newSelCacheVMAddress = objcSelectorOptimizer.selectorStringsChunk->cacheVMAddress + newSelBufferOffset; objcVisitor.updateTargetVMAddress(nameRef, newSelCacheVMAddress); } }); } static void sortObjCRelativeMethodList(const BuilderConfig& config, const objc_visitor::Visitor& objcVisitor, const objc_visitor::MethodList& objcMethodList, std::optional<metadata_visitor::ResolvedValue> extendedMethodTypesBase) { uint32_t numMethods = objcMethodList.numMethods(); // Is this possible? It simplifies code below, so check it anyway if ( numMethods == 0 ) return; // Don't sort if we have a single method if ( numMethods == 1 ) return; // At this point we assume we are using offsets directly to selectors. This // is so that the Method struct can also use direct offsets and not track the // SEL reference VMAddrs assert(objcMethodList.usesOffsetsFromSelectorBuffer()); // We can't sort relative method lists. So turn them in to Pointer based lists and sort those instead struct Method { VMAddress selStringVMAddr; VMAddress typeStringVMAddr; std::optional<VMAddress> impVMAddr; VMAddress extendedMethodTypeVMAddr; }; const uint32_t pointerSize = objcVisitor.mf()->pointerSize(); Method methods[numMethods]; for ( uint32_t i = 0; i != numMethods; ++i ) { objc_visitor::Method objcMethod = objcMethodList.getMethod(objcVisitor, i); methods[i].selStringVMAddr = objcMethod.getNameVMAddr(objcVisitor); methods[i].typeStringVMAddr = objcMethod.getTypesVMAddr(objcVisitor); methods[i].impVMAddr = objcMethod.getIMPVMAddr(objcVisitor); if ( extendedMethodTypesBase.has_value() ) { const uint8_t* methodTypesBase = (uint8_t*)extendedMethodTypesBase->value(); methodTypesBase += (pointerSize * i); metadata_visitor::ResolvedValue methodType(extendedMethodTypesBase.value(), methodTypesBase); // Get the VMAddr pointed to by this method type VMAddress targetVMAddr = objcVisitor.resolveRebase(methodType).vmAddress(); methods[i].extendedMethodTypeVMAddr = targetVMAddr; } } // Sort by selector address (not contents) auto sorter = [](const Method& a, const Method& b) { return a.selStringVMAddr < b.selStringVMAddr; }; // Stable sort because method lists can contain duplicates when categories have been attached. std::stable_sort(&methods[0], &methods[numMethods], sorter); // Replace the relative methods with the sorted ones for ( uint32_t i = 0; i != numMethods; ++i ) { objc_visitor::Method objcMethod = objcMethodList.getMethod(objcVisitor, i); objcMethod.setName(objcVisitor, methods[i].selStringVMAddr); objcMethod.setTypes(objcVisitor, methods[i].typeStringVMAddr); objcMethod.setIMP(objcVisitor, methods[i].impVMAddr); if ( extendedMethodTypesBase.has_value() ) { const uint8_t* methodTypesBase = (uint8_t*)extendedMethodTypesBase->value(); methodTypesBase += (pointerSize * i); metadata_visitor::ResolvedValue methodType(extendedMethodTypesBase.value(), methodTypesBase); // Get the VMAddr pointed to by this method type VMAddress targetVMAddr = methods[i].extendedMethodTypeVMAddr; objcVisitor.updateTargetVMAddress(methodType, CacheVMAddress(targetVMAddr.rawValue())); } } } static void sortObjCPointerMethodList(const BuilderConfig& config, const objc_visitor::Visitor& objcVisitor, const objc_visitor::MethodList& objcMethodList, std::optional<metadata_visitor::ResolvedValue> extendedMethodTypesBase) { uint32_t numMethods = objcMethodList.numMethods(); // Is this possible? It simplifies code below, so check it anyway if ( numMethods == 0 ) return; // Don't sort if we have a single method if ( numMethods == 1 ) return; // It's painful to sort both methods and method types at the same time, so // put everything in to a temporary array to sort struct Method { VMAddress selStringVMAddr; VMAddress typeStringVMAddr; std::optional<VMAddress> impVMAddr; VMAddress extendedMethodTypeVMAddr; }; const uint32_t pointerSize = objcVisitor.mf()->pointerSize(); Method methods[numMethods]; for ( uint32_t i = 0; i != numMethods; ++i ) { objc_visitor::Method objcMethod = objcMethodList.getMethod(objcVisitor, i); methods[i].selStringVMAddr = objcMethod.getNameVMAddr(objcVisitor); methods[i].typeStringVMAddr = objcMethod.getTypesVMAddr(objcVisitor); methods[i].impVMAddr = objcMethod.getIMPVMAddr(objcVisitor); if ( extendedMethodTypesBase.has_value() ) { const uint8_t* methodTypesBase = (uint8_t*)extendedMethodTypesBase->value(); methodTypesBase += (pointerSize * i); metadata_visitor::ResolvedValue methodType(extendedMethodTypesBase.value(), methodTypesBase); // Get the VMAddr pointed to by this method type VMAddress targetVMAddr = objcVisitor.resolveRebase(methodType).vmAddress(); methods[i].extendedMethodTypeVMAddr = targetVMAddr; } } // Sort by selector address (not contents) auto sorter = [](const Method& a, const Method& b) { return a.selStringVMAddr < b.selStringVMAddr; }; // Stable sort because method lists can contain duplicates when categories have been attached. std::stable_sort(&methods[0], &methods[numMethods], sorter); // Replace the methods with the sorted ones for ( uint32_t i = 0; i != numMethods; ++i ) { objc_visitor::Method objcMethod = objcMethodList.getMethod(objcVisitor, i); objcMethod.setName(objcVisitor, methods[i].selStringVMAddr); objcMethod.setTypes(objcVisitor, methods[i].typeStringVMAddr); objcMethod.setIMP(objcVisitor, methods[i].impVMAddr); if ( extendedMethodTypesBase.has_value() ) { const uint8_t* methodTypesBase = (uint8_t*)extendedMethodTypesBase->value(); methodTypesBase += (pointerSize * i); metadata_visitor::ResolvedValue methodType(extendedMethodTypesBase.value(), methodTypesBase); // Get the VMAddr pointed to by this method type VMAddress targetVMAddr = methods[i].extendedMethodTypeVMAddr; objcVisitor.updateTargetVMAddress(methodType, CacheVMAddress(targetVMAddr.rawValue())); } } } void CacheDylib::convertObjCMethodListsToOffsets(Diagnostics& diag, const BuilderConfig& config, Timer::AggregateTimer& timer, const Chunk* selectorStringsChunk) { if ( !this->inputHdr->hasObjC() ) return; Timer::AggregateTimer::Scope timedScope(timer, "dylib convertObjCMethodListsToOffsets time"); __block objc_visitor::Visitor objcVisitor = this->makeCacheObjCVisitor(config, selectorStringsChunk, nullptr, nullptr); // protocols can be listed multiple times in the _objc_protolist section, so we'll visit them multiple times here // We don't want to convert the method list twice, so keep track of all seen method lists // FIXME: Remove this once ld removes the duplicates (rdar://133008657) __block std::unordered_set<const void*> seenMethodLists; objcVisitor.forEachMethodList(^(objc_visitor::MethodList& objcMethodList, std::optional<metadata_visitor::ResolvedValue> extendedMethodTypes) { // Skip pointer based method lists if ( !objcMethodList.usesRelativeOffsets() ) return; // Skip method lists we've already converted if ( bool inserted = seenMethodLists.insert(objcMethodList.getLocation()).second; !inserted ) return; uint32_t numMethods = objcMethodList.numMethods(); for ( uint32_t i = 0; i != numMethods; ++i ) { objc_visitor::Method objcMethod = objcMethodList.getMethod(objcVisitor, i); const char* selString = objcMethod.getName(objcVisitor); uint64_t nameOffset = (uint64_t)selString - (uint64_t)selectorStringsChunk->subCacheBuffer; assert((uint32_t)nameOffset == nameOffset); objcMethod.convertNameToOffset(objcVisitor, (uint32_t)nameOffset); } objcMethodList.setUsesOffsetsFromSelectorBuffer(); }); } void CacheDylib::sortObjCMethodLists(Diagnostics& diag, const BuilderConfig& config, Timer::AggregateTimer& timer, const Chunk* selectorStringsChunk) { if ( !this->inputHdr->hasObjC() ) return; Timer::AggregateTimer::Scope timedScope(timer, "dylib sortObjCMethodLists time"); __block objc_visitor::Visitor objcVisitor = this->makeCacheObjCVisitor(config, selectorStringsChunk, nullptr, nullptr); objcVisitor.forEachMethodList(^(objc_visitor::MethodList& objcMethodList, std::optional<metadata_visitor::ResolvedValue> extendedMethodTypes) { if ( objcMethodList.usesRelativeOffsets() ) sortObjCRelativeMethodList(config, objcVisitor, objcMethodList, extendedMethodTypes); else sortObjCPointerMethodList(config, objcVisitor, objcMethodList, extendedMethodTypes); objcMethodList.setIsSorted(); }); } void CacheDylib::forEachReferenceToASelRef(Diagnostics &diags, void (^handler)(uint64_t kind, uint32_t* instrPtr, uint64_t selRefVMAddr)) const { const uint8_t* infoStart = this->inputDylibSplitSegStart; const uint8_t* infoEnd = this->inputDylibSplitSegEnd;; if ( *infoStart++ != DYLD_CACHE_ADJ_V2_FORMAT ) { // Must be split seg v1 return; } __block uint32_t textSectionIndex = ~0U; __block const uint8_t* textSectionContent = nullptr; __block uint32_t selRefSectionIndex = ~0U; __block uint64_t selRefSectionVMAddr = 0; // The mach_header is section 0 __block uint32_t sectionIndex = 1; this->cacheHdr->forEachSection(^(const Header::SegmentInfo &segInfo, const Header::SectionInfo §Info, bool &stop) { if ( (sectInfo.segmentName == "__TEXT" ) && (sectInfo.sectionName == "__text") ) { textSectionIndex = sectionIndex; VMOffset sectionOffsetInSegment(sectInfo.address - segInfo.vmaddr); textSectionContent = this->segments[sectInfo.segIndex].subCacheBuffer; textSectionContent += sectionOffsetInSegment.rawValue(); } if ( sectInfo.segmentName.starts_with("__DATA") && (sectInfo.sectionName == "__objc_selrefs") ) { selRefSectionIndex = sectionIndex; selRefSectionVMAddr = sectInfo.address; } ++sectionIndex; }); if ( (textSectionIndex == ~0U) || (selRefSectionIndex == ~0U) ) return; // Whole :== <count> FromToSection+ // FromToSection :== <from-sect-index> <to-sect-index> <count> ToOffset+ // ToOffset :== <to-sect-offset-delta> <count> FromOffset+ // FromOffset :== <kind> <count> <from-sect-offset-delta> const uint8_t* p = infoStart; uint64_t sectionCount = dyld3::MachOFile::read_uleb128(diags, p, infoEnd); for (uint64_t i=0; i < sectionCount; ++i) { uint64_t fromSectionIndex = dyld3::MachOFile::read_uleb128(diags, p, infoEnd); uint64_t toSectionIndex = dyld3::MachOFile::read_uleb128(diags, p, infoEnd); uint64_t toOffsetCount = dyld3::MachOFile::read_uleb128(diags, p, infoEnd); uint64_t toSectionOffset = 0; for (uint64_t j=0; j < toOffsetCount; ++j) { uint64_t toSectionDelta = dyld3::MachOFile::read_uleb128(diags, p, infoEnd); uint64_t fromOffsetCount = dyld3::MachOFile::read_uleb128(diags, p, infoEnd); toSectionOffset += toSectionDelta; for (uint64_t k=0; k < fromOffsetCount; ++k) { uint64_t kind = dyld3::MachOFile::read_uleb128(diags, p, infoEnd); if ( kind > 13 ) { diags.error("bad kind (%llu) value in %s\n", kind, installName.data()); } uint64_t fromSectDeltaCount = dyld3::MachOFile::read_uleb128(diags, p, infoEnd); uint64_t fromSectionOffset = 0; for (uint64_t l=0; l < fromSectDeltaCount; ++l) { uint64_t delta = dyld3::MachOFile::read_uleb128(diags, p, infoEnd); fromSectionOffset += delta; if ( (fromSectionIndex == textSectionIndex) && (toSectionIndex == selRefSectionIndex) ) { uint32_t* instrPtr = (uint32_t*)(textSectionContent + fromSectionOffset); uint64_t targetVMAddr = selRefSectionVMAddr + toSectionOffset; handler(kind, instrPtr, targetVMAddr); } } } } } } void CacheDylib::optimizeLoadsFromConstants(const BuilderConfig& config, Timer::AggregateTimer& timer, const ObjCStringsChunk* selectorStringsChunk) { const bool logSelectors = config.log.printDebugCacheLayout; Timer::AggregateTimer::Scope timedScope(timer, "dylib optimizeLoadsFromConstants time"); if ( !this->cacheHdr->is64() ) return; __block const uint8_t* textSectionContent = nullptr; __block CacheVMAddress textSectionVMAddr; __block const uint8_t* selRefSectionContent = nullptr; __block CacheVMAddress selRefSectionVMAddr; this->cacheHdr->forEachSection(^(const Header::SegmentInfo &segInfo, const Header::SectionInfo §Info, bool &stop) { VMOffset sectionOffsetInSegment(sectInfo.address - segInfo.vmaddr); if ( ( sectInfo.segmentName == "__TEXT" ) && (sectInfo.sectionName == "__text") ) { textSectionContent = this->segments[sectInfo.segIndex].subCacheBuffer; textSectionContent += sectionOffsetInSegment.rawValue(); textSectionVMAddr = CacheVMAddress(sectInfo.address); } if ( sectInfo.segmentName.starts_with("__DATA") && (sectInfo.sectionName == "__objc_selrefs") ) { selRefSectionContent = this->segments[sectInfo.segIndex].subCacheBuffer; selRefSectionContent += sectionOffsetInSegment.rawValue(); selRefSectionVMAddr = CacheVMAddress(sectInfo.address); } }); __block std::unordered_map<uint64_t, std::set<void*>> lohTracker; Diagnostics diag; this->forEachReferenceToASelRef(diag, ^(uint64_t kind, uint32_t *instrPtr, uint64_t selRefVMAddr) { if ( (kind == DYLD_CACHE_ADJ_V2_ARM64_ADRP) || (kind == DYLD_CACHE_ADJ_V2_ARM64_OFF12) ) { lohTracker[selRefVMAddr].insert(instrPtr); } }); if ( lohTracker.empty() ) return; uint64_t lohADRPCount = 0; uint64_t lohLDRCount = 0; CacheVMAddress selectorStringsStart = selectorStringsChunk->cacheVMAddress; CacheVMAddress selectorStringsEnd = selectorStringsStart + selectorStringsChunk->cacheVMSize; for (auto& targetAndInstructions : lohTracker) { CacheVMAddress selRefVMAddr(targetAndInstructions.first); std::set<void*>& instructions = targetAndInstructions.second; VMOffset selRefSectionOffset = selRefVMAddr - selRefSectionVMAddr; const void* selRefContent = selRefSectionContent + selRefSectionOffset.rawValue(); // Load the selector and make sure its in the selector strings chunk CacheVMAddress selStringVMAddr = Fixup::Cache64::getCacheVMAddressFromLocation(config.layout.cacheBaseAddress, selRefContent); const char* selectorString = nullptr; if ( (selStringVMAddr >= selectorStringsStart) && (selStringVMAddr < selectorStringsEnd) ) { VMOffset stringOffset = selStringVMAddr - selectorStringsStart; selectorString = (const char*)selectorStringsChunk->subCacheBuffer + stringOffset.rawValue(); } else { // This selRef doesn't point to the strings chunk, so skip it instructions.clear(); continue; } // We do 2 passes over the instructions. The first to validate them and the second // to actually update them. for (unsigned pass = 0; pass != 2; ++pass) { uint32_t adrpCount = 0; uint32_t ldrCount = 0; for (void* instructionAddress : instructions) { uint32_t& instruction = *(uint32_t*)instructionAddress; VMOffset instructionSectionOffset((uint64_t)instructionAddress - (uint64_t)textSectionContent); CacheVMAddress instructionVMAddr = textSectionVMAddr + instructionSectionOffset; if ( (instruction & 0x9F000000) == 0x90000000 ) { // ADRP int64_t pageDistance = ((selStringVMAddr.rawValue() & ~0xFFF) - (instructionVMAddr.rawValue() & ~0xFFF)); int64_t newPage21 = pageDistance >> 12; if (pass == 0) { if ( (newPage21 > 2097151) || (newPage21 < -2097151) ) { if (logSelectors) fprintf(stderr, "Out of bounds ADRP selector reference target\n"); instructions.clear(); break; } ++adrpCount; } if (pass == 1) { instruction = (instruction & 0x9F00001F) | ((newPage21 << 29) & 0x60000000) | ((newPage21 << 3) & 0x00FFFFE0); ++lohADRPCount; } continue; } if ( (instruction & 0x3B000000) == 0x39000000 ) { // LDR/STR. STR shouldn't be possible as this is a selref! if (pass == 0) { if ( (instruction & 0xC0C00000) != 0xC0400000 ) { // Not a load, or dest reg isn't xN, or uses sign extension if (logSelectors) fprintf(stderr, "Bad LDR for selector reference optimisation\n"); instructions.clear(); break; } if ( (instruction & 0x04000000) != 0 ) { // Loading a float if (logSelectors) fprintf(stderr, "Bad LDR for selector reference optimisation\n"); instructions.clear(); break; } ++ldrCount; } if (pass == 1) { uint32_t ldrDestReg = (instruction & 0x1F); uint32_t ldrBaseReg = ((instruction >> 5) & 0x1F); // Convert the LDR to an ADD instruction = 0x91000000; instruction |= ldrDestReg; instruction |= ldrBaseReg << 5; instruction |= (selStringVMAddr.rawValue() & 0xFFF) << 10; ++lohLDRCount; } continue; } if ( (instruction & 0xFFC00000) == 0x91000000 ) { // ADD imm12 // We don't support ADDs. if (logSelectors) fprintf(stderr, "Bad ADD for selector reference optimisation\n"); instructions.clear(); break; } if (logSelectors) fprintf(stderr, "Unknown instruction for selref optimisation\n"); instructions.clear(); break; } if (pass == 0) { // If we didn't see at least one ADRP/LDR in pass one then don't optimize this location if ((adrpCount == 0) || (ldrCount == 0)) { instructions.clear(); break; } } } } if ( logSelectors ) { config.log.log(" Optimized %lld ADRP LOHs\n", lohADRPCount); config.log.log(" Optimized %lld LDR LOHs\n", lohLDRCount); } } Error CacheDylib::setObjCImpCachesPointers(const BuilderConfig& config, const ObjCIMPCachesOptimizer& objcIMPCachesOptimizer, const ObjCStringsChunk* selectorStringsChunk) { if ( this->installName != "/usr/lib/libobjc.A.dylib" ) return Error(); Diagnostics diag; // New libobjc's have a magic symbol for the offsets std::string_view symbolName = objcIMPCachesOptimizer.sharedCacheOffsetsSymbolName; std::optional<BindTargetAndName> bindTargetAndName; bindTargetAndName = this->hasExportedSymbol(diag, symbolName.data(), SearchMode::onlySelf); if ( diag.hasError() ) return Error("Couldn't build IMP caches because: %s", diag.errorMessageCStr()); if ( !bindTargetAndName ) return Error("Couldn't build IMP caches because: couldn't find imp caches symbol"); BindTarget& bindTarget = bindTargetAndName->first; if ( bindTarget.kind != BindTarget::Kind::inputImage ) return Error("Couldn't build IMP caches because: symbol is wrong kind"); BindTarget::InputImage bindInputImage = bindTarget.inputImage; InputDylibVMAddress targetInputVMAddr = bindInputImage.targetDylib->inputLoadAddress + bindInputImage.targetRuntimeOffset; CacheVMAddress targetCacheVMAddr = bindInputImage.targetDylib->adjustor->adjustVMAddr(targetInputVMAddr); // Find the segment for the content for ( DylibSegmentChunk& segment : this->segments ) { if ( targetCacheVMAddr < segment.cacheVMAddress ) continue; if ( targetCacheVMAddr >= (segment.cacheVMAddress + segment.cacheVMSize) ) continue; VMOffset offsetInSegment = targetCacheVMAddr - segment.cacheVMAddress; uint8_t* content = segment.subCacheBuffer + offsetInSegment.rawValue(); // Section looks like // struct objc_opt_imp_caches_pointerlist_tt { // T selectorStringVMAddrStart; // T selectorStringVMAddrEnd; // T inlinedSelectorsVMAddrStart; // T inlinedSelectorsVMAddrEnd; // }; CacheVMAddress selectorStringStartVMAddr = selectorStringsChunk->cacheVMAddress; CacheVMAddress selectorStringEndVMAddr = selectorStringStartVMAddr + selectorStringsChunk->cacheVMSize; if ( config.layout.is64 ) { uint8_t* selectorStringStart = content; uint8_t* selectorStringEnd = content + 8; dyld3::MachOFile::PointerMetaData pmd; Fixup::Cache64::setLocation(config.layout.cacheBaseAddress, selectorStringStart, selectorStringStartVMAddr, pmd.high8, pmd.diversity, pmd.usesAddrDiversity, pmd.key, pmd.authenticated); Fixup::Cache64::setLocation(config.layout.cacheBaseAddress, selectorStringEnd, selectorStringEndVMAddr, pmd.high8, pmd.diversity, pmd.usesAddrDiversity, pmd.key, pmd.authenticated); segment.tracker.add(selectorStringStart); segment.tracker.add(selectorStringEnd); } else { uint8_t* selectorStringStart = content; uint8_t* selectorStringEnd = content + 4; dyld3::MachOFile::PointerMetaData pmd; Fixup::Cache32::setLocation(config.layout.cacheBaseAddress, selectorStringStart, selectorStringStartVMAddr); Fixup::Cache32::setLocation(config.layout.cacheBaseAddress, selectorStringStart, selectorStringEndVMAddr); segment.tracker.add(selectorStringStart); segment.tracker.add(selectorStringEnd); } return Error(); } return Error("Couldn't build IMP caches because: couldn't find section for imp caches symbol"); } Error CacheDylib::emitObjCIMPCaches(const BuilderConfig& config, Timer::AggregateTimer& timer, const ObjCIMPCachesOptimizer& objcIMPCachesOptimizer, const ObjCStringsChunk* selectorStringsChunk) { if ( !objcIMPCachesOptimizer.builder ) return Error(); const bool log = config.log.printDebugIMPCaches; Timer::AggregateTimer::Scope timedScope(timer, "emitObjCIMPCaches time"); const ObjCIMPCachesOptimizer::IMPCacheMap& dylibIMPCaches = objcIMPCachesOptimizer.dylibIMPCaches[this->cacheIndex]; // libobjc needs to know about some offsets, even if it didn't get IMP caches itself Error pointersErr = this->setObjCImpCachesPointers(config, objcIMPCachesOptimizer, selectorStringsChunk); if ( pointersErr.hasError() ) return pointersErr; // Skip dylibs without chained fixups. This simplifies binding superclasses across dylibs if ( !this->inputMF->hasChainedFixupsLoadCommand() ) return Error(); __block objc_visitor::Visitor objcVisitor = this->makeCacheObjCVisitor(config, nullptr, nullptr, nullptr); // Walk the classes in this dylib, and see if any have an IMP cache objcVisitor.forEachClassAndMetaClass(^(objc_visitor::Class& objcClass, bool& stopClass) { const ObjCIMPCachesOptimizer::ClassKey classKey = { objcClass.getName(objcVisitor), objcClass.isMetaClass }; auto it = dylibIMPCaches.find(classKey); if ( it == dylibIMPCaches.end() ) { // No IMP cache for this dylib return; } // Get the cache we are going to emit const imp_caches::IMPCache& impCache = it->second.first; // Get the offset in the IMPCache buffer for this IMP cache VMOffset impCacheOffset = it->second.second; // Skip dylibs where the "vtable" address is set if ( objcClass.getMethodCachePropertiesVMAddr(objcVisitor).has_value() ) return; MachOFile::PointerMetaData PMD; if ( config.layout.hasAuthRegion && (objcIMPCachesOptimizer.libobjcImpCachesVersion >= 4) ) { PMD.diversity = 0x9cff; // hash of "originalPreoptCache" PMD.high8 = 0; PMD.authenticated = 1; PMD.key = 2; // DA PMD.usesAddrDiversity = 1; } // Set the "vtable" to point to the cache CacheVMAddress impCacheVMAddr = objcIMPCachesOptimizer.impCachesChunk->cacheVMAddress + impCacheOffset; objcClass.setMethodCachePropertiesVMAddr(objcVisitor, VMAddress(impCacheVMAddr.rawValue()), PMD); // Tell the slide info emitter to slide this location metadata_visitor::ResolvedValue vtableField = objcClass.getMethodCachePropertiesField(objcVisitor); this->segments[vtableField.segmentIndex()].tracker.add(vtableField.value()); // TODO: This is where we could check the version if needed. For now we know objc // is new enough for the V2 format. uint8_t* impCachePos = objcIMPCachesOptimizer.impCachesChunk->subCacheBuffer; impCachePos += impCacheOffset.rawValue(); // Convert from VMAddress to CacheVMAddress as the objc visitor uses VMAddress internally CacheVMAddress classVMAddr = CacheVMAddress(objcClass.getVMAddress().rawValue()); ImpCacheHeader_v2* impCacheHeader = (ImpCacheHeader_v2*)impCachePos; VMOffset fallbackOffset; if ( impCache.fallback_class.has_value() ) { auto classIt = objcIMPCachesOptimizer.classMap.find(impCache.fallback_class.value()); assert(classIt != objcIMPCachesOptimizer.classMap.end()); const ObjCIMPCachesOptimizer::InputDylibLocation& inputDylibClass = classIt->second; CacheVMAddress superclassVMAddr = inputDylibClass.first->adjustor->adjustVMAddr(inputDylibClass.second); fallbackOffset = superclassVMAddr - classVMAddr; } else { // The default fallback class is the superclass VMAddress superclassVMAddr(0ULL); std::optional<VMAddress> optionalSuperclassVMAddr = objcClass.getSuperclassVMAddr(objcVisitor); if ( optionalSuperclassVMAddr.has_value() ) superclassVMAddr = optionalSuperclassVMAddr.value(); fallbackOffset = superclassVMAddr - VMAddress(classVMAddr.rawValue()); } impCacheHeader->fallback_class_offset = fallbackOffset.rawValue(); impCacheHeader->cache_shift = impCache.cache_shift; impCacheHeader->cache_mask = impCache.cache_mask; impCacheHeader->occupied = impCache.occupied; impCacheHeader->has_inlines = impCache.has_inlines; impCacheHeader->padding = impCache.padding; impCacheHeader->unused = impCache.unused; impCacheHeader->bit_one = impCache.bit_one; // Emit the buckets uint8_t* firstBucketPos = impCachePos + sizeof(*impCacheHeader); ImpCacheEntry_v2* currentBucket = (ImpCacheEntry_v2*)firstBucketPos; for ( const imp_caches::Bucket& bucket : impCache.buckets ) { if ( bucket.isEmptyBucket ) { currentBucket->selOffset = 0x3FFFFFF; currentBucket->impOffset = 0; } else { imp_caches::BucketMethod bucketMethod = { .className = bucket.className, .methodName = bucket.methodName, .isInstanceMethod = bucket.isInstanceMethod }; const auto& dylibMethodMap = objcIMPCachesOptimizer.methodMap.at(bucket.installName); auto bucketIt = dylibMethodMap.find(bucketMethod); assert(bucketIt != dylibMethodMap.end()); const ObjCIMPCachesOptimizer::InputDylibLocation& bucketInputLocation = bucketIt->second; CacheVMAddress methodVMAddr = bucketInputLocation.first->adjustor->adjustVMAddr(bucketInputLocation.second); VMOffset impVMOffset = classVMAddr - methodVMAddr; int64_t selOffset = (int64_t)bucket.selOffset; int64_t impOffset = (int64_t)impVMOffset.rawValue(); assert(impOffset % 4 == 0); // dest and source should be aligned impOffset >>= 2; // objc assumes the imp offset always has // its two bottom bits set to 0, this lets us have // 4x more reach assert(impOffset < 1ll << 39); assert(-impOffset < 1ll << 39); assert(selOffset < 0x4000000); currentBucket->selOffset = selOffset; currentBucket->impOffset = impOffset; if ( log ) { const uint8_t* selString = selectorStringsChunk->subCacheBuffer + currentBucket->selOffset; uint64_t bucketIndex = currentBucket - (ImpCacheEntry_v2*)firstBucketPos; config.log.log("[IMP Caches] Coder[%lld]: %#08llx (sel: %#08llx, imp %#08llx) %s\n", bucketIndex, methodVMAddr.rawValue(), selOffset, impOffset, (const char*)selString); } } ++currentBucket; } }); return Error(); } // This dylib may have uniqued GOTs. This returns a map from the address of the uniqued GOT // to the target of that GOT. CacheDylib::GOTToTargetMap CacheDylib::getUniquedGOTTargets(const PatchInfo& dylibPatchInfo) const { CacheDylib::GOTToTargetMap gotToTargetMap; for ( UniquedGOTKind sectionKind : { UniquedGOTKind::regular, UniquedGOTKind::authGot, UniquedGOTKind::authPtr } ) { std::span<const std::vector<PatchInfo::GOTInfo>> bindGOTUses; switch ( sectionKind ) { case UniquedGOTKind::regular: bindGOTUses = dylibPatchInfo.bindGOTUses; break; case UniquedGOTKind::authGot: bindGOTUses = dylibPatchInfo.bindAuthGOTUses; break; case UniquedGOTKind::authPtr: bindGOTUses = dylibPatchInfo.bindAuthPtrUses; break; } assert(this->bindTargets.size() == bindGOTUses.size()); for ( uint32_t bindIndex = 0; bindIndex != this->bindTargets.size(); ++bindIndex ) { const BindTarget& bindTarget = this->bindTargets[bindIndex]; // Skip binds with no uses const std::vector<PatchInfo::GOTInfo>& clientUses = bindGOTUses[bindIndex]; if ( clientUses.empty() ) continue; // Skip absolute binds. Perhaps we should track these, but we lost the information to patch them if ( bindTarget.kind == CacheDylib::BindTarget::Kind::absolute ) continue; assert(bindTarget.kind == BindTarget::Kind::cacheImage); const BindTarget::CacheImage& cacheImageTarget = bindTarget.cacheImage; CacheVMAddress bindTargetVMAddr = cacheImageTarget.targetDylib->cacheLoadAddress + cacheImageTarget.targetRuntimeOffset; for ( const PatchInfo::GOTInfo& gotInfo : clientUses ) { CacheVMAddress gotVMAddr = gotInfo.useLocation.clientGOT->cacheVMAddress + gotInfo.useLocation.clientGOTOffset; gotToTargetMap[gotVMAddr] = bindTargetVMAddr; } } } return gotToTargetMap; } CacheDylib::OldToNewStubMap CacheDylib::buildStubMaps(const BuilderConfig& config, const StubOptimizer& stubOptimizer, const PatchInfo& dylibPatchInfo) { __block OldToNewStubMap oldToNewStubMap; __block Diagnostics diag; __block uint32_t stubsLeftInterposable = 0; // Find all the indirect symbol names from the source dylib // Record all the indirect symbols __block std::vector<std::string_view> indirectSymbols; this->inputMF->withFileLayout(diag, ^(const mach_o::Layout& layout) { mach_o::SymbolTable symbols(layout); indirectSymbols.reserve(layout.linkedit.indirectSymbolTable.entryCount); symbols.forEachIndirectSymbol(diag, ^(const char* symbolName, uint32_t symNum) { indirectSymbols.push_back(symbolName); }); }); diag.assertNoError(); GOTToTargetMap uniquedGOTMap = getUniquedGOTTargets(dylibPatchInfo); // GOTs may have been optimized. We'll either end up in a GOT or auth GOT, depending on arch __block metadata_visitor::Visitor visitor = this->makeCacheVisitor(config); // Get the target of the GOT. It might be uniqued so look there too auto getGOTTarget = ^(uint64_t targetLPAddr) { std::optional<VMAddress> targetVMAddr; CacheVMAddress gotCacheVMAddr(targetLPAddr); VMAddress gotVMAddr(targetLPAddr); if ( auto it = uniquedGOTMap.find(gotCacheVMAddr); it != uniquedGOTMap.end() ) { targetVMAddr = VMAddress(it->second.rawValue()); } else { metadata_visitor::ResolvedValue gotValue = visitor.getValueFor(gotVMAddr); targetVMAddr = visitor.resolveOptionalRebaseToVMAddress(gotValue); } return targetVMAddr; }; // Walk all the stubs in the stubs sections this->cacheHdr->forEachSection(^(const Header::SegmentInfo &segInfo, const Header::SectionInfo §Info, bool &stop) { unsigned sectionType = (sectInfo.flags & SECTION_TYPE); if ( sectionType != S_SYMBOL_STUBS ) return; // We can only optimize certain stubs sections, depending on the arch if ( sectInfo.sectionName != this->developmentStubs.sectionName ) return; if ( sectInfo.segmentName != this->developmentStubs.segmentName ) return; // reserved1/reserved2 tell us how large stubs are, and our offset in to the symbol table const uint64_t indirectTableOffset = sectInfo.reserved1; const uint64_t stubsSize = sectInfo.reserved2; const uint64_t stubsCount = sectInfo.size / stubsSize; CacheVMAddress stubsSectionBaseAddress(sectInfo.address); // Work out where the stub buffer is in the cache const DylibSegmentChunk& segment = this->segments[segInfo.segmentIndex]; CacheVMAddress segmentBaseAddress = segment.cacheVMAddress; VMOffset sectionOffsetInSegment = stubsSectionBaseAddress - segmentBaseAddress; const uint8_t* sectionBuffer = segment.subCacheBuffer + sectionOffsetInSegment.rawValue(); for ( uint64_t stubIndex = 0; stubIndex != stubsCount; ++stubIndex ) { uint64_t stubOffset = stubsSize * stubIndex; CacheVMAddress oldStubVMAddr = stubsSectionBaseAddress + CacheVMSize(stubOffset); CacheVMAddress newStubVMAddr = this->developmentStubs.cacheVMAddress + VMOffset(stubOffset); const uint8_t* stubInstrs = sectionBuffer + stubOffset; uint64_t symbolIndex = indirectTableOffset + stubIndex; if ( symbolIndex >= indirectSymbolTable.size() ) { diag.warning("Symbol index (%lld) exceeds length of symbol table (%lld)", symbolIndex, (uint64_t)indirectSymbolTable.size()); continue; } std::string_view symName = indirectSymbols[symbolIndex]; if ( stubOptimizer.neverStubEliminate.count(symName) ) { stubsLeftInterposable++; continue; } if ( this->cacheHdr->isArch("arm64") ) { uint64_t targetLPAddr = StubOptimizer::gotAddrFromArm64Stub(diag, this->installName, stubInstrs, oldStubVMAddr.rawValue()); if ( targetLPAddr == 0 ) continue; std::optional<VMAddress> gotTargetVMAddr = getGOTTarget(targetLPAddr); if ( !gotTargetVMAddr.has_value() ) continue; // Track the stub for later oldToNewStubMap[oldStubVMAddr] = newStubVMAddr; // Emit this stub in to the stub islands for this dylib { // Dev stub uint8_t* newStubBuffer = developmentStubs.subCacheBuffer + stubOffset; StubOptimizer::generateArm64StubToGOT(newStubBuffer, newStubVMAddr.rawValue(), targetLPAddr); } { // Customer stub uint8_t* newStubBuffer = customerStubs.subCacheBuffer + stubOffset; StubOptimizer::generateArm64StubTo(newStubBuffer, newStubVMAddr.rawValue(), targetLPAddr, gotTargetVMAddr->rawValue()); } } else if ( this->cacheHdr->isArch("arm64e") ) { uint64_t targetLPAddr = StubOptimizer::gotAddrFromArm64eStub(diag, this->installName, stubInstrs, oldStubVMAddr.rawValue()); if ( targetLPAddr == 0 ) continue; std::optional<VMAddress> gotTargetVMAddr = getGOTTarget(targetLPAddr); if ( !gotTargetVMAddr.has_value() ) continue; // Track the stub for later oldToNewStubMap[oldStubVMAddr] = newStubVMAddr; // Emit this stub in to the stub islands for this dylib { // Dev stub uint8_t* newStubBuffer = developmentStubs.subCacheBuffer + stubOffset; StubOptimizer::generateArm64eStubToGOT(newStubBuffer, newStubVMAddr.rawValue(), targetLPAddr); } { // Customer stub uint8_t* newStubBuffer = customerStubs.subCacheBuffer + stubOffset; StubOptimizer::generateArm64eStubTo(newStubBuffer, newStubVMAddr.rawValue(), targetLPAddr, gotTargetVMAddr->rawValue()); } } else if ( this->cacheHdr->isArch("arm64_32") ) { uint64_t targetLPAddr = StubOptimizer::gotAddrFromArm64_32Stub(diag, this->installName, stubInstrs, oldStubVMAddr.rawValue()); if ( targetLPAddr == 0 ) continue; std::optional<VMAddress> gotTargetVMAddr = getGOTTarget(targetLPAddr); if ( !gotTargetVMAddr.has_value() ) continue; // Track the stub for later oldToNewStubMap[oldStubVMAddr] = newStubVMAddr; // Emit this stub in to the stub islands for this dylib { // Dev stub uint8_t* newStubBuffer = developmentStubs.subCacheBuffer + stubOffset; StubOptimizer::generateArm64_32StubToGOT(newStubBuffer, newStubVMAddr.rawValue(), targetLPAddr); } { // Customer stub uint8_t* newStubBuffer = customerStubs.subCacheBuffer + stubOffset; StubOptimizer::generateArm64_32StubTo(newStubBuffer, newStubVMAddr.rawValue(), gotTargetVMAddr->rawValue()); } } else { // Unknown arch assert(0); } } }); return oldToNewStubMap; } void CacheDylib::forEachCallSiteToAStub(Diagnostics& diag, const CallSiteHandler handler) { // Get the section layout and split seg info from the source dylib __block uint64_t textSectionIndex = ~0U; __block uint64_t stubSectionIndex = ~0U; __block uint8_t* textSectionBuffer = nullptr; __block uint64_t textSectionVMAddr = ~0ULL; __block uint64_t stubSectionVMAddr = ~0ULL; // Find the sections { // Section #0 is the mach_header __block uint32_t sectionIndex = 1; this->cacheHdr->forEachSection(^(const Header::SegmentInfo &segInfo, const Header::SectionInfo §Info, bool &stop) { if ( sectInfo.segmentName == "__TEXT" ) { if ( sectInfo.sectionName == "__text" ) { textSectionIndex = sectionIndex; textSectionVMAddr = sectInfo.address; // Work out the buffer for the text section const DylibSegmentChunk& segment = this->segments[segInfo.segmentIndex]; CacheVMAddress segmentBaseAddress = segment.cacheVMAddress; CacheVMAddress sectionBaseAddress(sectInfo.address); VMOffset sectionOffsetInSegment = sectionBaseAddress - segmentBaseAddress; textSectionBuffer = segment.subCacheBuffer + sectionOffsetInSegment.rawValue(); } else if ( sectInfo.sectionName == "__stubs" ) { // On arm64e devices, we ignore __stubs and only handle __auth_stubs if ( !this->cacheHdr->isArch("arm64e") ) { stubSectionIndex = sectionIndex; stubSectionVMAddr = sectInfo.address; } } else if ( sectInfo.sectionName == "__auth_stubs" ) { // On arm64e devices, we ignore __stubs and only handle __auth_stubs if ( this->cacheHdr->isArch("arm64e") ) { stubSectionIndex = sectionIndex; stubSectionVMAddr = sectInfo.address; } } } ++sectionIndex; }); } if ( textSectionIndex == ~0U ) return; if ( stubSectionIndex == ~0U ) return; this->inputMF->withFileLayout(diag, ^(const mach_o::Layout& layout) { const uint8_t* infoStart = layout.linkedit.splitSegInfo.buffer; const uint8_t* infoEnd = infoStart + layout.linkedit.splitSegInfo.bufferSize; if ( *infoStart++ != DYLD_CACHE_ADJ_V2_FORMAT ) { diag.error("malformed split seg info in %s", this->installName.data()); return; } // Whole :== <count> FromToSection+ // FromToSection :== <from-sect-index> <to-sect-index> <count> ToOffset+ // ToOffset :== <to-sect-offset-delta> <count> FromOffset+ // FromOffset :== <kind> <count> <from-sect-offset-delta> const uint8_t* p = infoStart; uint64_t sectionCount = dyld3::MachOFile::read_uleb128(diag, p, infoEnd); for (uint64_t i=0; i < sectionCount; ++i) { uint64_t fromSectionIndex = dyld3::MachOFile::read_uleb128(diag, p, infoEnd); uint64_t toSectionIndex = dyld3::MachOFile::read_uleb128(diag, p, infoEnd); uint64_t toOffsetCount = dyld3::MachOFile::read_uleb128(diag, p, infoEnd); uint64_t toSectionOffset = 0; for (uint64_t j=0; j < toOffsetCount; ++j) { uint64_t toSectionDelta = dyld3::MachOFile::read_uleb128(diag, p, infoEnd); uint64_t fromOffsetCount = dyld3::MachOFile::read_uleb128(diag, p, infoEnd); toSectionOffset += toSectionDelta; for (uint64_t k=0; k < fromOffsetCount; ++k) { uint64_t kind = dyld3::MachOFile::read_uleb128(diag, p, infoEnd); if ( kind > 13 ) { diag.error("bad kind (%llu) value in %s\n", kind, this->installName.data()); return; } uint64_t fromSectDeltaCount = dyld3::MachOFile::read_uleb128(diag, p, infoEnd); uint64_t fromSectionOffset = 0; for (uint64_t l=0; l < fromSectDeltaCount; ++l) { uint64_t delta = dyld3::MachOFile::read_uleb128(diag, p, infoEnd); fromSectionOffset += delta; if ( (fromSectionIndex == textSectionIndex) && (toSectionIndex == stubSectionIndex) ) { uint32_t* instrPtr = (uint32_t*)(textSectionBuffer + fromSectionOffset); uint64_t instrAddr = textSectionVMAddr + fromSectionOffset; uint64_t stubAddr = stubSectionVMAddr + toSectionOffset; uint32_t instruction = *instrPtr; if ( handler(kind, instrAddr, stubAddr, instruction) ) { *instrPtr = instruction; } } } } } } }); } // In a universal cache, dylibs should not longer use their own __stubs, but instead redirect to a stubs // subCache. There will be 1 stubs cache for customer and another for development void CacheDylib::optimizeStubs(const BuilderOptions& options, const BuilderConfig& config, Timer::AggregateTimer& timer, const StubOptimizer& stubOptimizer, const PatchInfo& dylibPatchInfo) { if ( options.kind != CacheKind::universal ) return; Timer::AggregateTimer::Scope timedScope(timer, "optimizeStubs time"); OldToNewStubMap oldToNewStubMap = this->buildStubMaps(config, stubOptimizer, dylibPatchInfo); __block Diagnostics diag; // Walk the split seg info from the input dylib, as its been removed from the cache dylib this->forEachCallSiteToAStub(diag, ^(uint8_t kind, uint64_t callSiteAddr, uint64_t stubAddr, uint32_t& instruction) { if ( kind != DYLD_CACHE_ADJ_V2_ARM64_BR26 ) return false; // skip all but BL or B if ( (instruction & 0x7C000000) != 0x14000000 ) return false; // compute target of branch instruction int32_t brDelta = (instruction & 0x03FFFFFF) << 2; if ( brDelta & 0x08000000 ) brDelta |= 0xF0000000; uint64_t targetAddr = callSiteAddr + (int64_t)brDelta; if ( targetAddr != stubAddr ) { diag.warning("stub target mismatch"); return false; } // ignore branch if not to a stub we want to optimize CacheVMAddress oldStubAddr(stubAddr); auto it = oldToNewStubMap.find(oldStubAddr); if ( it == oldToNewStubMap.end() ) return false; CacheVMAddress newStubAddr = it->second; int64_t deltaToNewStub = newStubAddr.rawValue() - callSiteAddr; static const int64_t b128MegLimit = 0x07FFFFFF; if ( (deltaToNewStub <= -b128MegLimit) || (deltaToNewStub >= b128MegLimit) ) { diag.error("%s call could not reach stub island at offset 0x%llx", this->installName.data(), deltaToNewStub); return false; } instruction = (instruction & 0xFC000000) | ((deltaToNewStub >> 2) & 0x03FFFFFF); return true; }); } void CacheDylib::fipsSign(Timer::AggregateTimer& timer) { // We only need corecrypto. Skip everything else if ( this->installName != "/usr/lib/system/libcorecrypto.dylib" ) return; Timer::AggregateTimer::Scope timedScope(timer, "fipsSign time"); // find location in libcorecrypto.dylib to store hash of __text section __block const void* textLocation = nullptr; __block CacheVMSize textSize; __block const void* hashStoreLocation = nullptr; __block CacheVMSize hashStoreSize; this->forEachCacheSection(^(std::string_view segmentName, std::string_view sectionName, uint8_t *sectionBuffer, CacheVMAddress sectionVMAddr, CacheVMSize sectionVMSize, bool &stop) { if ( (segmentName == "__TEXT") && (sectionName == "__text") ) { textLocation = sectionBuffer; textSize = sectionVMSize; } else if ( (segmentName == "__TEXT") && (sectionName == "__fips_hmacs") ) { hashStoreLocation = sectionBuffer; hashStoreSize = sectionVMSize; } }); if ( hashStoreLocation == nullptr ) { // FIXME: Plumb up a warning. We can't make this an error as some platforms don't have this dylib // _diagnostics.warning("Could not find __TEXT/__fips_hmacs section in libcorecrypto.dylib, skipping FIPS sealing"); return; } if ( hashStoreSize.rawValue() != 32 ) { // FIXME: Plumb up a warning. We can't make this an error as some platforms don't have this dylib // _diagnostics.warning("__TEXT/__fips_hmacs section in libcorecrypto.dylib is not 32 bytes in size, skipping FIPS sealing"); return; } if ( textLocation == nullptr ) { // FIXME: Plumb up a warning. We can't make this an error as some platforms don't have this dylib // _diagnostics.warning("Could not find __TEXT/__text section in libcorecrypto.dylib, skipping FIPS sealing"); return; } // store hash directly into hashStoreLocation unsigned char hmac_key = 0; CCHmac(kCCHmacAlgSHA256, &hmac_key, 1, textLocation, textSize.rawValue(), (void*)hashStoreLocation); } template <typename P> static void addObjcSegments(Diagnostics& diag, const dyld3::MachOFile* objcMF, CacheVMAddress readOnlyVMAddr, CacheVMSize readOnlyVMSize, CacheFileOffset readOnlyFileOffset, CacheVMAddress readWriteVMAddr, CacheVMSize readWriteVMSize, CacheFileOffset readWriteFileOffset) { // validate there is enough free space to add the load commands uint32_t freeSpace = ((const Header*)objcMF)->loadCommandsFreeSpace(); const uint32_t segSize = sizeof(macho_segment_command<P>); if ( freeSpace < 2*segSize ) { diag.warning("not enough space in libojbc.dylib to add load commands for objc optimization regions"); return; } // find location of LINKEDIT LC_SEGMENT load command, we need to insert new segments before it uint32_t linkeditIndex = 0; uint8_t* linkeditSeg = nullptr; linkeditSeg = (uint8_t*)((mach_o::Header*)objcMF)->findLoadCommand(linkeditIndex, ^bool(const load_command *lc) { CString segmentName; if ( lc->cmd == LC_SEGMENT ) segmentName = ((const segment_command*)lc)->segname; else if ( lc->cmd == LC_SEGMENT_64 ) segmentName = ((const segment_command_64*)lc)->segname; return segmentName == "__LINKEDIT"; }); if ( linkeditSeg == nullptr ) { diag.warning("__LINKEDIT not found in libojbc.dylib"); return; } // move load commands to make room to insert two new ones before LINKEDIT segment load command uint8_t* endOfLoadCommands = (uint8_t*)objcMF + sizeof(macho_header<P>) + objcMF->sizeofcmds; uint32_t remainingSize = (uint32_t)(endOfLoadCommands - linkeditSeg); memmove(linkeditSeg+2*segSize, linkeditSeg, remainingSize); // insert new segments macho_segment_command<P>* roSeg = (macho_segment_command<P>*)(linkeditSeg); macho_segment_command<P>* rwSeg = (macho_segment_command<P>*)(linkeditSeg+sizeof(macho_segment_command<P>)); roSeg->set_cmd(macho_segment_command<P>::CMD); roSeg->set_cmdsize(segSize); roSeg->set_segname("__OBJC_RO"); roSeg->set_vmaddr(readOnlyVMAddr.rawValue()); roSeg->set_vmsize(readOnlyVMSize.rawValue()); roSeg->set_fileoff(readOnlyFileOffset.rawValue()); roSeg->set_filesize(readOnlyVMSize.rawValue()); roSeg->set_maxprot(VM_PROT_READ); roSeg->set_initprot(VM_PROT_READ); roSeg->set_nsects(0); roSeg->set_flags(0); rwSeg->set_cmd(macho_segment_command<P>::CMD); rwSeg->set_cmdsize(segSize); rwSeg->set_segname("__OBJC_RW"); rwSeg->set_vmaddr(readWriteVMAddr.rawValue()); rwSeg->set_vmsize(readWriteVMSize.rawValue()); rwSeg->set_fileoff(readWriteFileOffset.rawValue()); rwSeg->set_filesize(readWriteVMSize.rawValue()); rwSeg->set_maxprot(VM_PROT_WRITE|VM_PROT_READ); rwSeg->set_initprot(VM_PROT_WRITE|VM_PROT_READ); rwSeg->set_nsects(0); rwSeg->set_flags(0); // update mach_header to account for new load commands macho_header<P>* mh = (macho_header<P>*)objcMF; mh->set_sizeofcmds(mh->sizeofcmds() + 2*segSize); mh->set_ncmds(mh->ncmds()+2); } void CacheDylib::addObjcSegments(Diagnostics& diag, Timer::AggregateTimer& timer, const ObjCHeaderInfoReadOnlyChunk* headerInfoReadOnlyChunk, const ObjCImageInfoChunk* imageInfoChunk, const ObjCProtocolHashTableChunk* protocolHashTableChunk, const ObjCPreAttachedCategoriesChunk* preAttachedCategoriesChunk, const ObjCHeaderInfoReadWriteChunk* headerInfoReadWriteChunk, const ObjCCanonicalProtocolsChunk* canonicalProtocolsChunk) { // We only need objc. Skip everything else if ( this->installName != "/usr/lib/libobjc.A.dylib" ) return; Timer::AggregateTimer::Scope timedScope(timer, "addObjcSegments time"); // Find the ranges for OBJC_RO and OBJC_RW // Read-only // Note these asserts are just to make sure we use the correct chunks for the start/end static_assert(Chunk::Kind::objcHeaderInfoRO < Chunk::Kind::objcImageInfo); static_assert(Chunk::Kind::objcImageInfo < Chunk::Kind::objcStrings); static_assert(Chunk::Kind::objcStrings < Chunk::Kind::objcSelectorsHashTable); static_assert(Chunk::Kind::objcSelectorsHashTable < Chunk::Kind::objcClassesHashTable); static_assert(Chunk::Kind::objcClassesHashTable < Chunk::Kind::objcProtocolsHashTable); static_assert(Chunk::Kind::objcProtocolsHashTable < Chunk::Kind::objcIMPCaches); static_assert(Chunk::Kind::objcIMPCaches < Chunk::Kind::objcPreAttachedCategories); CacheFileOffset readOnlyFileOffset = headerInfoReadOnlyChunk->subCacheFileOffset; CacheVMAddress readOnlyVMAddr = headerInfoReadOnlyChunk->cacheVMAddress; CacheVMSize readOnlyVMSize = (preAttachedCategoriesChunk->cacheVMAddress + preAttachedCategoriesChunk->cacheVMSize) - readOnlyVMAddr; // Read-write static_assert(Chunk::Kind::objcHeaderInfoRW < Chunk::Kind::objcCanonicalProtocols); CacheFileOffset readWriteFileOffset = headerInfoReadWriteChunk->subCacheFileOffset; CacheVMAddress readWriteVMAddr = headerInfoReadWriteChunk->cacheVMAddress; CacheVMSize readWriteVMSize = (canonicalProtocolsChunk->cacheVMAddress + canonicalProtocolsChunk->cacheVMSize) - readWriteVMAddr; if ( this->inputHdr->is64() ) { typedef Pointer64<LittleEndian> P; addObjcSegments<P>(diag, this->cacheMF, readOnlyVMAddr, readOnlyVMSize, readOnlyFileOffset, readWriteVMAddr, readWriteVMSize, readWriteFileOffset); } else { typedef Pointer32<LittleEndian> P; addObjcSegments<P>(diag, this->cacheMF, readOnlyVMAddr, readOnlyVMSize, readOnlyFileOffset, readWriteVMAddr, readWriteVMSize, readWriteFileOffset); } } void CacheDylib::removeLinkedDylibs(Diagnostics& diag) { mach_o::HeaderWriter* header = (mach_o::HeaderWriter*)cacheHdr; uint32_t lcLibSystemIndex = 0; if ( !header->findLoadCommand(lcLibSystemIndex, ^bool(const load_command *lc) { const dylib_command* dyliblc = mach_o::Header::isDylibLoadCommand(lc); if ( !dyliblc ) return false; const char* loadPath = (char*)dyliblc + dyliblc->dylib.name.offset; return strstr(loadPath, "libSystem"); }) ) { diag.error("can't remove linked dylibs from %s, expected to find libSystem dependency", header->installName()); return; } uint32_t lcDylibStart = 0; uint32_t lcDylibEnd = 0; header->findLoadCommandRange(lcDylibStart, lcDylibEnd, ^bool(const load_command *lc) { return mach_o::Header::isDylibLoadCommand(lc) != nullptr; }); // libSystem was found, so the range of dylib load commands also must not be empty assert(lcDylibStart != lcDylibEnd); assert(lcLibSystemIndex >= lcDylibStart); if ( lcDylibStart != lcLibSystemIndex ) { diag.error("expected libSystem to be the first linked dylib of %s, but it's ordinal is: %u", header->installName(), lcLibSystemIndex-lcDylibStart); return; } // This removes all load commands after LC_LOAD_DYLIB of libSystem if ( mach_o::Error err = header->removeLoadCommands(lcLibSystemIndex+1, lcDylibEnd) ) diag.error(err); } void CacheDylib::addLinkedDylib(Diagnostics& diag, const CacheDylib& dylib) { const char* dylibInstallName = nullptr; Version32 compatVersion; Version32 currentVersion; dylib.inputHdr->getDylibInstallName(&dylibInstallName, &compatVersion, ¤tVersion); // find the range of all LC_LOAD* commands, new dylib will be added as last uint32_t lcLoadStart = 0; uint32_t lcLoadEnd = 0; mach_o::HeaderWriter* header = (mach_o::HeaderWriter*)this->cacheHdr; header->findLoadCommandRange(lcLoadStart, lcLoadEnd, ^bool(const load_command *lc) { return mach_o::Header::isDylibLoadCommand(lc) != nullptr; }); if ( lcLoadEnd == 0 ) { // there should be at least one already diag.error("%s has no linked dylibs", header->installName()); return; } // determine command size mach_o::LinkedDylibAttributes attr = mach_o::LinkedDylibAttributes::regular; uint32_t traditionalCmd = 0; uint32_t cmdSize = header->sizeForLinkedDylibCommand(dylibInstallName, attr, traditionalCmd); // insert command load_command* lc = header->insertLoadCommand(lcLoadEnd, cmdSize); if ( lc == nullptr ) { diag.error("not enough space in %s to add %s load command", header->installName(), dylibInstallName); return; } header->setLinkedDylib(lc, dylibInstallName, attr, mach_o::Version32(compatVersion), mach_o::Version32(currentVersion)); } objc_visitor::Visitor CacheDylib::makeCacheObjCVisitor(const BuilderConfig& config, const Chunk* selectorStringsChunk, const ObjCCanonicalProtocolsChunk* canonicalProtocolsChunk, const ObjCPreAttachedCategoriesChunk* categoriesChunk) const { // Get the segment ranges. We need this as the dylib's segments are in different buffers, not in VM layout std::vector<metadata_visitor::Segment> cacheSegments; cacheSegments.reserve(this->segments.size()); for ( uint32_t segIndex = 0; segIndex != this->segments.size(); ++segIndex ) { const DylibSegmentChunk& segmentInfo = this->segments[segIndex]; metadata_visitor::Segment segment; segment.startVMAddr = VMAddress(segmentInfo.cacheVMAddress.rawValue()); segment.endVMAddr = VMAddress((segmentInfo.cacheVMAddress + segmentInfo.cacheVMSize).rawValue()); segment.bufferStart = segmentInfo.subCacheBuffer; // Cache dylibs never have a chained format. They always use the Fixup struct segment.onDiskDylibChainedPointerFormat = { }; // We need to know what segment we are in, so that we can find the ASLRTracker for the segment segment.segIndex = segIndex; cacheSegments.push_back(std::move(segment)); } // Add the selector strings chunk too. That way we can resolve references which land on it if ( selectorStringsChunk != nullptr ) { metadata_visitor::Segment segment; segment.startVMAddr = VMAddress(selectorStringsChunk->cacheVMAddress.rawValue()); segment.endVMAddr = VMAddress((selectorStringsChunk->cacheVMAddress + selectorStringsChunk->cacheVMSize).rawValue()); segment.bufferStart = selectorStringsChunk->subCacheBuffer; // Note we don't have a chainedPointerFormat as the selectors don't slide segment.onDiskDylibChainedPointerFormat = { }; cacheSegments.push_back(std::move(segment)); } // Add the canonical protocols chunk too. That way we can resolve references which land on it if ( canonicalProtocolsChunk != nullptr ) { metadata_visitor::Segment segment; segment.startVMAddr = VMAddress(canonicalProtocolsChunk->cacheVMAddress.rawValue()); segment.endVMAddr = VMAddress((canonicalProtocolsChunk->cacheVMAddress + canonicalProtocolsChunk->cacheVMSize).rawValue()); segment.bufferStart = canonicalProtocolsChunk->subCacheBuffer; // Cache segments never have a chained format. They always use the Fixup struct segment.onDiskDylibChainedPointerFormat = { }; cacheSegments.push_back(std::move(segment)); } // Add the categories data chunk too. That way we can resolve references which land on it if ( categoriesChunk != nullptr ) { metadata_visitor::Segment segment; segment.startVMAddr = VMAddress(categoriesChunk->cacheVMAddress.rawValue()); segment.endVMAddr = VMAddress((categoriesChunk->cacheVMAddress + categoriesChunk->cacheVMSize).rawValue()); segment.bufferStart = categoriesChunk->subCacheBuffer; // Cache segments never have a chained format. They always use the Fixup struct segment.onDiskDylibChainedPointerFormat = { }; cacheSegments.push_back(std::move(segment)); } VMAddress selectorStringsAddress; if ( selectorStringsChunk != nullptr ) selectorStringsAddress = VMAddress(selectorStringsChunk->cacheVMAddress.rawValue()); std::vector<uint64_t> unusedBindTargets; objc_visitor::Visitor objcVisitor(config.layout.cacheBaseAddress, this->cacheMF, std::move(cacheSegments), selectorStringsAddress, std::move(unusedBindTargets)); return objcVisitor; } metadata_visitor::SwiftVisitor CacheDylib::makeCacheSwiftVisitor(const BuilderConfig& config, std::span<metadata_visitor::Segment> extraRegions) const { // Get the segment ranges. We need this as the dylib's segments are in different buffers, not in VM layout std::vector<metadata_visitor::Segment> cacheSegments; cacheSegments.reserve(this->segments.size()); for ( uint32_t segIndex = 0; segIndex != this->segments.size(); ++segIndex ) { const DylibSegmentChunk& segmentInfo = this->segments[segIndex]; metadata_visitor::Segment segment; segment.startVMAddr = VMAddress(segmentInfo.cacheVMAddress.rawValue()); segment.endVMAddr = VMAddress((segmentInfo.cacheVMAddress + segmentInfo.cacheVMSize).rawValue()); segment.bufferStart = segmentInfo.subCacheBuffer; // Cache dylibs never have a chained format. They always use the Fixup struct segment.onDiskDylibChainedPointerFormat = { }; // We need to know what segment we are in, so that we can find the ASLRTracker for the segment segment.segIndex = segIndex; cacheSegments.push_back(std::move(segment)); } cacheSegments.insert(cacheSegments.end(), extraRegions.begin(), extraRegions.end()); std::vector<uint64_t> unusedBindTargets; metadata_visitor::SwiftVisitor swiftVisitor(config.layout.cacheBaseAddress, this->cacheMF, std::move(cacheSegments), VMAddress(0ULL), std::move(unusedBindTargets)); return swiftVisitor; } metadata_visitor::Visitor CacheDylib::makeCacheVisitor(const BuilderConfig& config) const { // Get the segment ranges. We need this as the dylib's segments are in different buffers, not in VM layout __block std::vector<metadata_visitor::Segment> cacheSegments; cacheSegments.reserve(this->segments.size()); for ( uint32_t segIndex = 0; segIndex != this->segments.size(); ++segIndex ) { const DylibSegmentChunk& segmentInfo = this->segments[segIndex]; metadata_visitor::Segment segment; segment.startVMAddr = VMAddress(segmentInfo.cacheVMAddress.rawValue()); segment.endVMAddr = VMAddress((segmentInfo.cacheVMAddress + segmentInfo.cacheVMSize).rawValue()); segment.bufferStart = segmentInfo.subCacheBuffer; // Cache dylibs never have a chained format. They always use the Fixup struct segment.onDiskDylibChainedPointerFormat = { }; // We need to know what segment we are in, so that we can find the ASLRTracker for the segment segment.segIndex = segIndex; cacheSegments.push_back(std::move(segment)); } // Add the GOTs too, if we have them optimizedSections.forEachCacheGOTChunk(^(const cache_builder::Chunk* chunk) { metadata_visitor::Segment segment; segment.startVMAddr = VMAddress(chunk->cacheVMAddress.rawValue()); segment.endVMAddr = VMAddress((chunk->cacheVMAddress + chunk->cacheVMSize).rawValue()); segment.bufferStart = chunk->subCacheBuffer; // Cache segments never have a chained format. They always use the Fixup struct segment.onDiskDylibChainedPointerFormat = { }; cacheSegments.push_back(std::move(segment)); }); std::vector<uint64_t> unusedBindTargets; metadata_visitor::Visitor visitor(config.layout.cacheBaseAddress, this->cacheMF, std::move(cacheSegments), { }, std::move(unusedBindTargets)); return visitor; } void CacheDylib::forEachCacheSection(void (^callback)(std::string_view segmentName, std::string_view sectionName, uint8_t* sectionBuffer, CacheVMAddress sectionVMAddr, CacheVMSize sectionVMSize, bool& stop)) { this->inputHdr->forEachSection(^(const Header::SegmentInfo &segInfo, const Header::SectionInfo §Info, bool &stop) { const DylibSegmentChunk& segment = this->segments[sectInfo.segIndex]; VMAddress sectionVMAddr(sectInfo.address); VMAddress segmentVMAddr(segInfo.vmaddr); VMOffset sectionOffsetInSegment = sectionVMAddr - segmentVMAddr; uint8_t* sectionBuffer = segment.subCacheBuffer + sectionOffsetInSegment.rawValue(); CacheVMAddress cacheVMAddr = segment.cacheVMAddress + sectionOffsetInSegment; callback(sectInfo.segmentName, sectInfo.sectionName, sectionBuffer, cacheVMAddr, CacheVMSize(sectInfo.size), stop); }); } |