1 //===-- MachODump.cpp - Object file dumping utility for llvm --------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements the MachO-specific dumper for llvm-objdump. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "MachODump.h" 14 15 #include "llvm-objdump.h" 16 #include "llvm-c/Disassembler.h" 17 #include "llvm/ADT/STLExtras.h" 18 #include "llvm/ADT/StringExtras.h" 19 #include "llvm/ADT/Triple.h" 20 #include "llvm/BinaryFormat/MachO.h" 21 #include "llvm/Config/config.h" 22 #include "llvm/DebugInfo/DIContext.h" 23 #include "llvm/DebugInfo/DWARF/DWARFContext.h" 24 #include "llvm/Demangle/Demangle.h" 25 #include "llvm/MC/MCAsmInfo.h" 26 #include "llvm/MC/MCContext.h" 27 #include "llvm/MC/MCDisassembler/MCDisassembler.h" 28 #include "llvm/MC/MCInst.h" 29 #include "llvm/MC/MCInstPrinter.h" 30 #include "llvm/MC/MCInstrDesc.h" 31 #include "llvm/MC/MCInstrInfo.h" 32 #include "llvm/MC/MCRegisterInfo.h" 33 #include "llvm/MC/MCSubtargetInfo.h" 34 #include "llvm/MC/MCTargetOptions.h" 35 #include "llvm/Object/MachO.h" 36 #include "llvm/Object/MachOUniversal.h" 37 #include "llvm/Support/Casting.h" 38 #include "llvm/Support/CommandLine.h" 39 #include "llvm/Support/Debug.h" 40 #include "llvm/Support/Endian.h" 41 #include "llvm/Support/Format.h" 42 #include "llvm/Support/FormattedStream.h" 43 #include "llvm/Support/GraphWriter.h" 44 #include "llvm/Support/LEB128.h" 45 #include "llvm/Support/MemoryBuffer.h" 46 #include "llvm/Support/TargetRegistry.h" 47 #include "llvm/Support/TargetSelect.h" 48 #include "llvm/Support/ToolOutputFile.h" 49 #include "llvm/Support/WithColor.h" 50 #include "llvm/Support/raw_ostream.h" 51 #include <algorithm> 52 #include <cstring> 53 #include <system_error> 54 55 #ifdef HAVE_LIBXAR 56 extern "C" { 57 #include <xar/xar.h> 58 } 59 #endif 60 61 using namespace llvm; 62 using namespace llvm::object; 63 using namespace llvm::objdump; 64 65 cl::OptionCategory objdump::MachOCat("llvm-objdump MachO Specific Options"); 66 67 cl::opt<bool> objdump::FirstPrivateHeader( 68 "private-header", 69 cl::desc("Display only the first format specific file header"), 70 cl::cat(MachOCat)); 71 72 cl::opt<bool> objdump::ExportsTrie("exports-trie", 73 cl::desc("Display mach-o exported symbols"), 74 cl::cat(MachOCat)); 75 76 cl::opt<bool> objdump::Rebase("rebase", 77 cl::desc("Display mach-o rebasing info"), 78 cl::cat(MachOCat)); 79 80 cl::opt<bool> objdump::Bind("bind", cl::desc("Display mach-o binding info"), 81 cl::cat(MachOCat)); 82 83 cl::opt<bool> objdump::LazyBind("lazy-bind", 84 cl::desc("Display mach-o lazy binding info"), 85 cl::cat(MachOCat)); 86 87 cl::opt<bool> objdump::WeakBind("weak-bind", 88 cl::desc("Display mach-o weak binding info"), 89 cl::cat(MachOCat)); 90 91 static cl::opt<bool> 92 UseDbg("g", cl::Grouping, 93 cl::desc("Print line information from debug info if available"), 94 cl::cat(MachOCat)); 95 96 static cl::opt<std::string> DSYMFile("dsym", 97 cl::desc("Use .dSYM file for debug info"), 98 cl::cat(MachOCat)); 99 100 static cl::opt<bool> FullLeadingAddr("full-leading-addr", 101 cl::desc("Print full leading address"), 102 cl::cat(MachOCat)); 103 104 static cl::opt<bool> NoLeadingHeaders("no-leading-headers", 105 cl::desc("Print no leading headers"), 106 cl::cat(MachOCat)); 107 108 cl::opt<bool> objdump::UniversalHeaders( 109 "universal-headers", 110 cl::desc("Print Mach-O universal headers (requires -macho)"), 111 cl::cat(MachOCat)); 112 113 static cl::opt<bool> ArchiveMemberOffsets( 114 "archive-member-offsets", 115 cl::desc("Print the offset to each archive member for Mach-O archives " 116 "(requires -macho and -archive-headers)"), 117 cl::cat(MachOCat)); 118 119 cl::opt<bool> objdump::IndirectSymbols( 120 "indirect-symbols", 121 cl::desc( 122 "Print indirect symbol table for Mach-O objects (requires -macho)"), 123 cl::cat(MachOCat)); 124 125 cl::opt<bool> objdump::DataInCode( 126 "data-in-code", 127 cl::desc( 128 "Print the data in code table for Mach-O objects (requires -macho)"), 129 cl::cat(MachOCat)); 130 131 cl::opt<bool> 132 objdump::LinkOptHints("link-opt-hints", 133 cl::desc("Print the linker optimization hints for " 134 "Mach-O objects (requires -macho)"), 135 cl::cat(MachOCat)); 136 137 cl::opt<bool> 138 objdump::InfoPlist("info-plist", 139 cl::desc("Print the info plist section as strings for " 140 "Mach-O objects (requires -macho)"), 141 cl::cat(MachOCat)); 142 143 cl::opt<bool> 144 objdump::DylibsUsed("dylibs-used", 145 cl::desc("Print the shared libraries used for linked " 146 "Mach-O files (requires -macho)"), 147 cl::cat(MachOCat)); 148 149 cl::opt<bool> objdump::DylibId("dylib-id", 150 cl::desc("Print the shared library's id for the " 151 "dylib Mach-O file (requires -macho)"), 152 cl::cat(MachOCat)); 153 154 static cl::opt<bool> 155 NonVerbose("non-verbose", 156 cl::desc("Print the info for Mach-O objects in non-verbose or " 157 "numeric form (requires -macho)"), 158 cl::cat(MachOCat)); 159 160 cl::opt<bool> 161 objdump::ObjcMetaData("objc-meta-data", 162 cl::desc("Print the Objective-C runtime meta data " 163 "for Mach-O files (requires -macho)"), 164 cl::cat(MachOCat)); 165 166 static cl::opt<std::string> DisSymName( 167 "dis-symname", 168 cl::desc("disassemble just this symbol's instructions (requires -macho)"), 169 cl::cat(MachOCat)); 170 171 static cl::opt<bool> NoSymbolicOperands( 172 "no-symbolic-operands", 173 cl::desc("do not symbolic operands when disassembling (requires -macho)"), 174 cl::cat(MachOCat)); 175 176 static cl::list<std::string> 177 ArchFlags("arch", cl::desc("architecture(s) from a Mach-O file to dump"), 178 cl::ZeroOrMore, cl::cat(MachOCat)); 179 180 static bool ArchAll = false; 181 182 static std::string ThumbTripleName; 183 184 static const Target *GetTarget(const MachOObjectFile *MachOObj, 185 const char **McpuDefault, 186 const Target **ThumbTarget) { 187 // Figure out the target triple. 188 Triple TT(TripleName); 189 if (TripleName.empty()) { 190 TT = MachOObj->getArchTriple(McpuDefault); 191 TripleName = TT.str(); 192 } 193 194 if (TT.getArch() == Triple::arm) { 195 // We've inferred a 32-bit ARM target from the object file. All MachO CPUs 196 // that support ARM are also capable of Thumb mode. 197 Triple ThumbTriple = TT; 198 std::string ThumbName = (Twine("thumb") + TT.getArchName().substr(3)).str(); 199 ThumbTriple.setArchName(ThumbName); 200 ThumbTripleName = ThumbTriple.str(); 201 } 202 203 // Get the target specific parser. 204 std::string Error; 205 const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error); 206 if (TheTarget && ThumbTripleName.empty()) 207 return TheTarget; 208 209 *ThumbTarget = TargetRegistry::lookupTarget(ThumbTripleName, Error); 210 if (*ThumbTarget) 211 return TheTarget; 212 213 WithColor::error(errs(), "llvm-objdump") << "unable to get target for '"; 214 if (!TheTarget) 215 errs() << TripleName; 216 else 217 errs() << ThumbTripleName; 218 errs() << "', see --version and --triple.\n"; 219 return nullptr; 220 } 221 222 namespace { 223 struct SymbolSorter { 224 bool operator()(const SymbolRef &A, const SymbolRef &B) { 225 Expected<SymbolRef::Type> ATypeOrErr = A.getType(); 226 if (!ATypeOrErr) 227 reportError(ATypeOrErr.takeError(), A.getObject()->getFileName()); 228 SymbolRef::Type AType = *ATypeOrErr; 229 Expected<SymbolRef::Type> BTypeOrErr = B.getType(); 230 if (!BTypeOrErr) 231 reportError(BTypeOrErr.takeError(), B.getObject()->getFileName()); 232 SymbolRef::Type BType = *BTypeOrErr; 233 uint64_t AAddr = 234 (AType != SymbolRef::ST_Function) ? 0 : cantFail(A.getValue()); 235 uint64_t BAddr = 236 (BType != SymbolRef::ST_Function) ? 0 : cantFail(B.getValue()); 237 return AAddr < BAddr; 238 } 239 }; 240 } // namespace 241 242 // Types for the storted data in code table that is built before disassembly 243 // and the predicate function to sort them. 244 typedef std::pair<uint64_t, DiceRef> DiceTableEntry; 245 typedef std::vector<DiceTableEntry> DiceTable; 246 typedef DiceTable::iterator dice_table_iterator; 247 248 #ifdef HAVE_LIBXAR 249 namespace { 250 struct ScopedXarFile { 251 xar_t xar; 252 ScopedXarFile(const char *filename, int32_t flags) 253 : xar(xar_open(filename, flags)) {} 254 ~ScopedXarFile() { 255 if (xar) 256 xar_close(xar); 257 } 258 ScopedXarFile(const ScopedXarFile &) = delete; 259 ScopedXarFile &operator=(const ScopedXarFile &) = delete; 260 operator xar_t() { return xar; } 261 }; 262 263 struct ScopedXarIter { 264 xar_iter_t iter; 265 ScopedXarIter() : iter(xar_iter_new()) {} 266 ~ScopedXarIter() { 267 if (iter) 268 xar_iter_free(iter); 269 } 270 ScopedXarIter(const ScopedXarIter &) = delete; 271 ScopedXarIter &operator=(const ScopedXarIter &) = delete; 272 operator xar_iter_t() { return iter; } 273 }; 274 } // namespace 275 #endif // defined(HAVE_LIBXAR) 276 277 // This is used to search for a data in code table entry for the PC being 278 // disassembled. The j parameter has the PC in j.first. A single data in code 279 // table entry can cover many bytes for each of its Kind's. So if the offset, 280 // aka the i.first value, of the data in code table entry plus its Length 281 // covers the PC being searched for this will return true. If not it will 282 // return false. 283 static bool compareDiceTableEntries(const DiceTableEntry &i, 284 const DiceTableEntry &j) { 285 uint16_t Length; 286 i.second.getLength(Length); 287 288 return j.first >= i.first && j.first < i.first + Length; 289 } 290 291 static uint64_t DumpDataInCode(const uint8_t *bytes, uint64_t Length, 292 unsigned short Kind) { 293 uint32_t Value, Size = 1; 294 295 switch (Kind) { 296 default: 297 case MachO::DICE_KIND_DATA: 298 if (Length >= 4) { 299 if (!NoShowRawInsn) 300 dumpBytes(makeArrayRef(bytes, 4), outs()); 301 Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0]; 302 outs() << "\t.long " << Value; 303 Size = 4; 304 } else if (Length >= 2) { 305 if (!NoShowRawInsn) 306 dumpBytes(makeArrayRef(bytes, 2), outs()); 307 Value = bytes[1] << 8 | bytes[0]; 308 outs() << "\t.short " << Value; 309 Size = 2; 310 } else { 311 if (!NoShowRawInsn) 312 dumpBytes(makeArrayRef(bytes, 2), outs()); 313 Value = bytes[0]; 314 outs() << "\t.byte " << Value; 315 Size = 1; 316 } 317 if (Kind == MachO::DICE_KIND_DATA) 318 outs() << "\t@ KIND_DATA\n"; 319 else 320 outs() << "\t@ data in code kind = " << Kind << "\n"; 321 break; 322 case MachO::DICE_KIND_JUMP_TABLE8: 323 if (!NoShowRawInsn) 324 dumpBytes(makeArrayRef(bytes, 1), outs()); 325 Value = bytes[0]; 326 outs() << "\t.byte " << format("%3u", Value) << "\t@ KIND_JUMP_TABLE8\n"; 327 Size = 1; 328 break; 329 case MachO::DICE_KIND_JUMP_TABLE16: 330 if (!NoShowRawInsn) 331 dumpBytes(makeArrayRef(bytes, 2), outs()); 332 Value = bytes[1] << 8 | bytes[0]; 333 outs() << "\t.short " << format("%5u", Value & 0xffff) 334 << "\t@ KIND_JUMP_TABLE16\n"; 335 Size = 2; 336 break; 337 case MachO::DICE_KIND_JUMP_TABLE32: 338 case MachO::DICE_KIND_ABS_JUMP_TABLE32: 339 if (!NoShowRawInsn) 340 dumpBytes(makeArrayRef(bytes, 4), outs()); 341 Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0]; 342 outs() << "\t.long " << Value; 343 if (Kind == MachO::DICE_KIND_JUMP_TABLE32) 344 outs() << "\t@ KIND_JUMP_TABLE32\n"; 345 else 346 outs() << "\t@ KIND_ABS_JUMP_TABLE32\n"; 347 Size = 4; 348 break; 349 } 350 return Size; 351 } 352 353 static void getSectionsAndSymbols(MachOObjectFile *MachOObj, 354 std::vector<SectionRef> &Sections, 355 std::vector<SymbolRef> &Symbols, 356 SmallVectorImpl<uint64_t> &FoundFns, 357 uint64_t &BaseSegmentAddress) { 358 const StringRef FileName = MachOObj->getFileName(); 359 for (const SymbolRef &Symbol : MachOObj->symbols()) { 360 StringRef SymName = unwrapOrError(Symbol.getName(), FileName); 361 if (!SymName.startswith("ltmp")) 362 Symbols.push_back(Symbol); 363 } 364 365 for (const SectionRef &Section : MachOObj->sections()) 366 Sections.push_back(Section); 367 368 bool BaseSegmentAddressSet = false; 369 for (const auto &Command : MachOObj->load_commands()) { 370 if (Command.C.cmd == MachO::LC_FUNCTION_STARTS) { 371 // We found a function starts segment, parse the addresses for later 372 // consumption. 373 MachO::linkedit_data_command LLC = 374 MachOObj->getLinkeditDataLoadCommand(Command); 375 376 MachOObj->ReadULEB128s(LLC.dataoff, FoundFns); 377 } else if (Command.C.cmd == MachO::LC_SEGMENT) { 378 MachO::segment_command SLC = MachOObj->getSegmentLoadCommand(Command); 379 StringRef SegName = SLC.segname; 380 if (!BaseSegmentAddressSet && SegName != "__PAGEZERO") { 381 BaseSegmentAddressSet = true; 382 BaseSegmentAddress = SLC.vmaddr; 383 } 384 } else if (Command.C.cmd == MachO::LC_SEGMENT_64) { 385 MachO::segment_command_64 SLC = MachOObj->getSegment64LoadCommand(Command); 386 StringRef SegName = SLC.segname; 387 if (!BaseSegmentAddressSet && SegName != "__PAGEZERO") { 388 BaseSegmentAddressSet = true; 389 BaseSegmentAddress = SLC.vmaddr; 390 } 391 } 392 } 393 } 394 395 static bool DumpAndSkipDataInCode(uint64_t PC, const uint8_t *bytes, 396 DiceTable &Dices, uint64_t &InstSize) { 397 // Check the data in code table here to see if this is data not an 398 // instruction to be disassembled. 399 DiceTable Dice; 400 Dice.push_back(std::make_pair(PC, DiceRef())); 401 dice_table_iterator DTI = 402 std::search(Dices.begin(), Dices.end(), Dice.begin(), Dice.end(), 403 compareDiceTableEntries); 404 if (DTI != Dices.end()) { 405 uint16_t Length; 406 DTI->second.getLength(Length); 407 uint16_t Kind; 408 DTI->second.getKind(Kind); 409 InstSize = DumpDataInCode(bytes, Length, Kind); 410 if ((Kind == MachO::DICE_KIND_JUMP_TABLE8) && 411 (PC == (DTI->first + Length - 1)) && (Length & 1)) 412 InstSize++; 413 return true; 414 } 415 return false; 416 } 417 418 static void printRelocationTargetName(const MachOObjectFile *O, 419 const MachO::any_relocation_info &RE, 420 raw_string_ostream &Fmt) { 421 // Target of a scattered relocation is an address. In the interest of 422 // generating pretty output, scan through the symbol table looking for a 423 // symbol that aligns with that address. If we find one, print it. 424 // Otherwise, we just print the hex address of the target. 425 const StringRef FileName = O->getFileName(); 426 if (O->isRelocationScattered(RE)) { 427 uint32_t Val = O->getPlainRelocationSymbolNum(RE); 428 429 for (const SymbolRef &Symbol : O->symbols()) { 430 uint64_t Addr = unwrapOrError(Symbol.getAddress(), FileName); 431 if (Addr != Val) 432 continue; 433 Fmt << unwrapOrError(Symbol.getName(), FileName); 434 return; 435 } 436 437 // If we couldn't find a symbol that this relocation refers to, try 438 // to find a section beginning instead. 439 for (const SectionRef &Section : ToolSectionFilter(*O)) { 440 uint64_t Addr = Section.getAddress(); 441 if (Addr != Val) 442 continue; 443 StringRef NameOrErr = unwrapOrError(Section.getName(), O->getFileName()); 444 Fmt << NameOrErr; 445 return; 446 } 447 448 Fmt << format("0x%x", Val); 449 return; 450 } 451 452 StringRef S; 453 bool isExtern = O->getPlainRelocationExternal(RE); 454 uint64_t Val = O->getPlainRelocationSymbolNum(RE); 455 456 if (O->getAnyRelocationType(RE) == MachO::ARM64_RELOC_ADDEND && 457 (O->getArch() == Triple::aarch64 || O->getArch() == Triple::aarch64_be)) { 458 Fmt << format("0x%0" PRIx64, Val); 459 return; 460 } 461 462 if (isExtern) { 463 symbol_iterator SI = O->symbol_begin(); 464 advance(SI, Val); 465 S = unwrapOrError(SI->getName(), FileName); 466 } else { 467 section_iterator SI = O->section_begin(); 468 // Adjust for the fact that sections are 1-indexed. 469 if (Val == 0) { 470 Fmt << "0 (?,?)"; 471 return; 472 } 473 uint32_t I = Val - 1; 474 while (I != 0 && SI != O->section_end()) { 475 --I; 476 advance(SI, 1); 477 } 478 if (SI == O->section_end()) { 479 Fmt << Val << " (?,?)"; 480 } else { 481 if (Expected<StringRef> NameOrErr = SI->getName()) 482 S = *NameOrErr; 483 else 484 consumeError(NameOrErr.takeError()); 485 } 486 } 487 488 Fmt << S; 489 } 490 491 Error objdump::getMachORelocationValueString(const MachOObjectFile *Obj, 492 const RelocationRef &RelRef, 493 SmallVectorImpl<char> &Result) { 494 DataRefImpl Rel = RelRef.getRawDataRefImpl(); 495 MachO::any_relocation_info RE = Obj->getRelocation(Rel); 496 497 unsigned Arch = Obj->getArch(); 498 499 std::string FmtBuf; 500 raw_string_ostream Fmt(FmtBuf); 501 unsigned Type = Obj->getAnyRelocationType(RE); 502 bool IsPCRel = Obj->getAnyRelocationPCRel(RE); 503 504 // Determine any addends that should be displayed with the relocation. 505 // These require decoding the relocation type, which is triple-specific. 506 507 // X86_64 has entirely custom relocation types. 508 if (Arch == Triple::x86_64) { 509 switch (Type) { 510 case MachO::X86_64_RELOC_GOT_LOAD: 511 case MachO::X86_64_RELOC_GOT: { 512 printRelocationTargetName(Obj, RE, Fmt); 513 Fmt << "@GOT"; 514 if (IsPCRel) 515 Fmt << "PCREL"; 516 break; 517 } 518 case MachO::X86_64_RELOC_SUBTRACTOR: { 519 DataRefImpl RelNext = Rel; 520 Obj->moveRelocationNext(RelNext); 521 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext); 522 523 // X86_64_RELOC_SUBTRACTOR must be followed by a relocation of type 524 // X86_64_RELOC_UNSIGNED. 525 // NOTE: Scattered relocations don't exist on x86_64. 526 unsigned RType = Obj->getAnyRelocationType(RENext); 527 if (RType != MachO::X86_64_RELOC_UNSIGNED) 528 reportError(Obj->getFileName(), "Expected X86_64_RELOC_UNSIGNED after " 529 "X86_64_RELOC_SUBTRACTOR."); 530 531 // The X86_64_RELOC_UNSIGNED contains the minuend symbol; 532 // X86_64_RELOC_SUBTRACTOR contains the subtrahend. 533 printRelocationTargetName(Obj, RENext, Fmt); 534 Fmt << "-"; 535 printRelocationTargetName(Obj, RE, Fmt); 536 break; 537 } 538 case MachO::X86_64_RELOC_TLV: 539 printRelocationTargetName(Obj, RE, Fmt); 540 Fmt << "@TLV"; 541 if (IsPCRel) 542 Fmt << "P"; 543 break; 544 case MachO::X86_64_RELOC_SIGNED_1: 545 printRelocationTargetName(Obj, RE, Fmt); 546 Fmt << "-1"; 547 break; 548 case MachO::X86_64_RELOC_SIGNED_2: 549 printRelocationTargetName(Obj, RE, Fmt); 550 Fmt << "-2"; 551 break; 552 case MachO::X86_64_RELOC_SIGNED_4: 553 printRelocationTargetName(Obj, RE, Fmt); 554 Fmt << "-4"; 555 break; 556 default: 557 printRelocationTargetName(Obj, RE, Fmt); 558 break; 559 } 560 // X86 and ARM share some relocation types in common. 561 } else if (Arch == Triple::x86 || Arch == Triple::arm || 562 Arch == Triple::ppc) { 563 // Generic relocation types... 564 switch (Type) { 565 case MachO::GENERIC_RELOC_PAIR: // prints no info 566 return Error::success(); 567 case MachO::GENERIC_RELOC_SECTDIFF: { 568 DataRefImpl RelNext = Rel; 569 Obj->moveRelocationNext(RelNext); 570 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext); 571 572 // X86 sect diff's must be followed by a relocation of type 573 // GENERIC_RELOC_PAIR. 574 unsigned RType = Obj->getAnyRelocationType(RENext); 575 576 if (RType != MachO::GENERIC_RELOC_PAIR) 577 reportError(Obj->getFileName(), "Expected GENERIC_RELOC_PAIR after " 578 "GENERIC_RELOC_SECTDIFF."); 579 580 printRelocationTargetName(Obj, RE, Fmt); 581 Fmt << "-"; 582 printRelocationTargetName(Obj, RENext, Fmt); 583 break; 584 } 585 } 586 587 if (Arch == Triple::x86 || Arch == Triple::ppc) { 588 switch (Type) { 589 case MachO::GENERIC_RELOC_LOCAL_SECTDIFF: { 590 DataRefImpl RelNext = Rel; 591 Obj->moveRelocationNext(RelNext); 592 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext); 593 594 // X86 sect diff's must be followed by a relocation of type 595 // GENERIC_RELOC_PAIR. 596 unsigned RType = Obj->getAnyRelocationType(RENext); 597 if (RType != MachO::GENERIC_RELOC_PAIR) 598 reportError(Obj->getFileName(), "Expected GENERIC_RELOC_PAIR after " 599 "GENERIC_RELOC_LOCAL_SECTDIFF."); 600 601 printRelocationTargetName(Obj, RE, Fmt); 602 Fmt << "-"; 603 printRelocationTargetName(Obj, RENext, Fmt); 604 break; 605 } 606 case MachO::GENERIC_RELOC_TLV: { 607 printRelocationTargetName(Obj, RE, Fmt); 608 Fmt << "@TLV"; 609 if (IsPCRel) 610 Fmt << "P"; 611 break; 612 } 613 default: 614 printRelocationTargetName(Obj, RE, Fmt); 615 } 616 } else { // ARM-specific relocations 617 switch (Type) { 618 case MachO::ARM_RELOC_HALF: 619 case MachO::ARM_RELOC_HALF_SECTDIFF: { 620 // Half relocations steal a bit from the length field to encode 621 // whether this is an upper16 or a lower16 relocation. 622 bool isUpper = (Obj->getAnyRelocationLength(RE) & 0x1) == 1; 623 624 if (isUpper) 625 Fmt << ":upper16:("; 626 else 627 Fmt << ":lower16:("; 628 printRelocationTargetName(Obj, RE, Fmt); 629 630 DataRefImpl RelNext = Rel; 631 Obj->moveRelocationNext(RelNext); 632 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext); 633 634 // ARM half relocs must be followed by a relocation of type 635 // ARM_RELOC_PAIR. 636 unsigned RType = Obj->getAnyRelocationType(RENext); 637 if (RType != MachO::ARM_RELOC_PAIR) 638 reportError(Obj->getFileName(), "Expected ARM_RELOC_PAIR after " 639 "ARM_RELOC_HALF"); 640 641 // NOTE: The half of the target virtual address is stashed in the 642 // address field of the secondary relocation, but we can't reverse 643 // engineer the constant offset from it without decoding the movw/movt 644 // instruction to find the other half in its immediate field. 645 646 // ARM_RELOC_HALF_SECTDIFF encodes the second section in the 647 // symbol/section pointer of the follow-on relocation. 648 if (Type == MachO::ARM_RELOC_HALF_SECTDIFF) { 649 Fmt << "-"; 650 printRelocationTargetName(Obj, RENext, Fmt); 651 } 652 653 Fmt << ")"; 654 break; 655 } 656 default: { 657 printRelocationTargetName(Obj, RE, Fmt); 658 } 659 } 660 } 661 } else 662 printRelocationTargetName(Obj, RE, Fmt); 663 664 Fmt.flush(); 665 Result.append(FmtBuf.begin(), FmtBuf.end()); 666 return Error::success(); 667 } 668 669 static void PrintIndirectSymbolTable(MachOObjectFile *O, bool verbose, 670 uint32_t n, uint32_t count, 671 uint32_t stride, uint64_t addr) { 672 MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand(); 673 uint32_t nindirectsyms = Dysymtab.nindirectsyms; 674 if (n > nindirectsyms) 675 outs() << " (entries start past the end of the indirect symbol " 676 "table) (reserved1 field greater than the table size)"; 677 else if (n + count > nindirectsyms) 678 outs() << " (entries extends past the end of the indirect symbol " 679 "table)"; 680 outs() << "\n"; 681 uint32_t cputype = O->getHeader().cputype; 682 if (cputype & MachO::CPU_ARCH_ABI64) 683 outs() << "address index"; 684 else 685 outs() << "address index"; 686 if (verbose) 687 outs() << " name\n"; 688 else 689 outs() << "\n"; 690 for (uint32_t j = 0; j < count && n + j < nindirectsyms; j++) { 691 if (cputype & MachO::CPU_ARCH_ABI64) 692 outs() << format("0x%016" PRIx64, addr + j * stride) << " "; 693 else 694 outs() << format("0x%08" PRIx32, (uint32_t)addr + j * stride) << " "; 695 MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand(); 696 uint32_t indirect_symbol = O->getIndirectSymbolTableEntry(Dysymtab, n + j); 697 if (indirect_symbol == MachO::INDIRECT_SYMBOL_LOCAL) { 698 outs() << "LOCAL\n"; 699 continue; 700 } 701 if (indirect_symbol == 702 (MachO::INDIRECT_SYMBOL_LOCAL | MachO::INDIRECT_SYMBOL_ABS)) { 703 outs() << "LOCAL ABSOLUTE\n"; 704 continue; 705 } 706 if (indirect_symbol == MachO::INDIRECT_SYMBOL_ABS) { 707 outs() << "ABSOLUTE\n"; 708 continue; 709 } 710 outs() << format("%5u ", indirect_symbol); 711 if (verbose) { 712 MachO::symtab_command Symtab = O->getSymtabLoadCommand(); 713 if (indirect_symbol < Symtab.nsyms) { 714 symbol_iterator Sym = O->getSymbolByIndex(indirect_symbol); 715 SymbolRef Symbol = *Sym; 716 outs() << unwrapOrError(Symbol.getName(), O->getFileName()); 717 } else { 718 outs() << "?"; 719 } 720 } 721 outs() << "\n"; 722 } 723 } 724 725 static void PrintIndirectSymbols(MachOObjectFile *O, bool verbose) { 726 for (const auto &Load : O->load_commands()) { 727 if (Load.C.cmd == MachO::LC_SEGMENT_64) { 728 MachO::segment_command_64 Seg = O->getSegment64LoadCommand(Load); 729 for (unsigned J = 0; J < Seg.nsects; ++J) { 730 MachO::section_64 Sec = O->getSection64(Load, J); 731 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE; 732 if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS || 733 section_type == MachO::S_LAZY_SYMBOL_POINTERS || 734 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS || 735 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS || 736 section_type == MachO::S_SYMBOL_STUBS) { 737 uint32_t stride; 738 if (section_type == MachO::S_SYMBOL_STUBS) 739 stride = Sec.reserved2; 740 else 741 stride = 8; 742 if (stride == 0) { 743 outs() << "Can't print indirect symbols for (" << Sec.segname << "," 744 << Sec.sectname << ") " 745 << "(size of stubs in reserved2 field is zero)\n"; 746 continue; 747 } 748 uint32_t count = Sec.size / stride; 749 outs() << "Indirect symbols for (" << Sec.segname << "," 750 << Sec.sectname << ") " << count << " entries"; 751 uint32_t n = Sec.reserved1; 752 PrintIndirectSymbolTable(O, verbose, n, count, stride, Sec.addr); 753 } 754 } 755 } else if (Load.C.cmd == MachO::LC_SEGMENT) { 756 MachO::segment_command Seg = O->getSegmentLoadCommand(Load); 757 for (unsigned J = 0; J < Seg.nsects; ++J) { 758 MachO::section Sec = O->getSection(Load, J); 759 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE; 760 if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS || 761 section_type == MachO::S_LAZY_SYMBOL_POINTERS || 762 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS || 763 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS || 764 section_type == MachO::S_SYMBOL_STUBS) { 765 uint32_t stride; 766 if (section_type == MachO::S_SYMBOL_STUBS) 767 stride = Sec.reserved2; 768 else 769 stride = 4; 770 if (stride == 0) { 771 outs() << "Can't print indirect symbols for (" << Sec.segname << "," 772 << Sec.sectname << ") " 773 << "(size of stubs in reserved2 field is zero)\n"; 774 continue; 775 } 776 uint32_t count = Sec.size / stride; 777 outs() << "Indirect symbols for (" << Sec.segname << "," 778 << Sec.sectname << ") " << count << " entries"; 779 uint32_t n = Sec.reserved1; 780 PrintIndirectSymbolTable(O, verbose, n, count, stride, Sec.addr); 781 } 782 } 783 } 784 } 785 } 786 787 static void PrintRType(const uint64_t cputype, const unsigned r_type) { 788 static char const *generic_r_types[] = { 789 "VANILLA ", "PAIR ", "SECTDIF ", "PBLAPTR ", "LOCSDIF ", "TLV ", 790 " 6 (?) ", " 7 (?) ", " 8 (?) ", " 9 (?) ", " 10 (?) ", " 11 (?) ", 791 " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) " 792 }; 793 static char const *x86_64_r_types[] = { 794 "UNSIGND ", "SIGNED ", "BRANCH ", "GOT_LD ", "GOT ", "SUB ", 795 "SIGNED1 ", "SIGNED2 ", "SIGNED4 ", "TLV ", " 10 (?) ", " 11 (?) ", 796 " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) " 797 }; 798 static char const *arm_r_types[] = { 799 "VANILLA ", "PAIR ", "SECTDIFF", "LOCSDIF ", "PBLAPTR ", 800 "BR24 ", "T_BR22 ", "T_BR32 ", "HALF ", "HALFDIF ", 801 " 10 (?) ", " 11 (?) ", " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) " 802 }; 803 static char const *arm64_r_types[] = { 804 "UNSIGND ", "SUB ", "BR26 ", "PAGE21 ", "PAGOF12 ", 805 "GOTLDP ", "GOTLDPOF", "PTRTGOT ", "TLVLDP ", "TLVLDPOF", 806 "ADDEND ", " 11 (?) ", " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) " 807 }; 808 809 if (r_type > 0xf){ 810 outs() << format("%-7u", r_type) << " "; 811 return; 812 } 813 switch (cputype) { 814 case MachO::CPU_TYPE_I386: 815 outs() << generic_r_types[r_type]; 816 break; 817 case MachO::CPU_TYPE_X86_64: 818 outs() << x86_64_r_types[r_type]; 819 break; 820 case MachO::CPU_TYPE_ARM: 821 outs() << arm_r_types[r_type]; 822 break; 823 case MachO::CPU_TYPE_ARM64: 824 case MachO::CPU_TYPE_ARM64_32: 825 outs() << arm64_r_types[r_type]; 826 break; 827 default: 828 outs() << format("%-7u ", r_type); 829 } 830 } 831 832 static void PrintRLength(const uint64_t cputype, const unsigned r_type, 833 const unsigned r_length, const bool previous_arm_half){ 834 if (cputype == MachO::CPU_TYPE_ARM && 835 (r_type == MachO::ARM_RELOC_HALF || 836 r_type == MachO::ARM_RELOC_HALF_SECTDIFF || previous_arm_half == true)) { 837 if ((r_length & 0x1) == 0) 838 outs() << "lo/"; 839 else 840 outs() << "hi/"; 841 if ((r_length & 0x1) == 0) 842 outs() << "arm "; 843 else 844 outs() << "thm "; 845 } else { 846 switch (r_length) { 847 case 0: 848 outs() << "byte "; 849 break; 850 case 1: 851 outs() << "word "; 852 break; 853 case 2: 854 outs() << "long "; 855 break; 856 case 3: 857 if (cputype == MachO::CPU_TYPE_X86_64) 858 outs() << "quad "; 859 else 860 outs() << format("?(%2d) ", r_length); 861 break; 862 default: 863 outs() << format("?(%2d) ", r_length); 864 } 865 } 866 } 867 868 static void PrintRelocationEntries(const MachOObjectFile *O, 869 const relocation_iterator Begin, 870 const relocation_iterator End, 871 const uint64_t cputype, 872 const bool verbose) { 873 const MachO::symtab_command Symtab = O->getSymtabLoadCommand(); 874 bool previous_arm_half = false; 875 bool previous_sectdiff = false; 876 uint32_t sectdiff_r_type = 0; 877 878 for (relocation_iterator Reloc = Begin; Reloc != End; ++Reloc) { 879 const DataRefImpl Rel = Reloc->getRawDataRefImpl(); 880 const MachO::any_relocation_info RE = O->getRelocation(Rel); 881 const unsigned r_type = O->getAnyRelocationType(RE); 882 const bool r_scattered = O->isRelocationScattered(RE); 883 const unsigned r_pcrel = O->getAnyRelocationPCRel(RE); 884 const unsigned r_length = O->getAnyRelocationLength(RE); 885 const unsigned r_address = O->getAnyRelocationAddress(RE); 886 const bool r_extern = (r_scattered ? false : 887 O->getPlainRelocationExternal(RE)); 888 const uint32_t r_value = (r_scattered ? 889 O->getScatteredRelocationValue(RE) : 0); 890 const unsigned r_symbolnum = (r_scattered ? 0 : 891 O->getPlainRelocationSymbolNum(RE)); 892 893 if (r_scattered && cputype != MachO::CPU_TYPE_X86_64) { 894 if (verbose) { 895 // scattered: address 896 if ((cputype == MachO::CPU_TYPE_I386 && 897 r_type == MachO::GENERIC_RELOC_PAIR) || 898 (cputype == MachO::CPU_TYPE_ARM && r_type == MachO::ARM_RELOC_PAIR)) 899 outs() << " "; 900 else 901 outs() << format("%08x ", (unsigned int)r_address); 902 903 // scattered: pcrel 904 if (r_pcrel) 905 outs() << "True "; 906 else 907 outs() << "False "; 908 909 // scattered: length 910 PrintRLength(cputype, r_type, r_length, previous_arm_half); 911 912 // scattered: extern & type 913 outs() << "n/a "; 914 PrintRType(cputype, r_type); 915 916 // scattered: scattered & value 917 outs() << format("True 0x%08x", (unsigned int)r_value); 918 if (previous_sectdiff == false) { 919 if ((cputype == MachO::CPU_TYPE_ARM && 920 r_type == MachO::ARM_RELOC_PAIR)) 921 outs() << format(" half = 0x%04x ", (unsigned int)r_address); 922 } else if (cputype == MachO::CPU_TYPE_ARM && 923 sectdiff_r_type == MachO::ARM_RELOC_HALF_SECTDIFF) 924 outs() << format(" other_half = 0x%04x ", (unsigned int)r_address); 925 if ((cputype == MachO::CPU_TYPE_I386 && 926 (r_type == MachO::GENERIC_RELOC_SECTDIFF || 927 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF)) || 928 (cputype == MachO::CPU_TYPE_ARM && 929 (sectdiff_r_type == MachO::ARM_RELOC_SECTDIFF || 930 sectdiff_r_type == MachO::ARM_RELOC_LOCAL_SECTDIFF || 931 sectdiff_r_type == MachO::ARM_RELOC_HALF_SECTDIFF))) { 932 previous_sectdiff = true; 933 sectdiff_r_type = r_type; 934 } else { 935 previous_sectdiff = false; 936 sectdiff_r_type = 0; 937 } 938 if (cputype == MachO::CPU_TYPE_ARM && 939 (r_type == MachO::ARM_RELOC_HALF || 940 r_type == MachO::ARM_RELOC_HALF_SECTDIFF)) 941 previous_arm_half = true; 942 else 943 previous_arm_half = false; 944 outs() << "\n"; 945 } 946 else { 947 // scattered: address pcrel length extern type scattered value 948 outs() << format("%08x %1d %-2d n/a %-7d 1 0x%08x\n", 949 (unsigned int)r_address, r_pcrel, r_length, r_type, 950 (unsigned int)r_value); 951 } 952 } 953 else { 954 if (verbose) { 955 // plain: address 956 if (cputype == MachO::CPU_TYPE_ARM && r_type == MachO::ARM_RELOC_PAIR) 957 outs() << " "; 958 else 959 outs() << format("%08x ", (unsigned int)r_address); 960 961 // plain: pcrel 962 if (r_pcrel) 963 outs() << "True "; 964 else 965 outs() << "False "; 966 967 // plain: length 968 PrintRLength(cputype, r_type, r_length, previous_arm_half); 969 970 if (r_extern) { 971 // plain: extern & type & scattered 972 outs() << "True "; 973 PrintRType(cputype, r_type); 974 outs() << "False "; 975 976 // plain: symbolnum/value 977 if (r_symbolnum > Symtab.nsyms) 978 outs() << format("?(%d)\n", r_symbolnum); 979 else { 980 SymbolRef Symbol = *O->getSymbolByIndex(r_symbolnum); 981 Expected<StringRef> SymNameNext = Symbol.getName(); 982 const char *name = NULL; 983 if (SymNameNext) 984 name = SymNameNext->data(); 985 if (name == NULL) 986 outs() << format("?(%d)\n", r_symbolnum); 987 else 988 outs() << name << "\n"; 989 } 990 } 991 else { 992 // plain: extern & type & scattered 993 outs() << "False "; 994 PrintRType(cputype, r_type); 995 outs() << "False "; 996 997 // plain: symbolnum/value 998 if (cputype == MachO::CPU_TYPE_ARM && r_type == MachO::ARM_RELOC_PAIR) 999 outs() << format("other_half = 0x%04x\n", (unsigned int)r_address); 1000 else if ((cputype == MachO::CPU_TYPE_ARM64 || 1001 cputype == MachO::CPU_TYPE_ARM64_32) && 1002 r_type == MachO::ARM64_RELOC_ADDEND) 1003 outs() << format("addend = 0x%06x\n", (unsigned int)r_symbolnum); 1004 else { 1005 outs() << format("%d ", r_symbolnum); 1006 if (r_symbolnum == MachO::R_ABS) 1007 outs() << "R_ABS\n"; 1008 else { 1009 // in this case, r_symbolnum is actually a 1-based section number 1010 uint32_t nsects = O->section_end()->getRawDataRefImpl().d.a; 1011 if (r_symbolnum > 0 && r_symbolnum <= nsects) { 1012 object::DataRefImpl DRI; 1013 DRI.d.a = r_symbolnum-1; 1014 StringRef SegName = O->getSectionFinalSegmentName(DRI); 1015 if (Expected<StringRef> NameOrErr = O->getSectionName(DRI)) 1016 outs() << "(" << SegName << "," << *NameOrErr << ")\n"; 1017 else 1018 outs() << "(?,?)\n"; 1019 } 1020 else { 1021 outs() << "(?,?)\n"; 1022 } 1023 } 1024 } 1025 } 1026 if (cputype == MachO::CPU_TYPE_ARM && 1027 (r_type == MachO::ARM_RELOC_HALF || 1028 r_type == MachO::ARM_RELOC_HALF_SECTDIFF)) 1029 previous_arm_half = true; 1030 else 1031 previous_arm_half = false; 1032 } 1033 else { 1034 // plain: address pcrel length extern type scattered symbolnum/section 1035 outs() << format("%08x %1d %-2d %1d %-7d 0 %d\n", 1036 (unsigned int)r_address, r_pcrel, r_length, r_extern, 1037 r_type, r_symbolnum); 1038 } 1039 } 1040 } 1041 } 1042 1043 static void PrintRelocations(const MachOObjectFile *O, const bool verbose) { 1044 const uint64_t cputype = O->getHeader().cputype; 1045 const MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand(); 1046 if (Dysymtab.nextrel != 0) { 1047 outs() << "External relocation information " << Dysymtab.nextrel 1048 << " entries"; 1049 outs() << "\naddress pcrel length extern type scattered " 1050 "symbolnum/value\n"; 1051 PrintRelocationEntries(O, O->extrel_begin(), O->extrel_end(), cputype, 1052 verbose); 1053 } 1054 if (Dysymtab.nlocrel != 0) { 1055 outs() << format("Local relocation information %u entries", 1056 Dysymtab.nlocrel); 1057 outs() << "\naddress pcrel length extern type scattered " 1058 "symbolnum/value\n"; 1059 PrintRelocationEntries(O, O->locrel_begin(), O->locrel_end(), cputype, 1060 verbose); 1061 } 1062 for (const auto &Load : O->load_commands()) { 1063 if (Load.C.cmd == MachO::LC_SEGMENT_64) { 1064 const MachO::segment_command_64 Seg = O->getSegment64LoadCommand(Load); 1065 for (unsigned J = 0; J < Seg.nsects; ++J) { 1066 const MachO::section_64 Sec = O->getSection64(Load, J); 1067 if (Sec.nreloc != 0) { 1068 DataRefImpl DRI; 1069 DRI.d.a = J; 1070 const StringRef SegName = O->getSectionFinalSegmentName(DRI); 1071 if (Expected<StringRef> NameOrErr = O->getSectionName(DRI)) 1072 outs() << "Relocation information (" << SegName << "," << *NameOrErr 1073 << format(") %u entries", Sec.nreloc); 1074 else 1075 outs() << "Relocation information (" << SegName << ",?) " 1076 << format("%u entries", Sec.nreloc); 1077 outs() << "\naddress pcrel length extern type scattered " 1078 "symbolnum/value\n"; 1079 PrintRelocationEntries(O, O->section_rel_begin(DRI), 1080 O->section_rel_end(DRI), cputype, verbose); 1081 } 1082 } 1083 } else if (Load.C.cmd == MachO::LC_SEGMENT) { 1084 const MachO::segment_command Seg = O->getSegmentLoadCommand(Load); 1085 for (unsigned J = 0; J < Seg.nsects; ++J) { 1086 const MachO::section Sec = O->getSection(Load, J); 1087 if (Sec.nreloc != 0) { 1088 DataRefImpl DRI; 1089 DRI.d.a = J; 1090 const StringRef SegName = O->getSectionFinalSegmentName(DRI); 1091 if (Expected<StringRef> NameOrErr = O->getSectionName(DRI)) 1092 outs() << "Relocation information (" << SegName << "," << *NameOrErr 1093 << format(") %u entries", Sec.nreloc); 1094 else 1095 outs() << "Relocation information (" << SegName << ",?) " 1096 << format("%u entries", Sec.nreloc); 1097 outs() << "\naddress pcrel length extern type scattered " 1098 "symbolnum/value\n"; 1099 PrintRelocationEntries(O, O->section_rel_begin(DRI), 1100 O->section_rel_end(DRI), cputype, verbose); 1101 } 1102 } 1103 } 1104 } 1105 } 1106 1107 static void PrintDataInCodeTable(MachOObjectFile *O, bool verbose) { 1108 MachO::linkedit_data_command DIC = O->getDataInCodeLoadCommand(); 1109 uint32_t nentries = DIC.datasize / sizeof(struct MachO::data_in_code_entry); 1110 outs() << "Data in code table (" << nentries << " entries)\n"; 1111 outs() << "offset length kind\n"; 1112 for (dice_iterator DI = O->begin_dices(), DE = O->end_dices(); DI != DE; 1113 ++DI) { 1114 uint32_t Offset; 1115 DI->getOffset(Offset); 1116 outs() << format("0x%08" PRIx32, Offset) << " "; 1117 uint16_t Length; 1118 DI->getLength(Length); 1119 outs() << format("%6u", Length) << " "; 1120 uint16_t Kind; 1121 DI->getKind(Kind); 1122 if (verbose) { 1123 switch (Kind) { 1124 case MachO::DICE_KIND_DATA: 1125 outs() << "DATA"; 1126 break; 1127 case MachO::DICE_KIND_JUMP_TABLE8: 1128 outs() << "JUMP_TABLE8"; 1129 break; 1130 case MachO::DICE_KIND_JUMP_TABLE16: 1131 outs() << "JUMP_TABLE16"; 1132 break; 1133 case MachO::DICE_KIND_JUMP_TABLE32: 1134 outs() << "JUMP_TABLE32"; 1135 break; 1136 case MachO::DICE_KIND_ABS_JUMP_TABLE32: 1137 outs() << "ABS_JUMP_TABLE32"; 1138 break; 1139 default: 1140 outs() << format("0x%04" PRIx32, Kind); 1141 break; 1142 } 1143 } else 1144 outs() << format("0x%04" PRIx32, Kind); 1145 outs() << "\n"; 1146 } 1147 } 1148 1149 static void PrintLinkOptHints(MachOObjectFile *O) { 1150 MachO::linkedit_data_command LohLC = O->getLinkOptHintsLoadCommand(); 1151 const char *loh = O->getData().substr(LohLC.dataoff, 1).data(); 1152 uint32_t nloh = LohLC.datasize; 1153 outs() << "Linker optimiztion hints (" << nloh << " total bytes)\n"; 1154 for (uint32_t i = 0; i < nloh;) { 1155 unsigned n; 1156 uint64_t identifier = decodeULEB128((const uint8_t *)(loh + i), &n); 1157 i += n; 1158 outs() << " identifier " << identifier << " "; 1159 if (i >= nloh) 1160 return; 1161 switch (identifier) { 1162 case 1: 1163 outs() << "AdrpAdrp\n"; 1164 break; 1165 case 2: 1166 outs() << "AdrpLdr\n"; 1167 break; 1168 case 3: 1169 outs() << "AdrpAddLdr\n"; 1170 break; 1171 case 4: 1172 outs() << "AdrpLdrGotLdr\n"; 1173 break; 1174 case 5: 1175 outs() << "AdrpAddStr\n"; 1176 break; 1177 case 6: 1178 outs() << "AdrpLdrGotStr\n"; 1179 break; 1180 case 7: 1181 outs() << "AdrpAdd\n"; 1182 break; 1183 case 8: 1184 outs() << "AdrpLdrGot\n"; 1185 break; 1186 default: 1187 outs() << "Unknown identifier value\n"; 1188 break; 1189 } 1190 uint64_t narguments = decodeULEB128((const uint8_t *)(loh + i), &n); 1191 i += n; 1192 outs() << " narguments " << narguments << "\n"; 1193 if (i >= nloh) 1194 return; 1195 1196 for (uint32_t j = 0; j < narguments; j++) { 1197 uint64_t value = decodeULEB128((const uint8_t *)(loh + i), &n); 1198 i += n; 1199 outs() << "\tvalue " << format("0x%" PRIx64, value) << "\n"; 1200 if (i >= nloh) 1201 return; 1202 } 1203 } 1204 } 1205 1206 static void PrintDylibs(MachOObjectFile *O, bool JustId) { 1207 unsigned Index = 0; 1208 for (const auto &Load : O->load_commands()) { 1209 if ((JustId && Load.C.cmd == MachO::LC_ID_DYLIB) || 1210 (!JustId && (Load.C.cmd == MachO::LC_ID_DYLIB || 1211 Load.C.cmd == MachO::LC_LOAD_DYLIB || 1212 Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB || 1213 Load.C.cmd == MachO::LC_REEXPORT_DYLIB || 1214 Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB || 1215 Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB))) { 1216 MachO::dylib_command dl = O->getDylibIDLoadCommand(Load); 1217 if (dl.dylib.name < dl.cmdsize) { 1218 const char *p = (const char *)(Load.Ptr) + dl.dylib.name; 1219 if (JustId) 1220 outs() << p << "\n"; 1221 else { 1222 outs() << "\t" << p; 1223 outs() << " (compatibility version " 1224 << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "." 1225 << ((dl.dylib.compatibility_version >> 8) & 0xff) << "." 1226 << (dl.dylib.compatibility_version & 0xff) << ","; 1227 outs() << " current version " 1228 << ((dl.dylib.current_version >> 16) & 0xffff) << "." 1229 << ((dl.dylib.current_version >> 8) & 0xff) << "." 1230 << (dl.dylib.current_version & 0xff); 1231 if (Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB) 1232 outs() << ", weak"; 1233 if (Load.C.cmd == MachO::LC_REEXPORT_DYLIB) 1234 outs() << ", reexport"; 1235 if (Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB) 1236 outs() << ", upward"; 1237 if (Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB) 1238 outs() << ", lazy"; 1239 outs() << ")\n"; 1240 } 1241 } else { 1242 outs() << "\tBad offset (" << dl.dylib.name << ") for name of "; 1243 if (Load.C.cmd == MachO::LC_ID_DYLIB) 1244 outs() << "LC_ID_DYLIB "; 1245 else if (Load.C.cmd == MachO::LC_LOAD_DYLIB) 1246 outs() << "LC_LOAD_DYLIB "; 1247 else if (Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB) 1248 outs() << "LC_LOAD_WEAK_DYLIB "; 1249 else if (Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB) 1250 outs() << "LC_LAZY_LOAD_DYLIB "; 1251 else if (Load.C.cmd == MachO::LC_REEXPORT_DYLIB) 1252 outs() << "LC_REEXPORT_DYLIB "; 1253 else if (Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB) 1254 outs() << "LC_LOAD_UPWARD_DYLIB "; 1255 else 1256 outs() << "LC_??? "; 1257 outs() << "command " << Index++ << "\n"; 1258 } 1259 } 1260 } 1261 } 1262 1263 typedef DenseMap<uint64_t, StringRef> SymbolAddressMap; 1264 1265 static void CreateSymbolAddressMap(MachOObjectFile *O, 1266 SymbolAddressMap *AddrMap) { 1267 // Create a map of symbol addresses to symbol names. 1268 const StringRef FileName = O->getFileName(); 1269 for (const SymbolRef &Symbol : O->symbols()) { 1270 SymbolRef::Type ST = unwrapOrError(Symbol.getType(), FileName); 1271 if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data || 1272 ST == SymbolRef::ST_Other) { 1273 uint64_t Address = cantFail(Symbol.getValue()); 1274 StringRef SymName = unwrapOrError(Symbol.getName(), FileName); 1275 if (!SymName.startswith(".objc")) 1276 (*AddrMap)[Address] = SymName; 1277 } 1278 } 1279 } 1280 1281 // GuessSymbolName is passed the address of what might be a symbol and a 1282 // pointer to the SymbolAddressMap. It returns the name of a symbol 1283 // with that address or nullptr if no symbol is found with that address. 1284 static const char *GuessSymbolName(uint64_t value, SymbolAddressMap *AddrMap) { 1285 const char *SymbolName = nullptr; 1286 // A DenseMap can't lookup up some values. 1287 if (value != 0xffffffffffffffffULL && value != 0xfffffffffffffffeULL) { 1288 StringRef name = AddrMap->lookup(value); 1289 if (!name.empty()) 1290 SymbolName = name.data(); 1291 } 1292 return SymbolName; 1293 } 1294 1295 static void DumpCstringChar(const char c) { 1296 char p[2]; 1297 p[0] = c; 1298 p[1] = '\0'; 1299 outs().write_escaped(p); 1300 } 1301 1302 static void DumpCstringSection(MachOObjectFile *O, const char *sect, 1303 uint32_t sect_size, uint64_t sect_addr, 1304 bool print_addresses) { 1305 for (uint32_t i = 0; i < sect_size; i++) { 1306 if (print_addresses) { 1307 if (O->is64Bit()) 1308 outs() << format("%016" PRIx64, sect_addr + i) << " "; 1309 else 1310 outs() << format("%08" PRIx64, sect_addr + i) << " "; 1311 } 1312 for (; i < sect_size && sect[i] != '\0'; i++) 1313 DumpCstringChar(sect[i]); 1314 if (i < sect_size && sect[i] == '\0') 1315 outs() << "\n"; 1316 } 1317 } 1318 1319 static void DumpLiteral4(uint32_t l, float f) { 1320 outs() << format("0x%08" PRIx32, l); 1321 if ((l & 0x7f800000) != 0x7f800000) 1322 outs() << format(" (%.16e)\n", f); 1323 else { 1324 if (l == 0x7f800000) 1325 outs() << " (+Infinity)\n"; 1326 else if (l == 0xff800000) 1327 outs() << " (-Infinity)\n"; 1328 else if ((l & 0x00400000) == 0x00400000) 1329 outs() << " (non-signaling Not-a-Number)\n"; 1330 else 1331 outs() << " (signaling Not-a-Number)\n"; 1332 } 1333 } 1334 1335 static void DumpLiteral4Section(MachOObjectFile *O, const char *sect, 1336 uint32_t sect_size, uint64_t sect_addr, 1337 bool print_addresses) { 1338 for (uint32_t i = 0; i < sect_size; i += sizeof(float)) { 1339 if (print_addresses) { 1340 if (O->is64Bit()) 1341 outs() << format("%016" PRIx64, sect_addr + i) << " "; 1342 else 1343 outs() << format("%08" PRIx64, sect_addr + i) << " "; 1344 } 1345 float f; 1346 memcpy(&f, sect + i, sizeof(float)); 1347 if (O->isLittleEndian() != sys::IsLittleEndianHost) 1348 sys::swapByteOrder(f); 1349 uint32_t l; 1350 memcpy(&l, sect + i, sizeof(uint32_t)); 1351 if (O->isLittleEndian() != sys::IsLittleEndianHost) 1352 sys::swapByteOrder(l); 1353 DumpLiteral4(l, f); 1354 } 1355 } 1356 1357 static void DumpLiteral8(MachOObjectFile *O, uint32_t l0, uint32_t l1, 1358 double d) { 1359 outs() << format("0x%08" PRIx32, l0) << " " << format("0x%08" PRIx32, l1); 1360 uint32_t Hi, Lo; 1361 Hi = (O->isLittleEndian()) ? l1 : l0; 1362 Lo = (O->isLittleEndian()) ? l0 : l1; 1363 1364 // Hi is the high word, so this is equivalent to if(isfinite(d)) 1365 if ((Hi & 0x7ff00000) != 0x7ff00000) 1366 outs() << format(" (%.16e)\n", d); 1367 else { 1368 if (Hi == 0x7ff00000 && Lo == 0) 1369 outs() << " (+Infinity)\n"; 1370 else if (Hi == 0xfff00000 && Lo == 0) 1371 outs() << " (-Infinity)\n"; 1372 else if ((Hi & 0x00080000) == 0x00080000) 1373 outs() << " (non-signaling Not-a-Number)\n"; 1374 else 1375 outs() << " (signaling Not-a-Number)\n"; 1376 } 1377 } 1378 1379 static void DumpLiteral8Section(MachOObjectFile *O, const char *sect, 1380 uint32_t sect_size, uint64_t sect_addr, 1381 bool print_addresses) { 1382 for (uint32_t i = 0; i < sect_size; i += sizeof(double)) { 1383 if (print_addresses) { 1384 if (O->is64Bit()) 1385 outs() << format("%016" PRIx64, sect_addr + i) << " "; 1386 else 1387 outs() << format("%08" PRIx64, sect_addr + i) << " "; 1388 } 1389 double d; 1390 memcpy(&d, sect + i, sizeof(double)); 1391 if (O->isLittleEndian() != sys::IsLittleEndianHost) 1392 sys::swapByteOrder(d); 1393 uint32_t l0, l1; 1394 memcpy(&l0, sect + i, sizeof(uint32_t)); 1395 memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t)); 1396 if (O->isLittleEndian() != sys::IsLittleEndianHost) { 1397 sys::swapByteOrder(l0); 1398 sys::swapByteOrder(l1); 1399 } 1400 DumpLiteral8(O, l0, l1, d); 1401 } 1402 } 1403 1404 static void DumpLiteral16(uint32_t l0, uint32_t l1, uint32_t l2, uint32_t l3) { 1405 outs() << format("0x%08" PRIx32, l0) << " "; 1406 outs() << format("0x%08" PRIx32, l1) << " "; 1407 outs() << format("0x%08" PRIx32, l2) << " "; 1408 outs() << format("0x%08" PRIx32, l3) << "\n"; 1409 } 1410 1411 static void DumpLiteral16Section(MachOObjectFile *O, const char *sect, 1412 uint32_t sect_size, uint64_t sect_addr, 1413 bool print_addresses) { 1414 for (uint32_t i = 0; i < sect_size; i += 16) { 1415 if (print_addresses) { 1416 if (O->is64Bit()) 1417 outs() << format("%016" PRIx64, sect_addr + i) << " "; 1418 else 1419 outs() << format("%08" PRIx64, sect_addr + i) << " "; 1420 } 1421 uint32_t l0, l1, l2, l3; 1422 memcpy(&l0, sect + i, sizeof(uint32_t)); 1423 memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t)); 1424 memcpy(&l2, sect + i + 2 * sizeof(uint32_t), sizeof(uint32_t)); 1425 memcpy(&l3, sect + i + 3 * sizeof(uint32_t), sizeof(uint32_t)); 1426 if (O->isLittleEndian() != sys::IsLittleEndianHost) { 1427 sys::swapByteOrder(l0); 1428 sys::swapByteOrder(l1); 1429 sys::swapByteOrder(l2); 1430 sys::swapByteOrder(l3); 1431 } 1432 DumpLiteral16(l0, l1, l2, l3); 1433 } 1434 } 1435 1436 static void DumpLiteralPointerSection(MachOObjectFile *O, 1437 const SectionRef &Section, 1438 const char *sect, uint32_t sect_size, 1439 uint64_t sect_addr, 1440 bool print_addresses) { 1441 // Collect the literal sections in this Mach-O file. 1442 std::vector<SectionRef> LiteralSections; 1443 for (const SectionRef &Section : O->sections()) { 1444 DataRefImpl Ref = Section.getRawDataRefImpl(); 1445 uint32_t section_type; 1446 if (O->is64Bit()) { 1447 const MachO::section_64 Sec = O->getSection64(Ref); 1448 section_type = Sec.flags & MachO::SECTION_TYPE; 1449 } else { 1450 const MachO::section Sec = O->getSection(Ref); 1451 section_type = Sec.flags & MachO::SECTION_TYPE; 1452 } 1453 if (section_type == MachO::S_CSTRING_LITERALS || 1454 section_type == MachO::S_4BYTE_LITERALS || 1455 section_type == MachO::S_8BYTE_LITERALS || 1456 section_type == MachO::S_16BYTE_LITERALS) 1457 LiteralSections.push_back(Section); 1458 } 1459 1460 // Set the size of the literal pointer. 1461 uint32_t lp_size = O->is64Bit() ? 8 : 4; 1462 1463 // Collect the external relocation symbols for the literal pointers. 1464 std::vector<std::pair<uint64_t, SymbolRef>> Relocs; 1465 for (const RelocationRef &Reloc : Section.relocations()) { 1466 DataRefImpl Rel; 1467 MachO::any_relocation_info RE; 1468 bool isExtern = false; 1469 Rel = Reloc.getRawDataRefImpl(); 1470 RE = O->getRelocation(Rel); 1471 isExtern = O->getPlainRelocationExternal(RE); 1472 if (isExtern) { 1473 uint64_t RelocOffset = Reloc.getOffset(); 1474 symbol_iterator RelocSym = Reloc.getSymbol(); 1475 Relocs.push_back(std::make_pair(RelocOffset, *RelocSym)); 1476 } 1477 } 1478 array_pod_sort(Relocs.begin(), Relocs.end()); 1479 1480 // Dump each literal pointer. 1481 for (uint32_t i = 0; i < sect_size; i += lp_size) { 1482 if (print_addresses) { 1483 if (O->is64Bit()) 1484 outs() << format("%016" PRIx64, sect_addr + i) << " "; 1485 else 1486 outs() << format("%08" PRIx64, sect_addr + i) << " "; 1487 } 1488 uint64_t lp; 1489 if (O->is64Bit()) { 1490 memcpy(&lp, sect + i, sizeof(uint64_t)); 1491 if (O->isLittleEndian() != sys::IsLittleEndianHost) 1492 sys::swapByteOrder(lp); 1493 } else { 1494 uint32_t li; 1495 memcpy(&li, sect + i, sizeof(uint32_t)); 1496 if (O->isLittleEndian() != sys::IsLittleEndianHost) 1497 sys::swapByteOrder(li); 1498 lp = li; 1499 } 1500 1501 // First look for an external relocation entry for this literal pointer. 1502 auto Reloc = find_if(Relocs, [&](const std::pair<uint64_t, SymbolRef> &P) { 1503 return P.first == i; 1504 }); 1505 if (Reloc != Relocs.end()) { 1506 symbol_iterator RelocSym = Reloc->second; 1507 StringRef SymName = unwrapOrError(RelocSym->getName(), O->getFileName()); 1508 outs() << "external relocation entry for symbol:" << SymName << "\n"; 1509 continue; 1510 } 1511 1512 // For local references see what the section the literal pointer points to. 1513 auto Sect = find_if(LiteralSections, [&](const SectionRef &R) { 1514 return lp >= R.getAddress() && lp < R.getAddress() + R.getSize(); 1515 }); 1516 if (Sect == LiteralSections.end()) { 1517 outs() << format("0x%" PRIx64, lp) << " (not in a literal section)\n"; 1518 continue; 1519 } 1520 1521 uint64_t SectAddress = Sect->getAddress(); 1522 uint64_t SectSize = Sect->getSize(); 1523 1524 StringRef SectName; 1525 Expected<StringRef> SectNameOrErr = Sect->getName(); 1526 if (SectNameOrErr) 1527 SectName = *SectNameOrErr; 1528 else 1529 consumeError(SectNameOrErr.takeError()); 1530 1531 DataRefImpl Ref = Sect->getRawDataRefImpl(); 1532 StringRef SegmentName = O->getSectionFinalSegmentName(Ref); 1533 outs() << SegmentName << ":" << SectName << ":"; 1534 1535 uint32_t section_type; 1536 if (O->is64Bit()) { 1537 const MachO::section_64 Sec = O->getSection64(Ref); 1538 section_type = Sec.flags & MachO::SECTION_TYPE; 1539 } else { 1540 const MachO::section Sec = O->getSection(Ref); 1541 section_type = Sec.flags & MachO::SECTION_TYPE; 1542 } 1543 1544 StringRef BytesStr = unwrapOrError(Sect->getContents(), O->getFileName()); 1545 1546 const char *Contents = reinterpret_cast<const char *>(BytesStr.data()); 1547 1548 switch (section_type) { 1549 case MachO::S_CSTRING_LITERALS: 1550 for (uint64_t i = lp - SectAddress; i < SectSize && Contents[i] != '\0'; 1551 i++) { 1552 DumpCstringChar(Contents[i]); 1553 } 1554 outs() << "\n"; 1555 break; 1556 case MachO::S_4BYTE_LITERALS: 1557 float f; 1558 memcpy(&f, Contents + (lp - SectAddress), sizeof(float)); 1559 uint32_t l; 1560 memcpy(&l, Contents + (lp - SectAddress), sizeof(uint32_t)); 1561 if (O->isLittleEndian() != sys::IsLittleEndianHost) { 1562 sys::swapByteOrder(f); 1563 sys::swapByteOrder(l); 1564 } 1565 DumpLiteral4(l, f); 1566 break; 1567 case MachO::S_8BYTE_LITERALS: { 1568 double d; 1569 memcpy(&d, Contents + (lp - SectAddress), sizeof(double)); 1570 uint32_t l0, l1; 1571 memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t)); 1572 memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t), 1573 sizeof(uint32_t)); 1574 if (O->isLittleEndian() != sys::IsLittleEndianHost) { 1575 sys::swapByteOrder(f); 1576 sys::swapByteOrder(l0); 1577 sys::swapByteOrder(l1); 1578 } 1579 DumpLiteral8(O, l0, l1, d); 1580 break; 1581 } 1582 case MachO::S_16BYTE_LITERALS: { 1583 uint32_t l0, l1, l2, l3; 1584 memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t)); 1585 memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t), 1586 sizeof(uint32_t)); 1587 memcpy(&l2, Contents + (lp - SectAddress) + 2 * sizeof(uint32_t), 1588 sizeof(uint32_t)); 1589 memcpy(&l3, Contents + (lp - SectAddress) + 3 * sizeof(uint32_t), 1590 sizeof(uint32_t)); 1591 if (O->isLittleEndian() != sys::IsLittleEndianHost) { 1592 sys::swapByteOrder(l0); 1593 sys::swapByteOrder(l1); 1594 sys::swapByteOrder(l2); 1595 sys::swapByteOrder(l3); 1596 } 1597 DumpLiteral16(l0, l1, l2, l3); 1598 break; 1599 } 1600 } 1601 } 1602 } 1603 1604 static void DumpInitTermPointerSection(MachOObjectFile *O, 1605 const SectionRef &Section, 1606 const char *sect, 1607 uint32_t sect_size, uint64_t sect_addr, 1608 SymbolAddressMap *AddrMap, 1609 bool verbose) { 1610 uint32_t stride; 1611 stride = (O->is64Bit()) ? sizeof(uint64_t) : sizeof(uint32_t); 1612 1613 // Collect the external relocation symbols for the pointers. 1614 std::vector<std::pair<uint64_t, SymbolRef>> Relocs; 1615 for (const RelocationRef &Reloc : Section.relocations()) { 1616 DataRefImpl Rel; 1617 MachO::any_relocation_info RE; 1618 bool isExtern = false; 1619 Rel = Reloc.getRawDataRefImpl(); 1620 RE = O->getRelocation(Rel); 1621 isExtern = O->getPlainRelocationExternal(RE); 1622 if (isExtern) { 1623 uint64_t RelocOffset = Reloc.getOffset(); 1624 symbol_iterator RelocSym = Reloc.getSymbol(); 1625 Relocs.push_back(std::make_pair(RelocOffset, *RelocSym)); 1626 } 1627 } 1628 array_pod_sort(Relocs.begin(), Relocs.end()); 1629 1630 for (uint32_t i = 0; i < sect_size; i += stride) { 1631 const char *SymbolName = nullptr; 1632 uint64_t p; 1633 if (O->is64Bit()) { 1634 outs() << format("0x%016" PRIx64, sect_addr + i * stride) << " "; 1635 uint64_t pointer_value; 1636 memcpy(&pointer_value, sect + i, stride); 1637 if (O->isLittleEndian() != sys::IsLittleEndianHost) 1638 sys::swapByteOrder(pointer_value); 1639 outs() << format("0x%016" PRIx64, pointer_value); 1640 p = pointer_value; 1641 } else { 1642 outs() << format("0x%08" PRIx64, sect_addr + i * stride) << " "; 1643 uint32_t pointer_value; 1644 memcpy(&pointer_value, sect + i, stride); 1645 if (O->isLittleEndian() != sys::IsLittleEndianHost) 1646 sys::swapByteOrder(pointer_value); 1647 outs() << format("0x%08" PRIx32, pointer_value); 1648 p = pointer_value; 1649 } 1650 if (verbose) { 1651 // First look for an external relocation entry for this pointer. 1652 auto Reloc = find_if(Relocs, [&](const std::pair<uint64_t, SymbolRef> &P) { 1653 return P.first == i; 1654 }); 1655 if (Reloc != Relocs.end()) { 1656 symbol_iterator RelocSym = Reloc->second; 1657 outs() << " " << unwrapOrError(RelocSym->getName(), O->getFileName()); 1658 } else { 1659 SymbolName = GuessSymbolName(p, AddrMap); 1660 if (SymbolName) 1661 outs() << " " << SymbolName; 1662 } 1663 } 1664 outs() << "\n"; 1665 } 1666 } 1667 1668 static void DumpRawSectionContents(MachOObjectFile *O, const char *sect, 1669 uint32_t size, uint64_t addr) { 1670 uint32_t cputype = O->getHeader().cputype; 1671 if (cputype == MachO::CPU_TYPE_I386 || cputype == MachO::CPU_TYPE_X86_64) { 1672 uint32_t j; 1673 for (uint32_t i = 0; i < size; i += j, addr += j) { 1674 if (O->is64Bit()) 1675 outs() << format("%016" PRIx64, addr) << "\t"; 1676 else 1677 outs() << format("%08" PRIx64, addr) << "\t"; 1678 for (j = 0; j < 16 && i + j < size; j++) { 1679 uint8_t byte_word = *(sect + i + j); 1680 outs() << format("%02" PRIx32, (uint32_t)byte_word) << " "; 1681 } 1682 outs() << "\n"; 1683 } 1684 } else { 1685 uint32_t j; 1686 for (uint32_t i = 0; i < size; i += j, addr += j) { 1687 if (O->is64Bit()) 1688 outs() << format("%016" PRIx64, addr) << "\t"; 1689 else 1690 outs() << format("%08" PRIx64, addr) << "\t"; 1691 for (j = 0; j < 4 * sizeof(int32_t) && i + j < size; 1692 j += sizeof(int32_t)) { 1693 if (i + j + sizeof(int32_t) <= size) { 1694 uint32_t long_word; 1695 memcpy(&long_word, sect + i + j, sizeof(int32_t)); 1696 if (O->isLittleEndian() != sys::IsLittleEndianHost) 1697 sys::swapByteOrder(long_word); 1698 outs() << format("%08" PRIx32, long_word) << " "; 1699 } else { 1700 for (uint32_t k = 0; i + j + k < size; k++) { 1701 uint8_t byte_word = *(sect + i + j + k); 1702 outs() << format("%02" PRIx32, (uint32_t)byte_word) << " "; 1703 } 1704 } 1705 } 1706 outs() << "\n"; 1707 } 1708 } 1709 } 1710 1711 static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF, 1712 StringRef DisSegName, StringRef DisSectName); 1713 static void DumpProtocolSection(MachOObjectFile *O, const char *sect, 1714 uint32_t size, uint32_t addr); 1715 #ifdef HAVE_LIBXAR 1716 static void DumpBitcodeSection(MachOObjectFile *O, const char *sect, 1717 uint32_t size, bool verbose, 1718 bool PrintXarHeader, bool PrintXarFileHeaders, 1719 std::string XarMemberName); 1720 #endif // defined(HAVE_LIBXAR) 1721 1722 static void DumpSectionContents(StringRef Filename, MachOObjectFile *O, 1723 bool verbose) { 1724 SymbolAddressMap AddrMap; 1725 if (verbose) 1726 CreateSymbolAddressMap(O, &AddrMap); 1727 1728 for (unsigned i = 0; i < FilterSections.size(); ++i) { 1729 StringRef DumpSection = FilterSections[i]; 1730 std::pair<StringRef, StringRef> DumpSegSectName; 1731 DumpSegSectName = DumpSection.split(','); 1732 StringRef DumpSegName, DumpSectName; 1733 if (!DumpSegSectName.second.empty()) { 1734 DumpSegName = DumpSegSectName.first; 1735 DumpSectName = DumpSegSectName.second; 1736 } else { 1737 DumpSegName = ""; 1738 DumpSectName = DumpSegSectName.first; 1739 } 1740 for (const SectionRef &Section : O->sections()) { 1741 StringRef SectName; 1742 Expected<StringRef> SecNameOrErr = Section.getName(); 1743 if (SecNameOrErr) 1744 SectName = *SecNameOrErr; 1745 else 1746 consumeError(SecNameOrErr.takeError()); 1747 1748 if (!DumpSection.empty()) 1749 FoundSectionSet.insert(DumpSection); 1750 1751 DataRefImpl Ref = Section.getRawDataRefImpl(); 1752 StringRef SegName = O->getSectionFinalSegmentName(Ref); 1753 if ((DumpSegName.empty() || SegName == DumpSegName) && 1754 (SectName == DumpSectName)) { 1755 1756 uint32_t section_flags; 1757 if (O->is64Bit()) { 1758 const MachO::section_64 Sec = O->getSection64(Ref); 1759 section_flags = Sec.flags; 1760 1761 } else { 1762 const MachO::section Sec = O->getSection(Ref); 1763 section_flags = Sec.flags; 1764 } 1765 uint32_t section_type = section_flags & MachO::SECTION_TYPE; 1766 1767 StringRef BytesStr = 1768 unwrapOrError(Section.getContents(), O->getFileName()); 1769 const char *sect = reinterpret_cast<const char *>(BytesStr.data()); 1770 uint32_t sect_size = BytesStr.size(); 1771 uint64_t sect_addr = Section.getAddress(); 1772 1773 if (!NoLeadingHeaders) 1774 outs() << "Contents of (" << SegName << "," << SectName 1775 << ") section\n"; 1776 1777 if (verbose) { 1778 if ((section_flags & MachO::S_ATTR_PURE_INSTRUCTIONS) || 1779 (section_flags & MachO::S_ATTR_SOME_INSTRUCTIONS)) { 1780 DisassembleMachO(Filename, O, SegName, SectName); 1781 continue; 1782 } 1783 if (SegName == "__TEXT" && SectName == "__info_plist") { 1784 outs() << sect; 1785 continue; 1786 } 1787 if (SegName == "__OBJC" && SectName == "__protocol") { 1788 DumpProtocolSection(O, sect, sect_size, sect_addr); 1789 continue; 1790 } 1791 #ifdef HAVE_LIBXAR 1792 if (SegName == "__LLVM" && SectName == "__bundle") { 1793 DumpBitcodeSection(O, sect, sect_size, verbose, !NoSymbolicOperands, 1794 ArchiveHeaders, ""); 1795 continue; 1796 } 1797 #endif // defined(HAVE_LIBXAR) 1798 switch (section_type) { 1799 case MachO::S_REGULAR: 1800 DumpRawSectionContents(O, sect, sect_size, sect_addr); 1801 break; 1802 case MachO::S_ZEROFILL: 1803 outs() << "zerofill section and has no contents in the file\n"; 1804 break; 1805 case MachO::S_CSTRING_LITERALS: 1806 DumpCstringSection(O, sect, sect_size, sect_addr, !NoLeadingAddr); 1807 break; 1808 case MachO::S_4BYTE_LITERALS: 1809 DumpLiteral4Section(O, sect, sect_size, sect_addr, !NoLeadingAddr); 1810 break; 1811 case MachO::S_8BYTE_LITERALS: 1812 DumpLiteral8Section(O, sect, sect_size, sect_addr, !NoLeadingAddr); 1813 break; 1814 case MachO::S_16BYTE_LITERALS: 1815 DumpLiteral16Section(O, sect, sect_size, sect_addr, !NoLeadingAddr); 1816 break; 1817 case MachO::S_LITERAL_POINTERS: 1818 DumpLiteralPointerSection(O, Section, sect, sect_size, sect_addr, 1819 !NoLeadingAddr); 1820 break; 1821 case MachO::S_MOD_INIT_FUNC_POINTERS: 1822 case MachO::S_MOD_TERM_FUNC_POINTERS: 1823 DumpInitTermPointerSection(O, Section, sect, sect_size, sect_addr, 1824 &AddrMap, verbose); 1825 break; 1826 default: 1827 outs() << "Unknown section type (" 1828 << format("0x%08" PRIx32, section_type) << ")\n"; 1829 DumpRawSectionContents(O, sect, sect_size, sect_addr); 1830 break; 1831 } 1832 } else { 1833 if (section_type == MachO::S_ZEROFILL) 1834 outs() << "zerofill section and has no contents in the file\n"; 1835 else 1836 DumpRawSectionContents(O, sect, sect_size, sect_addr); 1837 } 1838 } 1839 } 1840 } 1841 } 1842 1843 static void DumpInfoPlistSectionContents(StringRef Filename, 1844 MachOObjectFile *O) { 1845 for (const SectionRef &Section : O->sections()) { 1846 StringRef SectName; 1847 Expected<StringRef> SecNameOrErr = Section.getName(); 1848 if (SecNameOrErr) 1849 SectName = *SecNameOrErr; 1850 else 1851 consumeError(SecNameOrErr.takeError()); 1852 1853 DataRefImpl Ref = Section.getRawDataRefImpl(); 1854 StringRef SegName = O->getSectionFinalSegmentName(Ref); 1855 if (SegName == "__TEXT" && SectName == "__info_plist") { 1856 if (!NoLeadingHeaders) 1857 outs() << "Contents of (" << SegName << "," << SectName << ") section\n"; 1858 StringRef BytesStr = 1859 unwrapOrError(Section.getContents(), O->getFileName()); 1860 const char *sect = reinterpret_cast<const char *>(BytesStr.data()); 1861 outs() << format("%.*s", BytesStr.size(), sect) << "\n"; 1862 return; 1863 } 1864 } 1865 } 1866 1867 // checkMachOAndArchFlags() checks to see if the ObjectFile is a Mach-O file 1868 // and if it is and there is a list of architecture flags is specified then 1869 // check to make sure this Mach-O file is one of those architectures or all 1870 // architectures were specified. If not then an error is generated and this 1871 // routine returns false. Else it returns true. 1872 static bool checkMachOAndArchFlags(ObjectFile *O, StringRef Filename) { 1873 auto *MachO = dyn_cast<MachOObjectFile>(O); 1874 1875 if (!MachO || ArchAll || ArchFlags.empty()) 1876 return true; 1877 1878 MachO::mach_header H; 1879 MachO::mach_header_64 H_64; 1880 Triple T; 1881 const char *McpuDefault, *ArchFlag; 1882 if (MachO->is64Bit()) { 1883 H_64 = MachO->MachOObjectFile::getHeader64(); 1884 T = MachOObjectFile::getArchTriple(H_64.cputype, H_64.cpusubtype, 1885 &McpuDefault, &ArchFlag); 1886 } else { 1887 H = MachO->MachOObjectFile::getHeader(); 1888 T = MachOObjectFile::getArchTriple(H.cputype, H.cpusubtype, 1889 &McpuDefault, &ArchFlag); 1890 } 1891 const std::string ArchFlagName(ArchFlag); 1892 if (none_of(ArchFlags, [&](const std::string &Name) { 1893 return Name == ArchFlagName; 1894 })) { 1895 WithColor::error(errs(), "llvm-objdump") 1896 << Filename << ": no architecture specified.\n"; 1897 return false; 1898 } 1899 return true; 1900 } 1901 1902 static void printObjcMetaData(MachOObjectFile *O, bool verbose); 1903 1904 // ProcessMachO() is passed a single opened Mach-O file, which may be an 1905 // archive member and or in a slice of a universal file. It prints the 1906 // the file name and header info and then processes it according to the 1907 // command line options. 1908 static void ProcessMachO(StringRef Name, MachOObjectFile *MachOOF, 1909 StringRef ArchiveMemberName = StringRef(), 1910 StringRef ArchitectureName = StringRef()) { 1911 // If we are doing some processing here on the Mach-O file print the header 1912 // info. And don't print it otherwise like in the case of printing the 1913 // UniversalHeaders or ArchiveHeaders. 1914 if (Disassemble || Relocations || PrivateHeaders || ExportsTrie || Rebase || 1915 Bind || SymbolTable || LazyBind || WeakBind || IndirectSymbols || 1916 DataInCode || LinkOptHints || DylibsUsed || DylibId || ObjcMetaData || 1917 (!FilterSections.empty())) { 1918 if (!NoLeadingHeaders) { 1919 outs() << Name; 1920 if (!ArchiveMemberName.empty()) 1921 outs() << '(' << ArchiveMemberName << ')'; 1922 if (!ArchitectureName.empty()) 1923 outs() << " (architecture " << ArchitectureName << ")"; 1924 outs() << ":\n"; 1925 } 1926 } 1927 // To use the report_error() form with an ArchiveName and FileName set 1928 // these up based on what is passed for Name and ArchiveMemberName. 1929 StringRef ArchiveName; 1930 StringRef FileName; 1931 if (!ArchiveMemberName.empty()) { 1932 ArchiveName = Name; 1933 FileName = ArchiveMemberName; 1934 } else { 1935 ArchiveName = StringRef(); 1936 FileName = Name; 1937 } 1938 1939 // If we need the symbol table to do the operation then check it here to 1940 // produce a good error message as to where the Mach-O file comes from in 1941 // the error message. 1942 if (Disassemble || IndirectSymbols || !FilterSections.empty() || UnwindInfo) 1943 if (Error Err = MachOOF->checkSymbolTable()) 1944 reportError(std::move(Err), FileName, ArchiveName, ArchitectureName); 1945 1946 if (DisassembleAll) { 1947 for (const SectionRef &Section : MachOOF->sections()) { 1948 StringRef SectName; 1949 if (Expected<StringRef> NameOrErr = Section.getName()) 1950 SectName = *NameOrErr; 1951 else 1952 consumeError(NameOrErr.takeError()); 1953 1954 if (SectName.equals("__text")) { 1955 DataRefImpl Ref = Section.getRawDataRefImpl(); 1956 StringRef SegName = MachOOF->getSectionFinalSegmentName(Ref); 1957 DisassembleMachO(FileName, MachOOF, SegName, SectName); 1958 } 1959 } 1960 } 1961 else if (Disassemble) { 1962 if (MachOOF->getHeader().filetype == MachO::MH_KEXT_BUNDLE && 1963 MachOOF->getHeader().cputype == MachO::CPU_TYPE_ARM64) 1964 DisassembleMachO(FileName, MachOOF, "__TEXT_EXEC", "__text"); 1965 else 1966 DisassembleMachO(FileName, MachOOF, "__TEXT", "__text"); 1967 } 1968 if (IndirectSymbols) 1969 PrintIndirectSymbols(MachOOF, !NonVerbose); 1970 if (DataInCode) 1971 PrintDataInCodeTable(MachOOF, !NonVerbose); 1972 if (LinkOptHints) 1973 PrintLinkOptHints(MachOOF); 1974 if (Relocations) 1975 PrintRelocations(MachOOF, !NonVerbose); 1976 if (SectionHeaders) 1977 printSectionHeaders(MachOOF); 1978 if (SectionContents) 1979 printSectionContents(MachOOF); 1980 if (!FilterSections.empty()) 1981 DumpSectionContents(FileName, MachOOF, !NonVerbose); 1982 if (InfoPlist) 1983 DumpInfoPlistSectionContents(FileName, MachOOF); 1984 if (DylibsUsed) 1985 PrintDylibs(MachOOF, false); 1986 if (DylibId) 1987 PrintDylibs(MachOOF, true); 1988 if (SymbolTable) 1989 printSymbolTable(MachOOF, ArchiveName, ArchitectureName); 1990 if (UnwindInfo) 1991 printMachOUnwindInfo(MachOOF); 1992 if (PrivateHeaders) { 1993 printMachOFileHeader(MachOOF); 1994 printMachOLoadCommands(MachOOF); 1995 } 1996 if (FirstPrivateHeader) 1997 printMachOFileHeader(MachOOF); 1998 if (ObjcMetaData) 1999 printObjcMetaData(MachOOF, !NonVerbose); 2000 if (ExportsTrie) 2001 printExportsTrie(MachOOF); 2002 if (Rebase) 2003 printRebaseTable(MachOOF); 2004 if (Bind) 2005 printBindTable(MachOOF); 2006 if (LazyBind) 2007 printLazyBindTable(MachOOF); 2008 if (WeakBind) 2009 printWeakBindTable(MachOOF); 2010 2011 if (DwarfDumpType != DIDT_Null) { 2012 std::unique_ptr<DIContext> DICtx = DWARFContext::create(*MachOOF); 2013 // Dump the complete DWARF structure. 2014 DIDumpOptions DumpOpts; 2015 DumpOpts.DumpType = DwarfDumpType; 2016 DICtx->dump(outs(), DumpOpts); 2017 } 2018 } 2019 2020 // printUnknownCPUType() helps print_fat_headers for unknown CPU's. 2021 static void printUnknownCPUType(uint32_t cputype, uint32_t cpusubtype) { 2022 outs() << " cputype (" << cputype << ")\n"; 2023 outs() << " cpusubtype (" << cpusubtype << ")\n"; 2024 } 2025 2026 // printCPUType() helps print_fat_headers by printing the cputype and 2027 // pusubtype (symbolically for the one's it knows about). 2028 static void printCPUType(uint32_t cputype, uint32_t cpusubtype) { 2029 switch (cputype) { 2030 case MachO::CPU_TYPE_I386: 2031 switch (cpusubtype) { 2032 case MachO::CPU_SUBTYPE_I386_ALL: 2033 outs() << " cputype CPU_TYPE_I386\n"; 2034 outs() << " cpusubtype CPU_SUBTYPE_I386_ALL\n"; 2035 break; 2036 default: 2037 printUnknownCPUType(cputype, cpusubtype); 2038 break; 2039 } 2040 break; 2041 case MachO::CPU_TYPE_X86_64: 2042 switch (cpusubtype) { 2043 case MachO::CPU_SUBTYPE_X86_64_ALL: 2044 outs() << " cputype CPU_TYPE_X86_64\n"; 2045 outs() << " cpusubtype CPU_SUBTYPE_X86_64_ALL\n"; 2046 break; 2047 case MachO::CPU_SUBTYPE_X86_64_H: 2048 outs() << " cputype CPU_TYPE_X86_64\n"; 2049 outs() << " cpusubtype CPU_SUBTYPE_X86_64_H\n"; 2050 break; 2051 default: 2052 printUnknownCPUType(cputype, cpusubtype); 2053 break; 2054 } 2055 break; 2056 case MachO::CPU_TYPE_ARM: 2057 switch (cpusubtype) { 2058 case MachO::CPU_SUBTYPE_ARM_ALL: 2059 outs() << " cputype CPU_TYPE_ARM\n"; 2060 outs() << " cpusubtype CPU_SUBTYPE_ARM_ALL\n"; 2061 break; 2062 case MachO::CPU_SUBTYPE_ARM_V4T: 2063 outs() << " cputype CPU_TYPE_ARM\n"; 2064 outs() << " cpusubtype CPU_SUBTYPE_ARM_V4T\n"; 2065 break; 2066 case MachO::CPU_SUBTYPE_ARM_V5TEJ: 2067 outs() << " cputype CPU_TYPE_ARM\n"; 2068 outs() << " cpusubtype CPU_SUBTYPE_ARM_V5TEJ\n"; 2069 break; 2070 case MachO::CPU_SUBTYPE_ARM_XSCALE: 2071 outs() << " cputype CPU_TYPE_ARM\n"; 2072 outs() << " cpusubtype CPU_SUBTYPE_ARM_XSCALE\n"; 2073 break; 2074 case MachO::CPU_SUBTYPE_ARM_V6: 2075 outs() << " cputype CPU_TYPE_ARM\n"; 2076 outs() << " cpusubtype CPU_SUBTYPE_ARM_V6\n"; 2077 break; 2078 case MachO::CPU_SUBTYPE_ARM_V6M: 2079 outs() << " cputype CPU_TYPE_ARM\n"; 2080 outs() << " cpusubtype CPU_SUBTYPE_ARM_V6M\n"; 2081 break; 2082 case MachO::CPU_SUBTYPE_ARM_V7: 2083 outs() << " cputype CPU_TYPE_ARM\n"; 2084 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7\n"; 2085 break; 2086 case MachO::CPU_SUBTYPE_ARM_V7EM: 2087 outs() << " cputype CPU_TYPE_ARM\n"; 2088 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7EM\n"; 2089 break; 2090 case MachO::CPU_SUBTYPE_ARM_V7K: 2091 outs() << " cputype CPU_TYPE_ARM\n"; 2092 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7K\n"; 2093 break; 2094 case MachO::CPU_SUBTYPE_ARM_V7M: 2095 outs() << " cputype CPU_TYPE_ARM\n"; 2096 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7M\n"; 2097 break; 2098 case MachO::CPU_SUBTYPE_ARM_V7S: 2099 outs() << " cputype CPU_TYPE_ARM\n"; 2100 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7S\n"; 2101 break; 2102 default: 2103 printUnknownCPUType(cputype, cpusubtype); 2104 break; 2105 } 2106 break; 2107 case MachO::CPU_TYPE_ARM64: 2108 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) { 2109 case MachO::CPU_SUBTYPE_ARM64_ALL: 2110 outs() << " cputype CPU_TYPE_ARM64\n"; 2111 outs() << " cpusubtype CPU_SUBTYPE_ARM64_ALL\n"; 2112 break; 2113 case MachO::CPU_SUBTYPE_ARM64_V8: 2114 outs() << " cputype CPU_TYPE_ARM64\n"; 2115 outs() << " cpusubtype CPU_SUBTYPE_ARM64_V8\n"; 2116 break; 2117 case MachO::CPU_SUBTYPE_ARM64E: 2118 outs() << " cputype CPU_TYPE_ARM64\n"; 2119 outs() << " cpusubtype CPU_SUBTYPE_ARM64E\n"; 2120 break; 2121 default: 2122 printUnknownCPUType(cputype, cpusubtype); 2123 break; 2124 } 2125 break; 2126 case MachO::CPU_TYPE_ARM64_32: 2127 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) { 2128 case MachO::CPU_SUBTYPE_ARM64_32_V8: 2129 outs() << " cputype CPU_TYPE_ARM64_32\n"; 2130 outs() << " cpusubtype CPU_SUBTYPE_ARM64_32_V8\n"; 2131 break; 2132 default: 2133 printUnknownCPUType(cputype, cpusubtype); 2134 break; 2135 } 2136 break; 2137 default: 2138 printUnknownCPUType(cputype, cpusubtype); 2139 break; 2140 } 2141 } 2142 2143 static void printMachOUniversalHeaders(const object::MachOUniversalBinary *UB, 2144 bool verbose) { 2145 outs() << "Fat headers\n"; 2146 if (verbose) { 2147 if (UB->getMagic() == MachO::FAT_MAGIC) 2148 outs() << "fat_magic FAT_MAGIC\n"; 2149 else // UB->getMagic() == MachO::FAT_MAGIC_64 2150 outs() << "fat_magic FAT_MAGIC_64\n"; 2151 } else 2152 outs() << "fat_magic " << format("0x%" PRIx32, MachO::FAT_MAGIC) << "\n"; 2153 2154 uint32_t nfat_arch = UB->getNumberOfObjects(); 2155 StringRef Buf = UB->getData(); 2156 uint64_t size = Buf.size(); 2157 uint64_t big_size = sizeof(struct MachO::fat_header) + 2158 nfat_arch * sizeof(struct MachO::fat_arch); 2159 outs() << "nfat_arch " << UB->getNumberOfObjects(); 2160 if (nfat_arch == 0) 2161 outs() << " (malformed, contains zero architecture types)\n"; 2162 else if (big_size > size) 2163 outs() << " (malformed, architectures past end of file)\n"; 2164 else 2165 outs() << "\n"; 2166 2167 for (uint32_t i = 0; i < nfat_arch; ++i) { 2168 MachOUniversalBinary::ObjectForArch OFA(UB, i); 2169 uint32_t cputype = OFA.getCPUType(); 2170 uint32_t cpusubtype = OFA.getCPUSubType(); 2171 outs() << "architecture "; 2172 for (uint32_t j = 0; i != 0 && j <= i - 1; j++) { 2173 MachOUniversalBinary::ObjectForArch other_OFA(UB, j); 2174 uint32_t other_cputype = other_OFA.getCPUType(); 2175 uint32_t other_cpusubtype = other_OFA.getCPUSubType(); 2176 if (cputype != 0 && cpusubtype != 0 && cputype == other_cputype && 2177 (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) == 2178 (other_cpusubtype & ~MachO::CPU_SUBTYPE_MASK)) { 2179 outs() << "(illegal duplicate architecture) "; 2180 break; 2181 } 2182 } 2183 if (verbose) { 2184 outs() << OFA.getArchFlagName() << "\n"; 2185 printCPUType(cputype, cpusubtype & ~MachO::CPU_SUBTYPE_MASK); 2186 } else { 2187 outs() << i << "\n"; 2188 outs() << " cputype " << cputype << "\n"; 2189 outs() << " cpusubtype " << (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) 2190 << "\n"; 2191 } 2192 if (verbose && 2193 (cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64) 2194 outs() << " capabilities CPU_SUBTYPE_LIB64\n"; 2195 else 2196 outs() << " capabilities " 2197 << format("0x%" PRIx32, 2198 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24) << "\n"; 2199 outs() << " offset " << OFA.getOffset(); 2200 if (OFA.getOffset() > size) 2201 outs() << " (past end of file)"; 2202 if (OFA.getOffset() % (1ull << OFA.getAlign()) != 0) 2203 outs() << " (not aligned on it's alignment (2^" << OFA.getAlign() << ")"; 2204 outs() << "\n"; 2205 outs() << " size " << OFA.getSize(); 2206 big_size = OFA.getOffset() + OFA.getSize(); 2207 if (big_size > size) 2208 outs() << " (past end of file)"; 2209 outs() << "\n"; 2210 outs() << " align 2^" << OFA.getAlign() << " (" << (1 << OFA.getAlign()) 2211 << ")\n"; 2212 } 2213 } 2214 2215 static void printArchiveChild(StringRef Filename, const Archive::Child &C, 2216 size_t ChildIndex, bool verbose, 2217 bool print_offset, 2218 StringRef ArchitectureName = StringRef()) { 2219 if (print_offset) 2220 outs() << C.getChildOffset() << "\t"; 2221 sys::fs::perms Mode = 2222 unwrapOrError(C.getAccessMode(), getFileNameForError(C, ChildIndex), 2223 Filename, ArchitectureName); 2224 if (verbose) { 2225 // FIXME: this first dash, "-", is for (Mode & S_IFMT) == S_IFREG. 2226 // But there is nothing in sys::fs::perms for S_IFMT or S_IFREG. 2227 outs() << "-"; 2228 outs() << ((Mode & sys::fs::owner_read) ? "r" : "-"); 2229 outs() << ((Mode & sys::fs::owner_write) ? "w" : "-"); 2230 outs() << ((Mode & sys::fs::owner_exe) ? "x" : "-"); 2231 outs() << ((Mode & sys::fs::group_read) ? "r" : "-"); 2232 outs() << ((Mode & sys::fs::group_write) ? "w" : "-"); 2233 outs() << ((Mode & sys::fs::group_exe) ? "x" : "-"); 2234 outs() << ((Mode & sys::fs::others_read) ? "r" : "-"); 2235 outs() << ((Mode & sys::fs::others_write) ? "w" : "-"); 2236 outs() << ((Mode & sys::fs::others_exe) ? "x" : "-"); 2237 } else { 2238 outs() << format("0%o ", Mode); 2239 } 2240 2241 outs() << format("%3d/%-3d %5" PRId64 " ", 2242 unwrapOrError(C.getUID(), getFileNameForError(C, ChildIndex), 2243 Filename, ArchitectureName), 2244 unwrapOrError(C.getGID(), getFileNameForError(C, ChildIndex), 2245 Filename, ArchitectureName), 2246 unwrapOrError(C.getRawSize(), 2247 getFileNameForError(C, ChildIndex), Filename, 2248 ArchitectureName)); 2249 2250 StringRef RawLastModified = C.getRawLastModified(); 2251 if (verbose) { 2252 unsigned Seconds; 2253 if (RawLastModified.getAsInteger(10, Seconds)) 2254 outs() << "(date: \"" << RawLastModified 2255 << "\" contains non-decimal chars) "; 2256 else { 2257 // Since cime(3) returns a 26 character string of the form: 2258 // "Sun Sep 16 01:03:52 1973\n\0" 2259 // just print 24 characters. 2260 time_t t = Seconds; 2261 outs() << format("%.24s ", ctime(&t)); 2262 } 2263 } else { 2264 outs() << RawLastModified << " "; 2265 } 2266 2267 if (verbose) { 2268 Expected<StringRef> NameOrErr = C.getName(); 2269 if (!NameOrErr) { 2270 consumeError(NameOrErr.takeError()); 2271 outs() << unwrapOrError(C.getRawName(), 2272 getFileNameForError(C, ChildIndex), Filename, 2273 ArchitectureName) 2274 << "\n"; 2275 } else { 2276 StringRef Name = NameOrErr.get(); 2277 outs() << Name << "\n"; 2278 } 2279 } else { 2280 outs() << unwrapOrError(C.getRawName(), getFileNameForError(C, ChildIndex), 2281 Filename, ArchitectureName) 2282 << "\n"; 2283 } 2284 } 2285 2286 static void printArchiveHeaders(StringRef Filename, Archive *A, bool verbose, 2287 bool print_offset, 2288 StringRef ArchitectureName = StringRef()) { 2289 Error Err = Error::success(); 2290 size_t I = 0; 2291 for (const auto &C : A->children(Err, false)) 2292 printArchiveChild(Filename, C, I++, verbose, print_offset, 2293 ArchitectureName); 2294 2295 if (Err) 2296 reportError(std::move(Err), Filename, "", ArchitectureName); 2297 } 2298 2299 static bool ValidateArchFlags() { 2300 // Check for -arch all and verifiy the -arch flags are valid. 2301 for (unsigned i = 0; i < ArchFlags.size(); ++i) { 2302 if (ArchFlags[i] == "all") { 2303 ArchAll = true; 2304 } else { 2305 if (!MachOObjectFile::isValidArch(ArchFlags[i])) { 2306 WithColor::error(errs(), "llvm-objdump") 2307 << "unknown architecture named '" + ArchFlags[i] + 2308 "'for the -arch option\n"; 2309 return false; 2310 } 2311 } 2312 } 2313 return true; 2314 } 2315 2316 // ParseInputMachO() parses the named Mach-O file in Filename and handles the 2317 // -arch flags selecting just those slices as specified by them and also parses 2318 // archive files. Then for each individual Mach-O file ProcessMachO() is 2319 // called to process the file based on the command line options. 2320 void objdump::parseInputMachO(StringRef Filename) { 2321 if (!ValidateArchFlags()) 2322 return; 2323 2324 // Attempt to open the binary. 2325 Expected<OwningBinary<Binary>> BinaryOrErr = createBinary(Filename); 2326 if (!BinaryOrErr) { 2327 if (Error E = isNotObjectErrorInvalidFileType(BinaryOrErr.takeError())) 2328 reportError(std::move(E), Filename); 2329 else 2330 outs() << Filename << ": is not an object file\n"; 2331 return; 2332 } 2333 Binary &Bin = *BinaryOrErr.get().getBinary(); 2334 2335 if (Archive *A = dyn_cast<Archive>(&Bin)) { 2336 outs() << "Archive : " << Filename << "\n"; 2337 if (ArchiveHeaders) 2338 printArchiveHeaders(Filename, A, !NonVerbose, ArchiveMemberOffsets); 2339 2340 Error Err = Error::success(); 2341 unsigned I = -1; 2342 for (auto &C : A->children(Err)) { 2343 ++I; 2344 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary(); 2345 if (!ChildOrErr) { 2346 if (Error E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError())) 2347 reportError(std::move(E), getFileNameForError(C, I), Filename); 2348 continue; 2349 } 2350 if (MachOObjectFile *O = dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) { 2351 if (!checkMachOAndArchFlags(O, Filename)) 2352 return; 2353 ProcessMachO(Filename, O, O->getFileName()); 2354 } 2355 } 2356 if (Err) 2357 reportError(std::move(Err), Filename); 2358 return; 2359 } 2360 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin)) { 2361 parseInputMachO(UB); 2362 return; 2363 } 2364 if (ObjectFile *O = dyn_cast<ObjectFile>(&Bin)) { 2365 if (!checkMachOAndArchFlags(O, Filename)) 2366 return; 2367 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&*O)) 2368 ProcessMachO(Filename, MachOOF); 2369 else 2370 WithColor::error(errs(), "llvm-objdump") 2371 << Filename << "': " 2372 << "object is not a Mach-O file type.\n"; 2373 return; 2374 } 2375 llvm_unreachable("Input object can't be invalid at this point"); 2376 } 2377 2378 void objdump::parseInputMachO(MachOUniversalBinary *UB) { 2379 if (!ValidateArchFlags()) 2380 return; 2381 2382 auto Filename = UB->getFileName(); 2383 2384 if (UniversalHeaders) 2385 printMachOUniversalHeaders(UB, !NonVerbose); 2386 2387 // If we have a list of architecture flags specified dump only those. 2388 if (!ArchAll && !ArchFlags.empty()) { 2389 // Look for a slice in the universal binary that matches each ArchFlag. 2390 bool ArchFound; 2391 for (unsigned i = 0; i < ArchFlags.size(); ++i) { 2392 ArchFound = false; 2393 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(), 2394 E = UB->end_objects(); 2395 I != E; ++I) { 2396 if (ArchFlags[i] == I->getArchFlagName()) { 2397 ArchFound = true; 2398 Expected<std::unique_ptr<ObjectFile>> ObjOrErr = 2399 I->getAsObjectFile(); 2400 std::string ArchitectureName = ""; 2401 if (ArchFlags.size() > 1) 2402 ArchitectureName = I->getArchFlagName(); 2403 if (ObjOrErr) { 2404 ObjectFile &O = *ObjOrErr.get(); 2405 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O)) 2406 ProcessMachO(Filename, MachOOF, "", ArchitectureName); 2407 } else if (Error E = isNotObjectErrorInvalidFileType( 2408 ObjOrErr.takeError())) { 2409 reportError(std::move(E), "", Filename, ArchitectureName); 2410 continue; 2411 } else if (Expected<std::unique_ptr<Archive>> AOrErr = 2412 I->getAsArchive()) { 2413 std::unique_ptr<Archive> &A = *AOrErr; 2414 outs() << "Archive : " << Filename; 2415 if (!ArchitectureName.empty()) 2416 outs() << " (architecture " << ArchitectureName << ")"; 2417 outs() << "\n"; 2418 if (ArchiveHeaders) 2419 printArchiveHeaders(Filename, A.get(), !NonVerbose, 2420 ArchiveMemberOffsets, ArchitectureName); 2421 Error Err = Error::success(); 2422 unsigned I = -1; 2423 for (auto &C : A->children(Err)) { 2424 ++I; 2425 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary(); 2426 if (!ChildOrErr) { 2427 if (Error E = 2428 isNotObjectErrorInvalidFileType(ChildOrErr.takeError())) 2429 reportError(std::move(E), getFileNameForError(C, I), Filename, 2430 ArchitectureName); 2431 continue; 2432 } 2433 if (MachOObjectFile *O = 2434 dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) 2435 ProcessMachO(Filename, O, O->getFileName(), ArchitectureName); 2436 } 2437 if (Err) 2438 reportError(std::move(Err), Filename); 2439 } else { 2440 consumeError(AOrErr.takeError()); 2441 reportError(Filename, 2442 "Mach-O universal file for architecture " + 2443 StringRef(I->getArchFlagName()) + 2444 " is not a Mach-O file or an archive file"); 2445 } 2446 } 2447 } 2448 if (!ArchFound) { 2449 WithColor::error(errs(), "llvm-objdump") 2450 << "file: " + Filename + " does not contain " 2451 << "architecture: " + ArchFlags[i] + "\n"; 2452 return; 2453 } 2454 } 2455 return; 2456 } 2457 // No architecture flags were specified so if this contains a slice that 2458 // matches the host architecture dump only that. 2459 if (!ArchAll) { 2460 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(), 2461 E = UB->end_objects(); 2462 I != E; ++I) { 2463 if (MachOObjectFile::getHostArch().getArchName() == 2464 I->getArchFlagName()) { 2465 Expected<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile(); 2466 std::string ArchiveName; 2467 ArchiveName.clear(); 2468 if (ObjOrErr) { 2469 ObjectFile &O = *ObjOrErr.get(); 2470 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O)) 2471 ProcessMachO(Filename, MachOOF); 2472 } else if (Error E = 2473 isNotObjectErrorInvalidFileType(ObjOrErr.takeError())) { 2474 reportError(std::move(E), Filename); 2475 } else if (Expected<std::unique_ptr<Archive>> AOrErr = 2476 I->getAsArchive()) { 2477 std::unique_ptr<Archive> &A = *AOrErr; 2478 outs() << "Archive : " << Filename << "\n"; 2479 if (ArchiveHeaders) 2480 printArchiveHeaders(Filename, A.get(), !NonVerbose, 2481 ArchiveMemberOffsets); 2482 Error Err = Error::success(); 2483 unsigned I = -1; 2484 for (auto &C : A->children(Err)) { 2485 ++I; 2486 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary(); 2487 if (!ChildOrErr) { 2488 if (Error E = 2489 isNotObjectErrorInvalidFileType(ChildOrErr.takeError())) 2490 reportError(std::move(E), getFileNameForError(C, I), Filename); 2491 continue; 2492 } 2493 if (MachOObjectFile *O = 2494 dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) 2495 ProcessMachO(Filename, O, O->getFileName()); 2496 } 2497 if (Err) 2498 reportError(std::move(Err), Filename); 2499 } else { 2500 consumeError(AOrErr.takeError()); 2501 reportError(Filename, "Mach-O universal file for architecture " + 2502 StringRef(I->getArchFlagName()) + 2503 " is not a Mach-O file or an archive file"); 2504 } 2505 return; 2506 } 2507 } 2508 } 2509 // Either all architectures have been specified or none have been specified 2510 // and this does not contain the host architecture so dump all the slices. 2511 bool moreThanOneArch = UB->getNumberOfObjects() > 1; 2512 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(), 2513 E = UB->end_objects(); 2514 I != E; ++I) { 2515 Expected<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile(); 2516 std::string ArchitectureName = ""; 2517 if (moreThanOneArch) 2518 ArchitectureName = I->getArchFlagName(); 2519 if (ObjOrErr) { 2520 ObjectFile &Obj = *ObjOrErr.get(); 2521 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&Obj)) 2522 ProcessMachO(Filename, MachOOF, "", ArchitectureName); 2523 } else if (Error E = 2524 isNotObjectErrorInvalidFileType(ObjOrErr.takeError())) { 2525 reportError(std::move(E), Filename, "", ArchitectureName); 2526 } else if (Expected<std::unique_ptr<Archive>> AOrErr = I->getAsArchive()) { 2527 std::unique_ptr<Archive> &A = *AOrErr; 2528 outs() << "Archive : " << Filename; 2529 if (!ArchitectureName.empty()) 2530 outs() << " (architecture " << ArchitectureName << ")"; 2531 outs() << "\n"; 2532 if (ArchiveHeaders) 2533 printArchiveHeaders(Filename, A.get(), !NonVerbose, 2534 ArchiveMemberOffsets, ArchitectureName); 2535 Error Err = Error::success(); 2536 unsigned I = -1; 2537 for (auto &C : A->children(Err)) { 2538 ++I; 2539 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary(); 2540 if (!ChildOrErr) { 2541 if (Error E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError())) 2542 reportError(std::move(E), getFileNameForError(C, I), Filename, 2543 ArchitectureName); 2544 continue; 2545 } 2546 if (MachOObjectFile *O = 2547 dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) { 2548 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(O)) 2549 ProcessMachO(Filename, MachOOF, MachOOF->getFileName(), 2550 ArchitectureName); 2551 } 2552 } 2553 if (Err) 2554 reportError(std::move(Err), Filename); 2555 } else { 2556 consumeError(AOrErr.takeError()); 2557 reportError(Filename, "Mach-O universal file for architecture " + 2558 StringRef(I->getArchFlagName()) + 2559 " is not a Mach-O file or an archive file"); 2560 } 2561 } 2562 } 2563 2564 namespace { 2565 // The block of info used by the Symbolizer call backs. 2566 struct DisassembleInfo { 2567 DisassembleInfo(MachOObjectFile *O, SymbolAddressMap *AddrMap, 2568 std::vector<SectionRef> *Sections, bool verbose) 2569 : verbose(verbose), O(O), AddrMap(AddrMap), Sections(Sections) {} 2570 bool verbose; 2571 MachOObjectFile *O; 2572 SectionRef S; 2573 SymbolAddressMap *AddrMap; 2574 std::vector<SectionRef> *Sections; 2575 const char *class_name = nullptr; 2576 const char *selector_name = nullptr; 2577 std::unique_ptr<char[]> method = nullptr; 2578 char *demangled_name = nullptr; 2579 uint64_t adrp_addr = 0; 2580 uint32_t adrp_inst = 0; 2581 std::unique_ptr<SymbolAddressMap> bindtable; 2582 uint32_t depth = 0; 2583 }; 2584 } // namespace 2585 2586 // SymbolizerGetOpInfo() is the operand information call back function. 2587 // This is called to get the symbolic information for operand(s) of an 2588 // instruction when it is being done. This routine does this from 2589 // the relocation information, symbol table, etc. That block of information 2590 // is a pointer to the struct DisassembleInfo that was passed when the 2591 // disassembler context was created and passed to back to here when 2592 // called back by the disassembler for instruction operands that could have 2593 // relocation information. The address of the instruction containing operand is 2594 // at the Pc parameter. The immediate value the operand has is passed in 2595 // op_info->Value and is at Offset past the start of the instruction and has a 2596 // byte Size of 1, 2 or 4. The symbolc information is returned in TagBuf is the 2597 // LLVMOpInfo1 struct defined in the header "llvm-c/Disassembler.h" as symbol 2598 // names and addends of the symbolic expression to add for the operand. The 2599 // value of TagType is currently 1 (for the LLVMOpInfo1 struct). If symbolic 2600 // information is returned then this function returns 1 else it returns 0. 2601 static int SymbolizerGetOpInfo(void *DisInfo, uint64_t Pc, uint64_t Offset, 2602 uint64_t Size, int TagType, void *TagBuf) { 2603 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo; 2604 struct LLVMOpInfo1 *op_info = (struct LLVMOpInfo1 *)TagBuf; 2605 uint64_t value = op_info->Value; 2606 2607 // Make sure all fields returned are zero if we don't set them. 2608 memset((void *)op_info, '\0', sizeof(struct LLVMOpInfo1)); 2609 op_info->Value = value; 2610 2611 // If the TagType is not the value 1 which it code knows about or if no 2612 // verbose symbolic information is wanted then just return 0, indicating no 2613 // information is being returned. 2614 if (TagType != 1 || !info->verbose) 2615 return 0; 2616 2617 unsigned int Arch = info->O->getArch(); 2618 if (Arch == Triple::x86) { 2619 if (Size != 1 && Size != 2 && Size != 4 && Size != 0) 2620 return 0; 2621 if (info->O->getHeader().filetype != MachO::MH_OBJECT) { 2622 // TODO: 2623 // Search the external relocation entries of a fully linked image 2624 // (if any) for an entry that matches this segment offset. 2625 // uint32_t seg_offset = (Pc + Offset); 2626 return 0; 2627 } 2628 // In MH_OBJECT filetypes search the section's relocation entries (if any) 2629 // for an entry for this section offset. 2630 uint32_t sect_addr = info->S.getAddress(); 2631 uint32_t sect_offset = (Pc + Offset) - sect_addr; 2632 bool reloc_found = false; 2633 DataRefImpl Rel; 2634 MachO::any_relocation_info RE; 2635 bool isExtern = false; 2636 SymbolRef Symbol; 2637 bool r_scattered = false; 2638 uint32_t r_value, pair_r_value, r_type; 2639 for (const RelocationRef &Reloc : info->S.relocations()) { 2640 uint64_t RelocOffset = Reloc.getOffset(); 2641 if (RelocOffset == sect_offset) { 2642 Rel = Reloc.getRawDataRefImpl(); 2643 RE = info->O->getRelocation(Rel); 2644 r_type = info->O->getAnyRelocationType(RE); 2645 r_scattered = info->O->isRelocationScattered(RE); 2646 if (r_scattered) { 2647 r_value = info->O->getScatteredRelocationValue(RE); 2648 if (r_type == MachO::GENERIC_RELOC_SECTDIFF || 2649 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF) { 2650 DataRefImpl RelNext = Rel; 2651 info->O->moveRelocationNext(RelNext); 2652 MachO::any_relocation_info RENext; 2653 RENext = info->O->getRelocation(RelNext); 2654 if (info->O->isRelocationScattered(RENext)) 2655 pair_r_value = info->O->getScatteredRelocationValue(RENext); 2656 else 2657 return 0; 2658 } 2659 } else { 2660 isExtern = info->O->getPlainRelocationExternal(RE); 2661 if (isExtern) { 2662 symbol_iterator RelocSym = Reloc.getSymbol(); 2663 Symbol = *RelocSym; 2664 } 2665 } 2666 reloc_found = true; 2667 break; 2668 } 2669 } 2670 if (reloc_found && isExtern) { 2671 op_info->AddSymbol.Present = 1; 2672 op_info->AddSymbol.Name = 2673 unwrapOrError(Symbol.getName(), info->O->getFileName()).data(); 2674 // For i386 extern relocation entries the value in the instruction is 2675 // the offset from the symbol, and value is already set in op_info->Value. 2676 return 1; 2677 } 2678 if (reloc_found && (r_type == MachO::GENERIC_RELOC_SECTDIFF || 2679 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF)) { 2680 const char *add = GuessSymbolName(r_value, info->AddrMap); 2681 const char *sub = GuessSymbolName(pair_r_value, info->AddrMap); 2682 uint32_t offset = value - (r_value - pair_r_value); 2683 op_info->AddSymbol.Present = 1; 2684 if (add != nullptr) 2685 op_info->AddSymbol.Name = add; 2686 else 2687 op_info->AddSymbol.Value = r_value; 2688 op_info->SubtractSymbol.Present = 1; 2689 if (sub != nullptr) 2690 op_info->SubtractSymbol.Name = sub; 2691 else 2692 op_info->SubtractSymbol.Value = pair_r_value; 2693 op_info->Value = offset; 2694 return 1; 2695 } 2696 return 0; 2697 } 2698 if (Arch == Triple::x86_64) { 2699 if (Size != 1 && Size != 2 && Size != 4 && Size != 0) 2700 return 0; 2701 // For non MH_OBJECT types, like MH_KEXT_BUNDLE, Search the external 2702 // relocation entries of a linked image (if any) for an entry that matches 2703 // this segment offset. 2704 if (info->O->getHeader().filetype != MachO::MH_OBJECT) { 2705 uint64_t seg_offset = Pc + Offset; 2706 bool reloc_found = false; 2707 DataRefImpl Rel; 2708 MachO::any_relocation_info RE; 2709 bool isExtern = false; 2710 SymbolRef Symbol; 2711 for (const RelocationRef &Reloc : info->O->external_relocations()) { 2712 uint64_t RelocOffset = Reloc.getOffset(); 2713 if (RelocOffset == seg_offset) { 2714 Rel = Reloc.getRawDataRefImpl(); 2715 RE = info->O->getRelocation(Rel); 2716 // external relocation entries should always be external. 2717 isExtern = info->O->getPlainRelocationExternal(RE); 2718 if (isExtern) { 2719 symbol_iterator RelocSym = Reloc.getSymbol(); 2720 Symbol = *RelocSym; 2721 } 2722 reloc_found = true; 2723 break; 2724 } 2725 } 2726 if (reloc_found && isExtern) { 2727 // The Value passed in will be adjusted by the Pc if the instruction 2728 // adds the Pc. But for x86_64 external relocation entries the Value 2729 // is the offset from the external symbol. 2730 if (info->O->getAnyRelocationPCRel(RE)) 2731 op_info->Value -= Pc + Offset + Size; 2732 const char *name = 2733 unwrapOrError(Symbol.getName(), info->O->getFileName()).data(); 2734 op_info->AddSymbol.Present = 1; 2735 op_info->AddSymbol.Name = name; 2736 return 1; 2737 } 2738 return 0; 2739 } 2740 // In MH_OBJECT filetypes search the section's relocation entries (if any) 2741 // for an entry for this section offset. 2742 uint64_t sect_addr = info->S.getAddress(); 2743 uint64_t sect_offset = (Pc + Offset) - sect_addr; 2744 bool reloc_found = false; 2745 DataRefImpl Rel; 2746 MachO::any_relocation_info RE; 2747 bool isExtern = false; 2748 SymbolRef Symbol; 2749 for (const RelocationRef &Reloc : info->S.relocations()) { 2750 uint64_t RelocOffset = Reloc.getOffset(); 2751 if (RelocOffset == sect_offset) { 2752 Rel = Reloc.getRawDataRefImpl(); 2753 RE = info->O->getRelocation(Rel); 2754 // NOTE: Scattered relocations don't exist on x86_64. 2755 isExtern = info->O->getPlainRelocationExternal(RE); 2756 if (isExtern) { 2757 symbol_iterator RelocSym = Reloc.getSymbol(); 2758 Symbol = *RelocSym; 2759 } 2760 reloc_found = true; 2761 break; 2762 } 2763 } 2764 if (reloc_found && isExtern) { 2765 // The Value passed in will be adjusted by the Pc if the instruction 2766 // adds the Pc. But for x86_64 external relocation entries the Value 2767 // is the offset from the external symbol. 2768 if (info->O->getAnyRelocationPCRel(RE)) 2769 op_info->Value -= Pc + Offset + Size; 2770 const char *name = 2771 unwrapOrError(Symbol.getName(), info->O->getFileName()).data(); 2772 unsigned Type = info->O->getAnyRelocationType(RE); 2773 if (Type == MachO::X86_64_RELOC_SUBTRACTOR) { 2774 DataRefImpl RelNext = Rel; 2775 info->O->moveRelocationNext(RelNext); 2776 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext); 2777 unsigned TypeNext = info->O->getAnyRelocationType(RENext); 2778 bool isExternNext = info->O->getPlainRelocationExternal(RENext); 2779 unsigned SymbolNum = info->O->getPlainRelocationSymbolNum(RENext); 2780 if (TypeNext == MachO::X86_64_RELOC_UNSIGNED && isExternNext) { 2781 op_info->SubtractSymbol.Present = 1; 2782 op_info->SubtractSymbol.Name = name; 2783 symbol_iterator RelocSymNext = info->O->getSymbolByIndex(SymbolNum); 2784 Symbol = *RelocSymNext; 2785 name = unwrapOrError(Symbol.getName(), info->O->getFileName()).data(); 2786 } 2787 } 2788 // TODO: add the VariantKinds to op_info->VariantKind for relocation types 2789 // like: X86_64_RELOC_TLV, X86_64_RELOC_GOT_LOAD and X86_64_RELOC_GOT. 2790 op_info->AddSymbol.Present = 1; 2791 op_info->AddSymbol.Name = name; 2792 return 1; 2793 } 2794 return 0; 2795 } 2796 if (Arch == Triple::arm) { 2797 if (Offset != 0 || (Size != 4 && Size != 2)) 2798 return 0; 2799 if (info->O->getHeader().filetype != MachO::MH_OBJECT) { 2800 // TODO: 2801 // Search the external relocation entries of a fully linked image 2802 // (if any) for an entry that matches this segment offset. 2803 // uint32_t seg_offset = (Pc + Offset); 2804 return 0; 2805 } 2806 // In MH_OBJECT filetypes search the section's relocation entries (if any) 2807 // for an entry for this section offset. 2808 uint32_t sect_addr = info->S.getAddress(); 2809 uint32_t sect_offset = (Pc + Offset) - sect_addr; 2810 DataRefImpl Rel; 2811 MachO::any_relocation_info RE; 2812 bool isExtern = false; 2813 SymbolRef Symbol; 2814 bool r_scattered = false; 2815 uint32_t r_value, pair_r_value, r_type, r_length, other_half; 2816 auto Reloc = 2817 find_if(info->S.relocations(), [&](const RelocationRef &Reloc) { 2818 uint64_t RelocOffset = Reloc.getOffset(); 2819 return RelocOffset == sect_offset; 2820 }); 2821 2822 if (Reloc == info->S.relocations().end()) 2823 return 0; 2824 2825 Rel = Reloc->getRawDataRefImpl(); 2826 RE = info->O->getRelocation(Rel); 2827 r_length = info->O->getAnyRelocationLength(RE); 2828 r_scattered = info->O->isRelocationScattered(RE); 2829 if (r_scattered) { 2830 r_value = info->O->getScatteredRelocationValue(RE); 2831 r_type = info->O->getScatteredRelocationType(RE); 2832 } else { 2833 r_type = info->O->getAnyRelocationType(RE); 2834 isExtern = info->O->getPlainRelocationExternal(RE); 2835 if (isExtern) { 2836 symbol_iterator RelocSym = Reloc->getSymbol(); 2837 Symbol = *RelocSym; 2838 } 2839 } 2840 if (r_type == MachO::ARM_RELOC_HALF || 2841 r_type == MachO::ARM_RELOC_SECTDIFF || 2842 r_type == MachO::ARM_RELOC_LOCAL_SECTDIFF || 2843 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) { 2844 DataRefImpl RelNext = Rel; 2845 info->O->moveRelocationNext(RelNext); 2846 MachO::any_relocation_info RENext; 2847 RENext = info->O->getRelocation(RelNext); 2848 other_half = info->O->getAnyRelocationAddress(RENext) & 0xffff; 2849 if (info->O->isRelocationScattered(RENext)) 2850 pair_r_value = info->O->getScatteredRelocationValue(RENext); 2851 } 2852 2853 if (isExtern) { 2854 const char *name = 2855 unwrapOrError(Symbol.getName(), info->O->getFileName()).data(); 2856 op_info->AddSymbol.Present = 1; 2857 op_info->AddSymbol.Name = name; 2858 switch (r_type) { 2859 case MachO::ARM_RELOC_HALF: 2860 if ((r_length & 0x1) == 1) { 2861 op_info->Value = value << 16 | other_half; 2862 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16; 2863 } else { 2864 op_info->Value = other_half << 16 | value; 2865 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16; 2866 } 2867 break; 2868 default: 2869 break; 2870 } 2871 return 1; 2872 } 2873 // If we have a branch that is not an external relocation entry then 2874 // return 0 so the code in tryAddingSymbolicOperand() can use the 2875 // SymbolLookUp call back with the branch target address to look up the 2876 // symbol and possibility add an annotation for a symbol stub. 2877 if (isExtern == 0 && (r_type == MachO::ARM_RELOC_BR24 || 2878 r_type == MachO::ARM_THUMB_RELOC_BR22)) 2879 return 0; 2880 2881 uint32_t offset = 0; 2882 if (r_type == MachO::ARM_RELOC_HALF || 2883 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) { 2884 if ((r_length & 0x1) == 1) 2885 value = value << 16 | other_half; 2886 else 2887 value = other_half << 16 | value; 2888 } 2889 if (r_scattered && (r_type != MachO::ARM_RELOC_HALF && 2890 r_type != MachO::ARM_RELOC_HALF_SECTDIFF)) { 2891 offset = value - r_value; 2892 value = r_value; 2893 } 2894 2895 if (r_type == MachO::ARM_RELOC_HALF_SECTDIFF) { 2896 if ((r_length & 0x1) == 1) 2897 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16; 2898 else 2899 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16; 2900 const char *add = GuessSymbolName(r_value, info->AddrMap); 2901 const char *sub = GuessSymbolName(pair_r_value, info->AddrMap); 2902 int32_t offset = value - (r_value - pair_r_value); 2903 op_info->AddSymbol.Present = 1; 2904 if (add != nullptr) 2905 op_info->AddSymbol.Name = add; 2906 else 2907 op_info->AddSymbol.Value = r_value; 2908 op_info->SubtractSymbol.Present = 1; 2909 if (sub != nullptr) 2910 op_info->SubtractSymbol.Name = sub; 2911 else 2912 op_info->SubtractSymbol.Value = pair_r_value; 2913 op_info->Value = offset; 2914 return 1; 2915 } 2916 2917 op_info->AddSymbol.Present = 1; 2918 op_info->Value = offset; 2919 if (r_type == MachO::ARM_RELOC_HALF) { 2920 if ((r_length & 0x1) == 1) 2921 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16; 2922 else 2923 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16; 2924 } 2925 const char *add = GuessSymbolName(value, info->AddrMap); 2926 if (add != nullptr) { 2927 op_info->AddSymbol.Name = add; 2928 return 1; 2929 } 2930 op_info->AddSymbol.Value = value; 2931 return 1; 2932 } 2933 if (Arch == Triple::aarch64) { 2934 if (Offset != 0 || Size != 4) 2935 return 0; 2936 if (info->O->getHeader().filetype != MachO::MH_OBJECT) { 2937 // TODO: 2938 // Search the external relocation entries of a fully linked image 2939 // (if any) for an entry that matches this segment offset. 2940 // uint64_t seg_offset = (Pc + Offset); 2941 return 0; 2942 } 2943 // In MH_OBJECT filetypes search the section's relocation entries (if any) 2944 // for an entry for this section offset. 2945 uint64_t sect_addr = info->S.getAddress(); 2946 uint64_t sect_offset = (Pc + Offset) - sect_addr; 2947 auto Reloc = 2948 find_if(info->S.relocations(), [&](const RelocationRef &Reloc) { 2949 uint64_t RelocOffset = Reloc.getOffset(); 2950 return RelocOffset == sect_offset; 2951 }); 2952 2953 if (Reloc == info->S.relocations().end()) 2954 return 0; 2955 2956 DataRefImpl Rel = Reloc->getRawDataRefImpl(); 2957 MachO::any_relocation_info RE = info->O->getRelocation(Rel); 2958 uint32_t r_type = info->O->getAnyRelocationType(RE); 2959 if (r_type == MachO::ARM64_RELOC_ADDEND) { 2960 DataRefImpl RelNext = Rel; 2961 info->O->moveRelocationNext(RelNext); 2962 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext); 2963 if (value == 0) { 2964 value = info->O->getPlainRelocationSymbolNum(RENext); 2965 op_info->Value = value; 2966 } 2967 } 2968 // NOTE: Scattered relocations don't exist on arm64. 2969 if (!info->O->getPlainRelocationExternal(RE)) 2970 return 0; 2971 const char *name = 2972 unwrapOrError(Reloc->getSymbol()->getName(), info->O->getFileName()) 2973 .data(); 2974 op_info->AddSymbol.Present = 1; 2975 op_info->AddSymbol.Name = name; 2976 2977 switch (r_type) { 2978 case MachO::ARM64_RELOC_PAGE21: 2979 /* @page */ 2980 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGE; 2981 break; 2982 case MachO::ARM64_RELOC_PAGEOFF12: 2983 /* @pageoff */ 2984 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGEOFF; 2985 break; 2986 case MachO::ARM64_RELOC_GOT_LOAD_PAGE21: 2987 /* @gotpage */ 2988 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGE; 2989 break; 2990 case MachO::ARM64_RELOC_GOT_LOAD_PAGEOFF12: 2991 /* @gotpageoff */ 2992 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGEOFF; 2993 break; 2994 case MachO::ARM64_RELOC_TLVP_LOAD_PAGE21: 2995 /* @tvlppage is not implemented in llvm-mc */ 2996 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVP; 2997 break; 2998 case MachO::ARM64_RELOC_TLVP_LOAD_PAGEOFF12: 2999 /* @tvlppageoff is not implemented in llvm-mc */ 3000 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVOFF; 3001 break; 3002 default: 3003 case MachO::ARM64_RELOC_BRANCH26: 3004 op_info->VariantKind = LLVMDisassembler_VariantKind_None; 3005 break; 3006 } 3007 return 1; 3008 } 3009 return 0; 3010 } 3011 3012 // GuessCstringPointer is passed the address of what might be a pointer to a 3013 // literal string in a cstring section. If that address is in a cstring section 3014 // it returns a pointer to that string. Else it returns nullptr. 3015 static const char *GuessCstringPointer(uint64_t ReferenceValue, 3016 struct DisassembleInfo *info) { 3017 for (const auto &Load : info->O->load_commands()) { 3018 if (Load.C.cmd == MachO::LC_SEGMENT_64) { 3019 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load); 3020 for (unsigned J = 0; J < Seg.nsects; ++J) { 3021 MachO::section_64 Sec = info->O->getSection64(Load, J); 3022 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE; 3023 if (section_type == MachO::S_CSTRING_LITERALS && 3024 ReferenceValue >= Sec.addr && 3025 ReferenceValue < Sec.addr + Sec.size) { 3026 uint64_t sect_offset = ReferenceValue - Sec.addr; 3027 uint64_t object_offset = Sec.offset + sect_offset; 3028 StringRef MachOContents = info->O->getData(); 3029 uint64_t object_size = MachOContents.size(); 3030 const char *object_addr = (const char *)MachOContents.data(); 3031 if (object_offset < object_size) { 3032 const char *name = object_addr + object_offset; 3033 return name; 3034 } else { 3035 return nullptr; 3036 } 3037 } 3038 } 3039 } else if (Load.C.cmd == MachO::LC_SEGMENT) { 3040 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load); 3041 for (unsigned J = 0; J < Seg.nsects; ++J) { 3042 MachO::section Sec = info->O->getSection(Load, J); 3043 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE; 3044 if (section_type == MachO::S_CSTRING_LITERALS && 3045 ReferenceValue >= Sec.addr && 3046 ReferenceValue < Sec.addr + Sec.size) { 3047 uint64_t sect_offset = ReferenceValue - Sec.addr; 3048 uint64_t object_offset = Sec.offset + sect_offset; 3049 StringRef MachOContents = info->O->getData(); 3050 uint64_t object_size = MachOContents.size(); 3051 const char *object_addr = (const char *)MachOContents.data(); 3052 if (object_offset < object_size) { 3053 const char *name = object_addr + object_offset; 3054 return name; 3055 } else { 3056 return nullptr; 3057 } 3058 } 3059 } 3060 } 3061 } 3062 return nullptr; 3063 } 3064 3065 // GuessIndirectSymbol returns the name of the indirect symbol for the 3066 // ReferenceValue passed in or nullptr. This is used when ReferenceValue maybe 3067 // an address of a symbol stub or a lazy or non-lazy pointer to associate the 3068 // symbol name being referenced by the stub or pointer. 3069 static const char *GuessIndirectSymbol(uint64_t ReferenceValue, 3070 struct DisassembleInfo *info) { 3071 MachO::dysymtab_command Dysymtab = info->O->getDysymtabLoadCommand(); 3072 MachO::symtab_command Symtab = info->O->getSymtabLoadCommand(); 3073 for (const auto &Load : info->O->load_commands()) { 3074 if (Load.C.cmd == MachO::LC_SEGMENT_64) { 3075 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load); 3076 for (unsigned J = 0; J < Seg.nsects; ++J) { 3077 MachO::section_64 Sec = info->O->getSection64(Load, J); 3078 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE; 3079 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS || 3080 section_type == MachO::S_LAZY_SYMBOL_POINTERS || 3081 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS || 3082 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS || 3083 section_type == MachO::S_SYMBOL_STUBS) && 3084 ReferenceValue >= Sec.addr && 3085 ReferenceValue < Sec.addr + Sec.size) { 3086 uint32_t stride; 3087 if (section_type == MachO::S_SYMBOL_STUBS) 3088 stride = Sec.reserved2; 3089 else 3090 stride = 8; 3091 if (stride == 0) 3092 return nullptr; 3093 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride; 3094 if (index < Dysymtab.nindirectsyms) { 3095 uint32_t indirect_symbol = 3096 info->O->getIndirectSymbolTableEntry(Dysymtab, index); 3097 if (indirect_symbol < Symtab.nsyms) { 3098 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol); 3099 return unwrapOrError(Sym->getName(), info->O->getFileName()) 3100 .data(); 3101 } 3102 } 3103 } 3104 } 3105 } else if (Load.C.cmd == MachO::LC_SEGMENT) { 3106 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load); 3107 for (unsigned J = 0; J < Seg.nsects; ++J) { 3108 MachO::section Sec = info->O->getSection(Load, J); 3109 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE; 3110 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS || 3111 section_type == MachO::S_LAZY_SYMBOL_POINTERS || 3112 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS || 3113 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS || 3114 section_type == MachO::S_SYMBOL_STUBS) && 3115 ReferenceValue >= Sec.addr && 3116 ReferenceValue < Sec.addr + Sec.size) { 3117 uint32_t stride; 3118 if (section_type == MachO::S_SYMBOL_STUBS) 3119 stride = Sec.reserved2; 3120 else 3121 stride = 4; 3122 if (stride == 0) 3123 return nullptr; 3124 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride; 3125 if (index < Dysymtab.nindirectsyms) { 3126 uint32_t indirect_symbol = 3127 info->O->getIndirectSymbolTableEntry(Dysymtab, index); 3128 if (indirect_symbol < Symtab.nsyms) { 3129 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol); 3130 return unwrapOrError(Sym->getName(), info->O->getFileName()) 3131 .data(); 3132 } 3133 } 3134 } 3135 } 3136 } 3137 } 3138 return nullptr; 3139 } 3140 3141 // method_reference() is called passing it the ReferenceName that might be 3142 // a reference it to an Objective-C method call. If so then it allocates and 3143 // assembles a method call string with the values last seen and saved in 3144 // the DisassembleInfo's class_name and selector_name fields. This is saved 3145 // into the method field of the info and any previous string is free'ed. 3146 // Then the class_name field in the info is set to nullptr. The method call 3147 // string is set into ReferenceName and ReferenceType is set to 3148 // LLVMDisassembler_ReferenceType_Out_Objc_Message. If this not a method call 3149 // then both ReferenceType and ReferenceName are left unchanged. 3150 static void method_reference(struct DisassembleInfo *info, 3151 uint64_t *ReferenceType, 3152 const char **ReferenceName) { 3153 unsigned int Arch = info->O->getArch(); 3154 if (*ReferenceName != nullptr) { 3155 if (strcmp(*ReferenceName, "_objc_msgSend") == 0) { 3156 if (info->selector_name != nullptr) { 3157 if (info->class_name != nullptr) { 3158 info->method = std::make_unique<char[]>( 3159 5 + strlen(info->class_name) + strlen(info->selector_name)); 3160 char *method = info->method.get(); 3161 if (method != nullptr) { 3162 strcpy(method, "+["); 3163 strcat(method, info->class_name); 3164 strcat(method, " "); 3165 strcat(method, info->selector_name); 3166 strcat(method, "]"); 3167 *ReferenceName = method; 3168 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message; 3169 } 3170 } else { 3171 info->method = 3172 std::make_unique<char[]>(9 + strlen(info->selector_name)); 3173 char *method = info->method.get(); 3174 if (method != nullptr) { 3175 if (Arch == Triple::x86_64) 3176 strcpy(method, "-[%rdi "); 3177 else if (Arch == Triple::aarch64) 3178 strcpy(method, "-[x0 "); 3179 else 3180 strcpy(method, "-[r? "); 3181 strcat(method, info->selector_name); 3182 strcat(method, "]"); 3183 *ReferenceName = method; 3184 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message; 3185 } 3186 } 3187 info->class_name = nullptr; 3188 } 3189 } else if (strcmp(*ReferenceName, "_objc_msgSendSuper2") == 0) { 3190 if (info->selector_name != nullptr) { 3191 info->method = 3192 std::make_unique<char[]>(17 + strlen(info->selector_name)); 3193 char *method = info->method.get(); 3194 if (method != nullptr) { 3195 if (Arch == Triple::x86_64) 3196 strcpy(method, "-[[%rdi super] "); 3197 else if (Arch == Triple::aarch64) 3198 strcpy(method, "-[[x0 super] "); 3199 else 3200 strcpy(method, "-[[r? super] "); 3201 strcat(method, info->selector_name); 3202 strcat(method, "]"); 3203 *ReferenceName = method; 3204 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message; 3205 } 3206 info->class_name = nullptr; 3207 } 3208 } 3209 } 3210 } 3211 3212 // GuessPointerPointer() is passed the address of what might be a pointer to 3213 // a reference to an Objective-C class, selector, message ref or cfstring. 3214 // If so the value of the pointer is returned and one of the booleans are set 3215 // to true. If not zero is returned and all the booleans are set to false. 3216 static uint64_t GuessPointerPointer(uint64_t ReferenceValue, 3217 struct DisassembleInfo *info, 3218 bool &classref, bool &selref, bool &msgref, 3219 bool &cfstring) { 3220 classref = false; 3221 selref = false; 3222 msgref = false; 3223 cfstring = false; 3224 for (const auto &Load : info->O->load_commands()) { 3225 if (Load.C.cmd == MachO::LC_SEGMENT_64) { 3226 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load); 3227 for (unsigned J = 0; J < Seg.nsects; ++J) { 3228 MachO::section_64 Sec = info->O->getSection64(Load, J); 3229 if ((strncmp(Sec.sectname, "__objc_selrefs", 16) == 0 || 3230 strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 || 3231 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0 || 3232 strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 || 3233 strncmp(Sec.sectname, "__cfstring", 16) == 0) && 3234 ReferenceValue >= Sec.addr && 3235 ReferenceValue < Sec.addr + Sec.size) { 3236 uint64_t sect_offset = ReferenceValue - Sec.addr; 3237 uint64_t object_offset = Sec.offset + sect_offset; 3238 StringRef MachOContents = info->O->getData(); 3239 uint64_t object_size = MachOContents.size(); 3240 const char *object_addr = (const char *)MachOContents.data(); 3241 if (object_offset < object_size) { 3242 uint64_t pointer_value; 3243 memcpy(&pointer_value, object_addr + object_offset, 3244 sizeof(uint64_t)); 3245 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 3246 sys::swapByteOrder(pointer_value); 3247 if (strncmp(Sec.sectname, "__objc_selrefs", 16) == 0) 3248 selref = true; 3249 else if (strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 || 3250 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0) 3251 classref = true; 3252 else if (strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 && 3253 ReferenceValue + 8 < Sec.addr + Sec.size) { 3254 msgref = true; 3255 memcpy(&pointer_value, object_addr + object_offset + 8, 3256 sizeof(uint64_t)); 3257 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 3258 sys::swapByteOrder(pointer_value); 3259 } else if (strncmp(Sec.sectname, "__cfstring", 16) == 0) 3260 cfstring = true; 3261 return pointer_value; 3262 } else { 3263 return 0; 3264 } 3265 } 3266 } 3267 } 3268 // TODO: Look for LC_SEGMENT for 32-bit Mach-O files. 3269 } 3270 return 0; 3271 } 3272 3273 // get_pointer_64 returns a pointer to the bytes in the object file at the 3274 // Address from a section in the Mach-O file. And indirectly returns the 3275 // offset into the section, number of bytes left in the section past the offset 3276 // and which section is was being referenced. If the Address is not in a 3277 // section nullptr is returned. 3278 static const char *get_pointer_64(uint64_t Address, uint32_t &offset, 3279 uint32_t &left, SectionRef &S, 3280 DisassembleInfo *info, 3281 bool objc_only = false) { 3282 offset = 0; 3283 left = 0; 3284 S = SectionRef(); 3285 for (unsigned SectIdx = 0; SectIdx != info->Sections->size(); SectIdx++) { 3286 uint64_t SectAddress = ((*(info->Sections))[SectIdx]).getAddress(); 3287 uint64_t SectSize = ((*(info->Sections))[SectIdx]).getSize(); 3288 if (SectSize == 0) 3289 continue; 3290 if (objc_only) { 3291 StringRef SectName; 3292 Expected<StringRef> SecNameOrErr = 3293 ((*(info->Sections))[SectIdx]).getName(); 3294 if (SecNameOrErr) 3295 SectName = *SecNameOrErr; 3296 else 3297 consumeError(SecNameOrErr.takeError()); 3298 3299 DataRefImpl Ref = ((*(info->Sections))[SectIdx]).getRawDataRefImpl(); 3300 StringRef SegName = info->O->getSectionFinalSegmentName(Ref); 3301 if (SegName != "__OBJC" && SectName != "__cstring") 3302 continue; 3303 } 3304 if (Address >= SectAddress && Address < SectAddress + SectSize) { 3305 S = (*(info->Sections))[SectIdx]; 3306 offset = Address - SectAddress; 3307 left = SectSize - offset; 3308 StringRef SectContents = unwrapOrError( 3309 ((*(info->Sections))[SectIdx]).getContents(), info->O->getFileName()); 3310 return SectContents.data() + offset; 3311 } 3312 } 3313 return nullptr; 3314 } 3315 3316 static const char *get_pointer_32(uint32_t Address, uint32_t &offset, 3317 uint32_t &left, SectionRef &S, 3318 DisassembleInfo *info, 3319 bool objc_only = false) { 3320 return get_pointer_64(Address, offset, left, S, info, objc_only); 3321 } 3322 3323 // get_symbol_64() returns the name of a symbol (or nullptr) and the address of 3324 // the symbol indirectly through n_value. Based on the relocation information 3325 // for the specified section offset in the specified section reference. 3326 // If no relocation information is found and a non-zero ReferenceValue for the 3327 // symbol is passed, look up that address in the info's AddrMap. 3328 static const char *get_symbol_64(uint32_t sect_offset, SectionRef S, 3329 DisassembleInfo *info, uint64_t &n_value, 3330 uint64_t ReferenceValue = 0) { 3331 n_value = 0; 3332 if (!info->verbose) 3333 return nullptr; 3334 3335 // See if there is an external relocation entry at the sect_offset. 3336 bool reloc_found = false; 3337 DataRefImpl Rel; 3338 MachO::any_relocation_info RE; 3339 bool isExtern = false; 3340 SymbolRef Symbol; 3341 for (const RelocationRef &Reloc : S.relocations()) { 3342 uint64_t RelocOffset = Reloc.getOffset(); 3343 if (RelocOffset == sect_offset) { 3344 Rel = Reloc.getRawDataRefImpl(); 3345 RE = info->O->getRelocation(Rel); 3346 if (info->O->isRelocationScattered(RE)) 3347 continue; 3348 isExtern = info->O->getPlainRelocationExternal(RE); 3349 if (isExtern) { 3350 symbol_iterator RelocSym = Reloc.getSymbol(); 3351 Symbol = *RelocSym; 3352 } 3353 reloc_found = true; 3354 break; 3355 } 3356 } 3357 // If there is an external relocation entry for a symbol in this section 3358 // at this section_offset then use that symbol's value for the n_value 3359 // and return its name. 3360 const char *SymbolName = nullptr; 3361 if (reloc_found && isExtern) { 3362 n_value = cantFail(Symbol.getValue()); 3363 StringRef Name = unwrapOrError(Symbol.getName(), info->O->getFileName()); 3364 if (!Name.empty()) { 3365 SymbolName = Name.data(); 3366 return SymbolName; 3367 } 3368 } 3369 3370 // TODO: For fully linked images, look through the external relocation 3371 // entries off the dynamic symtab command. For these the r_offset is from the 3372 // start of the first writeable segment in the Mach-O file. So the offset 3373 // to this section from that segment is passed to this routine by the caller, 3374 // as the database_offset. Which is the difference of the section's starting 3375 // address and the first writable segment. 3376 // 3377 // NOTE: need add passing the database_offset to this routine. 3378 3379 // We did not find an external relocation entry so look up the ReferenceValue 3380 // as an address of a symbol and if found return that symbol's name. 3381 SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap); 3382 3383 return SymbolName; 3384 } 3385 3386 static const char *get_symbol_32(uint32_t sect_offset, SectionRef S, 3387 DisassembleInfo *info, 3388 uint32_t ReferenceValue) { 3389 uint64_t n_value64; 3390 return get_symbol_64(sect_offset, S, info, n_value64, ReferenceValue); 3391 } 3392 3393 namespace { 3394 3395 // These are structs in the Objective-C meta data and read to produce the 3396 // comments for disassembly. While these are part of the ABI they are no 3397 // public defintions. So the are here not in include/llvm/BinaryFormat/MachO.h 3398 // . 3399 3400 // The cfstring object in a 64-bit Mach-O file. 3401 struct cfstring64_t { 3402 uint64_t isa; // class64_t * (64-bit pointer) 3403 uint64_t flags; // flag bits 3404 uint64_t characters; // char * (64-bit pointer) 3405 uint64_t length; // number of non-NULL characters in above 3406 }; 3407 3408 // The class object in a 64-bit Mach-O file. 3409 struct class64_t { 3410 uint64_t isa; // class64_t * (64-bit pointer) 3411 uint64_t superclass; // class64_t * (64-bit pointer) 3412 uint64_t cache; // Cache (64-bit pointer) 3413 uint64_t vtable; // IMP * (64-bit pointer) 3414 uint64_t data; // class_ro64_t * (64-bit pointer) 3415 }; 3416 3417 struct class32_t { 3418 uint32_t isa; /* class32_t * (32-bit pointer) */ 3419 uint32_t superclass; /* class32_t * (32-bit pointer) */ 3420 uint32_t cache; /* Cache (32-bit pointer) */ 3421 uint32_t vtable; /* IMP * (32-bit pointer) */ 3422 uint32_t data; /* class_ro32_t * (32-bit pointer) */ 3423 }; 3424 3425 struct class_ro64_t { 3426 uint32_t flags; 3427 uint32_t instanceStart; 3428 uint32_t instanceSize; 3429 uint32_t reserved; 3430 uint64_t ivarLayout; // const uint8_t * (64-bit pointer) 3431 uint64_t name; // const char * (64-bit pointer) 3432 uint64_t baseMethods; // const method_list_t * (64-bit pointer) 3433 uint64_t baseProtocols; // const protocol_list_t * (64-bit pointer) 3434 uint64_t ivars; // const ivar_list_t * (64-bit pointer) 3435 uint64_t weakIvarLayout; // const uint8_t * (64-bit pointer) 3436 uint64_t baseProperties; // const struct objc_property_list (64-bit pointer) 3437 }; 3438 3439 struct class_ro32_t { 3440 uint32_t flags; 3441 uint32_t instanceStart; 3442 uint32_t instanceSize; 3443 uint32_t ivarLayout; /* const uint8_t * (32-bit pointer) */ 3444 uint32_t name; /* const char * (32-bit pointer) */ 3445 uint32_t baseMethods; /* const method_list_t * (32-bit pointer) */ 3446 uint32_t baseProtocols; /* const protocol_list_t * (32-bit pointer) */ 3447 uint32_t ivars; /* const ivar_list_t * (32-bit pointer) */ 3448 uint32_t weakIvarLayout; /* const uint8_t * (32-bit pointer) */ 3449 uint32_t baseProperties; /* const struct objc_property_list * 3450 (32-bit pointer) */ 3451 }; 3452 3453 /* Values for class_ro{64,32}_t->flags */ 3454 #define RO_META (1 << 0) 3455 #define RO_ROOT (1 << 1) 3456 #define RO_HAS_CXX_STRUCTORS (1 << 2) 3457 3458 struct method_list64_t { 3459 uint32_t entsize; 3460 uint32_t count; 3461 /* struct method64_t first; These structures follow inline */ 3462 }; 3463 3464 struct method_list32_t { 3465 uint32_t entsize; 3466 uint32_t count; 3467 /* struct method32_t first; These structures follow inline */ 3468 }; 3469 3470 struct method64_t { 3471 uint64_t name; /* SEL (64-bit pointer) */ 3472 uint64_t types; /* const char * (64-bit pointer) */ 3473 uint64_t imp; /* IMP (64-bit pointer) */ 3474 }; 3475 3476 struct method32_t { 3477 uint32_t name; /* SEL (32-bit pointer) */ 3478 uint32_t types; /* const char * (32-bit pointer) */ 3479 uint32_t imp; /* IMP (32-bit pointer) */ 3480 }; 3481 3482 struct protocol_list64_t { 3483 uint64_t count; /* uintptr_t (a 64-bit value) */ 3484 /* struct protocol64_t * list[0]; These pointers follow inline */ 3485 }; 3486 3487 struct protocol_list32_t { 3488 uint32_t count; /* uintptr_t (a 32-bit value) */ 3489 /* struct protocol32_t * list[0]; These pointers follow inline */ 3490 }; 3491 3492 struct protocol64_t { 3493 uint64_t isa; /* id * (64-bit pointer) */ 3494 uint64_t name; /* const char * (64-bit pointer) */ 3495 uint64_t protocols; /* struct protocol_list64_t * 3496 (64-bit pointer) */ 3497 uint64_t instanceMethods; /* method_list_t * (64-bit pointer) */ 3498 uint64_t classMethods; /* method_list_t * (64-bit pointer) */ 3499 uint64_t optionalInstanceMethods; /* method_list_t * (64-bit pointer) */ 3500 uint64_t optionalClassMethods; /* method_list_t * (64-bit pointer) */ 3501 uint64_t instanceProperties; /* struct objc_property_list * 3502 (64-bit pointer) */ 3503 }; 3504 3505 struct protocol32_t { 3506 uint32_t isa; /* id * (32-bit pointer) */ 3507 uint32_t name; /* const char * (32-bit pointer) */ 3508 uint32_t protocols; /* struct protocol_list_t * 3509 (32-bit pointer) */ 3510 uint32_t instanceMethods; /* method_list_t * (32-bit pointer) */ 3511 uint32_t classMethods; /* method_list_t * (32-bit pointer) */ 3512 uint32_t optionalInstanceMethods; /* method_list_t * (32-bit pointer) */ 3513 uint32_t optionalClassMethods; /* method_list_t * (32-bit pointer) */ 3514 uint32_t instanceProperties; /* struct objc_property_list * 3515 (32-bit pointer) */ 3516 }; 3517 3518 struct ivar_list64_t { 3519 uint32_t entsize; 3520 uint32_t count; 3521 /* struct ivar64_t first; These structures follow inline */ 3522 }; 3523 3524 struct ivar_list32_t { 3525 uint32_t entsize; 3526 uint32_t count; 3527 /* struct ivar32_t first; These structures follow inline */ 3528 }; 3529 3530 struct ivar64_t { 3531 uint64_t offset; /* uintptr_t * (64-bit pointer) */ 3532 uint64_t name; /* const char * (64-bit pointer) */ 3533 uint64_t type; /* const char * (64-bit pointer) */ 3534 uint32_t alignment; 3535 uint32_t size; 3536 }; 3537 3538 struct ivar32_t { 3539 uint32_t offset; /* uintptr_t * (32-bit pointer) */ 3540 uint32_t name; /* const char * (32-bit pointer) */ 3541 uint32_t type; /* const char * (32-bit pointer) */ 3542 uint32_t alignment; 3543 uint32_t size; 3544 }; 3545 3546 struct objc_property_list64 { 3547 uint32_t entsize; 3548 uint32_t count; 3549 /* struct objc_property64 first; These structures follow inline */ 3550 }; 3551 3552 struct objc_property_list32 { 3553 uint32_t entsize; 3554 uint32_t count; 3555 /* struct objc_property32 first; These structures follow inline */ 3556 }; 3557 3558 struct objc_property64 { 3559 uint64_t name; /* const char * (64-bit pointer) */ 3560 uint64_t attributes; /* const char * (64-bit pointer) */ 3561 }; 3562 3563 struct objc_property32 { 3564 uint32_t name; /* const char * (32-bit pointer) */ 3565 uint32_t attributes; /* const char * (32-bit pointer) */ 3566 }; 3567 3568 struct category64_t { 3569 uint64_t name; /* const char * (64-bit pointer) */ 3570 uint64_t cls; /* struct class_t * (64-bit pointer) */ 3571 uint64_t instanceMethods; /* struct method_list_t * (64-bit pointer) */ 3572 uint64_t classMethods; /* struct method_list_t * (64-bit pointer) */ 3573 uint64_t protocols; /* struct protocol_list_t * (64-bit pointer) */ 3574 uint64_t instanceProperties; /* struct objc_property_list * 3575 (64-bit pointer) */ 3576 }; 3577 3578 struct category32_t { 3579 uint32_t name; /* const char * (32-bit pointer) */ 3580 uint32_t cls; /* struct class_t * (32-bit pointer) */ 3581 uint32_t instanceMethods; /* struct method_list_t * (32-bit pointer) */ 3582 uint32_t classMethods; /* struct method_list_t * (32-bit pointer) */ 3583 uint32_t protocols; /* struct protocol_list_t * (32-bit pointer) */ 3584 uint32_t instanceProperties; /* struct objc_property_list * 3585 (32-bit pointer) */ 3586 }; 3587 3588 struct objc_image_info64 { 3589 uint32_t version; 3590 uint32_t flags; 3591 }; 3592 struct objc_image_info32 { 3593 uint32_t version; 3594 uint32_t flags; 3595 }; 3596 struct imageInfo_t { 3597 uint32_t version; 3598 uint32_t flags; 3599 }; 3600 /* masks for objc_image_info.flags */ 3601 #define OBJC_IMAGE_IS_REPLACEMENT (1 << 0) 3602 #define OBJC_IMAGE_SUPPORTS_GC (1 << 1) 3603 #define OBJC_IMAGE_IS_SIMULATED (1 << 5) 3604 #define OBJC_IMAGE_HAS_CATEGORY_CLASS_PROPERTIES (1 << 6) 3605 3606 struct message_ref64 { 3607 uint64_t imp; /* IMP (64-bit pointer) */ 3608 uint64_t sel; /* SEL (64-bit pointer) */ 3609 }; 3610 3611 struct message_ref32 { 3612 uint32_t imp; /* IMP (32-bit pointer) */ 3613 uint32_t sel; /* SEL (32-bit pointer) */ 3614 }; 3615 3616 // Objective-C 1 (32-bit only) meta data structs. 3617 3618 struct objc_module_t { 3619 uint32_t version; 3620 uint32_t size; 3621 uint32_t name; /* char * (32-bit pointer) */ 3622 uint32_t symtab; /* struct objc_symtab * (32-bit pointer) */ 3623 }; 3624 3625 struct objc_symtab_t { 3626 uint32_t sel_ref_cnt; 3627 uint32_t refs; /* SEL * (32-bit pointer) */ 3628 uint16_t cls_def_cnt; 3629 uint16_t cat_def_cnt; 3630 // uint32_t defs[1]; /* void * (32-bit pointer) variable size */ 3631 }; 3632 3633 struct objc_class_t { 3634 uint32_t isa; /* struct objc_class * (32-bit pointer) */ 3635 uint32_t super_class; /* struct objc_class * (32-bit pointer) */ 3636 uint32_t name; /* const char * (32-bit pointer) */ 3637 int32_t version; 3638 int32_t info; 3639 int32_t instance_size; 3640 uint32_t ivars; /* struct objc_ivar_list * (32-bit pointer) */ 3641 uint32_t methodLists; /* struct objc_method_list ** (32-bit pointer) */ 3642 uint32_t cache; /* struct objc_cache * (32-bit pointer) */ 3643 uint32_t protocols; /* struct objc_protocol_list * (32-bit pointer) */ 3644 }; 3645 3646 #define CLS_GETINFO(cls, infomask) ((cls)->info & (infomask)) 3647 // class is not a metaclass 3648 #define CLS_CLASS 0x1 3649 // class is a metaclass 3650 #define CLS_META 0x2 3651 3652 struct objc_category_t { 3653 uint32_t category_name; /* char * (32-bit pointer) */ 3654 uint32_t class_name; /* char * (32-bit pointer) */ 3655 uint32_t instance_methods; /* struct objc_method_list * (32-bit pointer) */ 3656 uint32_t class_methods; /* struct objc_method_list * (32-bit pointer) */ 3657 uint32_t protocols; /* struct objc_protocol_list * (32-bit ptr) */ 3658 }; 3659 3660 struct objc_ivar_t { 3661 uint32_t ivar_name; /* char * (32-bit pointer) */ 3662 uint32_t ivar_type; /* char * (32-bit pointer) */ 3663 int32_t ivar_offset; 3664 }; 3665 3666 struct objc_ivar_list_t { 3667 int32_t ivar_count; 3668 // struct objc_ivar_t ivar_list[1]; /* variable length structure */ 3669 }; 3670 3671 struct objc_method_list_t { 3672 uint32_t obsolete; /* struct objc_method_list * (32-bit pointer) */ 3673 int32_t method_count; 3674 // struct objc_method_t method_list[1]; /* variable length structure */ 3675 }; 3676 3677 struct objc_method_t { 3678 uint32_t method_name; /* SEL, aka struct objc_selector * (32-bit pointer) */ 3679 uint32_t method_types; /* char * (32-bit pointer) */ 3680 uint32_t method_imp; /* IMP, aka function pointer, (*IMP)(id, SEL, ...) 3681 (32-bit pointer) */ 3682 }; 3683 3684 struct objc_protocol_list_t { 3685 uint32_t next; /* struct objc_protocol_list * (32-bit pointer) */ 3686 int32_t count; 3687 // uint32_t list[1]; /* Protocol *, aka struct objc_protocol_t * 3688 // (32-bit pointer) */ 3689 }; 3690 3691 struct objc_protocol_t { 3692 uint32_t isa; /* struct objc_class * (32-bit pointer) */ 3693 uint32_t protocol_name; /* char * (32-bit pointer) */ 3694 uint32_t protocol_list; /* struct objc_protocol_list * (32-bit pointer) */ 3695 uint32_t instance_methods; /* struct objc_method_description_list * 3696 (32-bit pointer) */ 3697 uint32_t class_methods; /* struct objc_method_description_list * 3698 (32-bit pointer) */ 3699 }; 3700 3701 struct objc_method_description_list_t { 3702 int32_t count; 3703 // struct objc_method_description_t list[1]; 3704 }; 3705 3706 struct objc_method_description_t { 3707 uint32_t name; /* SEL, aka struct objc_selector * (32-bit pointer) */ 3708 uint32_t types; /* char * (32-bit pointer) */ 3709 }; 3710 3711 inline void swapStruct(struct cfstring64_t &cfs) { 3712 sys::swapByteOrder(cfs.isa); 3713 sys::swapByteOrder(cfs.flags); 3714 sys::swapByteOrder(cfs.characters); 3715 sys::swapByteOrder(cfs.length); 3716 } 3717 3718 inline void swapStruct(struct class64_t &c) { 3719 sys::swapByteOrder(c.isa); 3720 sys::swapByteOrder(c.superclass); 3721 sys::swapByteOrder(c.cache); 3722 sys::swapByteOrder(c.vtable); 3723 sys::swapByteOrder(c.data); 3724 } 3725 3726 inline void swapStruct(struct class32_t &c) { 3727 sys::swapByteOrder(c.isa); 3728 sys::swapByteOrder(c.superclass); 3729 sys::swapByteOrder(c.cache); 3730 sys::swapByteOrder(c.vtable); 3731 sys::swapByteOrder(c.data); 3732 } 3733 3734 inline void swapStruct(struct class_ro64_t &cro) { 3735 sys::swapByteOrder(cro.flags); 3736 sys::swapByteOrder(cro.instanceStart); 3737 sys::swapByteOrder(cro.instanceSize); 3738 sys::swapByteOrder(cro.reserved); 3739 sys::swapByteOrder(cro.ivarLayout); 3740 sys::swapByteOrder(cro.name); 3741 sys::swapByteOrder(cro.baseMethods); 3742 sys::swapByteOrder(cro.baseProtocols); 3743 sys::swapByteOrder(cro.ivars); 3744 sys::swapByteOrder(cro.weakIvarLayout); 3745 sys::swapByteOrder(cro.baseProperties); 3746 } 3747 3748 inline void swapStruct(struct class_ro32_t &cro) { 3749 sys::swapByteOrder(cro.flags); 3750 sys::swapByteOrder(cro.instanceStart); 3751 sys::swapByteOrder(cro.instanceSize); 3752 sys::swapByteOrder(cro.ivarLayout); 3753 sys::swapByteOrder(cro.name); 3754 sys::swapByteOrder(cro.baseMethods); 3755 sys::swapByteOrder(cro.baseProtocols); 3756 sys::swapByteOrder(cro.ivars); 3757 sys::swapByteOrder(cro.weakIvarLayout); 3758 sys::swapByteOrder(cro.baseProperties); 3759 } 3760 3761 inline void swapStruct(struct method_list64_t &ml) { 3762 sys::swapByteOrder(ml.entsize); 3763 sys::swapByteOrder(ml.count); 3764 } 3765 3766 inline void swapStruct(struct method_list32_t &ml) { 3767 sys::swapByteOrder(ml.entsize); 3768 sys::swapByteOrder(ml.count); 3769 } 3770 3771 inline void swapStruct(struct method64_t &m) { 3772 sys::swapByteOrder(m.name); 3773 sys::swapByteOrder(m.types); 3774 sys::swapByteOrder(m.imp); 3775 } 3776 3777 inline void swapStruct(struct method32_t &m) { 3778 sys::swapByteOrder(m.name); 3779 sys::swapByteOrder(m.types); 3780 sys::swapByteOrder(m.imp); 3781 } 3782 3783 inline void swapStruct(struct protocol_list64_t &pl) { 3784 sys::swapByteOrder(pl.count); 3785 } 3786 3787 inline void swapStruct(struct protocol_list32_t &pl) { 3788 sys::swapByteOrder(pl.count); 3789 } 3790 3791 inline void swapStruct(struct protocol64_t &p) { 3792 sys::swapByteOrder(p.isa); 3793 sys::swapByteOrder(p.name); 3794 sys::swapByteOrder(p.protocols); 3795 sys::swapByteOrder(p.instanceMethods); 3796 sys::swapByteOrder(p.classMethods); 3797 sys::swapByteOrder(p.optionalInstanceMethods); 3798 sys::swapByteOrder(p.optionalClassMethods); 3799 sys::swapByteOrder(p.instanceProperties); 3800 } 3801 3802 inline void swapStruct(struct protocol32_t &p) { 3803 sys::swapByteOrder(p.isa); 3804 sys::swapByteOrder(p.name); 3805 sys::swapByteOrder(p.protocols); 3806 sys::swapByteOrder(p.instanceMethods); 3807 sys::swapByteOrder(p.classMethods); 3808 sys::swapByteOrder(p.optionalInstanceMethods); 3809 sys::swapByteOrder(p.optionalClassMethods); 3810 sys::swapByteOrder(p.instanceProperties); 3811 } 3812 3813 inline void swapStruct(struct ivar_list64_t &il) { 3814 sys::swapByteOrder(il.entsize); 3815 sys::swapByteOrder(il.count); 3816 } 3817 3818 inline void swapStruct(struct ivar_list32_t &il) { 3819 sys::swapByteOrder(il.entsize); 3820 sys::swapByteOrder(il.count); 3821 } 3822 3823 inline void swapStruct(struct ivar64_t &i) { 3824 sys::swapByteOrder(i.offset); 3825 sys::swapByteOrder(i.name); 3826 sys::swapByteOrder(i.type); 3827 sys::swapByteOrder(i.alignment); 3828 sys::swapByteOrder(i.size); 3829 } 3830 3831 inline void swapStruct(struct ivar32_t &i) { 3832 sys::swapByteOrder(i.offset); 3833 sys::swapByteOrder(i.name); 3834 sys::swapByteOrder(i.type); 3835 sys::swapByteOrder(i.alignment); 3836 sys::swapByteOrder(i.size); 3837 } 3838 3839 inline void swapStruct(struct objc_property_list64 &pl) { 3840 sys::swapByteOrder(pl.entsize); 3841 sys::swapByteOrder(pl.count); 3842 } 3843 3844 inline void swapStruct(struct objc_property_list32 &pl) { 3845 sys::swapByteOrder(pl.entsize); 3846 sys::swapByteOrder(pl.count); 3847 } 3848 3849 inline void swapStruct(struct objc_property64 &op) { 3850 sys::swapByteOrder(op.name); 3851 sys::swapByteOrder(op.attributes); 3852 } 3853 3854 inline void swapStruct(struct objc_property32 &op) { 3855 sys::swapByteOrder(op.name); 3856 sys::swapByteOrder(op.attributes); 3857 } 3858 3859 inline void swapStruct(struct category64_t &c) { 3860 sys::swapByteOrder(c.name); 3861 sys::swapByteOrder(c.cls); 3862 sys::swapByteOrder(c.instanceMethods); 3863 sys::swapByteOrder(c.classMethods); 3864 sys::swapByteOrder(c.protocols); 3865 sys::swapByteOrder(c.instanceProperties); 3866 } 3867 3868 inline void swapStruct(struct category32_t &c) { 3869 sys::swapByteOrder(c.name); 3870 sys::swapByteOrder(c.cls); 3871 sys::swapByteOrder(c.instanceMethods); 3872 sys::swapByteOrder(c.classMethods); 3873 sys::swapByteOrder(c.protocols); 3874 sys::swapByteOrder(c.instanceProperties); 3875 } 3876 3877 inline void swapStruct(struct objc_image_info64 &o) { 3878 sys::swapByteOrder(o.version); 3879 sys::swapByteOrder(o.flags); 3880 } 3881 3882 inline void swapStruct(struct objc_image_info32 &o) { 3883 sys::swapByteOrder(o.version); 3884 sys::swapByteOrder(o.flags); 3885 } 3886 3887 inline void swapStruct(struct imageInfo_t &o) { 3888 sys::swapByteOrder(o.version); 3889 sys::swapByteOrder(o.flags); 3890 } 3891 3892 inline void swapStruct(struct message_ref64 &mr) { 3893 sys::swapByteOrder(mr.imp); 3894 sys::swapByteOrder(mr.sel); 3895 } 3896 3897 inline void swapStruct(struct message_ref32 &mr) { 3898 sys::swapByteOrder(mr.imp); 3899 sys::swapByteOrder(mr.sel); 3900 } 3901 3902 inline void swapStruct(struct objc_module_t &module) { 3903 sys::swapByteOrder(module.version); 3904 sys::swapByteOrder(module.size); 3905 sys::swapByteOrder(module.name); 3906 sys::swapByteOrder(module.symtab); 3907 } 3908 3909 inline void swapStruct(struct objc_symtab_t &symtab) { 3910 sys::swapByteOrder(symtab.sel_ref_cnt); 3911 sys::swapByteOrder(symtab.refs); 3912 sys::swapByteOrder(symtab.cls_def_cnt); 3913 sys::swapByteOrder(symtab.cat_def_cnt); 3914 } 3915 3916 inline void swapStruct(struct objc_class_t &objc_class) { 3917 sys::swapByteOrder(objc_class.isa); 3918 sys::swapByteOrder(objc_class.super_class); 3919 sys::swapByteOrder(objc_class.name); 3920 sys::swapByteOrder(objc_class.version); 3921 sys::swapByteOrder(objc_class.info); 3922 sys::swapByteOrder(objc_class.instance_size); 3923 sys::swapByteOrder(objc_class.ivars); 3924 sys::swapByteOrder(objc_class.methodLists); 3925 sys::swapByteOrder(objc_class.cache); 3926 sys::swapByteOrder(objc_class.protocols); 3927 } 3928 3929 inline void swapStruct(struct objc_category_t &objc_category) { 3930 sys::swapByteOrder(objc_category.category_name); 3931 sys::swapByteOrder(objc_category.class_name); 3932 sys::swapByteOrder(objc_category.instance_methods); 3933 sys::swapByteOrder(objc_category.class_methods); 3934 sys::swapByteOrder(objc_category.protocols); 3935 } 3936 3937 inline void swapStruct(struct objc_ivar_list_t &objc_ivar_list) { 3938 sys::swapByteOrder(objc_ivar_list.ivar_count); 3939 } 3940 3941 inline void swapStruct(struct objc_ivar_t &objc_ivar) { 3942 sys::swapByteOrder(objc_ivar.ivar_name); 3943 sys::swapByteOrder(objc_ivar.ivar_type); 3944 sys::swapByteOrder(objc_ivar.ivar_offset); 3945 } 3946 3947 inline void swapStruct(struct objc_method_list_t &method_list) { 3948 sys::swapByteOrder(method_list.obsolete); 3949 sys::swapByteOrder(method_list.method_count); 3950 } 3951 3952 inline void swapStruct(struct objc_method_t &method) { 3953 sys::swapByteOrder(method.method_name); 3954 sys::swapByteOrder(method.method_types); 3955 sys::swapByteOrder(method.method_imp); 3956 } 3957 3958 inline void swapStruct(struct objc_protocol_list_t &protocol_list) { 3959 sys::swapByteOrder(protocol_list.next); 3960 sys::swapByteOrder(protocol_list.count); 3961 } 3962 3963 inline void swapStruct(struct objc_protocol_t &protocol) { 3964 sys::swapByteOrder(protocol.isa); 3965 sys::swapByteOrder(protocol.protocol_name); 3966 sys::swapByteOrder(protocol.protocol_list); 3967 sys::swapByteOrder(protocol.instance_methods); 3968 sys::swapByteOrder(protocol.class_methods); 3969 } 3970 3971 inline void swapStruct(struct objc_method_description_list_t &mdl) { 3972 sys::swapByteOrder(mdl.count); 3973 } 3974 3975 inline void swapStruct(struct objc_method_description_t &md) { 3976 sys::swapByteOrder(md.name); 3977 sys::swapByteOrder(md.types); 3978 } 3979 3980 } // namespace 3981 3982 static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue, 3983 struct DisassembleInfo *info); 3984 3985 // get_objc2_64bit_class_name() is used for disassembly and is passed a pointer 3986 // to an Objective-C class and returns the class name. It is also passed the 3987 // address of the pointer, so when the pointer is zero as it can be in an .o 3988 // file, that is used to look for an external relocation entry with a symbol 3989 // name. 3990 static const char *get_objc2_64bit_class_name(uint64_t pointer_value, 3991 uint64_t ReferenceValue, 3992 struct DisassembleInfo *info) { 3993 const char *r; 3994 uint32_t offset, left; 3995 SectionRef S; 3996 3997 // The pointer_value can be 0 in an object file and have a relocation 3998 // entry for the class symbol at the ReferenceValue (the address of the 3999 // pointer). 4000 if (pointer_value == 0) { 4001 r = get_pointer_64(ReferenceValue, offset, left, S, info); 4002 if (r == nullptr || left < sizeof(uint64_t)) 4003 return nullptr; 4004 uint64_t n_value; 4005 const char *symbol_name = get_symbol_64(offset, S, info, n_value); 4006 if (symbol_name == nullptr) 4007 return nullptr; 4008 const char *class_name = strrchr(symbol_name, '$'); 4009 if (class_name != nullptr && class_name[1] == '_' && class_name[2] != '\0') 4010 return class_name + 2; 4011 else 4012 return nullptr; 4013 } 4014 4015 // The case were the pointer_value is non-zero and points to a class defined 4016 // in this Mach-O file. 4017 r = get_pointer_64(pointer_value, offset, left, S, info); 4018 if (r == nullptr || left < sizeof(struct class64_t)) 4019 return nullptr; 4020 struct class64_t c; 4021 memcpy(&c, r, sizeof(struct class64_t)); 4022 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 4023 swapStruct(c); 4024 if (c.data == 0) 4025 return nullptr; 4026 r = get_pointer_64(c.data, offset, left, S, info); 4027 if (r == nullptr || left < sizeof(struct class_ro64_t)) 4028 return nullptr; 4029 struct class_ro64_t cro; 4030 memcpy(&cro, r, sizeof(struct class_ro64_t)); 4031 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 4032 swapStruct(cro); 4033 if (cro.name == 0) 4034 return nullptr; 4035 const char *name = get_pointer_64(cro.name, offset, left, S, info); 4036 return name; 4037 } 4038 4039 // get_objc2_64bit_cfstring_name is used for disassembly and is passed a 4040 // pointer to a cfstring and returns its name or nullptr. 4041 static const char *get_objc2_64bit_cfstring_name(uint64_t ReferenceValue, 4042 struct DisassembleInfo *info) { 4043 const char *r, *name; 4044 uint32_t offset, left; 4045 SectionRef S; 4046 struct cfstring64_t cfs; 4047 uint64_t cfs_characters; 4048 4049 r = get_pointer_64(ReferenceValue, offset, left, S, info); 4050 if (r == nullptr || left < sizeof(struct cfstring64_t)) 4051 return nullptr; 4052 memcpy(&cfs, r, sizeof(struct cfstring64_t)); 4053 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 4054 swapStruct(cfs); 4055 if (cfs.characters == 0) { 4056 uint64_t n_value; 4057 const char *symbol_name = get_symbol_64( 4058 offset + offsetof(struct cfstring64_t, characters), S, info, n_value); 4059 if (symbol_name == nullptr) 4060 return nullptr; 4061 cfs_characters = n_value; 4062 } else 4063 cfs_characters = cfs.characters; 4064 name = get_pointer_64(cfs_characters, offset, left, S, info); 4065 4066 return name; 4067 } 4068 4069 // get_objc2_64bit_selref() is used for disassembly and is passed a the address 4070 // of a pointer to an Objective-C selector reference when the pointer value is 4071 // zero as in a .o file and is likely to have a external relocation entry with 4072 // who's symbol's n_value is the real pointer to the selector name. If that is 4073 // the case the real pointer to the selector name is returned else 0 is 4074 // returned 4075 static uint64_t get_objc2_64bit_selref(uint64_t ReferenceValue, 4076 struct DisassembleInfo *info) { 4077 uint32_t offset, left; 4078 SectionRef S; 4079 4080 const char *r = get_pointer_64(ReferenceValue, offset, left, S, info); 4081 if (r == nullptr || left < sizeof(uint64_t)) 4082 return 0; 4083 uint64_t n_value; 4084 const char *symbol_name = get_symbol_64(offset, S, info, n_value); 4085 if (symbol_name == nullptr) 4086 return 0; 4087 return n_value; 4088 } 4089 4090 static const SectionRef get_section(MachOObjectFile *O, const char *segname, 4091 const char *sectname) { 4092 for (const SectionRef &Section : O->sections()) { 4093 StringRef SectName; 4094 Expected<StringRef> SecNameOrErr = Section.getName(); 4095 if (SecNameOrErr) 4096 SectName = *SecNameOrErr; 4097 else 4098 consumeError(SecNameOrErr.takeError()); 4099 4100 DataRefImpl Ref = Section.getRawDataRefImpl(); 4101 StringRef SegName = O->getSectionFinalSegmentName(Ref); 4102 if (SegName == segname && SectName == sectname) 4103 return Section; 4104 } 4105 return SectionRef(); 4106 } 4107 4108 static void 4109 walk_pointer_list_64(const char *listname, const SectionRef S, 4110 MachOObjectFile *O, struct DisassembleInfo *info, 4111 void (*func)(uint64_t, struct DisassembleInfo *info)) { 4112 if (S == SectionRef()) 4113 return; 4114 4115 StringRef SectName; 4116 Expected<StringRef> SecNameOrErr = S.getName(); 4117 if (SecNameOrErr) 4118 SectName = *SecNameOrErr; 4119 else 4120 consumeError(SecNameOrErr.takeError()); 4121 4122 DataRefImpl Ref = S.getRawDataRefImpl(); 4123 StringRef SegName = O->getSectionFinalSegmentName(Ref); 4124 outs() << "Contents of (" << SegName << "," << SectName << ") section\n"; 4125 4126 StringRef BytesStr = unwrapOrError(S.getContents(), O->getFileName()); 4127 const char *Contents = reinterpret_cast<const char *>(BytesStr.data()); 4128 4129 for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint64_t)) { 4130 uint32_t left = S.getSize() - i; 4131 uint32_t size = left < sizeof(uint64_t) ? left : sizeof(uint64_t); 4132 uint64_t p = 0; 4133 memcpy(&p, Contents + i, size); 4134 if (i + sizeof(uint64_t) > S.getSize()) 4135 outs() << listname << " list pointer extends past end of (" << SegName 4136 << "," << SectName << ") section\n"; 4137 outs() << format("%016" PRIx64, S.getAddress() + i) << " "; 4138 4139 if (O->isLittleEndian() != sys::IsLittleEndianHost) 4140 sys::swapByteOrder(p); 4141 4142 uint64_t n_value = 0; 4143 const char *name = get_symbol_64(i, S, info, n_value, p); 4144 if (name == nullptr) 4145 name = get_dyld_bind_info_symbolname(S.getAddress() + i, info); 4146 4147 if (n_value != 0) { 4148 outs() << format("0x%" PRIx64, n_value); 4149 if (p != 0) 4150 outs() << " + " << format("0x%" PRIx64, p); 4151 } else 4152 outs() << format("0x%" PRIx64, p); 4153 if (name != nullptr) 4154 outs() << " " << name; 4155 outs() << "\n"; 4156 4157 p += n_value; 4158 if (func) 4159 func(p, info); 4160 } 4161 } 4162 4163 static void 4164 walk_pointer_list_32(const char *listname, const SectionRef S, 4165 MachOObjectFile *O, struct DisassembleInfo *info, 4166 void (*func)(uint32_t, struct DisassembleInfo *info)) { 4167 if (S == SectionRef()) 4168 return; 4169 4170 StringRef SectName = unwrapOrError(S.getName(), O->getFileName()); 4171 DataRefImpl Ref = S.getRawDataRefImpl(); 4172 StringRef SegName = O->getSectionFinalSegmentName(Ref); 4173 outs() << "Contents of (" << SegName << "," << SectName << ") section\n"; 4174 4175 StringRef BytesStr = unwrapOrError(S.getContents(), O->getFileName()); 4176 const char *Contents = reinterpret_cast<const char *>(BytesStr.data()); 4177 4178 for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint32_t)) { 4179 uint32_t left = S.getSize() - i; 4180 uint32_t size = left < sizeof(uint32_t) ? left : sizeof(uint32_t); 4181 uint32_t p = 0; 4182 memcpy(&p, Contents + i, size); 4183 if (i + sizeof(uint32_t) > S.getSize()) 4184 outs() << listname << " list pointer extends past end of (" << SegName 4185 << "," << SectName << ") section\n"; 4186 uint32_t Address = S.getAddress() + i; 4187 outs() << format("%08" PRIx32, Address) << " "; 4188 4189 if (O->isLittleEndian() != sys::IsLittleEndianHost) 4190 sys::swapByteOrder(p); 4191 outs() << format("0x%" PRIx32, p); 4192 4193 const char *name = get_symbol_32(i, S, info, p); 4194 if (name != nullptr) 4195 outs() << " " << name; 4196 outs() << "\n"; 4197 4198 if (func) 4199 func(p, info); 4200 } 4201 } 4202 4203 static void print_layout_map(const char *layout_map, uint32_t left) { 4204 if (layout_map == nullptr) 4205 return; 4206 outs() << " layout map: "; 4207 do { 4208 outs() << format("0x%02" PRIx32, (*layout_map) & 0xff) << " "; 4209 left--; 4210 layout_map++; 4211 } while (*layout_map != '\0' && left != 0); 4212 outs() << "\n"; 4213 } 4214 4215 static void print_layout_map64(uint64_t p, struct DisassembleInfo *info) { 4216 uint32_t offset, left; 4217 SectionRef S; 4218 const char *layout_map; 4219 4220 if (p == 0) 4221 return; 4222 layout_map = get_pointer_64(p, offset, left, S, info); 4223 print_layout_map(layout_map, left); 4224 } 4225 4226 static void print_layout_map32(uint32_t p, struct DisassembleInfo *info) { 4227 uint32_t offset, left; 4228 SectionRef S; 4229 const char *layout_map; 4230 4231 if (p == 0) 4232 return; 4233 layout_map = get_pointer_32(p, offset, left, S, info); 4234 print_layout_map(layout_map, left); 4235 } 4236 4237 static void print_method_list64_t(uint64_t p, struct DisassembleInfo *info, 4238 const char *indent) { 4239 struct method_list64_t ml; 4240 struct method64_t m; 4241 const char *r; 4242 uint32_t offset, xoffset, left, i; 4243 SectionRef S, xS; 4244 const char *name, *sym_name; 4245 uint64_t n_value; 4246 4247 r = get_pointer_64(p, offset, left, S, info); 4248 if (r == nullptr) 4249 return; 4250 memset(&ml, '\0', sizeof(struct method_list64_t)); 4251 if (left < sizeof(struct method_list64_t)) { 4252 memcpy(&ml, r, left); 4253 outs() << " (method_list_t entends past the end of the section)\n"; 4254 } else 4255 memcpy(&ml, r, sizeof(struct method_list64_t)); 4256 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 4257 swapStruct(ml); 4258 outs() << indent << "\t\t entsize " << ml.entsize << "\n"; 4259 outs() << indent << "\t\t count " << ml.count << "\n"; 4260 4261 p += sizeof(struct method_list64_t); 4262 offset += sizeof(struct method_list64_t); 4263 for (i = 0; i < ml.count; i++) { 4264 r = get_pointer_64(p, offset, left, S, info); 4265 if (r == nullptr) 4266 return; 4267 memset(&m, '\0', sizeof(struct method64_t)); 4268 if (left < sizeof(struct method64_t)) { 4269 memcpy(&m, r, left); 4270 outs() << indent << " (method_t extends past the end of the section)\n"; 4271 } else 4272 memcpy(&m, r, sizeof(struct method64_t)); 4273 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 4274 swapStruct(m); 4275 4276 outs() << indent << "\t\t name "; 4277 sym_name = get_symbol_64(offset + offsetof(struct method64_t, name), S, 4278 info, n_value, m.name); 4279 if (n_value != 0) { 4280 if (info->verbose && sym_name != nullptr) 4281 outs() << sym_name; 4282 else 4283 outs() << format("0x%" PRIx64, n_value); 4284 if (m.name != 0) 4285 outs() << " + " << format("0x%" PRIx64, m.name); 4286 } else 4287 outs() << format("0x%" PRIx64, m.name); 4288 name = get_pointer_64(m.name + n_value, xoffset, left, xS, info); 4289 if (name != nullptr) 4290 outs() << format(" %.*s", left, name); 4291 outs() << "\n"; 4292 4293 outs() << indent << "\t\t types "; 4294 sym_name = get_symbol_64(offset + offsetof(struct method64_t, types), S, 4295 info, n_value, m.types); 4296 if (n_value != 0) { 4297 if (info->verbose && sym_name != nullptr) 4298 outs() << sym_name; 4299 else 4300 outs() << format("0x%" PRIx64, n_value); 4301 if (m.types != 0) 4302 outs() << " + " << format("0x%" PRIx64, m.types); 4303 } else 4304 outs() << format("0x%" PRIx64, m.types); 4305 name = get_pointer_64(m.types + n_value, xoffset, left, xS, info); 4306 if (name != nullptr) 4307 outs() << format(" %.*s", left, name); 4308 outs() << "\n"; 4309 4310 outs() << indent << "\t\t imp "; 4311 name = get_symbol_64(offset + offsetof(struct method64_t, imp), S, info, 4312 n_value, m.imp); 4313 if (info->verbose && name == nullptr) { 4314 if (n_value != 0) { 4315 outs() << format("0x%" PRIx64, n_value) << " "; 4316 if (m.imp != 0) 4317 outs() << "+ " << format("0x%" PRIx64, m.imp) << " "; 4318 } else 4319 outs() << format("0x%" PRIx64, m.imp) << " "; 4320 } 4321 if (name != nullptr) 4322 outs() << name; 4323 outs() << "\n"; 4324 4325 p += sizeof(struct method64_t); 4326 offset += sizeof(struct method64_t); 4327 } 4328 } 4329 4330 static void print_method_list32_t(uint64_t p, struct DisassembleInfo *info, 4331 const char *indent) { 4332 struct method_list32_t ml; 4333 struct method32_t m; 4334 const char *r, *name; 4335 uint32_t offset, xoffset, left, i; 4336 SectionRef S, xS; 4337 4338 r = get_pointer_32(p, offset, left, S, info); 4339 if (r == nullptr) 4340 return; 4341 memset(&ml, '\0', sizeof(struct method_list32_t)); 4342 if (left < sizeof(struct method_list32_t)) { 4343 memcpy(&ml, r, left); 4344 outs() << " (method_list_t entends past the end of the section)\n"; 4345 } else 4346 memcpy(&ml, r, sizeof(struct method_list32_t)); 4347 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 4348 swapStruct(ml); 4349 outs() << indent << "\t\t entsize " << ml.entsize << "\n"; 4350 outs() << indent << "\t\t count " << ml.count << "\n"; 4351 4352 p += sizeof(struct method_list32_t); 4353 offset += sizeof(struct method_list32_t); 4354 for (i = 0; i < ml.count; i++) { 4355 r = get_pointer_32(p, offset, left, S, info); 4356 if (r == nullptr) 4357 return; 4358 memset(&m, '\0', sizeof(struct method32_t)); 4359 if (left < sizeof(struct method32_t)) { 4360 memcpy(&ml, r, left); 4361 outs() << indent << " (method_t entends past the end of the section)\n"; 4362 } else 4363 memcpy(&m, r, sizeof(struct method32_t)); 4364 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 4365 swapStruct(m); 4366 4367 outs() << indent << "\t\t name " << format("0x%" PRIx32, m.name); 4368 name = get_pointer_32(m.name, xoffset, left, xS, info); 4369 if (name != nullptr) 4370 outs() << format(" %.*s", left, name); 4371 outs() << "\n"; 4372 4373 outs() << indent << "\t\t types " << format("0x%" PRIx32, m.types); 4374 name = get_pointer_32(m.types, xoffset, left, xS, info); 4375 if (name != nullptr) 4376 outs() << format(" %.*s", left, name); 4377 outs() << "\n"; 4378 4379 outs() << indent << "\t\t imp " << format("0x%" PRIx32, m.imp); 4380 name = get_symbol_32(offset + offsetof(struct method32_t, imp), S, info, 4381 m.imp); 4382 if (name != nullptr) 4383 outs() << " " << name; 4384 outs() << "\n"; 4385 4386 p += sizeof(struct method32_t); 4387 offset += sizeof(struct method32_t); 4388 } 4389 } 4390 4391 static bool print_method_list(uint32_t p, struct DisassembleInfo *info) { 4392 uint32_t offset, left, xleft; 4393 SectionRef S; 4394 struct objc_method_list_t method_list; 4395 struct objc_method_t method; 4396 const char *r, *methods, *name, *SymbolName; 4397 int32_t i; 4398 4399 r = get_pointer_32(p, offset, left, S, info, true); 4400 if (r == nullptr) 4401 return true; 4402 4403 outs() << "\n"; 4404 if (left > sizeof(struct objc_method_list_t)) { 4405 memcpy(&method_list, r, sizeof(struct objc_method_list_t)); 4406 } else { 4407 outs() << "\t\t objc_method_list extends past end of the section\n"; 4408 memset(&method_list, '\0', sizeof(struct objc_method_list_t)); 4409 memcpy(&method_list, r, left); 4410 } 4411 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 4412 swapStruct(method_list); 4413 4414 outs() << "\t\t obsolete " 4415 << format("0x%08" PRIx32, method_list.obsolete) << "\n"; 4416 outs() << "\t\t method_count " << method_list.method_count << "\n"; 4417 4418 methods = r + sizeof(struct objc_method_list_t); 4419 for (i = 0; i < method_list.method_count; i++) { 4420 if ((i + 1) * sizeof(struct objc_method_t) > left) { 4421 outs() << "\t\t remaining method's extend past the of the section\n"; 4422 break; 4423 } 4424 memcpy(&method, methods + i * sizeof(struct objc_method_t), 4425 sizeof(struct objc_method_t)); 4426 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 4427 swapStruct(method); 4428 4429 outs() << "\t\t method_name " 4430 << format("0x%08" PRIx32, method.method_name); 4431 if (info->verbose) { 4432 name = get_pointer_32(method.method_name, offset, xleft, S, info, true); 4433 if (name != nullptr) 4434 outs() << format(" %.*s", xleft, name); 4435 else 4436 outs() << " (not in an __OBJC section)"; 4437 } 4438 outs() << "\n"; 4439 4440 outs() << "\t\t method_types " 4441 << format("0x%08" PRIx32, method.method_types); 4442 if (info->verbose) { 4443 name = get_pointer_32(method.method_types, offset, xleft, S, info, true); 4444 if (name != nullptr) 4445 outs() << format(" %.*s", xleft, name); 4446 else 4447 outs() << " (not in an __OBJC section)"; 4448 } 4449 outs() << "\n"; 4450 4451 outs() << "\t\t method_imp " 4452 << format("0x%08" PRIx32, method.method_imp) << " "; 4453 if (info->verbose) { 4454 SymbolName = GuessSymbolName(method.method_imp, info->AddrMap); 4455 if (SymbolName != nullptr) 4456 outs() << SymbolName; 4457 } 4458 outs() << "\n"; 4459 } 4460 return false; 4461 } 4462 4463 static void print_protocol_list64_t(uint64_t p, struct DisassembleInfo *info) { 4464 struct protocol_list64_t pl; 4465 uint64_t q, n_value; 4466 struct protocol64_t pc; 4467 const char *r; 4468 uint32_t offset, xoffset, left, i; 4469 SectionRef S, xS; 4470 const char *name, *sym_name; 4471 4472 r = get_pointer_64(p, offset, left, S, info); 4473 if (r == nullptr) 4474 return; 4475 memset(&pl, '\0', sizeof(struct protocol_list64_t)); 4476 if (left < sizeof(struct protocol_list64_t)) { 4477 memcpy(&pl, r, left); 4478 outs() << " (protocol_list_t entends past the end of the section)\n"; 4479 } else 4480 memcpy(&pl, r, sizeof(struct protocol_list64_t)); 4481 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 4482 swapStruct(pl); 4483 outs() << " count " << pl.count << "\n"; 4484 4485 p += sizeof(struct protocol_list64_t); 4486 offset += sizeof(struct protocol_list64_t); 4487 for (i = 0; i < pl.count; i++) { 4488 r = get_pointer_64(p, offset, left, S, info); 4489 if (r == nullptr) 4490 return; 4491 q = 0; 4492 if (left < sizeof(uint64_t)) { 4493 memcpy(&q, r, left); 4494 outs() << " (protocol_t * entends past the end of the section)\n"; 4495 } else 4496 memcpy(&q, r, sizeof(uint64_t)); 4497 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 4498 sys::swapByteOrder(q); 4499 4500 outs() << "\t\t list[" << i << "] "; 4501 sym_name = get_symbol_64(offset, S, info, n_value, q); 4502 if (n_value != 0) { 4503 if (info->verbose && sym_name != nullptr) 4504 outs() << sym_name; 4505 else 4506 outs() << format("0x%" PRIx64, n_value); 4507 if (q != 0) 4508 outs() << " + " << format("0x%" PRIx64, q); 4509 } else 4510 outs() << format("0x%" PRIx64, q); 4511 outs() << " (struct protocol_t *)\n"; 4512 4513 r = get_pointer_64(q + n_value, offset, left, S, info); 4514 if (r == nullptr) 4515 return; 4516 memset(&pc, '\0', sizeof(struct protocol64_t)); 4517 if (left < sizeof(struct protocol64_t)) { 4518 memcpy(&pc, r, left); 4519 outs() << " (protocol_t entends past the end of the section)\n"; 4520 } else 4521 memcpy(&pc, r, sizeof(struct protocol64_t)); 4522 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 4523 swapStruct(pc); 4524 4525 outs() << "\t\t\t isa " << format("0x%" PRIx64, pc.isa) << "\n"; 4526 4527 outs() << "\t\t\t name "; 4528 sym_name = get_symbol_64(offset + offsetof(struct protocol64_t, name), S, 4529 info, n_value, pc.name); 4530 if (n_value != 0) { 4531 if (info->verbose && sym_name != nullptr) 4532 outs() << sym_name; 4533 else 4534 outs() << format("0x%" PRIx64, n_value); 4535 if (pc.name != 0) 4536 outs() << " + " << format("0x%" PRIx64, pc.name); 4537 } else 4538 outs() << format("0x%" PRIx64, pc.name); 4539 name = get_pointer_64(pc.name + n_value, xoffset, left, xS, info); 4540 if (name != nullptr) 4541 outs() << format(" %.*s", left, name); 4542 outs() << "\n"; 4543 4544 outs() << "\t\t\tprotocols " << format("0x%" PRIx64, pc.protocols) << "\n"; 4545 4546 outs() << "\t\t instanceMethods "; 4547 sym_name = 4548 get_symbol_64(offset + offsetof(struct protocol64_t, instanceMethods), 4549 S, info, n_value, pc.instanceMethods); 4550 if (n_value != 0) { 4551 if (info->verbose && sym_name != nullptr) 4552 outs() << sym_name; 4553 else 4554 outs() << format("0x%" PRIx64, n_value); 4555 if (pc.instanceMethods != 0) 4556 outs() << " + " << format("0x%" PRIx64, pc.instanceMethods); 4557 } else 4558 outs() << format("0x%" PRIx64, pc.instanceMethods); 4559 outs() << " (struct method_list_t *)\n"; 4560 if (pc.instanceMethods + n_value != 0) 4561 print_method_list64_t(pc.instanceMethods + n_value, info, "\t"); 4562 4563 outs() << "\t\t classMethods "; 4564 sym_name = 4565 get_symbol_64(offset + offsetof(struct protocol64_t, classMethods), S, 4566 info, n_value, pc.classMethods); 4567 if (n_value != 0) { 4568 if (info->verbose && sym_name != nullptr) 4569 outs() << sym_name; 4570 else 4571 outs() << format("0x%" PRIx64, n_value); 4572 if (pc.classMethods != 0) 4573 outs() << " + " << format("0x%" PRIx64, pc.classMethods); 4574 } else 4575 outs() << format("0x%" PRIx64, pc.classMethods); 4576 outs() << " (struct method_list_t *)\n"; 4577 if (pc.classMethods + n_value != 0) 4578 print_method_list64_t(pc.classMethods + n_value, info, "\t"); 4579 4580 outs() << "\t optionalInstanceMethods " 4581 << format("0x%" PRIx64, pc.optionalInstanceMethods) << "\n"; 4582 outs() << "\t optionalClassMethods " 4583 << format("0x%" PRIx64, pc.optionalClassMethods) << "\n"; 4584 outs() << "\t instanceProperties " 4585 << format("0x%" PRIx64, pc.instanceProperties) << "\n"; 4586 4587 p += sizeof(uint64_t); 4588 offset += sizeof(uint64_t); 4589 } 4590 } 4591 4592 static void print_protocol_list32_t(uint32_t p, struct DisassembleInfo *info) { 4593 struct protocol_list32_t pl; 4594 uint32_t q; 4595 struct protocol32_t pc; 4596 const char *r; 4597 uint32_t offset, xoffset, left, i; 4598 SectionRef S, xS; 4599 const char *name; 4600 4601 r = get_pointer_32(p, offset, left, S, info); 4602 if (r == nullptr) 4603 return; 4604 memset(&pl, '\0', sizeof(struct protocol_list32_t)); 4605 if (left < sizeof(struct protocol_list32_t)) { 4606 memcpy(&pl, r, left); 4607 outs() << " (protocol_list_t entends past the end of the section)\n"; 4608 } else 4609 memcpy(&pl, r, sizeof(struct protocol_list32_t)); 4610 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 4611 swapStruct(pl); 4612 outs() << " count " << pl.count << "\n"; 4613 4614 p += sizeof(struct protocol_list32_t); 4615 offset += sizeof(struct protocol_list32_t); 4616 for (i = 0; i < pl.count; i++) { 4617 r = get_pointer_32(p, offset, left, S, info); 4618 if (r == nullptr) 4619 return; 4620 q = 0; 4621 if (left < sizeof(uint32_t)) { 4622 memcpy(&q, r, left); 4623 outs() << " (protocol_t * entends past the end of the section)\n"; 4624 } else 4625 memcpy(&q, r, sizeof(uint32_t)); 4626 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 4627 sys::swapByteOrder(q); 4628 outs() << "\t\t list[" << i << "] " << format("0x%" PRIx32, q) 4629 << " (struct protocol_t *)\n"; 4630 r = get_pointer_32(q, offset, left, S, info); 4631 if (r == nullptr) 4632 return; 4633 memset(&pc, '\0', sizeof(struct protocol32_t)); 4634 if (left < sizeof(struct protocol32_t)) { 4635 memcpy(&pc, r, left); 4636 outs() << " (protocol_t entends past the end of the section)\n"; 4637 } else 4638 memcpy(&pc, r, sizeof(struct protocol32_t)); 4639 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 4640 swapStruct(pc); 4641 outs() << "\t\t\t isa " << format("0x%" PRIx32, pc.isa) << "\n"; 4642 outs() << "\t\t\t name " << format("0x%" PRIx32, pc.name); 4643 name = get_pointer_32(pc.name, xoffset, left, xS, info); 4644 if (name != nullptr) 4645 outs() << format(" %.*s", left, name); 4646 outs() << "\n"; 4647 outs() << "\t\t\tprotocols " << format("0x%" PRIx32, pc.protocols) << "\n"; 4648 outs() << "\t\t instanceMethods " 4649 << format("0x%" PRIx32, pc.instanceMethods) 4650 << " (struct method_list_t *)\n"; 4651 if (pc.instanceMethods != 0) 4652 print_method_list32_t(pc.instanceMethods, info, "\t"); 4653 outs() << "\t\t classMethods " << format("0x%" PRIx32, pc.classMethods) 4654 << " (struct method_list_t *)\n"; 4655 if (pc.classMethods != 0) 4656 print_method_list32_t(pc.classMethods, info, "\t"); 4657 outs() << "\t optionalInstanceMethods " 4658 << format("0x%" PRIx32, pc.optionalInstanceMethods) << "\n"; 4659 outs() << "\t optionalClassMethods " 4660 << format("0x%" PRIx32, pc.optionalClassMethods) << "\n"; 4661 outs() << "\t instanceProperties " 4662 << format("0x%" PRIx32, pc.instanceProperties) << "\n"; 4663 p += sizeof(uint32_t); 4664 offset += sizeof(uint32_t); 4665 } 4666 } 4667 4668 static void print_indent(uint32_t indent) { 4669 for (uint32_t i = 0; i < indent;) { 4670 if (indent - i >= 8) { 4671 outs() << "\t"; 4672 i += 8; 4673 } else { 4674 for (uint32_t j = i; j < indent; j++) 4675 outs() << " "; 4676 return; 4677 } 4678 } 4679 } 4680 4681 static bool print_method_description_list(uint32_t p, uint32_t indent, 4682 struct DisassembleInfo *info) { 4683 uint32_t offset, left, xleft; 4684 SectionRef S; 4685 struct objc_method_description_list_t mdl; 4686 struct objc_method_description_t md; 4687 const char *r, *list, *name; 4688 int32_t i; 4689 4690 r = get_pointer_32(p, offset, left, S, info, true); 4691 if (r == nullptr) 4692 return true; 4693 4694 outs() << "\n"; 4695 if (left > sizeof(struct objc_method_description_list_t)) { 4696 memcpy(&mdl, r, sizeof(struct objc_method_description_list_t)); 4697 } else { 4698 print_indent(indent); 4699 outs() << " objc_method_description_list extends past end of the section\n"; 4700 memset(&mdl, '\0', sizeof(struct objc_method_description_list_t)); 4701 memcpy(&mdl, r, left); 4702 } 4703 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 4704 swapStruct(mdl); 4705 4706 print_indent(indent); 4707 outs() << " count " << mdl.count << "\n"; 4708 4709 list = r + sizeof(struct objc_method_description_list_t); 4710 for (i = 0; i < mdl.count; i++) { 4711 if ((i + 1) * sizeof(struct objc_method_description_t) > left) { 4712 print_indent(indent); 4713 outs() << " remaining list entries extend past the of the section\n"; 4714 break; 4715 } 4716 print_indent(indent); 4717 outs() << " list[" << i << "]\n"; 4718 memcpy(&md, list + i * sizeof(struct objc_method_description_t), 4719 sizeof(struct objc_method_description_t)); 4720 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 4721 swapStruct(md); 4722 4723 print_indent(indent); 4724 outs() << " name " << format("0x%08" PRIx32, md.name); 4725 if (info->verbose) { 4726 name = get_pointer_32(md.name, offset, xleft, S, info, true); 4727 if (name != nullptr) 4728 outs() << format(" %.*s", xleft, name); 4729 else 4730 outs() << " (not in an __OBJC section)"; 4731 } 4732 outs() << "\n"; 4733 4734 print_indent(indent); 4735 outs() << " types " << format("0x%08" PRIx32, md.types); 4736 if (info->verbose) { 4737 name = get_pointer_32(md.types, offset, xleft, S, info, true); 4738 if (name != nullptr) 4739 outs() << format(" %.*s", xleft, name); 4740 else 4741 outs() << " (not in an __OBJC section)"; 4742 } 4743 outs() << "\n"; 4744 } 4745 return false; 4746 } 4747 4748 static bool print_protocol_list(uint32_t p, uint32_t indent, 4749 struct DisassembleInfo *info); 4750 4751 static bool print_protocol(uint32_t p, uint32_t indent, 4752 struct DisassembleInfo *info) { 4753 uint32_t offset, left; 4754 SectionRef S; 4755 struct objc_protocol_t protocol; 4756 const char *r, *name; 4757 4758 r = get_pointer_32(p, offset, left, S, info, true); 4759 if (r == nullptr) 4760 return true; 4761 4762 outs() << "\n"; 4763 if (left >= sizeof(struct objc_protocol_t)) { 4764 memcpy(&protocol, r, sizeof(struct objc_protocol_t)); 4765 } else { 4766 print_indent(indent); 4767 outs() << " Protocol extends past end of the section\n"; 4768 memset(&protocol, '\0', sizeof(struct objc_protocol_t)); 4769 memcpy(&protocol, r, left); 4770 } 4771 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 4772 swapStruct(protocol); 4773 4774 print_indent(indent); 4775 outs() << " isa " << format("0x%08" PRIx32, protocol.isa) 4776 << "\n"; 4777 4778 print_indent(indent); 4779 outs() << " protocol_name " 4780 << format("0x%08" PRIx32, protocol.protocol_name); 4781 if (info->verbose) { 4782 name = get_pointer_32(protocol.protocol_name, offset, left, S, info, true); 4783 if (name != nullptr) 4784 outs() << format(" %.*s", left, name); 4785 else 4786 outs() << " (not in an __OBJC section)"; 4787 } 4788 outs() << "\n"; 4789 4790 print_indent(indent); 4791 outs() << " protocol_list " 4792 << format("0x%08" PRIx32, protocol.protocol_list); 4793 if (print_protocol_list(protocol.protocol_list, indent + 4, info)) 4794 outs() << " (not in an __OBJC section)\n"; 4795 4796 print_indent(indent); 4797 outs() << " instance_methods " 4798 << format("0x%08" PRIx32, protocol.instance_methods); 4799 if (print_method_description_list(protocol.instance_methods, indent, info)) 4800 outs() << " (not in an __OBJC section)\n"; 4801 4802 print_indent(indent); 4803 outs() << " class_methods " 4804 << format("0x%08" PRIx32, protocol.class_methods); 4805 if (print_method_description_list(protocol.class_methods, indent, info)) 4806 outs() << " (not in an __OBJC section)\n"; 4807 4808 return false; 4809 } 4810 4811 static bool print_protocol_list(uint32_t p, uint32_t indent, 4812 struct DisassembleInfo *info) { 4813 uint32_t offset, left, l; 4814 SectionRef S; 4815 struct objc_protocol_list_t protocol_list; 4816 const char *r, *list; 4817 int32_t i; 4818 4819 r = get_pointer_32(p, offset, left, S, info, true); 4820 if (r == nullptr) 4821 return true; 4822 4823 outs() << "\n"; 4824 if (left > sizeof(struct objc_protocol_list_t)) { 4825 memcpy(&protocol_list, r, sizeof(struct objc_protocol_list_t)); 4826 } else { 4827 outs() << "\t\t objc_protocol_list_t extends past end of the section\n"; 4828 memset(&protocol_list, '\0', sizeof(struct objc_protocol_list_t)); 4829 memcpy(&protocol_list, r, left); 4830 } 4831 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 4832 swapStruct(protocol_list); 4833 4834 print_indent(indent); 4835 outs() << " next " << format("0x%08" PRIx32, protocol_list.next) 4836 << "\n"; 4837 print_indent(indent); 4838 outs() << " count " << protocol_list.count << "\n"; 4839 4840 list = r + sizeof(struct objc_protocol_list_t); 4841 for (i = 0; i < protocol_list.count; i++) { 4842 if ((i + 1) * sizeof(uint32_t) > left) { 4843 outs() << "\t\t remaining list entries extend past the of the section\n"; 4844 break; 4845 } 4846 memcpy(&l, list + i * sizeof(uint32_t), sizeof(uint32_t)); 4847 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 4848 sys::swapByteOrder(l); 4849 4850 print_indent(indent); 4851 outs() << " list[" << i << "] " << format("0x%08" PRIx32, l); 4852 if (print_protocol(l, indent, info)) 4853 outs() << "(not in an __OBJC section)\n"; 4854 } 4855 return false; 4856 } 4857 4858 static void print_ivar_list64_t(uint64_t p, struct DisassembleInfo *info) { 4859 struct ivar_list64_t il; 4860 struct ivar64_t i; 4861 const char *r; 4862 uint32_t offset, xoffset, left, j; 4863 SectionRef S, xS; 4864 const char *name, *sym_name, *ivar_offset_p; 4865 uint64_t ivar_offset, n_value; 4866 4867 r = get_pointer_64(p, offset, left, S, info); 4868 if (r == nullptr) 4869 return; 4870 memset(&il, '\0', sizeof(struct ivar_list64_t)); 4871 if (left < sizeof(struct ivar_list64_t)) { 4872 memcpy(&il, r, left); 4873 outs() << " (ivar_list_t entends past the end of the section)\n"; 4874 } else 4875 memcpy(&il, r, sizeof(struct ivar_list64_t)); 4876 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 4877 swapStruct(il); 4878 outs() << " entsize " << il.entsize << "\n"; 4879 outs() << " count " << il.count << "\n"; 4880 4881 p += sizeof(struct ivar_list64_t); 4882 offset += sizeof(struct ivar_list64_t); 4883 for (j = 0; j < il.count; j++) { 4884 r = get_pointer_64(p, offset, left, S, info); 4885 if (r == nullptr) 4886 return; 4887 memset(&i, '\0', sizeof(struct ivar64_t)); 4888 if (left < sizeof(struct ivar64_t)) { 4889 memcpy(&i, r, left); 4890 outs() << " (ivar_t entends past the end of the section)\n"; 4891 } else 4892 memcpy(&i, r, sizeof(struct ivar64_t)); 4893 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 4894 swapStruct(i); 4895 4896 outs() << "\t\t\t offset "; 4897 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, offset), S, 4898 info, n_value, i.offset); 4899 if (n_value != 0) { 4900 if (info->verbose && sym_name != nullptr) 4901 outs() << sym_name; 4902 else 4903 outs() << format("0x%" PRIx64, n_value); 4904 if (i.offset != 0) 4905 outs() << " + " << format("0x%" PRIx64, i.offset); 4906 } else 4907 outs() << format("0x%" PRIx64, i.offset); 4908 ivar_offset_p = get_pointer_64(i.offset + n_value, xoffset, left, xS, info); 4909 if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) { 4910 memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset)); 4911 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 4912 sys::swapByteOrder(ivar_offset); 4913 outs() << " " << ivar_offset << "\n"; 4914 } else 4915 outs() << "\n"; 4916 4917 outs() << "\t\t\t name "; 4918 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, name), S, info, 4919 n_value, i.name); 4920 if (n_value != 0) { 4921 if (info->verbose && sym_name != nullptr) 4922 outs() << sym_name; 4923 else 4924 outs() << format("0x%" PRIx64, n_value); 4925 if (i.name != 0) 4926 outs() << " + " << format("0x%" PRIx64, i.name); 4927 } else 4928 outs() << format("0x%" PRIx64, i.name); 4929 name = get_pointer_64(i.name + n_value, xoffset, left, xS, info); 4930 if (name != nullptr) 4931 outs() << format(" %.*s", left, name); 4932 outs() << "\n"; 4933 4934 outs() << "\t\t\t type "; 4935 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, type), S, info, 4936 n_value, i.name); 4937 name = get_pointer_64(i.type + n_value, xoffset, left, xS, info); 4938 if (n_value != 0) { 4939 if (info->verbose && sym_name != nullptr) 4940 outs() << sym_name; 4941 else 4942 outs() << format("0x%" PRIx64, n_value); 4943 if (i.type != 0) 4944 outs() << " + " << format("0x%" PRIx64, i.type); 4945 } else 4946 outs() << format("0x%" PRIx64, i.type); 4947 if (name != nullptr) 4948 outs() << format(" %.*s", left, name); 4949 outs() << "\n"; 4950 4951 outs() << "\t\t\talignment " << i.alignment << "\n"; 4952 outs() << "\t\t\t size " << i.size << "\n"; 4953 4954 p += sizeof(struct ivar64_t); 4955 offset += sizeof(struct ivar64_t); 4956 } 4957 } 4958 4959 static void print_ivar_list32_t(uint32_t p, struct DisassembleInfo *info) { 4960 struct ivar_list32_t il; 4961 struct ivar32_t i; 4962 const char *r; 4963 uint32_t offset, xoffset, left, j; 4964 SectionRef S, xS; 4965 const char *name, *ivar_offset_p; 4966 uint32_t ivar_offset; 4967 4968 r = get_pointer_32(p, offset, left, S, info); 4969 if (r == nullptr) 4970 return; 4971 memset(&il, '\0', sizeof(struct ivar_list32_t)); 4972 if (left < sizeof(struct ivar_list32_t)) { 4973 memcpy(&il, r, left); 4974 outs() << " (ivar_list_t entends past the end of the section)\n"; 4975 } else 4976 memcpy(&il, r, sizeof(struct ivar_list32_t)); 4977 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 4978 swapStruct(il); 4979 outs() << " entsize " << il.entsize << "\n"; 4980 outs() << " count " << il.count << "\n"; 4981 4982 p += sizeof(struct ivar_list32_t); 4983 offset += sizeof(struct ivar_list32_t); 4984 for (j = 0; j < il.count; j++) { 4985 r = get_pointer_32(p, offset, left, S, info); 4986 if (r == nullptr) 4987 return; 4988 memset(&i, '\0', sizeof(struct ivar32_t)); 4989 if (left < sizeof(struct ivar32_t)) { 4990 memcpy(&i, r, left); 4991 outs() << " (ivar_t entends past the end of the section)\n"; 4992 } else 4993 memcpy(&i, r, sizeof(struct ivar32_t)); 4994 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 4995 swapStruct(i); 4996 4997 outs() << "\t\t\t offset " << format("0x%" PRIx32, i.offset); 4998 ivar_offset_p = get_pointer_32(i.offset, xoffset, left, xS, info); 4999 if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) { 5000 memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset)); 5001 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 5002 sys::swapByteOrder(ivar_offset); 5003 outs() << " " << ivar_offset << "\n"; 5004 } else 5005 outs() << "\n"; 5006 5007 outs() << "\t\t\t name " << format("0x%" PRIx32, i.name); 5008 name = get_pointer_32(i.name, xoffset, left, xS, info); 5009 if (name != nullptr) 5010 outs() << format(" %.*s", left, name); 5011 outs() << "\n"; 5012 5013 outs() << "\t\t\t type " << format("0x%" PRIx32, i.type); 5014 name = get_pointer_32(i.type, xoffset, left, xS, info); 5015 if (name != nullptr) 5016 outs() << format(" %.*s", left, name); 5017 outs() << "\n"; 5018 5019 outs() << "\t\t\talignment " << i.alignment << "\n"; 5020 outs() << "\t\t\t size " << i.size << "\n"; 5021 5022 p += sizeof(struct ivar32_t); 5023 offset += sizeof(struct ivar32_t); 5024 } 5025 } 5026 5027 static void print_objc_property_list64(uint64_t p, 5028 struct DisassembleInfo *info) { 5029 struct objc_property_list64 opl; 5030 struct objc_property64 op; 5031 const char *r; 5032 uint32_t offset, xoffset, left, j; 5033 SectionRef S, xS; 5034 const char *name, *sym_name; 5035 uint64_t n_value; 5036 5037 r = get_pointer_64(p, offset, left, S, info); 5038 if (r == nullptr) 5039 return; 5040 memset(&opl, '\0', sizeof(struct objc_property_list64)); 5041 if (left < sizeof(struct objc_property_list64)) { 5042 memcpy(&opl, r, left); 5043 outs() << " (objc_property_list entends past the end of the section)\n"; 5044 } else 5045 memcpy(&opl, r, sizeof(struct objc_property_list64)); 5046 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 5047 swapStruct(opl); 5048 outs() << " entsize " << opl.entsize << "\n"; 5049 outs() << " count " << opl.count << "\n"; 5050 5051 p += sizeof(struct objc_property_list64); 5052 offset += sizeof(struct objc_property_list64); 5053 for (j = 0; j < opl.count; j++) { 5054 r = get_pointer_64(p, offset, left, S, info); 5055 if (r == nullptr) 5056 return; 5057 memset(&op, '\0', sizeof(struct objc_property64)); 5058 if (left < sizeof(struct objc_property64)) { 5059 memcpy(&op, r, left); 5060 outs() << " (objc_property entends past the end of the section)\n"; 5061 } else 5062 memcpy(&op, r, sizeof(struct objc_property64)); 5063 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 5064 swapStruct(op); 5065 5066 outs() << "\t\t\t name "; 5067 sym_name = get_symbol_64(offset + offsetof(struct objc_property64, name), S, 5068 info, n_value, op.name); 5069 if (n_value != 0) { 5070 if (info->verbose && sym_name != nullptr) 5071 outs() << sym_name; 5072 else 5073 outs() << format("0x%" PRIx64, n_value); 5074 if (op.name != 0) 5075 outs() << " + " << format("0x%" PRIx64, op.name); 5076 } else 5077 outs() << format("0x%" PRIx64, op.name); 5078 name = get_pointer_64(op.name + n_value, xoffset, left, xS, info); 5079 if (name != nullptr) 5080 outs() << format(" %.*s", left, name); 5081 outs() << "\n"; 5082 5083 outs() << "\t\t\tattributes "; 5084 sym_name = 5085 get_symbol_64(offset + offsetof(struct objc_property64, attributes), S, 5086 info, n_value, op.attributes); 5087 if (n_value != 0) { 5088 if (info->verbose && sym_name != nullptr) 5089 outs() << sym_name; 5090 else 5091 outs() << format("0x%" PRIx64, n_value); 5092 if (op.attributes != 0) 5093 outs() << " + " << format("0x%" PRIx64, op.attributes); 5094 } else 5095 outs() << format("0x%" PRIx64, op.attributes); 5096 name = get_pointer_64(op.attributes + n_value, xoffset, left, xS, info); 5097 if (name != nullptr) 5098 outs() << format(" %.*s", left, name); 5099 outs() << "\n"; 5100 5101 p += sizeof(struct objc_property64); 5102 offset += sizeof(struct objc_property64); 5103 } 5104 } 5105 5106 static void print_objc_property_list32(uint32_t p, 5107 struct DisassembleInfo *info) { 5108 struct objc_property_list32 opl; 5109 struct objc_property32 op; 5110 const char *r; 5111 uint32_t offset, xoffset, left, j; 5112 SectionRef S, xS; 5113 const char *name; 5114 5115 r = get_pointer_32(p, offset, left, S, info); 5116 if (r == nullptr) 5117 return; 5118 memset(&opl, '\0', sizeof(struct objc_property_list32)); 5119 if (left < sizeof(struct objc_property_list32)) { 5120 memcpy(&opl, r, left); 5121 outs() << " (objc_property_list entends past the end of the section)\n"; 5122 } else 5123 memcpy(&opl, r, sizeof(struct objc_property_list32)); 5124 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 5125 swapStruct(opl); 5126 outs() << " entsize " << opl.entsize << "\n"; 5127 outs() << " count " << opl.count << "\n"; 5128 5129 p += sizeof(struct objc_property_list32); 5130 offset += sizeof(struct objc_property_list32); 5131 for (j = 0; j < opl.count; j++) { 5132 r = get_pointer_32(p, offset, left, S, info); 5133 if (r == nullptr) 5134 return; 5135 memset(&op, '\0', sizeof(struct objc_property32)); 5136 if (left < sizeof(struct objc_property32)) { 5137 memcpy(&op, r, left); 5138 outs() << " (objc_property entends past the end of the section)\n"; 5139 } else 5140 memcpy(&op, r, sizeof(struct objc_property32)); 5141 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 5142 swapStruct(op); 5143 5144 outs() << "\t\t\t name " << format("0x%" PRIx32, op.name); 5145 name = get_pointer_32(op.name, xoffset, left, xS, info); 5146 if (name != nullptr) 5147 outs() << format(" %.*s", left, name); 5148 outs() << "\n"; 5149 5150 outs() << "\t\t\tattributes " << format("0x%" PRIx32, op.attributes); 5151 name = get_pointer_32(op.attributes, xoffset, left, xS, info); 5152 if (name != nullptr) 5153 outs() << format(" %.*s", left, name); 5154 outs() << "\n"; 5155 5156 p += sizeof(struct objc_property32); 5157 offset += sizeof(struct objc_property32); 5158 } 5159 } 5160 5161 static bool print_class_ro64_t(uint64_t p, struct DisassembleInfo *info, 5162 bool &is_meta_class) { 5163 struct class_ro64_t cro; 5164 const char *r; 5165 uint32_t offset, xoffset, left; 5166 SectionRef S, xS; 5167 const char *name, *sym_name; 5168 uint64_t n_value; 5169 5170 r = get_pointer_64(p, offset, left, S, info); 5171 if (r == nullptr || left < sizeof(struct class_ro64_t)) 5172 return false; 5173 memcpy(&cro, r, sizeof(struct class_ro64_t)); 5174 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 5175 swapStruct(cro); 5176 outs() << " flags " << format("0x%" PRIx32, cro.flags); 5177 if (cro.flags & RO_META) 5178 outs() << " RO_META"; 5179 if (cro.flags & RO_ROOT) 5180 outs() << " RO_ROOT"; 5181 if (cro.flags & RO_HAS_CXX_STRUCTORS) 5182 outs() << " RO_HAS_CXX_STRUCTORS"; 5183 outs() << "\n"; 5184 outs() << " instanceStart " << cro.instanceStart << "\n"; 5185 outs() << " instanceSize " << cro.instanceSize << "\n"; 5186 outs() << " reserved " << format("0x%" PRIx32, cro.reserved) 5187 << "\n"; 5188 outs() << " ivarLayout " << format("0x%" PRIx64, cro.ivarLayout) 5189 << "\n"; 5190 print_layout_map64(cro.ivarLayout, info); 5191 5192 outs() << " name "; 5193 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, name), S, 5194 info, n_value, cro.name); 5195 if (n_value != 0) { 5196 if (info->verbose && sym_name != nullptr) 5197 outs() << sym_name; 5198 else 5199 outs() << format("0x%" PRIx64, n_value); 5200 if (cro.name != 0) 5201 outs() << " + " << format("0x%" PRIx64, cro.name); 5202 } else 5203 outs() << format("0x%" PRIx64, cro.name); 5204 name = get_pointer_64(cro.name + n_value, xoffset, left, xS, info); 5205 if (name != nullptr) 5206 outs() << format(" %.*s", left, name); 5207 outs() << "\n"; 5208 5209 outs() << " baseMethods "; 5210 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, baseMethods), 5211 S, info, n_value, cro.baseMethods); 5212 if (n_value != 0) { 5213 if (info->verbose && sym_name != nullptr) 5214 outs() << sym_name; 5215 else 5216 outs() << format("0x%" PRIx64, n_value); 5217 if (cro.baseMethods != 0) 5218 outs() << " + " << format("0x%" PRIx64, cro.baseMethods); 5219 } else 5220 outs() << format("0x%" PRIx64, cro.baseMethods); 5221 outs() << " (struct method_list_t *)\n"; 5222 if (cro.baseMethods + n_value != 0) 5223 print_method_list64_t(cro.baseMethods + n_value, info, ""); 5224 5225 outs() << " baseProtocols "; 5226 sym_name = 5227 get_symbol_64(offset + offsetof(struct class_ro64_t, baseProtocols), S, 5228 info, n_value, cro.baseProtocols); 5229 if (n_value != 0) { 5230 if (info->verbose && sym_name != nullptr) 5231 outs() << sym_name; 5232 else 5233 outs() << format("0x%" PRIx64, n_value); 5234 if (cro.baseProtocols != 0) 5235 outs() << " + " << format("0x%" PRIx64, cro.baseProtocols); 5236 } else 5237 outs() << format("0x%" PRIx64, cro.baseProtocols); 5238 outs() << "\n"; 5239 if (cro.baseProtocols + n_value != 0) 5240 print_protocol_list64_t(cro.baseProtocols + n_value, info); 5241 5242 outs() << " ivars "; 5243 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, ivars), S, 5244 info, n_value, cro.ivars); 5245 if (n_value != 0) { 5246 if (info->verbose && sym_name != nullptr) 5247 outs() << sym_name; 5248 else 5249 outs() << format("0x%" PRIx64, n_value); 5250 if (cro.ivars != 0) 5251 outs() << " + " << format("0x%" PRIx64, cro.ivars); 5252 } else 5253 outs() << format("0x%" PRIx64, cro.ivars); 5254 outs() << "\n"; 5255 if (cro.ivars + n_value != 0) 5256 print_ivar_list64_t(cro.ivars + n_value, info); 5257 5258 outs() << " weakIvarLayout "; 5259 sym_name = 5260 get_symbol_64(offset + offsetof(struct class_ro64_t, weakIvarLayout), S, 5261 info, n_value, cro.weakIvarLayout); 5262 if (n_value != 0) { 5263 if (info->verbose && sym_name != nullptr) 5264 outs() << sym_name; 5265 else 5266 outs() << format("0x%" PRIx64, n_value); 5267 if (cro.weakIvarLayout != 0) 5268 outs() << " + " << format("0x%" PRIx64, cro.weakIvarLayout); 5269 } else 5270 outs() << format("0x%" PRIx64, cro.weakIvarLayout); 5271 outs() << "\n"; 5272 print_layout_map64(cro.weakIvarLayout + n_value, info); 5273 5274 outs() << " baseProperties "; 5275 sym_name = 5276 get_symbol_64(offset + offsetof(struct class_ro64_t, baseProperties), S, 5277 info, n_value, cro.baseProperties); 5278 if (n_value != 0) { 5279 if (info->verbose && sym_name != nullptr) 5280 outs() << sym_name; 5281 else 5282 outs() << format("0x%" PRIx64, n_value); 5283 if (cro.baseProperties != 0) 5284 outs() << " + " << format("0x%" PRIx64, cro.baseProperties); 5285 } else 5286 outs() << format("0x%" PRIx64, cro.baseProperties); 5287 outs() << "\n"; 5288 if (cro.baseProperties + n_value != 0) 5289 print_objc_property_list64(cro.baseProperties + n_value, info); 5290 5291 is_meta_class = (cro.flags & RO_META) != 0; 5292 return true; 5293 } 5294 5295 static bool print_class_ro32_t(uint32_t p, struct DisassembleInfo *info, 5296 bool &is_meta_class) { 5297 struct class_ro32_t cro; 5298 const char *r; 5299 uint32_t offset, xoffset, left; 5300 SectionRef S, xS; 5301 const char *name; 5302 5303 r = get_pointer_32(p, offset, left, S, info); 5304 if (r == nullptr) 5305 return false; 5306 memset(&cro, '\0', sizeof(struct class_ro32_t)); 5307 if (left < sizeof(struct class_ro32_t)) { 5308 memcpy(&cro, r, left); 5309 outs() << " (class_ro_t entends past the end of the section)\n"; 5310 } else 5311 memcpy(&cro, r, sizeof(struct class_ro32_t)); 5312 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 5313 swapStruct(cro); 5314 outs() << " flags " << format("0x%" PRIx32, cro.flags); 5315 if (cro.flags & RO_META) 5316 outs() << " RO_META"; 5317 if (cro.flags & RO_ROOT) 5318 outs() << " RO_ROOT"; 5319 if (cro.flags & RO_HAS_CXX_STRUCTORS) 5320 outs() << " RO_HAS_CXX_STRUCTORS"; 5321 outs() << "\n"; 5322 outs() << " instanceStart " << cro.instanceStart << "\n"; 5323 outs() << " instanceSize " << cro.instanceSize << "\n"; 5324 outs() << " ivarLayout " << format("0x%" PRIx32, cro.ivarLayout) 5325 << "\n"; 5326 print_layout_map32(cro.ivarLayout, info); 5327 5328 outs() << " name " << format("0x%" PRIx32, cro.name); 5329 name = get_pointer_32(cro.name, xoffset, left, xS, info); 5330 if (name != nullptr) 5331 outs() << format(" %.*s", left, name); 5332 outs() << "\n"; 5333 5334 outs() << " baseMethods " 5335 << format("0x%" PRIx32, cro.baseMethods) 5336 << " (struct method_list_t *)\n"; 5337 if (cro.baseMethods != 0) 5338 print_method_list32_t(cro.baseMethods, info, ""); 5339 5340 outs() << " baseProtocols " 5341 << format("0x%" PRIx32, cro.baseProtocols) << "\n"; 5342 if (cro.baseProtocols != 0) 5343 print_protocol_list32_t(cro.baseProtocols, info); 5344 outs() << " ivars " << format("0x%" PRIx32, cro.ivars) 5345 << "\n"; 5346 if (cro.ivars != 0) 5347 print_ivar_list32_t(cro.ivars, info); 5348 outs() << " weakIvarLayout " 5349 << format("0x%" PRIx32, cro.weakIvarLayout) << "\n"; 5350 print_layout_map32(cro.weakIvarLayout, info); 5351 outs() << " baseProperties " 5352 << format("0x%" PRIx32, cro.baseProperties) << "\n"; 5353 if (cro.baseProperties != 0) 5354 print_objc_property_list32(cro.baseProperties, info); 5355 is_meta_class = (cro.flags & RO_META) != 0; 5356 return true; 5357 } 5358 5359 static void print_class64_t(uint64_t p, struct DisassembleInfo *info) { 5360 struct class64_t c; 5361 const char *r; 5362 uint32_t offset, left; 5363 SectionRef S; 5364 const char *name; 5365 uint64_t isa_n_value, n_value; 5366 5367 r = get_pointer_64(p, offset, left, S, info); 5368 if (r == nullptr || left < sizeof(struct class64_t)) 5369 return; 5370 memcpy(&c, r, sizeof(struct class64_t)); 5371 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 5372 swapStruct(c); 5373 5374 outs() << " isa " << format("0x%" PRIx64, c.isa); 5375 name = get_symbol_64(offset + offsetof(struct class64_t, isa), S, info, 5376 isa_n_value, c.isa); 5377 if (name != nullptr) 5378 outs() << " " << name; 5379 outs() << "\n"; 5380 5381 outs() << " superclass " << format("0x%" PRIx64, c.superclass); 5382 name = get_symbol_64(offset + offsetof(struct class64_t, superclass), S, info, 5383 n_value, c.superclass); 5384 if (name != nullptr) 5385 outs() << " " << name; 5386 else { 5387 name = get_dyld_bind_info_symbolname(S.getAddress() + 5388 offset + offsetof(struct class64_t, superclass), info); 5389 if (name != nullptr) 5390 outs() << " " << name; 5391 } 5392 outs() << "\n"; 5393 5394 outs() << " cache " << format("0x%" PRIx64, c.cache); 5395 name = get_symbol_64(offset + offsetof(struct class64_t, cache), S, info, 5396 n_value, c.cache); 5397 if (name != nullptr) 5398 outs() << " " << name; 5399 outs() << "\n"; 5400 5401 outs() << " vtable " << format("0x%" PRIx64, c.vtable); 5402 name = get_symbol_64(offset + offsetof(struct class64_t, vtable), S, info, 5403 n_value, c.vtable); 5404 if (name != nullptr) 5405 outs() << " " << name; 5406 outs() << "\n"; 5407 5408 name = get_symbol_64(offset + offsetof(struct class64_t, data), S, info, 5409 n_value, c.data); 5410 outs() << " data "; 5411 if (n_value != 0) { 5412 if (info->verbose && name != nullptr) 5413 outs() << name; 5414 else 5415 outs() << format("0x%" PRIx64, n_value); 5416 if (c.data != 0) 5417 outs() << " + " << format("0x%" PRIx64, c.data); 5418 } else 5419 outs() << format("0x%" PRIx64, c.data); 5420 outs() << " (struct class_ro_t *)"; 5421 5422 // This is a Swift class if some of the low bits of the pointer are set. 5423 if ((c.data + n_value) & 0x7) 5424 outs() << " Swift class"; 5425 outs() << "\n"; 5426 bool is_meta_class; 5427 if (!print_class_ro64_t((c.data + n_value) & ~0x7, info, is_meta_class)) 5428 return; 5429 5430 if (!is_meta_class && 5431 c.isa + isa_n_value != p && 5432 c.isa + isa_n_value != 0 && 5433 info->depth < 100) { 5434 info->depth++; 5435 outs() << "Meta Class\n"; 5436 print_class64_t(c.isa + isa_n_value, info); 5437 } 5438 } 5439 5440 static void print_class32_t(uint32_t p, struct DisassembleInfo *info) { 5441 struct class32_t c; 5442 const char *r; 5443 uint32_t offset, left; 5444 SectionRef S; 5445 const char *name; 5446 5447 r = get_pointer_32(p, offset, left, S, info); 5448 if (r == nullptr) 5449 return; 5450 memset(&c, '\0', sizeof(struct class32_t)); 5451 if (left < sizeof(struct class32_t)) { 5452 memcpy(&c, r, left); 5453 outs() << " (class_t entends past the end of the section)\n"; 5454 } else 5455 memcpy(&c, r, sizeof(struct class32_t)); 5456 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 5457 swapStruct(c); 5458 5459 outs() << " isa " << format("0x%" PRIx32, c.isa); 5460 name = 5461 get_symbol_32(offset + offsetof(struct class32_t, isa), S, info, c.isa); 5462 if (name != nullptr) 5463 outs() << " " << name; 5464 outs() << "\n"; 5465 5466 outs() << " superclass " << format("0x%" PRIx32, c.superclass); 5467 name = get_symbol_32(offset + offsetof(struct class32_t, superclass), S, info, 5468 c.superclass); 5469 if (name != nullptr) 5470 outs() << " " << name; 5471 outs() << "\n"; 5472 5473 outs() << " cache " << format("0x%" PRIx32, c.cache); 5474 name = get_symbol_32(offset + offsetof(struct class32_t, cache), S, info, 5475 c.cache); 5476 if (name != nullptr) 5477 outs() << " " << name; 5478 outs() << "\n"; 5479 5480 outs() << " vtable " << format("0x%" PRIx32, c.vtable); 5481 name = get_symbol_32(offset + offsetof(struct class32_t, vtable), S, info, 5482 c.vtable); 5483 if (name != nullptr) 5484 outs() << " " << name; 5485 outs() << "\n"; 5486 5487 name = 5488 get_symbol_32(offset + offsetof(struct class32_t, data), S, info, c.data); 5489 outs() << " data " << format("0x%" PRIx32, c.data) 5490 << " (struct class_ro_t *)"; 5491 5492 // This is a Swift class if some of the low bits of the pointer are set. 5493 if (c.data & 0x3) 5494 outs() << " Swift class"; 5495 outs() << "\n"; 5496 bool is_meta_class; 5497 if (!print_class_ro32_t(c.data & ~0x3, info, is_meta_class)) 5498 return; 5499 5500 if (!is_meta_class) { 5501 outs() << "Meta Class\n"; 5502 print_class32_t(c.isa, info); 5503 } 5504 } 5505 5506 static void print_objc_class_t(struct objc_class_t *objc_class, 5507 struct DisassembleInfo *info) { 5508 uint32_t offset, left, xleft; 5509 const char *name, *p, *ivar_list; 5510 SectionRef S; 5511 int32_t i; 5512 struct objc_ivar_list_t objc_ivar_list; 5513 struct objc_ivar_t ivar; 5514 5515 outs() << "\t\t isa " << format("0x%08" PRIx32, objc_class->isa); 5516 if (info->verbose && CLS_GETINFO(objc_class, CLS_META)) { 5517 name = get_pointer_32(objc_class->isa, offset, left, S, info, true); 5518 if (name != nullptr) 5519 outs() << format(" %.*s", left, name); 5520 else 5521 outs() << " (not in an __OBJC section)"; 5522 } 5523 outs() << "\n"; 5524 5525 outs() << "\t super_class " 5526 << format("0x%08" PRIx32, objc_class->super_class); 5527 if (info->verbose) { 5528 name = get_pointer_32(objc_class->super_class, offset, left, S, info, true); 5529 if (name != nullptr) 5530 outs() << format(" %.*s", left, name); 5531 else 5532 outs() << " (not in an __OBJC section)"; 5533 } 5534 outs() << "\n"; 5535 5536 outs() << "\t\t name " << format("0x%08" PRIx32, objc_class->name); 5537 if (info->verbose) { 5538 name = get_pointer_32(objc_class->name, offset, left, S, info, true); 5539 if (name != nullptr) 5540 outs() << format(" %.*s", left, name); 5541 else 5542 outs() << " (not in an __OBJC section)"; 5543 } 5544 outs() << "\n"; 5545 5546 outs() << "\t\t version " << format("0x%08" PRIx32, objc_class->version) 5547 << "\n"; 5548 5549 outs() << "\t\t info " << format("0x%08" PRIx32, objc_class->info); 5550 if (info->verbose) { 5551 if (CLS_GETINFO(objc_class, CLS_CLASS)) 5552 outs() << " CLS_CLASS"; 5553 else if (CLS_GETINFO(objc_class, CLS_META)) 5554 outs() << " CLS_META"; 5555 } 5556 outs() << "\n"; 5557 5558 outs() << "\t instance_size " 5559 << format("0x%08" PRIx32, objc_class->instance_size) << "\n"; 5560 5561 p = get_pointer_32(objc_class->ivars, offset, left, S, info, true); 5562 outs() << "\t\t ivars " << format("0x%08" PRIx32, objc_class->ivars); 5563 if (p != nullptr) { 5564 if (left > sizeof(struct objc_ivar_list_t)) { 5565 outs() << "\n"; 5566 memcpy(&objc_ivar_list, p, sizeof(struct objc_ivar_list_t)); 5567 } else { 5568 outs() << " (entends past the end of the section)\n"; 5569 memset(&objc_ivar_list, '\0', sizeof(struct objc_ivar_list_t)); 5570 memcpy(&objc_ivar_list, p, left); 5571 } 5572 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 5573 swapStruct(objc_ivar_list); 5574 outs() << "\t\t ivar_count " << objc_ivar_list.ivar_count << "\n"; 5575 ivar_list = p + sizeof(struct objc_ivar_list_t); 5576 for (i = 0; i < objc_ivar_list.ivar_count; i++) { 5577 if ((i + 1) * sizeof(struct objc_ivar_t) > left) { 5578 outs() << "\t\t remaining ivar's extend past the of the section\n"; 5579 break; 5580 } 5581 memcpy(&ivar, ivar_list + i * sizeof(struct objc_ivar_t), 5582 sizeof(struct objc_ivar_t)); 5583 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 5584 swapStruct(ivar); 5585 5586 outs() << "\t\t\tivar_name " << format("0x%08" PRIx32, ivar.ivar_name); 5587 if (info->verbose) { 5588 name = get_pointer_32(ivar.ivar_name, offset, xleft, S, info, true); 5589 if (name != nullptr) 5590 outs() << format(" %.*s", xleft, name); 5591 else 5592 outs() << " (not in an __OBJC section)"; 5593 } 5594 outs() << "\n"; 5595 5596 outs() << "\t\t\tivar_type " << format("0x%08" PRIx32, ivar.ivar_type); 5597 if (info->verbose) { 5598 name = get_pointer_32(ivar.ivar_type, offset, xleft, S, info, true); 5599 if (name != nullptr) 5600 outs() << format(" %.*s", xleft, name); 5601 else 5602 outs() << " (not in an __OBJC section)"; 5603 } 5604 outs() << "\n"; 5605 5606 outs() << "\t\t ivar_offset " 5607 << format("0x%08" PRIx32, ivar.ivar_offset) << "\n"; 5608 } 5609 } else { 5610 outs() << " (not in an __OBJC section)\n"; 5611 } 5612 5613 outs() << "\t\t methods " << format("0x%08" PRIx32, objc_class->methodLists); 5614 if (print_method_list(objc_class->methodLists, info)) 5615 outs() << " (not in an __OBJC section)\n"; 5616 5617 outs() << "\t\t cache " << format("0x%08" PRIx32, objc_class->cache) 5618 << "\n"; 5619 5620 outs() << "\t\tprotocols " << format("0x%08" PRIx32, objc_class->protocols); 5621 if (print_protocol_list(objc_class->protocols, 16, info)) 5622 outs() << " (not in an __OBJC section)\n"; 5623 } 5624 5625 static void print_objc_objc_category_t(struct objc_category_t *objc_category, 5626 struct DisassembleInfo *info) { 5627 uint32_t offset, left; 5628 const char *name; 5629 SectionRef S; 5630 5631 outs() << "\t category name " 5632 << format("0x%08" PRIx32, objc_category->category_name); 5633 if (info->verbose) { 5634 name = get_pointer_32(objc_category->category_name, offset, left, S, info, 5635 true); 5636 if (name != nullptr) 5637 outs() << format(" %.*s", left, name); 5638 else 5639 outs() << " (not in an __OBJC section)"; 5640 } 5641 outs() << "\n"; 5642 5643 outs() << "\t\t class name " 5644 << format("0x%08" PRIx32, objc_category->class_name); 5645 if (info->verbose) { 5646 name = 5647 get_pointer_32(objc_category->class_name, offset, left, S, info, true); 5648 if (name != nullptr) 5649 outs() << format(" %.*s", left, name); 5650 else 5651 outs() << " (not in an __OBJC section)"; 5652 } 5653 outs() << "\n"; 5654 5655 outs() << "\t instance methods " 5656 << format("0x%08" PRIx32, objc_category->instance_methods); 5657 if (print_method_list(objc_category->instance_methods, info)) 5658 outs() << " (not in an __OBJC section)\n"; 5659 5660 outs() << "\t class methods " 5661 << format("0x%08" PRIx32, objc_category->class_methods); 5662 if (print_method_list(objc_category->class_methods, info)) 5663 outs() << " (not in an __OBJC section)\n"; 5664 } 5665 5666 static void print_category64_t(uint64_t p, struct DisassembleInfo *info) { 5667 struct category64_t c; 5668 const char *r; 5669 uint32_t offset, xoffset, left; 5670 SectionRef S, xS; 5671 const char *name, *sym_name; 5672 uint64_t n_value; 5673 5674 r = get_pointer_64(p, offset, left, S, info); 5675 if (r == nullptr) 5676 return; 5677 memset(&c, '\0', sizeof(struct category64_t)); 5678 if (left < sizeof(struct category64_t)) { 5679 memcpy(&c, r, left); 5680 outs() << " (category_t entends past the end of the section)\n"; 5681 } else 5682 memcpy(&c, r, sizeof(struct category64_t)); 5683 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 5684 swapStruct(c); 5685 5686 outs() << " name "; 5687 sym_name = get_symbol_64(offset + offsetof(struct category64_t, name), S, 5688 info, n_value, c.name); 5689 if (n_value != 0) { 5690 if (info->verbose && sym_name != nullptr) 5691 outs() << sym_name; 5692 else 5693 outs() << format("0x%" PRIx64, n_value); 5694 if (c.name != 0) 5695 outs() << " + " << format("0x%" PRIx64, c.name); 5696 } else 5697 outs() << format("0x%" PRIx64, c.name); 5698 name = get_pointer_64(c.name + n_value, xoffset, left, xS, info); 5699 if (name != nullptr) 5700 outs() << format(" %.*s", left, name); 5701 outs() << "\n"; 5702 5703 outs() << " cls "; 5704 sym_name = get_symbol_64(offset + offsetof(struct category64_t, cls), S, info, 5705 n_value, c.cls); 5706 if (n_value != 0) { 5707 if (info->verbose && sym_name != nullptr) 5708 outs() << sym_name; 5709 else 5710 outs() << format("0x%" PRIx64, n_value); 5711 if (c.cls != 0) 5712 outs() << " + " << format("0x%" PRIx64, c.cls); 5713 } else 5714 outs() << format("0x%" PRIx64, c.cls); 5715 outs() << "\n"; 5716 if (c.cls + n_value != 0) 5717 print_class64_t(c.cls + n_value, info); 5718 5719 outs() << " instanceMethods "; 5720 sym_name = 5721 get_symbol_64(offset + offsetof(struct category64_t, instanceMethods), S, 5722 info, n_value, c.instanceMethods); 5723 if (n_value != 0) { 5724 if (info->verbose && sym_name != nullptr) 5725 outs() << sym_name; 5726 else 5727 outs() << format("0x%" PRIx64, n_value); 5728 if (c.instanceMethods != 0) 5729 outs() << " + " << format("0x%" PRIx64, c.instanceMethods); 5730 } else 5731 outs() << format("0x%" PRIx64, c.instanceMethods); 5732 outs() << "\n"; 5733 if (c.instanceMethods + n_value != 0) 5734 print_method_list64_t(c.instanceMethods + n_value, info, ""); 5735 5736 outs() << " classMethods "; 5737 sym_name = get_symbol_64(offset + offsetof(struct category64_t, classMethods), 5738 S, info, n_value, c.classMethods); 5739 if (n_value != 0) { 5740 if (info->verbose && sym_name != nullptr) 5741 outs() << sym_name; 5742 else 5743 outs() << format("0x%" PRIx64, n_value); 5744 if (c.classMethods != 0) 5745 outs() << " + " << format("0x%" PRIx64, c.classMethods); 5746 } else 5747 outs() << format("0x%" PRIx64, c.classMethods); 5748 outs() << "\n"; 5749 if (c.classMethods + n_value != 0) 5750 print_method_list64_t(c.classMethods + n_value, info, ""); 5751 5752 outs() << " protocols "; 5753 sym_name = get_symbol_64(offset + offsetof(struct category64_t, protocols), S, 5754 info, n_value, c.protocols); 5755 if (n_value != 0) { 5756 if (info->verbose && sym_name != nullptr) 5757 outs() << sym_name; 5758 else 5759 outs() << format("0x%" PRIx64, n_value); 5760 if (c.protocols != 0) 5761 outs() << " + " << format("0x%" PRIx64, c.protocols); 5762 } else 5763 outs() << format("0x%" PRIx64, c.protocols); 5764 outs() << "\n"; 5765 if (c.protocols + n_value != 0) 5766 print_protocol_list64_t(c.protocols + n_value, info); 5767 5768 outs() << "instanceProperties "; 5769 sym_name = 5770 get_symbol_64(offset + offsetof(struct category64_t, instanceProperties), 5771 S, info, n_value, c.instanceProperties); 5772 if (n_value != 0) { 5773 if (info->verbose && sym_name != nullptr) 5774 outs() << sym_name; 5775 else 5776 outs() << format("0x%" PRIx64, n_value); 5777 if (c.instanceProperties != 0) 5778 outs() << " + " << format("0x%" PRIx64, c.instanceProperties); 5779 } else 5780 outs() << format("0x%" PRIx64, c.instanceProperties); 5781 outs() << "\n"; 5782 if (c.instanceProperties + n_value != 0) 5783 print_objc_property_list64(c.instanceProperties + n_value, info); 5784 } 5785 5786 static void print_category32_t(uint32_t p, struct DisassembleInfo *info) { 5787 struct category32_t c; 5788 const char *r; 5789 uint32_t offset, left; 5790 SectionRef S, xS; 5791 const char *name; 5792 5793 r = get_pointer_32(p, offset, left, S, info); 5794 if (r == nullptr) 5795 return; 5796 memset(&c, '\0', sizeof(struct category32_t)); 5797 if (left < sizeof(struct category32_t)) { 5798 memcpy(&c, r, left); 5799 outs() << " (category_t entends past the end of the section)\n"; 5800 } else 5801 memcpy(&c, r, sizeof(struct category32_t)); 5802 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 5803 swapStruct(c); 5804 5805 outs() << " name " << format("0x%" PRIx32, c.name); 5806 name = get_symbol_32(offset + offsetof(struct category32_t, name), S, info, 5807 c.name); 5808 if (name) 5809 outs() << " " << name; 5810 outs() << "\n"; 5811 5812 outs() << " cls " << format("0x%" PRIx32, c.cls) << "\n"; 5813 if (c.cls != 0) 5814 print_class32_t(c.cls, info); 5815 outs() << " instanceMethods " << format("0x%" PRIx32, c.instanceMethods) 5816 << "\n"; 5817 if (c.instanceMethods != 0) 5818 print_method_list32_t(c.instanceMethods, info, ""); 5819 outs() << " classMethods " << format("0x%" PRIx32, c.classMethods) 5820 << "\n"; 5821 if (c.classMethods != 0) 5822 print_method_list32_t(c.classMethods, info, ""); 5823 outs() << " protocols " << format("0x%" PRIx32, c.protocols) << "\n"; 5824 if (c.protocols != 0) 5825 print_protocol_list32_t(c.protocols, info); 5826 outs() << "instanceProperties " << format("0x%" PRIx32, c.instanceProperties) 5827 << "\n"; 5828 if (c.instanceProperties != 0) 5829 print_objc_property_list32(c.instanceProperties, info); 5830 } 5831 5832 static void print_message_refs64(SectionRef S, struct DisassembleInfo *info) { 5833 uint32_t i, left, offset, xoffset; 5834 uint64_t p, n_value; 5835 struct message_ref64 mr; 5836 const char *name, *sym_name; 5837 const char *r; 5838 SectionRef xS; 5839 5840 if (S == SectionRef()) 5841 return; 5842 5843 StringRef SectName; 5844 Expected<StringRef> SecNameOrErr = S.getName(); 5845 if (SecNameOrErr) 5846 SectName = *SecNameOrErr; 5847 else 5848 consumeError(SecNameOrErr.takeError()); 5849 5850 DataRefImpl Ref = S.getRawDataRefImpl(); 5851 StringRef SegName = info->O->getSectionFinalSegmentName(Ref); 5852 outs() << "Contents of (" << SegName << "," << SectName << ") section\n"; 5853 offset = 0; 5854 for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) { 5855 p = S.getAddress() + i; 5856 r = get_pointer_64(p, offset, left, S, info); 5857 if (r == nullptr) 5858 return; 5859 memset(&mr, '\0', sizeof(struct message_ref64)); 5860 if (left < sizeof(struct message_ref64)) { 5861 memcpy(&mr, r, left); 5862 outs() << " (message_ref entends past the end of the section)\n"; 5863 } else 5864 memcpy(&mr, r, sizeof(struct message_ref64)); 5865 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 5866 swapStruct(mr); 5867 5868 outs() << " imp "; 5869 name = get_symbol_64(offset + offsetof(struct message_ref64, imp), S, info, 5870 n_value, mr.imp); 5871 if (n_value != 0) { 5872 outs() << format("0x%" PRIx64, n_value) << " "; 5873 if (mr.imp != 0) 5874 outs() << "+ " << format("0x%" PRIx64, mr.imp) << " "; 5875 } else 5876 outs() << format("0x%" PRIx64, mr.imp) << " "; 5877 if (name != nullptr) 5878 outs() << " " << name; 5879 outs() << "\n"; 5880 5881 outs() << " sel "; 5882 sym_name = get_symbol_64(offset + offsetof(struct message_ref64, sel), S, 5883 info, n_value, mr.sel); 5884 if (n_value != 0) { 5885 if (info->verbose && sym_name != nullptr) 5886 outs() << sym_name; 5887 else 5888 outs() << format("0x%" PRIx64, n_value); 5889 if (mr.sel != 0) 5890 outs() << " + " << format("0x%" PRIx64, mr.sel); 5891 } else 5892 outs() << format("0x%" PRIx64, mr.sel); 5893 name = get_pointer_64(mr.sel + n_value, xoffset, left, xS, info); 5894 if (name != nullptr) 5895 outs() << format(" %.*s", left, name); 5896 outs() << "\n"; 5897 5898 offset += sizeof(struct message_ref64); 5899 } 5900 } 5901 5902 static void print_message_refs32(SectionRef S, struct DisassembleInfo *info) { 5903 uint32_t i, left, offset, xoffset, p; 5904 struct message_ref32 mr; 5905 const char *name, *r; 5906 SectionRef xS; 5907 5908 if (S == SectionRef()) 5909 return; 5910 5911 StringRef SectName; 5912 Expected<StringRef> SecNameOrErr = S.getName(); 5913 if (SecNameOrErr) 5914 SectName = *SecNameOrErr; 5915 else 5916 consumeError(SecNameOrErr.takeError()); 5917 5918 DataRefImpl Ref = S.getRawDataRefImpl(); 5919 StringRef SegName = info->O->getSectionFinalSegmentName(Ref); 5920 outs() << "Contents of (" << SegName << "," << SectName << ") section\n"; 5921 offset = 0; 5922 for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) { 5923 p = S.getAddress() + i; 5924 r = get_pointer_32(p, offset, left, S, info); 5925 if (r == nullptr) 5926 return; 5927 memset(&mr, '\0', sizeof(struct message_ref32)); 5928 if (left < sizeof(struct message_ref32)) { 5929 memcpy(&mr, r, left); 5930 outs() << " (message_ref entends past the end of the section)\n"; 5931 } else 5932 memcpy(&mr, r, sizeof(struct message_ref32)); 5933 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 5934 swapStruct(mr); 5935 5936 outs() << " imp " << format("0x%" PRIx32, mr.imp); 5937 name = get_symbol_32(offset + offsetof(struct message_ref32, imp), S, info, 5938 mr.imp); 5939 if (name != nullptr) 5940 outs() << " " << name; 5941 outs() << "\n"; 5942 5943 outs() << " sel " << format("0x%" PRIx32, mr.sel); 5944 name = get_pointer_32(mr.sel, xoffset, left, xS, info); 5945 if (name != nullptr) 5946 outs() << " " << name; 5947 outs() << "\n"; 5948 5949 offset += sizeof(struct message_ref32); 5950 } 5951 } 5952 5953 static void print_image_info64(SectionRef S, struct DisassembleInfo *info) { 5954 uint32_t left, offset, swift_version; 5955 uint64_t p; 5956 struct objc_image_info64 o; 5957 const char *r; 5958 5959 if (S == SectionRef()) 5960 return; 5961 5962 StringRef SectName; 5963 Expected<StringRef> SecNameOrErr = S.getName(); 5964 if (SecNameOrErr) 5965 SectName = *SecNameOrErr; 5966 else 5967 consumeError(SecNameOrErr.takeError()); 5968 5969 DataRefImpl Ref = S.getRawDataRefImpl(); 5970 StringRef SegName = info->O->getSectionFinalSegmentName(Ref); 5971 outs() << "Contents of (" << SegName << "," << SectName << ") section\n"; 5972 p = S.getAddress(); 5973 r = get_pointer_64(p, offset, left, S, info); 5974 if (r == nullptr) 5975 return; 5976 memset(&o, '\0', sizeof(struct objc_image_info64)); 5977 if (left < sizeof(struct objc_image_info64)) { 5978 memcpy(&o, r, left); 5979 outs() << " (objc_image_info entends past the end of the section)\n"; 5980 } else 5981 memcpy(&o, r, sizeof(struct objc_image_info64)); 5982 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 5983 swapStruct(o); 5984 outs() << " version " << o.version << "\n"; 5985 outs() << " flags " << format("0x%" PRIx32, o.flags); 5986 if (o.flags & OBJC_IMAGE_IS_REPLACEMENT) 5987 outs() << " OBJC_IMAGE_IS_REPLACEMENT"; 5988 if (o.flags & OBJC_IMAGE_SUPPORTS_GC) 5989 outs() << " OBJC_IMAGE_SUPPORTS_GC"; 5990 if (o.flags & OBJC_IMAGE_IS_SIMULATED) 5991 outs() << " OBJC_IMAGE_IS_SIMULATED"; 5992 if (o.flags & OBJC_IMAGE_HAS_CATEGORY_CLASS_PROPERTIES) 5993 outs() << " OBJC_IMAGE_HAS_CATEGORY_CLASS_PROPERTIES"; 5994 swift_version = (o.flags >> 8) & 0xff; 5995 if (swift_version != 0) { 5996 if (swift_version == 1) 5997 outs() << " Swift 1.0"; 5998 else if (swift_version == 2) 5999 outs() << " Swift 1.1"; 6000 else if(swift_version == 3) 6001 outs() << " Swift 2.0"; 6002 else if(swift_version == 4) 6003 outs() << " Swift 3.0"; 6004 else if(swift_version == 5) 6005 outs() << " Swift 4.0"; 6006 else if(swift_version == 6) 6007 outs() << " Swift 4.1/Swift 4.2"; 6008 else if(swift_version == 7) 6009 outs() << " Swift 5 or later"; 6010 else 6011 outs() << " unknown future Swift version (" << swift_version << ")"; 6012 } 6013 outs() << "\n"; 6014 } 6015 6016 static void print_image_info32(SectionRef S, struct DisassembleInfo *info) { 6017 uint32_t left, offset, swift_version, p; 6018 struct objc_image_info32 o; 6019 const char *r; 6020 6021 if (S == SectionRef()) 6022 return; 6023 6024 StringRef SectName; 6025 Expected<StringRef> SecNameOrErr = S.getName(); 6026 if (SecNameOrErr) 6027 SectName = *SecNameOrErr; 6028 else 6029 consumeError(SecNameOrErr.takeError()); 6030 6031 DataRefImpl Ref = S.getRawDataRefImpl(); 6032 StringRef SegName = info->O->getSectionFinalSegmentName(Ref); 6033 outs() << "Contents of (" << SegName << "," << SectName << ") section\n"; 6034 p = S.getAddress(); 6035 r = get_pointer_32(p, offset, left, S, info); 6036 if (r == nullptr) 6037 return; 6038 memset(&o, '\0', sizeof(struct objc_image_info32)); 6039 if (left < sizeof(struct objc_image_info32)) { 6040 memcpy(&o, r, left); 6041 outs() << " (objc_image_info entends past the end of the section)\n"; 6042 } else 6043 memcpy(&o, r, sizeof(struct objc_image_info32)); 6044 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 6045 swapStruct(o); 6046 outs() << " version " << o.version << "\n"; 6047 outs() << " flags " << format("0x%" PRIx32, o.flags); 6048 if (o.flags & OBJC_IMAGE_IS_REPLACEMENT) 6049 outs() << " OBJC_IMAGE_IS_REPLACEMENT"; 6050 if (o.flags & OBJC_IMAGE_SUPPORTS_GC) 6051 outs() << " OBJC_IMAGE_SUPPORTS_GC"; 6052 swift_version = (o.flags >> 8) & 0xff; 6053 if (swift_version != 0) { 6054 if (swift_version == 1) 6055 outs() << " Swift 1.0"; 6056 else if (swift_version == 2) 6057 outs() << " Swift 1.1"; 6058 else if(swift_version == 3) 6059 outs() << " Swift 2.0"; 6060 else if(swift_version == 4) 6061 outs() << " Swift 3.0"; 6062 else if(swift_version == 5) 6063 outs() << " Swift 4.0"; 6064 else if(swift_version == 6) 6065 outs() << " Swift 4.1/Swift 4.2"; 6066 else if(swift_version == 7) 6067 outs() << " Swift 5 or later"; 6068 else 6069 outs() << " unknown future Swift version (" << swift_version << ")"; 6070 } 6071 outs() << "\n"; 6072 } 6073 6074 static void print_image_info(SectionRef S, struct DisassembleInfo *info) { 6075 uint32_t left, offset, p; 6076 struct imageInfo_t o; 6077 const char *r; 6078 6079 StringRef SectName; 6080 Expected<StringRef> SecNameOrErr = S.getName(); 6081 if (SecNameOrErr) 6082 SectName = *SecNameOrErr; 6083 else 6084 consumeError(SecNameOrErr.takeError()); 6085 6086 DataRefImpl Ref = S.getRawDataRefImpl(); 6087 StringRef SegName = info->O->getSectionFinalSegmentName(Ref); 6088 outs() << "Contents of (" << SegName << "," << SectName << ") section\n"; 6089 p = S.getAddress(); 6090 r = get_pointer_32(p, offset, left, S, info); 6091 if (r == nullptr) 6092 return; 6093 memset(&o, '\0', sizeof(struct imageInfo_t)); 6094 if (left < sizeof(struct imageInfo_t)) { 6095 memcpy(&o, r, left); 6096 outs() << " (imageInfo entends past the end of the section)\n"; 6097 } else 6098 memcpy(&o, r, sizeof(struct imageInfo_t)); 6099 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 6100 swapStruct(o); 6101 outs() << " version " << o.version << "\n"; 6102 outs() << " flags " << format("0x%" PRIx32, o.flags); 6103 if (o.flags & 0x1) 6104 outs() << " F&C"; 6105 if (o.flags & 0x2) 6106 outs() << " GC"; 6107 if (o.flags & 0x4) 6108 outs() << " GC-only"; 6109 else 6110 outs() << " RR"; 6111 outs() << "\n"; 6112 } 6113 6114 static void printObjc2_64bit_MetaData(MachOObjectFile *O, bool verbose) { 6115 SymbolAddressMap AddrMap; 6116 if (verbose) 6117 CreateSymbolAddressMap(O, &AddrMap); 6118 6119 std::vector<SectionRef> Sections; 6120 for (const SectionRef &Section : O->sections()) 6121 Sections.push_back(Section); 6122 6123 struct DisassembleInfo info(O, &AddrMap, &Sections, verbose); 6124 6125 SectionRef CL = get_section(O, "__OBJC2", "__class_list"); 6126 if (CL == SectionRef()) 6127 CL = get_section(O, "__DATA", "__objc_classlist"); 6128 if (CL == SectionRef()) 6129 CL = get_section(O, "__DATA_CONST", "__objc_classlist"); 6130 if (CL == SectionRef()) 6131 CL = get_section(O, "__DATA_DIRTY", "__objc_classlist"); 6132 info.S = CL; 6133 walk_pointer_list_64("class", CL, O, &info, print_class64_t); 6134 6135 SectionRef CR = get_section(O, "__OBJC2", "__class_refs"); 6136 if (CR == SectionRef()) 6137 CR = get_section(O, "__DATA", "__objc_classrefs"); 6138 if (CR == SectionRef()) 6139 CR = get_section(O, "__DATA_CONST", "__objc_classrefs"); 6140 if (CR == SectionRef()) 6141 CR = get_section(O, "__DATA_DIRTY", "__objc_classrefs"); 6142 info.S = CR; 6143 walk_pointer_list_64("class refs", CR, O, &info, nullptr); 6144 6145 SectionRef SR = get_section(O, "__OBJC2", "__super_refs"); 6146 if (SR == SectionRef()) 6147 SR = get_section(O, "__DATA", "__objc_superrefs"); 6148 if (SR == SectionRef()) 6149 SR = get_section(O, "__DATA_CONST", "__objc_superrefs"); 6150 if (SR == SectionRef()) 6151 SR = get_section(O, "__DATA_DIRTY", "__objc_superrefs"); 6152 info.S = SR; 6153 walk_pointer_list_64("super refs", SR, O, &info, nullptr); 6154 6155 SectionRef CA = get_section(O, "__OBJC2", "__category_list"); 6156 if (CA == SectionRef()) 6157 CA = get_section(O, "__DATA", "__objc_catlist"); 6158 if (CA == SectionRef()) 6159 CA = get_section(O, "__DATA_CONST", "__objc_catlist"); 6160 if (CA == SectionRef()) 6161 CA = get_section(O, "__DATA_DIRTY", "__objc_catlist"); 6162 info.S = CA; 6163 walk_pointer_list_64("category", CA, O, &info, print_category64_t); 6164 6165 SectionRef PL = get_section(O, "__OBJC2", "__protocol_list"); 6166 if (PL == SectionRef()) 6167 PL = get_section(O, "__DATA", "__objc_protolist"); 6168 if (PL == SectionRef()) 6169 PL = get_section(O, "__DATA_CONST", "__objc_protolist"); 6170 if (PL == SectionRef()) 6171 PL = get_section(O, "__DATA_DIRTY", "__objc_protolist"); 6172 info.S = PL; 6173 walk_pointer_list_64("protocol", PL, O, &info, nullptr); 6174 6175 SectionRef MR = get_section(O, "__OBJC2", "__message_refs"); 6176 if (MR == SectionRef()) 6177 MR = get_section(O, "__DATA", "__objc_msgrefs"); 6178 if (MR == SectionRef()) 6179 MR = get_section(O, "__DATA_CONST", "__objc_msgrefs"); 6180 if (MR == SectionRef()) 6181 MR = get_section(O, "__DATA_DIRTY", "__objc_msgrefs"); 6182 info.S = MR; 6183 print_message_refs64(MR, &info); 6184 6185 SectionRef II = get_section(O, "__OBJC2", "__image_info"); 6186 if (II == SectionRef()) 6187 II = get_section(O, "__DATA", "__objc_imageinfo"); 6188 if (II == SectionRef()) 6189 II = get_section(O, "__DATA_CONST", "__objc_imageinfo"); 6190 if (II == SectionRef()) 6191 II = get_section(O, "__DATA_DIRTY", "__objc_imageinfo"); 6192 info.S = II; 6193 print_image_info64(II, &info); 6194 } 6195 6196 static void printObjc2_32bit_MetaData(MachOObjectFile *O, bool verbose) { 6197 SymbolAddressMap AddrMap; 6198 if (verbose) 6199 CreateSymbolAddressMap(O, &AddrMap); 6200 6201 std::vector<SectionRef> Sections; 6202 for (const SectionRef &Section : O->sections()) 6203 Sections.push_back(Section); 6204 6205 struct DisassembleInfo info(O, &AddrMap, &Sections, verbose); 6206 6207 SectionRef CL = get_section(O, "__OBJC2", "__class_list"); 6208 if (CL == SectionRef()) 6209 CL = get_section(O, "__DATA", "__objc_classlist"); 6210 if (CL == SectionRef()) 6211 CL = get_section(O, "__DATA_CONST", "__objc_classlist"); 6212 if (CL == SectionRef()) 6213 CL = get_section(O, "__DATA_DIRTY", "__objc_classlist"); 6214 info.S = CL; 6215 walk_pointer_list_32("class", CL, O, &info, print_class32_t); 6216 6217 SectionRef CR = get_section(O, "__OBJC2", "__class_refs"); 6218 if (CR == SectionRef()) 6219 CR = get_section(O, "__DATA", "__objc_classrefs"); 6220 if (CR == SectionRef()) 6221 CR = get_section(O, "__DATA_CONST", "__objc_classrefs"); 6222 if (CR == SectionRef()) 6223 CR = get_section(O, "__DATA_DIRTY", "__objc_classrefs"); 6224 info.S = CR; 6225 walk_pointer_list_32("class refs", CR, O, &info, nullptr); 6226 6227 SectionRef SR = get_section(O, "__OBJC2", "__super_refs"); 6228 if (SR == SectionRef()) 6229 SR = get_section(O, "__DATA", "__objc_superrefs"); 6230 if (SR == SectionRef()) 6231 SR = get_section(O, "__DATA_CONST", "__objc_superrefs"); 6232 if (SR == SectionRef()) 6233 SR = get_section(O, "__DATA_DIRTY", "__objc_superrefs"); 6234 info.S = SR; 6235 walk_pointer_list_32("super refs", SR, O, &info, nullptr); 6236 6237 SectionRef CA = get_section(O, "__OBJC2", "__category_list"); 6238 if (CA == SectionRef()) 6239 CA = get_section(O, "__DATA", "__objc_catlist"); 6240 if (CA == SectionRef()) 6241 CA = get_section(O, "__DATA_CONST", "__objc_catlist"); 6242 if (CA == SectionRef()) 6243 CA = get_section(O, "__DATA_DIRTY", "__objc_catlist"); 6244 info.S = CA; 6245 walk_pointer_list_32("category", CA, O, &info, print_category32_t); 6246 6247 SectionRef PL = get_section(O, "__OBJC2", "__protocol_list"); 6248 if (PL == SectionRef()) 6249 PL = get_section(O, "__DATA", "__objc_protolist"); 6250 if (PL == SectionRef()) 6251 PL = get_section(O, "__DATA_CONST", "__objc_protolist"); 6252 if (PL == SectionRef()) 6253 PL = get_section(O, "__DATA_DIRTY", "__objc_protolist"); 6254 info.S = PL; 6255 walk_pointer_list_32("protocol", PL, O, &info, nullptr); 6256 6257 SectionRef MR = get_section(O, "__OBJC2", "__message_refs"); 6258 if (MR == SectionRef()) 6259 MR = get_section(O, "__DATA", "__objc_msgrefs"); 6260 if (MR == SectionRef()) 6261 MR = get_section(O, "__DATA_CONST", "__objc_msgrefs"); 6262 if (MR == SectionRef()) 6263 MR = get_section(O, "__DATA_DIRTY", "__objc_msgrefs"); 6264 info.S = MR; 6265 print_message_refs32(MR, &info); 6266 6267 SectionRef II = get_section(O, "__OBJC2", "__image_info"); 6268 if (II == SectionRef()) 6269 II = get_section(O, "__DATA", "__objc_imageinfo"); 6270 if (II == SectionRef()) 6271 II = get_section(O, "__DATA_CONST", "__objc_imageinfo"); 6272 if (II == SectionRef()) 6273 II = get_section(O, "__DATA_DIRTY", "__objc_imageinfo"); 6274 info.S = II; 6275 print_image_info32(II, &info); 6276 } 6277 6278 static bool printObjc1_32bit_MetaData(MachOObjectFile *O, bool verbose) { 6279 uint32_t i, j, p, offset, xoffset, left, defs_left, def; 6280 const char *r, *name, *defs; 6281 struct objc_module_t module; 6282 SectionRef S, xS; 6283 struct objc_symtab_t symtab; 6284 struct objc_class_t objc_class; 6285 struct objc_category_t objc_category; 6286 6287 outs() << "Objective-C segment\n"; 6288 S = get_section(O, "__OBJC", "__module_info"); 6289 if (S == SectionRef()) 6290 return false; 6291 6292 SymbolAddressMap AddrMap; 6293 if (verbose) 6294 CreateSymbolAddressMap(O, &AddrMap); 6295 6296 std::vector<SectionRef> Sections; 6297 for (const SectionRef &Section : O->sections()) 6298 Sections.push_back(Section); 6299 6300 struct DisassembleInfo info(O, &AddrMap, &Sections, verbose); 6301 6302 for (i = 0; i < S.getSize(); i += sizeof(struct objc_module_t)) { 6303 p = S.getAddress() + i; 6304 r = get_pointer_32(p, offset, left, S, &info, true); 6305 if (r == nullptr) 6306 return true; 6307 memset(&module, '\0', sizeof(struct objc_module_t)); 6308 if (left < sizeof(struct objc_module_t)) { 6309 memcpy(&module, r, left); 6310 outs() << " (module extends past end of __module_info section)\n"; 6311 } else 6312 memcpy(&module, r, sizeof(struct objc_module_t)); 6313 if (O->isLittleEndian() != sys::IsLittleEndianHost) 6314 swapStruct(module); 6315 6316 outs() << "Module " << format("0x%" PRIx32, p) << "\n"; 6317 outs() << " version " << module.version << "\n"; 6318 outs() << " size " << module.size << "\n"; 6319 outs() << " name "; 6320 name = get_pointer_32(module.name, xoffset, left, xS, &info, true); 6321 if (name != nullptr) 6322 outs() << format("%.*s", left, name); 6323 else 6324 outs() << format("0x%08" PRIx32, module.name) 6325 << "(not in an __OBJC section)"; 6326 outs() << "\n"; 6327 6328 r = get_pointer_32(module.symtab, xoffset, left, xS, &info, true); 6329 if (module.symtab == 0 || r == nullptr) { 6330 outs() << " symtab " << format("0x%08" PRIx32, module.symtab) 6331 << " (not in an __OBJC section)\n"; 6332 continue; 6333 } 6334 outs() << " symtab " << format("0x%08" PRIx32, module.symtab) << "\n"; 6335 memset(&symtab, '\0', sizeof(struct objc_symtab_t)); 6336 defs_left = 0; 6337 defs = nullptr; 6338 if (left < sizeof(struct objc_symtab_t)) { 6339 memcpy(&symtab, r, left); 6340 outs() << "\tsymtab extends past end of an __OBJC section)\n"; 6341 } else { 6342 memcpy(&symtab, r, sizeof(struct objc_symtab_t)); 6343 if (left > sizeof(struct objc_symtab_t)) { 6344 defs_left = left - sizeof(struct objc_symtab_t); 6345 defs = r + sizeof(struct objc_symtab_t); 6346 } 6347 } 6348 if (O->isLittleEndian() != sys::IsLittleEndianHost) 6349 swapStruct(symtab); 6350 6351 outs() << "\tsel_ref_cnt " << symtab.sel_ref_cnt << "\n"; 6352 r = get_pointer_32(symtab.refs, xoffset, left, xS, &info, true); 6353 outs() << "\trefs " << format("0x%08" PRIx32, symtab.refs); 6354 if (r == nullptr) 6355 outs() << " (not in an __OBJC section)"; 6356 outs() << "\n"; 6357 outs() << "\tcls_def_cnt " << symtab.cls_def_cnt << "\n"; 6358 outs() << "\tcat_def_cnt " << symtab.cat_def_cnt << "\n"; 6359 if (symtab.cls_def_cnt > 0) 6360 outs() << "\tClass Definitions\n"; 6361 for (j = 0; j < symtab.cls_def_cnt; j++) { 6362 if ((j + 1) * sizeof(uint32_t) > defs_left) { 6363 outs() << "\t(remaining class defs entries entends past the end of the " 6364 << "section)\n"; 6365 break; 6366 } 6367 memcpy(&def, defs + j * sizeof(uint32_t), sizeof(uint32_t)); 6368 if (O->isLittleEndian() != sys::IsLittleEndianHost) 6369 sys::swapByteOrder(def); 6370 6371 r = get_pointer_32(def, xoffset, left, xS, &info, true); 6372 outs() << "\tdefs[" << j << "] " << format("0x%08" PRIx32, def); 6373 if (r != nullptr) { 6374 if (left > sizeof(struct objc_class_t)) { 6375 outs() << "\n"; 6376 memcpy(&objc_class, r, sizeof(struct objc_class_t)); 6377 } else { 6378 outs() << " (entends past the end of the section)\n"; 6379 memset(&objc_class, '\0', sizeof(struct objc_class_t)); 6380 memcpy(&objc_class, r, left); 6381 } 6382 if (O->isLittleEndian() != sys::IsLittleEndianHost) 6383 swapStruct(objc_class); 6384 print_objc_class_t(&objc_class, &info); 6385 } else { 6386 outs() << "(not in an __OBJC section)\n"; 6387 } 6388 6389 if (CLS_GETINFO(&objc_class, CLS_CLASS)) { 6390 outs() << "\tMeta Class"; 6391 r = get_pointer_32(objc_class.isa, xoffset, left, xS, &info, true); 6392 if (r != nullptr) { 6393 if (left > sizeof(struct objc_class_t)) { 6394 outs() << "\n"; 6395 memcpy(&objc_class, r, sizeof(struct objc_class_t)); 6396 } else { 6397 outs() << " (entends past the end of the section)\n"; 6398 memset(&objc_class, '\0', sizeof(struct objc_class_t)); 6399 memcpy(&objc_class, r, left); 6400 } 6401 if (O->isLittleEndian() != sys::IsLittleEndianHost) 6402 swapStruct(objc_class); 6403 print_objc_class_t(&objc_class, &info); 6404 } else { 6405 outs() << "(not in an __OBJC section)\n"; 6406 } 6407 } 6408 } 6409 if (symtab.cat_def_cnt > 0) 6410 outs() << "\tCategory Definitions\n"; 6411 for (j = 0; j < symtab.cat_def_cnt; j++) { 6412 if ((j + symtab.cls_def_cnt + 1) * sizeof(uint32_t) > defs_left) { 6413 outs() << "\t(remaining category defs entries entends past the end of " 6414 << "the section)\n"; 6415 break; 6416 } 6417 memcpy(&def, defs + (j + symtab.cls_def_cnt) * sizeof(uint32_t), 6418 sizeof(uint32_t)); 6419 if (O->isLittleEndian() != sys::IsLittleEndianHost) 6420 sys::swapByteOrder(def); 6421 6422 r = get_pointer_32(def, xoffset, left, xS, &info, true); 6423 outs() << "\tdefs[" << j + symtab.cls_def_cnt << "] " 6424 << format("0x%08" PRIx32, def); 6425 if (r != nullptr) { 6426 if (left > sizeof(struct objc_category_t)) { 6427 outs() << "\n"; 6428 memcpy(&objc_category, r, sizeof(struct objc_category_t)); 6429 } else { 6430 outs() << " (entends past the end of the section)\n"; 6431 memset(&objc_category, '\0', sizeof(struct objc_category_t)); 6432 memcpy(&objc_category, r, left); 6433 } 6434 if (O->isLittleEndian() != sys::IsLittleEndianHost) 6435 swapStruct(objc_category); 6436 print_objc_objc_category_t(&objc_category, &info); 6437 } else { 6438 outs() << "(not in an __OBJC section)\n"; 6439 } 6440 } 6441 } 6442 const SectionRef II = get_section(O, "__OBJC", "__image_info"); 6443 if (II != SectionRef()) 6444 print_image_info(II, &info); 6445 6446 return true; 6447 } 6448 6449 static void DumpProtocolSection(MachOObjectFile *O, const char *sect, 6450 uint32_t size, uint32_t addr) { 6451 SymbolAddressMap AddrMap; 6452 CreateSymbolAddressMap(O, &AddrMap); 6453 6454 std::vector<SectionRef> Sections; 6455 for (const SectionRef &Section : O->sections()) 6456 Sections.push_back(Section); 6457 6458 struct DisassembleInfo info(O, &AddrMap, &Sections, true); 6459 6460 const char *p; 6461 struct objc_protocol_t protocol; 6462 uint32_t left, paddr; 6463 for (p = sect; p < sect + size; p += sizeof(struct objc_protocol_t)) { 6464 memset(&protocol, '\0', sizeof(struct objc_protocol_t)); 6465 left = size - (p - sect); 6466 if (left < sizeof(struct objc_protocol_t)) { 6467 outs() << "Protocol extends past end of __protocol section\n"; 6468 memcpy(&protocol, p, left); 6469 } else 6470 memcpy(&protocol, p, sizeof(struct objc_protocol_t)); 6471 if (O->isLittleEndian() != sys::IsLittleEndianHost) 6472 swapStruct(protocol); 6473 paddr = addr + (p - sect); 6474 outs() << "Protocol " << format("0x%" PRIx32, paddr); 6475 if (print_protocol(paddr, 0, &info)) 6476 outs() << "(not in an __OBJC section)\n"; 6477 } 6478 } 6479 6480 #ifdef HAVE_LIBXAR 6481 static inline void swapStruct(struct xar_header &xar) { 6482 sys::swapByteOrder(xar.magic); 6483 sys::swapByteOrder(xar.size); 6484 sys::swapByteOrder(xar.version); 6485 sys::swapByteOrder(xar.toc_length_compressed); 6486 sys::swapByteOrder(xar.toc_length_uncompressed); 6487 sys::swapByteOrder(xar.cksum_alg); 6488 } 6489 6490 static void PrintModeVerbose(uint32_t mode) { 6491 switch(mode & S_IFMT){ 6492 case S_IFDIR: 6493 outs() << "d"; 6494 break; 6495 case S_IFCHR: 6496 outs() << "c"; 6497 break; 6498 case S_IFBLK: 6499 outs() << "b"; 6500 break; 6501 case S_IFREG: 6502 outs() << "-"; 6503 break; 6504 case S_IFLNK: 6505 outs() << "l"; 6506 break; 6507 case S_IFSOCK: 6508 outs() << "s"; 6509 break; 6510 default: 6511 outs() << "?"; 6512 break; 6513 } 6514 6515 /* owner permissions */ 6516 if(mode & S_IREAD) 6517 outs() << "r"; 6518 else 6519 outs() << "-"; 6520 if(mode & S_IWRITE) 6521 outs() << "w"; 6522 else 6523 outs() << "-"; 6524 if(mode & S_ISUID) 6525 outs() << "s"; 6526 else if(mode & S_IEXEC) 6527 outs() << "x"; 6528 else 6529 outs() << "-"; 6530 6531 /* group permissions */ 6532 if(mode & (S_IREAD >> 3)) 6533 outs() << "r"; 6534 else 6535 outs() << "-"; 6536 if(mode & (S_IWRITE >> 3)) 6537 outs() << "w"; 6538 else 6539 outs() << "-"; 6540 if(mode & S_ISGID) 6541 outs() << "s"; 6542 else if(mode & (S_IEXEC >> 3)) 6543 outs() << "x"; 6544 else 6545 outs() << "-"; 6546 6547 /* other permissions */ 6548 if(mode & (S_IREAD >> 6)) 6549 outs() << "r"; 6550 else 6551 outs() << "-"; 6552 if(mode & (S_IWRITE >> 6)) 6553 outs() << "w"; 6554 else 6555 outs() << "-"; 6556 if(mode & S_ISVTX) 6557 outs() << "t"; 6558 else if(mode & (S_IEXEC >> 6)) 6559 outs() << "x"; 6560 else 6561 outs() << "-"; 6562 } 6563 6564 static void PrintXarFilesSummary(const char *XarFilename, xar_t xar) { 6565 xar_file_t xf; 6566 const char *key, *type, *mode, *user, *group, *size, *mtime, *name, *m; 6567 char *endp; 6568 uint32_t mode_value; 6569 6570 ScopedXarIter xi; 6571 if (!xi) { 6572 WithColor::error(errs(), "llvm-objdump") 6573 << "can't obtain an xar iterator for xar archive " << XarFilename 6574 << "\n"; 6575 return; 6576 } 6577 6578 // Go through the xar's files. 6579 for (xf = xar_file_first(xar, xi); xf; xf = xar_file_next(xi)) { 6580 ScopedXarIter xp; 6581 if(!xp){ 6582 WithColor::error(errs(), "llvm-objdump") 6583 << "can't obtain an xar iterator for xar archive " << XarFilename 6584 << "\n"; 6585 return; 6586 } 6587 type = nullptr; 6588 mode = nullptr; 6589 user = nullptr; 6590 group = nullptr; 6591 size = nullptr; 6592 mtime = nullptr; 6593 name = nullptr; 6594 for(key = xar_prop_first(xf, xp); key; key = xar_prop_next(xp)){ 6595 const char *val = nullptr; 6596 xar_prop_get(xf, key, &val); 6597 #if 0 // Useful for debugging. 6598 outs() << "key: " << key << " value: " << val << "\n"; 6599 #endif 6600 if(strcmp(key, "type") == 0) 6601 type = val; 6602 if(strcmp(key, "mode") == 0) 6603 mode = val; 6604 if(strcmp(key, "user") == 0) 6605 user = val; 6606 if(strcmp(key, "group") == 0) 6607 group = val; 6608 if(strcmp(key, "data/size") == 0) 6609 size = val; 6610 if(strcmp(key, "mtime") == 0) 6611 mtime = val; 6612 if(strcmp(key, "name") == 0) 6613 name = val; 6614 } 6615 if(mode != nullptr){ 6616 mode_value = strtoul(mode, &endp, 8); 6617 if(*endp != '\0') 6618 outs() << "(mode: \"" << mode << "\" contains non-octal chars) "; 6619 if(strcmp(type, "file") == 0) 6620 mode_value |= S_IFREG; 6621 PrintModeVerbose(mode_value); 6622 outs() << " "; 6623 } 6624 if(user != nullptr) 6625 outs() << format("%10s/", user); 6626 if(group != nullptr) 6627 outs() << format("%-10s ", group); 6628 if(size != nullptr) 6629 outs() << format("%7s ", size); 6630 if(mtime != nullptr){ 6631 for(m = mtime; *m != 'T' && *m != '\0'; m++) 6632 outs() << *m; 6633 if(*m == 'T') 6634 m++; 6635 outs() << " "; 6636 for( ; *m != 'Z' && *m != '\0'; m++) 6637 outs() << *m; 6638 outs() << " "; 6639 } 6640 if(name != nullptr) 6641 outs() << name; 6642 outs() << "\n"; 6643 } 6644 } 6645 6646 static void DumpBitcodeSection(MachOObjectFile *O, const char *sect, 6647 uint32_t size, bool verbose, 6648 bool PrintXarHeader, bool PrintXarFileHeaders, 6649 std::string XarMemberName) { 6650 if(size < sizeof(struct xar_header)) { 6651 outs() << "size of (__LLVM,__bundle) section too small (smaller than size " 6652 "of struct xar_header)\n"; 6653 return; 6654 } 6655 struct xar_header XarHeader; 6656 memcpy(&XarHeader, sect, sizeof(struct xar_header)); 6657 if (sys::IsLittleEndianHost) 6658 swapStruct(XarHeader); 6659 if (PrintXarHeader) { 6660 if (!XarMemberName.empty()) 6661 outs() << "In xar member " << XarMemberName << ": "; 6662 else 6663 outs() << "For (__LLVM,__bundle) section: "; 6664 outs() << "xar header\n"; 6665 if (XarHeader.magic == XAR_HEADER_MAGIC) 6666 outs() << " magic XAR_HEADER_MAGIC\n"; 6667 else 6668 outs() << " magic " 6669 << format_hex(XarHeader.magic, 10, true) 6670 << " (not XAR_HEADER_MAGIC)\n"; 6671 outs() << " size " << XarHeader.size << "\n"; 6672 outs() << " version " << XarHeader.version << "\n"; 6673 outs() << " toc_length_compressed " << XarHeader.toc_length_compressed 6674 << "\n"; 6675 outs() << "toc_length_uncompressed " << XarHeader.toc_length_uncompressed 6676 << "\n"; 6677 outs() << " cksum_alg "; 6678 switch (XarHeader.cksum_alg) { 6679 case XAR_CKSUM_NONE: 6680 outs() << "XAR_CKSUM_NONE\n"; 6681 break; 6682 case XAR_CKSUM_SHA1: 6683 outs() << "XAR_CKSUM_SHA1\n"; 6684 break; 6685 case XAR_CKSUM_MD5: 6686 outs() << "XAR_CKSUM_MD5\n"; 6687 break; 6688 #ifdef XAR_CKSUM_SHA256 6689 case XAR_CKSUM_SHA256: 6690 outs() << "XAR_CKSUM_SHA256\n"; 6691 break; 6692 #endif 6693 #ifdef XAR_CKSUM_SHA512 6694 case XAR_CKSUM_SHA512: 6695 outs() << "XAR_CKSUM_SHA512\n"; 6696 break; 6697 #endif 6698 default: 6699 outs() << XarHeader.cksum_alg << "\n"; 6700 } 6701 } 6702 6703 SmallString<128> XarFilename; 6704 int FD; 6705 std::error_code XarEC = 6706 sys::fs::createTemporaryFile("llvm-objdump", "xar", FD, XarFilename); 6707 if (XarEC) { 6708 WithColor::error(errs(), "llvm-objdump") << XarEC.message() << "\n"; 6709 return; 6710 } 6711 ToolOutputFile XarFile(XarFilename, FD); 6712 raw_fd_ostream &XarOut = XarFile.os(); 6713 StringRef XarContents(sect, size); 6714 XarOut << XarContents; 6715 XarOut.close(); 6716 if (XarOut.has_error()) 6717 return; 6718 6719 ScopedXarFile xar(XarFilename.c_str(), READ); 6720 if (!xar) { 6721 WithColor::error(errs(), "llvm-objdump") 6722 << "can't create temporary xar archive " << XarFilename << "\n"; 6723 return; 6724 } 6725 6726 SmallString<128> TocFilename; 6727 std::error_code TocEC = 6728 sys::fs::createTemporaryFile("llvm-objdump", "toc", TocFilename); 6729 if (TocEC) { 6730 WithColor::error(errs(), "llvm-objdump") << TocEC.message() << "\n"; 6731 return; 6732 } 6733 xar_serialize(xar, TocFilename.c_str()); 6734 6735 if (PrintXarFileHeaders) { 6736 if (!XarMemberName.empty()) 6737 outs() << "In xar member " << XarMemberName << ": "; 6738 else 6739 outs() << "For (__LLVM,__bundle) section: "; 6740 outs() << "xar archive files:\n"; 6741 PrintXarFilesSummary(XarFilename.c_str(), xar); 6742 } 6743 6744 ErrorOr<std::unique_ptr<MemoryBuffer>> FileOrErr = 6745 MemoryBuffer::getFileOrSTDIN(TocFilename.c_str()); 6746 if (std::error_code EC = FileOrErr.getError()) { 6747 WithColor::error(errs(), "llvm-objdump") << EC.message() << "\n"; 6748 return; 6749 } 6750 std::unique_ptr<MemoryBuffer> &Buffer = FileOrErr.get(); 6751 6752 if (!XarMemberName.empty()) 6753 outs() << "In xar member " << XarMemberName << ": "; 6754 else 6755 outs() << "For (__LLVM,__bundle) section: "; 6756 outs() << "xar table of contents:\n"; 6757 outs() << Buffer->getBuffer() << "\n"; 6758 6759 // TODO: Go through the xar's files. 6760 ScopedXarIter xi; 6761 if(!xi){ 6762 WithColor::error(errs(), "llvm-objdump") 6763 << "can't obtain an xar iterator for xar archive " 6764 << XarFilename.c_str() << "\n"; 6765 return; 6766 } 6767 for(xar_file_t xf = xar_file_first(xar, xi); xf; xf = xar_file_next(xi)){ 6768 const char *key; 6769 const char *member_name, *member_type, *member_size_string; 6770 size_t member_size; 6771 6772 ScopedXarIter xp; 6773 if(!xp){ 6774 WithColor::error(errs(), "llvm-objdump") 6775 << "can't obtain an xar iterator for xar archive " 6776 << XarFilename.c_str() << "\n"; 6777 return; 6778 } 6779 member_name = NULL; 6780 member_type = NULL; 6781 member_size_string = NULL; 6782 for(key = xar_prop_first(xf, xp); key; key = xar_prop_next(xp)){ 6783 const char *val = nullptr; 6784 xar_prop_get(xf, key, &val); 6785 #if 0 // Useful for debugging. 6786 outs() << "key: " << key << " value: " << val << "\n"; 6787 #endif 6788 if (strcmp(key, "name") == 0) 6789 member_name = val; 6790 if (strcmp(key, "type") == 0) 6791 member_type = val; 6792 if (strcmp(key, "data/size") == 0) 6793 member_size_string = val; 6794 } 6795 /* 6796 * If we find a file with a name, date/size and type properties 6797 * and with the type being "file" see if that is a xar file. 6798 */ 6799 if (member_name != NULL && member_type != NULL && 6800 strcmp(member_type, "file") == 0 && 6801 member_size_string != NULL){ 6802 // Extract the file into a buffer. 6803 char *endptr; 6804 member_size = strtoul(member_size_string, &endptr, 10); 6805 if (*endptr == '\0' && member_size != 0) { 6806 char *buffer; 6807 if (xar_extract_tobuffersz(xar, xf, &buffer, &member_size) == 0) { 6808 #if 0 // Useful for debugging. 6809 outs() << "xar member: " << member_name << " extracted\n"; 6810 #endif 6811 // Set the XarMemberName we want to see printed in the header. 6812 std::string OldXarMemberName; 6813 // If XarMemberName is already set this is nested. So 6814 // save the old name and create the nested name. 6815 if (!XarMemberName.empty()) { 6816 OldXarMemberName = XarMemberName; 6817 XarMemberName = 6818 (Twine("[") + XarMemberName + "]" + member_name).str(); 6819 } else { 6820 OldXarMemberName = ""; 6821 XarMemberName = member_name; 6822 } 6823 // See if this is could be a xar file (nested). 6824 if (member_size >= sizeof(struct xar_header)) { 6825 #if 0 // Useful for debugging. 6826 outs() << "could be a xar file: " << member_name << "\n"; 6827 #endif 6828 memcpy((char *)&XarHeader, buffer, sizeof(struct xar_header)); 6829 if (sys::IsLittleEndianHost) 6830 swapStruct(XarHeader); 6831 if (XarHeader.magic == XAR_HEADER_MAGIC) 6832 DumpBitcodeSection(O, buffer, member_size, verbose, 6833 PrintXarHeader, PrintXarFileHeaders, 6834 XarMemberName); 6835 } 6836 XarMemberName = OldXarMemberName; 6837 delete buffer; 6838 } 6839 } 6840 } 6841 } 6842 } 6843 #endif // defined(HAVE_LIBXAR) 6844 6845 static void printObjcMetaData(MachOObjectFile *O, bool verbose) { 6846 if (O->is64Bit()) 6847 printObjc2_64bit_MetaData(O, verbose); 6848 else { 6849 MachO::mach_header H; 6850 H = O->getHeader(); 6851 if (H.cputype == MachO::CPU_TYPE_ARM) 6852 printObjc2_32bit_MetaData(O, verbose); 6853 else { 6854 // This is the 32-bit non-arm cputype case. Which is normally 6855 // the first Objective-C ABI. But it may be the case of a 6856 // binary for the iOS simulator which is the second Objective-C 6857 // ABI. In that case printObjc1_32bit_MetaData() will determine that 6858 // and return false. 6859 if (!printObjc1_32bit_MetaData(O, verbose)) 6860 printObjc2_32bit_MetaData(O, verbose); 6861 } 6862 } 6863 } 6864 6865 // GuessLiteralPointer returns a string which for the item in the Mach-O file 6866 // for the address passed in as ReferenceValue for printing as a comment with 6867 // the instruction and also returns the corresponding type of that item 6868 // indirectly through ReferenceType. 6869 // 6870 // If ReferenceValue is an address of literal cstring then a pointer to the 6871 // cstring is returned and ReferenceType is set to 6872 // LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr . 6873 // 6874 // If ReferenceValue is an address of an Objective-C CFString, Selector ref or 6875 // Class ref that name is returned and the ReferenceType is set accordingly. 6876 // 6877 // Lastly, literals which are Symbol address in a literal pool are looked for 6878 // and if found the symbol name is returned and ReferenceType is set to 6879 // LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr . 6880 // 6881 // If there is no item in the Mach-O file for the address passed in as 6882 // ReferenceValue nullptr is returned and ReferenceType is unchanged. 6883 static const char *GuessLiteralPointer(uint64_t ReferenceValue, 6884 uint64_t ReferencePC, 6885 uint64_t *ReferenceType, 6886 struct DisassembleInfo *info) { 6887 // First see if there is an external relocation entry at the ReferencePC. 6888 if (info->O->getHeader().filetype == MachO::MH_OBJECT) { 6889 uint64_t sect_addr = info->S.getAddress(); 6890 uint64_t sect_offset = ReferencePC - sect_addr; 6891 bool reloc_found = false; 6892 DataRefImpl Rel; 6893 MachO::any_relocation_info RE; 6894 bool isExtern = false; 6895 SymbolRef Symbol; 6896 for (const RelocationRef &Reloc : info->S.relocations()) { 6897 uint64_t RelocOffset = Reloc.getOffset(); 6898 if (RelocOffset == sect_offset) { 6899 Rel = Reloc.getRawDataRefImpl(); 6900 RE = info->O->getRelocation(Rel); 6901 if (info->O->isRelocationScattered(RE)) 6902 continue; 6903 isExtern = info->O->getPlainRelocationExternal(RE); 6904 if (isExtern) { 6905 symbol_iterator RelocSym = Reloc.getSymbol(); 6906 Symbol = *RelocSym; 6907 } 6908 reloc_found = true; 6909 break; 6910 } 6911 } 6912 // If there is an external relocation entry for a symbol in a section 6913 // then used that symbol's value for the value of the reference. 6914 if (reloc_found && isExtern) { 6915 if (info->O->getAnyRelocationPCRel(RE)) { 6916 unsigned Type = info->O->getAnyRelocationType(RE); 6917 if (Type == MachO::X86_64_RELOC_SIGNED) { 6918 ReferenceValue = cantFail(Symbol.getValue()); 6919 } 6920 } 6921 } 6922 } 6923 6924 // Look for literals such as Objective-C CFStrings refs, Selector refs, 6925 // Message refs and Class refs. 6926 bool classref, selref, msgref, cfstring; 6927 uint64_t pointer_value = GuessPointerPointer(ReferenceValue, info, classref, 6928 selref, msgref, cfstring); 6929 if (classref && pointer_value == 0) { 6930 // Note the ReferenceValue is a pointer into the __objc_classrefs section. 6931 // And the pointer_value in that section is typically zero as it will be 6932 // set by dyld as part of the "bind information". 6933 const char *name = get_dyld_bind_info_symbolname(ReferenceValue, info); 6934 if (name != nullptr) { 6935 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref; 6936 const char *class_name = strrchr(name, '$'); 6937 if (class_name != nullptr && class_name[1] == '_' && 6938 class_name[2] != '\0') { 6939 info->class_name = class_name + 2; 6940 return name; 6941 } 6942 } 6943 } 6944 6945 if (classref) { 6946 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref; 6947 const char *name = 6948 get_objc2_64bit_class_name(pointer_value, ReferenceValue, info); 6949 if (name != nullptr) 6950 info->class_name = name; 6951 else 6952 name = "bad class ref"; 6953 return name; 6954 } 6955 6956 if (cfstring) { 6957 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_CFString_Ref; 6958 const char *name = get_objc2_64bit_cfstring_name(ReferenceValue, info); 6959 return name; 6960 } 6961 6962 if (selref && pointer_value == 0) 6963 pointer_value = get_objc2_64bit_selref(ReferenceValue, info); 6964 6965 if (pointer_value != 0) 6966 ReferenceValue = pointer_value; 6967 6968 const char *name = GuessCstringPointer(ReferenceValue, info); 6969 if (name) { 6970 if (pointer_value != 0 && selref) { 6971 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Selector_Ref; 6972 info->selector_name = name; 6973 } else if (pointer_value != 0 && msgref) { 6974 info->class_name = nullptr; 6975 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message_Ref; 6976 info->selector_name = name; 6977 } else 6978 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr; 6979 return name; 6980 } 6981 6982 // Lastly look for an indirect symbol with this ReferenceValue which is in 6983 // a literal pool. If found return that symbol name. 6984 name = GuessIndirectSymbol(ReferenceValue, info); 6985 if (name) { 6986 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr; 6987 return name; 6988 } 6989 6990 return nullptr; 6991 } 6992 6993 // SymbolizerSymbolLookUp is the symbol lookup function passed when creating 6994 // the Symbolizer. It looks up the ReferenceValue using the info passed via the 6995 // pointer to the struct DisassembleInfo that was passed when MCSymbolizer 6996 // is created and returns the symbol name that matches the ReferenceValue or 6997 // nullptr if none. The ReferenceType is passed in for the IN type of 6998 // reference the instruction is making from the values in defined in the header 6999 // "llvm-c/Disassembler.h". On return the ReferenceType can set to a specific 7000 // Out type and the ReferenceName will also be set which is added as a comment 7001 // to the disassembled instruction. 7002 // 7003 // If the symbol name is a C++ mangled name then the demangled name is 7004 // returned through ReferenceName and ReferenceType is set to 7005 // LLVMDisassembler_ReferenceType_DeMangled_Name . 7006 // 7007 // When this is called to get a symbol name for a branch target then the 7008 // ReferenceType will be LLVMDisassembler_ReferenceType_In_Branch and then 7009 // SymbolValue will be looked for in the indirect symbol table to determine if 7010 // it is an address for a symbol stub. If so then the symbol name for that 7011 // stub is returned indirectly through ReferenceName and then ReferenceType is 7012 // set to LLVMDisassembler_ReferenceType_Out_SymbolStub. 7013 // 7014 // When this is called with an value loaded via a PC relative load then 7015 // ReferenceType will be LLVMDisassembler_ReferenceType_In_PCrel_Load then the 7016 // SymbolValue is checked to be an address of literal pointer, symbol pointer, 7017 // or an Objective-C meta data reference. If so the output ReferenceType is 7018 // set to correspond to that as well as setting the ReferenceName. 7019 static const char *SymbolizerSymbolLookUp(void *DisInfo, 7020 uint64_t ReferenceValue, 7021 uint64_t *ReferenceType, 7022 uint64_t ReferencePC, 7023 const char **ReferenceName) { 7024 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo; 7025 // If no verbose symbolic information is wanted then just return nullptr. 7026 if (!info->verbose) { 7027 *ReferenceName = nullptr; 7028 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None; 7029 return nullptr; 7030 } 7031 7032 const char *SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap); 7033 7034 if (*ReferenceType == LLVMDisassembler_ReferenceType_In_Branch) { 7035 *ReferenceName = GuessIndirectSymbol(ReferenceValue, info); 7036 if (*ReferenceName != nullptr) { 7037 method_reference(info, ReferenceType, ReferenceName); 7038 if (*ReferenceType != LLVMDisassembler_ReferenceType_Out_Objc_Message) 7039 *ReferenceType = LLVMDisassembler_ReferenceType_Out_SymbolStub; 7040 } else if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) { 7041 if (info->demangled_name != nullptr) 7042 free(info->demangled_name); 7043 int status; 7044 info->demangled_name = 7045 itaniumDemangle(SymbolName + 1, nullptr, nullptr, &status); 7046 if (info->demangled_name != nullptr) { 7047 *ReferenceName = info->demangled_name; 7048 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name; 7049 } else 7050 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None; 7051 } else 7052 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None; 7053 } else if (*ReferenceType == LLVMDisassembler_ReferenceType_In_PCrel_Load) { 7054 *ReferenceName = 7055 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info); 7056 if (*ReferenceName) 7057 method_reference(info, ReferenceType, ReferenceName); 7058 else 7059 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None; 7060 // If this is arm64 and the reference is an adrp instruction save the 7061 // instruction, passed in ReferenceValue and the address of the instruction 7062 // for use later if we see and add immediate instruction. 7063 } else if (info->O->getArch() == Triple::aarch64 && 7064 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADRP) { 7065 info->adrp_inst = ReferenceValue; 7066 info->adrp_addr = ReferencePC; 7067 SymbolName = nullptr; 7068 *ReferenceName = nullptr; 7069 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None; 7070 // If this is arm64 and reference is an add immediate instruction and we 7071 // have 7072 // seen an adrp instruction just before it and the adrp's Xd register 7073 // matches 7074 // this add's Xn register reconstruct the value being referenced and look to 7075 // see if it is a literal pointer. Note the add immediate instruction is 7076 // passed in ReferenceValue. 7077 } else if (info->O->getArch() == Triple::aarch64 && 7078 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADDXri && 7079 ReferencePC - 4 == info->adrp_addr && 7080 (info->adrp_inst & 0x9f000000) == 0x90000000 && 7081 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) { 7082 uint32_t addxri_inst; 7083 uint64_t adrp_imm, addxri_imm; 7084 7085 adrp_imm = 7086 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3); 7087 if (info->adrp_inst & 0x0200000) 7088 adrp_imm |= 0xfffffffffc000000LL; 7089 7090 addxri_inst = ReferenceValue; 7091 addxri_imm = (addxri_inst >> 10) & 0xfff; 7092 if (((addxri_inst >> 22) & 0x3) == 1) 7093 addxri_imm <<= 12; 7094 7095 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) + 7096 (adrp_imm << 12) + addxri_imm; 7097 7098 *ReferenceName = 7099 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info); 7100 if (*ReferenceName == nullptr) 7101 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None; 7102 // If this is arm64 and the reference is a load register instruction and we 7103 // have seen an adrp instruction just before it and the adrp's Xd register 7104 // matches this add's Xn register reconstruct the value being referenced and 7105 // look to see if it is a literal pointer. Note the load register 7106 // instruction is passed in ReferenceValue. 7107 } else if (info->O->getArch() == Triple::aarch64 && 7108 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXui && 7109 ReferencePC - 4 == info->adrp_addr && 7110 (info->adrp_inst & 0x9f000000) == 0x90000000 && 7111 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) { 7112 uint32_t ldrxui_inst; 7113 uint64_t adrp_imm, ldrxui_imm; 7114 7115 adrp_imm = 7116 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3); 7117 if (info->adrp_inst & 0x0200000) 7118 adrp_imm |= 0xfffffffffc000000LL; 7119 7120 ldrxui_inst = ReferenceValue; 7121 ldrxui_imm = (ldrxui_inst >> 10) & 0xfff; 7122 7123 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) + 7124 (adrp_imm << 12) + (ldrxui_imm << 3); 7125 7126 *ReferenceName = 7127 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info); 7128 if (*ReferenceName == nullptr) 7129 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None; 7130 } 7131 // If this arm64 and is an load register (PC-relative) instruction the 7132 // ReferenceValue is the PC plus the immediate value. 7133 else if (info->O->getArch() == Triple::aarch64 && 7134 (*ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXl || 7135 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADR)) { 7136 *ReferenceName = 7137 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info); 7138 if (*ReferenceName == nullptr) 7139 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None; 7140 } else if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) { 7141 if (info->demangled_name != nullptr) 7142 free(info->demangled_name); 7143 int status; 7144 info->demangled_name = 7145 itaniumDemangle(SymbolName + 1, nullptr, nullptr, &status); 7146 if (info->demangled_name != nullptr) { 7147 *ReferenceName = info->demangled_name; 7148 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name; 7149 } 7150 } 7151 else { 7152 *ReferenceName = nullptr; 7153 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None; 7154 } 7155 7156 return SymbolName; 7157 } 7158 7159 /// Emits the comments that are stored in the CommentStream. 7160 /// Each comment in the CommentStream must end with a newline. 7161 static void emitComments(raw_svector_ostream &CommentStream, 7162 SmallString<128> &CommentsToEmit, 7163 formatted_raw_ostream &FormattedOS, 7164 const MCAsmInfo &MAI) { 7165 // Flush the stream before taking its content. 7166 StringRef Comments = CommentsToEmit.str(); 7167 // Get the default information for printing a comment. 7168 StringRef CommentBegin = MAI.getCommentString(); 7169 unsigned CommentColumn = MAI.getCommentColumn(); 7170 bool IsFirst = true; 7171 while (!Comments.empty()) { 7172 if (!IsFirst) 7173 FormattedOS << '\n'; 7174 // Emit a line of comments. 7175 FormattedOS.PadToColumn(CommentColumn); 7176 size_t Position = Comments.find('\n'); 7177 FormattedOS << CommentBegin << ' ' << Comments.substr(0, Position); 7178 // Move after the newline character. 7179 Comments = Comments.substr(Position + 1); 7180 IsFirst = false; 7181 } 7182 FormattedOS.flush(); 7183 7184 // Tell the comment stream that the vector changed underneath it. 7185 CommentsToEmit.clear(); 7186 } 7187 7188 static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF, 7189 StringRef DisSegName, StringRef DisSectName) { 7190 const char *McpuDefault = nullptr; 7191 const Target *ThumbTarget = nullptr; 7192 const Target *TheTarget = GetTarget(MachOOF, &McpuDefault, &ThumbTarget); 7193 if (!TheTarget) { 7194 // GetTarget prints out stuff. 7195 return; 7196 } 7197 std::string MachOMCPU; 7198 if (MCPU.empty() && McpuDefault) 7199 MachOMCPU = McpuDefault; 7200 else 7201 MachOMCPU = MCPU; 7202 7203 std::unique_ptr<const MCInstrInfo> InstrInfo(TheTarget->createMCInstrInfo()); 7204 std::unique_ptr<const MCInstrInfo> ThumbInstrInfo; 7205 if (ThumbTarget) 7206 ThumbInstrInfo.reset(ThumbTarget->createMCInstrInfo()); 7207 7208 // Package up features to be passed to target/subtarget 7209 std::string FeaturesStr; 7210 if (!MAttrs.empty()) { 7211 SubtargetFeatures Features; 7212 for (unsigned i = 0; i != MAttrs.size(); ++i) 7213 Features.AddFeature(MAttrs[i]); 7214 FeaturesStr = Features.getString(); 7215 } 7216 7217 MCTargetOptions MCOptions; 7218 // Set up disassembler. 7219 std::unique_ptr<const MCRegisterInfo> MRI( 7220 TheTarget->createMCRegInfo(TripleName)); 7221 std::unique_ptr<const MCAsmInfo> AsmInfo( 7222 TheTarget->createMCAsmInfo(*MRI, TripleName, MCOptions)); 7223 std::unique_ptr<const MCSubtargetInfo> STI( 7224 TheTarget->createMCSubtargetInfo(TripleName, MachOMCPU, FeaturesStr)); 7225 MCContext Ctx(AsmInfo.get(), MRI.get(), nullptr); 7226 std::unique_ptr<MCDisassembler> DisAsm( 7227 TheTarget->createMCDisassembler(*STI, Ctx)); 7228 std::unique_ptr<MCSymbolizer> Symbolizer; 7229 struct DisassembleInfo SymbolizerInfo(nullptr, nullptr, nullptr, false); 7230 std::unique_ptr<MCRelocationInfo> RelInfo( 7231 TheTarget->createMCRelocationInfo(TripleName, Ctx)); 7232 if (RelInfo) { 7233 Symbolizer.reset(TheTarget->createMCSymbolizer( 7234 TripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp, 7235 &SymbolizerInfo, &Ctx, std::move(RelInfo))); 7236 DisAsm->setSymbolizer(std::move(Symbolizer)); 7237 } 7238 int AsmPrinterVariant = AsmInfo->getAssemblerDialect(); 7239 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter( 7240 Triple(TripleName), AsmPrinterVariant, *AsmInfo, *InstrInfo, *MRI)); 7241 // Set the display preference for hex vs. decimal immediates. 7242 IP->setPrintImmHex(PrintImmHex); 7243 // Comment stream and backing vector. 7244 SmallString<128> CommentsToEmit; 7245 raw_svector_ostream CommentStream(CommentsToEmit); 7246 // FIXME: Setting the CommentStream in the InstPrinter is problematic in that 7247 // if it is done then arm64 comments for string literals don't get printed 7248 // and some constant get printed instead and not setting it causes intel 7249 // (32-bit and 64-bit) comments printed with different spacing before the 7250 // comment causing different diffs with the 'C' disassembler library API. 7251 // IP->setCommentStream(CommentStream); 7252 7253 if (!AsmInfo || !STI || !DisAsm || !IP) { 7254 WithColor::error(errs(), "llvm-objdump") 7255 << "couldn't initialize disassembler for target " << TripleName << '\n'; 7256 return; 7257 } 7258 7259 // Set up separate thumb disassembler if needed. 7260 std::unique_ptr<const MCRegisterInfo> ThumbMRI; 7261 std::unique_ptr<const MCAsmInfo> ThumbAsmInfo; 7262 std::unique_ptr<const MCSubtargetInfo> ThumbSTI; 7263 std::unique_ptr<MCDisassembler> ThumbDisAsm; 7264 std::unique_ptr<MCInstPrinter> ThumbIP; 7265 std::unique_ptr<MCContext> ThumbCtx; 7266 std::unique_ptr<MCSymbolizer> ThumbSymbolizer; 7267 struct DisassembleInfo ThumbSymbolizerInfo(nullptr, nullptr, nullptr, false); 7268 std::unique_ptr<MCRelocationInfo> ThumbRelInfo; 7269 if (ThumbTarget) { 7270 ThumbMRI.reset(ThumbTarget->createMCRegInfo(ThumbTripleName)); 7271 ThumbAsmInfo.reset( 7272 ThumbTarget->createMCAsmInfo(*ThumbMRI, ThumbTripleName, MCOptions)); 7273 ThumbSTI.reset( 7274 ThumbTarget->createMCSubtargetInfo(ThumbTripleName, MachOMCPU, 7275 FeaturesStr)); 7276 ThumbCtx.reset(new MCContext(ThumbAsmInfo.get(), ThumbMRI.get(), nullptr)); 7277 ThumbDisAsm.reset(ThumbTarget->createMCDisassembler(*ThumbSTI, *ThumbCtx)); 7278 MCContext *PtrThumbCtx = ThumbCtx.get(); 7279 ThumbRelInfo.reset( 7280 ThumbTarget->createMCRelocationInfo(ThumbTripleName, *PtrThumbCtx)); 7281 if (ThumbRelInfo) { 7282 ThumbSymbolizer.reset(ThumbTarget->createMCSymbolizer( 7283 ThumbTripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp, 7284 &ThumbSymbolizerInfo, PtrThumbCtx, std::move(ThumbRelInfo))); 7285 ThumbDisAsm->setSymbolizer(std::move(ThumbSymbolizer)); 7286 } 7287 int ThumbAsmPrinterVariant = ThumbAsmInfo->getAssemblerDialect(); 7288 ThumbIP.reset(ThumbTarget->createMCInstPrinter( 7289 Triple(ThumbTripleName), ThumbAsmPrinterVariant, *ThumbAsmInfo, 7290 *ThumbInstrInfo, *ThumbMRI)); 7291 // Set the display preference for hex vs. decimal immediates. 7292 ThumbIP->setPrintImmHex(PrintImmHex); 7293 } 7294 7295 if (ThumbTarget && (!ThumbAsmInfo || !ThumbSTI || !ThumbDisAsm || !ThumbIP)) { 7296 WithColor::error(errs(), "llvm-objdump") 7297 << "couldn't initialize disassembler for target " << ThumbTripleName 7298 << '\n'; 7299 return; 7300 } 7301 7302 MachO::mach_header Header = MachOOF->getHeader(); 7303 7304 // FIXME: Using the -cfg command line option, this code used to be able to 7305 // annotate relocations with the referenced symbol's name, and if this was 7306 // inside a __[cf]string section, the data it points to. This is now replaced 7307 // by the upcoming MCSymbolizer, which needs the appropriate setup done above. 7308 std::vector<SectionRef> Sections; 7309 std::vector<SymbolRef> Symbols; 7310 SmallVector<uint64_t, 8> FoundFns; 7311 uint64_t BaseSegmentAddress = 0; 7312 7313 getSectionsAndSymbols(MachOOF, Sections, Symbols, FoundFns, 7314 BaseSegmentAddress); 7315 7316 // Sort the symbols by address, just in case they didn't come in that way. 7317 llvm::sort(Symbols, SymbolSorter()); 7318 7319 // Build a data in code table that is sorted on by the address of each entry. 7320 uint64_t BaseAddress = 0; 7321 if (Header.filetype == MachO::MH_OBJECT) 7322 BaseAddress = Sections[0].getAddress(); 7323 else 7324 BaseAddress = BaseSegmentAddress; 7325 DiceTable Dices; 7326 for (dice_iterator DI = MachOOF->begin_dices(), DE = MachOOF->end_dices(); 7327 DI != DE; ++DI) { 7328 uint32_t Offset; 7329 DI->getOffset(Offset); 7330 Dices.push_back(std::make_pair(BaseAddress + Offset, *DI)); 7331 } 7332 array_pod_sort(Dices.begin(), Dices.end()); 7333 7334 // Try to find debug info and set up the DIContext for it. 7335 std::unique_ptr<DIContext> diContext; 7336 std::unique_ptr<Binary> DSYMBinary; 7337 std::unique_ptr<MemoryBuffer> DSYMBuf; 7338 if (UseDbg) { 7339 ObjectFile *DbgObj = MachOOF; 7340 7341 // A separate DSym file path was specified, parse it as a macho file, 7342 // get the sections and supply it to the section name parsing machinery. 7343 if (!DSYMFile.empty()) { 7344 std::string DSYMPath(DSYMFile); 7345 7346 // If DSYMPath is a .dSYM directory, append the Mach-O file. 7347 if (llvm::sys::fs::is_directory(DSYMPath) && 7348 llvm::sys::path::extension(DSYMPath) == ".dSYM") { 7349 SmallString<128> ShortName(llvm::sys::path::filename(DSYMPath)); 7350 llvm::sys::path::replace_extension(ShortName, ""); 7351 SmallString<1024> FullPath(DSYMPath); 7352 llvm::sys::path::append(FullPath, "Contents", "Resources", "DWARF", 7353 ShortName); 7354 DSYMPath = std::string(FullPath.str()); 7355 } 7356 7357 // Load the file. 7358 ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr = 7359 MemoryBuffer::getFileOrSTDIN(DSYMPath); 7360 if (std::error_code EC = BufOrErr.getError()) { 7361 reportError(errorCodeToError(EC), DSYMPath); 7362 return; 7363 } 7364 7365 // We need to keep the file alive, because we're replacing DbgObj with it. 7366 DSYMBuf = std::move(BufOrErr.get()); 7367 7368 Expected<std::unique_ptr<Binary>> BinaryOrErr = 7369 createBinary(DSYMBuf.get()->getMemBufferRef()); 7370 if (!BinaryOrErr) { 7371 reportError(BinaryOrErr.takeError(), DSYMPath); 7372 return; 7373 } 7374 7375 // We need to keep the Binary alive with the buffer 7376 DSYMBinary = std::move(BinaryOrErr.get()); 7377 if (ObjectFile *O = dyn_cast<ObjectFile>(DSYMBinary.get())) { 7378 // this is a Mach-O object file, use it 7379 if (MachOObjectFile *MachDSYM = dyn_cast<MachOObjectFile>(&*O)) { 7380 DbgObj = MachDSYM; 7381 } 7382 else { 7383 WithColor::error(errs(), "llvm-objdump") 7384 << DSYMPath << " is not a Mach-O file type.\n"; 7385 return; 7386 } 7387 } 7388 else if (auto UB = dyn_cast<MachOUniversalBinary>(DSYMBinary.get())){ 7389 // this is a Universal Binary, find a Mach-O for this architecture 7390 uint32_t CPUType, CPUSubType; 7391 const char *ArchFlag; 7392 if (MachOOF->is64Bit()) { 7393 const MachO::mach_header_64 H_64 = MachOOF->getHeader64(); 7394 CPUType = H_64.cputype; 7395 CPUSubType = H_64.cpusubtype; 7396 } else { 7397 const MachO::mach_header H = MachOOF->getHeader(); 7398 CPUType = H.cputype; 7399 CPUSubType = H.cpusubtype; 7400 } 7401 Triple T = MachOObjectFile::getArchTriple(CPUType, CPUSubType, nullptr, 7402 &ArchFlag); 7403 Expected<std::unique_ptr<MachOObjectFile>> MachDSYM = 7404 UB->getMachOObjectForArch(ArchFlag); 7405 if (!MachDSYM) { 7406 reportError(MachDSYM.takeError(), DSYMPath); 7407 return; 7408 } 7409 7410 // We need to keep the Binary alive with the buffer 7411 DbgObj = &*MachDSYM.get(); 7412 DSYMBinary = std::move(*MachDSYM); 7413 } 7414 else { 7415 WithColor::error(errs(), "llvm-objdump") 7416 << DSYMPath << " is not a Mach-O or Universal file type.\n"; 7417 return; 7418 } 7419 } 7420 7421 // Setup the DIContext 7422 diContext = DWARFContext::create(*DbgObj); 7423 } 7424 7425 if (FilterSections.empty()) 7426 outs() << "(" << DisSegName << "," << DisSectName << ") section\n"; 7427 7428 for (unsigned SectIdx = 0; SectIdx != Sections.size(); SectIdx++) { 7429 Expected<StringRef> SecNameOrErr = Sections[SectIdx].getName(); 7430 if (!SecNameOrErr) { 7431 consumeError(SecNameOrErr.takeError()); 7432 continue; 7433 } 7434 if (*SecNameOrErr != DisSectName) 7435 continue; 7436 7437 DataRefImpl DR = Sections[SectIdx].getRawDataRefImpl(); 7438 7439 StringRef SegmentName = MachOOF->getSectionFinalSegmentName(DR); 7440 if (SegmentName != DisSegName) 7441 continue; 7442 7443 StringRef BytesStr = 7444 unwrapOrError(Sections[SectIdx].getContents(), Filename); 7445 ArrayRef<uint8_t> Bytes = arrayRefFromStringRef(BytesStr); 7446 uint64_t SectAddress = Sections[SectIdx].getAddress(); 7447 7448 bool symbolTableWorked = false; 7449 7450 // Create a map of symbol addresses to symbol names for use by 7451 // the SymbolizerSymbolLookUp() routine. 7452 SymbolAddressMap AddrMap; 7453 bool DisSymNameFound = false; 7454 for (const SymbolRef &Symbol : MachOOF->symbols()) { 7455 SymbolRef::Type ST = 7456 unwrapOrError(Symbol.getType(), MachOOF->getFileName()); 7457 if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data || 7458 ST == SymbolRef::ST_Other) { 7459 uint64_t Address = cantFail(Symbol.getValue()); 7460 StringRef SymName = 7461 unwrapOrError(Symbol.getName(), MachOOF->getFileName()); 7462 AddrMap[Address] = SymName; 7463 if (!DisSymName.empty() && DisSymName == SymName) 7464 DisSymNameFound = true; 7465 } 7466 } 7467 if (!DisSymName.empty() && !DisSymNameFound) { 7468 outs() << "Can't find -dis-symname: " << DisSymName << "\n"; 7469 return; 7470 } 7471 // Set up the block of info used by the Symbolizer call backs. 7472 SymbolizerInfo.verbose = !NoSymbolicOperands; 7473 SymbolizerInfo.O = MachOOF; 7474 SymbolizerInfo.S = Sections[SectIdx]; 7475 SymbolizerInfo.AddrMap = &AddrMap; 7476 SymbolizerInfo.Sections = &Sections; 7477 // Same for the ThumbSymbolizer 7478 ThumbSymbolizerInfo.verbose = !NoSymbolicOperands; 7479 ThumbSymbolizerInfo.O = MachOOF; 7480 ThumbSymbolizerInfo.S = Sections[SectIdx]; 7481 ThumbSymbolizerInfo.AddrMap = &AddrMap; 7482 ThumbSymbolizerInfo.Sections = &Sections; 7483 7484 unsigned int Arch = MachOOF->getArch(); 7485 7486 // Skip all symbols if this is a stubs file. 7487 if (Bytes.empty()) 7488 return; 7489 7490 // If the section has symbols but no symbol at the start of the section 7491 // these are used to make sure the bytes before the first symbol are 7492 // disassembled. 7493 bool FirstSymbol = true; 7494 bool FirstSymbolAtSectionStart = true; 7495 7496 // Disassemble symbol by symbol. 7497 for (unsigned SymIdx = 0; SymIdx != Symbols.size(); SymIdx++) { 7498 StringRef SymName = 7499 unwrapOrError(Symbols[SymIdx].getName(), MachOOF->getFileName()); 7500 SymbolRef::Type ST = 7501 unwrapOrError(Symbols[SymIdx].getType(), MachOOF->getFileName()); 7502 if (ST != SymbolRef::ST_Function && ST != SymbolRef::ST_Data) 7503 continue; 7504 7505 // Make sure the symbol is defined in this section. 7506 bool containsSym = Sections[SectIdx].containsSymbol(Symbols[SymIdx]); 7507 if (!containsSym) { 7508 if (!DisSymName.empty() && DisSymName == SymName) { 7509 outs() << "-dis-symname: " << DisSymName << " not in the section\n"; 7510 return; 7511 } 7512 continue; 7513 } 7514 // The __mh_execute_header is special and we need to deal with that fact 7515 // this symbol is before the start of the (__TEXT,__text) section and at the 7516 // address of the start of the __TEXT segment. This is because this symbol 7517 // is an N_SECT symbol in the (__TEXT,__text) but its address is before the 7518 // start of the section in a standard MH_EXECUTE filetype. 7519 if (!DisSymName.empty() && DisSymName == "__mh_execute_header") { 7520 outs() << "-dis-symname: __mh_execute_header not in any section\n"; 7521 return; 7522 } 7523 // When this code is trying to disassemble a symbol at a time and in the 7524 // case there is only the __mh_execute_header symbol left as in a stripped 7525 // executable, we need to deal with this by ignoring this symbol so the 7526 // whole section is disassembled and this symbol is then not displayed. 7527 if (SymName == "__mh_execute_header" || SymName == "__mh_dylib_header" || 7528 SymName == "__mh_bundle_header" || SymName == "__mh_object_header" || 7529 SymName == "__mh_preload_header" || SymName == "__mh_dylinker_header") 7530 continue; 7531 7532 // If we are only disassembling one symbol see if this is that symbol. 7533 if (!DisSymName.empty() && DisSymName != SymName) 7534 continue; 7535 7536 // Start at the address of the symbol relative to the section's address. 7537 uint64_t SectSize = Sections[SectIdx].getSize(); 7538 uint64_t Start = cantFail(Symbols[SymIdx].getValue()); 7539 uint64_t SectionAddress = Sections[SectIdx].getAddress(); 7540 Start -= SectionAddress; 7541 7542 if (Start > SectSize) { 7543 outs() << "section data ends, " << SymName 7544 << " lies outside valid range\n"; 7545 return; 7546 } 7547 7548 // Stop disassembling either at the beginning of the next symbol or at 7549 // the end of the section. 7550 bool containsNextSym = false; 7551 uint64_t NextSym = 0; 7552 uint64_t NextSymIdx = SymIdx + 1; 7553 while (Symbols.size() > NextSymIdx) { 7554 SymbolRef::Type NextSymType = unwrapOrError( 7555 Symbols[NextSymIdx].getType(), MachOOF->getFileName()); 7556 if (NextSymType == SymbolRef::ST_Function) { 7557 containsNextSym = 7558 Sections[SectIdx].containsSymbol(Symbols[NextSymIdx]); 7559 NextSym = cantFail(Symbols[NextSymIdx].getValue()); 7560 NextSym -= SectionAddress; 7561 break; 7562 } 7563 ++NextSymIdx; 7564 } 7565 7566 uint64_t End = containsNextSym ? std::min(NextSym, SectSize) : SectSize; 7567 uint64_t Size; 7568 7569 symbolTableWorked = true; 7570 7571 DataRefImpl Symb = Symbols[SymIdx].getRawDataRefImpl(); 7572 uint32_t SymbolFlags = cantFail(MachOOF->getSymbolFlags(Symb)); 7573 bool IsThumb = SymbolFlags & SymbolRef::SF_Thumb; 7574 7575 // We only need the dedicated Thumb target if there's a real choice 7576 // (i.e. we're not targeting M-class) and the function is Thumb. 7577 bool UseThumbTarget = IsThumb && ThumbTarget; 7578 7579 // If we are not specifying a symbol to start disassembly with and this 7580 // is the first symbol in the section but not at the start of the section 7581 // then move the disassembly index to the start of the section and 7582 // don't print the symbol name just yet. This is so the bytes before the 7583 // first symbol are disassembled. 7584 uint64_t SymbolStart = Start; 7585 if (DisSymName.empty() && FirstSymbol && Start != 0) { 7586 FirstSymbolAtSectionStart = false; 7587 Start = 0; 7588 } 7589 else 7590 outs() << SymName << ":\n"; 7591 7592 DILineInfo lastLine; 7593 for (uint64_t Index = Start; Index < End; Index += Size) { 7594 MCInst Inst; 7595 7596 // If this is the first symbol in the section and it was not at the 7597 // start of the section, see if we are at its Index now and if so print 7598 // the symbol name. 7599 if (FirstSymbol && !FirstSymbolAtSectionStart && Index == SymbolStart) 7600 outs() << SymName << ":\n"; 7601 7602 uint64_t PC = SectAddress + Index; 7603 if (!NoLeadingAddr) { 7604 if (FullLeadingAddr) { 7605 if (MachOOF->is64Bit()) 7606 outs() << format("%016" PRIx64, PC); 7607 else 7608 outs() << format("%08" PRIx64, PC); 7609 } else { 7610 outs() << format("%8" PRIx64 ":", PC); 7611 } 7612 } 7613 if (!NoShowRawInsn || Arch == Triple::arm) 7614 outs() << "\t"; 7615 7616 if (DumpAndSkipDataInCode(PC, Bytes.data() + Index, Dices, Size)) 7617 continue; 7618 7619 SmallVector<char, 64> AnnotationsBytes; 7620 raw_svector_ostream Annotations(AnnotationsBytes); 7621 7622 bool gotInst; 7623 if (UseThumbTarget) 7624 gotInst = ThumbDisAsm->getInstruction(Inst, Size, Bytes.slice(Index), 7625 PC, Annotations); 7626 else 7627 gotInst = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index), PC, 7628 Annotations); 7629 if (gotInst) { 7630 if (!NoShowRawInsn || Arch == Triple::arm) { 7631 dumpBytes(makeArrayRef(Bytes.data() + Index, Size), outs()); 7632 } 7633 formatted_raw_ostream FormattedOS(outs()); 7634 StringRef AnnotationsStr = Annotations.str(); 7635 if (UseThumbTarget) 7636 ThumbIP->printInst(&Inst, PC, AnnotationsStr, *ThumbSTI, 7637 FormattedOS); 7638 else 7639 IP->printInst(&Inst, PC, AnnotationsStr, *STI, FormattedOS); 7640 emitComments(CommentStream, CommentsToEmit, FormattedOS, *AsmInfo); 7641 7642 // Print debug info. 7643 if (diContext) { 7644 DILineInfo dli = diContext->getLineInfoForAddress({PC, SectIdx}); 7645 // Print valid line info if it changed. 7646 if (dli != lastLine && dli.Line != 0) 7647 outs() << "\t## " << dli.FileName << ':' << dli.Line << ':' 7648 << dli.Column; 7649 lastLine = dli; 7650 } 7651 outs() << "\n"; 7652 } else { 7653 if (MachOOF->getArchTriple().isX86()) { 7654 outs() << format("\t.byte 0x%02x #bad opcode\n", 7655 *(Bytes.data() + Index) & 0xff); 7656 Size = 1; // skip exactly one illegible byte and move on. 7657 } else if (Arch == Triple::aarch64 || 7658 (Arch == Triple::arm && !IsThumb)) { 7659 uint32_t opcode = (*(Bytes.data() + Index) & 0xff) | 7660 (*(Bytes.data() + Index + 1) & 0xff) << 8 | 7661 (*(Bytes.data() + Index + 2) & 0xff) << 16 | 7662 (*(Bytes.data() + Index + 3) & 0xff) << 24; 7663 outs() << format("\t.long\t0x%08x\n", opcode); 7664 Size = 4; 7665 } else if (Arch == Triple::arm) { 7666 assert(IsThumb && "ARM mode should have been dealt with above"); 7667 uint32_t opcode = (*(Bytes.data() + Index) & 0xff) | 7668 (*(Bytes.data() + Index + 1) & 0xff) << 8; 7669 outs() << format("\t.short\t0x%04x\n", opcode); 7670 Size = 2; 7671 } else{ 7672 WithColor::warning(errs(), "llvm-objdump") 7673 << "invalid instruction encoding\n"; 7674 if (Size == 0) 7675 Size = 1; // skip illegible bytes 7676 } 7677 } 7678 } 7679 // Now that we are done disassembled the first symbol set the bool that 7680 // were doing this to false. 7681 FirstSymbol = false; 7682 } 7683 if (!symbolTableWorked) { 7684 // Reading the symbol table didn't work, disassemble the whole section. 7685 uint64_t SectAddress = Sections[SectIdx].getAddress(); 7686 uint64_t SectSize = Sections[SectIdx].getSize(); 7687 uint64_t InstSize; 7688 for (uint64_t Index = 0; Index < SectSize; Index += InstSize) { 7689 MCInst Inst; 7690 7691 uint64_t PC = SectAddress + Index; 7692 7693 if (DumpAndSkipDataInCode(PC, Bytes.data() + Index, Dices, InstSize)) 7694 continue; 7695 7696 SmallVector<char, 64> AnnotationsBytes; 7697 raw_svector_ostream Annotations(AnnotationsBytes); 7698 if (DisAsm->getInstruction(Inst, InstSize, Bytes.slice(Index), PC, 7699 Annotations)) { 7700 if (!NoLeadingAddr) { 7701 if (FullLeadingAddr) { 7702 if (MachOOF->is64Bit()) 7703 outs() << format("%016" PRIx64, PC); 7704 else 7705 outs() << format("%08" PRIx64, PC); 7706 } else { 7707 outs() << format("%8" PRIx64 ":", PC); 7708 } 7709 } 7710 if (!NoShowRawInsn || Arch == Triple::arm) { 7711 outs() << "\t"; 7712 dumpBytes(makeArrayRef(Bytes.data() + Index, InstSize), outs()); 7713 } 7714 StringRef AnnotationsStr = Annotations.str(); 7715 IP->printInst(&Inst, PC, AnnotationsStr, *STI, outs()); 7716 outs() << "\n"; 7717 } else { 7718 if (MachOOF->getArchTriple().isX86()) { 7719 outs() << format("\t.byte 0x%02x #bad opcode\n", 7720 *(Bytes.data() + Index) & 0xff); 7721 InstSize = 1; // skip exactly one illegible byte and move on. 7722 } else { 7723 WithColor::warning(errs(), "llvm-objdump") 7724 << "invalid instruction encoding\n"; 7725 if (InstSize == 0) 7726 InstSize = 1; // skip illegible bytes 7727 } 7728 } 7729 } 7730 } 7731 // The TripleName's need to be reset if we are called again for a different 7732 // architecture. 7733 TripleName = ""; 7734 ThumbTripleName = ""; 7735 7736 if (SymbolizerInfo.demangled_name != nullptr) 7737 free(SymbolizerInfo.demangled_name); 7738 if (ThumbSymbolizerInfo.demangled_name != nullptr) 7739 free(ThumbSymbolizerInfo.demangled_name); 7740 } 7741 } 7742 7743 //===----------------------------------------------------------------------===// 7744 // __compact_unwind section dumping 7745 //===----------------------------------------------------------------------===// 7746 7747 namespace { 7748 7749 template <typename T> 7750 static uint64_t read(StringRef Contents, ptrdiff_t Offset) { 7751 using llvm::support::little; 7752 using llvm::support::unaligned; 7753 7754 if (Offset + sizeof(T) > Contents.size()) { 7755 outs() << "warning: attempt to read past end of buffer\n"; 7756 return T(); 7757 } 7758 7759 uint64_t Val = 7760 support::endian::read<T, little, unaligned>(Contents.data() + Offset); 7761 return Val; 7762 } 7763 7764 template <typename T> 7765 static uint64_t readNext(StringRef Contents, ptrdiff_t &Offset) { 7766 T Val = read<T>(Contents, Offset); 7767 Offset += sizeof(T); 7768 return Val; 7769 } 7770 7771 struct CompactUnwindEntry { 7772 uint32_t OffsetInSection; 7773 7774 uint64_t FunctionAddr; 7775 uint32_t Length; 7776 uint32_t CompactEncoding; 7777 uint64_t PersonalityAddr; 7778 uint64_t LSDAAddr; 7779 7780 RelocationRef FunctionReloc; 7781 RelocationRef PersonalityReloc; 7782 RelocationRef LSDAReloc; 7783 7784 CompactUnwindEntry(StringRef Contents, unsigned Offset, bool Is64) 7785 : OffsetInSection(Offset) { 7786 if (Is64) 7787 read<uint64_t>(Contents, Offset); 7788 else 7789 read<uint32_t>(Contents, Offset); 7790 } 7791 7792 private: 7793 template <typename UIntPtr> void read(StringRef Contents, ptrdiff_t Offset) { 7794 FunctionAddr = readNext<UIntPtr>(Contents, Offset); 7795 Length = readNext<uint32_t>(Contents, Offset); 7796 CompactEncoding = readNext<uint32_t>(Contents, Offset); 7797 PersonalityAddr = readNext<UIntPtr>(Contents, Offset); 7798 LSDAAddr = readNext<UIntPtr>(Contents, Offset); 7799 } 7800 }; 7801 } 7802 7803 /// Given a relocation from __compact_unwind, consisting of the RelocationRef 7804 /// and data being relocated, determine the best base Name and Addend to use for 7805 /// display purposes. 7806 /// 7807 /// 1. An Extern relocation will directly reference a symbol (and the data is 7808 /// then already an addend), so use that. 7809 /// 2. Otherwise the data is an offset in the object file's layout; try to find 7810 // a symbol before it in the same section, and use the offset from there. 7811 /// 3. Finally, if all that fails, fall back to an offset from the start of the 7812 /// referenced section. 7813 static void findUnwindRelocNameAddend(const MachOObjectFile *Obj, 7814 std::map<uint64_t, SymbolRef> &Symbols, 7815 const RelocationRef &Reloc, uint64_t Addr, 7816 StringRef &Name, uint64_t &Addend) { 7817 if (Reloc.getSymbol() != Obj->symbol_end()) { 7818 Name = unwrapOrError(Reloc.getSymbol()->getName(), Obj->getFileName()); 7819 Addend = Addr; 7820 return; 7821 } 7822 7823 auto RE = Obj->getRelocation(Reloc.getRawDataRefImpl()); 7824 SectionRef RelocSection = Obj->getAnyRelocationSection(RE); 7825 7826 uint64_t SectionAddr = RelocSection.getAddress(); 7827 7828 auto Sym = Symbols.upper_bound(Addr); 7829 if (Sym == Symbols.begin()) { 7830 // The first symbol in the object is after this reference, the best we can 7831 // do is section-relative notation. 7832 if (Expected<StringRef> NameOrErr = RelocSection.getName()) 7833 Name = *NameOrErr; 7834 else 7835 consumeError(NameOrErr.takeError()); 7836 7837 Addend = Addr - SectionAddr; 7838 return; 7839 } 7840 7841 // Go back one so that SymbolAddress <= Addr. 7842 --Sym; 7843 7844 section_iterator SymSection = 7845 unwrapOrError(Sym->second.getSection(), Obj->getFileName()); 7846 if (RelocSection == *SymSection) { 7847 // There's a valid symbol in the same section before this reference. 7848 Name = unwrapOrError(Sym->second.getName(), Obj->getFileName()); 7849 Addend = Addr - Sym->first; 7850 return; 7851 } 7852 7853 // There is a symbol before this reference, but it's in a different 7854 // section. Probably not helpful to mention it, so use the section name. 7855 if (Expected<StringRef> NameOrErr = RelocSection.getName()) 7856 Name = *NameOrErr; 7857 else 7858 consumeError(NameOrErr.takeError()); 7859 7860 Addend = Addr - SectionAddr; 7861 } 7862 7863 static void printUnwindRelocDest(const MachOObjectFile *Obj, 7864 std::map<uint64_t, SymbolRef> &Symbols, 7865 const RelocationRef &Reloc, uint64_t Addr) { 7866 StringRef Name; 7867 uint64_t Addend; 7868 7869 if (!Reloc.getObject()) 7870 return; 7871 7872 findUnwindRelocNameAddend(Obj, Symbols, Reloc, Addr, Name, Addend); 7873 7874 outs() << Name; 7875 if (Addend) 7876 outs() << " + " << format("0x%" PRIx64, Addend); 7877 } 7878 7879 static void 7880 printMachOCompactUnwindSection(const MachOObjectFile *Obj, 7881 std::map<uint64_t, SymbolRef> &Symbols, 7882 const SectionRef &CompactUnwind) { 7883 7884 if (!Obj->isLittleEndian()) { 7885 outs() << "Skipping big-endian __compact_unwind section\n"; 7886 return; 7887 } 7888 7889 bool Is64 = Obj->is64Bit(); 7890 uint32_t PointerSize = Is64 ? sizeof(uint64_t) : sizeof(uint32_t); 7891 uint32_t EntrySize = 3 * PointerSize + 2 * sizeof(uint32_t); 7892 7893 StringRef Contents = 7894 unwrapOrError(CompactUnwind.getContents(), Obj->getFileName()); 7895 SmallVector<CompactUnwindEntry, 4> CompactUnwinds; 7896 7897 // First populate the initial raw offsets, encodings and so on from the entry. 7898 for (unsigned Offset = 0; Offset < Contents.size(); Offset += EntrySize) { 7899 CompactUnwindEntry Entry(Contents, Offset, Is64); 7900 CompactUnwinds.push_back(Entry); 7901 } 7902 7903 // Next we need to look at the relocations to find out what objects are 7904 // actually being referred to. 7905 for (const RelocationRef &Reloc : CompactUnwind.relocations()) { 7906 uint64_t RelocAddress = Reloc.getOffset(); 7907 7908 uint32_t EntryIdx = RelocAddress / EntrySize; 7909 uint32_t OffsetInEntry = RelocAddress - EntryIdx * EntrySize; 7910 CompactUnwindEntry &Entry = CompactUnwinds[EntryIdx]; 7911 7912 if (OffsetInEntry == 0) 7913 Entry.FunctionReloc = Reloc; 7914 else if (OffsetInEntry == PointerSize + 2 * sizeof(uint32_t)) 7915 Entry.PersonalityReloc = Reloc; 7916 else if (OffsetInEntry == 2 * PointerSize + 2 * sizeof(uint32_t)) 7917 Entry.LSDAReloc = Reloc; 7918 else { 7919 outs() << "Invalid relocation in __compact_unwind section\n"; 7920 return; 7921 } 7922 } 7923 7924 // Finally, we're ready to print the data we've gathered. 7925 outs() << "Contents of __compact_unwind section:\n"; 7926 for (auto &Entry : CompactUnwinds) { 7927 outs() << " Entry at offset " 7928 << format("0x%" PRIx32, Entry.OffsetInSection) << ":\n"; 7929 7930 // 1. Start of the region this entry applies to. 7931 outs() << " start: " << format("0x%" PRIx64, 7932 Entry.FunctionAddr) << ' '; 7933 printUnwindRelocDest(Obj, Symbols, Entry.FunctionReloc, Entry.FunctionAddr); 7934 outs() << '\n'; 7935 7936 // 2. Length of the region this entry applies to. 7937 outs() << " length: " << format("0x%" PRIx32, Entry.Length) 7938 << '\n'; 7939 // 3. The 32-bit compact encoding. 7940 outs() << " compact encoding: " 7941 << format("0x%08" PRIx32, Entry.CompactEncoding) << '\n'; 7942 7943 // 4. The personality function, if present. 7944 if (Entry.PersonalityReloc.getObject()) { 7945 outs() << " personality function: " 7946 << format("0x%" PRIx64, Entry.PersonalityAddr) << ' '; 7947 printUnwindRelocDest(Obj, Symbols, Entry.PersonalityReloc, 7948 Entry.PersonalityAddr); 7949 outs() << '\n'; 7950 } 7951 7952 // 5. This entry's language-specific data area. 7953 if (Entry.LSDAReloc.getObject()) { 7954 outs() << " LSDA: " << format("0x%" PRIx64, 7955 Entry.LSDAAddr) << ' '; 7956 printUnwindRelocDest(Obj, Symbols, Entry.LSDAReloc, Entry.LSDAAddr); 7957 outs() << '\n'; 7958 } 7959 } 7960 } 7961 7962 //===----------------------------------------------------------------------===// 7963 // __unwind_info section dumping 7964 //===----------------------------------------------------------------------===// 7965 7966 static void printRegularSecondLevelUnwindPage(StringRef PageData) { 7967 ptrdiff_t Pos = 0; 7968 uint32_t Kind = readNext<uint32_t>(PageData, Pos); 7969 (void)Kind; 7970 assert(Kind == 2 && "kind for a regular 2nd level index should be 2"); 7971 7972 uint16_t EntriesStart = readNext<uint16_t>(PageData, Pos); 7973 uint16_t NumEntries = readNext<uint16_t>(PageData, Pos); 7974 7975 Pos = EntriesStart; 7976 for (unsigned i = 0; i < NumEntries; ++i) { 7977 uint32_t FunctionOffset = readNext<uint32_t>(PageData, Pos); 7978 uint32_t Encoding = readNext<uint32_t>(PageData, Pos); 7979 7980 outs() << " [" << i << "]: " 7981 << "function offset=" << format("0x%08" PRIx32, FunctionOffset) 7982 << ", " 7983 << "encoding=" << format("0x%08" PRIx32, Encoding) << '\n'; 7984 } 7985 } 7986 7987 static void printCompressedSecondLevelUnwindPage( 7988 StringRef PageData, uint32_t FunctionBase, 7989 const SmallVectorImpl<uint32_t> &CommonEncodings) { 7990 ptrdiff_t Pos = 0; 7991 uint32_t Kind = readNext<uint32_t>(PageData, Pos); 7992 (void)Kind; 7993 assert(Kind == 3 && "kind for a compressed 2nd level index should be 3"); 7994 7995 uint16_t EntriesStart = readNext<uint16_t>(PageData, Pos); 7996 uint16_t NumEntries = readNext<uint16_t>(PageData, Pos); 7997 7998 uint16_t EncodingsStart = readNext<uint16_t>(PageData, Pos); 7999 readNext<uint16_t>(PageData, Pos); 8000 StringRef PageEncodings = PageData.substr(EncodingsStart, StringRef::npos); 8001 8002 Pos = EntriesStart; 8003 for (unsigned i = 0; i < NumEntries; ++i) { 8004 uint32_t Entry = readNext<uint32_t>(PageData, Pos); 8005 uint32_t FunctionOffset = FunctionBase + (Entry & 0xffffff); 8006 uint32_t EncodingIdx = Entry >> 24; 8007 8008 uint32_t Encoding; 8009 if (EncodingIdx < CommonEncodings.size()) 8010 Encoding = CommonEncodings[EncodingIdx]; 8011 else 8012 Encoding = read<uint32_t>(PageEncodings, 8013 sizeof(uint32_t) * 8014 (EncodingIdx - CommonEncodings.size())); 8015 8016 outs() << " [" << i << "]: " 8017 << "function offset=" << format("0x%08" PRIx32, FunctionOffset) 8018 << ", " 8019 << "encoding[" << EncodingIdx 8020 << "]=" << format("0x%08" PRIx32, Encoding) << '\n'; 8021 } 8022 } 8023 8024 static void printMachOUnwindInfoSection(const MachOObjectFile *Obj, 8025 std::map<uint64_t, SymbolRef> &Symbols, 8026 const SectionRef &UnwindInfo) { 8027 8028 if (!Obj->isLittleEndian()) { 8029 outs() << "Skipping big-endian __unwind_info section\n"; 8030 return; 8031 } 8032 8033 outs() << "Contents of __unwind_info section:\n"; 8034 8035 StringRef Contents = 8036 unwrapOrError(UnwindInfo.getContents(), Obj->getFileName()); 8037 ptrdiff_t Pos = 0; 8038 8039 //===---------------------------------- 8040 // Section header 8041 //===---------------------------------- 8042 8043 uint32_t Version = readNext<uint32_t>(Contents, Pos); 8044 outs() << " Version: " 8045 << format("0x%" PRIx32, Version) << '\n'; 8046 if (Version != 1) { 8047 outs() << " Skipping section with unknown version\n"; 8048 return; 8049 } 8050 8051 uint32_t CommonEncodingsStart = readNext<uint32_t>(Contents, Pos); 8052 outs() << " Common encodings array section offset: " 8053 << format("0x%" PRIx32, CommonEncodingsStart) << '\n'; 8054 uint32_t NumCommonEncodings = readNext<uint32_t>(Contents, Pos); 8055 outs() << " Number of common encodings in array: " 8056 << format("0x%" PRIx32, NumCommonEncodings) << '\n'; 8057 8058 uint32_t PersonalitiesStart = readNext<uint32_t>(Contents, Pos); 8059 outs() << " Personality function array section offset: " 8060 << format("0x%" PRIx32, PersonalitiesStart) << '\n'; 8061 uint32_t NumPersonalities = readNext<uint32_t>(Contents, Pos); 8062 outs() << " Number of personality functions in array: " 8063 << format("0x%" PRIx32, NumPersonalities) << '\n'; 8064 8065 uint32_t IndicesStart = readNext<uint32_t>(Contents, Pos); 8066 outs() << " Index array section offset: " 8067 << format("0x%" PRIx32, IndicesStart) << '\n'; 8068 uint32_t NumIndices = readNext<uint32_t>(Contents, Pos); 8069 outs() << " Number of indices in array: " 8070 << format("0x%" PRIx32, NumIndices) << '\n'; 8071 8072 //===---------------------------------- 8073 // A shared list of common encodings 8074 //===---------------------------------- 8075 8076 // These occupy indices in the range [0, N] whenever an encoding is referenced 8077 // from a compressed 2nd level index table. In practice the linker only 8078 // creates ~128 of these, so that indices are available to embed encodings in 8079 // the 2nd level index. 8080 8081 SmallVector<uint32_t, 64> CommonEncodings; 8082 outs() << " Common encodings: (count = " << NumCommonEncodings << ")\n"; 8083 Pos = CommonEncodingsStart; 8084 for (unsigned i = 0; i < NumCommonEncodings; ++i) { 8085 uint32_t Encoding = readNext<uint32_t>(Contents, Pos); 8086 CommonEncodings.push_back(Encoding); 8087 8088 outs() << " encoding[" << i << "]: " << format("0x%08" PRIx32, Encoding) 8089 << '\n'; 8090 } 8091 8092 //===---------------------------------- 8093 // Personality functions used in this executable 8094 //===---------------------------------- 8095 8096 // There should be only a handful of these (one per source language, 8097 // roughly). Particularly since they only get 2 bits in the compact encoding. 8098 8099 outs() << " Personality functions: (count = " << NumPersonalities << ")\n"; 8100 Pos = PersonalitiesStart; 8101 for (unsigned i = 0; i < NumPersonalities; ++i) { 8102 uint32_t PersonalityFn = readNext<uint32_t>(Contents, Pos); 8103 outs() << " personality[" << i + 1 8104 << "]: " << format("0x%08" PRIx32, PersonalityFn) << '\n'; 8105 } 8106 8107 //===---------------------------------- 8108 // The level 1 index entries 8109 //===---------------------------------- 8110 8111 // These specify an approximate place to start searching for the more detailed 8112 // information, sorted by PC. 8113 8114 struct IndexEntry { 8115 uint32_t FunctionOffset; 8116 uint32_t SecondLevelPageStart; 8117 uint32_t LSDAStart; 8118 }; 8119 8120 SmallVector<IndexEntry, 4> IndexEntries; 8121 8122 outs() << " Top level indices: (count = " << NumIndices << ")\n"; 8123 Pos = IndicesStart; 8124 for (unsigned i = 0; i < NumIndices; ++i) { 8125 IndexEntry Entry; 8126 8127 Entry.FunctionOffset = readNext<uint32_t>(Contents, Pos); 8128 Entry.SecondLevelPageStart = readNext<uint32_t>(Contents, Pos); 8129 Entry.LSDAStart = readNext<uint32_t>(Contents, Pos); 8130 IndexEntries.push_back(Entry); 8131 8132 outs() << " [" << i << "]: " 8133 << "function offset=" << format("0x%08" PRIx32, Entry.FunctionOffset) 8134 << ", " 8135 << "2nd level page offset=" 8136 << format("0x%08" PRIx32, Entry.SecondLevelPageStart) << ", " 8137 << "LSDA offset=" << format("0x%08" PRIx32, Entry.LSDAStart) << '\n'; 8138 } 8139 8140 //===---------------------------------- 8141 // Next come the LSDA tables 8142 //===---------------------------------- 8143 8144 // The LSDA layout is rather implicit: it's a contiguous array of entries from 8145 // the first top-level index's LSDAOffset to the last (sentinel). 8146 8147 outs() << " LSDA descriptors:\n"; 8148 Pos = IndexEntries[0].LSDAStart; 8149 const uint32_t LSDASize = 2 * sizeof(uint32_t); 8150 int NumLSDAs = 8151 (IndexEntries.back().LSDAStart - IndexEntries[0].LSDAStart) / LSDASize; 8152 8153 for (int i = 0; i < NumLSDAs; ++i) { 8154 uint32_t FunctionOffset = readNext<uint32_t>(Contents, Pos); 8155 uint32_t LSDAOffset = readNext<uint32_t>(Contents, Pos); 8156 outs() << " [" << i << "]: " 8157 << "function offset=" << format("0x%08" PRIx32, FunctionOffset) 8158 << ", " 8159 << "LSDA offset=" << format("0x%08" PRIx32, LSDAOffset) << '\n'; 8160 } 8161 8162 //===---------------------------------- 8163 // Finally, the 2nd level indices 8164 //===---------------------------------- 8165 8166 // Generally these are 4K in size, and have 2 possible forms: 8167 // + Regular stores up to 511 entries with disparate encodings 8168 // + Compressed stores up to 1021 entries if few enough compact encoding 8169 // values are used. 8170 outs() << " Second level indices:\n"; 8171 for (unsigned i = 0; i < IndexEntries.size() - 1; ++i) { 8172 // The final sentinel top-level index has no associated 2nd level page 8173 if (IndexEntries[i].SecondLevelPageStart == 0) 8174 break; 8175 8176 outs() << " Second level index[" << i << "]: " 8177 << "offset in section=" 8178 << format("0x%08" PRIx32, IndexEntries[i].SecondLevelPageStart) 8179 << ", " 8180 << "base function offset=" 8181 << format("0x%08" PRIx32, IndexEntries[i].FunctionOffset) << '\n'; 8182 8183 Pos = IndexEntries[i].SecondLevelPageStart; 8184 if (Pos + sizeof(uint32_t) > Contents.size()) { 8185 outs() << "warning: invalid offset for second level page: " << Pos << '\n'; 8186 continue; 8187 } 8188 8189 uint32_t Kind = 8190 *reinterpret_cast<const support::ulittle32_t *>(Contents.data() + Pos); 8191 if (Kind == 2) 8192 printRegularSecondLevelUnwindPage(Contents.substr(Pos, 4096)); 8193 else if (Kind == 3) 8194 printCompressedSecondLevelUnwindPage(Contents.substr(Pos, 4096), 8195 IndexEntries[i].FunctionOffset, 8196 CommonEncodings); 8197 else 8198 outs() << " Skipping 2nd level page with unknown kind " << Kind 8199 << '\n'; 8200 } 8201 } 8202 8203 void objdump::printMachOUnwindInfo(const MachOObjectFile *Obj) { 8204 std::map<uint64_t, SymbolRef> Symbols; 8205 for (const SymbolRef &SymRef : Obj->symbols()) { 8206 // Discard any undefined or absolute symbols. They're not going to take part 8207 // in the convenience lookup for unwind info and just take up resources. 8208 auto SectOrErr = SymRef.getSection(); 8209 if (!SectOrErr) { 8210 // TODO: Actually report errors helpfully. 8211 consumeError(SectOrErr.takeError()); 8212 continue; 8213 } 8214 section_iterator Section = *SectOrErr; 8215 if (Section == Obj->section_end()) 8216 continue; 8217 8218 uint64_t Addr = cantFail(SymRef.getValue()); 8219 Symbols.insert(std::make_pair(Addr, SymRef)); 8220 } 8221 8222 for (const SectionRef &Section : Obj->sections()) { 8223 StringRef SectName; 8224 if (Expected<StringRef> NameOrErr = Section.getName()) 8225 SectName = *NameOrErr; 8226 else 8227 consumeError(NameOrErr.takeError()); 8228 8229 if (SectName == "__compact_unwind") 8230 printMachOCompactUnwindSection(Obj, Symbols, Section); 8231 else if (SectName == "__unwind_info") 8232 printMachOUnwindInfoSection(Obj, Symbols, Section); 8233 } 8234 } 8235 8236 static void PrintMachHeader(uint32_t magic, uint32_t cputype, 8237 uint32_t cpusubtype, uint32_t filetype, 8238 uint32_t ncmds, uint32_t sizeofcmds, uint32_t flags, 8239 bool verbose) { 8240 outs() << "Mach header\n"; 8241 outs() << " magic cputype cpusubtype caps filetype ncmds " 8242 "sizeofcmds flags\n"; 8243 if (verbose) { 8244 if (magic == MachO::MH_MAGIC) 8245 outs() << " MH_MAGIC"; 8246 else if (magic == MachO::MH_MAGIC_64) 8247 outs() << "MH_MAGIC_64"; 8248 else 8249 outs() << format(" 0x%08" PRIx32, magic); 8250 switch (cputype) { 8251 case MachO::CPU_TYPE_I386: 8252 outs() << " I386"; 8253 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) { 8254 case MachO::CPU_SUBTYPE_I386_ALL: 8255 outs() << " ALL"; 8256 break; 8257 default: 8258 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK); 8259 break; 8260 } 8261 break; 8262 case MachO::CPU_TYPE_X86_64: 8263 outs() << " X86_64"; 8264 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) { 8265 case MachO::CPU_SUBTYPE_X86_64_ALL: 8266 outs() << " ALL"; 8267 break; 8268 case MachO::CPU_SUBTYPE_X86_64_H: 8269 outs() << " Haswell"; 8270 break; 8271 default: 8272 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK); 8273 break; 8274 } 8275 break; 8276 case MachO::CPU_TYPE_ARM: 8277 outs() << " ARM"; 8278 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) { 8279 case MachO::CPU_SUBTYPE_ARM_ALL: 8280 outs() << " ALL"; 8281 break; 8282 case MachO::CPU_SUBTYPE_ARM_V4T: 8283 outs() << " V4T"; 8284 break; 8285 case MachO::CPU_SUBTYPE_ARM_V5TEJ: 8286 outs() << " V5TEJ"; 8287 break; 8288 case MachO::CPU_SUBTYPE_ARM_XSCALE: 8289 outs() << " XSCALE"; 8290 break; 8291 case MachO::CPU_SUBTYPE_ARM_V6: 8292 outs() << " V6"; 8293 break; 8294 case MachO::CPU_SUBTYPE_ARM_V6M: 8295 outs() << " V6M"; 8296 break; 8297 case MachO::CPU_SUBTYPE_ARM_V7: 8298 outs() << " V7"; 8299 break; 8300 case MachO::CPU_SUBTYPE_ARM_V7EM: 8301 outs() << " V7EM"; 8302 break; 8303 case MachO::CPU_SUBTYPE_ARM_V7K: 8304 outs() << " V7K"; 8305 break; 8306 case MachO::CPU_SUBTYPE_ARM_V7M: 8307 outs() << " V7M"; 8308 break; 8309 case MachO::CPU_SUBTYPE_ARM_V7S: 8310 outs() << " V7S"; 8311 break; 8312 default: 8313 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK); 8314 break; 8315 } 8316 break; 8317 case MachO::CPU_TYPE_ARM64: 8318 outs() << " ARM64"; 8319 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) { 8320 case MachO::CPU_SUBTYPE_ARM64_ALL: 8321 outs() << " ALL"; 8322 break; 8323 case MachO::CPU_SUBTYPE_ARM64_V8: 8324 outs() << " V8"; 8325 break; 8326 case MachO::CPU_SUBTYPE_ARM64E: 8327 outs() << " E"; 8328 break; 8329 default: 8330 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK); 8331 break; 8332 } 8333 break; 8334 case MachO::CPU_TYPE_ARM64_32: 8335 outs() << " ARM64_32"; 8336 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) { 8337 case MachO::CPU_SUBTYPE_ARM64_32_V8: 8338 outs() << " V8"; 8339 break; 8340 default: 8341 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK); 8342 break; 8343 } 8344 break; 8345 case MachO::CPU_TYPE_POWERPC: 8346 outs() << " PPC"; 8347 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) { 8348 case MachO::CPU_SUBTYPE_POWERPC_ALL: 8349 outs() << " ALL"; 8350 break; 8351 default: 8352 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK); 8353 break; 8354 } 8355 break; 8356 case MachO::CPU_TYPE_POWERPC64: 8357 outs() << " PPC64"; 8358 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) { 8359 case MachO::CPU_SUBTYPE_POWERPC_ALL: 8360 outs() << " ALL"; 8361 break; 8362 default: 8363 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK); 8364 break; 8365 } 8366 break; 8367 default: 8368 outs() << format(" %7d", cputype); 8369 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK); 8370 break; 8371 } 8372 if ((cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64) { 8373 outs() << " LIB64"; 8374 } else { 8375 outs() << format(" 0x%02" PRIx32, 8376 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24); 8377 } 8378 switch (filetype) { 8379 case MachO::MH_OBJECT: 8380 outs() << " OBJECT"; 8381 break; 8382 case MachO::MH_EXECUTE: 8383 outs() << " EXECUTE"; 8384 break; 8385 case MachO::MH_FVMLIB: 8386 outs() << " FVMLIB"; 8387 break; 8388 case MachO::MH_CORE: 8389 outs() << " CORE"; 8390 break; 8391 case MachO::MH_PRELOAD: 8392 outs() << " PRELOAD"; 8393 break; 8394 case MachO::MH_DYLIB: 8395 outs() << " DYLIB"; 8396 break; 8397 case MachO::MH_DYLIB_STUB: 8398 outs() << " DYLIB_STUB"; 8399 break; 8400 case MachO::MH_DYLINKER: 8401 outs() << " DYLINKER"; 8402 break; 8403 case MachO::MH_BUNDLE: 8404 outs() << " BUNDLE"; 8405 break; 8406 case MachO::MH_DSYM: 8407 outs() << " DSYM"; 8408 break; 8409 case MachO::MH_KEXT_BUNDLE: 8410 outs() << " KEXTBUNDLE"; 8411 break; 8412 default: 8413 outs() << format(" %10u", filetype); 8414 break; 8415 } 8416 outs() << format(" %5u", ncmds); 8417 outs() << format(" %10u", sizeofcmds); 8418 uint32_t f = flags; 8419 if (f & MachO::MH_NOUNDEFS) { 8420 outs() << " NOUNDEFS"; 8421 f &= ~MachO::MH_NOUNDEFS; 8422 } 8423 if (f & MachO::MH_INCRLINK) { 8424 outs() << " INCRLINK"; 8425 f &= ~MachO::MH_INCRLINK; 8426 } 8427 if (f & MachO::MH_DYLDLINK) { 8428 outs() << " DYLDLINK"; 8429 f &= ~MachO::MH_DYLDLINK; 8430 } 8431 if (f & MachO::MH_BINDATLOAD) { 8432 outs() << " BINDATLOAD"; 8433 f &= ~MachO::MH_BINDATLOAD; 8434 } 8435 if (f & MachO::MH_PREBOUND) { 8436 outs() << " PREBOUND"; 8437 f &= ~MachO::MH_PREBOUND; 8438 } 8439 if (f & MachO::MH_SPLIT_SEGS) { 8440 outs() << " SPLIT_SEGS"; 8441 f &= ~MachO::MH_SPLIT_SEGS; 8442 } 8443 if (f & MachO::MH_LAZY_INIT) { 8444 outs() << " LAZY_INIT"; 8445 f &= ~MachO::MH_LAZY_INIT; 8446 } 8447 if (f & MachO::MH_TWOLEVEL) { 8448 outs() << " TWOLEVEL"; 8449 f &= ~MachO::MH_TWOLEVEL; 8450 } 8451 if (f & MachO::MH_FORCE_FLAT) { 8452 outs() << " FORCE_FLAT"; 8453 f &= ~MachO::MH_FORCE_FLAT; 8454 } 8455 if (f & MachO::MH_NOMULTIDEFS) { 8456 outs() << " NOMULTIDEFS"; 8457 f &= ~MachO::MH_NOMULTIDEFS; 8458 } 8459 if (f & MachO::MH_NOFIXPREBINDING) { 8460 outs() << " NOFIXPREBINDING"; 8461 f &= ~MachO::MH_NOFIXPREBINDING; 8462 } 8463 if (f & MachO::MH_PREBINDABLE) { 8464 outs() << " PREBINDABLE"; 8465 f &= ~MachO::MH_PREBINDABLE; 8466 } 8467 if (f & MachO::MH_ALLMODSBOUND) { 8468 outs() << " ALLMODSBOUND"; 8469 f &= ~MachO::MH_ALLMODSBOUND; 8470 } 8471 if (f & MachO::MH_SUBSECTIONS_VIA_SYMBOLS) { 8472 outs() << " SUBSECTIONS_VIA_SYMBOLS"; 8473 f &= ~MachO::MH_SUBSECTIONS_VIA_SYMBOLS; 8474 } 8475 if (f & MachO::MH_CANONICAL) { 8476 outs() << " CANONICAL"; 8477 f &= ~MachO::MH_CANONICAL; 8478 } 8479 if (f & MachO::MH_WEAK_DEFINES) { 8480 outs() << " WEAK_DEFINES"; 8481 f &= ~MachO::MH_WEAK_DEFINES; 8482 } 8483 if (f & MachO::MH_BINDS_TO_WEAK) { 8484 outs() << " BINDS_TO_WEAK"; 8485 f &= ~MachO::MH_BINDS_TO_WEAK; 8486 } 8487 if (f & MachO::MH_ALLOW_STACK_EXECUTION) { 8488 outs() << " ALLOW_STACK_EXECUTION"; 8489 f &= ~MachO::MH_ALLOW_STACK_EXECUTION; 8490 } 8491 if (f & MachO::MH_DEAD_STRIPPABLE_DYLIB) { 8492 outs() << " DEAD_STRIPPABLE_DYLIB"; 8493 f &= ~MachO::MH_DEAD_STRIPPABLE_DYLIB; 8494 } 8495 if (f & MachO::MH_PIE) { 8496 outs() << " PIE"; 8497 f &= ~MachO::MH_PIE; 8498 } 8499 if (f & MachO::MH_NO_REEXPORTED_DYLIBS) { 8500 outs() << " NO_REEXPORTED_DYLIBS"; 8501 f &= ~MachO::MH_NO_REEXPORTED_DYLIBS; 8502 } 8503 if (f & MachO::MH_HAS_TLV_DESCRIPTORS) { 8504 outs() << " MH_HAS_TLV_DESCRIPTORS"; 8505 f &= ~MachO::MH_HAS_TLV_DESCRIPTORS; 8506 } 8507 if (f & MachO::MH_NO_HEAP_EXECUTION) { 8508 outs() << " MH_NO_HEAP_EXECUTION"; 8509 f &= ~MachO::MH_NO_HEAP_EXECUTION; 8510 } 8511 if (f & MachO::MH_APP_EXTENSION_SAFE) { 8512 outs() << " APP_EXTENSION_SAFE"; 8513 f &= ~MachO::MH_APP_EXTENSION_SAFE; 8514 } 8515 if (f & MachO::MH_NLIST_OUTOFSYNC_WITH_DYLDINFO) { 8516 outs() << " NLIST_OUTOFSYNC_WITH_DYLDINFO"; 8517 f &= ~MachO::MH_NLIST_OUTOFSYNC_WITH_DYLDINFO; 8518 } 8519 if (f != 0 || flags == 0) 8520 outs() << format(" 0x%08" PRIx32, f); 8521 } else { 8522 outs() << format(" 0x%08" PRIx32, magic); 8523 outs() << format(" %7d", cputype); 8524 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK); 8525 outs() << format(" 0x%02" PRIx32, 8526 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24); 8527 outs() << format(" %10u", filetype); 8528 outs() << format(" %5u", ncmds); 8529 outs() << format(" %10u", sizeofcmds); 8530 outs() << format(" 0x%08" PRIx32, flags); 8531 } 8532 outs() << "\n"; 8533 } 8534 8535 static void PrintSegmentCommand(uint32_t cmd, uint32_t cmdsize, 8536 StringRef SegName, uint64_t vmaddr, 8537 uint64_t vmsize, uint64_t fileoff, 8538 uint64_t filesize, uint32_t maxprot, 8539 uint32_t initprot, uint32_t nsects, 8540 uint32_t flags, uint32_t object_size, 8541 bool verbose) { 8542 uint64_t expected_cmdsize; 8543 if (cmd == MachO::LC_SEGMENT) { 8544 outs() << " cmd LC_SEGMENT\n"; 8545 expected_cmdsize = nsects; 8546 expected_cmdsize *= sizeof(struct MachO::section); 8547 expected_cmdsize += sizeof(struct MachO::segment_command); 8548 } else { 8549 outs() << " cmd LC_SEGMENT_64\n"; 8550 expected_cmdsize = nsects; 8551 expected_cmdsize *= sizeof(struct MachO::section_64); 8552 expected_cmdsize += sizeof(struct MachO::segment_command_64); 8553 } 8554 outs() << " cmdsize " << cmdsize; 8555 if (cmdsize != expected_cmdsize) 8556 outs() << " Inconsistent size\n"; 8557 else 8558 outs() << "\n"; 8559 outs() << " segname " << SegName << "\n"; 8560 if (cmd == MachO::LC_SEGMENT_64) { 8561 outs() << " vmaddr " << format("0x%016" PRIx64, vmaddr) << "\n"; 8562 outs() << " vmsize " << format("0x%016" PRIx64, vmsize) << "\n"; 8563 } else { 8564 outs() << " vmaddr " << format("0x%08" PRIx64, vmaddr) << "\n"; 8565 outs() << " vmsize " << format("0x%08" PRIx64, vmsize) << "\n"; 8566 } 8567 outs() << " fileoff " << fileoff; 8568 if (fileoff > object_size) 8569 outs() << " (past end of file)\n"; 8570 else 8571 outs() << "\n"; 8572 outs() << " filesize " << filesize; 8573 if (fileoff + filesize > object_size) 8574 outs() << " (past end of file)\n"; 8575 else 8576 outs() << "\n"; 8577 if (verbose) { 8578 if ((maxprot & 8579 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE | 8580 MachO::VM_PROT_EXECUTE)) != 0) 8581 outs() << " maxprot ?" << format("0x%08" PRIx32, maxprot) << "\n"; 8582 else { 8583 outs() << " maxprot "; 8584 outs() << ((maxprot & MachO::VM_PROT_READ) ? "r" : "-"); 8585 outs() << ((maxprot & MachO::VM_PROT_WRITE) ? "w" : "-"); 8586 outs() << ((maxprot & MachO::VM_PROT_EXECUTE) ? "x\n" : "-\n"); 8587 } 8588 if ((initprot & 8589 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE | 8590 MachO::VM_PROT_EXECUTE)) != 0) 8591 outs() << " initprot ?" << format("0x%08" PRIx32, initprot) << "\n"; 8592 else { 8593 outs() << " initprot "; 8594 outs() << ((initprot & MachO::VM_PROT_READ) ? "r" : "-"); 8595 outs() << ((initprot & MachO::VM_PROT_WRITE) ? "w" : "-"); 8596 outs() << ((initprot & MachO::VM_PROT_EXECUTE) ? "x\n" : "-\n"); 8597 } 8598 } else { 8599 outs() << " maxprot " << format("0x%08" PRIx32, maxprot) << "\n"; 8600 outs() << " initprot " << format("0x%08" PRIx32, initprot) << "\n"; 8601 } 8602 outs() << " nsects " << nsects << "\n"; 8603 if (verbose) { 8604 outs() << " flags"; 8605 if (flags == 0) 8606 outs() << " (none)\n"; 8607 else { 8608 if (flags & MachO::SG_HIGHVM) { 8609 outs() << " HIGHVM"; 8610 flags &= ~MachO::SG_HIGHVM; 8611 } 8612 if (flags & MachO::SG_FVMLIB) { 8613 outs() << " FVMLIB"; 8614 flags &= ~MachO::SG_FVMLIB; 8615 } 8616 if (flags & MachO::SG_NORELOC) { 8617 outs() << " NORELOC"; 8618 flags &= ~MachO::SG_NORELOC; 8619 } 8620 if (flags & MachO::SG_PROTECTED_VERSION_1) { 8621 outs() << " PROTECTED_VERSION_1"; 8622 flags &= ~MachO::SG_PROTECTED_VERSION_1; 8623 } 8624 if (flags) 8625 outs() << format(" 0x%08" PRIx32, flags) << " (unknown flags)\n"; 8626 else 8627 outs() << "\n"; 8628 } 8629 } else { 8630 outs() << " flags " << format("0x%" PRIx32, flags) << "\n"; 8631 } 8632 } 8633 8634 static void PrintSection(const char *sectname, const char *segname, 8635 uint64_t addr, uint64_t size, uint32_t offset, 8636 uint32_t align, uint32_t reloff, uint32_t nreloc, 8637 uint32_t flags, uint32_t reserved1, uint32_t reserved2, 8638 uint32_t cmd, const char *sg_segname, 8639 uint32_t filetype, uint32_t object_size, 8640 bool verbose) { 8641 outs() << "Section\n"; 8642 outs() << " sectname " << format("%.16s\n", sectname); 8643 outs() << " segname " << format("%.16s", segname); 8644 if (filetype != MachO::MH_OBJECT && strncmp(sg_segname, segname, 16) != 0) 8645 outs() << " (does not match segment)\n"; 8646 else 8647 outs() << "\n"; 8648 if (cmd == MachO::LC_SEGMENT_64) { 8649 outs() << " addr " << format("0x%016" PRIx64, addr) << "\n"; 8650 outs() << " size " << format("0x%016" PRIx64, size); 8651 } else { 8652 outs() << " addr " << format("0x%08" PRIx64, addr) << "\n"; 8653 outs() << " size " << format("0x%08" PRIx64, size); 8654 } 8655 if ((flags & MachO::S_ZEROFILL) != 0 && offset + size > object_size) 8656 outs() << " (past end of file)\n"; 8657 else 8658 outs() << "\n"; 8659 outs() << " offset " << offset; 8660 if (offset > object_size) 8661 outs() << " (past end of file)\n"; 8662 else 8663 outs() << "\n"; 8664 uint32_t align_shifted = 1 << align; 8665 outs() << " align 2^" << align << " (" << align_shifted << ")\n"; 8666 outs() << " reloff " << reloff; 8667 if (reloff > object_size) 8668 outs() << " (past end of file)\n"; 8669 else 8670 outs() << "\n"; 8671 outs() << " nreloc " << nreloc; 8672 if (reloff + nreloc * sizeof(struct MachO::relocation_info) > object_size) 8673 outs() << " (past end of file)\n"; 8674 else 8675 outs() << "\n"; 8676 uint32_t section_type = flags & MachO::SECTION_TYPE; 8677 if (verbose) { 8678 outs() << " type"; 8679 if (section_type == MachO::S_REGULAR) 8680 outs() << " S_REGULAR\n"; 8681 else if (section_type == MachO::S_ZEROFILL) 8682 outs() << " S_ZEROFILL\n"; 8683 else if (section_type == MachO::S_CSTRING_LITERALS) 8684 outs() << " S_CSTRING_LITERALS\n"; 8685 else if (section_type == MachO::S_4BYTE_LITERALS) 8686 outs() << " S_4BYTE_LITERALS\n"; 8687 else if (section_type == MachO::S_8BYTE_LITERALS) 8688 outs() << " S_8BYTE_LITERALS\n"; 8689 else if (section_type == MachO::S_16BYTE_LITERALS) 8690 outs() << " S_16BYTE_LITERALS\n"; 8691 else if (section_type == MachO::S_LITERAL_POINTERS) 8692 outs() << " S_LITERAL_POINTERS\n"; 8693 else if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS) 8694 outs() << " S_NON_LAZY_SYMBOL_POINTERS\n"; 8695 else if (section_type == MachO::S_LAZY_SYMBOL_POINTERS) 8696 outs() << " S_LAZY_SYMBOL_POINTERS\n"; 8697 else if (section_type == MachO::S_SYMBOL_STUBS) 8698 outs() << " S_SYMBOL_STUBS\n"; 8699 else if (section_type == MachO::S_MOD_INIT_FUNC_POINTERS) 8700 outs() << " S_MOD_INIT_FUNC_POINTERS\n"; 8701 else if (section_type == MachO::S_MOD_TERM_FUNC_POINTERS) 8702 outs() << " S_MOD_TERM_FUNC_POINTERS\n"; 8703 else if (section_type == MachO::S_COALESCED) 8704 outs() << " S_COALESCED\n"; 8705 else if (section_type == MachO::S_INTERPOSING) 8706 outs() << " S_INTERPOSING\n"; 8707 else if (section_type == MachO::S_DTRACE_DOF) 8708 outs() << " S_DTRACE_DOF\n"; 8709 else if (section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS) 8710 outs() << " S_LAZY_DYLIB_SYMBOL_POINTERS\n"; 8711 else if (section_type == MachO::S_THREAD_LOCAL_REGULAR) 8712 outs() << " S_THREAD_LOCAL_REGULAR\n"; 8713 else if (section_type == MachO::S_THREAD_LOCAL_ZEROFILL) 8714 outs() << " S_THREAD_LOCAL_ZEROFILL\n"; 8715 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLES) 8716 outs() << " S_THREAD_LOCAL_VARIABLES\n"; 8717 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS) 8718 outs() << " S_THREAD_LOCAL_VARIABLE_POINTERS\n"; 8719 else if (section_type == MachO::S_THREAD_LOCAL_INIT_FUNCTION_POINTERS) 8720 outs() << " S_THREAD_LOCAL_INIT_FUNCTION_POINTERS\n"; 8721 else 8722 outs() << format("0x%08" PRIx32, section_type) << "\n"; 8723 outs() << "attributes"; 8724 uint32_t section_attributes = flags & MachO::SECTION_ATTRIBUTES; 8725 if (section_attributes & MachO::S_ATTR_PURE_INSTRUCTIONS) 8726 outs() << " PURE_INSTRUCTIONS"; 8727 if (section_attributes & MachO::S_ATTR_NO_TOC) 8728 outs() << " NO_TOC"; 8729 if (section_attributes & MachO::S_ATTR_STRIP_STATIC_SYMS) 8730 outs() << " STRIP_STATIC_SYMS"; 8731 if (section_attributes & MachO::S_ATTR_NO_DEAD_STRIP) 8732 outs() << " NO_DEAD_STRIP"; 8733 if (section_attributes & MachO::S_ATTR_LIVE_SUPPORT) 8734 outs() << " LIVE_SUPPORT"; 8735 if (section_attributes & MachO::S_ATTR_SELF_MODIFYING_CODE) 8736 outs() << " SELF_MODIFYING_CODE"; 8737 if (section_attributes & MachO::S_ATTR_DEBUG) 8738 outs() << " DEBUG"; 8739 if (section_attributes & MachO::S_ATTR_SOME_INSTRUCTIONS) 8740 outs() << " SOME_INSTRUCTIONS"; 8741 if (section_attributes & MachO::S_ATTR_EXT_RELOC) 8742 outs() << " EXT_RELOC"; 8743 if (section_attributes & MachO::S_ATTR_LOC_RELOC) 8744 outs() << " LOC_RELOC"; 8745 if (section_attributes == 0) 8746 outs() << " (none)"; 8747 outs() << "\n"; 8748 } else 8749 outs() << " flags " << format("0x%08" PRIx32, flags) << "\n"; 8750 outs() << " reserved1 " << reserved1; 8751 if (section_type == MachO::S_SYMBOL_STUBS || 8752 section_type == MachO::S_LAZY_SYMBOL_POINTERS || 8753 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS || 8754 section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS || 8755 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS) 8756 outs() << " (index into indirect symbol table)\n"; 8757 else 8758 outs() << "\n"; 8759 outs() << " reserved2 " << reserved2; 8760 if (section_type == MachO::S_SYMBOL_STUBS) 8761 outs() << " (size of stubs)\n"; 8762 else 8763 outs() << "\n"; 8764 } 8765 8766 static void PrintSymtabLoadCommand(MachO::symtab_command st, bool Is64Bit, 8767 uint32_t object_size) { 8768 outs() << " cmd LC_SYMTAB\n"; 8769 outs() << " cmdsize " << st.cmdsize; 8770 if (st.cmdsize != sizeof(struct MachO::symtab_command)) 8771 outs() << " Incorrect size\n"; 8772 else 8773 outs() << "\n"; 8774 outs() << " symoff " << st.symoff; 8775 if (st.symoff > object_size) 8776 outs() << " (past end of file)\n"; 8777 else 8778 outs() << "\n"; 8779 outs() << " nsyms " << st.nsyms; 8780 uint64_t big_size; 8781 if (Is64Bit) { 8782 big_size = st.nsyms; 8783 big_size *= sizeof(struct MachO::nlist_64); 8784 big_size += st.symoff; 8785 if (big_size > object_size) 8786 outs() << " (past end of file)\n"; 8787 else 8788 outs() << "\n"; 8789 } else { 8790 big_size = st.nsyms; 8791 big_size *= sizeof(struct MachO::nlist); 8792 big_size += st.symoff; 8793 if (big_size > object_size) 8794 outs() << " (past end of file)\n"; 8795 else 8796 outs() << "\n"; 8797 } 8798 outs() << " stroff " << st.stroff; 8799 if (st.stroff > object_size) 8800 outs() << " (past end of file)\n"; 8801 else 8802 outs() << "\n"; 8803 outs() << " strsize " << st.strsize; 8804 big_size = st.stroff; 8805 big_size += st.strsize; 8806 if (big_size > object_size) 8807 outs() << " (past end of file)\n"; 8808 else 8809 outs() << "\n"; 8810 } 8811 8812 static void PrintDysymtabLoadCommand(MachO::dysymtab_command dyst, 8813 uint32_t nsyms, uint32_t object_size, 8814 bool Is64Bit) { 8815 outs() << " cmd LC_DYSYMTAB\n"; 8816 outs() << " cmdsize " << dyst.cmdsize; 8817 if (dyst.cmdsize != sizeof(struct MachO::dysymtab_command)) 8818 outs() << " Incorrect size\n"; 8819 else 8820 outs() << "\n"; 8821 outs() << " ilocalsym " << dyst.ilocalsym; 8822 if (dyst.ilocalsym > nsyms) 8823 outs() << " (greater than the number of symbols)\n"; 8824 else 8825 outs() << "\n"; 8826 outs() << " nlocalsym " << dyst.nlocalsym; 8827 uint64_t big_size; 8828 big_size = dyst.ilocalsym; 8829 big_size += dyst.nlocalsym; 8830 if (big_size > nsyms) 8831 outs() << " (past the end of the symbol table)\n"; 8832 else 8833 outs() << "\n"; 8834 outs() << " iextdefsym " << dyst.iextdefsym; 8835 if (dyst.iextdefsym > nsyms) 8836 outs() << " (greater than the number of symbols)\n"; 8837 else 8838 outs() << "\n"; 8839 outs() << " nextdefsym " << dyst.nextdefsym; 8840 big_size = dyst.iextdefsym; 8841 big_size += dyst.nextdefsym; 8842 if (big_size > nsyms) 8843 outs() << " (past the end of the symbol table)\n"; 8844 else 8845 outs() << "\n"; 8846 outs() << " iundefsym " << dyst.iundefsym; 8847 if (dyst.iundefsym > nsyms) 8848 outs() << " (greater than the number of symbols)\n"; 8849 else 8850 outs() << "\n"; 8851 outs() << " nundefsym " << dyst.nundefsym; 8852 big_size = dyst.iundefsym; 8853 big_size += dyst.nundefsym; 8854 if (big_size > nsyms) 8855 outs() << " (past the end of the symbol table)\n"; 8856 else 8857 outs() << "\n"; 8858 outs() << " tocoff " << dyst.tocoff; 8859 if (dyst.tocoff > object_size) 8860 outs() << " (past end of file)\n"; 8861 else 8862 outs() << "\n"; 8863 outs() << " ntoc " << dyst.ntoc; 8864 big_size = dyst.ntoc; 8865 big_size *= sizeof(struct MachO::dylib_table_of_contents); 8866 big_size += dyst.tocoff; 8867 if (big_size > object_size) 8868 outs() << " (past end of file)\n"; 8869 else 8870 outs() << "\n"; 8871 outs() << " modtaboff " << dyst.modtaboff; 8872 if (dyst.modtaboff > object_size) 8873 outs() << " (past end of file)\n"; 8874 else 8875 outs() << "\n"; 8876 outs() << " nmodtab " << dyst.nmodtab; 8877 uint64_t modtabend; 8878 if (Is64Bit) { 8879 modtabend = dyst.nmodtab; 8880 modtabend *= sizeof(struct MachO::dylib_module_64); 8881 modtabend += dyst.modtaboff; 8882 } else { 8883 modtabend = dyst.nmodtab; 8884 modtabend *= sizeof(struct MachO::dylib_module); 8885 modtabend += dyst.modtaboff; 8886 } 8887 if (modtabend > object_size) 8888 outs() << " (past end of file)\n"; 8889 else 8890 outs() << "\n"; 8891 outs() << " extrefsymoff " << dyst.extrefsymoff; 8892 if (dyst.extrefsymoff > object_size) 8893 outs() << " (past end of file)\n"; 8894 else 8895 outs() << "\n"; 8896 outs() << " nextrefsyms " << dyst.nextrefsyms; 8897 big_size = dyst.nextrefsyms; 8898 big_size *= sizeof(struct MachO::dylib_reference); 8899 big_size += dyst.extrefsymoff; 8900 if (big_size > object_size) 8901 outs() << " (past end of file)\n"; 8902 else 8903 outs() << "\n"; 8904 outs() << " indirectsymoff " << dyst.indirectsymoff; 8905 if (dyst.indirectsymoff > object_size) 8906 outs() << " (past end of file)\n"; 8907 else 8908 outs() << "\n"; 8909 outs() << " nindirectsyms " << dyst.nindirectsyms; 8910 big_size = dyst.nindirectsyms; 8911 big_size *= sizeof(uint32_t); 8912 big_size += dyst.indirectsymoff; 8913 if (big_size > object_size) 8914 outs() << " (past end of file)\n"; 8915 else 8916 outs() << "\n"; 8917 outs() << " extreloff " << dyst.extreloff; 8918 if (dyst.extreloff > object_size) 8919 outs() << " (past end of file)\n"; 8920 else 8921 outs() << "\n"; 8922 outs() << " nextrel " << dyst.nextrel; 8923 big_size = dyst.nextrel; 8924 big_size *= sizeof(struct MachO::relocation_info); 8925 big_size += dyst.extreloff; 8926 if (big_size > object_size) 8927 outs() << " (past end of file)\n"; 8928 else 8929 outs() << "\n"; 8930 outs() << " locreloff " << dyst.locreloff; 8931 if (dyst.locreloff > object_size) 8932 outs() << " (past end of file)\n"; 8933 else 8934 outs() << "\n"; 8935 outs() << " nlocrel " << dyst.nlocrel; 8936 big_size = dyst.nlocrel; 8937 big_size *= sizeof(struct MachO::relocation_info); 8938 big_size += dyst.locreloff; 8939 if (big_size > object_size) 8940 outs() << " (past end of file)\n"; 8941 else 8942 outs() << "\n"; 8943 } 8944 8945 static void PrintDyldInfoLoadCommand(MachO::dyld_info_command dc, 8946 uint32_t object_size) { 8947 if (dc.cmd == MachO::LC_DYLD_INFO) 8948 outs() << " cmd LC_DYLD_INFO\n"; 8949 else 8950 outs() << " cmd LC_DYLD_INFO_ONLY\n"; 8951 outs() << " cmdsize " << dc.cmdsize; 8952 if (dc.cmdsize != sizeof(struct MachO::dyld_info_command)) 8953 outs() << " Incorrect size\n"; 8954 else 8955 outs() << "\n"; 8956 outs() << " rebase_off " << dc.rebase_off; 8957 if (dc.rebase_off > object_size) 8958 outs() << " (past end of file)\n"; 8959 else 8960 outs() << "\n"; 8961 outs() << " rebase_size " << dc.rebase_size; 8962 uint64_t big_size; 8963 big_size = dc.rebase_off; 8964 big_size += dc.rebase_size; 8965 if (big_size > object_size) 8966 outs() << " (past end of file)\n"; 8967 else 8968 outs() << "\n"; 8969 outs() << " bind_off " << dc.bind_off; 8970 if (dc.bind_off > object_size) 8971 outs() << " (past end of file)\n"; 8972 else 8973 outs() << "\n"; 8974 outs() << " bind_size " << dc.bind_size; 8975 big_size = dc.bind_off; 8976 big_size += dc.bind_size; 8977 if (big_size > object_size) 8978 outs() << " (past end of file)\n"; 8979 else 8980 outs() << "\n"; 8981 outs() << " weak_bind_off " << dc.weak_bind_off; 8982 if (dc.weak_bind_off > object_size) 8983 outs() << " (past end of file)\n"; 8984 else 8985 outs() << "\n"; 8986 outs() << " weak_bind_size " << dc.weak_bind_size; 8987 big_size = dc.weak_bind_off; 8988 big_size += dc.weak_bind_size; 8989 if (big_size > object_size) 8990 outs() << " (past end of file)\n"; 8991 else 8992 outs() << "\n"; 8993 outs() << " lazy_bind_off " << dc.lazy_bind_off; 8994 if (dc.lazy_bind_off > object_size) 8995 outs() << " (past end of file)\n"; 8996 else 8997 outs() << "\n"; 8998 outs() << " lazy_bind_size " << dc.lazy_bind_size; 8999 big_size = dc.lazy_bind_off; 9000 big_size += dc.lazy_bind_size; 9001 if (big_size > object_size) 9002 outs() << " (past end of file)\n"; 9003 else 9004 outs() << "\n"; 9005 outs() << " export_off " << dc.export_off; 9006 if (dc.export_off > object_size) 9007 outs() << " (past end of file)\n"; 9008 else 9009 outs() << "\n"; 9010 outs() << " export_size " << dc.export_size; 9011 big_size = dc.export_off; 9012 big_size += dc.export_size; 9013 if (big_size > object_size) 9014 outs() << " (past end of file)\n"; 9015 else 9016 outs() << "\n"; 9017 } 9018 9019 static void PrintDyldLoadCommand(MachO::dylinker_command dyld, 9020 const char *Ptr) { 9021 if (dyld.cmd == MachO::LC_ID_DYLINKER) 9022 outs() << " cmd LC_ID_DYLINKER\n"; 9023 else if (dyld.cmd == MachO::LC_LOAD_DYLINKER) 9024 outs() << " cmd LC_LOAD_DYLINKER\n"; 9025 else if (dyld.cmd == MachO::LC_DYLD_ENVIRONMENT) 9026 outs() << " cmd LC_DYLD_ENVIRONMENT\n"; 9027 else 9028 outs() << " cmd ?(" << dyld.cmd << ")\n"; 9029 outs() << " cmdsize " << dyld.cmdsize; 9030 if (dyld.cmdsize < sizeof(struct MachO::dylinker_command)) 9031 outs() << " Incorrect size\n"; 9032 else 9033 outs() << "\n"; 9034 if (dyld.name >= dyld.cmdsize) 9035 outs() << " name ?(bad offset " << dyld.name << ")\n"; 9036 else { 9037 const char *P = (const char *)(Ptr) + dyld.name; 9038 outs() << " name " << P << " (offset " << dyld.name << ")\n"; 9039 } 9040 } 9041 9042 static void PrintUuidLoadCommand(MachO::uuid_command uuid) { 9043 outs() << " cmd LC_UUID\n"; 9044 outs() << " cmdsize " << uuid.cmdsize; 9045 if (uuid.cmdsize != sizeof(struct MachO::uuid_command)) 9046 outs() << " Incorrect size\n"; 9047 else 9048 outs() << "\n"; 9049 outs() << " uuid "; 9050 for (int i = 0; i < 16; ++i) { 9051 outs() << format("%02" PRIX32, uuid.uuid[i]); 9052 if (i == 3 || i == 5 || i == 7 || i == 9) 9053 outs() << "-"; 9054 } 9055 outs() << "\n"; 9056 } 9057 9058 static void PrintRpathLoadCommand(MachO::rpath_command rpath, const char *Ptr) { 9059 outs() << " cmd LC_RPATH\n"; 9060 outs() << " cmdsize " << rpath.cmdsize; 9061 if (rpath.cmdsize < sizeof(struct MachO::rpath_command)) 9062 outs() << " Incorrect size\n"; 9063 else 9064 outs() << "\n"; 9065 if (rpath.path >= rpath.cmdsize) 9066 outs() << " path ?(bad offset " << rpath.path << ")\n"; 9067 else { 9068 const char *P = (const char *)(Ptr) + rpath.path; 9069 outs() << " path " << P << " (offset " << rpath.path << ")\n"; 9070 } 9071 } 9072 9073 static void PrintVersionMinLoadCommand(MachO::version_min_command vd) { 9074 StringRef LoadCmdName; 9075 switch (vd.cmd) { 9076 case MachO::LC_VERSION_MIN_MACOSX: 9077 LoadCmdName = "LC_VERSION_MIN_MACOSX"; 9078 break; 9079 case MachO::LC_VERSION_MIN_IPHONEOS: 9080 LoadCmdName = "LC_VERSION_MIN_IPHONEOS"; 9081 break; 9082 case MachO::LC_VERSION_MIN_TVOS: 9083 LoadCmdName = "LC_VERSION_MIN_TVOS"; 9084 break; 9085 case MachO::LC_VERSION_MIN_WATCHOS: 9086 LoadCmdName = "LC_VERSION_MIN_WATCHOS"; 9087 break; 9088 default: 9089 llvm_unreachable("Unknown version min load command"); 9090 } 9091 9092 outs() << " cmd " << LoadCmdName << '\n'; 9093 outs() << " cmdsize " << vd.cmdsize; 9094 if (vd.cmdsize != sizeof(struct MachO::version_min_command)) 9095 outs() << " Incorrect size\n"; 9096 else 9097 outs() << "\n"; 9098 outs() << " version " 9099 << MachOObjectFile::getVersionMinMajor(vd, false) << "." 9100 << MachOObjectFile::getVersionMinMinor(vd, false); 9101 uint32_t Update = MachOObjectFile::getVersionMinUpdate(vd, false); 9102 if (Update != 0) 9103 outs() << "." << Update; 9104 outs() << "\n"; 9105 if (vd.sdk == 0) 9106 outs() << " sdk n/a"; 9107 else { 9108 outs() << " sdk " 9109 << MachOObjectFile::getVersionMinMajor(vd, true) << "." 9110 << MachOObjectFile::getVersionMinMinor(vd, true); 9111 } 9112 Update = MachOObjectFile::getVersionMinUpdate(vd, true); 9113 if (Update != 0) 9114 outs() << "." << Update; 9115 outs() << "\n"; 9116 } 9117 9118 static void PrintNoteLoadCommand(MachO::note_command Nt) { 9119 outs() << " cmd LC_NOTE\n"; 9120 outs() << " cmdsize " << Nt.cmdsize; 9121 if (Nt.cmdsize != sizeof(struct MachO::note_command)) 9122 outs() << " Incorrect size\n"; 9123 else 9124 outs() << "\n"; 9125 const char *d = Nt.data_owner; 9126 outs() << "data_owner " << format("%.16s\n", d); 9127 outs() << " offset " << Nt.offset << "\n"; 9128 outs() << " size " << Nt.size << "\n"; 9129 } 9130 9131 static void PrintBuildToolVersion(MachO::build_tool_version bv) { 9132 outs() << " tool " << MachOObjectFile::getBuildTool(bv.tool) << "\n"; 9133 outs() << " version " << MachOObjectFile::getVersionString(bv.version) 9134 << "\n"; 9135 } 9136 9137 static void PrintBuildVersionLoadCommand(const MachOObjectFile *obj, 9138 MachO::build_version_command bd) { 9139 outs() << " cmd LC_BUILD_VERSION\n"; 9140 outs() << " cmdsize " << bd.cmdsize; 9141 if (bd.cmdsize != 9142 sizeof(struct MachO::build_version_command) + 9143 bd.ntools * sizeof(struct MachO::build_tool_version)) 9144 outs() << " Incorrect size\n"; 9145 else 9146 outs() << "\n"; 9147 outs() << " platform " << MachOObjectFile::getBuildPlatform(bd.platform) 9148 << "\n"; 9149 if (bd.sdk) 9150 outs() << " sdk " << MachOObjectFile::getVersionString(bd.sdk) 9151 << "\n"; 9152 else 9153 outs() << " sdk n/a\n"; 9154 outs() << " minos " << MachOObjectFile::getVersionString(bd.minos) 9155 << "\n"; 9156 outs() << " ntools " << bd.ntools << "\n"; 9157 for (unsigned i = 0; i < bd.ntools; ++i) { 9158 MachO::build_tool_version bv = obj->getBuildToolVersion(i); 9159 PrintBuildToolVersion(bv); 9160 } 9161 } 9162 9163 static void PrintSourceVersionCommand(MachO::source_version_command sd) { 9164 outs() << " cmd LC_SOURCE_VERSION\n"; 9165 outs() << " cmdsize " << sd.cmdsize; 9166 if (sd.cmdsize != sizeof(struct MachO::source_version_command)) 9167 outs() << " Incorrect size\n"; 9168 else 9169 outs() << "\n"; 9170 uint64_t a = (sd.version >> 40) & 0xffffff; 9171 uint64_t b = (sd.version >> 30) & 0x3ff; 9172 uint64_t c = (sd.version >> 20) & 0x3ff; 9173 uint64_t d = (sd.version >> 10) & 0x3ff; 9174 uint64_t e = sd.version & 0x3ff; 9175 outs() << " version " << a << "." << b; 9176 if (e != 0) 9177 outs() << "." << c << "." << d << "." << e; 9178 else if (d != 0) 9179 outs() << "." << c << "." << d; 9180 else if (c != 0) 9181 outs() << "." << c; 9182 outs() << "\n"; 9183 } 9184 9185 static void PrintEntryPointCommand(MachO::entry_point_command ep) { 9186 outs() << " cmd LC_MAIN\n"; 9187 outs() << " cmdsize " << ep.cmdsize; 9188 if (ep.cmdsize != sizeof(struct MachO::entry_point_command)) 9189 outs() << " Incorrect size\n"; 9190 else 9191 outs() << "\n"; 9192 outs() << " entryoff " << ep.entryoff << "\n"; 9193 outs() << " stacksize " << ep.stacksize << "\n"; 9194 } 9195 9196 static void PrintEncryptionInfoCommand(MachO::encryption_info_command ec, 9197 uint32_t object_size) { 9198 outs() << " cmd LC_ENCRYPTION_INFO\n"; 9199 outs() << " cmdsize " << ec.cmdsize; 9200 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command)) 9201 outs() << " Incorrect size\n"; 9202 else 9203 outs() << "\n"; 9204 outs() << " cryptoff " << ec.cryptoff; 9205 if (ec.cryptoff > object_size) 9206 outs() << " (past end of file)\n"; 9207 else 9208 outs() << "\n"; 9209 outs() << " cryptsize " << ec.cryptsize; 9210 if (ec.cryptsize > object_size) 9211 outs() << " (past end of file)\n"; 9212 else 9213 outs() << "\n"; 9214 outs() << " cryptid " << ec.cryptid << "\n"; 9215 } 9216 9217 static void PrintEncryptionInfoCommand64(MachO::encryption_info_command_64 ec, 9218 uint32_t object_size) { 9219 outs() << " cmd LC_ENCRYPTION_INFO_64\n"; 9220 outs() << " cmdsize " << ec.cmdsize; 9221 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command_64)) 9222 outs() << " Incorrect size\n"; 9223 else 9224 outs() << "\n"; 9225 outs() << " cryptoff " << ec.cryptoff; 9226 if (ec.cryptoff > object_size) 9227 outs() << " (past end of file)\n"; 9228 else 9229 outs() << "\n"; 9230 outs() << " cryptsize " << ec.cryptsize; 9231 if (ec.cryptsize > object_size) 9232 outs() << " (past end of file)\n"; 9233 else 9234 outs() << "\n"; 9235 outs() << " cryptid " << ec.cryptid << "\n"; 9236 outs() << " pad " << ec.pad << "\n"; 9237 } 9238 9239 static void PrintLinkerOptionCommand(MachO::linker_option_command lo, 9240 const char *Ptr) { 9241 outs() << " cmd LC_LINKER_OPTION\n"; 9242 outs() << " cmdsize " << lo.cmdsize; 9243 if (lo.cmdsize < sizeof(struct MachO::linker_option_command)) 9244 outs() << " Incorrect size\n"; 9245 else 9246 outs() << "\n"; 9247 outs() << " count " << lo.count << "\n"; 9248 const char *string = Ptr + sizeof(struct MachO::linker_option_command); 9249 uint32_t left = lo.cmdsize - sizeof(struct MachO::linker_option_command); 9250 uint32_t i = 0; 9251 while (left > 0) { 9252 while (*string == '\0' && left > 0) { 9253 string++; 9254 left--; 9255 } 9256 if (left > 0) { 9257 i++; 9258 outs() << " string #" << i << " " << format("%.*s\n", left, string); 9259 uint32_t NullPos = StringRef(string, left).find('\0'); 9260 uint32_t len = std::min(NullPos, left) + 1; 9261 string += len; 9262 left -= len; 9263 } 9264 } 9265 if (lo.count != i) 9266 outs() << " count " << lo.count << " does not match number of strings " 9267 << i << "\n"; 9268 } 9269 9270 static void PrintSubFrameworkCommand(MachO::sub_framework_command sub, 9271 const char *Ptr) { 9272 outs() << " cmd LC_SUB_FRAMEWORK\n"; 9273 outs() << " cmdsize " << sub.cmdsize; 9274 if (sub.cmdsize < sizeof(struct MachO::sub_framework_command)) 9275 outs() << " Incorrect size\n"; 9276 else 9277 outs() << "\n"; 9278 if (sub.umbrella < sub.cmdsize) { 9279 const char *P = Ptr + sub.umbrella; 9280 outs() << " umbrella " << P << " (offset " << sub.umbrella << ")\n"; 9281 } else { 9282 outs() << " umbrella ?(bad offset " << sub.umbrella << ")\n"; 9283 } 9284 } 9285 9286 static void PrintSubUmbrellaCommand(MachO::sub_umbrella_command sub, 9287 const char *Ptr) { 9288 outs() << " cmd LC_SUB_UMBRELLA\n"; 9289 outs() << " cmdsize " << sub.cmdsize; 9290 if (sub.cmdsize < sizeof(struct MachO::sub_umbrella_command)) 9291 outs() << " Incorrect size\n"; 9292 else 9293 outs() << "\n"; 9294 if (sub.sub_umbrella < sub.cmdsize) { 9295 const char *P = Ptr + sub.sub_umbrella; 9296 outs() << " sub_umbrella " << P << " (offset " << sub.sub_umbrella << ")\n"; 9297 } else { 9298 outs() << " sub_umbrella ?(bad offset " << sub.sub_umbrella << ")\n"; 9299 } 9300 } 9301 9302 static void PrintSubLibraryCommand(MachO::sub_library_command sub, 9303 const char *Ptr) { 9304 outs() << " cmd LC_SUB_LIBRARY\n"; 9305 outs() << " cmdsize " << sub.cmdsize; 9306 if (sub.cmdsize < sizeof(struct MachO::sub_library_command)) 9307 outs() << " Incorrect size\n"; 9308 else 9309 outs() << "\n"; 9310 if (sub.sub_library < sub.cmdsize) { 9311 const char *P = Ptr + sub.sub_library; 9312 outs() << " sub_library " << P << " (offset " << sub.sub_library << ")\n"; 9313 } else { 9314 outs() << " sub_library ?(bad offset " << sub.sub_library << ")\n"; 9315 } 9316 } 9317 9318 static void PrintSubClientCommand(MachO::sub_client_command sub, 9319 const char *Ptr) { 9320 outs() << " cmd LC_SUB_CLIENT\n"; 9321 outs() << " cmdsize " << sub.cmdsize; 9322 if (sub.cmdsize < sizeof(struct MachO::sub_client_command)) 9323 outs() << " Incorrect size\n"; 9324 else 9325 outs() << "\n"; 9326 if (sub.client < sub.cmdsize) { 9327 const char *P = Ptr + sub.client; 9328 outs() << " client " << P << " (offset " << sub.client << ")\n"; 9329 } else { 9330 outs() << " client ?(bad offset " << sub.client << ")\n"; 9331 } 9332 } 9333 9334 static void PrintRoutinesCommand(MachO::routines_command r) { 9335 outs() << " cmd LC_ROUTINES\n"; 9336 outs() << " cmdsize " << r.cmdsize; 9337 if (r.cmdsize != sizeof(struct MachO::routines_command)) 9338 outs() << " Incorrect size\n"; 9339 else 9340 outs() << "\n"; 9341 outs() << " init_address " << format("0x%08" PRIx32, r.init_address) << "\n"; 9342 outs() << " init_module " << r.init_module << "\n"; 9343 outs() << " reserved1 " << r.reserved1 << "\n"; 9344 outs() << " reserved2 " << r.reserved2 << "\n"; 9345 outs() << " reserved3 " << r.reserved3 << "\n"; 9346 outs() << " reserved4 " << r.reserved4 << "\n"; 9347 outs() << " reserved5 " << r.reserved5 << "\n"; 9348 outs() << " reserved6 " << r.reserved6 << "\n"; 9349 } 9350 9351 static void PrintRoutinesCommand64(MachO::routines_command_64 r) { 9352 outs() << " cmd LC_ROUTINES_64\n"; 9353 outs() << " cmdsize " << r.cmdsize; 9354 if (r.cmdsize != sizeof(struct MachO::routines_command_64)) 9355 outs() << " Incorrect size\n"; 9356 else 9357 outs() << "\n"; 9358 outs() << " init_address " << format("0x%016" PRIx64, r.init_address) << "\n"; 9359 outs() << " init_module " << r.init_module << "\n"; 9360 outs() << " reserved1 " << r.reserved1 << "\n"; 9361 outs() << " reserved2 " << r.reserved2 << "\n"; 9362 outs() << " reserved3 " << r.reserved3 << "\n"; 9363 outs() << " reserved4 " << r.reserved4 << "\n"; 9364 outs() << " reserved5 " << r.reserved5 << "\n"; 9365 outs() << " reserved6 " << r.reserved6 << "\n"; 9366 } 9367 9368 static void Print_x86_thread_state32_t(MachO::x86_thread_state32_t &cpu32) { 9369 outs() << "\t eax " << format("0x%08" PRIx32, cpu32.eax); 9370 outs() << " ebx " << format("0x%08" PRIx32, cpu32.ebx); 9371 outs() << " ecx " << format("0x%08" PRIx32, cpu32.ecx); 9372 outs() << " edx " << format("0x%08" PRIx32, cpu32.edx) << "\n"; 9373 outs() << "\t edi " << format("0x%08" PRIx32, cpu32.edi); 9374 outs() << " esi " << format("0x%08" PRIx32, cpu32.esi); 9375 outs() << " ebp " << format("0x%08" PRIx32, cpu32.ebp); 9376 outs() << " esp " << format("0x%08" PRIx32, cpu32.esp) << "\n"; 9377 outs() << "\t ss " << format("0x%08" PRIx32, cpu32.ss); 9378 outs() << " eflags " << format("0x%08" PRIx32, cpu32.eflags); 9379 outs() << " eip " << format("0x%08" PRIx32, cpu32.eip); 9380 outs() << " cs " << format("0x%08" PRIx32, cpu32.cs) << "\n"; 9381 outs() << "\t ds " << format("0x%08" PRIx32, cpu32.ds); 9382 outs() << " es " << format("0x%08" PRIx32, cpu32.es); 9383 outs() << " fs " << format("0x%08" PRIx32, cpu32.fs); 9384 outs() << " gs " << format("0x%08" PRIx32, cpu32.gs) << "\n"; 9385 } 9386 9387 static void Print_x86_thread_state64_t(MachO::x86_thread_state64_t &cpu64) { 9388 outs() << " rax " << format("0x%016" PRIx64, cpu64.rax); 9389 outs() << " rbx " << format("0x%016" PRIx64, cpu64.rbx); 9390 outs() << " rcx " << format("0x%016" PRIx64, cpu64.rcx) << "\n"; 9391 outs() << " rdx " << format("0x%016" PRIx64, cpu64.rdx); 9392 outs() << " rdi " << format("0x%016" PRIx64, cpu64.rdi); 9393 outs() << " rsi " << format("0x%016" PRIx64, cpu64.rsi) << "\n"; 9394 outs() << " rbp " << format("0x%016" PRIx64, cpu64.rbp); 9395 outs() << " rsp " << format("0x%016" PRIx64, cpu64.rsp); 9396 outs() << " r8 " << format("0x%016" PRIx64, cpu64.r8) << "\n"; 9397 outs() << " r9 " << format("0x%016" PRIx64, cpu64.r9); 9398 outs() << " r10 " << format("0x%016" PRIx64, cpu64.r10); 9399 outs() << " r11 " << format("0x%016" PRIx64, cpu64.r11) << "\n"; 9400 outs() << " r12 " << format("0x%016" PRIx64, cpu64.r12); 9401 outs() << " r13 " << format("0x%016" PRIx64, cpu64.r13); 9402 outs() << " r14 " << format("0x%016" PRIx64, cpu64.r14) << "\n"; 9403 outs() << " r15 " << format("0x%016" PRIx64, cpu64.r15); 9404 outs() << " rip " << format("0x%016" PRIx64, cpu64.rip) << "\n"; 9405 outs() << "rflags " << format("0x%016" PRIx64, cpu64.rflags); 9406 outs() << " cs " << format("0x%016" PRIx64, cpu64.cs); 9407 outs() << " fs " << format("0x%016" PRIx64, cpu64.fs) << "\n"; 9408 outs() << " gs " << format("0x%016" PRIx64, cpu64.gs) << "\n"; 9409 } 9410 9411 static void Print_mmst_reg(MachO::mmst_reg_t &r) { 9412 uint32_t f; 9413 outs() << "\t mmst_reg "; 9414 for (f = 0; f < 10; f++) 9415 outs() << format("%02" PRIx32, (r.mmst_reg[f] & 0xff)) << " "; 9416 outs() << "\n"; 9417 outs() << "\t mmst_rsrv "; 9418 for (f = 0; f < 6; f++) 9419 outs() << format("%02" PRIx32, (r.mmst_rsrv[f] & 0xff)) << " "; 9420 outs() << "\n"; 9421 } 9422 9423 static void Print_xmm_reg(MachO::xmm_reg_t &r) { 9424 uint32_t f; 9425 outs() << "\t xmm_reg "; 9426 for (f = 0; f < 16; f++) 9427 outs() << format("%02" PRIx32, (r.xmm_reg[f] & 0xff)) << " "; 9428 outs() << "\n"; 9429 } 9430 9431 static void Print_x86_float_state_t(MachO::x86_float_state64_t &fpu) { 9432 outs() << "\t fpu_reserved[0] " << fpu.fpu_reserved[0]; 9433 outs() << " fpu_reserved[1] " << fpu.fpu_reserved[1] << "\n"; 9434 outs() << "\t control: invalid " << fpu.fpu_fcw.invalid; 9435 outs() << " denorm " << fpu.fpu_fcw.denorm; 9436 outs() << " zdiv " << fpu.fpu_fcw.zdiv; 9437 outs() << " ovrfl " << fpu.fpu_fcw.ovrfl; 9438 outs() << " undfl " << fpu.fpu_fcw.undfl; 9439 outs() << " precis " << fpu.fpu_fcw.precis << "\n"; 9440 outs() << "\t\t pc "; 9441 if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_24B) 9442 outs() << "FP_PREC_24B "; 9443 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_53B) 9444 outs() << "FP_PREC_53B "; 9445 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_64B) 9446 outs() << "FP_PREC_64B "; 9447 else 9448 outs() << fpu.fpu_fcw.pc << " "; 9449 outs() << "rc "; 9450 if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_NEAR) 9451 outs() << "FP_RND_NEAR "; 9452 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_DOWN) 9453 outs() << "FP_RND_DOWN "; 9454 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_UP) 9455 outs() << "FP_RND_UP "; 9456 else if (fpu.fpu_fcw.rc == MachO::x86_FP_CHOP) 9457 outs() << "FP_CHOP "; 9458 outs() << "\n"; 9459 outs() << "\t status: invalid " << fpu.fpu_fsw.invalid; 9460 outs() << " denorm " << fpu.fpu_fsw.denorm; 9461 outs() << " zdiv " << fpu.fpu_fsw.zdiv; 9462 outs() << " ovrfl " << fpu.fpu_fsw.ovrfl; 9463 outs() << " undfl " << fpu.fpu_fsw.undfl; 9464 outs() << " precis " << fpu.fpu_fsw.precis; 9465 outs() << " stkflt " << fpu.fpu_fsw.stkflt << "\n"; 9466 outs() << "\t errsumm " << fpu.fpu_fsw.errsumm; 9467 outs() << " c0 " << fpu.fpu_fsw.c0; 9468 outs() << " c1 " << fpu.fpu_fsw.c1; 9469 outs() << " c2 " << fpu.fpu_fsw.c2; 9470 outs() << " tos " << fpu.fpu_fsw.tos; 9471 outs() << " c3 " << fpu.fpu_fsw.c3; 9472 outs() << " busy " << fpu.fpu_fsw.busy << "\n"; 9473 outs() << "\t fpu_ftw " << format("0x%02" PRIx32, fpu.fpu_ftw); 9474 outs() << " fpu_rsrv1 " << format("0x%02" PRIx32, fpu.fpu_rsrv1); 9475 outs() << " fpu_fop " << format("0x%04" PRIx32, fpu.fpu_fop); 9476 outs() << " fpu_ip " << format("0x%08" PRIx32, fpu.fpu_ip) << "\n"; 9477 outs() << "\t fpu_cs " << format("0x%04" PRIx32, fpu.fpu_cs); 9478 outs() << " fpu_rsrv2 " << format("0x%04" PRIx32, fpu.fpu_rsrv2); 9479 outs() << " fpu_dp " << format("0x%08" PRIx32, fpu.fpu_dp); 9480 outs() << " fpu_ds " << format("0x%04" PRIx32, fpu.fpu_ds) << "\n"; 9481 outs() << "\t fpu_rsrv3 " << format("0x%04" PRIx32, fpu.fpu_rsrv3); 9482 outs() << " fpu_mxcsr " << format("0x%08" PRIx32, fpu.fpu_mxcsr); 9483 outs() << " fpu_mxcsrmask " << format("0x%08" PRIx32, fpu.fpu_mxcsrmask); 9484 outs() << "\n"; 9485 outs() << "\t fpu_stmm0:\n"; 9486 Print_mmst_reg(fpu.fpu_stmm0); 9487 outs() << "\t fpu_stmm1:\n"; 9488 Print_mmst_reg(fpu.fpu_stmm1); 9489 outs() << "\t fpu_stmm2:\n"; 9490 Print_mmst_reg(fpu.fpu_stmm2); 9491 outs() << "\t fpu_stmm3:\n"; 9492 Print_mmst_reg(fpu.fpu_stmm3); 9493 outs() << "\t fpu_stmm4:\n"; 9494 Print_mmst_reg(fpu.fpu_stmm4); 9495 outs() << "\t fpu_stmm5:\n"; 9496 Print_mmst_reg(fpu.fpu_stmm5); 9497 outs() << "\t fpu_stmm6:\n"; 9498 Print_mmst_reg(fpu.fpu_stmm6); 9499 outs() << "\t fpu_stmm7:\n"; 9500 Print_mmst_reg(fpu.fpu_stmm7); 9501 outs() << "\t fpu_xmm0:\n"; 9502 Print_xmm_reg(fpu.fpu_xmm0); 9503 outs() << "\t fpu_xmm1:\n"; 9504 Print_xmm_reg(fpu.fpu_xmm1); 9505 outs() << "\t fpu_xmm2:\n"; 9506 Print_xmm_reg(fpu.fpu_xmm2); 9507 outs() << "\t fpu_xmm3:\n"; 9508 Print_xmm_reg(fpu.fpu_xmm3); 9509 outs() << "\t fpu_xmm4:\n"; 9510 Print_xmm_reg(fpu.fpu_xmm4); 9511 outs() << "\t fpu_xmm5:\n"; 9512 Print_xmm_reg(fpu.fpu_xmm5); 9513 outs() << "\t fpu_xmm6:\n"; 9514 Print_xmm_reg(fpu.fpu_xmm6); 9515 outs() << "\t fpu_xmm7:\n"; 9516 Print_xmm_reg(fpu.fpu_xmm7); 9517 outs() << "\t fpu_xmm8:\n"; 9518 Print_xmm_reg(fpu.fpu_xmm8); 9519 outs() << "\t fpu_xmm9:\n"; 9520 Print_xmm_reg(fpu.fpu_xmm9); 9521 outs() << "\t fpu_xmm10:\n"; 9522 Print_xmm_reg(fpu.fpu_xmm10); 9523 outs() << "\t fpu_xmm11:\n"; 9524 Print_xmm_reg(fpu.fpu_xmm11); 9525 outs() << "\t fpu_xmm12:\n"; 9526 Print_xmm_reg(fpu.fpu_xmm12); 9527 outs() << "\t fpu_xmm13:\n"; 9528 Print_xmm_reg(fpu.fpu_xmm13); 9529 outs() << "\t fpu_xmm14:\n"; 9530 Print_xmm_reg(fpu.fpu_xmm14); 9531 outs() << "\t fpu_xmm15:\n"; 9532 Print_xmm_reg(fpu.fpu_xmm15); 9533 outs() << "\t fpu_rsrv4:\n"; 9534 for (uint32_t f = 0; f < 6; f++) { 9535 outs() << "\t "; 9536 for (uint32_t g = 0; g < 16; g++) 9537 outs() << format("%02" PRIx32, fpu.fpu_rsrv4[f * g]) << " "; 9538 outs() << "\n"; 9539 } 9540 outs() << "\t fpu_reserved1 " << format("0x%08" PRIx32, fpu.fpu_reserved1); 9541 outs() << "\n"; 9542 } 9543 9544 static void Print_x86_exception_state_t(MachO::x86_exception_state64_t &exc64) { 9545 outs() << "\t trapno " << format("0x%08" PRIx32, exc64.trapno); 9546 outs() << " err " << format("0x%08" PRIx32, exc64.err); 9547 outs() << " faultvaddr " << format("0x%016" PRIx64, exc64.faultvaddr) << "\n"; 9548 } 9549 9550 static void Print_arm_thread_state32_t(MachO::arm_thread_state32_t &cpu32) { 9551 outs() << "\t r0 " << format("0x%08" PRIx32, cpu32.r[0]); 9552 outs() << " r1 " << format("0x%08" PRIx32, cpu32.r[1]); 9553 outs() << " r2 " << format("0x%08" PRIx32, cpu32.r[2]); 9554 outs() << " r3 " << format("0x%08" PRIx32, cpu32.r[3]) << "\n"; 9555 outs() << "\t r4 " << format("0x%08" PRIx32, cpu32.r[4]); 9556 outs() << " r5 " << format("0x%08" PRIx32, cpu32.r[5]); 9557 outs() << " r6 " << format("0x%08" PRIx32, cpu32.r[6]); 9558 outs() << " r7 " << format("0x%08" PRIx32, cpu32.r[7]) << "\n"; 9559 outs() << "\t r8 " << format("0x%08" PRIx32, cpu32.r[8]); 9560 outs() << " r9 " << format("0x%08" PRIx32, cpu32.r[9]); 9561 outs() << " r10 " << format("0x%08" PRIx32, cpu32.r[10]); 9562 outs() << " r11 " << format("0x%08" PRIx32, cpu32.r[11]) << "\n"; 9563 outs() << "\t r12 " << format("0x%08" PRIx32, cpu32.r[12]); 9564 outs() << " sp " << format("0x%08" PRIx32, cpu32.sp); 9565 outs() << " lr " << format("0x%08" PRIx32, cpu32.lr); 9566 outs() << " pc " << format("0x%08" PRIx32, cpu32.pc) << "\n"; 9567 outs() << "\t cpsr " << format("0x%08" PRIx32, cpu32.cpsr) << "\n"; 9568 } 9569 9570 static void Print_arm_thread_state64_t(MachO::arm_thread_state64_t &cpu64) { 9571 outs() << "\t x0 " << format("0x%016" PRIx64, cpu64.x[0]); 9572 outs() << " x1 " << format("0x%016" PRIx64, cpu64.x[1]); 9573 outs() << " x2 " << format("0x%016" PRIx64, cpu64.x[2]) << "\n"; 9574 outs() << "\t x3 " << format("0x%016" PRIx64, cpu64.x[3]); 9575 outs() << " x4 " << format("0x%016" PRIx64, cpu64.x[4]); 9576 outs() << " x5 " << format("0x%016" PRIx64, cpu64.x[5]) << "\n"; 9577 outs() << "\t x6 " << format("0x%016" PRIx64, cpu64.x[6]); 9578 outs() << " x7 " << format("0x%016" PRIx64, cpu64.x[7]); 9579 outs() << " x8 " << format("0x%016" PRIx64, cpu64.x[8]) << "\n"; 9580 outs() << "\t x9 " << format("0x%016" PRIx64, cpu64.x[9]); 9581 outs() << " x10 " << format("0x%016" PRIx64, cpu64.x[10]); 9582 outs() << " x11 " << format("0x%016" PRIx64, cpu64.x[11]) << "\n"; 9583 outs() << "\t x12 " << format("0x%016" PRIx64, cpu64.x[12]); 9584 outs() << " x13 " << format("0x%016" PRIx64, cpu64.x[13]); 9585 outs() << " x14 " << format("0x%016" PRIx64, cpu64.x[14]) << "\n"; 9586 outs() << "\t x15 " << format("0x%016" PRIx64, cpu64.x[15]); 9587 outs() << " x16 " << format("0x%016" PRIx64, cpu64.x[16]); 9588 outs() << " x17 " << format("0x%016" PRIx64, cpu64.x[17]) << "\n"; 9589 outs() << "\t x18 " << format("0x%016" PRIx64, cpu64.x[18]); 9590 outs() << " x19 " << format("0x%016" PRIx64, cpu64.x[19]); 9591 outs() << " x20 " << format("0x%016" PRIx64, cpu64.x[20]) << "\n"; 9592 outs() << "\t x21 " << format("0x%016" PRIx64, cpu64.x[21]); 9593 outs() << " x22 " << format("0x%016" PRIx64, cpu64.x[22]); 9594 outs() << " x23 " << format("0x%016" PRIx64, cpu64.x[23]) << "\n"; 9595 outs() << "\t x24 " << format("0x%016" PRIx64, cpu64.x[24]); 9596 outs() << " x25 " << format("0x%016" PRIx64, cpu64.x[25]); 9597 outs() << " x26 " << format("0x%016" PRIx64, cpu64.x[26]) << "\n"; 9598 outs() << "\t x27 " << format("0x%016" PRIx64, cpu64.x[27]); 9599 outs() << " x28 " << format("0x%016" PRIx64, cpu64.x[28]); 9600 outs() << " fp " << format("0x%016" PRIx64, cpu64.fp) << "\n"; 9601 outs() << "\t lr " << format("0x%016" PRIx64, cpu64.lr); 9602 outs() << " sp " << format("0x%016" PRIx64, cpu64.sp); 9603 outs() << " pc " << format("0x%016" PRIx64, cpu64.pc) << "\n"; 9604 outs() << "\t cpsr " << format("0x%08" PRIx32, cpu64.cpsr) << "\n"; 9605 } 9606 9607 static void PrintThreadCommand(MachO::thread_command t, const char *Ptr, 9608 bool isLittleEndian, uint32_t cputype) { 9609 if (t.cmd == MachO::LC_THREAD) 9610 outs() << " cmd LC_THREAD\n"; 9611 else if (t.cmd == MachO::LC_UNIXTHREAD) 9612 outs() << " cmd LC_UNIXTHREAD\n"; 9613 else 9614 outs() << " cmd " << t.cmd << " (unknown)\n"; 9615 outs() << " cmdsize " << t.cmdsize; 9616 if (t.cmdsize < sizeof(struct MachO::thread_command) + 2 * sizeof(uint32_t)) 9617 outs() << " Incorrect size\n"; 9618 else 9619 outs() << "\n"; 9620 9621 const char *begin = Ptr + sizeof(struct MachO::thread_command); 9622 const char *end = Ptr + t.cmdsize; 9623 uint32_t flavor, count, left; 9624 if (cputype == MachO::CPU_TYPE_I386) { 9625 while (begin < end) { 9626 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) { 9627 memcpy((char *)&flavor, begin, sizeof(uint32_t)); 9628 begin += sizeof(uint32_t); 9629 } else { 9630 flavor = 0; 9631 begin = end; 9632 } 9633 if (isLittleEndian != sys::IsLittleEndianHost) 9634 sys::swapByteOrder(flavor); 9635 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) { 9636 memcpy((char *)&count, begin, sizeof(uint32_t)); 9637 begin += sizeof(uint32_t); 9638 } else { 9639 count = 0; 9640 begin = end; 9641 } 9642 if (isLittleEndian != sys::IsLittleEndianHost) 9643 sys::swapByteOrder(count); 9644 if (flavor == MachO::x86_THREAD_STATE32) { 9645 outs() << " flavor i386_THREAD_STATE\n"; 9646 if (count == MachO::x86_THREAD_STATE32_COUNT) 9647 outs() << " count i386_THREAD_STATE_COUNT\n"; 9648 else 9649 outs() << " count " << count 9650 << " (not x86_THREAD_STATE32_COUNT)\n"; 9651 MachO::x86_thread_state32_t cpu32; 9652 left = end - begin; 9653 if (left >= sizeof(MachO::x86_thread_state32_t)) { 9654 memcpy(&cpu32, begin, sizeof(MachO::x86_thread_state32_t)); 9655 begin += sizeof(MachO::x86_thread_state32_t); 9656 } else { 9657 memset(&cpu32, '\0', sizeof(MachO::x86_thread_state32_t)); 9658 memcpy(&cpu32, begin, left); 9659 begin += left; 9660 } 9661 if (isLittleEndian != sys::IsLittleEndianHost) 9662 swapStruct(cpu32); 9663 Print_x86_thread_state32_t(cpu32); 9664 } else if (flavor == MachO::x86_THREAD_STATE) { 9665 outs() << " flavor x86_THREAD_STATE\n"; 9666 if (count == MachO::x86_THREAD_STATE_COUNT) 9667 outs() << " count x86_THREAD_STATE_COUNT\n"; 9668 else 9669 outs() << " count " << count 9670 << " (not x86_THREAD_STATE_COUNT)\n"; 9671 struct MachO::x86_thread_state_t ts; 9672 left = end - begin; 9673 if (left >= sizeof(MachO::x86_thread_state_t)) { 9674 memcpy(&ts, begin, sizeof(MachO::x86_thread_state_t)); 9675 begin += sizeof(MachO::x86_thread_state_t); 9676 } else { 9677 memset(&ts, '\0', sizeof(MachO::x86_thread_state_t)); 9678 memcpy(&ts, begin, left); 9679 begin += left; 9680 } 9681 if (isLittleEndian != sys::IsLittleEndianHost) 9682 swapStruct(ts); 9683 if (ts.tsh.flavor == MachO::x86_THREAD_STATE32) { 9684 outs() << "\t tsh.flavor x86_THREAD_STATE32 "; 9685 if (ts.tsh.count == MachO::x86_THREAD_STATE32_COUNT) 9686 outs() << "tsh.count x86_THREAD_STATE32_COUNT\n"; 9687 else 9688 outs() << "tsh.count " << ts.tsh.count 9689 << " (not x86_THREAD_STATE32_COUNT\n"; 9690 Print_x86_thread_state32_t(ts.uts.ts32); 9691 } else { 9692 outs() << "\t tsh.flavor " << ts.tsh.flavor << " tsh.count " 9693 << ts.tsh.count << "\n"; 9694 } 9695 } else { 9696 outs() << " flavor " << flavor << " (unknown)\n"; 9697 outs() << " count " << count << "\n"; 9698 outs() << " state (unknown)\n"; 9699 begin += count * sizeof(uint32_t); 9700 } 9701 } 9702 } else if (cputype == MachO::CPU_TYPE_X86_64) { 9703 while (begin < end) { 9704 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) { 9705 memcpy((char *)&flavor, begin, sizeof(uint32_t)); 9706 begin += sizeof(uint32_t); 9707 } else { 9708 flavor = 0; 9709 begin = end; 9710 } 9711 if (isLittleEndian != sys::IsLittleEndianHost) 9712 sys::swapByteOrder(flavor); 9713 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) { 9714 memcpy((char *)&count, begin, sizeof(uint32_t)); 9715 begin += sizeof(uint32_t); 9716 } else { 9717 count = 0; 9718 begin = end; 9719 } 9720 if (isLittleEndian != sys::IsLittleEndianHost) 9721 sys::swapByteOrder(count); 9722 if (flavor == MachO::x86_THREAD_STATE64) { 9723 outs() << " flavor x86_THREAD_STATE64\n"; 9724 if (count == MachO::x86_THREAD_STATE64_COUNT) 9725 outs() << " count x86_THREAD_STATE64_COUNT\n"; 9726 else 9727 outs() << " count " << count 9728 << " (not x86_THREAD_STATE64_COUNT)\n"; 9729 MachO::x86_thread_state64_t cpu64; 9730 left = end - begin; 9731 if (left >= sizeof(MachO::x86_thread_state64_t)) { 9732 memcpy(&cpu64, begin, sizeof(MachO::x86_thread_state64_t)); 9733 begin += sizeof(MachO::x86_thread_state64_t); 9734 } else { 9735 memset(&cpu64, '\0', sizeof(MachO::x86_thread_state64_t)); 9736 memcpy(&cpu64, begin, left); 9737 begin += left; 9738 } 9739 if (isLittleEndian != sys::IsLittleEndianHost) 9740 swapStruct(cpu64); 9741 Print_x86_thread_state64_t(cpu64); 9742 } else if (flavor == MachO::x86_THREAD_STATE) { 9743 outs() << " flavor x86_THREAD_STATE\n"; 9744 if (count == MachO::x86_THREAD_STATE_COUNT) 9745 outs() << " count x86_THREAD_STATE_COUNT\n"; 9746 else 9747 outs() << " count " << count 9748 << " (not x86_THREAD_STATE_COUNT)\n"; 9749 struct MachO::x86_thread_state_t ts; 9750 left = end - begin; 9751 if (left >= sizeof(MachO::x86_thread_state_t)) { 9752 memcpy(&ts, begin, sizeof(MachO::x86_thread_state_t)); 9753 begin += sizeof(MachO::x86_thread_state_t); 9754 } else { 9755 memset(&ts, '\0', sizeof(MachO::x86_thread_state_t)); 9756 memcpy(&ts, begin, left); 9757 begin += left; 9758 } 9759 if (isLittleEndian != sys::IsLittleEndianHost) 9760 swapStruct(ts); 9761 if (ts.tsh.flavor == MachO::x86_THREAD_STATE64) { 9762 outs() << "\t tsh.flavor x86_THREAD_STATE64 "; 9763 if (ts.tsh.count == MachO::x86_THREAD_STATE64_COUNT) 9764 outs() << "tsh.count x86_THREAD_STATE64_COUNT\n"; 9765 else 9766 outs() << "tsh.count " << ts.tsh.count 9767 << " (not x86_THREAD_STATE64_COUNT\n"; 9768 Print_x86_thread_state64_t(ts.uts.ts64); 9769 } else { 9770 outs() << "\t tsh.flavor " << ts.tsh.flavor << " tsh.count " 9771 << ts.tsh.count << "\n"; 9772 } 9773 } else if (flavor == MachO::x86_FLOAT_STATE) { 9774 outs() << " flavor x86_FLOAT_STATE\n"; 9775 if (count == MachO::x86_FLOAT_STATE_COUNT) 9776 outs() << " count x86_FLOAT_STATE_COUNT\n"; 9777 else 9778 outs() << " count " << count << " (not x86_FLOAT_STATE_COUNT)\n"; 9779 struct MachO::x86_float_state_t fs; 9780 left = end - begin; 9781 if (left >= sizeof(MachO::x86_float_state_t)) { 9782 memcpy(&fs, begin, sizeof(MachO::x86_float_state_t)); 9783 begin += sizeof(MachO::x86_float_state_t); 9784 } else { 9785 memset(&fs, '\0', sizeof(MachO::x86_float_state_t)); 9786 memcpy(&fs, begin, left); 9787 begin += left; 9788 } 9789 if (isLittleEndian != sys::IsLittleEndianHost) 9790 swapStruct(fs); 9791 if (fs.fsh.flavor == MachO::x86_FLOAT_STATE64) { 9792 outs() << "\t fsh.flavor x86_FLOAT_STATE64 "; 9793 if (fs.fsh.count == MachO::x86_FLOAT_STATE64_COUNT) 9794 outs() << "fsh.count x86_FLOAT_STATE64_COUNT\n"; 9795 else 9796 outs() << "fsh.count " << fs.fsh.count 9797 << " (not x86_FLOAT_STATE64_COUNT\n"; 9798 Print_x86_float_state_t(fs.ufs.fs64); 9799 } else { 9800 outs() << "\t fsh.flavor " << fs.fsh.flavor << " fsh.count " 9801 << fs.fsh.count << "\n"; 9802 } 9803 } else if (flavor == MachO::x86_EXCEPTION_STATE) { 9804 outs() << " flavor x86_EXCEPTION_STATE\n"; 9805 if (count == MachO::x86_EXCEPTION_STATE_COUNT) 9806 outs() << " count x86_EXCEPTION_STATE_COUNT\n"; 9807 else 9808 outs() << " count " << count 9809 << " (not x86_EXCEPTION_STATE_COUNT)\n"; 9810 struct MachO::x86_exception_state_t es; 9811 left = end - begin; 9812 if (left >= sizeof(MachO::x86_exception_state_t)) { 9813 memcpy(&es, begin, sizeof(MachO::x86_exception_state_t)); 9814 begin += sizeof(MachO::x86_exception_state_t); 9815 } else { 9816 memset(&es, '\0', sizeof(MachO::x86_exception_state_t)); 9817 memcpy(&es, begin, left); 9818 begin += left; 9819 } 9820 if (isLittleEndian != sys::IsLittleEndianHost) 9821 swapStruct(es); 9822 if (es.esh.flavor == MachO::x86_EXCEPTION_STATE64) { 9823 outs() << "\t esh.flavor x86_EXCEPTION_STATE64\n"; 9824 if (es.esh.count == MachO::x86_EXCEPTION_STATE64_COUNT) 9825 outs() << "\t esh.count x86_EXCEPTION_STATE64_COUNT\n"; 9826 else 9827 outs() << "\t esh.count " << es.esh.count 9828 << " (not x86_EXCEPTION_STATE64_COUNT\n"; 9829 Print_x86_exception_state_t(es.ues.es64); 9830 } else { 9831 outs() << "\t esh.flavor " << es.esh.flavor << " esh.count " 9832 << es.esh.count << "\n"; 9833 } 9834 } else if (flavor == MachO::x86_EXCEPTION_STATE64) { 9835 outs() << " flavor x86_EXCEPTION_STATE64\n"; 9836 if (count == MachO::x86_EXCEPTION_STATE64_COUNT) 9837 outs() << " count x86_EXCEPTION_STATE64_COUNT\n"; 9838 else 9839 outs() << " count " << count 9840 << " (not x86_EXCEPTION_STATE64_COUNT)\n"; 9841 struct MachO::x86_exception_state64_t es64; 9842 left = end - begin; 9843 if (left >= sizeof(MachO::x86_exception_state64_t)) { 9844 memcpy(&es64, begin, sizeof(MachO::x86_exception_state64_t)); 9845 begin += sizeof(MachO::x86_exception_state64_t); 9846 } else { 9847 memset(&es64, '\0', sizeof(MachO::x86_exception_state64_t)); 9848 memcpy(&es64, begin, left); 9849 begin += left; 9850 } 9851 if (isLittleEndian != sys::IsLittleEndianHost) 9852 swapStruct(es64); 9853 Print_x86_exception_state_t(es64); 9854 } else { 9855 outs() << " flavor " << flavor << " (unknown)\n"; 9856 outs() << " count " << count << "\n"; 9857 outs() << " state (unknown)\n"; 9858 begin += count * sizeof(uint32_t); 9859 } 9860 } 9861 } else if (cputype == MachO::CPU_TYPE_ARM) { 9862 while (begin < end) { 9863 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) { 9864 memcpy((char *)&flavor, begin, sizeof(uint32_t)); 9865 begin += sizeof(uint32_t); 9866 } else { 9867 flavor = 0; 9868 begin = end; 9869 } 9870 if (isLittleEndian != sys::IsLittleEndianHost) 9871 sys::swapByteOrder(flavor); 9872 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) { 9873 memcpy((char *)&count, begin, sizeof(uint32_t)); 9874 begin += sizeof(uint32_t); 9875 } else { 9876 count = 0; 9877 begin = end; 9878 } 9879 if (isLittleEndian != sys::IsLittleEndianHost) 9880 sys::swapByteOrder(count); 9881 if (flavor == MachO::ARM_THREAD_STATE) { 9882 outs() << " flavor ARM_THREAD_STATE\n"; 9883 if (count == MachO::ARM_THREAD_STATE_COUNT) 9884 outs() << " count ARM_THREAD_STATE_COUNT\n"; 9885 else 9886 outs() << " count " << count 9887 << " (not ARM_THREAD_STATE_COUNT)\n"; 9888 MachO::arm_thread_state32_t cpu32; 9889 left = end - begin; 9890 if (left >= sizeof(MachO::arm_thread_state32_t)) { 9891 memcpy(&cpu32, begin, sizeof(MachO::arm_thread_state32_t)); 9892 begin += sizeof(MachO::arm_thread_state32_t); 9893 } else { 9894 memset(&cpu32, '\0', sizeof(MachO::arm_thread_state32_t)); 9895 memcpy(&cpu32, begin, left); 9896 begin += left; 9897 } 9898 if (isLittleEndian != sys::IsLittleEndianHost) 9899 swapStruct(cpu32); 9900 Print_arm_thread_state32_t(cpu32); 9901 } else { 9902 outs() << " flavor " << flavor << " (unknown)\n"; 9903 outs() << " count " << count << "\n"; 9904 outs() << " state (unknown)\n"; 9905 begin += count * sizeof(uint32_t); 9906 } 9907 } 9908 } else if (cputype == MachO::CPU_TYPE_ARM64 || 9909 cputype == MachO::CPU_TYPE_ARM64_32) { 9910 while (begin < end) { 9911 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) { 9912 memcpy((char *)&flavor, begin, sizeof(uint32_t)); 9913 begin += sizeof(uint32_t); 9914 } else { 9915 flavor = 0; 9916 begin = end; 9917 } 9918 if (isLittleEndian != sys::IsLittleEndianHost) 9919 sys::swapByteOrder(flavor); 9920 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) { 9921 memcpy((char *)&count, begin, sizeof(uint32_t)); 9922 begin += sizeof(uint32_t); 9923 } else { 9924 count = 0; 9925 begin = end; 9926 } 9927 if (isLittleEndian != sys::IsLittleEndianHost) 9928 sys::swapByteOrder(count); 9929 if (flavor == MachO::ARM_THREAD_STATE64) { 9930 outs() << " flavor ARM_THREAD_STATE64\n"; 9931 if (count == MachO::ARM_THREAD_STATE64_COUNT) 9932 outs() << " count ARM_THREAD_STATE64_COUNT\n"; 9933 else 9934 outs() << " count " << count 9935 << " (not ARM_THREAD_STATE64_COUNT)\n"; 9936 MachO::arm_thread_state64_t cpu64; 9937 left = end - begin; 9938 if (left >= sizeof(MachO::arm_thread_state64_t)) { 9939 memcpy(&cpu64, begin, sizeof(MachO::arm_thread_state64_t)); 9940 begin += sizeof(MachO::arm_thread_state64_t); 9941 } else { 9942 memset(&cpu64, '\0', sizeof(MachO::arm_thread_state64_t)); 9943 memcpy(&cpu64, begin, left); 9944 begin += left; 9945 } 9946 if (isLittleEndian != sys::IsLittleEndianHost) 9947 swapStruct(cpu64); 9948 Print_arm_thread_state64_t(cpu64); 9949 } else { 9950 outs() << " flavor " << flavor << " (unknown)\n"; 9951 outs() << " count " << count << "\n"; 9952 outs() << " state (unknown)\n"; 9953 begin += count * sizeof(uint32_t); 9954 } 9955 } 9956 } else { 9957 while (begin < end) { 9958 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) { 9959 memcpy((char *)&flavor, begin, sizeof(uint32_t)); 9960 begin += sizeof(uint32_t); 9961 } else { 9962 flavor = 0; 9963 begin = end; 9964 } 9965 if (isLittleEndian != sys::IsLittleEndianHost) 9966 sys::swapByteOrder(flavor); 9967 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) { 9968 memcpy((char *)&count, begin, sizeof(uint32_t)); 9969 begin += sizeof(uint32_t); 9970 } else { 9971 count = 0; 9972 begin = end; 9973 } 9974 if (isLittleEndian != sys::IsLittleEndianHost) 9975 sys::swapByteOrder(count); 9976 outs() << " flavor " << flavor << "\n"; 9977 outs() << " count " << count << "\n"; 9978 outs() << " state (Unknown cputype/cpusubtype)\n"; 9979 begin += count * sizeof(uint32_t); 9980 } 9981 } 9982 } 9983 9984 static void PrintDylibCommand(MachO::dylib_command dl, const char *Ptr) { 9985 if (dl.cmd == MachO::LC_ID_DYLIB) 9986 outs() << " cmd LC_ID_DYLIB\n"; 9987 else if (dl.cmd == MachO::LC_LOAD_DYLIB) 9988 outs() << " cmd LC_LOAD_DYLIB\n"; 9989 else if (dl.cmd == MachO::LC_LOAD_WEAK_DYLIB) 9990 outs() << " cmd LC_LOAD_WEAK_DYLIB\n"; 9991 else if (dl.cmd == MachO::LC_REEXPORT_DYLIB) 9992 outs() << " cmd LC_REEXPORT_DYLIB\n"; 9993 else if (dl.cmd == MachO::LC_LAZY_LOAD_DYLIB) 9994 outs() << " cmd LC_LAZY_LOAD_DYLIB\n"; 9995 else if (dl.cmd == MachO::LC_LOAD_UPWARD_DYLIB) 9996 outs() << " cmd LC_LOAD_UPWARD_DYLIB\n"; 9997 else 9998 outs() << " cmd " << dl.cmd << " (unknown)\n"; 9999 outs() << " cmdsize " << dl.cmdsize; 10000 if (dl.cmdsize < sizeof(struct MachO::dylib_command)) 10001 outs() << " Incorrect size\n"; 10002 else 10003 outs() << "\n"; 10004 if (dl.dylib.name < dl.cmdsize) { 10005 const char *P = (const char *)(Ptr) + dl.dylib.name; 10006 outs() << " name " << P << " (offset " << dl.dylib.name << ")\n"; 10007 } else { 10008 outs() << " name ?(bad offset " << dl.dylib.name << ")\n"; 10009 } 10010 outs() << " time stamp " << dl.dylib.timestamp << " "; 10011 time_t t = dl.dylib.timestamp; 10012 outs() << ctime(&t); 10013 outs() << " current version "; 10014 if (dl.dylib.current_version == 0xffffffff) 10015 outs() << "n/a\n"; 10016 else 10017 outs() << ((dl.dylib.current_version >> 16) & 0xffff) << "." 10018 << ((dl.dylib.current_version >> 8) & 0xff) << "." 10019 << (dl.dylib.current_version & 0xff) << "\n"; 10020 outs() << "compatibility version "; 10021 if (dl.dylib.compatibility_version == 0xffffffff) 10022 outs() << "n/a\n"; 10023 else 10024 outs() << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "." 10025 << ((dl.dylib.compatibility_version >> 8) & 0xff) << "." 10026 << (dl.dylib.compatibility_version & 0xff) << "\n"; 10027 } 10028 10029 static void PrintLinkEditDataCommand(MachO::linkedit_data_command ld, 10030 uint32_t object_size) { 10031 if (ld.cmd == MachO::LC_CODE_SIGNATURE) 10032 outs() << " cmd LC_CODE_SIGNATURE\n"; 10033 else if (ld.cmd == MachO::LC_SEGMENT_SPLIT_INFO) 10034 outs() << " cmd LC_SEGMENT_SPLIT_INFO\n"; 10035 else if (ld.cmd == MachO::LC_FUNCTION_STARTS) 10036 outs() << " cmd LC_FUNCTION_STARTS\n"; 10037 else if (ld.cmd == MachO::LC_DATA_IN_CODE) 10038 outs() << " cmd LC_DATA_IN_CODE\n"; 10039 else if (ld.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS) 10040 outs() << " cmd LC_DYLIB_CODE_SIGN_DRS\n"; 10041 else if (ld.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT) 10042 outs() << " cmd LC_LINKER_OPTIMIZATION_HINT\n"; 10043 else 10044 outs() << " cmd " << ld.cmd << " (?)\n"; 10045 outs() << " cmdsize " << ld.cmdsize; 10046 if (ld.cmdsize != sizeof(struct MachO::linkedit_data_command)) 10047 outs() << " Incorrect size\n"; 10048 else 10049 outs() << "\n"; 10050 outs() << " dataoff " << ld.dataoff; 10051 if (ld.dataoff > object_size) 10052 outs() << " (past end of file)\n"; 10053 else 10054 outs() << "\n"; 10055 outs() << " datasize " << ld.datasize; 10056 uint64_t big_size = ld.dataoff; 10057 big_size += ld.datasize; 10058 if (big_size > object_size) 10059 outs() << " (past end of file)\n"; 10060 else 10061 outs() << "\n"; 10062 } 10063 10064 static void PrintLoadCommands(const MachOObjectFile *Obj, uint32_t filetype, 10065 uint32_t cputype, bool verbose) { 10066 StringRef Buf = Obj->getData(); 10067 unsigned Index = 0; 10068 for (const auto &Command : Obj->load_commands()) { 10069 outs() << "Load command " << Index++ << "\n"; 10070 if (Command.C.cmd == MachO::LC_SEGMENT) { 10071 MachO::segment_command SLC = Obj->getSegmentLoadCommand(Command); 10072 const char *sg_segname = SLC.segname; 10073 PrintSegmentCommand(SLC.cmd, SLC.cmdsize, SLC.segname, SLC.vmaddr, 10074 SLC.vmsize, SLC.fileoff, SLC.filesize, SLC.maxprot, 10075 SLC.initprot, SLC.nsects, SLC.flags, Buf.size(), 10076 verbose); 10077 for (unsigned j = 0; j < SLC.nsects; j++) { 10078 MachO::section S = Obj->getSection(Command, j); 10079 PrintSection(S.sectname, S.segname, S.addr, S.size, S.offset, S.align, 10080 S.reloff, S.nreloc, S.flags, S.reserved1, S.reserved2, 10081 SLC.cmd, sg_segname, filetype, Buf.size(), verbose); 10082 } 10083 } else if (Command.C.cmd == MachO::LC_SEGMENT_64) { 10084 MachO::segment_command_64 SLC_64 = Obj->getSegment64LoadCommand(Command); 10085 const char *sg_segname = SLC_64.segname; 10086 PrintSegmentCommand(SLC_64.cmd, SLC_64.cmdsize, SLC_64.segname, 10087 SLC_64.vmaddr, SLC_64.vmsize, SLC_64.fileoff, 10088 SLC_64.filesize, SLC_64.maxprot, SLC_64.initprot, 10089 SLC_64.nsects, SLC_64.flags, Buf.size(), verbose); 10090 for (unsigned j = 0; j < SLC_64.nsects; j++) { 10091 MachO::section_64 S_64 = Obj->getSection64(Command, j); 10092 PrintSection(S_64.sectname, S_64.segname, S_64.addr, S_64.size, 10093 S_64.offset, S_64.align, S_64.reloff, S_64.nreloc, 10094 S_64.flags, S_64.reserved1, S_64.reserved2, SLC_64.cmd, 10095 sg_segname, filetype, Buf.size(), verbose); 10096 } 10097 } else if (Command.C.cmd == MachO::LC_SYMTAB) { 10098 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand(); 10099 PrintSymtabLoadCommand(Symtab, Obj->is64Bit(), Buf.size()); 10100 } else if (Command.C.cmd == MachO::LC_DYSYMTAB) { 10101 MachO::dysymtab_command Dysymtab = Obj->getDysymtabLoadCommand(); 10102 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand(); 10103 PrintDysymtabLoadCommand(Dysymtab, Symtab.nsyms, Buf.size(), 10104 Obj->is64Bit()); 10105 } else if (Command.C.cmd == MachO::LC_DYLD_INFO || 10106 Command.C.cmd == MachO::LC_DYLD_INFO_ONLY) { 10107 MachO::dyld_info_command DyldInfo = Obj->getDyldInfoLoadCommand(Command); 10108 PrintDyldInfoLoadCommand(DyldInfo, Buf.size()); 10109 } else if (Command.C.cmd == MachO::LC_LOAD_DYLINKER || 10110 Command.C.cmd == MachO::LC_ID_DYLINKER || 10111 Command.C.cmd == MachO::LC_DYLD_ENVIRONMENT) { 10112 MachO::dylinker_command Dyld = Obj->getDylinkerCommand(Command); 10113 PrintDyldLoadCommand(Dyld, Command.Ptr); 10114 } else if (Command.C.cmd == MachO::LC_UUID) { 10115 MachO::uuid_command Uuid = Obj->getUuidCommand(Command); 10116 PrintUuidLoadCommand(Uuid); 10117 } else if (Command.C.cmd == MachO::LC_RPATH) { 10118 MachO::rpath_command Rpath = Obj->getRpathCommand(Command); 10119 PrintRpathLoadCommand(Rpath, Command.Ptr); 10120 } else if (Command.C.cmd == MachO::LC_VERSION_MIN_MACOSX || 10121 Command.C.cmd == MachO::LC_VERSION_MIN_IPHONEOS || 10122 Command.C.cmd == MachO::LC_VERSION_MIN_TVOS || 10123 Command.C.cmd == MachO::LC_VERSION_MIN_WATCHOS) { 10124 MachO::version_min_command Vd = Obj->getVersionMinLoadCommand(Command); 10125 PrintVersionMinLoadCommand(Vd); 10126 } else if (Command.C.cmd == MachO::LC_NOTE) { 10127 MachO::note_command Nt = Obj->getNoteLoadCommand(Command); 10128 PrintNoteLoadCommand(Nt); 10129 } else if (Command.C.cmd == MachO::LC_BUILD_VERSION) { 10130 MachO::build_version_command Bv = 10131 Obj->getBuildVersionLoadCommand(Command); 10132 PrintBuildVersionLoadCommand(Obj, Bv); 10133 } else if (Command.C.cmd == MachO::LC_SOURCE_VERSION) { 10134 MachO::source_version_command Sd = Obj->getSourceVersionCommand(Command); 10135 PrintSourceVersionCommand(Sd); 10136 } else if (Command.C.cmd == MachO::LC_MAIN) { 10137 MachO::entry_point_command Ep = Obj->getEntryPointCommand(Command); 10138 PrintEntryPointCommand(Ep); 10139 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO) { 10140 MachO::encryption_info_command Ei = 10141 Obj->getEncryptionInfoCommand(Command); 10142 PrintEncryptionInfoCommand(Ei, Buf.size()); 10143 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO_64) { 10144 MachO::encryption_info_command_64 Ei = 10145 Obj->getEncryptionInfoCommand64(Command); 10146 PrintEncryptionInfoCommand64(Ei, Buf.size()); 10147 } else if (Command.C.cmd == MachO::LC_LINKER_OPTION) { 10148 MachO::linker_option_command Lo = 10149 Obj->getLinkerOptionLoadCommand(Command); 10150 PrintLinkerOptionCommand(Lo, Command.Ptr); 10151 } else if (Command.C.cmd == MachO::LC_SUB_FRAMEWORK) { 10152 MachO::sub_framework_command Sf = Obj->getSubFrameworkCommand(Command); 10153 PrintSubFrameworkCommand(Sf, Command.Ptr); 10154 } else if (Command.C.cmd == MachO::LC_SUB_UMBRELLA) { 10155 MachO::sub_umbrella_command Sf = Obj->getSubUmbrellaCommand(Command); 10156 PrintSubUmbrellaCommand(Sf, Command.Ptr); 10157 } else if (Command.C.cmd == MachO::LC_SUB_LIBRARY) { 10158 MachO::sub_library_command Sl = Obj->getSubLibraryCommand(Command); 10159 PrintSubLibraryCommand(Sl, Command.Ptr); 10160 } else if (Command.C.cmd == MachO::LC_SUB_CLIENT) { 10161 MachO::sub_client_command Sc = Obj->getSubClientCommand(Command); 10162 PrintSubClientCommand(Sc, Command.Ptr); 10163 } else if (Command.C.cmd == MachO::LC_ROUTINES) { 10164 MachO::routines_command Rc = Obj->getRoutinesCommand(Command); 10165 PrintRoutinesCommand(Rc); 10166 } else if (Command.C.cmd == MachO::LC_ROUTINES_64) { 10167 MachO::routines_command_64 Rc = Obj->getRoutinesCommand64(Command); 10168 PrintRoutinesCommand64(Rc); 10169 } else if (Command.C.cmd == MachO::LC_THREAD || 10170 Command.C.cmd == MachO::LC_UNIXTHREAD) { 10171 MachO::thread_command Tc = Obj->getThreadCommand(Command); 10172 PrintThreadCommand(Tc, Command.Ptr, Obj->isLittleEndian(), cputype); 10173 } else if (Command.C.cmd == MachO::LC_LOAD_DYLIB || 10174 Command.C.cmd == MachO::LC_ID_DYLIB || 10175 Command.C.cmd == MachO::LC_LOAD_WEAK_DYLIB || 10176 Command.C.cmd == MachO::LC_REEXPORT_DYLIB || 10177 Command.C.cmd == MachO::LC_LAZY_LOAD_DYLIB || 10178 Command.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB) { 10179 MachO::dylib_command Dl = Obj->getDylibIDLoadCommand(Command); 10180 PrintDylibCommand(Dl, Command.Ptr); 10181 } else if (Command.C.cmd == MachO::LC_CODE_SIGNATURE || 10182 Command.C.cmd == MachO::LC_SEGMENT_SPLIT_INFO || 10183 Command.C.cmd == MachO::LC_FUNCTION_STARTS || 10184 Command.C.cmd == MachO::LC_DATA_IN_CODE || 10185 Command.C.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS || 10186 Command.C.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT) { 10187 MachO::linkedit_data_command Ld = 10188 Obj->getLinkeditDataLoadCommand(Command); 10189 PrintLinkEditDataCommand(Ld, Buf.size()); 10190 } else { 10191 outs() << " cmd ?(" << format("0x%08" PRIx32, Command.C.cmd) 10192 << ")\n"; 10193 outs() << " cmdsize " << Command.C.cmdsize << "\n"; 10194 // TODO: get and print the raw bytes of the load command. 10195 } 10196 // TODO: print all the other kinds of load commands. 10197 } 10198 } 10199 10200 static void PrintMachHeader(const MachOObjectFile *Obj, bool verbose) { 10201 if (Obj->is64Bit()) { 10202 MachO::mach_header_64 H_64; 10203 H_64 = Obj->getHeader64(); 10204 PrintMachHeader(H_64.magic, H_64.cputype, H_64.cpusubtype, H_64.filetype, 10205 H_64.ncmds, H_64.sizeofcmds, H_64.flags, verbose); 10206 } else { 10207 MachO::mach_header H; 10208 H = Obj->getHeader(); 10209 PrintMachHeader(H.magic, H.cputype, H.cpusubtype, H.filetype, H.ncmds, 10210 H.sizeofcmds, H.flags, verbose); 10211 } 10212 } 10213 10214 void objdump::printMachOFileHeader(const object::ObjectFile *Obj) { 10215 const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj); 10216 PrintMachHeader(file, !NonVerbose); 10217 } 10218 10219 void objdump::printMachOLoadCommands(const object::ObjectFile *Obj) { 10220 const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj); 10221 uint32_t filetype = 0; 10222 uint32_t cputype = 0; 10223 if (file->is64Bit()) { 10224 MachO::mach_header_64 H_64; 10225 H_64 = file->getHeader64(); 10226 filetype = H_64.filetype; 10227 cputype = H_64.cputype; 10228 } else { 10229 MachO::mach_header H; 10230 H = file->getHeader(); 10231 filetype = H.filetype; 10232 cputype = H.cputype; 10233 } 10234 PrintLoadCommands(file, filetype, cputype, !NonVerbose); 10235 } 10236 10237 //===----------------------------------------------------------------------===// 10238 // export trie dumping 10239 //===----------------------------------------------------------------------===// 10240 10241 static void printMachOExportsTrie(const object::MachOObjectFile *Obj) { 10242 uint64_t BaseSegmentAddress = 0; 10243 for (const auto &Command : Obj->load_commands()) { 10244 if (Command.C.cmd == MachO::LC_SEGMENT) { 10245 MachO::segment_command Seg = Obj->getSegmentLoadCommand(Command); 10246 if (Seg.fileoff == 0 && Seg.filesize != 0) { 10247 BaseSegmentAddress = Seg.vmaddr; 10248 break; 10249 } 10250 } else if (Command.C.cmd == MachO::LC_SEGMENT_64) { 10251 MachO::segment_command_64 Seg = Obj->getSegment64LoadCommand(Command); 10252 if (Seg.fileoff == 0 && Seg.filesize != 0) { 10253 BaseSegmentAddress = Seg.vmaddr; 10254 break; 10255 } 10256 } 10257 } 10258 Error Err = Error::success(); 10259 for (const object::ExportEntry &Entry : Obj->exports(Err)) { 10260 uint64_t Flags = Entry.flags(); 10261 bool ReExport = (Flags & MachO::EXPORT_SYMBOL_FLAGS_REEXPORT); 10262 bool WeakDef = (Flags & MachO::EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION); 10263 bool ThreadLocal = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) == 10264 MachO::EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL); 10265 bool Abs = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) == 10266 MachO::EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE); 10267 bool Resolver = (Flags & MachO::EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER); 10268 if (ReExport) 10269 outs() << "[re-export] "; 10270 else 10271 outs() << format("0x%08llX ", 10272 Entry.address() + BaseSegmentAddress); 10273 outs() << Entry.name(); 10274 if (WeakDef || ThreadLocal || Resolver || Abs) { 10275 bool NeedsComma = false; 10276 outs() << " ["; 10277 if (WeakDef) { 10278 outs() << "weak_def"; 10279 NeedsComma = true; 10280 } 10281 if (ThreadLocal) { 10282 if (NeedsComma) 10283 outs() << ", "; 10284 outs() << "per-thread"; 10285 NeedsComma = true; 10286 } 10287 if (Abs) { 10288 if (NeedsComma) 10289 outs() << ", "; 10290 outs() << "absolute"; 10291 NeedsComma = true; 10292 } 10293 if (Resolver) { 10294 if (NeedsComma) 10295 outs() << ", "; 10296 outs() << format("resolver=0x%08llX", Entry.other()); 10297 NeedsComma = true; 10298 } 10299 outs() << "]"; 10300 } 10301 if (ReExport) { 10302 StringRef DylibName = "unknown"; 10303 int Ordinal = Entry.other() - 1; 10304 Obj->getLibraryShortNameByIndex(Ordinal, DylibName); 10305 if (Entry.otherName().empty()) 10306 outs() << " (from " << DylibName << ")"; 10307 else 10308 outs() << " (" << Entry.otherName() << " from " << DylibName << ")"; 10309 } 10310 outs() << "\n"; 10311 } 10312 if (Err) 10313 reportError(std::move(Err), Obj->getFileName()); 10314 } 10315 10316 //===----------------------------------------------------------------------===// 10317 // rebase table dumping 10318 //===----------------------------------------------------------------------===// 10319 10320 static void printMachORebaseTable(object::MachOObjectFile *Obj) { 10321 outs() << "segment section address type\n"; 10322 Error Err = Error::success(); 10323 for (const object::MachORebaseEntry &Entry : Obj->rebaseTable(Err)) { 10324 StringRef SegmentName = Entry.segmentName(); 10325 StringRef SectionName = Entry.sectionName(); 10326 uint64_t Address = Entry.address(); 10327 10328 // Table lines look like: __DATA __nl_symbol_ptr 0x0000F00C pointer 10329 outs() << format("%-8s %-18s 0x%08" PRIX64 " %s\n", 10330 SegmentName.str().c_str(), SectionName.str().c_str(), 10331 Address, Entry.typeName().str().c_str()); 10332 } 10333 if (Err) 10334 reportError(std::move(Err), Obj->getFileName()); 10335 } 10336 10337 static StringRef ordinalName(const object::MachOObjectFile *Obj, int Ordinal) { 10338 StringRef DylibName; 10339 switch (Ordinal) { 10340 case MachO::BIND_SPECIAL_DYLIB_SELF: 10341 return "this-image"; 10342 case MachO::BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE: 10343 return "main-executable"; 10344 case MachO::BIND_SPECIAL_DYLIB_FLAT_LOOKUP: 10345 return "flat-namespace"; 10346 default: 10347 if (Ordinal > 0) { 10348 std::error_code EC = 10349 Obj->getLibraryShortNameByIndex(Ordinal - 1, DylibName); 10350 if (EC) 10351 return "<<bad library ordinal>>"; 10352 return DylibName; 10353 } 10354 } 10355 return "<<unknown special ordinal>>"; 10356 } 10357 10358 //===----------------------------------------------------------------------===// 10359 // bind table dumping 10360 //===----------------------------------------------------------------------===// 10361 10362 static void printMachOBindTable(object::MachOObjectFile *Obj) { 10363 // Build table of sections so names can used in final output. 10364 outs() << "segment section address type " 10365 "addend dylib symbol\n"; 10366 Error Err = Error::success(); 10367 for (const object::MachOBindEntry &Entry : Obj->bindTable(Err)) { 10368 StringRef SegmentName = Entry.segmentName(); 10369 StringRef SectionName = Entry.sectionName(); 10370 uint64_t Address = Entry.address(); 10371 10372 // Table lines look like: 10373 // __DATA __got 0x00012010 pointer 0 libSystem ___stack_chk_guard 10374 StringRef Attr; 10375 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_WEAK_IMPORT) 10376 Attr = " (weak_import)"; 10377 outs() << left_justify(SegmentName, 8) << " " 10378 << left_justify(SectionName, 18) << " " 10379 << format_hex(Address, 10, true) << " " 10380 << left_justify(Entry.typeName(), 8) << " " 10381 << format_decimal(Entry.addend(), 8) << " " 10382 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " " 10383 << Entry.symbolName() << Attr << "\n"; 10384 } 10385 if (Err) 10386 reportError(std::move(Err), Obj->getFileName()); 10387 } 10388 10389 //===----------------------------------------------------------------------===// 10390 // lazy bind table dumping 10391 //===----------------------------------------------------------------------===// 10392 10393 static void printMachOLazyBindTable(object::MachOObjectFile *Obj) { 10394 outs() << "segment section address " 10395 "dylib symbol\n"; 10396 Error Err = Error::success(); 10397 for (const object::MachOBindEntry &Entry : Obj->lazyBindTable(Err)) { 10398 StringRef SegmentName = Entry.segmentName(); 10399 StringRef SectionName = Entry.sectionName(); 10400 uint64_t Address = Entry.address(); 10401 10402 // Table lines look like: 10403 // __DATA __got 0x00012010 libSystem ___stack_chk_guard 10404 outs() << left_justify(SegmentName, 8) << " " 10405 << left_justify(SectionName, 18) << " " 10406 << format_hex(Address, 10, true) << " " 10407 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " " 10408 << Entry.symbolName() << "\n"; 10409 } 10410 if (Err) 10411 reportError(std::move(Err), Obj->getFileName()); 10412 } 10413 10414 //===----------------------------------------------------------------------===// 10415 // weak bind table dumping 10416 //===----------------------------------------------------------------------===// 10417 10418 static void printMachOWeakBindTable(object::MachOObjectFile *Obj) { 10419 outs() << "segment section address " 10420 "type addend symbol\n"; 10421 Error Err = Error::success(); 10422 for (const object::MachOBindEntry &Entry : Obj->weakBindTable(Err)) { 10423 // Strong symbols don't have a location to update. 10424 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION) { 10425 outs() << " strong " 10426 << Entry.symbolName() << "\n"; 10427 continue; 10428 } 10429 StringRef SegmentName = Entry.segmentName(); 10430 StringRef SectionName = Entry.sectionName(); 10431 uint64_t Address = Entry.address(); 10432 10433 // Table lines look like: 10434 // __DATA __data 0x00001000 pointer 0 _foo 10435 outs() << left_justify(SegmentName, 8) << " " 10436 << left_justify(SectionName, 18) << " " 10437 << format_hex(Address, 10, true) << " " 10438 << left_justify(Entry.typeName(), 8) << " " 10439 << format_decimal(Entry.addend(), 8) << " " << Entry.symbolName() 10440 << "\n"; 10441 } 10442 if (Err) 10443 reportError(std::move(Err), Obj->getFileName()); 10444 } 10445 10446 // get_dyld_bind_info_symbolname() is used for disassembly and passed an 10447 // address, ReferenceValue, in the Mach-O file and looks in the dyld bind 10448 // information for that address. If the address is found its binding symbol 10449 // name is returned. If not nullptr is returned. 10450 static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue, 10451 struct DisassembleInfo *info) { 10452 if (info->bindtable == nullptr) { 10453 info->bindtable = std::make_unique<SymbolAddressMap>(); 10454 Error Err = Error::success(); 10455 for (const object::MachOBindEntry &Entry : info->O->bindTable(Err)) { 10456 uint64_t Address = Entry.address(); 10457 StringRef name = Entry.symbolName(); 10458 if (!name.empty()) 10459 (*info->bindtable)[Address] = name; 10460 } 10461 if (Err) 10462 reportError(std::move(Err), info->O->getFileName()); 10463 } 10464 auto name = info->bindtable->lookup(ReferenceValue); 10465 return !name.empty() ? name.data() : nullptr; 10466 } 10467 10468 void objdump::printLazyBindTable(ObjectFile *o) { 10469 outs() << "Lazy bind table:\n"; 10470 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o)) 10471 printMachOLazyBindTable(MachO); 10472 else 10473 WithColor::error() 10474 << "This operation is only currently supported " 10475 "for Mach-O executable files.\n"; 10476 } 10477 10478 void objdump::printWeakBindTable(ObjectFile *o) { 10479 outs() << "Weak bind table:\n"; 10480 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o)) 10481 printMachOWeakBindTable(MachO); 10482 else 10483 WithColor::error() 10484 << "This operation is only currently supported " 10485 "for Mach-O executable files.\n"; 10486 } 10487 10488 void objdump::printExportsTrie(const ObjectFile *o) { 10489 outs() << "Exports trie:\n"; 10490 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o)) 10491 printMachOExportsTrie(MachO); 10492 else 10493 WithColor::error() 10494 << "This operation is only currently supported " 10495 "for Mach-O executable files.\n"; 10496 } 10497 10498 void objdump::printRebaseTable(ObjectFile *o) { 10499 outs() << "Rebase table:\n"; 10500 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o)) 10501 printMachORebaseTable(MachO); 10502 else 10503 WithColor::error() 10504 << "This operation is only currently supported " 10505 "for Mach-O executable files.\n"; 10506 } 10507 10508 void objdump::printBindTable(ObjectFile *o) { 10509 outs() << "Bind table:\n"; 10510 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o)) 10511 printMachOBindTable(MachO); 10512 else 10513 WithColor::error() 10514 << "This operation is only currently supported " 10515 "for Mach-O executable files.\n"; 10516 } 10517