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 | /* * Copyright (c) 2017 Apple Inc. All rights reserved. * * @APPLE_LICENSE_HEADER_START@ * * This file contains Original Code and/or Modifications of Original Code * as defined in and that are subject to the Apple Public Source License * Version 2.0 (the 'License'). You may not use this file except in * compliance with the License. Please obtain a copy of the License at * http://www.opensource.apple.com/apsl/ and read it before using this * file. * * The Original Code and all software distributed under the License are * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. * Please see the License for the specific language governing rights and * limitations under the License. * * @APPLE_LICENSE_HEADER_END@ */ #include <sys/types.h> #include <sys/stat.h> #include <sys/errno.h> #include <sys/mman.h> #include <mach/mach.h> #include <fcntl.h> #include <stdlib.h> #include <stdio.h> #include <unistd.h> #include <assert.h> #include <mach-o/reloc.h> #include <mach-o/nlist.h> extern "C" { #include <corecrypto/ccdigest.h> #include <corecrypto/ccsha1.h> #include <corecrypto/ccsha2.h> } #include "MachOFile.h" #include "MachOLoaded.h" #include "CodeSigningTypes.h" namespace dyld3 { void MachOLoaded::getLinkEditLoadCommands(Diagnostics& diag, LinkEditInfo& result) const { result.dyldInfo = nullptr; result.exportsTrie = nullptr; result.chainedFixups = nullptr; result.symTab = nullptr; result.dynSymTab = nullptr; result.splitSegInfo = nullptr; result.functionStarts = nullptr; result.dataInCode = nullptr; result.codeSig = nullptr; __block bool hasUUID = false; __block bool hasMinVersion = false; __block bool hasEncrypt = false; forEachLoadCommand(diag, ^(const load_command* cmd, bool& stop) { switch ( cmd->cmd ) { case LC_DYLD_INFO: case LC_DYLD_INFO_ONLY: if ( cmd->cmdsize != sizeof(dyld_info_command) ) diag.error("LC_DYLD_INFO load command size wrong"); else if ( result.dyldInfo != nullptr ) diag.error("multiple LC_DYLD_INFO load commands"); result.dyldInfo = (dyld_info_command*)cmd; break; case LC_DYLD_EXPORTS_TRIE: if ( cmd->cmdsize != sizeof(linkedit_data_command) ) diag.error("LC_DYLD_EXPORTS_TRIE load command size wrong"); else if ( result.exportsTrie != nullptr ) diag.error("multiple LC_DYLD_EXPORTS_TRIE load commands"); result.exportsTrie = (linkedit_data_command*)cmd; break; case LC_DYLD_CHAINED_FIXUPS: if ( cmd->cmdsize != sizeof(linkedit_data_command) ) diag.error("LC_DYLD_CHAINED_FIXUPS load command size wrong"); else if ( result.chainedFixups != nullptr ) diag.error("multiple LC_DYLD_CHAINED_FIXUPS load commands"); result.chainedFixups = (linkedit_data_command*)cmd; break; case LC_SYMTAB: if ( cmd->cmdsize != sizeof(symtab_command) ) diag.error("LC_SYMTAB load command size wrong"); else if ( result.symTab != nullptr ) diag.error("multiple LC_SYMTAB load commands"); result.symTab = (symtab_command*)cmd; break; case LC_DYSYMTAB: if ( cmd->cmdsize != sizeof(dysymtab_command) ) diag.error("LC_DYSYMTAB load command size wrong"); else if ( result.dynSymTab != nullptr ) diag.error("multiple LC_DYSYMTAB load commands"); result.dynSymTab = (dysymtab_command*)cmd; break; case LC_SEGMENT_SPLIT_INFO: if ( cmd->cmdsize != sizeof(linkedit_data_command) ) diag.error("LC_SEGMENT_SPLIT_INFO load command size wrong"); else if ( result.splitSegInfo != nullptr ) diag.error("multiple LC_SEGMENT_SPLIT_INFO load commands"); result.splitSegInfo = (linkedit_data_command*)cmd; break; case LC_FUNCTION_STARTS: if ( cmd->cmdsize != sizeof(linkedit_data_command) ) diag.error("LC_FUNCTION_STARTS load command size wrong"); else if ( result.functionStarts != nullptr ) diag.error("multiple LC_FUNCTION_STARTS load commands"); result.functionStarts = (linkedit_data_command*)cmd; break; case LC_DATA_IN_CODE: if ( cmd->cmdsize != sizeof(linkedit_data_command) ) diag.error("LC_DATA_IN_CODE load command size wrong"); else if ( result.dataInCode != nullptr ) diag.error("multiple LC_DATA_IN_CODE load commands"); result.dataInCode = (linkedit_data_command*)cmd; break; case LC_CODE_SIGNATURE: if ( cmd->cmdsize != sizeof(linkedit_data_command) ) diag.error("LC_CODE_SIGNATURE load command size wrong"); else if ( result.codeSig != nullptr ) diag.error("multiple LC_CODE_SIGNATURE load commands"); result.codeSig = (linkedit_data_command*)cmd; break; case LC_UUID: if ( cmd->cmdsize != sizeof(uuid_command) ) diag.error("LC_UUID load command size wrong"); else if ( hasUUID ) diag.error("multiple LC_UUID load commands"); hasUUID = true; break; case LC_VERSION_MIN_IPHONEOS: case LC_VERSION_MIN_MACOSX: case LC_VERSION_MIN_TVOS: case LC_VERSION_MIN_WATCHOS: if ( cmd->cmdsize != sizeof(version_min_command) ) diag.error("LC_VERSION_* load command size wrong"); else if ( hasMinVersion ) diag.error("multiple LC_VERSION_MIN_* load commands"); hasMinVersion = true; break; case LC_BUILD_VERSION: if ( cmd->cmdsize != (sizeof(build_version_command) + ((build_version_command*)cmd)->ntools * sizeof(build_tool_version)) ) diag.error("LC_BUILD_VERSION load command size wrong"); break; case LC_ENCRYPTION_INFO: if ( cmd->cmdsize != sizeof(encryption_info_command) ) diag.error("LC_ENCRYPTION_INFO load command size wrong"); else if ( hasEncrypt ) diag.error("multiple LC_ENCRYPTION_INFO load commands"); else if ( is64() ) diag.error("LC_ENCRYPTION_INFO found in 64-bit mach-o"); hasEncrypt = true; break; case LC_ENCRYPTION_INFO_64: if ( cmd->cmdsize != sizeof(encryption_info_command_64) ) diag.error("LC_ENCRYPTION_INFO_64 load command size wrong"); else if ( hasEncrypt ) diag.error("multiple LC_ENCRYPTION_INFO_64 load commands"); else if ( !is64() ) diag.error("LC_ENCRYPTION_INFO_64 found in 32-bit mach-o"); hasEncrypt = true; break; } }); if ( diag.noError() && (result.dynSymTab != nullptr) && (result.symTab == nullptr) ) diag.error("LC_DYSYMTAB but no LC_SYMTAB load command"); } void MachOLoaded::getLinkEditPointers(Diagnostics& diag, LinkEditInfo& result) const { getLinkEditLoadCommands(diag, result); if ( diag.noError() ) getLayoutInfo(result.layout); } const uint8_t* MachOLoaded::getExportsTrie(const LinkEditInfo& leInfo, uint64_t& trieSize) const { if ( leInfo.exportsTrie != nullptr) { trieSize = leInfo.exportsTrie->datasize; uint64_t offsetInLinkEdit = leInfo.exportsTrie->dataoff - leInfo.layout.linkeditFileOffset; return (uint8_t*)this + (leInfo.layout.linkeditUnslidVMAddr - leInfo.layout.textUnslidVMAddr) + offsetInLinkEdit; } else if ( leInfo.dyldInfo != nullptr ) { trieSize = leInfo.dyldInfo->export_size; uint64_t offsetInLinkEdit = leInfo.dyldInfo->export_off - leInfo.layout.linkeditFileOffset; return (uint8_t*)this + (leInfo.layout.linkeditUnslidVMAddr - leInfo.layout.textUnslidVMAddr) + offsetInLinkEdit; } trieSize = 0; return nullptr; } void MachOLoaded::getLayoutInfo(LayoutInfo& result) const { forEachSegment(^(const SegmentInfo& info, bool& stop) { if ( strcmp(info.segName, "__TEXT") == 0 ) { result.textUnslidVMAddr = (uintptr_t)info.vmAddr; result.slide = (uintptr_t)(((uint64_t)this) - info.vmAddr); } else if ( strcmp(info.segName, "__LINKEDIT") == 0 ) { result.linkeditUnslidVMAddr = (uintptr_t)info.vmAddr; result.linkeditFileOffset = (uint32_t)info.fileOffset; result.linkeditFileSize = (uint32_t)info.fileSize; result.linkeditSegIndex = info.segIndex; } result.lastSegIndex = info.segIndex; }); } bool MachOLoaded::hasExportTrie(uint32_t& runtimeOffset, uint32_t& size) const { runtimeOffset = 0; size = 0; Diagnostics diag; LinkEditInfo leInfo; getLinkEditPointers(diag, leInfo); diag.assertNoError(); // any malformations in the file should have been caught by earlier validate() call if ( diag.hasError() ) return false; uint64_t trieSize; if ( const uint8_t* trie = getExportsTrie(leInfo, trieSize) ) { runtimeOffset = (uint32_t)(trie - (uint8_t*)this); size = (uint32_t)trieSize; return true; } return false; } //#if BUILDING_LIBDYLD // this is only used by dlsym() at runtime. All other binding is done when the closure is built. bool MachOLoaded::hasExportedSymbol(const char* symbolName, DependentToMachOLoaded finder, void** result, bool* resultPointsToInstructions) const { typedef void* (*ResolverFunc)(void); ResolverFunc resolver; Diagnostics diag; FoundSymbol foundInfo; if ( findExportedSymbol(diag, symbolName, false, foundInfo, finder) ) { switch ( foundInfo.kind ) { case FoundSymbol::Kind::headerOffset: { *result = (uint8_t*)foundInfo.foundInDylib + foundInfo.value; *resultPointsToInstructions = false; int64_t slide = foundInfo.foundInDylib->getSlide(); foundInfo.foundInDylib->forEachSection(^(const SectionInfo& sectInfo, bool malformedSectionRange, bool& stop) { uint64_t sectStartAddr = sectInfo.sectAddr + slide; uint64_t sectEndAddr = sectStartAddr + sectInfo.sectSize; if ( ((uint64_t)*result >= sectStartAddr) && ((uint64_t)*result < sectEndAddr) ) { *resultPointsToInstructions = (sectInfo.sectFlags & S_ATTR_PURE_INSTRUCTIONS) || (sectInfo.sectFlags & S_ATTR_SOME_INSTRUCTIONS); stop = true; } }); break; } case FoundSymbol::Kind::absolute: *result = (void*)(long)foundInfo.value; *resultPointsToInstructions = false; break; case FoundSymbol::Kind::resolverOffset: // foundInfo.value contains "stub". // in dlsym() we want to call resolver function to get final function address resolver = (ResolverFunc)((uint8_t*)foundInfo.foundInDylib + foundInfo.resolverFuncOffset); *result = (*resolver)(); // FIXME: Set this properly *resultPointsToInstructions = true; break; } return true; } return false; } //#endif // BUILDING_LIBDYLD bool MachOLoaded::findExportedSymbol(Diagnostics& diag, const char* symbolName, bool weakImport, FoundSymbol& foundInfo, DependentToMachOLoaded findDependent) const { LinkEditInfo leInfo; getLinkEditPointers(diag, leInfo); if ( diag.hasError() ) return false; uint64_t trieSize; if ( const uint8_t* trieStart = getExportsTrie(leInfo, trieSize) ) { const uint8_t* trieEnd = trieStart + trieSize; const uint8_t* node = trieWalk(diag, trieStart, trieEnd, symbolName); if ( node == nullptr ) { // symbol not exported from this image. Seach any re-exported dylibs __block unsigned depIndex = 0; __block bool foundInReExportedDylib = false; forEachDependentDylib(^(const char* loadPath, bool isWeak, bool isReExport, bool isUpward, uint32_t compatVersion, uint32_t curVersion, bool& stop) { if ( isReExport && findDependent ) { if ( const MachOLoaded* depMH = findDependent(this, depIndex) ) { if ( depMH->findExportedSymbol(diag, symbolName, weakImport, foundInfo, findDependent) ) { stop = true; foundInReExportedDylib = true; } } } ++depIndex; }); return foundInReExportedDylib; } const uint8_t* p = node; const uint64_t flags = read_uleb128(diag, p, trieEnd); if ( flags & EXPORT_SYMBOL_FLAGS_REEXPORT ) { if ( !findDependent ) return false; // re-export from another dylib, lookup there const uint64_t ordinal = read_uleb128(diag, p, trieEnd); const char* importedName = (char*)p; if ( importedName[0] == '\0' ) importedName = symbolName; if ( (ordinal == 0) || (ordinal > dependentDylibCount()) ) { diag.error("re-export ordinal %lld out of range for %s", ordinal, symbolName); return false; } uint32_t depIndex = (uint32_t)(ordinal-1); if ( const MachOLoaded* depMH = findDependent(this, depIndex) ) { return depMH->findExportedSymbol(diag, importedName, weakImport, foundInfo, findDependent); } else if (weakImport) { return false; } else { diag.error("dependent dylib %lld not found for re-exported symbol %s", ordinal, symbolName); return false; } } foundInfo.kind = FoundSymbol::Kind::headerOffset; foundInfo.isThreadLocal = false; foundInfo.isWeakDef = false; foundInfo.foundInDylib = this; foundInfo.value = read_uleb128(diag, p, trieEnd); foundInfo.resolverFuncOffset = 0; foundInfo.foundSymbolName = symbolName; if ( diag.hasError() ) return false; switch ( flags & EXPORT_SYMBOL_FLAGS_KIND_MASK ) { case EXPORT_SYMBOL_FLAGS_KIND_REGULAR: if ( flags & EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER ) { foundInfo.kind = FoundSymbol::Kind::headerOffset; foundInfo.resolverFuncOffset = (uint32_t)read_uleb128(diag, p, trieEnd); } else { foundInfo.kind = FoundSymbol::Kind::headerOffset; } if ( flags & EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION ) foundInfo.isWeakDef = true; break; case EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL: foundInfo.isThreadLocal = true; break; case EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE: foundInfo.kind = FoundSymbol::Kind::absolute; break; default: diag.error("unsupported exported symbol kind. flags=%llu at node offset=0x%0lX", flags, (long)(node-trieStart)); return false; } return true; } else { // this is an old binary (before macOS 10.6), scan the symbol table foundInfo.foundInDylib = nullptr; forEachGlobalSymbol(diag, ^(const char* aSymbolName, uint64_t n_value, uint8_t n_type, uint8_t n_sect, uint16_t n_desc, bool& stop) { if ( strcmp(aSymbolName, symbolName) == 0 ) { foundInfo.kind = FoundSymbol::Kind::headerOffset; foundInfo.isThreadLocal = false; foundInfo.foundInDylib = this; foundInfo.value = n_value - leInfo.layout.textUnslidVMAddr; foundInfo.resolverFuncOffset = 0; foundInfo.foundSymbolName = symbolName; stop = true; } }); if ( foundInfo.foundInDylib == nullptr ) { // symbol not exported from this image. Search any re-exported dylibs __block unsigned depIndex = 0; forEachDependentDylib(^(const char* loadPath, bool isWeak, bool isReExport, bool isUpward, uint32_t compatVersion, uint32_t curVersion, bool& stop) { if ( isReExport && findDependent ) { if ( const MachOLoaded* depMH = findDependent(this, depIndex) ) { if ( depMH->findExportedSymbol(diag, symbolName, weakImport, foundInfo, findDependent) ) { stop = true; } } } ++depIndex; }); } return (foundInfo.foundInDylib != nullptr); } } intptr_t MachOLoaded::getSlide() const { Diagnostics diag; __block intptr_t slide = 0; forEachLoadCommand(diag, ^(const load_command* cmd, bool& stop) { if ( cmd->cmd == LC_SEGMENT_64 ) { const segment_command_64* seg = (segment_command_64*)cmd; if ( strcmp(seg->segname, "__TEXT") == 0 ) { slide = (uintptr_t)(((uint64_t)this) - seg->vmaddr); stop = true; } } else if ( cmd->cmd == LC_SEGMENT ) { const segment_command* seg = (segment_command*)cmd; if ( strcmp(seg->segname, "__TEXT") == 0 ) { slide = (uintptr_t)(((uint64_t)this) - seg->vmaddr); stop = true; } } }); diag.assertNoError(); // any malformations in the file should have been caught by earlier validate() call return slide; } const uint8_t* MachOLoaded::getLinkEditContent(const LayoutInfo& info, uint32_t fileOffset) const { uint32_t offsetInLinkedit = fileOffset - info.linkeditFileOffset; uintptr_t linkeditStartAddr = info.linkeditUnslidVMAddr + info.slide; return (uint8_t*)(linkeditStartAddr + offsetInLinkedit); } void MachOLoaded::forEachGlobalSymbol(Diagnostics& diag, void (^callback)(const char* symbolName, uint64_t n_value, uint8_t n_type, uint8_t n_sect, uint16_t n_desc, bool& stop)) const { LinkEditInfo leInfo; getLinkEditPointers(diag, leInfo); if ( diag.hasError() ) return; const bool is64Bit = is64(); if ( leInfo.symTab != nullptr ) { uint32_t globalsStartIndex = 0; uint32_t globalsCount = leInfo.symTab->nsyms; if ( leInfo.dynSymTab != nullptr ) { globalsStartIndex = leInfo.dynSymTab->iextdefsym; globalsCount = leInfo.dynSymTab->nextdefsym; } uint32_t maxStringOffset = leInfo.symTab->strsize; const char* stringPool = (char*)getLinkEditContent(leInfo.layout, leInfo.symTab->stroff); const struct nlist* symbols = (struct nlist*) (getLinkEditContent(leInfo.layout, leInfo.symTab->symoff)); const struct nlist_64* symbols64 = (struct nlist_64*)symbols; bool stop = false; for (uint32_t i=0; (i < globalsCount) && !stop; ++i) { if ( is64Bit ) { const struct nlist_64& sym = symbols64[globalsStartIndex+i]; if ( sym.n_un.n_strx > maxStringOffset ) continue; if ( (sym.n_type & N_EXT) && ((sym.n_type & N_TYPE) == N_SECT) && ((sym.n_type & N_STAB) == 0) ) callback(&stringPool[sym.n_un.n_strx], sym.n_value, sym.n_type, sym.n_sect, sym.n_desc, stop); } else { const struct nlist& sym = symbols[globalsStartIndex+i]; if ( sym.n_un.n_strx > maxStringOffset ) continue; if ( (sym.n_type & N_EXT) && ((sym.n_type & N_TYPE) == N_SECT) && ((sym.n_type & N_STAB) == 0) ) callback(&stringPool[sym.n_un.n_strx], sym.n_value, sym.n_type, sym.n_sect, sym.n_desc, stop); } } } } void MachOLoaded::forEachLocalSymbol(Diagnostics& diag, void (^callback)(const char* symbolName, uint64_t n_value, uint8_t n_type, uint8_t n_sect, uint16_t n_desc, bool& stop)) const { LinkEditInfo leInfo; getLinkEditPointers(diag, leInfo); if ( diag.hasError() ) return; const bool is64Bit = is64(); if ( leInfo.symTab != nullptr ) { uint32_t localsStartIndex = 0; uint32_t localsCount = leInfo.symTab->nsyms; if ( leInfo.dynSymTab != nullptr ) { localsStartIndex = leInfo.dynSymTab->ilocalsym; localsCount = leInfo.dynSymTab->nlocalsym; } uint32_t maxStringOffset = leInfo.symTab->strsize; const char* stringPool = (char*)getLinkEditContent(leInfo.layout, leInfo.symTab->stroff); const struct nlist* symbols = (struct nlist*) (getLinkEditContent(leInfo.layout, leInfo.symTab->symoff)); const struct nlist_64* symbols64 = (struct nlist_64*)(getLinkEditContent(leInfo.layout, leInfo.symTab->symoff)); bool stop = false; for (uint32_t i=0; (i < localsCount) && !stop; ++i) { if ( is64Bit ) { const struct nlist_64& sym = symbols64[localsStartIndex+i]; if ( sym.n_un.n_strx > maxStringOffset ) continue; if ( ((sym.n_type & N_EXT) == 0) && ((sym.n_type & N_TYPE) == N_SECT) && ((sym.n_type & N_STAB) == 0) ) callback(&stringPool[sym.n_un.n_strx], sym.n_value, sym.n_type, sym.n_sect, sym.n_desc, stop); } else { const struct nlist& sym = symbols[localsStartIndex+i]; if ( sym.n_un.n_strx > maxStringOffset ) continue; if ( ((sym.n_type & N_EXT) == 0) && ((sym.n_type & N_TYPE) == N_SECT) && ((sym.n_type & N_STAB) == 0) ) callback(&stringPool[sym.n_un.n_strx], sym.n_value, sym.n_type, sym.n_sect, sym.n_desc, stop); } } } } uint32_t MachOLoaded::dependentDylibCount(bool* allDepsAreNormalPtr) const { __block uint32_t count = 0; __block bool allDepsAreNormal = true; forEachDependentDylib(^(const char* loadPath, bool isWeak, bool isReExport, bool isUpward, uint32_t compatVersion, uint32_t curVersion, bool& stop) { ++count; if ( isWeak || isReExport || isUpward ) allDepsAreNormal = false; }); if ( allDepsAreNormalPtr != nullptr ) *allDepsAreNormalPtr = allDepsAreNormal; return count; } const char* MachOLoaded::dependentDylibLoadPath(uint32_t depIndex) const { __block const char* foundLoadPath = nullptr; __block uint32_t curDepIndex = 0; forEachDependentDylib(^(const char* loadPath, bool isWeak, bool isReExport, bool isUpward, uint32_t compatVersion, uint32_t curVersion, bool& stop) { if ( curDepIndex == depIndex ) { foundLoadPath = loadPath; stop = true; } ++curDepIndex; }); return foundLoadPath; } const char* MachOLoaded::segmentName(uint32_t targetSegIndex) const { __block const char* result = nullptr; forEachSegment(^(const SegmentInfo& info, bool& stop) { if ( targetSegIndex == info.segIndex ) { result = info.segName; stop = true; } }); return result; } bool MachOLoaded::findClosestFunctionStart(uint64_t address, uint64_t* functionStartAddress) const { Diagnostics diag; LinkEditInfo leInfo; getLinkEditPointers(diag, leInfo); if ( diag.hasError() ) return false; if ( leInfo.functionStarts == nullptr ) return false; const uint8_t* starts = getLinkEditContent(leInfo.layout, leInfo.functionStarts->dataoff); const uint8_t* startsEnd = starts + leInfo.functionStarts->datasize; uint64_t lastAddr = (uint64_t)(long)this; uint64_t runningAddr = lastAddr; while (diag.noError()) { uint64_t value = read_uleb128(diag, starts, startsEnd); if ( value == 0 ) break; lastAddr = runningAddr; runningAddr += value; //fprintf(stderr, " addr=0x%08llX\n", runningAddr); if ( runningAddr > address ) { *functionStartAddress = lastAddr; return true; } }; return false; } bool MachOLoaded::findClosestSymbol(uint64_t address, const char** symbolName, uint64_t* symbolAddr) const { Diagnostics diag; LinkEditInfo leInfo; getLinkEditPointers(diag, leInfo); if ( diag.hasError() ) return false; if ( (leInfo.symTab == nullptr) || (leInfo.dynSymTab == nullptr) ) return false; uint64_t targetUnslidAddress = address - leInfo.layout.slide; // find section index the address is in to validate n_sect __block uint32_t sectionIndexForTargetAddress = 0; forEachSection(^(const SectionInfo& sectInfo, bool malformedSectionRange, bool& stop) { ++sectionIndexForTargetAddress; if ( (sectInfo.sectAddr <= targetUnslidAddress) && (targetUnslidAddress < sectInfo.sectAddr+sectInfo.sectSize) ) { stop = true; } }); uint32_t maxStringOffset = leInfo.symTab->strsize; const char* stringPool = (char*)getLinkEditContent(leInfo.layout, leInfo.symTab->stroff); const struct nlist* symbols = (struct nlist*) (getLinkEditContent(leInfo.layout, leInfo.symTab->symoff)); if ( is64() ) { const struct nlist_64* symbols64 = (struct nlist_64*)symbols; const struct nlist_64* bestSymbol = nullptr; // first walk all global symbols const struct nlist_64* const globalsStart = &symbols64[leInfo.dynSymTab->iextdefsym]; const struct nlist_64* const globalsEnd = &globalsStart[leInfo.dynSymTab->nextdefsym]; for (const struct nlist_64* s = globalsStart; s < globalsEnd; ++s) { if ( (s->n_type & N_TYPE) == N_SECT ) { if ( bestSymbol == nullptr ) { if ( (s->n_value <= targetUnslidAddress) && (s->n_sect == sectionIndexForTargetAddress) ) bestSymbol = s; } else if ( (s->n_value <= targetUnslidAddress) && (bestSymbol->n_value < s->n_value) && (s->n_sect == sectionIndexForTargetAddress) ) { bestSymbol = s; } } } // next walk all local symbols const struct nlist_64* const localsStart = &symbols64[leInfo.dynSymTab->ilocalsym]; const struct nlist_64* const localsEnd = &localsStart[leInfo.dynSymTab->nlocalsym]; for (const struct nlist_64* s = localsStart; s < localsEnd; ++s) { if ( ((s->n_type & N_TYPE) == N_SECT) && ((s->n_type & N_STAB) == 0) ) { if ( bestSymbol == nullptr ) { if ( (s->n_value <= targetUnslidAddress) && (s->n_sect == sectionIndexForTargetAddress) ) bestSymbol = s; } else if ( (s->n_value <= targetUnslidAddress) && (bestSymbol->n_value < s->n_value) && (s->n_sect == sectionIndexForTargetAddress) ) { bestSymbol = s; } } } if ( bestSymbol != NULL ) { *symbolAddr = bestSymbol->n_value + leInfo.layout.slide; if ( bestSymbol->n_un.n_strx < maxStringOffset ) *symbolName = &stringPool[bestSymbol->n_un.n_strx]; return true; } } else { const struct nlist* bestSymbol = nullptr; // first walk all global symbols const struct nlist* const globalsStart = &symbols[leInfo.dynSymTab->iextdefsym]; const struct nlist* const globalsEnd = &globalsStart[leInfo.dynSymTab->nextdefsym]; for (const struct nlist* s = globalsStart; s < globalsEnd; ++s) { if ( (s->n_type & N_TYPE) == N_SECT ) { if ( bestSymbol == nullptr ) { if ( (s->n_value <= targetUnslidAddress) && (s->n_sect == sectionIndexForTargetAddress) ) bestSymbol = s; } else if ( (s->n_value <= targetUnslidAddress) && (bestSymbol->n_value < s->n_value) && (s->n_sect == sectionIndexForTargetAddress) ) { bestSymbol = s; } } } // next walk all local symbols const struct nlist* const localsStart = &symbols[leInfo.dynSymTab->ilocalsym]; const struct nlist* const localsEnd = &localsStart[leInfo.dynSymTab->nlocalsym]; for (const struct nlist* s = localsStart; s < localsEnd; ++s) { if ( ((s->n_type & N_TYPE) == N_SECT) && ((s->n_type & N_STAB) == 0) ) { if ( bestSymbol == nullptr ) { if ( (s->n_value <= targetUnslidAddress) && (s->n_sect == sectionIndexForTargetAddress) ) bestSymbol = s; } else if ( (s->n_value <= targetUnslidAddress) && (bestSymbol->n_value < s->n_value) && (s->n_sect == sectionIndexForTargetAddress) ) { bestSymbol = s; } } } if ( bestSymbol != nullptr ) { #if __arm__ if ( bestSymbol->n_desc & N_ARM_THUMB_DEF ) *symbolAddr = (bestSymbol->n_value | 1) + leInfo.layout.slide; else *symbolAddr = bestSymbol->n_value + leInfo.layout.slide; #else *symbolAddr = bestSymbol->n_value + leInfo.layout.slide; #endif if ( bestSymbol->n_un.n_strx < maxStringOffset ) *symbolName = &stringPool[bestSymbol->n_un.n_strx]; return true; } } return false; } const void* MachOLoaded::findSectionContent(const char* segName, const char* sectName, uint64_t& size, bool matchSegNameAsPrefix) const { __block const void* result = nullptr; forEachSection(^(const SectionInfo& sectInfo, bool malformedSectionRange, bool& stop) { if ( strcmp(sectInfo.sectName, sectName) != 0 ) return; // Segment name is either matched exactly or by prefix if ( matchSegNameAsPrefix ) { if ( strstr(sectInfo.segInfo.segName, segName) != sectInfo.segInfo.segName ) return; } else { if ( strcmp(sectInfo.segInfo.segName, segName) != 0 ) return; } size = sectInfo.sectSize; result = (void*)(sectInfo.sectAddr + getSlide()); stop = true; }); return result; } bool MachOLoaded::intersectsRange(uintptr_t start, uintptr_t length) const { __block bool result = false; uintptr_t slide = getSlide(); forEachSegment(^(const SegmentInfo& info, bool& stop) { if ( (info.vmAddr+info.vmSize+slide >= start) && (info.vmAddr+slide < start+length) ) result = true; }); return result; } const uint8_t* MachOLoaded::trieWalk(Diagnostics& diag, const uint8_t* start, const uint8_t* end, const char* symbol) { STACK_ALLOC_OVERFLOW_SAFE_ARRAY(uint32_t, visitedNodeOffsets, 128); visitedNodeOffsets.push_back(0); const uint8_t* p = start; while ( p < end ) { uint64_t terminalSize = *p++; if ( terminalSize > 127 ) { // except for re-export-with-rename, all terminal sizes fit in one byte --p; terminalSize = read_uleb128(diag, p, end); if ( diag.hasError() ) return nullptr; } if ( (*symbol == '\0') && (terminalSize != 0) ) { return p; } const uint8_t* children = p + terminalSize; if ( children > end ) { //diag.error("malformed trie node, terminalSize=0x%llX extends past end of trie\n", terminalSize); return nullptr; } uint8_t childrenRemaining = *children++; p = children; uint64_t nodeOffset = 0; for (; childrenRemaining > 0; --childrenRemaining) { const char* ss = symbol; bool wrongEdge = false; // scan whole edge to get to next edge // if edge is longer than target symbol name, don't read past end of symbol name char c = *p; while ( c != '\0' ) { if ( !wrongEdge ) { if ( c != *ss ) wrongEdge = true; ++ss; } ++p; c = *p; } if ( wrongEdge ) { // advance to next child ++p; // skip over zero terminator // skip over uleb128 until last byte is found while ( (*p & 0x80) != 0 ) ++p; ++p; // skip over last byte of uleb128 if ( p > end ) { diag.error("malformed trie node, child node extends past end of trie\n"); return nullptr; } } else { // the symbol so far matches this edge (child) // so advance to the child's node ++p; nodeOffset = read_uleb128(diag, p, end); if ( diag.hasError() ) return nullptr; if ( (nodeOffset == 0) || ( &start[nodeOffset] > end) ) { diag.error("malformed trie child, nodeOffset=0x%llX out of range\n", nodeOffset); return nullptr; } symbol = ss; break; } } if ( nodeOffset != 0 ) { if ( nodeOffset > (uint64_t)(end-start) ) { diag.error("malformed trie child, nodeOffset=0x%llX out of range\n", nodeOffset); return nullptr; } // check for cycles for (uint32_t aVisitedNodeOffset : visitedNodeOffsets) { if ( aVisitedNodeOffset == nodeOffset ) { diag.error("malformed trie child, cycle to nodeOffset=0x%llX\n", nodeOffset); return nullptr; } } visitedNodeOffsets.push_back((uint32_t)nodeOffset); p = &start[nodeOffset]; } else p = end; } return nullptr; } void MachOLoaded::forEachCDHashOfCodeSignature(const void* codeSigStart, size_t codeSignLen, void (^callback)(const uint8_t cdHash[20])) const { forEachCodeDirectoryBlob(codeSigStart, codeSignLen, ^(const void *cdBuffer) { const CS_CodeDirectory* cd = (const CS_CodeDirectory*)cdBuffer; uint32_t cdLength = htonl(cd->length); uint8_t cdHash[20]; if ( cd->hashType == CS_HASHTYPE_SHA384 ) { uint8_t digest[CCSHA384_OUTPUT_SIZE]; const struct ccdigest_info* di = ccsha384_di(); ccdigest_di_decl(di, tempBuf); // declares tempBuf array in stack ccdigest_init(di, tempBuf); ccdigest_update(di, tempBuf, cdLength, cd); ccdigest_final(di, tempBuf, digest); ccdigest_di_clear(di, tempBuf); // cd-hash of sigs that use SHA384 is the first 20 bytes of the SHA384 of the code digest memcpy(cdHash, digest, 20); callback(cdHash); return; } else if ( (cd->hashType == CS_HASHTYPE_SHA256) || (cd->hashType == CS_HASHTYPE_SHA256_TRUNCATED) ) { uint8_t digest[CCSHA256_OUTPUT_SIZE]; const struct ccdigest_info* di = ccsha256_di(); ccdigest_di_decl(di, tempBuf); // declares tempBuf array in stack ccdigest_init(di, tempBuf); ccdigest_update(di, tempBuf, cdLength, cd); ccdigest_final(di, tempBuf, digest); ccdigest_di_clear(di, tempBuf); // cd-hash of sigs that use SHA256 is the first 20 bytes of the SHA256 of the code digest memcpy(cdHash, digest, 20); callback(cdHash); return; } else if ( cd->hashType == CS_HASHTYPE_SHA1 ) { // compute hash directly into return buffer const struct ccdigest_info* di = ccsha1_di(); ccdigest_di_decl(di, tempBuf); // declares tempBuf array in stack ccdigest_init(di, tempBuf); ccdigest_update(di, tempBuf, cdLength, cd); ccdigest_final(di, tempBuf, cdHash); ccdigest_di_clear(di, tempBuf); callback(cdHash); return; } }); } // Note, this has to match the kernel static const uint32_t hashPriorities[] = { CS_HASHTYPE_SHA1, CS_HASHTYPE_SHA256_TRUNCATED, CS_HASHTYPE_SHA256, CS_HASHTYPE_SHA384, }; static unsigned int hash_rank(const CS_CodeDirectory *cd) { uint32_t type = cd->hashType; for (uint32_t n = 0; n < sizeof(hashPriorities) / sizeof(hashPriorities[0]); ++n) { if (hashPriorities[n] == type) return n + 1; } /* not supported */ return 0; } // Note, this does NOT match the kernel. // On watchOS, in main executables, we will record all cd hashes then make sure // one of the ones we record matches the kernel. // This list is only for dylibs where we embed the cd hash in the closure instead of the // mod time and inode // This is sorted so that we choose sha1 first when checking dylibs static const uint32_t hashPriorities_watchOS_dylibs[] = { CS_HASHTYPE_SHA256_TRUNCATED, CS_HASHTYPE_SHA256, CS_HASHTYPE_SHA384, CS_HASHTYPE_SHA1 }; static unsigned int hash_rank_watchOS_dylibs(const CS_CodeDirectory *cd) { uint32_t type = cd->hashType; for (uint32_t n = 0; n < sizeof(hashPriorities_watchOS_dylibs) / sizeof(hashPriorities_watchOS_dylibs[0]); ++n) { if (hashPriorities_watchOS_dylibs[n] == type) return n + 1; } /* not supported */ return 0; } // This calls the callback for all code directories required for a given platform/binary combination. // On watchOS main executables this is all cd hashes. // On watchOS dylibs this is only the single cd hash we need (by rank defined by dyld, not the kernel). // On all other platforms this always returns a single best cd hash (ranked to match the kernel). // Note the callback parameter is really a CS_CodeDirectory. void MachOLoaded::forEachCodeDirectoryBlob(const void* codeSigStart, size_t codeSignLen, void (^callback)(const void* cd)) const { // verify min length of overall code signature if ( codeSignLen < sizeof(CS_SuperBlob) ) return; // verify magic at start const CS_SuperBlob* codeSuperBlob = (CS_SuperBlob*)codeSigStart; if ( codeSuperBlob->magic != htonl(CSMAGIC_EMBEDDED_SIGNATURE) ) return; // verify count of sub-blobs not too large uint32_t subBlobCount = htonl(codeSuperBlob->count); if ( (codeSignLen-sizeof(CS_SuperBlob))/sizeof(CS_BlobIndex) < subBlobCount ) return; // Note: The kernel sometimes chooses sha1 on watchOS, and sometimes sha256. // Embed all of them so that we just need to match any of them const bool isWatchOS = this->builtForPlatform(Platform::watchOS); const bool isMainExecutable = this->isMainExecutable(); auto hashRankFn = isWatchOS ? &hash_rank_watchOS_dylibs : &hash_rank; // walk each sub blob, looking at ones with type CSSLOT_CODEDIRECTORY const CS_CodeDirectory* bestCd = nullptr; for (uint32_t i=0; i < subBlobCount; ++i) { if ( codeSuperBlob->index[i].type == htonl(CSSLOT_CODEDIRECTORY) ) { // Ok, this is the regular code directory } else if ( codeSuperBlob->index[i].type >= htonl(CSSLOT_ALTERNATE_CODEDIRECTORIES) && codeSuperBlob->index[i].type <= htonl(CSSLOT_ALTERNATE_CODEDIRECTORY_LIMIT)) { // Ok, this is the alternative code directory } else { continue; } uint32_t cdOffset = htonl(codeSuperBlob->index[i].offset); // verify offset is not out of range if ( cdOffset > (codeSignLen - sizeof(CS_CodeDirectory)) ) continue; const CS_CodeDirectory* cd = (CS_CodeDirectory*)((uint8_t*)codeSuperBlob + cdOffset); uint32_t cdLength = htonl(cd->length); // verify code directory length not out of range if ( cdLength > (codeSignLen - cdOffset) ) continue; // The watch main executable wants to know about all cd hashes if ( isWatchOS && isMainExecutable ) { callback(cd); continue; } if ( cd->magic == htonl(CSMAGIC_CODEDIRECTORY) ) { if ( !bestCd || (hashRankFn(cd) > hashRankFn(bestCd)) ) bestCd = cd; } } // Note this callback won't happen on watchOS as that one was done in the loop if ( bestCd != nullptr ) callback(bestCd); } uint64_t MachOLoaded::ChainedFixupPointerOnDisk::Arm64e::unpackTarget() const { assert(this->authBind.bind == 0); assert(this->authBind.auth == 0); return ((uint64_t)(this->rebase.high8) << 56) | (this->rebase.target); } uint64_t MachOLoaded::ChainedFixupPointerOnDisk::Arm64e::signExtendedAddend() const { assert(this->authBind.bind == 1); assert(this->authBind.auth == 0); uint64_t addend19 = this->bind.addend; if ( addend19 & 0x40000 ) return addend19 | 0xFFFFFFFFFFFC0000ULL; else return addend19; } const char* MachOLoaded::ChainedFixupPointerOnDisk::Arm64e::keyName(uint8_t keyBits) { static const char* const names[] = { "IA", "IB", "DA", "DB" }; assert(keyBits < 4); return names[keyBits]; } const char* MachOLoaded::ChainedFixupPointerOnDisk::Arm64e::keyName() const { assert(this->authBind.auth == 1); return keyName(this->authBind.key); } uint64_t MachOLoaded::ChainedFixupPointerOnDisk::Arm64e::signPointer(uint64_t unsignedAddr, void* loc, bool addrDiv, uint16_t diversity, uint8_t key) { // don't sign NULL if ( unsignedAddr == 0 ) return 0; #if __has_feature(ptrauth_calls) uint64_t extendedDiscriminator = diversity; if ( addrDiv ) extendedDiscriminator = __builtin_ptrauth_blend_discriminator(loc, extendedDiscriminator); switch ( key ) { case 0: // IA return (uintptr_t)__builtin_ptrauth_sign_unauthenticated((void*)unsignedAddr, 0, extendedDiscriminator); case 1: // IB return (uintptr_t)__builtin_ptrauth_sign_unauthenticated((void*)unsignedAddr, 1, extendedDiscriminator); case 2: // DA return (uintptr_t)__builtin_ptrauth_sign_unauthenticated((void*)unsignedAddr, 2, extendedDiscriminator); case 3: // DB return (uintptr_t)__builtin_ptrauth_sign_unauthenticated((void*)unsignedAddr, 3, extendedDiscriminator); } assert(0 && "invalid signing key"); #else assert(0 && "arm64e signing only arm64e"); #endif } uint64_t MachOLoaded::ChainedFixupPointerOnDisk::Arm64e::signPointer(void* loc, uint64_t target) const { assert(this->authBind.auth == 1); return signPointer(target, loc, authBind.addrDiv, authBind.diversity, authBind.key); } uint64_t MachOLoaded::ChainedFixupPointerOnDisk::Generic64::unpackedTarget() const { return (((uint64_t)this->rebase.high8) << 56) | (uint64_t)(this->rebase.target); } uint64_t MachOLoaded::ChainedFixupPointerOnDisk::Generic64::signExtendedAddend() const { uint64_t addend27 = this->bind.addend; uint64_t top8Bits = addend27 & 0x00007F80000ULL; uint64_t bottom19Bits = addend27 & 0x0000007FFFFULL; uint64_t newValue = (top8Bits << 13) | (((uint64_t)(bottom19Bits << 37) >> 37) & 0x00FFFFFFFFFFFFFF); return newValue; } const char* MachOLoaded::ChainedFixupPointerOnDisk::Kernel64::keyName() const { static const char* names[] = { "IA", "IB", "DA", "DB" }; assert(this->isAuth == 1); uint8_t keyBits = this->key; assert(keyBits < 4); return names[keyBits]; } bool MachOLoaded::ChainedFixupPointerOnDisk::isRebase(uint16_t pointerFormat, uint64_t preferedLoadAddress, uint64_t& targetRuntimeOffset) const { switch (pointerFormat) { case DYLD_CHAINED_PTR_ARM64E: case DYLD_CHAINED_PTR_ARM64E_USERLAND: case DYLD_CHAINED_PTR_ARM64E_USERLAND24: case DYLD_CHAINED_PTR_ARM64E_KERNEL: case DYLD_CHAINED_PTR_ARM64E_FIRMWARE: if ( this->arm64e.bind.bind ) return false; if ( this->arm64e.authRebase.auth ) { targetRuntimeOffset = this->arm64e.authRebase.target; return true; } else { targetRuntimeOffset = this->arm64e.unpackTarget(); if ( (pointerFormat == DYLD_CHAINED_PTR_ARM64E) || (pointerFormat == DYLD_CHAINED_PTR_ARM64E_FIRMWARE) ) { targetRuntimeOffset -= preferedLoadAddress; } return true; } break; case DYLD_CHAINED_PTR_64: case DYLD_CHAINED_PTR_64_OFFSET: if ( this->generic64.bind.bind ) return false; targetRuntimeOffset = this->generic64.unpackedTarget(); if ( pointerFormat == DYLD_CHAINED_PTR_64 ) targetRuntimeOffset -= preferedLoadAddress; return true; break; case DYLD_CHAINED_PTR_64_KERNEL_CACHE: case DYLD_CHAINED_PTR_X86_64_KERNEL_CACHE: targetRuntimeOffset = this->kernel64.target; return true; break; case DYLD_CHAINED_PTR_32: if ( this->generic32.bind.bind ) return false; targetRuntimeOffset = this->generic32.rebase.target - preferedLoadAddress; return true; break; case DYLD_CHAINED_PTR_32_FIRMWARE: targetRuntimeOffset = this->firmware32.target - preferedLoadAddress; return true; break; default: break; } assert(0 && "unsupported pointer chain format"); } bool MachOLoaded::ChainedFixupPointerOnDisk::isBind(uint16_t pointerFormat, uint32_t& bindOrdinal, int64_t& addend) const { addend = 0; switch (pointerFormat) { case DYLD_CHAINED_PTR_ARM64E: case DYLD_CHAINED_PTR_ARM64E_USERLAND: case DYLD_CHAINED_PTR_ARM64E_USERLAND24: case DYLD_CHAINED_PTR_ARM64E_KERNEL: case DYLD_CHAINED_PTR_ARM64E_FIRMWARE: if ( !this->arm64e.authBind.bind ) return false; if ( this->arm64e.authBind.auth ) { if ( pointerFormat == DYLD_CHAINED_PTR_ARM64E_USERLAND24 ) bindOrdinal = this->arm64e.authBind24.ordinal; else bindOrdinal = this->arm64e.authBind.ordinal; return true; } else { if ( pointerFormat == DYLD_CHAINED_PTR_ARM64E_USERLAND24 ) bindOrdinal = this->arm64e.bind24.ordinal; else bindOrdinal = this->arm64e.bind.ordinal; addend = this->arm64e.signExtendedAddend(); return true; } break; case DYLD_CHAINED_PTR_64: case DYLD_CHAINED_PTR_64_OFFSET: if ( !this->generic64.bind.bind ) return false; bindOrdinal = this->generic64.bind.ordinal; addend = this->generic64.bind.addend; return true; break; case DYLD_CHAINED_PTR_32: if ( !this->generic32.bind.bind ) return false; bindOrdinal = this->generic32.bind.ordinal; addend = this->generic32.bind.addend; return true; break; case DYLD_CHAINED_PTR_64_KERNEL_CACHE: case DYLD_CHAINED_PTR_X86_64_KERNEL_CACHE: return false; default: break; } assert(0 && "unsupported pointer chain format"); } unsigned MachOLoaded::ChainedFixupPointerOnDisk::strideSize(uint16_t pointerFormat) { switch (pointerFormat) { case DYLD_CHAINED_PTR_ARM64E: case DYLD_CHAINED_PTR_ARM64E_USERLAND: case DYLD_CHAINED_PTR_ARM64E_USERLAND24: return 8; case DYLD_CHAINED_PTR_ARM64E_KERNEL: case DYLD_CHAINED_PTR_ARM64E_FIRMWARE: case DYLD_CHAINED_PTR_32_FIRMWARE: case DYLD_CHAINED_PTR_64: case DYLD_CHAINED_PTR_64_OFFSET: case DYLD_CHAINED_PTR_32: case DYLD_CHAINED_PTR_32_CACHE: case DYLD_CHAINED_PTR_64_KERNEL_CACHE: return 4; case DYLD_CHAINED_PTR_X86_64_KERNEL_CACHE: return 1; } assert(0 && "unsupported pointer chain format"); } //#if BUILDING_DYLD || BUILDING_LIBDYLD void MachOLoaded::fixupAllChainedFixups(Diagnostics& diag, const dyld_chained_starts_in_image* starts, uintptr_t slide, Array<const void*> bindTargets, void (^logFixup)(void* loc, void* newValue)) const { forEachFixupInAllChains(diag, starts, true, ^(ChainedFixupPointerOnDisk* fixupLoc, const dyld_chained_starts_in_segment* segInfo, bool& stop) { void* newValue; switch (segInfo->pointer_format) { #if __LP64__ #if __has_feature(ptrauth_calls) case DYLD_CHAINED_PTR_ARM64E: case DYLD_CHAINED_PTR_ARM64E_KERNEL: case DYLD_CHAINED_PTR_ARM64E_USERLAND: case DYLD_CHAINED_PTR_ARM64E_USERLAND24: if ( fixupLoc->arm64e.authRebase.auth ) { if ( fixupLoc->arm64e.authBind.bind ) { uint32_t bindOrdinal = (segInfo->pointer_format == DYLD_CHAINED_PTR_ARM64E_USERLAND24) ? fixupLoc->arm64e.authBind24.ordinal : fixupLoc->arm64e.authBind.ordinal; if ( bindOrdinal >= bindTargets.count() ) { diag.error("out of range bind ordinal %d (max %lu)", bindOrdinal, bindTargets.count()); stop = true; break; } else { // authenticated bind newValue = (void*)(bindTargets[bindOrdinal]); if (newValue != 0) // Don't sign missing weak imports newValue = (void*)fixupLoc->arm64e.signPointer(fixupLoc, (uintptr_t)newValue); } } else { // authenticated rebase newValue = (void*)fixupLoc->arm64e.signPointer(fixupLoc, (uintptr_t)this + fixupLoc->arm64e.authRebase.target); } } else { if ( fixupLoc->arm64e.bind.bind ) { uint32_t bindOrdinal = (segInfo->pointer_format == DYLD_CHAINED_PTR_ARM64E_USERLAND24) ? fixupLoc->arm64e.bind24.ordinal : fixupLoc->arm64e.bind.ordinal; if ( bindOrdinal >= bindTargets.count() ) { diag.error("out of range bind ordinal %d (max %lu)", bindOrdinal, bindTargets.count()); stop = true; break; } else { // plain bind newValue = (void*)((long)bindTargets[bindOrdinal] + fixupLoc->arm64e.signExtendedAddend()); } } else { // plain rebase (old format target is vmaddr, new format target is offset) if ( segInfo->pointer_format == DYLD_CHAINED_PTR_ARM64E ) newValue = (void*)(fixupLoc->arm64e.unpackTarget()+slide); else newValue = (void*)((uintptr_t)this + fixupLoc->arm64e.unpackTarget()); } } if ( logFixup ) logFixup(fixupLoc, newValue); fixupLoc->raw64 = (uintptr_t)newValue; break; #endif case DYLD_CHAINED_PTR_64: case DYLD_CHAINED_PTR_64_OFFSET: if ( fixupLoc->generic64.bind.bind ) { if ( fixupLoc->generic64.bind.ordinal >= bindTargets.count() ) { diag.error("out of range bind ordinal %d (max %lu)", fixupLoc->generic64.bind.ordinal, bindTargets.count()); stop = true; break; } else { newValue = (void*)((long)bindTargets[fixupLoc->generic64.bind.ordinal] + fixupLoc->generic64.signExtendedAddend()); } } else { // plain rebase (old format target is vmaddr, new format target is offset) if ( segInfo->pointer_format == DYLD_CHAINED_PTR_64 ) newValue = (void*)(fixupLoc->generic64.unpackedTarget()+slide); else newValue = (void*)((uintptr_t)this + fixupLoc->generic64.unpackedTarget()); } if ( logFixup ) logFixup(fixupLoc, newValue); fixupLoc->raw64 = (uintptr_t)newValue; break; #else case DYLD_CHAINED_PTR_32: if ( fixupLoc->generic32.bind.bind ) { if ( fixupLoc->generic32.bind.ordinal >= bindTargets.count() ) { diag.error("out of range bind ordinal %d (max %lu)", fixupLoc->generic32.bind.ordinal, bindTargets.count()); stop = true; break; } else { newValue = (void*)((long)bindTargets[fixupLoc->generic32.bind.ordinal] + fixupLoc->generic32.bind.addend); } } else { if ( fixupLoc->generic32.rebase.target > segInfo->max_valid_pointer ) { // handle non-pointers in chain uint32_t bias = (0x04000000 + segInfo->max_valid_pointer)/2; newValue = (void*)(fixupLoc->generic32.rebase.target - bias); } else { newValue = (void*)(fixupLoc->generic32.rebase.target + slide); } } if ( logFixup ) logFixup(fixupLoc, newValue); fixupLoc->raw32 = (uint32_t)(uintptr_t)newValue; break; #endif // __LP64__ default: diag.error("unsupported pointer chain format: 0x%04X", segInfo->pointer_format); stop = true; break; } }); } //#endif bool MachOLoaded::walkChain(Diagnostics& diag, ChainedFixupPointerOnDisk* chain, uint16_t pointer_format, bool notifyNonPointers, uint32_t max_valid_pointer, void (^handler)(ChainedFixupPointerOnDisk* fixupLocation, bool& stop)) const { const unsigned stride = ChainedFixupPointerOnDisk::strideSize(pointer_format); bool stop = false; bool chainEnd = false; while (!stop && !chainEnd) { // copy chain content, in case handler modifies location to final value ChainedFixupPointerOnDisk chainContent = *chain; handler(chain, stop); if ( !stop ) { switch (pointer_format) { case DYLD_CHAINED_PTR_ARM64E: case DYLD_CHAINED_PTR_ARM64E_KERNEL: case DYLD_CHAINED_PTR_ARM64E_USERLAND: case DYLD_CHAINED_PTR_ARM64E_USERLAND24: case DYLD_CHAINED_PTR_ARM64E_FIRMWARE: if ( chainContent.arm64e.rebase.next == 0 ) chainEnd = true; else chain = (ChainedFixupPointerOnDisk*)((uint8_t*)chain + chainContent.arm64e.rebase.next*stride); break; case DYLD_CHAINED_PTR_64: case DYLD_CHAINED_PTR_64_OFFSET: if ( chainContent.generic64.rebase.next == 0 ) chainEnd = true; else chain = (ChainedFixupPointerOnDisk*)((uint8_t*)chain + chainContent.generic64.rebase.next*4); break; case DYLD_CHAINED_PTR_32: if ( chainContent.generic32.rebase.next == 0 ) chainEnd = true; else { chain = (ChainedFixupPointerOnDisk*)((uint8_t*)chain + chainContent.generic32.rebase.next*4); if ( !notifyNonPointers ) { while ( (chain->generic32.rebase.bind == 0) && (chain->generic32.rebase.target > max_valid_pointer) ) { // not a real pointer, but a non-pointer co-opted into chain chain = (ChainedFixupPointerOnDisk*)((uint8_t*)chain + chain->generic32.rebase.next*4); } } } break; case DYLD_CHAINED_PTR_64_KERNEL_CACHE: case DYLD_CHAINED_PTR_X86_64_KERNEL_CACHE: if ( chainContent.kernel64.next == 0 ) chainEnd = true; else chain = (ChainedFixupPointerOnDisk*)((uint8_t*)chain + chainContent.kernel64.next*stride); break; case DYLD_CHAINED_PTR_32_FIRMWARE: if ( chainContent.firmware32.next == 0 ) chainEnd = true; else chain = (ChainedFixupPointerOnDisk*)((uint8_t*)chain + chainContent.firmware32.next*4); break; default: diag.error("unknown pointer format 0x%04X", pointer_format); stop = true; } } } return stop; } void MachOLoaded::forEachFixupChainSegment(Diagnostics& diag, const dyld_chained_starts_in_image* starts, void (^handler)(const dyld_chained_starts_in_segment* segInfo, uint32_t segIndex, bool& stop)) const { bool stopped = false; for (uint32_t segIndex=0; segIndex < starts->seg_count && !stopped; ++segIndex) { if ( starts->seg_info_offset[segIndex] == 0 ) continue; const dyld_chained_starts_in_segment* segInfo = (dyld_chained_starts_in_segment*)((uint8_t*)starts + starts->seg_info_offset[segIndex]); handler(segInfo, segIndex, stopped); } } void MachOLoaded::forEachFixupInSegmentChains(Diagnostics& diag, const dyld_chained_starts_in_segment* segInfo, bool notifyNonPointers, void (^handler)(ChainedFixupPointerOnDisk* fixupLocation, const dyld_chained_starts_in_segment* segInfo, bool& stop)) const { auto adaptor = ^(ChainedFixupPointerOnDisk* fixupLocation, bool& stop) { handler(fixupLocation, segInfo, stop); }; bool stopped = false; for (uint32_t pageIndex=0; pageIndex < segInfo->page_count && !stopped; ++pageIndex) { uint16_t offsetInPage = segInfo->page_start[pageIndex]; if ( offsetInPage == DYLD_CHAINED_PTR_START_NONE ) continue; if ( offsetInPage & DYLD_CHAINED_PTR_START_MULTI ) { // 32-bit chains which may need multiple starts per page uint32_t overflowIndex = offsetInPage & ~DYLD_CHAINED_PTR_START_MULTI; bool chainEnd = false; while (!stopped && !chainEnd) { chainEnd = (segInfo->page_start[overflowIndex] & DYLD_CHAINED_PTR_START_LAST); offsetInPage = (segInfo->page_start[overflowIndex] & ~DYLD_CHAINED_PTR_START_LAST); uint8_t* pageContentStart = (uint8_t*)this + segInfo->segment_offset + (pageIndex * segInfo->page_size); ChainedFixupPointerOnDisk* chain = (ChainedFixupPointerOnDisk*)(pageContentStart+offsetInPage); stopped = walkChain(diag, chain, segInfo->pointer_format, notifyNonPointers, segInfo->max_valid_pointer, adaptor); ++overflowIndex; } } else { // one chain per page uint8_t* pageContentStart = (uint8_t*)this + segInfo->segment_offset + (pageIndex * segInfo->page_size); ChainedFixupPointerOnDisk* chain = (ChainedFixupPointerOnDisk*)(pageContentStart+offsetInPage); stopped = walkChain(diag, chain, segInfo->pointer_format, notifyNonPointers, segInfo->max_valid_pointer, adaptor); } } } void MachOLoaded::forEachFixupInAllChains(Diagnostics& diag, const dyld_chained_starts_in_image* starts, bool notifyNonPointers, void (^handler)(ChainedFixupPointerOnDisk* fixupLocation, const dyld_chained_starts_in_segment* segInfo, bool& stop)) const { bool stopped = false; for (uint32_t segIndex=0; segIndex < starts->seg_count && !stopped; ++segIndex) { if ( starts->seg_info_offset[segIndex] == 0 ) continue; const dyld_chained_starts_in_segment* segInfo = (dyld_chained_starts_in_segment*)((uint8_t*)starts + starts->seg_info_offset[segIndex]); forEachFixupInSegmentChains(diag, segInfo, notifyNonPointers, handler); } } void MachOLoaded::forEachFixupInAllChains(Diagnostics& diag, uint16_t pointer_format, uint32_t starts_count, const uint32_t chain_starts[], void (^handler)(ChainedFixupPointerOnDisk* fixupLocation, bool& stop)) const { for (uint32_t i=0; i < starts_count; ++i) { ChainedFixupPointerOnDisk* chain = (ChainedFixupPointerOnDisk*)((uint8_t*)this + chain_starts[i]); if ( walkChain(diag, chain, pointer_format, false, 0, handler) ) break; } } MachOLoaded::PointerMetaData::PointerMetaData() { this->diversity = 0; this->high8 = 0; this->authenticated = 0; this->key = 0; this->usesAddrDiversity = 0; } MachOLoaded::PointerMetaData::PointerMetaData(const ChainedFixupPointerOnDisk* fixupLoc, uint16_t pointer_format) { this->diversity = 0; this->high8 = 0; this->authenticated = 0; this->key = 0; this->usesAddrDiversity = 0; switch ( pointer_format ) { case DYLD_CHAINED_PTR_ARM64E: case DYLD_CHAINED_PTR_ARM64E_KERNEL: case DYLD_CHAINED_PTR_ARM64E_USERLAND: case DYLD_CHAINED_PTR_ARM64E_FIRMWARE: case DYLD_CHAINED_PTR_ARM64E_USERLAND24: this->authenticated = fixupLoc->arm64e.authRebase.auth; if ( this->authenticated ) { this->key = fixupLoc->arm64e.authRebase.key; this->usesAddrDiversity = fixupLoc->arm64e.authRebase.addrDiv; this->diversity = fixupLoc->arm64e.authRebase.diversity; } else if ( fixupLoc->arm64e.bind.bind == 0 ) { this->high8 = fixupLoc->arm64e.rebase.high8; } break; case DYLD_CHAINED_PTR_64: case DYLD_CHAINED_PTR_64_OFFSET: if ( fixupLoc->generic64.bind.bind == 0 ) this->high8 = fixupLoc->generic64.rebase.high8; break; } } } // namespace dyld3 |