Loading...
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 | /* -*- mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*- * * Copyright (c) 2014 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 "AppCacheBuilder.h" #include <mach/mach_time.h> #include <sys/stat.h> #include <CoreFoundation/CFArray.h> #include <CoreFoundation/CFError.h> #include <CoreFoundation/CFNumber.h> #include <CoreFoundation/CFPropertyList.h> #include <CoreFoundation/CFString.h> #include <CommonCrypto/CommonHMAC.h> #include <CommonCrypto/CommonDigest.h> #include <CommonCrypto/CommonDigestSPI.h> AppCacheBuilder::AppCacheBuilder(const DyldSharedCache::CreateOptions& options, const Options& appCacheOptions, const dyld3::closure::FileSystem& fileSystem) : CacheBuilder(options, fileSystem), appCacheOptions(appCacheOptions) { // FIXME: 32-bit support _is64 = true; } AppCacheBuilder::~AppCacheBuilder() { if (prelinkInfoDict) { CFRelease(prelinkInfoDict); } if (_fullAllocatedBuffer) { vm_deallocate(mach_task_self(), _fullAllocatedBuffer, _allocatedBufferSize); } } void AppCacheBuilder::makeSortedDylibs(const std::vector<InputDylib>& dylibs) { for (const InputDylib& file : dylibs) { if ( file.dylib.loadedFileInfo.fileContent == nullptr ) { codelessKexts.push_back(file); } else { AppCacheDylibInfo& dylibInfo = sortedDylibs.emplace_back(); dylibInfo.input = &file.dylib; dylibInfo.dylibID = file.dylibID; dylibInfo.dependencies = file.dylibDeps; dylibInfo.infoPlist = file.infoPlist; dylibInfo.errors = file.errors; dylibInfo.bundlePath = file.bundlePath; dylibInfo.stripMode = file.stripMode; } } std::sort(sortedDylibs.begin(), sortedDylibs.end(), [&](const DylibInfo& a, const DylibInfo& b) { // Sort the kernel first, then kext's bool isStaticExecutableA = a.input->mappedFile.mh->isStaticExecutable(); bool isStaticExecutableB = b.input->mappedFile.mh->isStaticExecutable(); if (isStaticExecutableA != isStaticExecutableB) return isStaticExecutableA; // Sort split seg next bool splitSegA = a.input->mappedFile.mh->hasSplitSeg(); bool splitSegB = b.input->mappedFile.mh->hasSplitSeg(); if (splitSegA != splitSegB) return splitSegA; // Finally sort by path return a.input->mappedFile.runtimePath < b.input->mappedFile.runtimePath; }); // Sort codeless kext's by ID std::sort(codelessKexts.begin(), codelessKexts.end(), [&](const InputDylib& a, const InputDylib& b) { return a.dylibID < b.dylibID; }); } void AppCacheBuilder::forEachCacheDylib(void (^callback)(const dyld3::MachOAnalyzer* ma, const std::string& dylibID, DylibStripMode stripMode, const std::vector<std::string>& dependencies, Diagnostics& dylibDiag, bool& stop)) const { bool stop = false; for (const AppCacheDylibInfo& dylib : sortedDylibs) { for (const SegmentMappingInfo& loc : dylib.cacheLocation) { if (!strcmp(loc.segName, "__TEXT")) { // Assume __TEXT contains the mach header callback((const dyld3::MachOAnalyzer*)loc.dstSegment, dylib.dylibID, dylib.stripMode, dylib.dependencies, *dylib.errors, stop); break; } } if (stop) break; } } void AppCacheBuilder::forEachDylibInfo(void (^callback)(const DylibInfo& dylib, Diagnostics& dylibDiag, ASLR_Tracker& dylibASLRTracker)) { for (const AppCacheDylibInfo& dylibInfo : sortedDylibs) callback(dylibInfo, *dylibInfo.errors, _aslrTracker); } const CacheBuilder::DylibInfo* AppCacheBuilder::getKernelStaticExecutableInputFile() const { for (const auto& dylib : sortedDylibs) { const dyld3::MachOAnalyzer* ma = dylib.input->mappedFile.mh; if ( ma->isStaticExecutable() ) return &dylib; } return nullptr; } const dyld3::MachOAnalyzer* AppCacheBuilder::getKernelStaticExecutableFromCache() const { // FIXME: Support reading this from a prebuilt KC assert(appCacheOptions.cacheKind == Options::AppCacheKind::kernel); __block const dyld3::MachOAnalyzer* kernelMA = nullptr; forEachCacheDylib(^(const dyld3::MachOAnalyzer *ma, const std::string &dylibID, DylibStripMode stripMode, const std::vector<std::string>& dependencies, Diagnostics& dylibDiag, bool& stop) { if ( ma->isStaticExecutable() ) { kernelMA = ma; stop = true; } }); assert(kernelMA != nullptr); return kernelMA; } void AppCacheBuilder::forEachRegion(void (^callback)(const Region& region)) const { // cacheHeaderRegion callback(cacheHeaderRegion); // readOnlyTextRegion callback(readOnlyTextRegion); // readExecuteRegion if ( readExecuteRegion.sizeInUse != 0 ) callback(readExecuteRegion); // branchStubsRegion if ( branchStubsRegion.bufferSize != 0 ) callback(branchStubsRegion); // dataConstRegion if ( dataConstRegion.sizeInUse != 0 ) callback(dataConstRegion); // branchGOTsRegion if ( branchGOTsRegion.bufferSize != 0 ) callback(branchGOTsRegion); // readWriteRegion if ( readWriteRegion.sizeInUse != 0 ) callback(readWriteRegion); // hibernateRegion if ( hibernateRegion.sizeInUse != 0 ) callback(hibernateRegion); // -sectcreate for (const Region& region : customDataRegions) callback(region); // prelinkInfoRegion if ( prelinkInfoDict != nullptr ) callback(prelinkInfoRegion); // nonSplitSegRegions for (const Region& region : nonSplitSegRegions) callback(region); // _readOnlyRegion callback(_readOnlyRegion); // fixupsRegion // We don't count this as its not a real region } uint64_t AppCacheBuilder::numRegions() const { __block uint64_t count = 0; forEachRegion(^(const Region ®ion) { ++count; }); return count; } uint64_t AppCacheBuilder::fixupsPageSize() const { bool use4K = false; use4K |= (_options.archs == &dyld3::GradedArchs::x86_64); use4K |= (_options.archs == &dyld3::GradedArchs::x86_64h); return use4K ? 4096 : 16384; } uint64_t AppCacheBuilder::numWritablePagesToFixup(uint64_t numBytesToFixup) const { uint64_t pageSize = fixupsPageSize(); assert((numBytesToFixup % pageSize) == 0); uint64_t numPagesToFixup = numBytesToFixup / pageSize; return numPagesToFixup; } // Returns true if each kext inside the KC needs to be reloadable, ie, have its // pages reset and its start method rerun. This means we can't pack pages and need // fixups on each kext individually bool AppCacheBuilder::fixupsArePerKext() const { if ( appCacheOptions.cacheKind == Options::AppCacheKind::pageableKC ) return true; bool isX86 = (_options.archs == &dyld3::GradedArchs::x86_64) || (_options.archs == &dyld3::GradedArchs::x86_64h); return isX86 && (appCacheOptions.cacheKind == Options::AppCacheKind::auxKC); } // x86_64 kext's don't contain stubs for branches so we need to generate some // if branches cross from one KC to another, eg, from the auxKC to the base KC uint64_t AppCacheBuilder::numBranchRelocationTargets() { bool mayHaveBranchRelocations = false; mayHaveBranchRelocations |= (_options.archs == &dyld3::GradedArchs::x86_64); mayHaveBranchRelocations |= (_options.archs == &dyld3::GradedArchs::x86_64h); if ( !mayHaveBranchRelocations ) return 0; switch (appCacheOptions.cacheKind) { case Options::AppCacheKind::none: case Options::AppCacheKind::kernel: // Nothing to do here as we can't bind from a lower level up to a higher one return 0; case Options::AppCacheKind::pageableKC: case Options::AppCacheKind::kernelCollectionLevel2: case Options::AppCacheKind::auxKC: // Any calls in these might be to a lower level so add space for each call target break; } uint64_t totalTargets = 0; for (const DylibInfo& dylib : sortedDylibs) { // We need the symbol name and libOrdinal just in case we bind to the same symbol name in 2 different KCs typedef std::pair<std::string_view, int> Symbol; struct SymbolHash { size_t operator() (const Symbol& symbol) const { return std::hash<std::string_view>{}(symbol.first) ^ std::hash<int>{}(symbol.second); } }; __block std::unordered_set<Symbol, SymbolHash> seenSymbols; dylib.input->mappedFile.mh->forEachBind(_diagnostics, ^(uint64_t runtimeOffset, int libOrdinal, uint8_t type, const char *symbolName, bool weakImport, bool lazyBind, uint64_t addend, bool &stop) { if ( type != BIND_TYPE_TEXT_PCREL32 ) return; seenSymbols.insert({ symbolName, libOrdinal }); }, ^(const char *symbolName) { }); totalTargets += seenSymbols.size(); } return totalTargets; } void AppCacheBuilder::assignSegmentRegionsAndOffsets() { // Segments can be re-ordered in memory relative to the order of the LC_SEGMENT load comamnds // so first make space for all the cache location objects so that we get the order the same // as the LC_SEGMENTs for (DylibInfo& dylib : sortedDylibs) { dylib.input->mappedFile.mh->forEachSegment(^(const dyld3::MachOFile::SegmentInfo& segInfo, bool& stop) { dylib.cacheLocation.push_back({}); }); } // If we are building the kernel collection, then inherit the base address of the statically linked kernel const dyld3::MachOAnalyzer* kernelMA = nullptr; if ( appCacheOptions.cacheKind == Options::AppCacheKind::kernel ) { for (DylibInfo& dylib : sortedDylibs) { if ( dylib.input->mappedFile.mh->isStaticExecutable() ) { kernelMA = dylib.input->mappedFile.mh; break; } } if ( kernelMA == nullptr ) { _diagnostics.error("Could not find kernel image"); return; } cacheBaseAddress = kernelMA->preferredLoadAddress(); } // x86_64 doesn't have stubs for kext branches. So work out how many potential targets // we need to emit stubs for. uint64_t branchTargetsFromKexts = numBranchRelocationTargets(); uint32_t minimumSegmentAlignmentP2 = 14; if ( (_options.archs == &dyld3::GradedArchs::x86_64) || (_options.archs == &dyld3::GradedArchs::x86_64h) ) { minimumSegmentAlignmentP2 = 12; } auto getMinAlignment = ^(const dyld3::MachOAnalyzer* ma) { // The kernel wants to be able to unmap its own segments so always align it. // And align the pageable KC as each kext can be mapped individually if ( ma == kernelMA ) return minimumSegmentAlignmentP2; if ( fixupsArePerKext() ) return minimumSegmentAlignmentP2; return 0U; }; { // __TEXT segments with r/o permissions __block uint64_t offsetInRegion = 0; for (DylibInfo& dylib : sortedDylibs) { bool canBePacked = dylib.input->mappedFile.mh->hasSplitSeg(); if (!canBePacked) continue; __block uint64_t textSegVmAddr = 0; dylib.input->mappedFile.mh->forEachSegment(^(const dyld3::MachOFile::SegmentInfo& segInfo, bool& stop) { if ( strcmp(segInfo.segName, "__TEXT") == 0 ) textSegVmAddr = segInfo.vmAddr; if ( segInfo.protections != (VM_PROT_READ) ) return; if ( (strcmp(segInfo.segName, "__DATA_CONST") == 0) || (strcmp(segInfo.segName, "__PPLDATA_CONST") == 0) || (strcmp(segInfo.segName, "__LASTDATA_CONST") == 0) ) return; if ( strcmp(segInfo.segName, "__LINKEDIT") == 0 ) return; if ( strcmp(segInfo.segName, "__LINKINFO") == 0 ) return; uint32_t minAlignmentP2 = getMinAlignment(dylib.input->mappedFile.mh); size_t copySize = std::min((size_t)segInfo.fileSize, (size_t)segInfo.sizeOfSections); uint64_t dstCacheSegmentSize = align(segInfo.sizeOfSections, minAlignmentP2); // __CTF is not mapped in to the kernel, so remove it from the final binary. if ( strcmp(segInfo.segName, "__CTF") == 0 ) { copySize = 0; dstCacheSegmentSize = 0; } // kxld packs __TEXT so we will do // Note we align to at least 16-bytes as LDR's can scale up to 16 from their address // and aligning them less than 16 would break that offsetInRegion = align(offsetInRegion, std::max(segInfo.p2align, 4U)); offsetInRegion = align(offsetInRegion, minAlignmentP2); SegmentMappingInfo loc; loc.srcSegment = (uint8_t*)dylib.input->mappedFile.mh + segInfo.vmAddr - textSegVmAddr; loc.segName = segInfo.segName; loc.dstSegment = nullptr; loc.dstCacheUnslidAddress = offsetInRegion; // This will be updated later once we've assigned addresses loc.dstCacheFileOffset = (uint32_t)offsetInRegion; loc.dstCacheSegmentSize = (uint32_t)dstCacheSegmentSize; loc.dstCacheFileSize = (uint32_t)copySize; loc.copySegmentSize = (uint32_t)copySize; loc.srcSegmentIndex = segInfo.segIndex; loc.parentRegion = &readOnlyTextRegion; dylib.cacheLocation[segInfo.segIndex] = loc; offsetInRegion += dstCacheSegmentSize; }); } // kclist needs this segment, even if its empty, so leave it in there readOnlyTextRegion.bufferSize = align(offsetInRegion, 14); readOnlyTextRegion.sizeInUse = readOnlyTextRegion.bufferSize; readOnlyTextRegion.initProt = VM_PROT_READ; readOnlyTextRegion.maxProt = VM_PROT_READ; readOnlyTextRegion.name = "__PRELINK_TEXT"; } // __TEXT segments with r/x permissions { // __TEXT segments with r/x permissions __block uint64_t offsetInRegion = 0; for (DylibInfo& dylib : sortedDylibs) { bool canBePacked = dylib.input->mappedFile.mh->hasSplitSeg(); if (!canBePacked) continue; __block uint64_t textSegVmAddr = 0; dylib.input->mappedFile.mh->forEachSegment(^(const dyld3::MachOFile::SegmentInfo& segInfo, bool& stop) { if ( strcmp(segInfo.segName, "__TEXT") == 0 ) textSegVmAddr = segInfo.vmAddr; if ( strcmp(segInfo.segName, "__HIB") == 0 ) return; if ( segInfo.protections != (VM_PROT_READ | VM_PROT_EXECUTE) ) return; // kxld packs __TEXT_EXEC so we will do // Note we align to at least 16-bytes as LDR's can scale up to 16 from their address // and aligning them less than 16 would break that uint32_t minAlignmentP2 = getMinAlignment(dylib.input->mappedFile.mh); offsetInRegion = align(offsetInRegion, std::max(segInfo.p2align, 4U)); offsetInRegion = align(offsetInRegion, minAlignmentP2); size_t copySize = std::min((size_t)segInfo.fileSize, (size_t)segInfo.sizeOfSections); uint64_t dstCacheSegmentSize = align(segInfo.sizeOfSections, minAlignmentP2); SegmentMappingInfo loc; loc.srcSegment = (uint8_t*)dylib.input->mappedFile.mh + segInfo.vmAddr - textSegVmAddr; loc.segName = segInfo.segName; loc.dstSegment = nullptr; loc.dstCacheUnslidAddress = offsetInRegion; // This will be updated later once we've assigned addresses loc.dstCacheFileOffset = (uint32_t)offsetInRegion; loc.dstCacheSegmentSize = (uint32_t)dstCacheSegmentSize; loc.dstCacheFileSize = (uint32_t)copySize; loc.copySegmentSize = (uint32_t)copySize; loc.srcSegmentIndex = segInfo.segIndex; loc.parentRegion = &readExecuteRegion; dylib.cacheLocation[segInfo.segIndex] = loc; offsetInRegion += loc.dstCacheSegmentSize; }); } // align r/x region end readExecuteRegion.bufferSize = align(offsetInRegion, 14); readExecuteRegion.sizeInUse = readExecuteRegion.bufferSize; readExecuteRegion.initProt = VM_PROT_READ | VM_PROT_EXECUTE; readExecuteRegion.maxProt = VM_PROT_READ | VM_PROT_EXECUTE; readExecuteRegion.name = "__TEXT_EXEC"; } if ( branchTargetsFromKexts != 0 ) { // 6-bytes per jmpq branchStubsRegion.bufferSize = align(branchTargetsFromKexts * 6, 14); branchStubsRegion.sizeInUse = branchStubsRegion.bufferSize; branchStubsRegion.initProt = VM_PROT_READ | VM_PROT_EXECUTE; branchStubsRegion.maxProt = VM_PROT_READ | VM_PROT_EXECUTE; branchStubsRegion.name = "__BRANCH_STUBS"; } // __DATA_CONST segments { __block uint64_t offsetInRegion = 0; for (DylibInfo& dylib : sortedDylibs) { if (!dylib.input->mappedFile.mh->hasSplitSeg()) continue; __block uint64_t textSegVmAddr = 0; dylib.input->mappedFile.mh->forEachSegment(^(const dyld3::MachOFile::SegmentInfo& segInfo, bool& stop) { if ( strcmp(segInfo.segName, "__TEXT") == 0 ) textSegVmAddr = segInfo.vmAddr; if ( (segInfo.protections & VM_PROT_EXECUTE) != 0 ) return; if ( (strcmp(segInfo.segName, "__DATA_CONST") != 0) && (strcmp(segInfo.segName, "__PPLDATA_CONST") != 0) && (strcmp(segInfo.segName, "__LASTDATA_CONST") != 0) ) return; // kxld packs __DATA_CONST so we will do uint32_t minAlignmentP2 = getMinAlignment(dylib.input->mappedFile.mh); offsetInRegion = align(offsetInRegion, segInfo.p2align); offsetInRegion = align(offsetInRegion, minAlignmentP2); size_t copySize = std::min((size_t)segInfo.fileSize, (size_t)segInfo.sizeOfSections); uint64_t dstCacheSegmentSize = align(segInfo.sizeOfSections, minAlignmentP2); SegmentMappingInfo loc; loc.srcSegment = (uint8_t*)dylib.input->mappedFile.mh + segInfo.vmAddr - textSegVmAddr; loc.segName = segInfo.segName; loc.dstSegment = nullptr; loc.dstCacheUnslidAddress = offsetInRegion; // This will be updated later once we've assigned addresses loc.dstCacheFileOffset = (uint32_t)offsetInRegion; loc.dstCacheSegmentSize = (uint32_t)dstCacheSegmentSize; loc.dstCacheFileSize = (uint32_t)copySize; loc.copySegmentSize = (uint32_t)copySize; loc.srcSegmentIndex = segInfo.segIndex; loc.parentRegion = &dataConstRegion; dylib.cacheLocation[segInfo.segIndex] = loc; offsetInRegion += loc.dstCacheSegmentSize; }); } // align r/o region end dataConstRegion.bufferSize = align(offsetInRegion, 14); dataConstRegion.sizeInUse = dataConstRegion.bufferSize; dataConstRegion.initProt = VM_PROT_READ; dataConstRegion.maxProt = VM_PROT_READ; dataConstRegion.name = "__DATA_CONST"; } // Branch GOTs if ( branchTargetsFromKexts != 0 ) { // 8-bytes per GOT branchGOTsRegion.bufferSize = align(branchTargetsFromKexts * 8, 14); branchGOTsRegion.sizeInUse = branchGOTsRegion.bufferSize; branchGOTsRegion.initProt = VM_PROT_READ | VM_PROT_WRITE; branchGOTsRegion.maxProt = VM_PROT_READ | VM_PROT_WRITE; branchGOTsRegion.name = "__BRANCH_GOTS"; } // __DATA* segments { __block uint64_t offsetInRegion = 0; for (DylibInfo& dylib : sortedDylibs) { if (!dylib.input->mappedFile.mh->hasSplitSeg()) continue; __block uint64_t textSegVmAddr = 0; dylib.input->mappedFile.mh->forEachSegment(^(const dyld3::MachOFile::SegmentInfo& segInfo, bool& stop) { if ( strcmp(segInfo.segName, "__TEXT") == 0 ) textSegVmAddr = segInfo.vmAddr; if ( strcmp(segInfo.segName, "__HIB") == 0 ) return; if ( (strcmp(segInfo.segName, "__DATA_CONST") == 0) || (strcmp(segInfo.segName, "__PPLDATA_CONST") == 0) || (strcmp(segInfo.segName, "__LASTDATA_CONST") == 0) ) return; if ( segInfo.protections != (VM_PROT_READ | VM_PROT_WRITE) ) return; // kxld packs __DATA so we will do uint32_t minAlignmentP2 = getMinAlignment(dylib.input->mappedFile.mh); offsetInRegion = align(offsetInRegion, segInfo.p2align); offsetInRegion = align(offsetInRegion, minAlignmentP2); size_t copySize = std::min((size_t)segInfo.fileSize, (size_t)segInfo.sizeOfSections); uint64_t dstCacheSegmentSize = align(segInfo.sizeOfSections, minAlignmentP2); SegmentMappingInfo loc; loc.srcSegment = (uint8_t*)dylib.input->mappedFile.mh + segInfo.vmAddr - textSegVmAddr; loc.segName = segInfo.segName; loc.dstSegment = nullptr; loc.dstCacheUnslidAddress = offsetInRegion; // This will be updated later once we've assigned addresses loc.dstCacheFileOffset = (uint32_t)offsetInRegion; loc.dstCacheSegmentSize = (uint32_t)dstCacheSegmentSize; loc.dstCacheFileSize = (uint32_t)copySize; loc.copySegmentSize = (uint32_t)copySize; loc.srcSegmentIndex = segInfo.segIndex; loc.parentRegion = &readWriteRegion; dylib.cacheLocation[segInfo.segIndex] = loc; offsetInRegion += loc.dstCacheSegmentSize; }); } // align r/w region end readWriteRegion.bufferSize = align(offsetInRegion, 14); readWriteRegion.sizeInUse = readWriteRegion.bufferSize; readWriteRegion.initProt = VM_PROT_READ | VM_PROT_WRITE; readWriteRegion.maxProt = VM_PROT_READ | VM_PROT_WRITE; readWriteRegion.name = "__DATA"; } { // Hibernate region __block uint64_t offsetInRegion = 0; for (DylibInfo& dylib : sortedDylibs) { if ( !dylib.input->mappedFile.mh->isStaticExecutable() ) continue; __block uint64_t textSegVmAddr = 0; dylib.input->mappedFile.mh->forEachSegment(^(const dyld3::MachOFile::SegmentInfo& segInfo, bool& stop) { if ( strcmp(segInfo.segName, "__TEXT") == 0 ) textSegVmAddr = segInfo.vmAddr; if ( strcmp(segInfo.segName, "__HIB") != 0 ) return; size_t copySize = std::min((size_t)segInfo.fileSize, (size_t)segInfo.sizeOfSections); SegmentMappingInfo loc; loc.srcSegment = (uint8_t*)dylib.input->mappedFile.mh + segInfo.vmAddr - textSegVmAddr; loc.segName = segInfo.segName; loc.dstSegment = nullptr; loc.dstCacheUnslidAddress = offsetInRegion; // This will be updated later once we've assigned addresses loc.dstCacheFileOffset = (uint32_t)offsetInRegion; loc.dstCacheSegmentSize = (uint32_t)segInfo.vmSize; loc.dstCacheFileSize = (uint32_t)copySize; loc.copySegmentSize = (uint32_t)copySize; loc.srcSegmentIndex = segInfo.segIndex; loc.parentRegion = &hibernateRegion; dylib.cacheLocation[segInfo.segIndex] = loc; offsetInRegion += loc.dstCacheSegmentSize; hibernateAddress = segInfo.vmAddr; }); // Only xnu has __HIB, so no need to continue once we've found it. break; } hibernateRegion.bufferSize = align(offsetInRegion, 14); hibernateRegion.sizeInUse = hibernateRegion.bufferSize; hibernateRegion.initProt = VM_PROT_READ | VM_PROT_WRITE | VM_PROT_EXECUTE; hibernateRegion.maxProt = VM_PROT_READ | VM_PROT_WRITE | VM_PROT_EXECUTE; hibernateRegion.name = "__HIB"; } // __TEXT and __DATA from non-split seg dylibs, if we have any { for (DylibInfo& dylib : sortedDylibs) { bool canBePacked = dylib.input->mappedFile.mh->hasSplitSeg(); if (canBePacked) continue; __block uint64_t textSegVmAddr = 0; dylib.input->mappedFile.mh->forEachSegment(^(const dyld3::MachOFile::SegmentInfo& segInfo, bool& stop) { if ( strcmp(segInfo.segName, "__TEXT") == 0 ) textSegVmAddr = segInfo.vmAddr; if ( strcmp(segInfo.segName, "__LINKEDIT") == 0 ) return; nonSplitSegRegions.emplace_back(); nonSplitSegRegions.back().initProt = segInfo.protections; nonSplitSegRegions.back().maxProt = segInfo.protections; nonSplitSegRegions.back().name = "__REGION" + std::to_string(nonSplitSegRegions.size() - 1); // Note we don't align the region offset as we have no split seg uint64_t offsetInRegion = 0; SegmentMappingInfo loc; loc.srcSegment = (uint8_t*)dylib.input->mappedFile.mh + segInfo.vmAddr - textSegVmAddr; loc.segName = segInfo.segName; loc.dstSegment = nullptr; loc.dstCacheUnslidAddress = offsetInRegion; // This will be updated later once we've assigned addresses loc.dstCacheFileOffset = (uint32_t)offsetInRegion; loc.dstCacheSegmentSize = (uint32_t)segInfo.vmSize; loc.dstCacheFileSize = (uint32_t)segInfo.fileSize; loc.copySegmentSize = (uint32_t)segInfo.fileSize; loc.srcSegmentIndex = segInfo.segIndex; loc.parentRegion = &nonSplitSegRegions.back(); dylib.cacheLocation[segInfo.segIndex] = loc; offsetInRegion += loc.dstCacheSegmentSize; // record non-split seg region end nonSplitSegRegions.back().bufferSize = offsetInRegion; nonSplitSegRegions.back().sizeInUse = nonSplitSegRegions.back().bufferSize; }); } } // -sectcreate if ( !customSegments.empty() ) { for (CustomSegment& segment: customSegments) { uint64_t offsetInRegion = 0; for (CustomSegment::CustomSection& section : segment.sections) { section.offsetInRegion = offsetInRegion; offsetInRegion += section.data.size(); } Region& customRegion = customDataRegions.emplace_back(); segment.parentRegion = &customRegion; // align region end customRegion.bufferSize = align(offsetInRegion, 14); customRegion.sizeInUse = customRegion.bufferSize; customRegion.initProt = VM_PROT_READ; customRegion.maxProt = VM_PROT_READ; customRegion.name = segment.segmentName; } } // __PRELINK_INFO { // This is populated with regular kexts and codeless kexts struct PrelinkInfo { CFDictionaryRef infoPlist = nullptr; const dyld3::MachOAnalyzer* ma = nullptr; std::string_view bundlePath; std::string_view executablePath; }; std::vector<PrelinkInfo> infos; for (AppCacheDylibInfo& dylib : sortedDylibs) { if (dylib.infoPlist == nullptr) continue; infos.push_back({ dylib.infoPlist, dylib.input->mappedFile.mh, dylib.bundlePath, dylib.input->loadedFileInfo.path }); } for (InputDylib& dylib : codelessKexts) { infos.push_back({ dylib.infoPlist, nullptr, dylib.bundlePath, "" }); } CFMutableArrayRef bundlesArrayRef = CFArrayCreateMutable(kCFAllocatorDefault, 0, &kCFTypeArrayCallBacks); for (PrelinkInfo& info : infos) { CFDictionaryRef infoPlist = info.infoPlist; // Create a copy of the dictionary so that we can add more fields CFMutableDictionaryRef dictCopyRef = CFDictionaryCreateMutableCopy(kCFAllocatorDefault, 0, infoPlist); // _PrelinkBundlePath CFStringRef bundlePath = CFStringCreateWithCStringNoCopy(kCFAllocatorDefault, info.bundlePath.data(), kCFStringEncodingASCII, kCFAllocatorNull); CFDictionarySetValue(dictCopyRef, CFSTR("_PrelinkBundlePath"), bundlePath); CFRelease(bundlePath); // Note we want this address to be a large enough integer in the xml format that we have enough space // to replace it with its real address later const uint64_t largeAddress = 0x7FFFFFFFFFFFFFFF; // _PrelinkExecutableLoadAddr // Leave a placeholder for this for now just so that we have enough space for it later CFNumberRef loadAddrRef = CFNumberCreate(kCFAllocatorDefault, kCFNumberLongLongType, &largeAddress); CFDictionarySetValue(dictCopyRef, CFSTR("_PrelinkExecutableLoadAddr"), loadAddrRef); CFRelease(loadAddrRef); // _PrelinkExecutableRelativePath if ( info.executablePath != "" ) { const char* relativePath = info.executablePath.data(); if ( strncmp(relativePath, info.bundlePath.data(), info.bundlePath.size()) == 0 ) { relativePath = relativePath + info.bundlePath.size(); if ( relativePath[0] == '/' ) ++relativePath; } else if ( const char* lastSlash = strrchr(relativePath, '/') ) relativePath = lastSlash+1; CFStringRef executablePath = CFStringCreateWithCStringNoCopy(kCFAllocatorDefault, relativePath, kCFStringEncodingASCII, kCFAllocatorNull); CFDictionarySetValue(dictCopyRef, CFSTR("_PrelinkExecutableRelativePath"), executablePath); CFRelease(executablePath); } // _PrelinkExecutableSize // This seems to be the file size of __TEXT __block uint64_t textSegFileSize = 0; if ( info.ma != nullptr ) { info.ma->forEachSegment(^(const dyld3::MachOFile::SegmentInfo& segInfo, bool& stop) { if ( strcmp(segInfo.segName, "__TEXT") == 0 ) textSegFileSize = segInfo.fileSize; }); } if (textSegFileSize != 0) { CFNumberRef fileSizeRef = CFNumberCreate(kCFAllocatorDefault, kCFNumberLongLongType, &textSegFileSize); CFDictionarySetValue(dictCopyRef, CFSTR("_PrelinkExecutableSize"), fileSizeRef); CFRelease(fileSizeRef); } // _PrelinkExecutableSourceAddr // Leave a placeholder for this for now just so that we have enough space for it later CFNumberRef sourceAddrRef = CFNumberCreate(kCFAllocatorDefault, kCFNumberLongLongType, &largeAddress); CFDictionarySetValue(dictCopyRef, CFSTR("_PrelinkExecutableSourceAddr"), sourceAddrRef); CFRelease(sourceAddrRef); // _PrelinkKmodInfo // Leave a placeholder for this for now just so that we have enough space for it later dyld3::MachOAnalyzer::FoundSymbol foundInfo; if ( (info.ma != nullptr) ) { // Check for a global first __block bool found = false; found = info.ma->findExportedSymbol(_diagnostics, "_kmod_info", true, foundInfo, nullptr); if ( !found ) { // And fall back to a local if we need to info.ma->forEachLocalSymbol(_diagnostics, ^(const char* aSymbolName, uint64_t n_value, uint8_t n_type, uint8_t n_sect, uint16_t n_desc, bool& stop) { if ( strcmp(aSymbolName, "_kmod_info") == 0 ) { found = true; stop = true; } }); } if ( found ) { CFNumberRef kmodInfoAddrRef = CFNumberCreate(kCFAllocatorDefault, kCFNumberLongLongType, &largeAddress); CFDictionarySetValue(dictCopyRef, CFSTR("_PrelinkKmodInfo"), kmodInfoAddrRef); CFRelease(kmodInfoAddrRef); } } CFArrayAppendValue(bundlesArrayRef, dictCopyRef); // Release the temporary dictionary now that its in the array CFRelease(dictCopyRef); } prelinkInfoDict = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); // First add any data from addPrelinkInfo() if ( extraPrelinkInfo != nullptr ) { CFDictionaryApplierFunction applier = [](const void *key, const void *value, void *context) { CFMutableDictionaryRef parentDict = (CFMutableDictionaryRef)context; CFDictionaryAddValue(parentDict, key, value); }; CFDictionaryApplyFunction(extraPrelinkInfo, applier, (void*)prelinkInfoDict); } if ( bundlesArrayRef != nullptr ) { CFDictionaryAddValue(prelinkInfoDict, CFSTR("_PrelinkInfoDictionary"), bundlesArrayRef); CFRelease(bundlesArrayRef); } // Add a placeholder for the collection UUID { uuid_t uuid = {}; CFDataRef dataRef = CFDataCreate(kCFAllocatorDefault, (const uint8_t*)&uuid, sizeof(uuid)); CFDictionaryAddValue(prelinkInfoDict, CFSTR("_PrelinkKCID"), dataRef); CFRelease(dataRef); } // The pageable/aux KCs should embed the UUID of the base kernel collection if ( existingKernelCollection != nullptr ) { uuid_t uuid = {}; bool foundUUID = existingKernelCollection->getUuid(uuid); if ( !foundUUID ) { _diagnostics.error("Could not find UUID in base kernel collection"); return; } CFDataRef dataRef = CFDataCreate(kCFAllocatorDefault, (const uint8_t*)&uuid, sizeof(uuid)); CFDictionaryAddValue(prelinkInfoDict, CFSTR("_BootKCID"), dataRef); CFRelease(dataRef); } // The aux KC should embed the UUID of the pageable kernel collection if we have one if ( pageableKernelCollection != nullptr ) { uuid_t uuid = {}; bool foundUUID = pageableKernelCollection->getUuid(uuid); if ( !foundUUID ) { _diagnostics.error("Could not find UUID in pageable kernel collection"); return; } CFDataRef dataRef = CFDataCreate(kCFAllocatorDefault, (const uint8_t*)&uuid, sizeof(uuid)); CFDictionaryAddValue(prelinkInfoDict, CFSTR("_PageableKCID"), dataRef); CFRelease(dataRef); } CFErrorRef errorRef = nullptr; CFDataRef xmlData = CFPropertyListCreateData(kCFAllocatorDefault, prelinkInfoDict, kCFPropertyListXMLFormat_v1_0, 0, &errorRef); if (errorRef != nullptr) { CFStringRef errorString = CFErrorCopyDescription(errorRef); _diagnostics.error("Could not serialise plist because :%s", CFStringGetCStringPtr(errorString, kCFStringEncodingASCII)); CFRelease(xmlData); CFRelease(errorRef); return; } else { CFIndex xmlDataLength = CFDataGetLength(xmlData); CFRelease(xmlData); // align region end prelinkInfoRegion.bufferSize = align(xmlDataLength, 14); prelinkInfoRegion.sizeInUse = prelinkInfoRegion.bufferSize; prelinkInfoRegion.initProt = VM_PROT_READ | VM_PROT_WRITE; prelinkInfoRegion.maxProt = VM_PROT_READ | VM_PROT_WRITE; prelinkInfoRegion.name = "__PRELINK_INFO"; } } // Do all __LINKINFO regardless of split seg _nonLinkEditReadOnlySize = 0; __block uint64_t offsetInRegion = 0; for (DylibInfo& dylib : sortedDylibs) { __block uint64_t textSegVmAddr = 0; dylib.input->mappedFile.mh->forEachSegment(^(const dyld3::MachOFile::SegmentInfo& segInfo, bool& stop) { if ( strcmp(segInfo.segName, "__TEXT") == 0 ) textSegVmAddr = segInfo.vmAddr; if ( segInfo.protections != VM_PROT_READ ) return; if ( strcmp(segInfo.segName, "__LINKINFO") != 0 ) return; // Keep segments 4K or more aligned offsetInRegion = align(offsetInRegion, std::max((int)segInfo.p2align, (int)12)); size_t copySize = std::min((size_t)segInfo.fileSize, (size_t)segInfo.sizeOfSections); SegmentMappingInfo loc; loc.srcSegment = (uint8_t*)dylib.input->mappedFile.mh + segInfo.vmAddr - textSegVmAddr; loc.segName = segInfo.segName; loc.dstSegment = nullptr; loc.dstCacheUnslidAddress = offsetInRegion; // This will be updated later once we've assigned addresses loc.dstCacheFileOffset = (uint32_t)offsetInRegion; loc.dstCacheSegmentSize = (uint32_t)align(segInfo.sizeOfSections, 12); loc.dstCacheFileSize = (uint32_t)copySize; loc.copySegmentSize = (uint32_t)copySize; loc.srcSegmentIndex = segInfo.segIndex; loc.parentRegion = &_readOnlyRegion; dylib.cacheLocation[segInfo.segIndex] = loc; offsetInRegion += loc.dstCacheSegmentSize; }); } // Align the end of the __LINKINFO offsetInRegion = align(offsetInRegion, 14); _nonLinkEditReadOnlySize = offsetInRegion; // Do all __LINKEDIT, regardless of split seg for (DylibInfo& dylib : sortedDylibs) { __block uint64_t textSegVmAddr = 0; dylib.input->mappedFile.mh->forEachSegment(^(const dyld3::MachOFile::SegmentInfo& segInfo, bool& stop) { if ( strcmp(segInfo.segName, "__TEXT") == 0 ) textSegVmAddr = segInfo.vmAddr; if ( segInfo.protections != VM_PROT_READ ) return; if ( strcmp(segInfo.segName, "__LINKEDIT") != 0 ) return; // Keep segments 4K or more aligned offsetInRegion = align(offsetInRegion, std::max((int)segInfo.p2align, (int)12)); size_t copySize = std::min((size_t)segInfo.fileSize, (size_t)segInfo.sizeOfSections); SegmentMappingInfo loc; loc.srcSegment = (uint8_t*)dylib.input->mappedFile.mh + segInfo.vmAddr - textSegVmAddr; loc.segName = segInfo.segName; loc.dstSegment = nullptr; loc.dstCacheUnslidAddress = offsetInRegion; // This will be updated later once we've assigned addresses loc.dstCacheFileOffset = (uint32_t)offsetInRegion; loc.dstCacheSegmentSize = (uint32_t)align(segInfo.sizeOfSections, 12); loc.dstCacheFileSize = (uint32_t)copySize; loc.copySegmentSize = (uint32_t)copySize; loc.srcSegmentIndex = segInfo.segIndex; loc.parentRegion = &_readOnlyRegion; dylib.cacheLocation[segInfo.segIndex] = loc; offsetInRegion += loc.dstCacheSegmentSize; }); } // align r/o region end _readOnlyRegion.bufferSize = align(offsetInRegion, 14); _readOnlyRegion.sizeInUse = _readOnlyRegion.bufferSize; _readOnlyRegion.initProt = VM_PROT_READ; _readOnlyRegion.maxProt = VM_PROT_READ; _readOnlyRegion.name = "__LINKEDIT"; // Add space in __LINKEDIT for chained fixups and classic relocs { // The pageableKC (and sometimes auxKC) has 1 LC_DYLD_CHAINED_FIXUPS per kext // while other KCs have 1 for the whole KC. // It also tracks each segment in each kext for chained fixups, not the segments on the KC itself __block uint64_t numSegmentsForChainedFixups = 0; uint64_t numChainedFixupHeaders = 0; if ( fixupsArePerKext() ) { for (DylibInfo& dylib : sortedDylibs) { dylib.input->mappedFile.mh->forEachSegment(^(const dyld3::MachOFile::SegmentInfo& segInfo, bool& stop) { ++numSegmentsForChainedFixups; }); } numChainedFixupHeaders = sortedDylibs.size(); // Branch stubs need fixups on the GOTs region. So add in a top-level chained fixup entry // and for now all the regions as we don't know what segment index the branch GOTs will be numSegmentsForChainedFixups += numRegions(); numChainedFixupHeaders++; } else { numSegmentsForChainedFixups = numRegions(); numChainedFixupHeaders = 1; } uint64_t numBytesForPageStarts = 0; if ( dataConstRegion.sizeInUse != 0 ) numBytesForPageStarts += sizeof(dyld_chained_starts_in_segment) + (sizeof(uint16_t) * numWritablePagesToFixup(dataConstRegion.bufferSize)); if ( branchGOTsRegion.bufferSize != 0 ) numBytesForPageStarts += sizeof(dyld_chained_starts_in_segment) + (sizeof(uint16_t) * numWritablePagesToFixup(branchGOTsRegion.bufferSize)); if ( readWriteRegion.sizeInUse != 0 ) numBytesForPageStarts += sizeof(dyld_chained_starts_in_segment) + (sizeof(uint16_t) * numWritablePagesToFixup(readWriteRegion.bufferSize)); if ( hibernateRegion.sizeInUse != 0 ) numBytesForPageStarts += sizeof(dyld_chained_starts_in_segment) + (sizeof(uint16_t) * numWritablePagesToFixup(hibernateRegion.bufferSize)); for (const Region& region : nonSplitSegRegions) { // Assume writable regions have fixups to emit // Note, third party kext's have __TEXT fixups, so assume all of these have fixups // LINKEDIT is already elsewhere numBytesForPageStarts += sizeof(dyld_chained_starts_in_segment) + (sizeof(uint16_t) * numWritablePagesToFixup(region.bufferSize)); } uint64_t numBytesForChainedFixups = 0; if ( numBytesForPageStarts != 0 ) { numBytesForChainedFixups = numBytesForPageStarts; numBytesForChainedFixups += sizeof(dyld_chained_fixups_header) * numChainedFixupHeaders; numBytesForChainedFixups += sizeof(dyld_chained_starts_in_image) * numChainedFixupHeaders; numBytesForChainedFixups += sizeof(uint32_t) * numSegmentsForChainedFixups; } __block uint64_t numBytesForClassicRelocs = 0; if ( appCacheOptions.cacheKind == Options::AppCacheKind::kernel ) { if ( const DylibInfo* dylib = getKernelStaticExecutableInputFile() ) { if ( dylib->input->mappedFile.mh->usesClassicRelocationsInKernelCollection() ) { dylib->input->mappedFile.mh->forEachRebase(_diagnostics, false, ^(uint64_t runtimeOffset, bool &stop) { numBytesForClassicRelocs += sizeof(relocation_info); }); } } } // align fixups region end if ( (numBytesForChainedFixups != 0) || (numBytesForClassicRelocs != 0) ) { uint64_t numBytes = align(numBytesForChainedFixups, 3) + align(numBytesForClassicRelocs, 3); fixupsSubRegion.bufferSize = align(numBytes, 14); fixupsSubRegion.sizeInUse = fixupsSubRegion.bufferSize; fixupsSubRegion.initProt = VM_PROT_READ; fixupsSubRegion.maxProt = VM_PROT_READ; fixupsSubRegion.name = "__FIXUPS"; } } } void AppCacheBuilder::assignSegmentAddresses() { // Segments already have offsets in to their regions. Now assign the regions their addresses // in the full allocated buffer, and then assign all segments in those regions for (DylibInfo& dylib : sortedDylibs) { for (SegmentMappingInfo& loc : dylib.cacheLocation) { loc.dstSegment = loc.parentRegion->buffer + loc.dstCacheFileOffset; loc.dstCacheUnslidAddress = loc.parentRegion->unslidLoadAddress + loc.dstCacheFileOffset; loc.dstCacheFileOffset = (uint32_t)loc.parentRegion->cacheFileOffset + loc.dstCacheFileOffset; } } } void AppCacheBuilder::copyRawSegments() { const bool log = false; // Call the base class to copy segment data CacheBuilder::copyRawSegments(); // The copy any custom sections for (const CustomSegment& segment : customSegments) { for (const CustomSegment::CustomSection& section : segment.sections) { uint8_t* dstBuffer = segment.parentRegion->buffer + section.offsetInRegion; uint64_t dstVMAddr = segment.parentRegion->unslidLoadAddress + section.offsetInRegion; if (log) fprintf(stderr, "copy %s segment %s %s (0x%08lX bytes) from %p to %p (logical addr 0x%llX)\n", _options.archs->name(), segment.segmentName.c_str(), section.sectionName.c_str(), section.data.size(), section.data.data(), dstBuffer, dstVMAddr); ::memcpy(dstBuffer, section.data.data(), section.data.size()); } } } static uint8_t getFixupLevel(AppCacheBuilder::Options::AppCacheKind kind) { uint8_t currentLevel = (uint8_t)~0U; switch (kind) { case AppCacheBuilder::Options::AppCacheKind::none: assert(0 && "Cache kind should have been set"); break; case AppCacheBuilder::Options::AppCacheKind::kernel: currentLevel = 0; break; case AppCacheBuilder::Options::AppCacheKind::pageableKC: // The pageableKC sits right above the baseKC which is level 0 currentLevel = 1; break; case AppCacheBuilder::Options::AppCacheKind::kernelCollectionLevel2: assert(0 && "Unimplemented"); break; case AppCacheBuilder::Options::AppCacheKind::auxKC: currentLevel = 3; break; } return currentLevel; } uint32_t AppCacheBuilder::getCurrentFixupLevel() const { return getFixupLevel(appCacheOptions.cacheKind); } struct VTableBindSymbol { std::string_view binaryID; std::string symbolName; }; // For every dylib, lets make a map from its exports to its defs struct DylibSymbols { // Define a bunch of constructors so that we know we are getting move constructors not copies DylibSymbols() = default; DylibSymbols(const DylibSymbols&) = delete; DylibSymbols(DylibSymbols&&) = default; DylibSymbols(std::map<std::string_view, uint64_t>&& globals, std::map<std::string_view, uint64_t>&& locals, std::unique_ptr<std::unordered_set<std::string>> kpiSymbols, uint32_t dylibLevel, const std::string& dylibName) : globals(std::move(globals)), locals(std::move(locals)), kpiSymbols(std::move(kpiSymbols)), dylibLevel(dylibLevel), dylibName(dylibName) { } DylibSymbols& operator=(const DylibSymbols& other) = delete; DylibSymbols& operator=(DylibSymbols&& other) = default; std::map<std::string_view, uint64_t> globals; // We also need to track locals as vtable patching supports patching with these too std::map<std::string_view, uint64_t> locals; // KPI (ie, a symbol set embedded in this binary) std::unique_ptr<std::unordered_set<std::string>> kpiSymbols; // Kernel collections can reference each other in levels. This is the level // of the exported dylib. Eg, the base KC is 0, and the aux KC is 3 uint32_t dylibLevel = 0; // Store the name of the dylib for fast lookups std::string dylibName; // Keep track of the binds in this dylib as these tell us if a vtable slot is to a local // or external definition of a function std::unordered_map<const uint8_t*, VTableBindSymbol> resolvedBindLocations; }; class VTablePatcher { public: VTablePatcher(uint32_t numFixupLevels); bool hasError() const; void addKernelCollection(const dyld3::MachOAppCache* cacheMA, AppCacheBuilder::Options::AppCacheKind kind, const uint8_t* basePointer, uint64_t baseAddress); void addDylib(Diagnostics& diags, const dyld3::MachOAnalyzer* ma, const std::string& dylibID, const std::vector<std::string>& dependencies, uint8_t cacheLevel); void findMetaclassDefinitions(std::map<std::string, DylibSymbols>& dylibsToSymbols, const std::string& kernelID, const dyld3::MachOAnalyzer* kernelMA, AppCacheBuilder::Options::AppCacheKind cacheKind); void findExistingFixups(Diagnostics& diags, const dyld3::MachOAppCache* existingKernelCollection, const dyld3::MachOAppCache* pageableKernelCollection); void findBaseKernelVTables(Diagnostics& diags, const dyld3::MachOAppCache* existingKernelCollection, std::map<std::string, DylibSymbols>& dylibsToSymbols); void findPageableKernelVTables(Diagnostics& diags, const dyld3::MachOAppCache* existingKernelCollection, std::map<std::string, DylibSymbols>& dylibsToSymbols); void findVTables(uint8_t currentLevel, const dyld3::MachOAnalyzer* kernelMA, std::map<std::string, DylibSymbols>& dylibsToSymbols, const AppCacheBuilder::ASLR_Tracker& aslrTracker, const std::map<const uint8_t*, const VTableBindSymbol>& missingBindLocations); void calculateSymbols(); void patchVTables(Diagnostics& diags, std::map<const uint8_t*, const VTableBindSymbol>& missingBindLocations, AppCacheBuilder::ASLR_Tracker& aslrTracker, uint8_t currentLevel); private: void logFunc(const char* format, ...) { if ( logPatching ) { va_list list; va_start(list, format); vfprintf(stderr, format, list); va_end(list); } }; void logFuncVerbose(const char* format, ...) { if ( logPatchingVerbose ) { va_list list; va_start(list, format); vfprintf(stderr, format, list); va_end(list); } }; // Extract a substring by dropping optional prefix/suffix std::string_view extractString(std::string_view str, std::string_view prefix, std::string_view suffix) { if ( !prefix.empty() ) { // Make sure we have the prefix we are looking for if ( str.find(prefix) != 0 ) { return std::string_view(); } str.remove_prefix(prefix.size()); } if ( !suffix.empty() ) { // Make sure we have the prefix we are looking for size_t pos = str.rfind(suffix); if ( pos != (str.size() - suffix.size()) ) { return std::string_view(); } str.remove_suffix(suffix.size()); } return str; }; struct VTable { struct Entry { const uint8_t* location = nullptr; uint64_t targetVMAddr = ~0ULL; uint32_t targetCacheLevel = ~0; // Pointer auth uint16_t diversity = 0; bool hasAddrDiv = false; uint8_t key = 0; bool hasPointerAuth = false; }; const dyld3::MachOAnalyzer* ma = nullptr; const uint8_t* superVTable = nullptr; const DylibSymbols* dylib = nullptr; bool fromParentCollection = false; bool patched = false; std::string name = ""; std::vector<Entry> entries; }; struct SymbolLocation { uint64_t vmAddr = 0; bool foundSymbol = 0; bool found() const { return foundSymbol; } }; struct Fixup { uint64_t targetVMAddr = 0; uint8_t cacheLevel = 0; // Pointer auth uint16_t diversity = 0; bool hasAddrDiv = false; uint8_t key = 0; bool hasPointerAuth = false; }; struct VTableDylib { Diagnostics* diags = nullptr; const dyld3::MachOAnalyzer* ma = nullptr; std::string dylibID = ""; std::vector<std::string> dependencies; uint32_t cacheLevel = ~0U; }; struct KernelCollection { const dyld3::MachOAppCache* ma = nullptr; // We need the base pointers to the buffers for every level // These are the base of the allocated memory, which corresponds to pointing to the lowest // vmAddr for the buffer. These do *not* necessarily point to a mach_header const uint8_t* basePointer = nullptr; // We also need the base vm addresses to the buffers for every level uint64_t baseAddress = ~0ULL; std::unordered_map<uint64_t, const char*> symbolNames; std::map<uint64_t, std::string_view> metaclassDefinitions; }; SymbolLocation findVTablePatchingSymbol(std::string_view symbolName, const DylibSymbols& dylibSymbols); std::vector<VTableDylib> dylibs; std::map<const uint8_t*, VTable> vtables; std::vector<KernelCollection> collections; const uint8_t* baseMetaClassVTableLoc = nullptr; // Record all the fixup locations in the base/pageable KCs as we need to use them instead of the ASLR tracker std::map<const uint8_t*, Fixup> existingCollectionFixupLocations; const uint32_t pointerSize = 8; const bool logPatching = false; const bool logPatchingVerbose = false; // Magic constants for vtable patching //const char* cxxPrefix = "__Z"; const char* vtablePrefix = "__ZTV"; const char* osObjPrefix = "__ZN"; // const char* vtableReservedToken = "_RESERVED"; const char* metaclassToken = "10gMetaClassE"; const char* superMetaclassPointerToken = "10superClassE"; const char* metaclassVTablePrefix = "__ZTVN"; const char* metaclassVTableSuffix = "9MetaClassE"; }; VTablePatcher::VTablePatcher(uint32_t numFixupLevels) { collections.resize(numFixupLevels); } bool VTablePatcher::hasError() const { for (const VTableDylib& dylib : dylibs) { if ( dylib.diags->hasError() ) return true; } return false; } void VTablePatcher::addKernelCollection(const dyld3::MachOAppCache* cacheMA, AppCacheBuilder::Options::AppCacheKind kind, const uint8_t* basePointer, uint64_t baseAddress) { uint8_t cacheLevel = getFixupLevel(kind); assert(cacheLevel < collections.size()); assert(collections[cacheLevel].ma == nullptr); collections[cacheLevel].ma = cacheMA; collections[cacheLevel].basePointer = basePointer; collections[cacheLevel].baseAddress = baseAddress; } void VTablePatcher::addDylib(Diagnostics &diags, const dyld3::MachOAnalyzer *ma, const std::string& dylibID, const std::vector<std::string>& dependencies, uint8_t cacheLevel) { dylibs.push_back((VTableDylib){ &diags, ma, dylibID, dependencies, cacheLevel }); } VTablePatcher::SymbolLocation VTablePatcher::findVTablePatchingSymbol(std::string_view symbolName, const DylibSymbols& dylibSymbols) { // First look in the globals auto globalsIt = dylibSymbols.globals.find(symbolName); if ( globalsIt != dylibSymbols.globals.end() ) { return { globalsIt->second, true }; } // Then again in the locals auto localsIt = dylibSymbols.locals.find(symbolName); if ( localsIt != dylibSymbols.locals.end() ) { return { localsIt->second, true }; } return { ~0ULL, false }; }; void VTablePatcher::findMetaclassDefinitions(std::map<std::string, DylibSymbols>& dylibsToSymbols, const std::string& kernelID, const dyld3::MachOAnalyzer* kernelMA, AppCacheBuilder::Options::AppCacheKind cacheKind) { for (VTableDylib& dylib : dylibs) { auto& metaclassDefinitions = collections[dylib.cacheLevel].metaclassDefinitions; dylib.ma->forEachGlobalSymbol(*dylib.diags, ^(const char *symbolName, uint64_t n_value, uint8_t n_type, uint8_t n_sect, uint16_t n_desc, bool &stop) { if ( strstr(symbolName, metaclassToken) != nullptr ) metaclassDefinitions[n_value] = symbolName; }); dylib.ma->forEachLocalSymbol(*dylib.diags, ^(const char *symbolName, uint64_t n_value, uint8_t n_type, uint8_t n_sect, uint16_t n_desc, bool &stop) { if ( strstr(symbolName, metaclassToken) != nullptr ) metaclassDefinitions[n_value] = symbolName; }); } // Keep track of the root OSMetaClass from which all other metaclasses inherit DylibSymbols& kernelDylibSymbols = dylibsToSymbols[kernelID]; SymbolLocation symbolLocation = findVTablePatchingSymbol("__ZTV11OSMetaClass", kernelDylibSymbols); if ( symbolLocation.found() ) { baseMetaClassVTableLoc = (uint8_t*)kernelMA + (symbolLocation.vmAddr - kernelMA->preferredLoadAddress()); VTable& vtable = vtables[baseMetaClassVTableLoc]; vtable.ma = kernelMA; vtable.dylib = &kernelDylibSymbols; vtable.fromParentCollection = (cacheKind != AppCacheBuilder::Options::AppCacheKind::kernel); vtable.patched = true; vtable.name = "__ZTV11OSMetaClass"; } } void VTablePatcher::findExistingFixups(Diagnostics& diags, const dyld3::MachOAppCache* existingKernelCollection, const dyld3::MachOAppCache* pageableKernelCollection) { const bool is64 = pointerSize == 8; if ( existingKernelCollection != nullptr ) { uint8_t kernelLevel = getFixupLevel(AppCacheBuilder::Options::AppCacheKind::kernel); uint64_t kernelBaseAddress = collections[kernelLevel].baseAddress; const uint8_t* kernelBasePointer = collections[kernelLevel].basePointer; // We may have both chained and classic fixups. First add chained if ( existingKernelCollection->hasChainedFixupsLoadCommand() ) { existingKernelCollection->withChainStarts(diags, 0, ^(const dyld_chained_starts_in_image* starts) { existingKernelCollection->forEachFixupInAllChains(diags, starts, false, ^(dyld3::MachOLoaded::ChainedFixupPointerOnDisk* fixupLoc, const dyld_chained_starts_in_segment* segInfo, bool& stop) { uint64_t vmOffset = 0; bool isRebase = fixupLoc->isRebase(segInfo->pointer_format, kernelBaseAddress, vmOffset); assert(isRebase); uint64_t targetVMAddr = kernelBaseAddress + vmOffset; uint16_t diversity = fixupLoc->kernel64.diversity; bool hasAddrDiv = fixupLoc->kernel64.addrDiv; uint8_t key = fixupLoc->kernel64.key; bool hasPointerAuth = fixupLoc->kernel64.isAuth; existingCollectionFixupLocations[(const uint8_t*)fixupLoc] = { targetVMAddr, kernelLevel, diversity, hasAddrDiv, key, hasPointerAuth }; }); }); } // And add classic if we have them existingKernelCollection->forEachRebase(diags, ^(const char *opcodeName, const dyld3::MachOAnalyzer::LinkEditInfo &leInfo, const dyld3::MachOAnalyzer::SegmentInfo *segments, bool segIndexSet, uint32_t ptrSize, uint8_t segmentIndex, uint64_t segmentOffset, dyld3::MachOAnalyzer::Rebase kind, bool &stop) { uint64_t rebaseVmAddr = segments[segmentIndex].vmAddr + segmentOffset; uint64_t runtimeOffset = rebaseVmAddr - kernelBaseAddress; const uint8_t* fixupLoc = kernelBasePointer + runtimeOffset; uint64_t targetVMAddr = 0; if ( is64 ) { targetVMAddr = *(uint64_t*)fixupLoc; } else { targetVMAddr = *(uint32_t*)fixupLoc; } // Classic relocs have no pointer auth uint16_t diversity = 0; bool hasAddrDiv = false; uint8_t key = 0; bool hasPointerAuth = false; existingCollectionFixupLocations[(const uint8_t*)fixupLoc] = { targetVMAddr, kernelLevel, diversity, hasAddrDiv, key, hasPointerAuth }; }); } // Add pageable fixup locations if we have it if ( pageableKernelCollection != nullptr ) { // We only have chained fixups here to add, but they are on each kext, not on the KC itself pageableKernelCollection->forEachDylib(diags, ^(const dyld3::MachOAnalyzer *ma, const char *name, bool &stop) { // Skip kexts without fixups if ( !ma->hasChainedFixupsLoadCommand() ) return; ma->withChainStarts(diags, 0, ^(const dyld_chained_starts_in_image* starts) { ma->forEachFixupInAllChains(diags, starts, false, ^(dyld3::MachOLoaded::ChainedFixupPointerOnDisk* fixupLoc, const dyld_chained_starts_in_segment* segInfo, bool& stopFixups) { uint64_t vmOffset = 0; bool isRebase = fixupLoc->isRebase(DYLD_CHAINED_PTR_64_KERNEL_CACHE, 0, vmOffset); assert(isRebase); uint8_t targetFixupLevel = fixupLoc->kernel64.cacheLevel; uint64_t targetVMAddr = collections[targetFixupLevel].baseAddress + vmOffset; uint16_t diversity = fixupLoc->kernel64.diversity; bool hasAddrDiv = fixupLoc->kernel64.addrDiv; uint8_t key = fixupLoc->kernel64.key; bool hasPointerAuth = fixupLoc->kernel64.isAuth; existingCollectionFixupLocations[(const uint8_t*)fixupLoc] = { targetVMAddr, targetFixupLevel, diversity, hasAddrDiv, key, hasPointerAuth }; }); }); }); } } void VTablePatcher::findBaseKernelVTables(Diagnostics& diags, const dyld3::MachOAppCache* existingKernelCollection, std::map<std::string, DylibSymbols>& dylibsToSymbols) { const bool is64 = pointerSize == 8; uint8_t kernelLevel = getFixupLevel(AppCacheBuilder::Options::AppCacheKind::kernel); uint64_t kernelBaseAddress = collections[kernelLevel].baseAddress; const uint8_t* kernelBasePointer = collections[kernelLevel].basePointer; uint16_t chainedPointerFormat = 0; if ( existingKernelCollection->hasChainedFixupsLoadCommand() ) chainedPointerFormat = existingKernelCollection->chainedPointerFormat(); // Map from dylibID to list of dependencies std::map<std::string, const std::vector<std::string>*> kextDependencies; for (VTableDylib& dylib : dylibs) { if ( dylib.cacheLevel != kernelLevel ) continue; kextDependencies[dylib.dylibID] = &dylib.dependencies; } bool kernelUsesClassicRelocs = existingKernelCollection->usesClassicRelocationsInKernelCollection(); existingKernelCollection->forEachDylib(diags, ^(const dyld3::MachOAnalyzer *ma, const char *dylibID, bool &stop) { uint64_t loadAddress = ma->preferredLoadAddress(); auto visitBaseKernelCollectionSymbols = ^(const char *symbolName, uint64_t n_value) { if ( strstr(symbolName, superMetaclassPointerToken) == nullptr ) return; uint8_t* fixupLoc = (uint8_t*)ma + (n_value - loadAddress); logFunc("Found superclass pointer with name '%s' in '%s' at %p\n", symbolName, dylibID, fixupLoc); // 2 - Derive the name of the class from the super MetaClass pointer. std::string_view className = extractString(symbolName, osObjPrefix, superMetaclassPointerToken); // If the string isn't prefixed/suffixed appropriately, then give up on this one if ( className.empty() ) { logFunc("Unsupported vtable superclass name\n"); return; } logFunc("Class name: '%s'\n", std::string(className).c_str()); // 3 - Derive the name of the class's vtable from the name of the class // We support namespaces too which means adding an N before the class name and E after std::string classVTableName = std::string(vtablePrefix) + std::string(className); logFunc("Class vtable name: '%s'\n", classVTableName.c_str()); uint64_t classVTableVMAddr = 0; const DylibSymbols& dylibSymbols = dylibsToSymbols[dylibID]; { std::string namespacedVTableName; SymbolLocation symbolLocation = findVTablePatchingSymbol(classVTableName, dylibSymbols); if ( !symbolLocation.found() ) { // If we didn't find a name then try again with namespaces namespacedVTableName = std::string(vtablePrefix) + "N" + std::string(className) + "E"; logFunc("Class namespaced vtable name: '%s'\n", namespacedVTableName.c_str()); symbolLocation = findVTablePatchingSymbol(namespacedVTableName, dylibSymbols); } if ( symbolLocation.found() ) { classVTableVMAddr = symbolLocation.vmAddr; } else { diags.error("Class vtables '%s' or '%s' is not exported from '%s'", classVTableName.c_str(), namespacedVTableName.c_str(), dylibID); stop = true; return; } } logFunc("Class vtable vmAddr: '0x%llx'\n", classVTableVMAddr); const uint8_t* classVTableLoc = kernelBasePointer + (classVTableVMAddr - kernelBaseAddress); // 4 - Follow the super MetaClass pointer to get the address of the super MetaClass's symbol uint64_t superMetaclassSymbolAddress = 0; auto existingKernelCollectionFixupLocIt = existingCollectionFixupLocations.find(fixupLoc); if ( existingKernelCollectionFixupLocIt != existingCollectionFixupLocations.end() ) { if ( ma->isKextBundle() || !kernelUsesClassicRelocs ) { auto* chainedFixupLoc = (dyld3::MachOLoaded::ChainedFixupPointerOnDisk*)fixupLoc; uint64_t vmOffset = 0; bool isRebase = chainedFixupLoc->isRebase(chainedPointerFormat, kernelBaseAddress, vmOffset); assert(isRebase); superMetaclassSymbolAddress = kernelBaseAddress + vmOffset; } else { // The classic reloc is already the vmAddr so nothing special to do here. assert(is64); superMetaclassSymbolAddress = *(uint64_t*)fixupLoc; } } logFunc("Super MetaClass's symbol address: '0x%llx'\n", superMetaclassSymbolAddress); if ( superMetaclassSymbolAddress == 0 ) { if ( classVTableName == "__ZTV8OSObject" ) { // This is the base class of all objects, so it doesn't have a super class // We add it as a placeholder and set it to 'true' to show its already been processed VTable& vtable = vtables[classVTableLoc]; vtable.ma = ma; vtable.dylib = &dylibSymbols; vtable.fromParentCollection = true; vtable.patched = true; vtable.name = classVTableName; return; } } // 5 - Look up the super MetaClass symbol by address // FIXME: VTable patching the auxKC with the superclass in the baseKC uint8_t superclassFixupLevel = kernelLevel; auto& metaclassDefinitions = collections[superclassFixupLevel].metaclassDefinitions; auto metaclassIt = metaclassDefinitions.find(superMetaclassSymbolAddress); if ( metaclassIt == metaclassDefinitions.end() ) { diags.error("Cannot find symbol for metaclass pointed to by '%s' in '%s'", symbolName, dylibID); stop = true; return; } // 6 - Derive the super class's name from the super MetaClass name std::string_view superClassName = extractString(metaclassIt->second, osObjPrefix, metaclassToken); // If the string isn't prefixed/suffixed appropriately, then give up on this one if ( superClassName.empty() ) { logFunc("Unsupported vtable superclass name\n"); return; } logFunc("Superclass name: '%s'\n", std::string(superClassName).c_str()); // 7 - Derive the super class's vtable from the super class's name std::string superclassVTableName = std::string(vtablePrefix) + std::string(superClassName); // We support namespaces, so first try the superclass without the namespace, then again with it const uint8_t* superclassVTableLoc = nullptr; for (unsigned i = 0; i != 2; ++i) { if ( i == 1 ) { superclassVTableName = std::string(vtablePrefix) + + "N" + std::string(superClassName) + "E"; } logFunc("Superclass vtable name: '%s'\n", superclassVTableName.c_str()); if ( ma->isKextBundle() ) { // First check if the superclass vtable comes from a dependent kext auto it = kextDependencies.find(dylibID); assert(it != kextDependencies.end()); const std::vector<std::string>& dependencies = *it->second; for (const std::string& dependencyID : dependencies) { auto depIt = dylibsToSymbols.find(dependencyID); if (depIt == dylibsToSymbols.end()) { diags.error("Failed to bind '%s' in '%s' as could not find a kext with '%s' bundle-id", symbolName, dylibID, dependencyID.c_str()); stop = true; return; } const DylibSymbols& depDylibSymbols = depIt->second; SymbolLocation symbolLocation = findVTablePatchingSymbol(superclassVTableName, depDylibSymbols); if ( !symbolLocation.found() ) continue; uint64_t superclassVTableVMAddr = symbolLocation.vmAddr; logFunc("Superclass vtable vmAddr: '0x%llx'\n", superclassVTableVMAddr); superclassVTableLoc = collections[depDylibSymbols.dylibLevel].basePointer + (superclassVTableVMAddr - collections[depDylibSymbols.dylibLevel].baseAddress); break; } } if ( superclassVTableLoc == nullptr ) { auto depIt = dylibsToSymbols.find(dylibID); if (depIt == dylibsToSymbols.end()) { diags.error("Failed to bind '%s' in '%s' as could not find a binary with '%s' bundle-id", symbolName, dylibID, dylibID); stop = true; return; } const DylibSymbols& depDylibSymbols = depIt->second; SymbolLocation symbolLocation = findVTablePatchingSymbol(superclassVTableName, depDylibSymbols); if ( symbolLocation.found() ) { uint64_t superclassVTableVMAddr = symbolLocation.vmAddr; logFunc("Superclass vtable vmAddr: '0x%llx'\n", superclassVTableVMAddr); superclassVTableLoc = collections[depDylibSymbols.dylibLevel].basePointer + (superclassVTableVMAddr - collections[depDylibSymbols.dylibLevel].baseAddress); } } if ( superclassVTableLoc != nullptr ) break; } if ( superclassVTableLoc == nullptr ) { superclassVTableName = std::string(vtablePrefix) + std::string(superClassName); diags.error("Superclass vtable '%s' is not exported from '%s' or its dependencies", superclassVTableName.c_str(), dylibID); stop = true; return; } // Add an entry for this vtable VTable& vtable = vtables[classVTableLoc]; vtable.superVTable = superclassVTableLoc; vtable.ma = ma; vtable.dylib = &dylibSymbols; vtable.fromParentCollection = true; vtable.patched = true; vtable.name = classVTableName; // And an entry for the superclass vtable VTable& supervtable = vtables[superclassVTableLoc]; supervtable.fromParentCollection = true; supervtable.patched = true; supervtable.name = superclassVTableName; }; ma->forEachGlobalSymbol(diags, ^(const char *symbolName, uint64_t n_value, uint8_t n_type, uint8_t n_sect, uint16_t n_desc, bool &stopSymbols) { visitBaseKernelCollectionSymbols(symbolName, n_value); }); if ( diags.hasError() ) { stop = true; return; } ma->forEachLocalSymbol(diags, ^(const char *symbolName, uint64_t n_value, uint8_t n_type, uint8_t n_sect, uint16_t n_desc, bool &stopSymbols) { visitBaseKernelCollectionSymbols(symbolName, n_value); }); if ( diags.hasError() ) { stop = true; return; } }); } void VTablePatcher::findPageableKernelVTables(Diagnostics& diags, const dyld3::MachOAppCache* pageableKernelCollection, std::map<std::string, DylibSymbols>& dylibsToSymbols) { uint8_t collectionLevel = getFixupLevel(AppCacheBuilder::Options::AppCacheKind::pageableKC); uint64_t collectionBaseAddress = collections[collectionLevel].baseAddress; const uint8_t* collectionBasePointer = collections[collectionLevel].basePointer; // Map from dylibID to list of dependencies std::map<std::string, const std::vector<std::string>*> kextDependencies; for (VTableDylib& dylib : dylibs) { if ( dylib.cacheLevel != collectionLevel ) continue; kextDependencies[dylib.dylibID] = &dylib.dependencies; } pageableKernelCollection->forEachDylib(diags, ^(const dyld3::MachOAnalyzer *ma, const char *dylibID, bool &stop) { uint64_t loadAddress = ma->preferredLoadAddress(); auto visitPageableKernelCollectionSymbols = ^(const char *symbolName, uint64_t n_value) { if ( strstr(symbolName, superMetaclassPointerToken) == nullptr ) return; uint8_t* fixupLoc = (uint8_t*)ma + (n_value - loadAddress); logFunc("Found superclass pointer with name '%s' in '%s' at %p\n", symbolName, dylibID, fixupLoc); // 2 - Derive the name of the class from the super MetaClass pointer. std::string_view className = extractString(symbolName, osObjPrefix, superMetaclassPointerToken); // If the string isn't prefixed/suffixed appropriately, then give up on this one if ( className.empty() ) { logFunc("Unsupported vtable superclass name\n"); return; } logFunc("Class name: '%s'\n", std::string(className).c_str()); // 3 - Derive the name of the class's vtable from the name of the class // We support namespaces too which means adding an N before the class name and E after std::string classVTableName = std::string(vtablePrefix) + std::string(className); logFunc("Class vtable name: '%s'\n", classVTableName.c_str()); uint64_t classVTableVMAddr = 0; const DylibSymbols& dylibSymbols = dylibsToSymbols[dylibID]; { std::string namespacedVTableName; SymbolLocation symbolLocation = findVTablePatchingSymbol(classVTableName, dylibSymbols); if ( !symbolLocation.found() ) { // If we didn't find a name then try again with namespaces namespacedVTableName = std::string(vtablePrefix) + "N" + std::string(className) + "E"; logFunc("Class namespaced vtable name: '%s'\n", namespacedVTableName.c_str()); symbolLocation = findVTablePatchingSymbol(namespacedVTableName, dylibSymbols); } if ( symbolLocation.found() ) { classVTableVMAddr = symbolLocation.vmAddr; } else { diags.error("Class vtables '%s' or '%s' is not exported from '%s'", classVTableName.c_str(), namespacedVTableName.c_str(), dylibID); stop = true; return; } } logFunc("Class vtable vmAddr: '0x%llx'\n", classVTableVMAddr); const uint8_t* classVTableLoc = collectionBasePointer + (classVTableVMAddr - collectionBaseAddress); // 4 - Follow the super MetaClass pointer to get the address of the super MetaClass's symbol uint8_t superclassFixupLevel = (uint8_t)~0U; uint64_t superMetaclassSymbolAddress = 0; auto existingKernelCollectionFixupLocIt = existingCollectionFixupLocations.find(fixupLoc); if ( existingKernelCollectionFixupLocIt != existingCollectionFixupLocations.end() ) { auto* chainedFixupLoc = (dyld3::MachOLoaded::ChainedFixupPointerOnDisk*)fixupLoc; uint64_t vmOffset = 0; bool isRebase = chainedFixupLoc->isRebase(DYLD_CHAINED_PTR_64_KERNEL_CACHE, 0, vmOffset); assert(isRebase); // The superclass could be in the baseKC, while we are analysing the pageableKC, so we need to get the correct level // from the fixup superclassFixupLevel = chainedFixupLoc->kernel64.cacheLevel; superMetaclassSymbolAddress = collections[superclassFixupLevel].baseAddress + vmOffset; } logFunc("Super MetaClass's symbol address: '0x%llx'\n", superMetaclassSymbolAddress); if ( superMetaclassSymbolAddress == 0 ) { if ( classVTableName == "__ZTV8OSObject" ) { // This is the base class of all objects, so it doesn't have a super class // We add it as a placeholder and set it to 'true' to show its already been processed VTable& vtable = vtables[classVTableLoc]; vtable.ma = ma; vtable.dylib = &dylibSymbols; vtable.fromParentCollection = true; vtable.patched = true; vtable.name = classVTableName; return; } } // 5 - Look up the super MetaClass symbol by address auto& metaclassDefinitions = collections[superclassFixupLevel].metaclassDefinitions; auto metaclassIt = metaclassDefinitions.find(superMetaclassSymbolAddress); if ( metaclassIt == metaclassDefinitions.end() ) { diags.error("Cannot find symbol for metaclass pointed to by '%s' in '%s'", symbolName, dylibID); stop = true; return; } // 6 - Derive the super class's name from the super MetaClass name std::string_view superClassName = extractString(metaclassIt->second, osObjPrefix, metaclassToken); // If the string isn't prefixed/suffixed appropriately, then give up on this one if ( superClassName.empty() ) { logFunc("Unsupported vtable superclass name\n"); return; } logFunc("Superclass name: '%s'\n", std::string(superClassName).c_str()); // 7 - Derive the super class's vtable from the super class's name std::string superclassVTableName = std::string(vtablePrefix) + std::string(superClassName); // We support namespaces, so first try the superclass without the namespace, then again with it const uint8_t* superclassVTableLoc = nullptr; for (unsigned i = 0; i != 2; ++i) { if ( i == 1 ) { superclassVTableName = std::string(vtablePrefix) + + "N" + std::string(superClassName) + "E"; } logFunc("Superclass vtable name: '%s'\n", superclassVTableName.c_str()); if ( ma->isKextBundle() ) { // First check if the superclass vtable comes from a dependent kext auto it = kextDependencies.find(dylibID); assert(it != kextDependencies.end()); const std::vector<std::string>& dependencies = *it->second; for (const std::string& dependencyID : dependencies) { auto depIt = dylibsToSymbols.find(dependencyID); if (depIt == dylibsToSymbols.end()) { diags.error("Failed to bind '%s' in '%s' as could not find a kext with '%s' bundle-id", symbolName, dylibID, dependencyID.c_str()); stop = true; return; } const DylibSymbols& depDylibSymbols = depIt->second; SymbolLocation symbolLocation = findVTablePatchingSymbol(superclassVTableName, depDylibSymbols); if ( !symbolLocation.found() ) continue; uint64_t superclassVTableVMAddr = symbolLocation.vmAddr; logFunc("Superclass vtable vmAddr: '0x%llx'\n", superclassVTableVMAddr); superclassVTableLoc = collections[depDylibSymbols.dylibLevel].basePointer + (superclassVTableVMAddr - collections[depDylibSymbols.dylibLevel].baseAddress); break; } } if ( superclassVTableLoc == nullptr ) { auto depIt = dylibsToSymbols.find(dylibID); if (depIt == dylibsToSymbols.end()) { diags.error("Failed to bind '%s' in '%s' as could not find a binary with '%s' bundle-id", symbolName, dylibID, dylibID); stop = true; return; } const DylibSymbols& depDylibSymbols = depIt->second; SymbolLocation symbolLocation = findVTablePatchingSymbol(superclassVTableName, depDylibSymbols); if ( symbolLocation.found() ) { uint64_t superclassVTableVMAddr = symbolLocation.vmAddr; logFunc("Superclass vtable vmAddr: '0x%llx'\n", superclassVTableVMAddr); superclassVTableLoc = collections[depDylibSymbols.dylibLevel].basePointer + (superclassVTableVMAddr - collections[depDylibSymbols.dylibLevel].baseAddress); } } if ( superclassVTableLoc != nullptr ) break; } if ( superclassVTableLoc == nullptr ) { superclassVTableName = std::string(vtablePrefix) + std::string(superClassName); diags.error("Superclass vtable '%s' is not exported from '%s' or its dependencies", superclassVTableName.c_str(), dylibID); stop = true; return; } // Add an entry for this vtable VTable& vtable = vtables[classVTableLoc]; vtable.superVTable = superclassVTableLoc; vtable.ma = ma; vtable.dylib = &dylibSymbols; vtable.fromParentCollection = true; vtable.patched = true; vtable.name = classVTableName; // And an entry for the superclass vtable VTable& supervtable = vtables[superclassVTableLoc]; supervtable.fromParentCollection = true; supervtable.patched = true; supervtable.name = superclassVTableName; }; ma->forEachGlobalSymbol(diags, ^(const char *symbolName, uint64_t n_value, uint8_t n_type, uint8_t n_sect, uint16_t n_desc, bool &stopSymbols) { visitPageableKernelCollectionSymbols(symbolName, n_value); }); if ( diags.hasError() ) { stop = true; return; } ma->forEachLocalSymbol(diags, ^(const char *symbolName, uint64_t n_value, uint8_t n_type, uint8_t n_sect, uint16_t n_desc, bool &stopSymbols) { visitPageableKernelCollectionSymbols(symbolName, n_value); }); if ( diags.hasError() ) { stop = true; return; } }); } void VTablePatcher::findVTables(uint8_t currentLevel, const dyld3::MachOAnalyzer* kernelMA, std::map<std::string, DylibSymbols>& dylibsToSymbols, const AppCacheBuilder::ASLR_Tracker& aslrTracker, const std::map<const uint8_t*, const VTableBindSymbol>& missingBindLocations) { const bool is64 = pointerSize == 8; uint64_t collectionBaseAddress = collections[currentLevel].baseAddress; const uint8_t* collectionBasePointer = collections[currentLevel].basePointer; // VTable patching algorithm (for each symbol...): // - To find the address of a class vtable: // - Take symbols with '10superClassE' in their name, eg, __ZN10IOMachPort10superClassE // - Work out the name of the class from that symbol name, eg, 10IOMachPort // - Work out the name of the VTable from that class name, eg, __ZTV10IOMachPort // - Find the address for the export with that vtable name // - To find the superclass for a given class // - Take the symbol with '10superClassE' in their name, eg, __ZN10IOMachPort10superClassE // - Take its address and dereference it as "__ZN10IOMachPort10superClassE = &__ZN8OSObject10gMetaClassE" // - Find the name of the symbol at this address, eg, work out we have a symbol called __ZN8OSObject10gMetaClassE // - Get the superclassic from that symbol name, eg, 8OSObject // - Get the VTable name from that symbol, eg, __ZTV8OSObject // - Find the superclass vtable address from that name by searching the image and dependents for __ZTV8OSObject for (VTableDylib& dylib : dylibs) { // Only process dylibs in the level we are building // Existing collections were handled elsewhere if ( dylib.cacheLevel != currentLevel ) continue; const dyld3::MachOAnalyzer* ma = dylib.ma; const std::string& dylibID = dylib.dylibID; Diagnostics& dylibDiags = *dylib.diags; const std::vector<std::string>& dependencies = dylib.dependencies; uint64_t loadAddress = ma->preferredLoadAddress(); bool alreadyPatched = (ma == kernelMA); auto visitSymbols = ^(const char *symbolName, uint64_t n_value) { if ( strstr(symbolName, superMetaclassPointerToken) == nullptr ) return; uint8_t* fixupLoc = (uint8_t*)ma + (n_value - loadAddress); logFunc("Found superclass pointer with name '%s' in '%s' at %p\n", symbolName, dylibID.c_str(), fixupLoc); // 2 - Derive the name of the class from the super MetaClass pointer. std::string_view className = extractString(symbolName, osObjPrefix, superMetaclassPointerToken); // If the string isn't prefixed/suffixed appropriately, then give up on this one if ( className.empty() ) { logFunc("Unsupported vtable superclass name\n"); return; } logFunc("Class name: '%s'\n", std::string(className).c_str()); // 3 - Derive the name of the class's vtable from the name of the class // We support namespaces too which means adding an N before the class name and E after std::string classVTableName = std::string(vtablePrefix) + std::string(className); logFunc("Class vtable name: '%s'\n", classVTableName.c_str()); uint64_t classVTableVMAddr = 0; const DylibSymbols& dylibSymbols = dylibsToSymbols[dylibID]; { std::string namespacedVTableName; SymbolLocation symbolLocation = findVTablePatchingSymbol(classVTableName, dylibSymbols); if ( !symbolLocation.found() ) { // If we didn't find a name then try again with namespaces namespacedVTableName = std::string(vtablePrefix) + "N" + std::string(className) + "E"; logFunc("Class namespaced vtable name: '%s'\n", namespacedVTableName.c_str()); symbolLocation = findVTablePatchingSymbol(namespacedVTableName, dylibSymbols); } if ( symbolLocation.found() ) { classVTableVMAddr = symbolLocation.vmAddr; } else { dylibDiags.error("Class vtables '%s' or '%s' is not an exported symbol", classVTableName.c_str(), namespacedVTableName.c_str()); return; } } logFunc("Class vtable vmAddr: '0x%llx'\n", classVTableVMAddr); const uint8_t* classVTableLoc = (uint8_t*)ma + (classVTableVMAddr - loadAddress); // 4 - Follow the super MetaClass pointer to get the address of the super MetaClass's symbol uint64_t superMetaclassSymbolAddress = 0; { uint32_t vmAddr32 = 0; uint64_t vmAddr64 = 0; if ( aslrTracker.hasRebaseTarget32(fixupLoc, &vmAddr32) ) { superMetaclassSymbolAddress = vmAddr32; } else if ( aslrTracker.hasRebaseTarget64(fixupLoc, &vmAddr64) ) { superMetaclassSymbolAddress = vmAddr64; } else { assert(is64); superMetaclassSymbolAddress = *(uint64_t*)fixupLoc; } uint8_t highByte = 0; if ( aslrTracker.hasHigh8(fixupLoc, &highByte) ) { uint64_t tbi = (uint64_t)highByte << 56; superMetaclassSymbolAddress |= tbi; } } logFunc("Super MetaClass's symbol address: '0x%llx'\n", superMetaclassSymbolAddress); if ( superMetaclassSymbolAddress == 0 ) { if ( classVTableName == "__ZTV8OSObject" ) { // This is the base class of all objects, so it doesn't have a super class // We add it as a placeholder and set it to 'true' to show its already been processed VTable& vtable = vtables[classVTableLoc]; vtable.ma = ma; vtable.dylib = &dylibSymbols; vtable.fromParentCollection = false; vtable.patched = true; vtable.name = classVTableName; return; } } // 5 - Look up the super MetaClass symbol by address // FIXME: VTable patching the auxKC with the superclass in the baseKC uint8_t superclassFixupLevel = currentLevel; aslrTracker.has(fixupLoc, &superclassFixupLevel); auto& metaclassDefinitions = collections[superclassFixupLevel].metaclassDefinitions; auto metaclassIt = metaclassDefinitions.find(superMetaclassSymbolAddress); if ( metaclassIt == metaclassDefinitions.end() ) { auto bindIt = missingBindLocations.find(fixupLoc); if ( bindIt != missingBindLocations.end() ) { dylibDiags.error("Cannot find symbol for metaclass pointed to by '%s'. " "Expected symbol '%s' to be defined in another kext", symbolName, bindIt->second.symbolName.c_str()); } else { dylibDiags.error("Cannot find symbol for metaclass pointed to by '%s'", symbolName); } return; } // 6 - Derive the super class's name from the super MetaClass name std::string_view superClassName = extractString(metaclassIt->second, osObjPrefix, metaclassToken); // If the string isn't prefixed/suffixed appropriately, then give up on this one if ( superClassName.empty() ) { logFunc("Unsupported vtable superclass name\n"); return; } logFunc("Superclass name: '%s'\n", std::string(superClassName).c_str()); // 7 - Derive the super class's vtable from the super class's name std::string superclassVTableName = std::string(vtablePrefix) + std::string(superClassName); // We support namespaces, so first try the superclass without the namespace, then again with it const uint8_t* superclassVTableLoc = nullptr; bool superVTableIsInParentCollection = false; for (unsigned i = 0; i != 2; ++i) { if ( i == 1 ) { superclassVTableName = std::string(vtablePrefix) + + "N" + std::string(superClassName) + "E"; } logFunc("Superclass vtable name: '%s'\n", superclassVTableName.c_str()); { // First check if the superclass vtable comes from a dependent kext for (const std::string& dependencyID : dependencies) { auto depIt = dylibsToSymbols.find(dependencyID); if (depIt == dylibsToSymbols.end()) { dylibDiags.error("Failed to bind '%s' as could not find a kext with '%s' bundle-id", symbolName, dependencyID.c_str()); return; } const DylibSymbols& depDylibSymbols = depIt->second; SymbolLocation symbolLocation = findVTablePatchingSymbol(superclassVTableName, depDylibSymbols); if ( !symbolLocation.found() ) continue; uint64_t superclassVTableVMAddr = symbolLocation.vmAddr; logFunc("Superclass vtable vmAddr: '0x%llx'\n", superclassVTableVMAddr); superclassVTableLoc = collections[depDylibSymbols.dylibLevel].basePointer + (superclassVTableVMAddr - collections[depDylibSymbols.dylibLevel].baseAddress); superVTableIsInParentCollection = depDylibSymbols.dylibLevel != currentLevel; break; } if ( superclassVTableLoc == nullptr ) { SymbolLocation symbolLocation = findVTablePatchingSymbol(superclassVTableName, dylibSymbols); if ( symbolLocation.found() ) { uint64_t superclassVTableVMAddr = symbolLocation.vmAddr; superclassVTableLoc = (uint8_t*)collectionBasePointer + (superclassVTableVMAddr - collectionBaseAddress); superVTableIsInParentCollection = false; } } } if ( superclassVTableLoc != nullptr ) break; } if ( superclassVTableLoc == nullptr ) { superclassVTableName = std::string(vtablePrefix) + std::string(superClassName); dylibDiags.error("Superclass vtable '%s' is not exported from kext or its dependencies", superclassVTableName.c_str()); return; } // Add an entry for this vtable { VTable& vtable = vtables[classVTableLoc]; vtable.superVTable = superclassVTableLoc; vtable.ma = ma; vtable.dylib = &dylibSymbols; vtable.fromParentCollection = false; vtable.patched |= alreadyPatched; vtable.name = classVTableName; } // And an entry for the superclass vtable { VTable& supervtable = vtables[superclassVTableLoc]; supervtable.fromParentCollection = superVTableIsInParentCollection; supervtable.patched |= alreadyPatched; supervtable.name = superclassVTableName; } // Also calculate the metaclass vtable name so that we can patch it std::string metaclassVTableName = std::string(metaclassVTablePrefix) + std::string(className) + metaclassVTableSuffix; logFunc("Metaclass vtable name: '%s'\n", metaclassVTableName.c_str()); { // Note its safe to just ignore missing metaclass symbols if we can't find them // If the binary links then kxld would have let it run SymbolLocation symbolLocation = findVTablePatchingSymbol(metaclassVTableName, dylibSymbols); if ( symbolLocation.found() ) { uint64_t metaclassVTableVMAddr = symbolLocation.vmAddr; logFunc("Metaclass vtable vmAddr: '0x%llx'\n", metaclassVTableVMAddr); uint8_t* metaclassVTableLoc = (uint8_t*)ma + (metaclassVTableVMAddr - loadAddress); // Add an entry for this vtable VTable& vtable = vtables[metaclassVTableLoc]; vtable.superVTable = baseMetaClassVTableLoc; vtable.ma = ma; vtable.dylib = &dylibSymbols; vtable.fromParentCollection = false; vtable.patched |= alreadyPatched; vtable.name = metaclassVTableName; } } }; ma->forEachGlobalSymbol(dylibDiags, ^(const char *symbolName, uint64_t n_value, uint8_t n_type, uint8_t n_sect, uint16_t n_desc, bool &stop) { visitSymbols(symbolName, n_value); }); ma->forEachLocalSymbol(dylibDiags, ^(const char *symbolName, uint64_t n_value, uint8_t n_type, uint8_t n_sect, uint16_t n_desc, bool &stop) { visitSymbols(symbolName, n_value); }); } } void VTablePatcher::calculateSymbols() { for (VTableDylib& dylib : dylibs) { auto& symbolNames = collections[dylib.cacheLevel].symbolNames; dylib.ma->forEachGlobalSymbol(*dylib.diags, ^(const char *symbolName, uint64_t n_value, uint8_t n_type, uint8_t n_sect, uint16_t n_desc, bool &stop) { symbolNames[n_value] = symbolName; }); dylib.ma->forEachLocalSymbol(*dylib.diags, ^(const char *symbolName, uint64_t n_value, uint8_t n_type, uint8_t n_sect, uint16_t n_desc, bool &stop) { symbolNames[n_value] = symbolName; }); } } void VTablePatcher::patchVTables(Diagnostics& diags, std::map<const uint8_t*, const VTableBindSymbol>& missingBindLocations, AppCacheBuilder::ASLR_Tracker& aslrTracker, uint8_t currentLevel) { const bool is64 = pointerSize == 8; // If we have vtables to patch, then make sure we found the OSMetaClass symbol to patch against if ( (baseMetaClassVTableLoc == nullptr) && !vtables.empty() ) { diags.error("Could not find OSMetaClass vtable in kernel binary"); return; } calculateSymbols(); auto calculateVTableEntries = ^(const uint8_t* vtableLoc, VTable& vtable) { assert(vtable.patched); logFunc("Calculating vtable: '%s'\n", vtable.name.c_str()); // The first entry we want to patch is 2 pointers from the start of the vtable const uint8_t* relocLoc = vtableLoc + (2 * pointerSize); if ( vtable.fromParentCollection ) { auto it = existingCollectionFixupLocations.find(relocLoc); while ( it != existingCollectionFixupLocations.end() ) { const Fixup& fixup = it->second; uint64_t targetVMAddr = fixup.targetVMAddr; uint16_t diversity = fixup.diversity; bool hasAddrDiv = fixup.hasAddrDiv; uint8_t key = fixup.key; bool hasPointerAuth = fixup.hasPointerAuth; uint32_t cacheLevel = fixup.cacheLevel; vtable.entries.push_back({ relocLoc, targetVMAddr, cacheLevel, diversity, hasAddrDiv, key, hasPointerAuth }); relocLoc += pointerSize; it = existingCollectionFixupLocations.find(relocLoc); } } else { while ( aslrTracker.has((void*)relocLoc) || (missingBindLocations.find(relocLoc) != missingBindLocations.end()) ) { uint16_t diversity = 0; bool hasAddrDiv = false; uint8_t key = 0; bool hasPointerAuth = false; uint8_t cacheLevel = currentLevel; if ( aslrTracker.has((void*)relocLoc, &cacheLevel) ) { hasPointerAuth = aslrTracker.hasAuthData((void*)relocLoc, &diversity, &hasAddrDiv, &key); } uint64_t targetVMAddr = 0; { uint32_t vmAddr32 = 0; uint64_t vmAddr64 = 0; if ( aslrTracker.hasRebaseTarget32((void*)relocLoc, &vmAddr32) ) { targetVMAddr = vmAddr32; } else if ( aslrTracker.hasRebaseTarget64((void*)relocLoc, &vmAddr64) ) { targetVMAddr = vmAddr64; } else { assert(is64); targetVMAddr = *(uint64_t*)relocLoc; } uint8_t highByte = 0; if ( aslrTracker.hasHigh8((void*)relocLoc, &highByte) ) { uint64_t tbi = (uint64_t)highByte << 56; targetVMAddr |= tbi; } } vtable.entries.push_back({ relocLoc, targetVMAddr, cacheLevel, diversity, hasAddrDiv, key, hasPointerAuth }); relocLoc += pointerSize; } } logFunc("Found %d vtable items: '%s'\n", vtable.entries.size(), vtable.name.c_str()); }; // Map from MachO to diagnostics to emit for that file std::unordered_map<const dyld3::MachOAnalyzer*, Diagnostics*> diagsMap; for (VTableDylib& dylib : dylibs) diagsMap[dylib.ma] = dylib.diags; uint32_t numPatchedVTables = 0; for (auto& vtableEntry : vtables) { if ( vtableEntry.second.patched ) { calculateVTableEntries(vtableEntry.first, vtableEntry.second); ++numPatchedVTables; } } while ( numPatchedVTables != vtables.size() ) { typedef std::pair<const uint8_t*, VTable*> VTableEntry; std::vector<VTableEntry> toBePatched; for (auto& vtableEntry : vtables) { if ( vtableEntry.second.patched ) continue; auto superIt = vtables.find(vtableEntry.second.superVTable); assert(superIt != vtables.end()); if ( !superIt->second.patched ) continue; logFunc("Found unpatched vtable: '%s' with patched superclass '%s'\n", vtableEntry.second.name.c_str(), superIt->second.name.c_str()); toBePatched.push_back({ vtableEntry.first, &vtableEntry.second }); } if ( toBePatched.empty() ) { // If we can't find anything to patch, then print out what we have left for (const auto& vtableEntry : vtables) { if ( vtableEntry.second.patched ) continue; auto superIt = vtables.find(vtableEntry.second.superVTable); assert(superIt != vtables.end()); diags.error("Found unpatched vtable: '%s' with unpatched superclass '%s'\n", vtableEntry.second.name.c_str(), superIt->second.name.c_str()); } break; } for (VTableEntry& vtableEntryToPatch : toBePatched) { VTable& vtable = *vtableEntryToPatch.second; // We can immediately mark this as patched as then calculateVTableEntries can make // sure we never ask for vtables which aren't ready yet vtable.patched = true; ++numPatchedVTables; auto superIt = vtables.find(vtable.superVTable); logFunc("Processing unpatched vtable: '%s' with patched superclass '%s'\n", vtable.name.c_str(), superIt->second.name.c_str()); calculateVTableEntries(vtableEntryToPatch.first, vtable); const VTable& supervtable = superIt->second; if ( vtable.entries.size() < supervtable.entries.size() ) { // Try emit the error to a per dylib diagnostic object if we can find one auto diagIt = diagsMap.find(vtable.ma); Diagnostics* diag = (diagIt != diagsMap.end()) ? diagIt->second : &diags; diag->error("Malformed vtable. Super class '%s' has %lu entries vs subclass '%s' with %lu entries", supervtable.name.c_str(), supervtable.entries.size(), vtable.name.c_str(), vtable.entries.size()); return; } const std::unordered_map<const uint8_t*, VTableBindSymbol>& resolvedBindLocations = vtable.dylib->resolvedBindLocations; for (uint64_t entryIndex = 0; entryIndex != supervtable.entries.size(); ++entryIndex) { logFuncVerbose("Processing entry %lld: super[0x%llx] vs subclass[0x%llx]\n", entryIndex, *(uint64_t*)supervtable.entries[entryIndex].location, *(uint64_t*)vtable.entries[entryIndex].location); VTable::Entry& vtableEntry = vtable.entries[entryIndex]; const VTable::Entry& superVTableEntry = supervtable.entries[entryIndex]; const uint8_t* patchLoc = vtableEntry.location; uint64_t targetVMAddr = superVTableEntry.targetVMAddr; // 1) If the symbol is defined locally, do not patch // This corresponds to a rebase not a bind, so if we have a match in our bind set // we were bound to another image, and should see if that bind should be overridden by a // better vtable patch. auto resolvedBindIt = resolvedBindLocations.find(patchLoc); auto unresolvedBindIt = missingBindLocations.find(patchLoc); if ( (resolvedBindIt == resolvedBindLocations.end()) && (unresolvedBindIt == missingBindLocations.end()) ) continue; // Find the child and parent symbols, if any const char* childSymbolName = nullptr; const char* parentSymbolName = nullptr; if ( resolvedBindIt != resolvedBindLocations.end() ) { childSymbolName = resolvedBindIt->second.symbolName.c_str(); } else { assert(unresolvedBindIt != missingBindLocations.end()); childSymbolName = unresolvedBindIt->second.symbolName.c_str(); } auto& symbolNames = collections[superVTableEntry.targetCacheLevel].symbolNames; auto parentNameIt = symbolNames.find(superVTableEntry.targetVMAddr); if ( parentNameIt != symbolNames.end() ) parentSymbolName = parentNameIt->second; // The child entry can be NULL when a locally-defined, non-external // symbol is stripped. We wouldn't patch this entry anyway, so we just skip it. if ( childSymbolName == nullptr ) { continue; } // It's possible for the patched parent entry not to have a symbol // (e.g. when the definition is inlined). We can't patch this entry no // matter what, so we'll just skip it and die later if it's a problem // (which is not likely). if ( parentSymbolName == nullptr ) { continue; } logFuncVerbose("Processing entry %lld: super[%s] vs subclass[%s]\n", entryIndex, parentSymbolName, childSymbolName); // 2) If the child is a pure virtual function, do not patch. // In general, we want to proceed with patching when the symbol is // externally defined because pad slots fall into this category. // The pure virtual function symbol is special case, as the pure // virtual property itself overrides the parent's implementation. if ( !strcmp(childSymbolName, "___cxa_pure_virtual") ) { continue; } // 3) If the symbols are the same, do not patch // Note that if the symbol was a missing bind, then we'll still patch // This is the case where the vtable entry itself was a local symbol // so we had originally failed to bind to it as it wasn't exported, but it // has the same name as the parent name if ( !strcmp(childSymbolName, parentSymbolName) && (unresolvedBindIt == missingBindLocations.end()) ) { continue; } #if 0 // FIXME: Implement this // 4) If the parent vtable entry is a pad slot, and the child does not // match it, then the child was built against a newer version of the // libraries, so it is binary-incompatible. require_action(!kxld_sym_name_is_padslot(parent_entry->patched.name), finish, rval = KERN_FAILURE; kxld_log(kKxldLogPatching, kKxldLogErr, kKxldLogParentOutOfDate, kxld_demangle(super_vtable->name, &demangled_name1, &demangled_length1), kxld_demangle(vtable->name, &demangled_name2, &demangled_length2))); #endif logFunc("Patching entry '%s' in '%s' to point to '%s' in superclass '%s'\n", childSymbolName, vtable.name.c_str(), parentSymbolName, supervtable.name.c_str()); if ( is64 ) { *((uint64_t*)patchLoc) = targetVMAddr; } else { *((uint32_t*)patchLoc) = (uint32_t)targetVMAddr; } // FIXME: When we support a baseKC, pageableKC, and auxKC, the supervtable cache level // may no longer be correct here as we may be: // - patching a vtable in auxKC // - where the supervtable is in pageableKC // - but the entry slot points to baseKC aslrTracker.add((void*)patchLoc, superVTableEntry.targetCacheLevel); // Add pointer auth if the super vtable had it if ( superVTableEntry.hasPointerAuth ) aslrTracker.setAuthData((void*)patchLoc, superVTableEntry.diversity, superVTableEntry.hasAddrDiv, superVTableEntry.key); // Update this vtable entry in case there are any subclasses which then need to use it // to be patched themselves vtableEntry.targetVMAddr = superVTableEntry.targetVMAddr; vtableEntry.targetCacheLevel = superVTableEntry.targetCacheLevel; vtableEntry.diversity = superVTableEntry.diversity; vtableEntry.hasAddrDiv = superVTableEntry.hasAddrDiv; vtableEntry.key = superVTableEntry.key; vtableEntry.hasPointerAuth = superVTableEntry.hasPointerAuth; missingBindLocations.erase(patchLoc); } } } } typedef std::pair<uint8_t, uint64_t> CacheOffset; struct DylibSymbolLocation { const DylibSymbols* dylibSymbols; uint64_t symbolVMAddr; bool isKPI; }; struct DylibFixups { void processFixups(const std::map<std::string, DylibSymbols>& dylibsToSymbols, const std::unordered_map<std::string_view, std::vector<DylibSymbolLocation>>& symbolMap, const std::string& kernelID, const CacheBuilder::ASLR_Tracker& aslrTracker); // Inputs const dyld3::MachOAnalyzer* ma = nullptr; DylibSymbols& dylibSymbols; Diagnostics& dylibDiag; const std::vector<std::string>& dependencies; // Outputs struct AuthData { uint16_t diversity; bool addrDiv; uint8_t key; }; struct BranchStubData { CacheOffset targetCacheOffset; const void* fixupLoc; uint64_t fixupVMOffset; }; std::unordered_map<const uint8_t*, VTableBindSymbol> missingBindLocations; std::unordered_map<void*, uint8_t> fixupLocs; std::unordered_map<void*, uint8_t> fixupHigh8s; std::unordered_map<void*, AuthData> fixupAuths; std::vector<BranchStubData> branchStubs; }; void DylibFixups::processFixups(const std::map<std::string, DylibSymbols>& dylibsToSymbols, const std::unordered_map<std::string_view, std::vector<DylibSymbolLocation>>& symbolMap, const std::string& kernelID, const CacheBuilder::ASLR_Tracker& aslrTracker) { auto& resolvedBindLocations = dylibSymbols.resolvedBindLocations; const std::string& dylibID = dylibSymbols.dylibName; const bool _is64 = true; const bool isThirdPartyKext = (dylibID.find("com.apple") != 0); // The magic symbol for missing weak imports const char* missingWeakImportSymbolName = "_gOSKextUnresolved"; struct SymbolDefinition { uint64_t symbolVMAddr; uint32_t kernelCollectionLevel; }; auto findDependencyWithSymbol = [&symbolMap, &isThirdPartyKext](const char* symbolName, const std::vector<std::string>& deps) { auto symbolMapIt = symbolMap.find(symbolName); if ( symbolMapIt == symbolMap.end() ) return (SymbolDefinition){ ~0ULL, 0 }; // Find the first dependency in the list const std::vector<DylibSymbolLocation>& depDylibSymbols = symbolMapIt->second; // The massively common case is 1 or 2 definitions of a given symbol, so a basic searhc should be // fine for (const std::string& dependency : deps) { for (const DylibSymbolLocation& dylibSymbol : depDylibSymbols) { if ( dependency == dylibSymbol.dylibSymbols->dylibName ) { // If the Apple kext we are linking has a symbol set, and the user is a third-party kext, // then only allow the third party kext to see symbols in the kext export list, if it has one const bool isAppleKext = (dependency.find("com.apple") == 0); if ( isThirdPartyKext && isAppleKext && !dylibSymbol.isKPI ) continue; return (SymbolDefinition){ dylibSymbol.symbolVMAddr, dylibSymbol.dylibSymbols->dylibLevel }; } } } return (SymbolDefinition){ ~0ULL, 0 }; }; if (ma->hasChainedFixups()) { // build array of targets struct BindTarget { const VTableBindSymbol bindSymbol; uint64_t vmAddr; uint32_t dylibLevel; bool isMissingWeakImport; bool isMissingSymbol; }; __block std::vector<BindTarget> bindTargets; __block bool foundMissingWeakImport = false; ma->forEachChainedFixupTarget(dylibDiag, ^(int libOrdinal, const char* symbolName, uint64_t addend, bool weakImport, bool& stop) { if ( (libOrdinal != BIND_SPECIAL_DYLIB_FLAT_LOOKUP) && (libOrdinal != BIND_SPECIAL_DYLIB_WEAK_LOOKUP) ) { dylibDiag.error("All chained binds should be flat namespace or weak lookups"); stop = true; return; } if ( addend != 0 ) { dylibDiag.error("Chained bind addends are not supported right now"); stop = true; return; } VTableBindSymbol bindSymbol = { dylibID, symbolName }; bool isMissingSymbol = false; for (const std::string& dependencyID : dependencies) { auto depIt = dylibsToSymbols.find(dependencyID); if (depIt == dylibsToSymbols.end()) { dylibDiag.error("Failed to bind '%s' as could not find a kext with '%s' bundle-id", symbolName, dependencyID.c_str()); stop = true; return; } const DylibSymbols& depDylibSymbols = depIt->second; auto exportIt = depDylibSymbols.globals.find(symbolName); if ( exportIt == depDylibSymbols.globals.end() ) continue; isMissingSymbol = false; bindTargets.push_back({ bindSymbol, exportIt->second, depDylibSymbols.dylibLevel, false, isMissingSymbol }); return; } // If the symbol is weak, and we didn't find it in our listed // dependencies, then use our own definition if ( libOrdinal == BIND_SPECIAL_DYLIB_WEAK_LOOKUP ) { auto dylibIt = dylibsToSymbols.find(dylibID); if (dylibIt == dylibsToSymbols.end()) { dylibDiag.error("Failed to bind weak '%s' as could not find a define in self", symbolName); stop = true; return; } const DylibSymbols& depDylibSymbols = dylibIt->second; auto exportIt = depDylibSymbols.globals.find(symbolName); if ( exportIt != depDylibSymbols.globals.end() ) { isMissingSymbol = false; bindTargets.push_back({ bindSymbol, exportIt->second, depDylibSymbols.dylibLevel, false, isMissingSymbol }); return; } } if ( weakImport ) { // Find _gOSKextUnresolved in the kernel // Weak imports are not compared against null, but instead against the address of that symbol auto kernelSymbolsIt = dylibsToSymbols.find(kernelID); assert(kernelSymbolsIt != dylibsToSymbols.end()); const DylibSymbols& kernelSymbols = kernelSymbolsIt->second; auto exportIt = kernelSymbols.globals.find(missingWeakImportSymbolName); if (exportIt != kernelSymbols.globals.end()) { foundMissingWeakImport = true; isMissingSymbol = false; bindTargets.push_back({ bindSymbol, exportIt->second, kernelSymbols.dylibLevel, true, isMissingSymbol }); return; } dylibDiag.error("Weak bind symbol '%s' not found in kernel", missingWeakImportSymbolName); return; } // Store missing binds for later. They may be fixed by vtable patching isMissingSymbol = true; bindTargets.push_back({ bindSymbol, 0, 0, false, isMissingSymbol }); }); if ( dylibDiag.hasError() ) return; if( foundMissingWeakImport ) { // If we found a missing weak import, then we need to check that the user did // something like "if ( &foo == &gOSKextUnresolved )" // If they didn't use gOSKextUnresolved at all, then there's no way they could be doing that check auto kernelSymbolsIt = dylibsToSymbols.find(kernelID); assert(kernelSymbolsIt != dylibsToSymbols.end()); const DylibSymbols& kernelSymbols = kernelSymbolsIt->second; auto exportIt = kernelSymbols.globals.find(missingWeakImportSymbolName); assert(exportIt != kernelSymbols.globals.end()); bool foundUseOfMagicSymbol = false; for (const BindTarget& bindTarget : bindTargets) { // Skip the missing weak imports if ( bindTarget.isMissingWeakImport || bindTarget.isMissingSymbol ) continue; // Skip anything which isn't the symbol we are looking for if ( (bindTarget.dylibLevel != 0) && (bindTarget.vmAddr != exportIt->second) ) continue; foundUseOfMagicSymbol = true; break; } if ( !foundUseOfMagicSymbol ) { dylibDiag.error("Has weak references but does not test for them. " "Test for weak references with OSKextSymbolIsResolved()."); return; } } // uint64_t baseAddress = ma->preferredLoadAddress(); ma->withChainStarts(dylibDiag, 0, ^(const dyld_chained_starts_in_image* starts) { ma->forEachFixupInAllChains(dylibDiag, starts, false, ^(dyld3::MachOLoaded::ChainedFixupPointerOnDisk* fixupLoc, const dyld_chained_starts_in_segment* segInfo, bool& stop) { switch (segInfo->pointer_format) { case DYLD_CHAINED_PTR_64_OFFSET: if ( fixupLoc->generic64.bind.bind ) { uint64_t bindOrdinal = fixupLoc->generic64.bind.ordinal; if ( bindOrdinal >= bindTargets.size() ) { dylibDiag.error("Bind ordinal %lld out of range %lu", bindOrdinal, bindTargets.size()); stop = true; return; } const BindTarget& bindTarget = bindTargets[bindOrdinal]; if ( bindTarget.isMissingSymbol ) { // Track this missing bind for later // For now we bind it to null and don't slide it. fixupLoc->raw64 = 0; missingBindLocations[(const uint8_t*)fixupLoc] = bindTarget.bindSymbol; } else { fixupLoc->raw64 = bindTarget.vmAddr; fixupLocs[fixupLoc] = bindTarget.dylibLevel; resolvedBindLocations[(const uint8_t*)fixupLoc] = bindTarget.bindSymbol; } } else { // convert rebase chain entry to raw pointer to target vmaddr uint64_t targetVMAddr = fixupLoc->generic64.rebase.target; uint64_t sideTableAddr = 0; if ( aslrTracker.hasRebaseTarget64(fixupLoc, &sideTableAddr) ) targetVMAddr = sideTableAddr; // store high8 in side table if ( fixupLoc->generic64.rebase.high8 ) fixupHigh8s[fixupLoc] = fixupLoc->generic64.rebase.high8; fixupLoc->raw64 = targetVMAddr; } break; case DYLD_CHAINED_PTR_ARM64E_KERNEL: if ( fixupLoc->arm64e.bind.bind ) { uint64_t bindOrdinal = fixupLoc->arm64e.bind.ordinal; if ( bindOrdinal >= bindTargets.size() ) { dylibDiag.error("Bind ordinal %lld out of range %lu", bindOrdinal, bindTargets.size()); stop = true; return; } const BindTarget& bindTarget = bindTargets[bindOrdinal]; uint64_t targetVMAddr = bindTarget.vmAddr; if ( fixupLoc->arm64e.authBind.auth ) { // store auth data in side table fixupAuths[fixupLoc] = { (uint16_t)fixupLoc->arm64e.authBind.diversity, (bool)fixupLoc->arm64e.authBind.addrDiv, (uint8_t)fixupLoc->arm64e.authBind.key }; } else { // plain binds can have addend in chain targetVMAddr += fixupLoc->arm64e.bind.addend; } // change location from a chain ptr into a raw pointer to the target vmaddr if ( bindTarget.isMissingSymbol ) { // Track this missing bind for later // For now we bind it to null and don't slide it. fixupLoc->raw64 = 0; missingBindLocations[(const uint8_t*)fixupLoc] = bindTarget.bindSymbol; } else { fixupLoc->raw64 = targetVMAddr; fixupLocs[fixupLoc] = bindTarget.dylibLevel; resolvedBindLocations[(const uint8_t*)fixupLoc] = bindTarget.bindSymbol; } } else { // convert rebase chain entry to raw pointer to target vmaddr if ( fixupLoc->arm64e.rebase.auth ) { // store auth data in side table fixupAuths[fixupLoc] = { (uint16_t)fixupLoc->arm64e.authRebase.diversity, (bool)fixupLoc->arm64e.authRebase.addrDiv, (uint8_t)fixupLoc->arm64e.authRebase.key }; uint64_t targetVMAddr = fixupLoc->arm64e.authRebase.target; fixupLoc->raw64 = targetVMAddr; } else { uint64_t targetVMAddr = fixupLoc->arm64e.rebase.target; uint64_t sideTableAddr; if ( aslrTracker.hasRebaseTarget64(fixupLoc, &sideTableAddr) ) targetVMAddr = sideTableAddr; // store high8 in side table if ( fixupLoc->arm64e.rebase.high8 ) fixupHigh8s[fixupLoc] = fixupLoc->arm64e.rebase.high8; fixupLoc->raw64 = targetVMAddr; } } break; default: fprintf(stderr, "unknown pointer type %d\n", segInfo->pointer_format); break; } }); }); return; } // If we have any missing imports, then they should check for the kernel symbol // Grab a hold of that now if it exists so we can check it later __block bool foundUseOfMagicSymbol = false; __block bool foundMissingWeakImport = false; const uint64_t loadAddress = ma->preferredLoadAddress(); ma->forEachBind(dylibDiag, ^(uint64_t runtimeOffset, int libOrdinal, uint8_t bindType, const char *symbolName, bool weakImport, bool lazyBind, uint64_t addend, bool &stop) { // printf("Bind at 0x%llx to '%s'\n", runtimeOffset, symbolName); // Kext binds are a flat namespace so walk until we find the symbol we need bool foundSymbol = false; VTableBindSymbol bindSymbol = { dylibID, symbolName }; if (SymbolDefinition symbolDef = findDependencyWithSymbol(symbolName, dependencies); symbolDef.symbolVMAddr != ~0ULL) { // Set the bind to the target address since we found it uint8_t* fixupLoc = (uint8_t*)ma+runtimeOffset; if ( bindType == BIND_TYPE_POINTER ) { if ( _is64 ) *((uint64_t*)fixupLoc) = symbolDef.symbolVMAddr; else *((uint32_t*)fixupLoc) = (uint32_t)symbolDef.symbolVMAddr; // Only track regular fixups for ASLR, not branch fixups fixupLocs[fixupLoc] = symbolDef.kernelCollectionLevel; resolvedBindLocations[(const uint8_t*)fixupLoc] = bindSymbol; } else if ( bindType == BIND_TYPE_TEXT_PCREL32 ) { // The value to store is the difference between the bind target // and the value of the PC after this instruction uint64_t targetAddress = 0; if ( dylibSymbols.dylibLevel != symbolDef.kernelCollectionLevel ) { // Record this for later as we want to create stubs serially CacheOffset targetCacheOffset = { symbolDef.kernelCollectionLevel, symbolDef.symbolVMAddr }; branchStubs.emplace_back((BranchStubData){ .targetCacheOffset = targetCacheOffset, .fixupLoc = fixupLoc, .fixupVMOffset = runtimeOffset }); } else { targetAddress = symbolDef.symbolVMAddr; uint64_t diffValue = targetAddress - (loadAddress + runtimeOffset + 4); *((uint32_t*)fixupLoc) = (uint32_t)diffValue; } } else { dylibDiag.error("Unexpected bind type: %d", bindType); stop = true; return; } foundSymbol = true; } if ( foundSymbol && !foundUseOfMagicSymbol ) { foundUseOfMagicSymbol = (strcmp(symbolName, missingWeakImportSymbolName) == 0); } if (!foundSymbol) { for (const std::string& dependencyID : dependencies) { auto depIt = dylibsToSymbols.find(dependencyID); if (depIt == dylibsToSymbols.end()) { dylibDiag.error("Failed to bind '%s' as could not find a kext with '%s' bundle-id", symbolName, dependencyID.c_str()); stop = true; return; } const DylibSymbols& depDylibSymbols = depIt->second; auto exportIt = depDylibSymbols.globals.find(symbolName); if ( exportIt == depDylibSymbols.globals.end() ) continue; findDependencyWithSymbol(symbolName, dependencies); break; } } // If the symbol is weak, and we didn't find it in our listed // dependencies, then use our own definition if ( !foundSymbol && (libOrdinal == BIND_SPECIAL_DYLIB_WEAK_LOOKUP) ) { auto dylibIt = dylibsToSymbols.find(dylibID); if (dylibIt == dylibsToSymbols.end()) { dylibDiag.error("Failed to bind weak '%s' as could not find a define in self", symbolName); stop = true; return; } const DylibSymbols& depDylibSymbols = dylibIt->second; auto exportIt = depDylibSymbols.globals.find(symbolName); if ( exportIt != depDylibSymbols.globals.end() ) { // Set the bind to the target address since we found it uint8_t* fixupLoc = (uint8_t*)ma+runtimeOffset; if ( bindType == BIND_TYPE_POINTER ) { if ( _is64 ) *((uint64_t*)fixupLoc) = exportIt->second; else *((uint32_t*)fixupLoc) = (uint32_t)exportIt->second; // Only track regular fixups for ASLR, not branch fixups fixupLocs[fixupLoc] = dylibSymbols.dylibLevel; resolvedBindLocations[(const uint8_t*)fixupLoc] = bindSymbol; } else if ( bindType == BIND_TYPE_TEXT_PCREL32 ) { // We should never have a branch to a weak bind as we should have had a GOT for these dylibDiag.error("Unexpected weak bind type: %d", bindType); stop = true; return; } else { dylibDiag.error("Unexpected bind type: %d", bindType); stop = true; return; } foundSymbol = true; } } if ( !foundSymbol && weakImport ) { if ( bindType != BIND_TYPE_POINTER ) { dylibDiag.error("Unexpected bind type: %d", bindType); stop = true; return; } // Find _gOSKextUnresolved in the kernel // Weak imports are not compared against null, but instead against the address of that symbol auto kernelSymbolsIt = dylibsToSymbols.find(kernelID); assert(kernelSymbolsIt != dylibsToSymbols.end()); const DylibSymbols& kernelSymbols = kernelSymbolsIt->second; auto exportIt = kernelSymbols.globals.find(missingWeakImportSymbolName); if (exportIt != kernelSymbols.globals.end()) { foundMissingWeakImport = true; uint8_t* fixupLoc = (uint8_t*)ma+runtimeOffset; if ( _is64 ) *((uint64_t*)fixupLoc) = exportIt->second; else *((uint32_t*)fixupLoc) = (uint32_t)exportIt->second; // Only track regular fixups for ASLR, not branch fixups fixupLocs[fixupLoc] = kernelSymbols.dylibLevel; return; } dylibDiag.error("Weak bind symbol '%s' not found in kernel", missingWeakImportSymbolName); return; } if ( !foundSymbol ) { // Store missing binds for later. They may be fixed by vtable patching const uint8_t* fixupLoc = (uint8_t*)ma+runtimeOffset; missingBindLocations[fixupLoc] = bindSymbol; } }, ^(const char *symbolName) { dylibDiag.error("Strong binds are not supported right now"); }); if ( foundMissingWeakImport && !foundUseOfMagicSymbol ) { dylibDiag.error("Has weak references but does not test for them. " "Test for weak references with OSKextSymbolIsResolved()."); return; } ma->forEachRebase(dylibDiag, false, ^(uint64_t runtimeOffset, bool &stop) { uint8_t* fixupLoc = (uint8_t*)ma+runtimeOffset; fixupLocs[fixupLoc] = (uint8_t)~0U; }); } // A helper to automatically call CFRelease when we go out of scope struct AutoReleaseTypeRef { AutoReleaseTypeRef() = default; ~AutoReleaseTypeRef() { if ( ref != nullptr ) { CFRelease(ref); } } void setRef(CFTypeRef typeRef) { assert(ref == nullptr); ref = typeRef; } CFTypeRef ref = nullptr; }; static std::unique_ptr<std::unordered_set<std::string>> getKPI(Diagnostics& diags, const dyld3::MachOAnalyzer* ma, std::string_view dylibID) { bool isAppleKext = (dylibID.find("com.apple") == 0); if ( !isAppleKext ) return {}; __block std::list<std::string> nonASCIIStrings; auto getString = ^(Diagnostics& diagnostics, CFStringRef symbolNameRef) { const char* symbolName = CFStringGetCStringPtr(symbolNameRef, kCFStringEncodingUTF8); if ( symbolName != nullptr ) return symbolName; CFIndex len = CFStringGetMaximumSizeForEncoding(CFStringGetLength(symbolNameRef), kCFStringEncodingUTF8); char buffer[len + 1]; if ( !CFStringGetCString(symbolNameRef, buffer, len, kCFStringEncodingUTF8) ) { diagnostics.error("Could not convert string to ASCII"); return (const char*)nullptr; } buffer[len] = '\0'; nonASCIIStrings.push_back(buffer); return nonASCIIStrings.back().c_str(); }; uint64_t symbolSetsSize = 0; const void* symbolSetsContent = ma->findSectionContent("__LINKINFO", "__symbolsets", symbolSetsSize); if ( symbolSetsContent == nullptr ) return {}; AutoReleaseTypeRef dataRefReleaser; AutoReleaseTypeRef plistRefReleaser; std::unordered_set<std::string> symbols; CFDataRef dataRef = CFDataCreateWithBytesNoCopy(kCFAllocatorDefault, (const uint8_t*)symbolSetsContent, symbolSetsSize, kCFAllocatorNull); if ( dataRef == nullptr ) { diags.error("Could not create data ref for kpi"); return {}; } dataRefReleaser.setRef(dataRef); CFErrorRef errorRef = nullptr; CFPropertyListRef plistRef = CFPropertyListCreateWithData(kCFAllocatorDefault, dataRef, kCFPropertyListImmutable, nullptr, &errorRef); if (errorRef != nullptr) { CFStringRef errorString = CFErrorCopyDescription(errorRef); diags.error("Could not load plist because :%s", CFStringGetCStringPtr(errorString, kCFStringEncodingASCII)); CFRelease(errorRef); return {}; } if ( plistRef == nullptr ) { diags.error("Could not create plist ref for kpi"); return {}; } plistRefReleaser.setRef(plistRef); if ( CFGetTypeID(plistRef) != CFDictionaryGetTypeID() ) { diags.error("kpi plist should be a dictionary"); return {}; } CFDictionaryRef symbolSetsDictRef = (CFDictionaryRef)plistRef; // CFBundleIdentifier CFStringRef bundleIDRef = (CFStringRef)CFDictionaryGetValue(symbolSetsDictRef, CFSTR("CFBundleIdentifier")); if ( (bundleIDRef == nullptr) || (CFGetTypeID(bundleIDRef) != CFStringGetTypeID()) ) { diags.error("kpi bundle ID should be a string"); return {}; } const char* bundleID = getString(diags, bundleIDRef); if ( bundleID == nullptr ) return {}; if ( dylibID != bundleID ) { diags.error("kpi bundle ID doesn't match kext"); return {}; } CFArrayRef symbolsArrayRef = (CFArrayRef)CFDictionaryGetValue(symbolSetsDictRef, CFSTR("Symbols")); if ( symbolsArrayRef != nullptr ) { if ( CFGetTypeID(symbolsArrayRef) != CFArrayGetTypeID() ) { diags.error("Symbols value should be an array"); return {}; } for (CFIndex symbolSetIndex = 0; symbolSetIndex != CFArrayGetCount(symbolsArrayRef); ++symbolSetIndex) { CFStringRef symbolNameRef = (CFStringRef)CFArrayGetValueAtIndex(symbolsArrayRef, symbolSetIndex); if ( (symbolNameRef == nullptr) || (CFGetTypeID(symbolNameRef) != CFStringGetTypeID()) ) { diags.error("Symbol name should be a string"); return {}; } const char* symbolName = getString(diags, symbolNameRef); if ( symbolName == nullptr ) return {}; symbols.insert(symbolName); } } return std::make_unique<std::unordered_set<std::string>>(std::move(symbols)); } void AppCacheBuilder::processFixups() { auto dylibsToSymbolsOwner = std::make_unique<std::map<std::string, DylibSymbols>>(); std::map<std::string, DylibSymbols>& dylibsToSymbols = *dylibsToSymbolsOwner.get(); auto vtablePatcherOwner = std::make_unique<VTablePatcher>(numFixupLevels); VTablePatcher& vtablePatcher = *vtablePatcherOwner.get(); const uint32_t kernelLevel = 0; uint8_t currentLevel = getCurrentFixupLevel(); // Keep track of missing binds until later. They may be "resolved" by vtable patching std::map<const uint8_t*, const VTableBindSymbol> missingBindLocations; __block std::string kernelID; __block const dyld3::MachOAnalyzer* kernelMA = nullptr; if ( appCacheOptions.cacheKind == Options::AppCacheKind::kernel ) { kernelMA = getKernelStaticExecutableFromCache(); forEachCacheDylib(^(const dyld3::MachOAnalyzer *ma, const std::string &dylibID, DylibStripMode stripMode, const std::vector<std::string> &dependencies, Diagnostics& dylibDiag, bool &stop) { if ( ma == kernelMA ) { kernelID = dylibID; stop = true; } }); assert(!kernelID.empty()); } else { assert(existingKernelCollection != nullptr); existingKernelCollection->forEachDylib(_diagnostics, ^(const dyld3::MachOAnalyzer *ma, const char *name, bool &stop) { if ( ma->isStaticExecutable() ) { kernelMA = ma; kernelID = name; } }); if ( kernelMA == nullptr ) { _diagnostics.error("Could not find kernel in kernel collection"); return; } } auto getGlobals = [](Diagnostics& diags, const dyld3::MachOAnalyzer *ma) -> std::map<std::string_view, uint64_t> { // Note we don't put __block on the variable directly as then it gets copied in to the return value std::map<std::string_view, uint64_t> exports; __block std::map<std::string_view, uint64_t>& exportsRef = exports; ma->forEachGlobalSymbol(diags, ^(const char *symbolName, uint64_t n_value, uint8_t n_type, uint8_t n_sect, uint16_t n_desc, bool &stop) { exportsRef[symbolName] = n_value; }); return exports; }; auto getLocals = [](Diagnostics& diags, const dyld3::MachOAnalyzer *ma) -> std::map<std::string_view, uint64_t> { // Note we don't put __block on the variable directly as then it gets copied in to the return value std::map<std::string_view, uint64_t> exports; __block std::map<std::string_view, uint64_t>& exportsRef = exports; ma->forEachLocalSymbol(diags, ^(const char *symbolName, uint64_t n_value, uint8_t n_type, uint8_t n_sect, uint16_t n_desc, bool &stop) { exportsRef[symbolName] = n_value; }); return exports; }; dylibsToSymbols[kernelID] = { getGlobals(_diagnostics, kernelMA), getLocals(_diagnostics, kernelMA), nullptr, kernelLevel, std::string(kernelID) }; // Add all the codeless kext's as kext's can list them as dependencies // Note we add placeholders here which can be legitimately replaced by symbol sets for (const InputDylib& dylib : codelessKexts) { dylibsToSymbols[dylib.dylibID] = { }; } // Similarly, add placeholders for codeless kexts in the baseKC if ( existingKernelCollection != nullptr ) { existingKernelCollection->forEachPrelinkInfoLibrary(_diagnostics, ^(const char *bundleName, const char* relativePath, const std::vector<const char *> &deps) { dylibsToSymbols[bundleName] = { }; }); } // And placeholders for codeless kexts in the pageableKC if ( pageableKernelCollection != nullptr ) { pageableKernelCollection->forEachPrelinkInfoLibrary(_diagnostics, ^(const char *bundleName, const char* relativePath, const std::vector<const char *> &deps) { dylibsToSymbols[bundleName] = { }; }); } // Get the symbol sets AutoReleaseTypeRef dataRefReleaser; AutoReleaseTypeRef plistRefReleaser; __block std::list<std::string> nonASCIIStrings; auto getString = ^(Diagnostics& diags, CFStringRef symbolNameRef) { const char* symbolName = CFStringGetCStringPtr(symbolNameRef, kCFStringEncodingUTF8); if ( symbolName != nullptr ) return symbolName; CFIndex len = CFStringGetMaximumSizeForEncoding(CFStringGetLength(symbolNameRef), kCFStringEncodingUTF8); char buffer[len + 1]; if ( !CFStringGetCString(symbolNameRef, buffer, len, kCFStringEncodingUTF8) ) { diags.error("Could not convert string to ASCII"); return (const char*)nullptr; } buffer[len] = '\0'; nonASCIIStrings.push_back(buffer); return nonASCIIStrings.back().c_str(); }; uint64_t symbolSetsSize = 0; const void* symbolSetsContent = kernelMA->findSectionContent("__LINKINFO", "__symbolsets", symbolSetsSize); if ( symbolSetsContent != nullptr ) { const DylibSymbols& kernelSymbols = dylibsToSymbols[kernelID]; CFDataRef dataRef = CFDataCreateWithBytesNoCopy(kCFAllocatorDefault, (const uint8_t*)symbolSetsContent, symbolSetsSize, kCFAllocatorNull); if ( dataRef == nullptr ) { _diagnostics.error("Could not create data ref for symbol sets"); return; } dataRefReleaser.setRef(dataRef); CFErrorRef errorRef = nullptr; CFPropertyListRef plistRef = CFPropertyListCreateWithData(kCFAllocatorDefault, dataRef, kCFPropertyListImmutable, nullptr, &errorRef); if (errorRef != nullptr) { CFStringRef errorString = CFErrorCopyDescription(errorRef); _diagnostics.error("Could not load plist because :%s", CFStringGetCStringPtr(errorString, kCFStringEncodingASCII)); CFRelease(errorRef); return; } if ( plistRef == nullptr ) { _diagnostics.error("Could not create plist ref for symbol sets"); return; } plistRefReleaser.setRef(plistRef); if ( CFGetTypeID(plistRef) != CFDictionaryGetTypeID() ) { _diagnostics.error("Symbol set plist should be a dictionary"); return; } CFDictionaryRef symbolSetsDictRef = (CFDictionaryRef)plistRef; CFArrayRef symbolSetArrayRef = (CFArrayRef)CFDictionaryGetValue(symbolSetsDictRef, CFSTR("SymbolsSets")); if ( symbolSetArrayRef != nullptr ) { if ( CFGetTypeID(symbolSetArrayRef) != CFArrayGetTypeID() ) { _diagnostics.error("SymbolsSets value should be an array"); return; } for (CFIndex symbolSetIndex = 0; symbolSetIndex != CFArrayGetCount(symbolSetArrayRef); ++symbolSetIndex) { CFDictionaryRef symbolSetDictRef = (CFDictionaryRef)CFArrayGetValueAtIndex(symbolSetArrayRef, symbolSetIndex); if ( CFGetTypeID(symbolSetDictRef) != CFDictionaryGetTypeID() ) { _diagnostics.error("Symbol set element should be a dictionary"); return; } // CFBundleIdentifier CFStringRef bundleIDRef = (CFStringRef)CFDictionaryGetValue(symbolSetDictRef, CFSTR("CFBundleIdentifier")); if ( (bundleIDRef == nullptr) || (CFGetTypeID(bundleIDRef) != CFStringGetTypeID()) ) { _diagnostics.error("Symbol set bundle ID should be a string"); return; } // Symbols CFArrayRef symbolsArrayRef = (CFArrayRef)CFDictionaryGetValue(symbolSetDictRef, CFSTR("Symbols")); if ( (symbolsArrayRef == nullptr) || (CFGetTypeID(symbolsArrayRef) != CFArrayGetTypeID()) ) { _diagnostics.error("Symbol set symbols should be an array"); return; } std::map<std::string_view, uint64_t> symbolSetGlobals; std::map<std::string_view, uint64_t> symbolSetLocals; for (CFIndex symbolIndex = 0; symbolIndex != CFArrayGetCount(symbolsArrayRef); ++symbolIndex) { CFDictionaryRef symbolDictRef = (CFDictionaryRef)CFArrayGetValueAtIndex(symbolsArrayRef, symbolIndex); if ( CFGetTypeID(symbolDictRef) != CFDictionaryGetTypeID() ) { _diagnostics.error("Symbols array element should be a dictionary"); return; } // SymbolPrefix CFStringRef symbolPrefixRef = (CFStringRef)CFDictionaryGetValue(symbolDictRef, CFSTR("SymbolPrefix")); if ( symbolPrefixRef != nullptr ) { if ( CFGetTypeID(symbolPrefixRef) != CFStringGetTypeID() ) { _diagnostics.error("Symbol prefix should be a string"); return; } const char* symbolPrefix = getString(_diagnostics, symbolPrefixRef); if ( symbolPrefix == nullptr ) return; size_t symbolPrefixLen = strlen(symbolPrefix); // FIXME: Brute force might not be the best thing here for (std::pair<std::string_view, uint64_t> kernelGlobal : kernelSymbols.globals) { if ( strncmp(kernelGlobal.first.data(), symbolPrefix, symbolPrefixLen) == 0 ) { symbolSetGlobals[kernelGlobal.first] = kernelGlobal.second; } } for (std::pair<std::string_view, uint64_t> kernelLocal : kernelSymbols.locals) { if ( strncmp(kernelLocal.first.data(), symbolPrefix, symbolPrefixLen) == 0 ) { symbolSetLocals[kernelLocal.first] = kernelLocal.second; } } continue; } // SymbolName CFStringRef symbolNameRef = (CFStringRef)CFDictionaryGetValue(symbolDictRef, CFSTR("SymbolName")); if ( (symbolNameRef == nullptr) || (CFGetTypeID(symbolNameRef) != CFStringGetTypeID()) ) { _diagnostics.error("Symbol name should be a string"); return; } // AliasTarget [Optional] CFStringRef aliasTargetRef = (CFStringRef)CFDictionaryGetValue(symbolDictRef, CFSTR("AliasTarget")); if ( aliasTargetRef == nullptr ) { // No alias const char* symbolName = getString(_diagnostics, symbolNameRef); if ( symbolName == nullptr ) return; // Find the symbol in xnu auto globalIt = kernelSymbols.globals.find(symbolName); if (globalIt != kernelSymbols.globals.end()) { symbolSetGlobals[symbolName] = globalIt->second; } auto localIt = kernelSymbols.locals.find(symbolName); if (localIt != kernelSymbols.locals.end()) { symbolSetLocals[symbolName] = localIt->second; } } else { // We have an alias if ( CFGetTypeID(aliasTargetRef) != CFStringGetTypeID() ) { _diagnostics.error("Alias should be a string"); return; } const char* symbolName = getString(_diagnostics, symbolNameRef); if ( symbolName == nullptr ) return; const char* aliasTargetName = getString(_diagnostics, aliasTargetRef); if ( aliasTargetName == nullptr ) return; // Find the alias symbol in xnu auto globalIt = kernelSymbols.globals.find(aliasTargetName); if (globalIt != kernelSymbols.globals.end()) { symbolSetGlobals[symbolName] = globalIt->second; } else { _diagnostics.error("Alias '%s' not found in kernel", aliasTargetName); return; } auto localIt = kernelSymbols.locals.find(aliasTargetName); if (localIt != kernelSymbols.locals.end()) { symbolSetLocals[symbolName] = localIt->second; } else { // This is not an error, as aliases from symbol sets from the kernel // are only for vtable patching, not general binding } } } const char* dylibID = getString(_diagnostics, bundleIDRef); if ( dylibID == nullptr ) return; // HACK: kxld aliases __ZN15OSMetaClassBase25_RESERVEDOSMetaClassBase3Ev to __ZN15OSMetaClassBase8DispatchE5IORPC auto metaclassHackIt = symbolSetGlobals.find("__ZN15OSMetaClassBase8DispatchE5IORPC"); if ( metaclassHackIt != symbolSetGlobals.end() ) symbolSetGlobals["__ZN15OSMetaClassBase25_RESERVEDOSMetaClassBase3Ev"] = metaclassHackIt->second; dylibsToSymbols[dylibID] = { std::move(symbolSetGlobals), std::move(symbolSetLocals), nullptr, kernelLevel, dylibID }; } } } auto processBinary = ^(Diagnostics& dylibDiags, const dyld3::MachOAnalyzer *ma, const std::string& dylibID, uint32_t dylibLevel) { // We dont support export trie's for now uint32_t unusedExportTrieOffset = 0; uint32_t unusedExportTrieSize = 0; if (ma->hasExportTrie(unusedExportTrieOffset, unusedExportTrieSize)) assert(false); // Already done the kernel before. if ( ma == kernelMA ) return; // Regular kext. dylibsToSymbols[dylibID] = { getGlobals(dylibDiags, ma), getLocals(dylibDiags, ma), getKPI(dylibDiags, ma, dylibID), dylibLevel, dylibID }; }; // Process binary symbols in parallel { struct DylibData { const dyld3::MachOAnalyzer* ma = nullptr; Diagnostics& dylibDiag; const std::string& dylibID; }; __block std::vector<DylibData> dylibDatas; dylibDatas.reserve(sortedDylibs.size()); forEachCacheDylib(^(const dyld3::MachOAnalyzer *ma, const std::string &dylibID, DylibStripMode stripMode, const std::vector<std::string> &dependencies, Diagnostics &dylibDiag, bool &stop) { // Already done the kernel before. if ( ma == kernelMA ) return; // Make space for all the map entries so that we know they are there when we write their values later dylibsToSymbols[dylibID] = { }; dylibDatas.emplace_back((DylibData){ ma, dylibDiag, dylibID }); }); dispatch_apply(dylibDatas.size(), DISPATCH_APPLY_AUTO, ^(size_t index) { DylibData& dylibData = dylibDatas[index]; processBinary(dylibData.dylibDiag, dylibData.ma, dylibData.dylibID, currentLevel); }); } // Add exports from the kernel collection if we have it if ( existingKernelCollection != nullptr ) { uint8_t fixupLevel = getFixupLevel(Options::AppCacheKind::kernel); existingKernelCollection->forEachDylib(_diagnostics, ^(const dyld3::MachOAnalyzer *ma, const char *name, bool &stop) { processBinary(_diagnostics, ma, name, fixupLevel); }); } // Add exports from the pageable collection if we have it if ( pageableKernelCollection != nullptr ) { uint8_t fixupLevel = getFixupLevel(Options::AppCacheKind::pageableKC); pageableKernelCollection->forEachDylib(_diagnostics, ^(const dyld3::MachOAnalyzer *ma, const char *name, bool &stop) { processBinary(_diagnostics, ma, name, fixupLevel); }); } // Map from an offset in to a KC to a synthesized stub which branches to that offset struct CacheOffsetHash { size_t operator() (const CacheOffset& cacheOffset) const { return std::hash<uint32_t>{}(cacheOffset.first) ^ std::hash<uint64_t>{}(cacheOffset.second); } }; std::unordered_map<CacheOffset, uint64_t, CacheOffsetHash> branchStubs; // Clear the branch regions sizes so that we fill them up to their buffer sizes as we go branchStubsRegion.sizeInUse = 0; branchGOTsRegion.sizeInUse = 0; { // Map from each symbol to the list of dylibs which export it auto symbolMapOwner = std::make_unique<std::unordered_map<std::string_view, std::vector<DylibSymbolLocation>>>(); __block auto& symbolMap = *symbolMapOwner.get(); for (const auto& dylibNameAndSymbols : dylibsToSymbols) { const DylibSymbols& dylibSymbols = dylibNameAndSymbols.second; for (const auto& symbolNameAndAddress : dylibSymbols.globals) { // By default, everything i KPI, ie, can be linked by third parties. // If a symbol is is provided, even an empty one, then it can override this bool isKPI = true; if ( dylibSymbols.dylibName == "com.apple.kpi.private" ) { // com.apple.kpi.private is always hidden from third parties. They shouldn't even list it as a dependency isKPI = false; } else if ( dylibSymbols.kpiSymbols ) { const std::unordered_set<std::string>* kpiSymbols = dylibSymbols.kpiSymbols.get(); if ( kpiSymbols->count(symbolNameAndAddress.first.data()) == 0 ) isKPI = false; } symbolMap[symbolNameAndAddress.first].push_back({ &dylibSymbols, symbolNameAndAddress.second, isKPI }); } } auto dylibFixupsOwner = std::make_unique<std::vector<DylibFixups>>(); __block auto& dylibFixups = *dylibFixupsOwner.get(); dylibFixups.reserve(sortedDylibs.size()); forEachCacheDylib(^(const dyld3::MachOAnalyzer *ma, const std::string &dylibID, DylibStripMode stripMode, const std::vector<std::string> &dependencies, Diagnostics &dylibDiag, bool &stop) { auto dylibSymbolsIt = dylibsToSymbols.find(dylibID); assert(dylibSymbolsIt != dylibsToSymbols.end()); dylibFixups.emplace_back((DylibFixups){ .ma = ma, .dylibSymbols = dylibSymbolsIt->second, .dylibDiag = dylibDiag, .dependencies = dependencies }); }); dispatch_apply(dylibFixups.size(), DISPATCH_APPLY_AUTO, ^(size_t index) { DylibFixups& dylibFixup = dylibFixups[index]; dylibFixup.processFixups(dylibsToSymbols, symbolMap, kernelID, _aslrTracker); }); // Merge all the dylib results in serial for (DylibFixups& dylibFixup : dylibFixups) { // Skip bad dylibs if ( dylibFixup.dylibDiag.hasError() ) { if ( !_diagnostics.hasError() ) { _diagnostics.error("One or more binaries has an error which prevented linking. See other errors."); } return; } if ( !dylibFixup.missingBindLocations.empty() ) { missingBindLocations.insert(dylibFixup.missingBindLocations.begin(), dylibFixup.missingBindLocations.end()); } if ( !dylibFixup.fixupLocs.empty() ) { for (auto fixupLocAndLevel : dylibFixup.fixupLocs) { _aslrTracker.add(fixupLocAndLevel.first, fixupLocAndLevel.second); } } if ( !dylibFixup.fixupHigh8s.empty() ) { for (auto fixupLocAndHigh8 : dylibFixup.fixupHigh8s) { _aslrTracker.setHigh8(fixupLocAndHigh8.first, fixupLocAndHigh8.second); } } if ( !dylibFixup.fixupAuths.empty() ) { for (auto fixupLocAndAuth : dylibFixup.fixupAuths) { _aslrTracker.setAuthData(fixupLocAndAuth.first, fixupLocAndAuth.second.diversity, fixupLocAndAuth.second.addrDiv, fixupLocAndAuth.second.key); } } // Emit branch stubs const uint64_t loadAddress = dylibFixup.ma->preferredLoadAddress(); for (const DylibFixups::BranchStubData& branchData : dylibFixup.branchStubs) { // Branching from the auxKC to baseKC. ld64 doesn't emit a stub in x86_64 kexts // so we need to synthesize one now uint64_t targetAddress = 0; const CacheOffset& targetCacheOffset = branchData.targetCacheOffset; auto itAndInserted = branchStubs.insert({ targetCacheOffset, 0 }); if ( itAndInserted.second ) { // We inserted the branch location, so we need to create new stubs and GOTs if ( branchStubsRegion.sizeInUse == branchStubsRegion.bufferSize ) { _diagnostics.error("Overflow in branch stubs region"); return; } if ( branchGOTsRegion.sizeInUse == branchGOTsRegion.bufferSize ) { _diagnostics.error("Overflow in branch GOTs region"); return; } uint64_t stubAddress = branchStubsRegion.unslidLoadAddress + branchStubsRegion.sizeInUse; uint8_t* stubBuffer = branchStubsRegion.buffer + branchStubsRegion.sizeInUse; uint64_t gotAddress = branchGOTsRegion.unslidLoadAddress + branchGOTsRegion.sizeInUse; uint8_t* gotBuffer = branchGOTsRegion.buffer + branchGOTsRegion.sizeInUse; // Write the stub // ff 25 aa bb cc dd jmpq *0xddccbbaa(%rip) uint64_t diffValue = gotAddress - (stubAddress + 6); stubBuffer[0] = 0xFF; stubBuffer[1] = 0x25; memcpy(&stubBuffer[2], &diffValue, sizeof(uint32_t)); // And write the GOT uint8_t symbolCacheLevel = targetCacheOffset.first; uint64_t symbolVMAddr = targetCacheOffset.second; if ( _is64 ) *((uint64_t*)gotBuffer) = symbolVMAddr; else *((uint32_t*)gotBuffer) = (uint32_t)symbolVMAddr; _aslrTracker.add(gotBuffer, symbolCacheLevel); branchStubsRegion.sizeInUse += 6; branchGOTsRegion.sizeInUse += 8; targetAddress = stubAddress; itAndInserted.first->second = targetAddress; } else { // The stub already existed, so use it targetAddress = itAndInserted.first->second; } uint64_t diffValue = targetAddress - (loadAddress + branchData.fixupVMOffset + 4); *((uint32_t*)branchData.fixupLoc) = (uint32_t)diffValue; } } // FIXME: We could move symbolOwner and dylibFixupsOwner to a worker thread to be destroyed } // Now that we've processes all rebases/binds, patch all the vtables // Add all the collections to the vtable patcher if ( existingKernelCollection != nullptr ) { // The baseKC for x86_64 has __HIB mapped first , so we need to get either the __DATA or __TEXT depending on what is earliest // The kernel base address is still __TEXT, even if __DATA or __HIB is mapped prior to that. // The loader may have loaded something before __TEXT, but the existingKernelCollection pointer still corresponds to __TEXT __block uint64_t baseAddress = ~0ULL; existingKernelCollection->forEachSegment(^(const dyld3::MachOAnalyzer::SegmentInfo& info, bool& stop) { baseAddress = std::min(baseAddress, info.vmAddr); }); // The existing collection is a pointer to the mach_header for the baseKC, but __HIB and other segments may be before that // Offset those here uint64_t basePointerOffset = existingKernelCollection->preferredLoadAddress() - baseAddress; const uint8_t* basePointer = (uint8_t*)existingKernelCollection - basePointerOffset; vtablePatcher.addKernelCollection(existingKernelCollection, Options::AppCacheKind::kernel, basePointer, baseAddress); } if ( pageableKernelCollection != nullptr ) { // The baseKC for x86_64 has __HIB mapped first , so we need to get either the __DATA or __TEXT depending on what is earliest // The kernel base address is still __TEXT, even if __DATA or __HIB is mapped prior to that. // The loader may have loaded something before __TEXT, but the existingKernelCollection pointer still corresponds to __TEXT __block uint64_t baseAddress = ~0ULL; pageableKernelCollection->forEachSegment(^(const dyld3::MachOAnalyzer::SegmentInfo& info, bool& stop) { baseAddress = std::min(baseAddress, info.vmAddr); }); // The existing collection is a pointer to the mach_header for the baseKC, but __HIB and other segments may be before that // Offset those here uint64_t basePointerOffset = pageableKernelCollection->preferredLoadAddress() - baseAddress; const uint8_t* basePointer = (uint8_t*)pageableKernelCollection - basePointerOffset; vtablePatcher.addKernelCollection(pageableKernelCollection, Options::AppCacheKind::pageableKC, basePointer, baseAddress); } // Also add our KC vtablePatcher.addKernelCollection((const dyld3::MachOAppCache*)cacheHeader.header, appCacheOptions.cacheKind, (const uint8_t*)_fullAllocatedBuffer, cacheBaseAddress); // Add all the dylibs to the patcher { if ( existingKernelCollection != nullptr ) { uint8_t fixupLevel = getFixupLevel(Options::AppCacheKind::kernel); __block std::map<std::string, std::vector<std::string>> kextDependencies; kextDependencies[kernelID] = {}; existingKernelCollection->forEachPrelinkInfoLibrary(_diagnostics, ^(const char *bundleName, const char* relativePath, const std::vector<const char *> &deps) { std::vector<std::string>& dependencies = kextDependencies[bundleName]; dependencies.insert(dependencies.end(), deps.begin(), deps.end()); }); existingKernelCollection->forEachDylib(_diagnostics, ^(const dyld3::MachOAnalyzer *ma, const char *dylibID, bool &stop) { auto depsIt = kextDependencies.find(dylibID); assert(depsIt != kextDependencies.end()); vtablePatcher.addDylib(_diagnostics, ma, dylibID, depsIt->second, fixupLevel); }); } if ( pageableKernelCollection != nullptr ) { uint8_t fixupLevel = getFixupLevel(Options::AppCacheKind::pageableKC); __block std::map<std::string, std::vector<std::string>> kextDependencies; pageableKernelCollection->forEachPrelinkInfoLibrary(_diagnostics, ^(const char *bundleName, const char* relativePath, const std::vector<const char *> &deps) { std::vector<std::string>& dependencies = kextDependencies[bundleName]; dependencies.insert(dependencies.end(), deps.begin(), deps.end()); }); pageableKernelCollection->forEachDylib(_diagnostics, ^(const dyld3::MachOAnalyzer *ma, const char *dylibID, bool &stop) { auto depsIt = kextDependencies.find(dylibID); assert(depsIt != kextDependencies.end()); vtablePatcher.addDylib(_diagnostics, ma, dylibID, depsIt->second, fixupLevel); }); } forEachCacheDylib(^(const dyld3::MachOAnalyzer *ma, const std::string &dylibID, DylibStripMode stripMode, const std::vector<std::string> &dependencies, Diagnostics& dylibDiag, bool &stop) { vtablePatcher.addDylib(dylibDiag, ma, dylibID, dependencies, currentLevel); }); } vtablePatcher.findMetaclassDefinitions(dylibsToSymbols, kernelID, kernelMA, appCacheOptions.cacheKind); vtablePatcher.findExistingFixups(_diagnostics, existingKernelCollection, pageableKernelCollection); if ( _diagnostics.hasError() ) return; // Add vtables from the base KC if we have one if ( existingKernelCollection != nullptr ) { vtablePatcher.findBaseKernelVTables(_diagnostics, existingKernelCollection, dylibsToSymbols); if ( _diagnostics.hasError() ) return; } // Add vtables from the pageable KC if we have one if ( pageableKernelCollection != nullptr ) { vtablePatcher.findPageableKernelVTables(_diagnostics, pageableKernelCollection, dylibsToSymbols); if ( _diagnostics.hasError() ) return; } // Add vables from our level vtablePatcher.findVTables(currentLevel, kernelMA, dylibsToSymbols, _aslrTracker, missingBindLocations); // Don't run the patcher if we have a failure finding the vtables if ( vtablePatcher.hasError() ) { _diagnostics.error("One or more binaries has an error which prevented linking. See other errors."); return; } // Now patch all of the vtables. vtablePatcher.patchVTables(_diagnostics, missingBindLocations, _aslrTracker, currentLevel); if ( _diagnostics.hasError() ) return; if ( vtablePatcher.hasError() ) { _diagnostics.error("One or more binaries has an error which prevented linking. See other errors."); return; } // FIXME: We could move vtablePatcherOwner to a worker thread to be destroyed vtablePatcherOwner.reset(); // Also error out if we have an error on any of the dylib diagnostic objects // Log any binds which are still missing for (const auto& missingLocationAndBind : missingBindLocations) { const uint8_t* missingBindLoc = missingLocationAndBind.first; const VTableBindSymbol& missingBind = missingLocationAndBind.second; // Work out which segment and section this missing bind was in __block bool reportedError = false; forEachCacheDylib(^(const dyld3::MachOAnalyzer *ma, const std::string &dylibID, DylibStripMode stripMode, const std::vector<std::string> &dependencies, Diagnostics& dylibDiag, bool &stopDylib) { intptr_t slide = ma->getSlide(); ma->forEachSection(^(const dyld3::MachOAnalyzer::SectionInfo §Info, bool malformedSectionRange, bool &stopSection) { const uint8_t* content = (uint8_t*)(sectInfo.sectAddr + slide); const uint8_t* start = (uint8_t*)content; const uint8_t* end = start + sectInfo.sectSize; if ( (missingBindLoc >= start) && (missingBindLoc < end) ) { std::string segmentName = sectInfo.segInfo.segName; std::string sectionName = sectInfo.sectName; uint64_t sectionOffset = (missingBindLoc - start); dylibDiag.error("Failed to bind '%s' in '%s' (at offset 0x%llx in %s, %s) as " "could not find a kext which exports this symbol", missingBind.symbolName.c_str(), missingBind.binaryID.data(), sectionOffset, segmentName.c_str(), sectionName.c_str()); reportedError = true; stopSection = true; stopDylib = true; } }); }); if ( !reportedError ) { _diagnostics.error("Failed to bind '%s' in '%s' as could not find a kext which exports this symbol", missingBind.symbolName.c_str(), missingBind.binaryID.data()); } } // If we had missing binds and reported no other errors, then generate an error to give the diagnostics something to track if ( !missingBindLocations.empty() && _diagnostics.noError() ) { _diagnostics.error("One or more binaries has an error which prevented linking. See other errors."); } // FIXME: We could move dylibsToSymbolsOwner to a worker thread to be destroyed } namespace { class ByteBuffer { public: ByteBuffer(uint8_t* storage, uintptr_t allocCount) { buffer.setInitialStorage(storage, allocCount); } uint8_t* makeSpace(size_t bytesNeeded) { // Make space in the buffer for (size_t i = 0; i != bytesNeeded; ++i) buffer.default_constuct_back(); // Grab a pointer to our position in the buffer uint8_t* data = buffer.begin(); // Move the buffer to start after our data dyld3::Array<uint8_t> newBuffer(buffer.end(), buffer.freeCount(), 0); buffer = newBuffer; return data; }; const uint8_t* begin() const { return buffer.begin(); } const uint8_t* end() const { return buffer.end(); } private: dyld3::Array<uint8_t> buffer; }; } void AppCacheBuilder::writeFixups() { if ( fixupsSubRegion.sizeInUse == 0 ) return; __block ByteBuffer byteBuffer(fixupsSubRegion.buffer, fixupsSubRegion.bufferSize); // Keep track of where we put the fixups const uint8_t* classicRelocsBufferStart = nullptr; const uint8_t* classicRelocsBufferEnd = nullptr; // If the kernel needs classic relocs, emit those first CacheHeader64& header = cacheHeader; if ( header.dynSymbolTable != nullptr ) { classicRelocsBufferStart = byteBuffer.begin(); dyld3::MachOAnalyzer* cacheMA = (dyld3::MachOAnalyzer*)header.header; __block uint64_t localRelocBaseAddress = 0; cacheMA->forEachSegment(^(const dyld3::MachOAnalyzer::SegmentInfo &info, bool &stop) { if ( info.protections & VM_PROT_WRITE ) { localRelocBaseAddress = info.vmAddr; stop = true; } }); const std::vector<void*> allRebaseTargets = _aslrTracker.getRebaseTargets(); const dyld3::MachOAnalyzer* kernelMA = getKernelStaticExecutableFromCache(); kernelMA->forEachSegment(^(const dyld3::MachOAnalyzer::SegmentInfo &info, bool &stop) { std::vector<void*> segmentRebaseTargets; uint64_t segmentVMOffset = info.vmAddr - cacheBaseAddress; const uint8_t* segmentStartAddr = (const uint8_t*)(_fullAllocatedBuffer + segmentVMOffset); const uint8_t* segmentEndAddr = (const uint8_t*)(segmentStartAddr + info.vmSize); for (void* target : allRebaseTargets) { if ( (target >= segmentStartAddr) && (target < segmentEndAddr) ) { segmentRebaseTargets.push_back(target); } } std::sort(segmentRebaseTargets.begin(), segmentRebaseTargets.end()); for (void* target : segmentRebaseTargets) { uint64_t targetSegmentOffset = (uint64_t)target - (uint64_t)segmentStartAddr; //printf("Target: %s + 0x%llx: %p\n", info.segName, targetSegmentOffset, target); uint64_t offsetFromBaseAddress = (info.vmAddr + targetSegmentOffset) - localRelocBaseAddress; relocation_info* reloc = (relocation_info*)byteBuffer.makeSpace(sizeof(relocation_info)); reloc->r_address = (uint32_t)offsetFromBaseAddress; reloc->r_symbolnum = 0; reloc->r_pcrel = false; reloc->r_length = 0; reloc->r_extern = 0; reloc->r_type = 0; uint32_t vmAddr32 = 0; uint64_t vmAddr64 = 0; if ( _aslrTracker.hasRebaseTarget32(target, &vmAddr32) ) { reloc->r_length = 2; *(uint32_t*)target = vmAddr32; } else if ( _aslrTracker.hasRebaseTarget64(target, &vmAddr64) ) { reloc->r_length = 3; *(uint64_t*)target = vmAddr64; } } // Remove these fixups so that we don't also emit chained fixups for them for (void* target : segmentRebaseTargets) _aslrTracker.remove(target); }); classicRelocsBufferEnd = byteBuffer.begin(); } // TODO: 32-bit pointer format assert(_is64); const uint8_t currentLevel = getCurrentFixupLevel(); // We can have up to 4 levels in the fixup format. These are the base addresses from // which each level starts BLOCK_ACCCESSIBLE_ARRAY(uint64_t, levelBaseAddresses, 4); for (unsigned i = 0; i != numFixupLevels; ++i) levelBaseAddresses[i] = 0; levelBaseAddresses[currentLevel] = cacheBaseAddress; if ( appCacheOptions.cacheKind != Options::AppCacheKind::kernel ) { assert(existingKernelCollection != nullptr); // The auxKC is mapped with __DATA first, so we need to get either the __DATA or __TEXT depending on what is earliest __block uint64_t baseAddress = ~0ULL; existingKernelCollection->forEachSegment(^(const dyld3::MachOAnalyzer::SegmentInfo& info, bool& stop) { baseAddress = std::min(baseAddress, info.vmAddr); }); levelBaseAddresses[0] = baseAddress; } if ( pageableKernelCollection != nullptr ) { // We may have __DATA first, so we need to get either the __DATA or __TEXT depending on what is earliest __block uint64_t baseAddress = ~0ULL; pageableKernelCollection->forEachSegment(^(const dyld3::MachOAnalyzer::SegmentInfo& info, bool& stop) { baseAddress = std::min(baseAddress, info.vmAddr); }); uint8_t fixupLevel = getFixupLevel(Options::AppCacheKind::pageableKC); levelBaseAddresses[fixupLevel] = baseAddress; } // We have a dyld_chained_starts_in_segment plus an offset for each page struct SegmentFixups { //const Region* region = nullptr; uint8_t* segmentBuffer = nullptr; uint64_t segmentIndex = 0; uint64_t unslidLoadAddress = 0; uint64_t sizeInUse = 0; dyld_chained_starts_in_segment* starts = nullptr; uint64_t startsByteSize = 0; uint64_t numPagesToFixup = 0; }; auto buildChainedFixups = ^(uint64_t baseAddress, uint64_t segmentCount, std::vector<SegmentFixups>& startsInSegments) { const uint8_t* chainedFixupsBufferStart = nullptr; const uint8_t* chainedFixupsBufferEnd = nullptr; chainedFixupsBufferStart = byteBuffer.begin(); // Start with dyld_chained_fixups_header which is fixed size dyld_chained_fixups_header* fixupsHeader = (dyld_chained_fixups_header*)byteBuffer.makeSpace(sizeof(dyld_chained_fixups_header)); // We have a dyld_chained_starts_in_image plus an offset for each segment dyld_chained_starts_in_image* startsInImage = (dyld_chained_starts_in_image*)byteBuffer.makeSpace(sizeof(dyld_chained_starts_in_image) + (segmentCount * sizeof(uint32_t))); const uint8_t* endOfStarts = nullptr; for (SegmentFixups& segmentFixups : startsInSegments) { uint64_t startsInSegmentByteSize = sizeof(dyld_chained_starts_in_segment) + (segmentFixups.numPagesToFixup * sizeof(uint16_t)); dyld_chained_starts_in_segment* startsInSegment = (dyld_chained_starts_in_segment*)byteBuffer.makeSpace(startsInSegmentByteSize); endOfStarts = (const uint8_t*)startsInSegment + startsInSegmentByteSize; segmentFixups.starts = startsInSegment; segmentFixups.startsByteSize = startsInSegmentByteSize; } // Starts in image startsInImage->seg_count = (uint32_t)segmentCount; for (uint32_t segmentIndex = 0; segmentIndex != segmentCount; ++segmentIndex) { startsInImage->seg_info_offset[segmentIndex] = 0; } for (const SegmentFixups& segmentFixups : startsInSegments) { dyld_chained_starts_in_segment* startsInSegment = segmentFixups.starts; uint64_t segmentIndex = segmentFixups.segmentIndex; assert(segmentIndex < segmentCount); assert(startsInImage->seg_info_offset[segmentIndex] == 0); startsInImage->seg_info_offset[segmentIndex] = (uint32_t)((uint8_t*)startsInSegment - (uint8_t*)startsInImage); } const unsigned chainedPointerStride = dyld3::MachOAnalyzer::ChainedFixupPointerOnDisk::strideSize(chainedPointerFormat); // Starts in segment for (const SegmentFixups& segmentFixups : startsInSegments) { dyld_chained_starts_in_segment* startsInSegment = segmentFixups.starts; startsInSegment->size = (uint32_t)segmentFixups.startsByteSize; startsInSegment->page_size = fixupsPageSize(); startsInSegment->pointer_format = chainedPointerFormat; startsInSegment->segment_offset = segmentFixups.unslidLoadAddress - baseAddress; startsInSegment->max_valid_pointer = 0; // FIXME: Needed in 32-bit only startsInSegment->page_count = (segmentFixups.sizeInUse + startsInSegment->page_size - 1) / startsInSegment->page_size; for (uint64_t pageIndex = 0; pageIndex != startsInSegment->page_count; ++pageIndex) { startsInSegment->page_start[pageIndex] = DYLD_CHAINED_PTR_START_NONE; uint8_t* lastLoc = nullptr; // Note we always walk in 1-byte at a time as x86_64 has unaligned fixups for (uint64_t pageOffset = 0; pageOffset != startsInSegment->page_size; pageOffset += 1) { uint8_t* fixupLoc = segmentFixups.segmentBuffer + (pageIndex * startsInSegment->page_size) + pageOffset; uint8_t fixupLevel = currentLevel; if ( !_aslrTracker.has(fixupLoc, &fixupLevel) ) continue; assert((pageOffset % chainedPointerStride) == 0); if ( lastLoc ) { // Patch last loc to point here assert(_is64); dyld_chained_ptr_64_kernel_cache_rebase* lastLocBits = (dyld_chained_ptr_64_kernel_cache_rebase*)lastLoc; assert(lastLocBits->next == 0); uint64_t next = (fixupLoc - lastLoc) / chainedPointerStride; lastLocBits->next = next; assert(lastLocBits->next == next && "next location truncated"); } else { // First fixup on this page startsInSegment->page_start[pageIndex] = pageOffset; } lastLoc = fixupLoc; uint64_t targetVMAddr = *(uint64_t*)fixupLoc; uint8_t highByte = 0; if ( _aslrTracker.hasHigh8(fixupLoc, &highByte) ) { uint64_t tbi = (uint64_t)highByte << 56; targetVMAddr |= tbi; } assert(fixupLevel < numFixupLevels); uint64_t targetVMOffset = targetVMAddr - levelBaseAddresses[fixupLevel]; // Pack the vmAddr on this location in to the fixup format dyld_chained_ptr_64_kernel_cache_rebase* locBits = (dyld_chained_ptr_64_kernel_cache_rebase*)fixupLoc; uint16_t diversity; bool hasAddrDiv; uint8_t key; if ( _aslrTracker.hasAuthData(fixupLoc, &diversity, &hasAddrDiv, &key) ) { locBits->target = targetVMOffset; locBits->cacheLevel = fixupLevel; locBits->diversity = diversity; locBits->addrDiv = hasAddrDiv; locBits->key = key; locBits->next = 0; locBits->isAuth = 1; assert(locBits->target == targetVMOffset && "target truncated"); } else { locBits->target = targetVMOffset; locBits->cacheLevel = fixupLevel; locBits->diversity = 0; locBits->addrDiv = 0; locBits->key = 0; locBits->next = 0; locBits->isAuth = 0; assert(locBits->target == targetVMOffset && "target truncated"); } } } } chainedFixupsBufferEnd = byteBuffer.begin(); // Header fixupsHeader->fixups_version = 0; fixupsHeader->starts_offset = (uint32_t)((uint8_t*)startsInImage - (uint8_t*)fixupsHeader); fixupsHeader->imports_offset = (uint32_t)((uint8_t*)chainedFixupsBufferEnd - (uint8_t*)fixupsHeader); fixupsHeader->symbols_offset = fixupsHeader->imports_offset; fixupsHeader->imports_count = 0; fixupsHeader->imports_format = DYLD_CHAINED_IMPORT; // The validate code wants a value here fixupsHeader->symbols_format = 0; return std::make_pair(chainedFixupsBufferStart, chainedFixupsBufferEnd); }; if ( fixupsArePerKext() ) { // The pageableKC (and sometimes auxKC) has one LC_DYLD_CHAINED_FIXUPS per kext, not 1 total forEachCacheDylib(^(const dyld3::MachOAnalyzer *ma, const std::string &dylibID, DylibStripMode stripMode, const std::vector<std::string> &dependencies, Diagnostics& dylibDiag, bool &stop) { uint64_t loadAddress = ma->preferredLoadAddress(); __block uint64_t numSegments = 0; __block std::vector<SegmentFixups> segmentFixups; ma->forEachSegment(^(const dyld3::MachOAnalyzer::SegmentInfo &info, bool &stopSegments) { // Third party kexts have writable __TEXT, so we need to add starts for all segments // other than LINKEDIT bool segmentCanHaveFixups = false; if ( appCacheOptions.cacheKind == Options::AppCacheKind::pageableKC ) { segmentCanHaveFixups = (info.protections & VM_PROT_WRITE) != 0; } else { // auxKC segmentCanHaveFixups = (strcmp(info.segName, "__LINKEDIT") != 0); } if ( segmentCanHaveFixups) { SegmentFixups segmentToFixup; segmentToFixup.segmentBuffer = (uint8_t*)ma + (info.vmAddr - loadAddress); segmentToFixup.segmentIndex = info.segIndex; segmentToFixup.unslidLoadAddress = info.vmAddr; segmentToFixup.sizeInUse = info.vmSize; segmentToFixup.starts = nullptr; segmentToFixup.startsByteSize = 0; segmentToFixup.numPagesToFixup = numWritablePagesToFixup(info.vmSize); segmentFixups.push_back(segmentToFixup); } ++numSegments; }); std::pair<const uint8_t*, const uint8_t*> chainedFixupsRange = buildChainedFixups(loadAddress, numSegments, segmentFixups); const uint8_t* chainedFixupsBufferStart = chainedFixupsRange.first; const uint8_t* chainedFixupsBufferEnd = chainedFixupsRange.second; if ( chainedFixupsBufferStart != chainedFixupsBufferEnd ) { // Add the load command to our file uint64_t fixupsOffset = (uint64_t)chainedFixupsBufferStart - (uint64_t)fixupsSubRegion.buffer; uint64_t fixupsSize = (uint64_t)chainedFixupsBufferEnd - (uint64_t)chainedFixupsBufferStart; // 64-bit assert(_is64); typedef Pointer64<LittleEndian> P; uint32_t freeSpace = ma->loadCommandsFreeSpace(); assert(freeSpace >= sizeof(macho_linkedit_data_command<P>)); uint8_t* endOfLoadCommands = (uint8_t*)ma + sizeof(macho_header<P>) + ma->sizeofcmds; // update mach_header to account for new load commands macho_header<P>* mh = (macho_header<P>*)ma; mh->set_sizeofcmds(mh->sizeofcmds() + sizeof(macho_linkedit_data_command<P>)); mh->set_ncmds(mh->ncmds() + 1); // Add the new load command macho_linkedit_data_command<P>* cmd = (macho_linkedit_data_command<P>*)endOfLoadCommands; cmd->set_cmd(LC_DYLD_CHAINED_FIXUPS); cmd->set_cmdsize(sizeof(linkedit_data_command)); cmd->set_dataoff((uint32_t)(_readOnlyRegion.cacheFileOffset + _readOnlyRegion.sizeInUse + fixupsOffset)); cmd->set_datasize((uint32_t)fixupsSize); } }); // Also build chained fixups on the top level for the branch stub GOTs // FIXME: We don't need numRegions() here, but instead just up to an including the RW region uint64_t segmentCount = numRegions(); __block std::vector<SegmentFixups> segmentFixups; if ( branchGOTsRegion.sizeInUse != 0 ) { SegmentFixups segmentToFixup; segmentToFixup.segmentBuffer = branchGOTsRegion.buffer; segmentToFixup.segmentIndex = branchGOTsRegion.index; segmentToFixup.unslidLoadAddress = branchGOTsRegion.unslidLoadAddress; segmentToFixup.sizeInUse = branchGOTsRegion.sizeInUse; segmentToFixup.starts = nullptr; segmentToFixup.startsByteSize = 0; segmentToFixup.numPagesToFixup = numWritablePagesToFixup(branchGOTsRegion.bufferSize); segmentFixups.push_back(segmentToFixup); } std::pair<const uint8_t*, const uint8_t*> chainedFixupsRange = buildChainedFixups(cacheHeaderRegion.unslidLoadAddress, segmentCount, segmentFixups); const uint8_t* chainedFixupsBufferStart = chainedFixupsRange.first; const uint8_t* chainedFixupsBufferEnd = chainedFixupsRange.second; if ( chainedFixupsBufferStart != chainedFixupsBufferEnd ) { uint64_t fixupsOffset = (uint64_t)chainedFixupsBufferStart - (uint64_t)fixupsSubRegion.buffer; uint64_t fixupsSize = (uint64_t)chainedFixupsBufferEnd - (uint64_t)chainedFixupsBufferStart; header.chainedFixups->dataoff = (uint32_t)_readOnlyRegion.cacheFileOffset + (uint32_t)_readOnlyRegion.sizeInUse + (uint32_t)fixupsOffset; header.chainedFixups->datasize = (uint32_t)fixupsSize; } } else { // Build the chained fixups for just the kernel collection itself // FIXME: We don't need numRegions() here, but instead just up to an including the RW region uint64_t segmentCount = numRegions(); __block std::vector<SegmentFixups> segmentFixups; auto addSegmentStarts = ^(const Region& region) { SegmentFixups segmentToFixup; segmentToFixup.segmentBuffer = region.buffer; segmentToFixup.segmentIndex = region.index; segmentToFixup.unslidLoadAddress = region.unslidLoadAddress; segmentToFixup.sizeInUse = region.sizeInUse; segmentToFixup.starts = nullptr; segmentToFixup.startsByteSize = 0; segmentToFixup.numPagesToFixup = numWritablePagesToFixup(region.bufferSize); segmentFixups.push_back(segmentToFixup); }; if ( dataConstRegion.sizeInUse != 0 ) addSegmentStarts(dataConstRegion); if ( branchGOTsRegion.sizeInUse != 0 ) addSegmentStarts(branchGOTsRegion); if ( readWriteRegion.sizeInUse != 0 ) addSegmentStarts(readWriteRegion); if ( hibernateRegion.sizeInUse != 0 ) addSegmentStarts(hibernateRegion); for (const Region& region : nonSplitSegRegions) { // Assume writable regions have fixups to emit // Note, third party kext's have __TEXT fixups, so assume all of these have fixups // LINKEDIT is already elsewhere addSegmentStarts(region); } std::pair<const uint8_t*, const uint8_t*> chainedFixupsRange = buildChainedFixups(cacheHeaderRegion.unslidLoadAddress, segmentCount, segmentFixups); const uint8_t* chainedFixupsBufferStart = chainedFixupsRange.first; const uint8_t* chainedFixupsBufferEnd = chainedFixupsRange.second; if ( chainedFixupsBufferStart != chainedFixupsBufferEnd ) { uint64_t fixupsOffset = (uint64_t)chainedFixupsBufferStart - (uint64_t)fixupsSubRegion.buffer; uint64_t fixupsSize = (uint64_t)chainedFixupsBufferEnd - (uint64_t)chainedFixupsBufferStart; header.chainedFixups->dataoff = (uint32_t)_readOnlyRegion.cacheFileOffset + (uint32_t)_readOnlyRegion.sizeInUse + (uint32_t)fixupsOffset; header.chainedFixups->datasize = (uint32_t)fixupsSize; } } // Move the fixups to the end of __LINKEDIT if ( classicRelocsBufferStart != classicRelocsBufferEnd ) { uint64_t fixupsOffset = (uint64_t)classicRelocsBufferStart - (uint64_t)fixupsSubRegion.buffer; uint64_t fixupsSize = (uint64_t)classicRelocsBufferEnd - (uint64_t)classicRelocsBufferStart; header.dynSymbolTable->locreloff = (uint32_t)_readOnlyRegion.cacheFileOffset + (uint32_t)_readOnlyRegion.sizeInUse + (uint32_t)fixupsOffset; header.dynSymbolTable->nlocrel = (uint32_t)fixupsSize / sizeof(fixupsSize); } uint64_t fixupsSpace = (uint64_t)byteBuffer.end() - (uint64_t)fixupsSubRegion.buffer; uint8_t* linkeditEnd = _readOnlyRegion.buffer + _readOnlyRegion.sizeInUse; memcpy(linkeditEnd, fixupsSubRegion.buffer, fixupsSpace); uint8_t* fixupsEnd = linkeditEnd + fixupsSpace; _readOnlyRegion.sizeInUse += align(fixupsSpace, _is64 ? 3 : 2); _readOnlyRegion.sizeInUse = align(_readOnlyRegion.sizeInUse, 14); _readOnlyRegion.bufferSize = _readOnlyRegion.sizeInUse; // Zero the alignment gap, just in case there's any unoptimized LINKEDIT in there uint8_t* alignedBufferEnd = _readOnlyRegion.buffer + _readOnlyRegion.sizeInUse; if ( fixupsEnd != alignedBufferEnd ){ memset(fixupsEnd, 0, alignedBufferEnd - fixupsEnd); } #if 0 dyld3::MachOAnalyzer* cacheMA = (dyld3::MachOAnalyzer*)header.header; uint64_t cachePreferredLoadAddress = cacheMA->preferredLoadAddress(); cacheMA->forEachRebase(_diagnostics, false, ^(uint64_t runtimeOffset, bool &stop) { printf("Rebase: 0x%llx = 0x%llx\n", runtimeOffset, runtimeOffset + cachePreferredLoadAddress); }); #endif } void AppCacheBuilder::allocateBuffer() { // Whether to order the regions __TEXT, __DATA, __LINKEDIT or __DATA, __TEXT, __LINKEDIT in VM address order bool dataRegionFirstInVMOrder = false; bool hibernateRegionFirstInVMOrder = false; switch (appCacheOptions.cacheKind) { case Options::AppCacheKind::none: assert(0 && "Cache kind should have been set"); break; case Options::AppCacheKind::kernel: if ( hibernateAddress != 0 ) hibernateRegionFirstInVMOrder = true; break; case Options::AppCacheKind::pageableKC: // There's no interesting ordering for the pageableKC break; case Options::AppCacheKind::kernelCollectionLevel2: assert(0 && "Unimplemented"); break; case Options::AppCacheKind::auxKC: dataRegionFirstInVMOrder = true; break; } // Count how many bytes we need from all our regions __block uint64_t numRegionFileBytes = 0; __block uint64_t numRegionVMBytes = 0; std::vector<std::pair<Region*, uint64_t>> regions; std::vector<std::pair<Region*, uint64_t>> regionsVMOrder; std::map<const Region*, uint32_t> sectionsToAddToRegions; if ( hibernateRegionFirstInVMOrder ) { regionsVMOrder.push_back({ &hibernateRegion, numRegionVMBytes }); // Pad out the VM offset so that the cache header starts where the base address // really should be uint64_t paddedSize = cacheBaseAddress - hibernateAddress; if ( hibernateRegion.bufferSize > paddedSize ) { _diagnostics.error("Could not lay out __HIB segment"); return; } numRegionVMBytes = paddedSize; // Set the base address to the hibernate address so that we actually put the // hibernate segment there cacheBaseAddress = hibernateAddress; // Add a section too sectionsToAddToRegions[&hibernateRegion] = 1; } else if ( dataRegionFirstInVMOrder ) { if ( prelinkInfoDict != nullptr ) { numRegionVMBytes = align(numRegionVMBytes, 14); regionsVMOrder.push_back({ &prelinkInfoRegion, numRegionVMBytes }); numRegionVMBytes += prelinkInfoRegion.bufferSize; } if ( readWriteRegion.sizeInUse != 0 ) { numRegionVMBytes = align(numRegionVMBytes, 14); regionsVMOrder.push_back({ &readWriteRegion, numRegionVMBytes }); numRegionVMBytes += readWriteRegion.bufferSize; } } // Cache header numRegionVMBytes = align(numRegionVMBytes, 14); regions.push_back({ &cacheHeaderRegion, 0 }); regionsVMOrder.push_back({ &cacheHeaderRegion, numRegionVMBytes }); // Split seg __TEXT { // File offset readOnlyTextRegion.cacheFileOffset = numRegionFileBytes; numRegionFileBytes += readOnlyTextRegion.bufferSize; regions.push_back({ &readOnlyTextRegion, 0 }); // VM offset numRegionVMBytes = align(numRegionVMBytes, 14); regionsVMOrder.push_back({ &readOnlyTextRegion, numRegionVMBytes }); numRegionVMBytes += readOnlyTextRegion.bufferSize; // Add a section too sectionsToAddToRegions[&readOnlyTextRegion] = 1; } // Split seg __TEXT_EXEC if ( readExecuteRegion.sizeInUse != 0 ) { // File offset readExecuteRegion.cacheFileOffset = numRegionFileBytes; numRegionFileBytes += readExecuteRegion.bufferSize; regions.push_back({ &readExecuteRegion, 0 }); // VM offset numRegionVMBytes = align(numRegionVMBytes, 14); regionsVMOrder.push_back({ &readExecuteRegion, numRegionVMBytes }); numRegionVMBytes += readExecuteRegion.bufferSize; } // __BRANCH_STUBS if ( branchStubsRegion.bufferSize != 0 ) { // File offset branchStubsRegion.cacheFileOffset = numRegionFileBytes; numRegionFileBytes += branchStubsRegion.bufferSize; regions.push_back({ &branchStubsRegion, 0 }); // VM offset numRegionVMBytes = align(numRegionVMBytes, 14); regionsVMOrder.push_back({ &branchStubsRegion, numRegionVMBytes }); numRegionVMBytes += branchStubsRegion.bufferSize; } // __DATA_CONST if ( dataConstRegion.sizeInUse != 0 ) { // File offset dataConstRegion.cacheFileOffset = numRegionFileBytes; numRegionFileBytes += dataConstRegion.bufferSize; regions.push_back({ &dataConstRegion, 0 }); // VM offset numRegionVMBytes = align(numRegionVMBytes, 14); regionsVMOrder.push_back({ &dataConstRegion, numRegionVMBytes }); numRegionVMBytes += dataConstRegion.bufferSize; } // __BRANCH_GOTS if ( branchGOTsRegion.bufferSize != 0 ) { // File offset branchGOTsRegion.cacheFileOffset = numRegionFileBytes; numRegionFileBytes += branchGOTsRegion.bufferSize; regions.push_back({ &branchGOTsRegion, 0 }); // VM offset numRegionVMBytes = align(numRegionVMBytes, 14); regionsVMOrder.push_back({ &branchGOTsRegion, numRegionVMBytes }); numRegionVMBytes += branchGOTsRegion.bufferSize; } // -sectcreate // Align to 16k before we lay out all contiguous regions numRegionFileBytes = align(numRegionFileBytes, 14); for (CustomSegment& customSegment : customSegments) { Region& region = *customSegment.parentRegion; region.cacheFileOffset = numRegionFileBytes; numRegionFileBytes += region.bufferSize; regions.push_back({ ®ion, 0 }); // VM offset // Note we can't align the vm offset in here assert( (numRegionVMBytes % 4096) == 0); regionsVMOrder.push_back({ ®ion, numRegionVMBytes }); numRegionVMBytes += region.bufferSize; // Maybe add sections too uint32_t sectionsToAdd = 0; if ( customSegment.sections.size() > 1 ) { // More than one section, so they all need names sectionsToAdd = (uint32_t)customSegment.sections.size(); } else if ( !customSegment.sections.front().sectionName.empty() ) { // Only one section, but it has a name sectionsToAdd = 1; } sectionsToAddToRegions[®ion] = sectionsToAdd; } numRegionVMBytes = align(numRegionVMBytes, 14); // __PRELINK_INFO // Align to 16k numRegionFileBytes = align(numRegionFileBytes, 14); if ( prelinkInfoDict != nullptr ) { // File offset prelinkInfoRegion.cacheFileOffset = numRegionFileBytes; numRegionFileBytes += prelinkInfoRegion.bufferSize; regions.push_back({ &prelinkInfoRegion, 0 }); if ( !dataRegionFirstInVMOrder ) { // VM offset numRegionVMBytes = align(numRegionVMBytes, 14); regionsVMOrder.push_back({ &prelinkInfoRegion, numRegionVMBytes }); numRegionVMBytes += prelinkInfoRegion.bufferSize; } // Add a section too sectionsToAddToRegions[&prelinkInfoRegion] = 1; } // Split seg __DATA // Align to 16k numRegionFileBytes = align(numRegionFileBytes, 14); if ( readWriteRegion.sizeInUse != 0 ) { // File offset readWriteRegion.cacheFileOffset = numRegionFileBytes; numRegionFileBytes += readWriteRegion.bufferSize; regions.push_back({ &readWriteRegion, 0 }); if ( !dataRegionFirstInVMOrder ) { // VM offset numRegionVMBytes = align(numRegionVMBytes, 14); regionsVMOrder.push_back({ &readWriteRegion, numRegionVMBytes }); numRegionVMBytes += readWriteRegion.bufferSize; } } // Split seg __HIB // Align to 16k numRegionFileBytes = align(numRegionFileBytes, 14); if ( hibernateRegion.sizeInUse != 0 ) { // File offset hibernateRegion.cacheFileOffset = numRegionFileBytes; numRegionFileBytes += hibernateRegion.bufferSize; regions.push_back({ &hibernateRegion, 0 }); // VM offset was already handled earlier } // Non split seg regions // Align to 16k before we lay out all contiguous regions numRegionFileBytes = align(numRegionFileBytes, 14); for (Region& region : nonSplitSegRegions) { region.cacheFileOffset = numRegionFileBytes; numRegionFileBytes += region.bufferSize; regions.push_back({ ®ion, 0 }); // VM offset // Note we can't align the vm offset in here assert( (numRegionVMBytes % 4096) == 0); regionsVMOrder.push_back({ ®ion, numRegionVMBytes }); numRegionVMBytes += region.bufferSize; } numRegionVMBytes = align(numRegionVMBytes, 14); // __LINKEDIT // Align to 16k // File offset numRegionFileBytes = align(numRegionFileBytes, 14); _readOnlyRegion.cacheFileOffset = numRegionFileBytes; numRegionFileBytes += _readOnlyRegion.bufferSize; regions.push_back({ &_readOnlyRegion, 0 }); // VM offset numRegionVMBytes = align(numRegionVMBytes, 14); regionsVMOrder.push_back({ &_readOnlyRegion, numRegionVMBytes }); numRegionVMBytes += _readOnlyRegion.bufferSize; // __LINKEDIT fixups sub region // Align to 16k numRegionFileBytes = align(numRegionFileBytes, 14); if ( fixupsSubRegion.sizeInUse != 0 ) { fixupsSubRegion.cacheFileOffset = numRegionFileBytes; numRegionFileBytes += fixupsSubRegion.bufferSize; //regions.push_back({ &fixupsSubRegion, 0 }); // VM offset regionsVMOrder.push_back({ &fixupsSubRegion, numRegionVMBytes }); numRegionVMBytes += fixupsSubRegion.bufferSize; } const thread_command* unixThread = nullptr; if (const DylibInfo* dylib = getKernelStaticExecutableInputFile()) { unixThread = dylib->input->mappedFile.mh->unixThreadLoadCommand(); } if (_is64) { const uint64_t cacheHeaderSize = sizeof(mach_header_64); uint64_t cacheLoadCommandsSize = 0; uint64_t cacheNumLoadCommands = 0; // UUID ++cacheNumLoadCommands; uint64_t uuidOffset = cacheHeaderSize + cacheLoadCommandsSize; cacheLoadCommandsSize += sizeof(uuid_command); // BUILD VERSION ++cacheNumLoadCommands; uint64_t buildVersionOffset = cacheHeaderSize + cacheLoadCommandsSize; cacheLoadCommandsSize += sizeof(build_version_command); // UNIX THREAD uint64_t unixThreadOffset = 0; if ( unixThread != nullptr ) { ++cacheNumLoadCommands; unixThreadOffset = cacheHeaderSize + cacheLoadCommandsSize; cacheLoadCommandsSize += unixThread->cmdsize; } // SYMTAB and DYSYMTAB uint64_t symbolTableOffset = 0; uint64_t dynSymbolTableOffset = 0; if (const DylibInfo* dylib = getKernelStaticExecutableInputFile()) { if ( dylib->input->mappedFile.mh->usesClassicRelocationsInKernelCollection() ) { // SYMTAB ++cacheNumLoadCommands; symbolTableOffset = cacheHeaderSize + cacheLoadCommandsSize; cacheLoadCommandsSize += sizeof(symtab_command); // DYSYMTAB ++cacheNumLoadCommands; dynSymbolTableOffset = cacheHeaderSize + cacheLoadCommandsSize; cacheLoadCommandsSize += sizeof(dysymtab_command); } } // LC_DYLD_CHAINED_FIXUPS // The pageableKC has one LC_DYLD_CHAINED_FIXUPS per kext, and 1 more on the top-level // for the branch GOTs uint64_t chainedFixupsOffset = 0; if ( fixupsSubRegion.bufferSize != 0 ) { ++cacheNumLoadCommands; chainedFixupsOffset = cacheHeaderSize + cacheLoadCommandsSize; cacheLoadCommandsSize += sizeof(linkedit_data_command); } // Add an LC_SEGMENT_64 for each region for (auto& regionAndOffset : regions) { ++cacheNumLoadCommands; regionAndOffset.second = cacheHeaderSize + cacheLoadCommandsSize; cacheLoadCommandsSize += sizeof(segment_command_64); // Add space for any sections too auto sectionIt = sectionsToAddToRegions.find(regionAndOffset.first); if ( sectionIt != sectionsToAddToRegions.end() ) { uint32_t numSections = sectionIt->second; cacheLoadCommandsSize += sizeof(section_64) * numSections; } } // Add an LC_FILESET_ENTRY for each dylib std::vector<std::pair<const DylibInfo*, uint64_t>> dylibs; for (const auto& dylib : sortedDylibs) { ++cacheNumLoadCommands; const char* dylibID = dylib.dylibID.c_str(); dylibs.push_back({ &dylib, cacheHeaderSize + cacheLoadCommandsSize }); uint64_t size = align(sizeof(fileset_entry_command) + strlen(dylibID) + 1, 3); cacheLoadCommandsSize += size; } uint64_t cacheHeaderRegionSize = cacheHeaderSize + cacheLoadCommandsSize; // Align the app cache header before the rest of the bytes cacheHeaderRegionSize = align(cacheHeaderRegionSize, 14); assert(numRegionFileBytes <= numRegionVMBytes); _allocatedBufferSize = cacheHeaderRegionSize + numRegionVMBytes; // The fixup format cannot handle a KC over 1GB (64MB for arm64e auxKC). Error out if we exceed that uint64_t cacheLimit = 1 << 30; if ( (appCacheOptions.cacheKind == Options::AppCacheKind::auxKC) && (_options.archs == &dyld3::GradedArchs::arm64e) ) cacheLimit = 64 * (1 << 20); if ( _allocatedBufferSize >= cacheLimit ) { _diagnostics.error("kernel collection size exceeds maximum size of %lld vs actual size of %lld", cacheLimit, _allocatedBufferSize); return; } if ( vm_allocate(mach_task_self(), &_fullAllocatedBuffer, _allocatedBufferSize, VM_FLAGS_ANYWHERE) != 0 ) { _diagnostics.error("could not allocate buffer"); return; } // Assign region vm and buffer addresses now that we know the size of // the cache header { // All vm offsets prior to the cache header are already correct // All those after the cache header need to be shifted by the cache // header size bool seenCacheHeader = false; for (const auto& regionAndVMOffset : regionsVMOrder) { Region* region = regionAndVMOffset.first; uint64_t vmOffset = regionAndVMOffset.second; region->unslidLoadAddress = cacheBaseAddress + vmOffset; if ( seenCacheHeader ) { // Shift by the cache header size region->unslidLoadAddress += cacheHeaderRegionSize; } else { // The offset is correct but add in the base address seenCacheHeader = (region == &cacheHeaderRegion); } region->buffer = (uint8_t*)_fullAllocatedBuffer + (region->unslidLoadAddress - cacheBaseAddress); } } // Cache header cacheHeaderRegion.bufferSize = cacheHeaderRegionSize; cacheHeaderRegion.sizeInUse = cacheHeaderRegion.bufferSize; cacheHeaderRegion.cacheFileOffset = 0; cacheHeaderRegion.initProt = VM_PROT_READ; cacheHeaderRegion.maxProt = VM_PROT_READ; cacheHeaderRegion.name = "__TEXT"; #if 0 for (const auto& regionAndVMOffset : regionsVMOrder) { printf("0x%llx : %s\n", regionAndVMOffset.first->unslidLoadAddress, regionAndVMOffset.first->name.c_str()); } #endif CacheHeader64& header = cacheHeader; header.header = (mach_header_64*)cacheHeaderRegion.buffer; header.numLoadCommands = cacheNumLoadCommands; header.loadCommandsSize = cacheLoadCommandsSize; header.uuid = (uuid_command*)(cacheHeaderRegion.buffer + uuidOffset); header.buildVersion = (build_version_command*)(cacheHeaderRegion.buffer + buildVersionOffset); if ( unixThread != nullptr ) { header.unixThread = (thread_command*)(cacheHeaderRegion.buffer + unixThreadOffset); // Copy the contents here while we have the source pointer available memcpy(header.unixThread, unixThread, unixThread->cmdsize); } if ( symbolTableOffset != 0 ) { header.symbolTable = (symtab_command*)(cacheHeaderRegion.buffer + symbolTableOffset); } if ( dynSymbolTableOffset != 0 ) { header.dynSymbolTable = (dysymtab_command*)(cacheHeaderRegion.buffer + dynSymbolTableOffset); } if ( chainedFixupsOffset != 0 ) { header.chainedFixups = (linkedit_data_command*)(cacheHeaderRegion.buffer + chainedFixupsOffset); } for (auto& regionAndOffset : regions) { assert(regionAndOffset.first->initProt != 0); assert(regionAndOffset.first->maxProt != 0); segment_command_64* loadCommand = (segment_command_64*)(cacheHeaderRegion.buffer + regionAndOffset.second); header.segments.push_back({ loadCommand, regionAndOffset.first }); } for (const auto& dylibAndOffset : dylibs) { fileset_entry_command* loadCommand = (fileset_entry_command*)(cacheHeaderRegion.buffer + dylibAndOffset.second); header.dylibs.push_back({ loadCommand, dylibAndOffset.first }); } // Move the offsets of all the other regions // Split seg __TEXT readOnlyTextRegion.cacheFileOffset += cacheHeaderRegion.sizeInUse; // Split seg __TEXT_EXEC readExecuteRegion.cacheFileOffset += cacheHeaderRegion.sizeInUse; // __BRANCH_STUBS branchStubsRegion.cacheFileOffset += cacheHeaderRegion.sizeInUse; // Split seg __DATA_CONST dataConstRegion.cacheFileOffset += cacheHeaderRegion.sizeInUse; // __BRANCH_GOTS branchGOTsRegion.cacheFileOffset += cacheHeaderRegion.sizeInUse; // Split seg __DATA readWriteRegion.cacheFileOffset += cacheHeaderRegion.sizeInUse; // Split seg __HIB hibernateRegion.cacheFileOffset += cacheHeaderRegion.sizeInUse; // -sectcreate for (Region& region : customDataRegions) { region.cacheFileOffset += cacheHeaderRegion.sizeInUse; } // Non split seg regions for (Region& region : nonSplitSegRegions) { region.cacheFileOffset += cacheHeaderRegion.sizeInUse; } // __PRELINK_INFO prelinkInfoRegion.cacheFileOffset += cacheHeaderRegion.sizeInUse; // __LINKEDIT _readOnlyRegion.cacheFileOffset += cacheHeaderRegion.sizeInUse; // __LINKEDIT fixups sub region fixupsSubRegion.cacheFileOffset += cacheHeaderRegion.sizeInUse; } else { assert(false); } } void AppCacheBuilder::generateCacheHeader() { if ( !_is64 ) assert(0 && "Unimplemented"); { // 64-bit typedef Pointer64<LittleEndian> P; CacheHeader64& header = cacheHeader; // Write the header macho_header<P>* mh = (macho_header<P>*)header.header; mh->set_magic(MH_MAGIC_64); mh->set_cputype(_options.archs->_orderedCpuTypes[0].type); mh->set_cpusubtype(_options.archs->_orderedCpuTypes[0].subtype); mh->set_filetype(MH_FILESET); mh->set_ncmds((uint32_t)header.numLoadCommands); mh->set_sizeofcmds((uint32_t)header.loadCommandsSize); mh->set_flags(0); mh->set_reserved(0); // FIXME: Move this to writeAppCacheHeader { macho_uuid_command<P>* cmd = (macho_uuid_command<P>*)header.uuid; cmd->set_cmd(LC_UUID); cmd->set_cmdsize(sizeof(uuid_command)); cmd->set_uuid((uuid_t){}); } // FIXME: Move this to writeAppCacheHeader { macho_build_version_command<P>* cmd = (macho_build_version_command<P>*)header.buildVersion; cmd->set_cmd(LC_BUILD_VERSION); cmd->set_cmdsize(sizeof(build_version_command)); cmd->set_platform((uint32_t)_options.platform); cmd->set_minos(0); cmd->set_sdk(0); cmd->set_ntools(0); } // FIXME: Move this to writeAppCacheHeader // LC_UNIXTHREAD was already memcpy()'ed from the source dylib when we allocated space for it // We still need to slide its PC value here before we lose the information about the slide if ( header.unixThread != nullptr ) { const DylibInfo* dylib = getKernelStaticExecutableInputFile(); const dyld3::MachOAnalyzer* ma = dylib->input->mappedFile.mh; ma->forEachSegment(^(const dyld3::MachOAnalyzer::SegmentInfo &info, bool &stop) { uint64_t startAddress = dylib->input->mappedFile.mh->entryAddrFromThreadCmd(header.unixThread); if ( (startAddress < info.vmAddr) || (startAddress >= (info.vmAddr + info.vmSize)) ) return; uint64_t segSlide = dylib->cacheLocation[info.segIndex].dstCacheUnslidAddress - info.vmAddr; startAddress += segSlide; macho_thread_command<P>* cmd = (macho_thread_command<P>*)header.unixThread; cmd->set_thread_register(ma->entryAddrRegisterIndexForThreadCmd(), startAddress); stop = true; }); } if ( header.symbolTable != nullptr ) { macho_symtab_command<P>* cmd = (macho_symtab_command<P>*)header.symbolTable; cmd->set_cmd(LC_SYMTAB); cmd->set_cmdsize(sizeof(symtab_command)); cmd->set_symoff(0); cmd->set_nsyms(0); cmd->set_stroff(0); cmd->set_strsize(0); } if ( header.dynSymbolTable != nullptr ) { macho_dysymtab_command<P>* cmd = (macho_dysymtab_command<P>*)header.dynSymbolTable; cmd->set_cmd(LC_DYSYMTAB); cmd->set_cmdsize(sizeof(dysymtab_command)); cmd->set_ilocalsym(0); cmd->set_nlocalsym(0); cmd->set_iextdefsym(0); cmd->set_nextdefsym(0); cmd->set_iundefsym(0); cmd->set_nundefsym(0); cmd->set_tocoff(0); cmd->set_ntoc(0); cmd->set_modtaboff(0); cmd->set_nmodtab(0); cmd->set_extrefsymoff(0); cmd->set_nextrefsyms(0); cmd->set_indirectsymoff(0); cmd->set_nindirectsyms(0); cmd->set_extreloff(0); cmd->set_nextrel(0); cmd->set_locreloff(0); cmd->set_nlocrel(0); } if ( header.chainedFixups != nullptr ) { macho_linkedit_data_command<P>* cmd = (macho_linkedit_data_command<P>*)header.chainedFixups; cmd->set_cmd(LC_DYLD_CHAINED_FIXUPS); cmd->set_cmdsize(sizeof(linkedit_data_command)); cmd->set_dataoff(0); cmd->set_datasize(0); } // FIXME: Move this to writeAppCacheHeader uint64_t segmentIndex = 0; for (CacheHeader64::SegmentCommandAndRegion& cmdAndInfo : header.segments) { macho_segment_command<P>* cmd = (macho_segment_command<P>*)cmdAndInfo.first; Region* region = cmdAndInfo.second; region->index = segmentIndex; ++segmentIndex; assert(region->initProt != 0); assert(region->maxProt != 0); const char* name = region->name.c_str(); cmd->set_cmd(LC_SEGMENT_64); cmd->set_cmdsize(sizeof(segment_command_64)); cmd->set_segname(name); cmd->set_vmaddr(region->unslidLoadAddress); cmd->set_vmsize(region->sizeInUse); cmd->set_fileoff(region->cacheFileOffset); cmd->set_filesize(region->sizeInUse); cmd->set_maxprot(region->maxProt); cmd->set_initprot(region->initProt); cmd->set_nsects(0); cmd->set_flags(0); if ( region == &readOnlyTextRegion ) { // __PRELINK_TEXT should also get a section cmd->set_cmdsize(cmd->cmdsize() + sizeof(section_64)); cmd->set_nsects(1); macho_section<P>* section = (macho_section<P>*)((uint64_t)cmd + sizeof(*cmd)); section->set_sectname("__text"); section->set_segname(name); section->set_addr(region->unslidLoadAddress); section->set_size(region->sizeInUse); section->set_offset((uint32_t)region->cacheFileOffset); section->set_align(0); section->set_reloff(0); section->set_nreloc(0); section->set_flags(S_REGULAR | S_ATTR_SOME_INSTRUCTIONS | S_ATTR_PURE_INSTRUCTIONS); section->set_reserved1(0); section->set_reserved2(0); } else if ( region == &prelinkInfoRegion ) { // __PRELINK_INFO should also get a section cmd->set_cmdsize(cmd->cmdsize() + sizeof(section_64)); cmd->set_nsects(1); macho_section<P>* section = (macho_section<P>*)((uint64_t)cmd + sizeof(*cmd)); section->set_sectname("__info"); section->set_segname(name); section->set_addr(region->unslidLoadAddress); section->set_size(region->sizeInUse); section->set_offset((uint32_t)region->cacheFileOffset); section->set_align(0); section->set_reloff(0); section->set_nreloc(0); section->set_flags(S_REGULAR); section->set_reserved1(0); section->set_reserved2(0); } else if ( region == &hibernateRegion ) { // __HIB should also get a section cmd->set_cmdsize(cmd->cmdsize() + sizeof(section_64)); cmd->set_nsects(1); macho_section<P>* section = (macho_section<P>*)((uint64_t)cmd + sizeof(*cmd)); section->set_sectname("__text"); section->set_segname(name); section->set_addr(region->unslidLoadAddress); section->set_size(region->sizeInUse); section->set_offset((uint32_t)region->cacheFileOffset); section->set_align(0); section->set_reloff(0); section->set_nreloc(0); section->set_flags(S_REGULAR | S_ATTR_SOME_INSTRUCTIONS); section->set_reserved1(0); section->set_reserved2(0); } else { // Custom segments may have sections for (CustomSegment &customSegment : customSegments) { if ( region != customSegment.parentRegion ) continue; // Found a segment for this region. Now work out how many sections to emit // Maybe add sections too uint32_t sectionsToAdd = 0; if ( customSegment.sections.size() > 1 ) { // More than one section, so they all need names sectionsToAdd = (uint32_t)customSegment.sections.size(); } else if ( !customSegment.sections.front().sectionName.empty() ) { // Only one section, but it has a name sectionsToAdd = 1; } else { // Only 1 section, and it has no name, so don't add a section continue; } cmd->set_cmdsize(cmd->cmdsize() + (sizeof(section_64) * sectionsToAdd)); cmd->set_nsects(sectionsToAdd); uint8_t* bufferPos = (uint8_t*)cmd + sizeof(*cmd); for (const CustomSegment::CustomSection& customSection : customSegment.sections) { macho_section<P>* section = (macho_section<P>*)bufferPos; section->set_sectname(customSection.sectionName.c_str()); section->set_segname(name); section->set_addr(region->unslidLoadAddress + customSection.offsetInRegion); section->set_size(customSection.data.size()); section->set_offset((uint32_t)(region->cacheFileOffset + customSection.offsetInRegion)); section->set_align(0); section->set_reloff(0); section->set_nreloc(0); section->set_flags(S_REGULAR); section->set_reserved1(0); section->set_reserved2(0); bufferPos += sizeof(section_64); } } } } // Write the dylibs. These are all we need for now to be able to walk the // app cache for (CacheHeader64::DylibCommandAndInfo& cmdAndInfo : header.dylibs) { macho_fileset_entry_command<P>* cmd = (macho_fileset_entry_command<P>*)cmdAndInfo.first; const DylibInfo* dylib = cmdAndInfo.second; const char* dylibID = dylib->dylibID.c_str(); uint64_t size = align(sizeof(fileset_entry_command) + strlen(dylibID) + 1, 3); cmd->set_cmd(LC_FILESET_ENTRY); cmd->set_cmdsize((uint32_t)size); cmd->set_vmaddr(dylib->cacheLocation[0].dstCacheUnslidAddress); cmd->set_fileoff(dylib->cacheLocation[0].dstCacheFileOffset); cmd->set_entry_id(dylibID); } } } void AppCacheBuilder::generatePrelinkInfo() { if ( prelinkInfoDict == nullptr ) { // The kernel doesn't need a prelink dictionary just for itself bool needsPrelink = true; if ( appCacheOptions.cacheKind == Options::AppCacheKind::kernel ) { if ( sortedDylibs.size() == 1 ) needsPrelink = false; } if ( needsPrelink ) { _diagnostics.error("Expected prelink info dictionary"); } return; } CFMutableArrayRef arrayRef = (CFMutableArrayRef)CFDictionaryGetValue(prelinkInfoDict, CFSTR("_PrelinkInfoDictionary")); if ( arrayRef == nullptr ) { _diagnostics.error("Expected prelink info dictionary array"); return; } typedef std::pair<const dyld3::MachOAnalyzer*, Diagnostics*> DylibAndDiag; __block std::unordered_map<std::string_view, DylibAndDiag> dylibs; forEachCacheDylib(^(const dyld3::MachOAnalyzer *ma, const std::string &dylibID, DylibStripMode stripMode, const std::vector<std::string>& dependencies, Diagnostics& dylibDiag, bool& stop) { dylibs[dylibID] = { ma, &dylibDiag }; }); for (const InputDylib& dylib : codelessKexts) { dylibs[dylib.dylibID] = { nullptr, nullptr }; } __block std::list<std::string> nonASCIIStrings; auto getString = ^(Diagnostics& diags, CFStringRef symbolNameRef) { const char* symbolName = CFStringGetCStringPtr(symbolNameRef, kCFStringEncodingUTF8); if ( symbolName != nullptr ) return symbolName; CFIndex len = CFStringGetMaximumSizeForEncoding(CFStringGetLength(symbolNameRef), kCFStringEncodingUTF8); char buffer[len + 1]; if ( !CFStringGetCString(symbolNameRef, buffer, len, kCFStringEncodingUTF8) ) { diags.error("Could not convert string to ASCII"); return (const char*)nullptr; } buffer[len] = '\0'; nonASCIIStrings.push_back(buffer); return nonASCIIStrings.back().c_str(); }; bool badKext = false; CFIndex arrayCount = CFArrayGetCount(arrayRef); for (CFIndex i = 0; i != arrayCount; ++i) { CFMutableDictionaryRef dictRef = (CFMutableDictionaryRef)CFArrayGetValueAtIndex(arrayRef, i); CFStringRef bundleIDRef = (CFStringRef)CFDictionaryGetValue(dictRef, CFSTR("CFBundleIdentifier")); if ( bundleIDRef == nullptr ) { _diagnostics.error("Cannot get bundle ID for dylib"); return; } const char* bundleIDStr = getString(_diagnostics, bundleIDRef); if ( _diagnostics.hasError() ) return; auto dylibIt = dylibs.find(bundleIDStr); if ( dylibIt == dylibs.end() ) { _diagnostics.error("Cannot get dylib for bundle ID %s", bundleIDStr); return; } const dyld3::MachOAnalyzer *ma = dylibIt->second.first; Diagnostics* dylibDiag = dylibIt->second.second; // Skip codeless kext's if ( ma == nullptr ) continue; uint64_t loadAddress = ma->preferredLoadAddress(); // _PrelinkExecutableLoadAddr CFNumberRef loadAddrRef = CFNumberCreate(kCFAllocatorDefault, kCFNumberLongLongType, &loadAddress); CFDictionarySetValue(dictRef, CFSTR("_PrelinkExecutableLoadAddr"), loadAddrRef); CFRelease(loadAddrRef); // _PrelinkExecutableSourceAddr CFNumberRef sourceAddrRef = CFNumberCreate(kCFAllocatorDefault, kCFNumberLongLongType, &loadAddress); CFDictionarySetValue(dictRef, CFSTR("_PrelinkExecutableSourceAddr"), sourceAddrRef); CFRelease(sourceAddrRef); // _PrelinkKmodInfo __block uint64_t kmodInfoAddress = 0; // Check for a global first __block bool found = false; { dyld3::MachOAnalyzer::FoundSymbol foundInfo; found = ma->findExportedSymbol(_diagnostics, "_kmod_info", true, foundInfo, nullptr); if ( found ) { kmodInfoAddress = loadAddress + foundInfo.value; } } // And fall back to a local if we need to if ( !found ) { ma->forEachLocalSymbol(_diagnostics, ^(const char* aSymbolName, uint64_t n_value, uint8_t n_type, uint8_t n_sect, uint16_t n_desc, bool& stop) { if ( strcmp(aSymbolName, "_kmod_info") == 0 ) { kmodInfoAddress = n_value; found = true; stop = true; } }); } if ( found ) { CFNumberRef kmodInfoAddrRef = CFNumberCreate(kCFAllocatorDefault, kCFNumberLongLongType, &kmodInfoAddress); CFDictionarySetValue(dictRef, CFSTR("_PrelinkKmodInfo"), kmodInfoAddrRef); CFRelease(kmodInfoAddrRef); // Since we have a reference to the kmod info anyway, set its address field to the correct value assert(_is64); uint64_t kmodInfoVMOffset = kmodInfoAddress - loadAddress; dyld3::MachOAppCache::KModInfo64_v1* kmodInfo = (dyld3::MachOAppCache::KModInfo64_v1*)((uint8_t*)ma + kmodInfoVMOffset); if ( kmodInfo->info_version != 1 ) { dylibDiag->error("unsupported kmod_info version of %d", kmodInfo->info_version); badKext = true; continue; } __block uint64_t textSegmnentVMAddr = 0; __block uint64_t textSegmnentVMSize = 0; ma->forEachSegment(^(const dyld3::MachOAnalyzer::SegmentInfo &info, bool &stop) { if ( !strcmp(info.segName, "__TEXT") ) { textSegmnentVMAddr = info.vmAddr; textSegmnentVMSize = info.vmSize; stop = true; } }); kmodInfo->address = textSegmnentVMAddr; kmodInfo->size = textSegmnentVMSize; } } CFErrorRef errorRef = nullptr; CFDataRef xmlData = CFPropertyListCreateData(kCFAllocatorDefault, prelinkInfoDict, kCFPropertyListXMLFormat_v1_0, 0, &errorRef); if (errorRef != nullptr) { CFStringRef errorString = CFErrorCopyDescription(errorRef); _diagnostics.error("Could not serialise plist because :%s", CFStringGetCStringPtr(errorString, kCFStringEncodingASCII)); CFRelease(xmlData); CFRelease(errorRef); return; } else { CFIndex xmlDataLength = CFDataGetLength(xmlData); if ( xmlDataLength > prelinkInfoRegion.bufferSize ) { _diagnostics.error("Overflow in prelink info segment. 0x%llx vs 0x%llx", (uint64_t)xmlDataLength, prelinkInfoRegion.bufferSize); CFRelease(xmlData); return; } // Write the prelink info in to the buffer memcpy(prelinkInfoRegion.buffer, CFDataGetBytePtr(xmlData), xmlDataLength); CFRelease(xmlData); } if ( badKext && _diagnostics.noError() ) { _diagnostics.error("One or more binaries has an error which prevented linking. See other errors."); } } bool AppCacheBuilder::addCustomSection(const std::string& segmentName, CustomSegment::CustomSection section) { for (CustomSegment& segment: customSegments) { if ( segment.segmentName != segmentName ) continue; // Found a matching segment // Make sure we don't have a section with this name already if ( section.sectionName.empty() ) { // We can't add a segment only section if other sections exist _diagnostics.error("Cannot add empty section name with segment '%s' as other sections exist on that segment", segmentName.c_str()); return false; } for (const CustomSegment::CustomSection& existingSection : segment.sections) { if ( existingSection.sectionName.empty() ) { // We can't add a section with a name if an existing section exists with no name _diagnostics.error("Cannot add section named '%s' with segment '%s' as segment has existing nameless section", segmentName.c_str(), section.sectionName.c_str()); return false; } if ( existingSection.sectionName == section.sectionName ) { // We can't add a section with the same name as an existing one _diagnostics.error("Cannot add section named '%s' with segment '%s' as section already exists", segmentName.c_str(), section.sectionName.c_str()); return false; } } segment.sections.push_back(section); return true; } // Didn't find a segment, so add a new one CustomSegment segment; segment.segmentName = segmentName; segment.sections.push_back(section); customSegments.push_back(segment); return true; } void AppCacheBuilder::setExistingKernelCollection(const dyld3::MachOAppCache* appCacheMA) { existingKernelCollection = appCacheMA; } void AppCacheBuilder::setExistingPageableKernelCollection(const dyld3::MachOAppCache* appCacheMA) { pageableKernelCollection = appCacheMA; } void AppCacheBuilder::setExtraPrelinkInfo(CFDictionaryRef dictionary) { extraPrelinkInfo = dictionary; } inline uint32_t absolutetime_to_milliseconds(uint64_t abstime) { return (uint32_t)(abstime/1000/1000); } void AppCacheBuilder::buildAppCache(const std::vector<InputDylib>& dylibs) { uint64_t t1 = mach_absolute_time(); // make copy of dylib list and sort makeSortedDylibs(dylibs); // Set the chained pointer format // x86_64 uses unaligned fixups if ( (_options.archs == &dyld3::GradedArchs::x86_64) || (_options.archs == &dyld3::GradedArchs::x86_64h) ) { chainedPointerFormat = DYLD_CHAINED_PTR_X86_64_KERNEL_CACHE; } else { chainedPointerFormat = DYLD_CHAINED_PTR_64_KERNEL_CACHE; } // If we have only codeless kexts, then error out if ( sortedDylibs.empty() ) { if ( codelessKexts.empty() ) { _diagnostics.error("No binaries or codeless kexts were provided"); } else { _diagnostics.error("Cannot build collection without binaries as only %lx codeless kexts provided", codelessKexts.size()); } return; } // assign addresses for each segment of each dylib in new cache assignSegmentRegionsAndOffsets(); if ( _diagnostics.hasError() ) return; // allocate space used by largest possible cache plus room for LINKEDITS before optimization allocateBuffer(); if ( _diagnostics.hasError() ) return; assignSegmentAddresses(); generateCacheHeader(); // copy all segments into cache uint64_t t2 = mach_absolute_time(); copyRawSegments(); // rebase all dylibs for new location in cache uint64_t t3 = mach_absolute_time(); if ( appCacheOptions.cacheKind == Options::AppCacheKind::auxKC ) { // We can have text fixups in the auxKC so ASLR should just track the whole buffer __block const Region* firstDataRegion = nullptr; __block const Region* lastDataRegion = nullptr; forEachRegion(^(const Region ®ion) { if ( (firstDataRegion == nullptr) || (region.buffer < firstDataRegion->buffer) ) firstDataRegion = ®ion; if ( (lastDataRegion == nullptr) || (region.buffer > lastDataRegion->buffer) ) lastDataRegion = ®ion; }); if ( firstDataRegion != nullptr ) { uint64_t size = (lastDataRegion->buffer - firstDataRegion->buffer) + lastDataRegion->bufferSize; _aslrTracker.setDataRegion(firstDataRegion->buffer, size); } } else { const Region* firstDataRegion = nullptr; const Region* lastDataRegion = nullptr; if ( hibernateRegion.sizeInUse != 0 ) { firstDataRegion = &hibernateRegion; lastDataRegion = &hibernateRegion; } if ( dataConstRegion.sizeInUse != 0 ) { if ( firstDataRegion == nullptr ) firstDataRegion = &dataConstRegion; if ( (lastDataRegion == nullptr) || (dataConstRegion.buffer > lastDataRegion->buffer) ) lastDataRegion = &dataConstRegion; } if ( branchGOTsRegion.bufferSize != 0 ) { if ( firstDataRegion == nullptr ) firstDataRegion = &branchGOTsRegion; if ( (lastDataRegion == nullptr) || (branchGOTsRegion.buffer > lastDataRegion->buffer) ) lastDataRegion = &branchGOTsRegion; } if ( readWriteRegion.sizeInUse != 0 ) { // __DATA might be before __DATA_CONST in an auxKC if ( (firstDataRegion == nullptr) || (readWriteRegion.buffer < firstDataRegion->buffer) ) firstDataRegion = &readWriteRegion; if ( (lastDataRegion == nullptr) || (readWriteRegion.buffer > lastDataRegion->buffer) ) lastDataRegion = &readWriteRegion; } for (const Region& region : nonSplitSegRegions) { // Assume writable regions have fixups to emit // Note, third party kext's have __TEXT fixups, so assume all of these have fixups // LINKEDIT is already elsewhere if ( readWriteRegion.sizeInUse != 0 ) { assert(region.buffer >= readWriteRegion.buffer); } if ( firstDataRegion == nullptr ) firstDataRegion = ®ion; if ( (lastDataRegion == nullptr) || (region.buffer > lastDataRegion->buffer) ) lastDataRegion = ®ion; } if ( firstDataRegion != nullptr ) { uint64_t size = (lastDataRegion->buffer - firstDataRegion->buffer) + lastDataRegion->bufferSize; _aslrTracker.setDataRegion(firstDataRegion->buffer, size); } } adjustAllImagesForNewSegmentLocations(cacheBaseAddress, nullptr, nullptr); if ( _diagnostics.hasError() ) return; // Once we have the final addresses, we can emit the prelink info segment generatePrelinkInfo(); if ( _diagnostics.hasError() ) return; // build ImageArray for dyld3, which has side effect of binding all cached dylibs uint64_t t4 = mach_absolute_time(); processFixups(); if ( _diagnostics.hasError() ) return; uint64_t t5 = mach_absolute_time(); // optimize away stubs uint64_t t6 = mach_absolute_time(); { __block std::vector<std::pair<const mach_header*, const char*>> images; forEachCacheDylib(^(const dyld3::MachOAnalyzer *ma, const std::string &dylibID, DylibStripMode stripMode, const std::vector<std::string>& dependencies, Diagnostics& dylibDiag, bool& stop) { images.push_back({ ma, dylibID.c_str() }); }); // FIXME: Should we keep the same never stub eliminate symbols? Eg, for gmalloc. const char* const neverStubEliminateSymbols[] = { nullptr }; uint64_t cacheUnslidAddr = cacheBaseAddress; int64_t cacheSlide = (long)_fullAllocatedBuffer - cacheUnslidAddr; optimizeAwayStubs(images, cacheSlide, cacheUnslidAddr, nullptr, neverStubEliminateSymbols); } // FIPS seal corecrypto, This must be done after stub elimination (so that __TEXT,__text is not changed after sealing) fipsSign(); // merge and compact LINKEDIT segments uint64_t t7 = mach_absolute_time(); { __block std::vector<std::tuple<const mach_header*, const char*, DylibStripMode>> images; __block std::set<const mach_header*> imagesToStrip; __block const dyld3::MachOAnalyzer* kernelMA = nullptr; forEachCacheDylib(^(const dyld3::MachOAnalyzer *ma, const std::string &dylibID, DylibStripMode stripMode, const std::vector<std::string>& dependencies, Diagnostics& dylibDiag, bool& stop) { if ( stripMode == DylibStripMode::stripNone ) { // If the binary didn't have a strip mode, then use the global mode switch (appCacheOptions.cacheKind) { case Options::AppCacheKind::none: assert("Unhandled kind"); break; case Options::AppCacheKind::kernel: switch (appCacheOptions.stripMode) { case Options::StripMode::none: break; case Options::StripMode::all: stripMode = CacheBuilder::DylibStripMode::stripAll; break; case Options::StripMode::allExceptKernel: // Strip all binaries which are not the kernel if ( kernelMA == nullptr ) { kernelMA = getKernelStaticExecutableFromCache(); } if ( ma != kernelMA ) stripMode = CacheBuilder::DylibStripMode::stripAll; break; } break; case Options::AppCacheKind::pageableKC: assert("Unhandled kind"); break; case Options::AppCacheKind::kernelCollectionLevel2: assert("Unhandled kind"); break; case Options::AppCacheKind::auxKC: assert("Unhandled kind"); break; } } images.push_back({ ma, dylibID.c_str(), stripMode }); }); optimizeLinkedit(_readOnlyRegion, _nonLinkEditReadOnlySize, nullptr, images); // update final readOnly region size if ( !_is64 ) assert(0 && "Unimplemented"); { // 64-bit CacheHeader64& header = cacheHeader; for (CacheHeader64::SegmentCommandAndRegion& cmdAndRegion : header.segments) { if (cmdAndRegion.second != &_readOnlyRegion) continue; cmdAndRegion.first->vmsize = _readOnlyRegion.sizeInUse; cmdAndRegion.first->filesize = _readOnlyRegion.sizeInUse; break; } } } uint64_t t8 = mach_absolute_time(); uint64_t t9 = mach_absolute_time(); // Add fixups to rebase/bind the app cache writeFixups(); { if ( !_is64 ) assert(0 && "Unimplemented"); // update final readOnly region size { // 64-bit CacheHeader64& header = cacheHeader; for (CacheHeader64::SegmentCommandAndRegion& cmdAndRegion : header.segments) { if (cmdAndRegion.second != &_readOnlyRegion) continue; cmdAndRegion.first->vmsize = _readOnlyRegion.sizeInUse; cmdAndRegion.first->filesize = _readOnlyRegion.sizeInUse; break; } } } // FIXME: We could move _aslrTracker to a worker thread to be destroyed as we don't need it // after this point uint64_t t10 = mach_absolute_time(); generateUUID(); if ( _diagnostics.hasError() ) return; uint64_t t11 = mach_absolute_time(); if ( _options.verbose ) { fprintf(stderr, "time to layout cache: %ums\n", absolutetime_to_milliseconds(t2-t1)); fprintf(stderr, "time to copy cached dylibs into buffer: %ums\n", absolutetime_to_milliseconds(t3-t2)); fprintf(stderr, "time to adjust segments for new split locations: %ums\n", absolutetime_to_milliseconds(t4-t3)); fprintf(stderr, "time to bind all images: %ums\n", absolutetime_to_milliseconds(t5-t4)); fprintf(stderr, "time to optimize Objective-C: %ums\n", absolutetime_to_milliseconds(t6-t5)); fprintf(stderr, "time to do stub elimination: %ums\n", absolutetime_to_milliseconds(t7-t6)); fprintf(stderr, "time to optimize LINKEDITs: %ums\n", absolutetime_to_milliseconds(t8-t7)); fprintf(stderr, "time to compute slide info: %ums\n", absolutetime_to_milliseconds(t10-t9)); fprintf(stderr, "time to compute UUID and codesign cache file: %ums\n", absolutetime_to_milliseconds(t11-t10)); } } void AppCacheBuilder::fipsSign() { if ( appCacheOptions.cacheKind != Options::AppCacheKind::kernel ) return; // find com.apple.kec.corecrypto in collection being built __block const dyld3::MachOAnalyzer* kextMA = nullptr; forEachCacheDylib(^(const dyld3::MachOAnalyzer *ma, const std::string &dylibID, DylibStripMode stripMode, const std::vector<std::string>& dependencies, Diagnostics& dylibDiag, bool& stop) { if ( dylibID == "com.apple.kec.corecrypto" ) { kextMA = ma; stop = true; } }); if ( kextMA == nullptr ) { _diagnostics.warning("Could not find com.apple.kec.corecrypto, skipping FIPS sealing"); return; } // find location in com.apple.kec.corecrypto to store hash of __text section uint64_t hashStoreSize; const void* hashStoreLocation = kextMA->findSectionContent("__TEXT", "__fips_hmacs", hashStoreSize); if ( hashStoreLocation == nullptr ) { _diagnostics.warning("Could not find __TEXT/__fips_hmacs section in com.apple.kec.corecrypto, skipping FIPS sealing"); return; } if ( hashStoreSize < 32 ) { _diagnostics.warning("__TEXT/__fips_hmacs section in com.apple.kec.corecrypto must be at least 32 bytes in size, skipping FIPS sealing"); return; } // compute hmac hash of __text section. It may be in __TEXT_EXEC or __TEXT uint64_t textSize; const void* textLocation = kextMA->findSectionContent("__TEXT", "__text", textSize); if ( textLocation == nullptr ) { textLocation = kextMA->findSectionContent("__TEXT_EXEC", "__text", textSize); } if ( textLocation == nullptr ) { _diagnostics.warning("Could not find __TEXT/__text section in com.apple.kec.corecrypto, skipping FIPS sealing"); return; } unsigned char hmac_key = 0; CCHmac(kCCHmacAlgSHA256, &hmac_key, 1, textLocation, textSize, (void*)hashStoreLocation); // store hash directly into hashStoreLocation } void AppCacheBuilder::generateUUID() { uint8_t* uuidLoc = cacheHeader.uuid->uuid; assert(uuid_is_null(uuidLoc)); CCDigestRef digestRef = CCDigestCreate(kCCDigestSHA256); forEachRegion(^(const Region ®ion) { if ( _diagnostics.hasError() ) return; if ( region.sizeInUse == 0 ) return; int result = CCDigestUpdate(digestRef, region.buffer, region.sizeInUse); if ( result != 0 ) { _diagnostics.error("Could not generate UUID: %d", result); return; } }); if ( !_diagnostics.hasError() ) { uint8_t buffer[CCDigestGetOutputSize(kCCDigestSHA256)]; int result = CCDigestFinal(digestRef, buffer); memcpy(cacheHeader.uuid->uuid, buffer, sizeof(cacheHeader.uuid->uuid)); if ( result != 0 ) { _diagnostics.error("Could not finalize UUID: %d", result); } } CCDigestDestroy(digestRef); if ( _diagnostics.hasError() ) return; // Update the prelink info dictionary too if ( prelinkInfoDict != nullptr ) { CFDataRef dataRef = CFDataCreate(kCFAllocatorDefault, &cacheHeader.uuid->uuid[0], sizeof(cacheHeader.uuid->uuid)); CFDictionarySetValue(prelinkInfoDict, CFSTR("_PrelinkKCID"), dataRef); CFRelease(dataRef); CFErrorRef errorRef = nullptr; CFDataRef xmlData = CFPropertyListCreateData(kCFAllocatorDefault, prelinkInfoDict, kCFPropertyListXMLFormat_v1_0, 0, &errorRef); if (errorRef != nullptr) { CFStringRef errorString = CFErrorCopyDescription(errorRef); _diagnostics.error("Could not serialise plist because :%s", CFStringGetCStringPtr(errorString, kCFStringEncodingASCII)); CFRelease(xmlData); CFRelease(errorRef); return; } else { CFIndex xmlDataLength = CFDataGetLength(xmlData); if ( xmlDataLength > prelinkInfoRegion.bufferSize ) { _diagnostics.error("Overflow in prelink info segment. 0x%llx vs 0x%llx", (uint64_t)xmlDataLength, prelinkInfoRegion.bufferSize); CFRelease(xmlData); return; } // Write the prelink info in to the buffer memcpy(prelinkInfoRegion.buffer, CFDataGetBytePtr(xmlData), xmlDataLength); CFRelease(xmlData); } } } void AppCacheBuilder::writeFile(const std::string& path) { std::string pathTemplate = path + "-XXXXXX"; size_t templateLen = strlen(pathTemplate.c_str())+2; BLOCK_ACCCESSIBLE_ARRAY(char, pathTemplateSpace, templateLen); strlcpy(pathTemplateSpace, pathTemplate.c_str(), templateLen); int fd = mkstemp(pathTemplateSpace); if ( fd == -1 ) { _diagnostics.error("could not open file %s", pathTemplateSpace); return; } uint64_t cacheFileSize = 0; // FIXME: Do we ever need to avoid allocating space for zero fill? cacheFileSize = _readOnlyRegion.cacheFileOffset + _readOnlyRegion.sizeInUse; // set final cache file size (may help defragment file) ::ftruncate(fd, cacheFileSize); // Write the whole buffer uint64_t writtenSize = pwrite(fd, (const uint8_t*)_fullAllocatedBuffer, cacheFileSize, 0); if (writtenSize == cacheFileSize) { ::fchmod(fd, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH); // mkstemp() makes file "rw-------", switch it to "rw-r--r--" if ( ::rename(pathTemplateSpace, path.c_str()) == 0) { ::close(fd); return; // success } } else { _diagnostics.error("could not write whole file. %lld bytes out of %lld were written", writtenSize, cacheFileSize); return; } ::close(fd); ::unlink(pathTemplateSpace); } void AppCacheBuilder::writeBuffer(uint8_t*& buffer, uint64_t& bufferSize) const { bufferSize = _readOnlyRegion.cacheFileOffset + _readOnlyRegion.sizeInUse; buffer = (uint8_t*)malloc(bufferSize); forEachRegion(^(const Region ®ion) { if ( region.sizeInUse == 0 ) return; memcpy(buffer + region.cacheFileOffset, (const uint8_t*)region.buffer, region.sizeInUse); }); } |