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 "llvm-objdump.h" 14 #include "llvm-c/Disassembler.h" 15 #include "llvm/ADT/STLExtras.h" 16 #include "llvm/ADT/StringExtras.h" 17 #include "llvm/ADT/StringSet.h" 18 #include "llvm/ADT/Triple.h" 19 #include "llvm/BinaryFormat/MachO.h" 20 #include "llvm/Config/config.h" 21 #include "llvm/DebugInfo/DIContext.h" 22 #include "llvm/DebugInfo/DWARF/DWARFContext.h" 23 #include "llvm/Demangle/Demangle.h" 24 #include "llvm/MC/MCAsmInfo.h" 25 #include "llvm/MC/MCContext.h" 26 #include "llvm/MC/MCDisassembler/MCDisassembler.h" 27 #include "llvm/MC/MCInst.h" 28 #include "llvm/MC/MCInstPrinter.h" 29 #include "llvm/MC/MCInstrDesc.h" 30 #include "llvm/MC/MCInstrInfo.h" 31 #include "llvm/MC/MCRegisterInfo.h" 32 #include "llvm/MC/MCSubtargetInfo.h" 33 #include "llvm/MC/MCTargetOptions.h" 34 #include "llvm/Object/MachO.h" 35 #include "llvm/Object/MachOUniversal.h" 36 #include "llvm/Support/Casting.h" 37 #include "llvm/Support/CommandLine.h" 38 #include "llvm/Support/Debug.h" 39 #include "llvm/Support/Endian.h" 40 #include "llvm/Support/Format.h" 41 #include "llvm/Support/FormattedStream.h" 42 #include "llvm/Support/GraphWriter.h" 43 #include "llvm/Support/LEB128.h" 44 #include "llvm/Support/MemoryBuffer.h" 45 #include "llvm/Support/TargetRegistry.h" 46 #include "llvm/Support/TargetSelect.h" 47 #include "llvm/Support/ToolOutputFile.h" 48 #include "llvm/Support/WithColor.h" 49 #include "llvm/Support/raw_ostream.h" 50 #include <algorithm> 51 #include <cstring> 52 #include <system_error> 53 54 #ifdef HAVE_LIBXAR 55 extern "C" { 56 #include <xar/xar.h> 57 } 58 #endif 59 60 using namespace llvm::object; 61 62 namespace llvm { 63 64 cl::OptionCategory MachOCat("llvm-objdump MachO Specific Options"); 65 66 extern cl::opt<bool> ArchiveHeaders; 67 extern cl::opt<bool> Disassemble; 68 extern cl::opt<bool> DisassembleAll; 69 extern cl::opt<DIDumpType> DwarfDumpType; 70 extern cl::list<std::string> FilterSections; 71 extern cl::list<std::string> MAttrs; 72 extern cl::opt<std::string> MCPU; 73 extern cl::opt<bool> NoShowRawInsn; 74 extern cl::opt<bool> NoLeadingAddr; 75 extern cl::opt<bool> PrintImmHex; 76 extern cl::opt<bool> PrivateHeaders; 77 extern cl::opt<bool> Relocations; 78 extern cl::opt<bool> SectionHeaders; 79 extern cl::opt<bool> SectionContents; 80 extern cl::opt<bool> SymbolTable; 81 extern cl::opt<std::string> TripleName; 82 extern cl::opt<bool> UnwindInfo; 83 84 cl::opt<bool> 85 FirstPrivateHeader("private-header", 86 cl::desc("Display only the first format specific file " 87 "header"), 88 cl::cat(MachOCat)); 89 90 cl::opt<bool> ExportsTrie("exports-trie", 91 cl::desc("Display mach-o exported symbols"), 92 cl::cat(MachOCat)); 93 94 cl::opt<bool> Rebase("rebase", cl::desc("Display mach-o rebasing info"), 95 cl::cat(MachOCat)); 96 97 cl::opt<bool> Bind("bind", cl::desc("Display mach-o binding info"), 98 cl::cat(MachOCat)); 99 100 cl::opt<bool> LazyBind("lazy-bind", 101 cl::desc("Display mach-o lazy binding info"), 102 cl::cat(MachOCat)); 103 104 cl::opt<bool> WeakBind("weak-bind", 105 cl::desc("Display mach-o weak binding info"), 106 cl::cat(MachOCat)); 107 108 static cl::opt<bool> 109 UseDbg("g", cl::Grouping, 110 cl::desc("Print line information from debug info if available"), 111 cl::cat(MachOCat)); 112 113 static cl::opt<std::string> DSYMFile("dsym", 114 cl::desc("Use .dSYM file for debug info"), 115 cl::cat(MachOCat)); 116 117 static cl::opt<bool> FullLeadingAddr("full-leading-addr", 118 cl::desc("Print full leading address"), 119 cl::cat(MachOCat)); 120 121 static cl::opt<bool> NoLeadingHeaders("no-leading-headers", 122 cl::desc("Print no leading headers"), 123 cl::cat(MachOCat)); 124 125 cl::opt<bool> UniversalHeaders("universal-headers", 126 cl::desc("Print Mach-O universal headers " 127 "(requires -macho)"), 128 cl::cat(MachOCat)); 129 130 cl::opt<bool> 131 ArchiveMemberOffsets("archive-member-offsets", 132 cl::desc("Print the offset to each archive member for " 133 "Mach-O archives (requires -macho and " 134 "-archive-headers)"), 135 cl::cat(MachOCat)); 136 137 cl::opt<bool> IndirectSymbols("indirect-symbols", 138 cl::desc("Print indirect symbol table for Mach-O " 139 "objects (requires -macho)"), 140 cl::cat(MachOCat)); 141 142 cl::opt<bool> 143 DataInCode("data-in-code", 144 cl::desc("Print the data in code table for Mach-O objects " 145 "(requires -macho)"), 146 cl::cat(MachOCat)); 147 148 cl::opt<bool> LinkOptHints("link-opt-hints", 149 cl::desc("Print the linker optimization hints for " 150 "Mach-O objects (requires -macho)"), 151 cl::cat(MachOCat)); 152 153 cl::opt<bool> InfoPlist("info-plist", 154 cl::desc("Print the info plist section as strings for " 155 "Mach-O objects (requires -macho)"), 156 cl::cat(MachOCat)); 157 158 cl::opt<bool> DylibsUsed("dylibs-used", 159 cl::desc("Print the shared libraries used for linked " 160 "Mach-O files (requires -macho)"), 161 cl::cat(MachOCat)); 162 163 cl::opt<bool> 164 DylibId("dylib-id", 165 cl::desc("Print the shared library's id for the dylib Mach-O " 166 "file (requires -macho)"), 167 cl::cat(MachOCat)); 168 169 cl::opt<bool> 170 NonVerbose("non-verbose", 171 cl::desc("Print the info for Mach-O objects in " 172 "non-verbose or numeric form (requires -macho)"), 173 cl::cat(MachOCat)); 174 175 cl::opt<bool> 176 ObjcMetaData("objc-meta-data", 177 cl::desc("Print the Objective-C runtime meta data for " 178 "Mach-O files (requires -macho)"), 179 cl::cat(MachOCat)); 180 181 cl::opt<std::string> DisSymName( 182 "dis-symname", 183 cl::desc("disassemble just this symbol's instructions (requires -macho)"), 184 cl::cat(MachOCat)); 185 186 static cl::opt<bool> NoSymbolicOperands( 187 "no-symbolic-operands", 188 cl::desc("do not symbolic operands when disassembling (requires -macho)"), 189 cl::cat(MachOCat)); 190 191 static cl::list<std::string> 192 ArchFlags("arch", cl::desc("architecture(s) from a Mach-O file to dump"), 193 cl::ZeroOrMore, cl::cat(MachOCat)); 194 195 extern StringSet<> FoundSectionSet; 196 197 bool ArchAll = false; 198 199 static std::string ThumbTripleName; 200 201 static const Target *GetTarget(const MachOObjectFile *MachOObj, 202 const char **McpuDefault, 203 const Target **ThumbTarget) { 204 // Figure out the target triple. 205 Triple TT(TripleName); 206 if (TripleName.empty()) { 207 TT = MachOObj->getArchTriple(McpuDefault); 208 TripleName = TT.str(); 209 } 210 211 if (TT.getArch() == Triple::arm) { 212 // We've inferred a 32-bit ARM target from the object file. All MachO CPUs 213 // that support ARM are also capable of Thumb mode. 214 Triple ThumbTriple = TT; 215 std::string ThumbName = (Twine("thumb") + TT.getArchName().substr(3)).str(); 216 ThumbTriple.setArchName(ThumbName); 217 ThumbTripleName = ThumbTriple.str(); 218 } 219 220 // Get the target specific parser. 221 std::string Error; 222 const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error); 223 if (TheTarget && ThumbTripleName.empty()) 224 return TheTarget; 225 226 *ThumbTarget = TargetRegistry::lookupTarget(ThumbTripleName, Error); 227 if (*ThumbTarget) 228 return TheTarget; 229 230 WithColor::error(errs(), "llvm-objdump") << "unable to get target for '"; 231 if (!TheTarget) 232 errs() << TripleName; 233 else 234 errs() << ThumbTripleName; 235 errs() << "', see --version and --triple.\n"; 236 return nullptr; 237 } 238 239 struct SymbolSorter { 240 bool operator()(const SymbolRef &A, const SymbolRef &B) { 241 Expected<SymbolRef::Type> ATypeOrErr = A.getType(); 242 if (!ATypeOrErr) 243 reportError(ATypeOrErr.takeError(), A.getObject()->getFileName()); 244 SymbolRef::Type AType = *ATypeOrErr; 245 Expected<SymbolRef::Type> BTypeOrErr = B.getType(); 246 if (!BTypeOrErr) 247 reportError(BTypeOrErr.takeError(), B.getObject()->getFileName()); 248 SymbolRef::Type BType = *BTypeOrErr; 249 uint64_t AAddr = (AType != SymbolRef::ST_Function) ? 0 : A.getValue(); 250 uint64_t BAddr = (BType != SymbolRef::ST_Function) ? 0 : B.getValue(); 251 return AAddr < BAddr; 252 } 253 }; 254 255 // Types for the storted data in code table that is built before disassembly 256 // and the predicate function to sort them. 257 typedef std::pair<uint64_t, DiceRef> DiceTableEntry; 258 typedef std::vector<DiceTableEntry> DiceTable; 259 typedef DiceTable::iterator dice_table_iterator; 260 261 #ifdef HAVE_LIBXAR 262 namespace { 263 struct ScopedXarFile { 264 xar_t xar; 265 ScopedXarFile(const char *filename, int32_t flags) 266 : xar(xar_open(filename, flags)) {} 267 ~ScopedXarFile() { 268 if (xar) 269 xar_close(xar); 270 } 271 ScopedXarFile(const ScopedXarFile &) = delete; 272 ScopedXarFile &operator=(const ScopedXarFile &) = delete; 273 operator xar_t() { return xar; } 274 }; 275 276 struct ScopedXarIter { 277 xar_iter_t iter; 278 ScopedXarIter() : iter(xar_iter_new()) {} 279 ~ScopedXarIter() { 280 if (iter) 281 xar_iter_free(iter); 282 } 283 ScopedXarIter(const ScopedXarIter &) = delete; 284 ScopedXarIter &operator=(const ScopedXarIter &) = delete; 285 operator xar_iter_t() { return iter; } 286 }; 287 } // namespace 288 #endif // defined(HAVE_LIBXAR) 289 290 // This is used to search for a data in code table entry for the PC being 291 // disassembled. The j parameter has the PC in j.first. A single data in code 292 // table entry can cover many bytes for each of its Kind's. So if the offset, 293 // aka the i.first value, of the data in code table entry plus its Length 294 // covers the PC being searched for this will return true. If not it will 295 // return false. 296 static bool compareDiceTableEntries(const DiceTableEntry &i, 297 const DiceTableEntry &j) { 298 uint16_t Length; 299 i.second.getLength(Length); 300 301 return j.first >= i.first && j.first < i.first + Length; 302 } 303 304 static uint64_t DumpDataInCode(const uint8_t *bytes, uint64_t Length, 305 unsigned short Kind) { 306 uint32_t Value, Size = 1; 307 308 switch (Kind) { 309 default: 310 case MachO::DICE_KIND_DATA: 311 if (Length >= 4) { 312 if (!NoShowRawInsn) 313 dumpBytes(makeArrayRef(bytes, 4), outs()); 314 Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0]; 315 outs() << "\t.long " << Value; 316 Size = 4; 317 } else if (Length >= 2) { 318 if (!NoShowRawInsn) 319 dumpBytes(makeArrayRef(bytes, 2), outs()); 320 Value = bytes[1] << 8 | bytes[0]; 321 outs() << "\t.short " << Value; 322 Size = 2; 323 } else { 324 if (!NoShowRawInsn) 325 dumpBytes(makeArrayRef(bytes, 2), outs()); 326 Value = bytes[0]; 327 outs() << "\t.byte " << Value; 328 Size = 1; 329 } 330 if (Kind == MachO::DICE_KIND_DATA) 331 outs() << "\t@ KIND_DATA\n"; 332 else 333 outs() << "\t@ data in code kind = " << Kind << "\n"; 334 break; 335 case MachO::DICE_KIND_JUMP_TABLE8: 336 if (!NoShowRawInsn) 337 dumpBytes(makeArrayRef(bytes, 1), outs()); 338 Value = bytes[0]; 339 outs() << "\t.byte " << format("%3u", Value) << "\t@ KIND_JUMP_TABLE8\n"; 340 Size = 1; 341 break; 342 case MachO::DICE_KIND_JUMP_TABLE16: 343 if (!NoShowRawInsn) 344 dumpBytes(makeArrayRef(bytes, 2), outs()); 345 Value = bytes[1] << 8 | bytes[0]; 346 outs() << "\t.short " << format("%5u", Value & 0xffff) 347 << "\t@ KIND_JUMP_TABLE16\n"; 348 Size = 2; 349 break; 350 case MachO::DICE_KIND_JUMP_TABLE32: 351 case MachO::DICE_KIND_ABS_JUMP_TABLE32: 352 if (!NoShowRawInsn) 353 dumpBytes(makeArrayRef(bytes, 4), outs()); 354 Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0]; 355 outs() << "\t.long " << Value; 356 if (Kind == MachO::DICE_KIND_JUMP_TABLE32) 357 outs() << "\t@ KIND_JUMP_TABLE32\n"; 358 else 359 outs() << "\t@ KIND_ABS_JUMP_TABLE32\n"; 360 Size = 4; 361 break; 362 } 363 return Size; 364 } 365 366 static void getSectionsAndSymbols(MachOObjectFile *MachOObj, 367 std::vector<SectionRef> &Sections, 368 std::vector<SymbolRef> &Symbols, 369 SmallVectorImpl<uint64_t> &FoundFns, 370 uint64_t &BaseSegmentAddress) { 371 const StringRef FileName = MachOObj->getFileName(); 372 for (const SymbolRef &Symbol : MachOObj->symbols()) { 373 StringRef SymName = unwrapOrError(Symbol.getName(), FileName); 374 if (!SymName.startswith("ltmp")) 375 Symbols.push_back(Symbol); 376 } 377 378 for (const SectionRef &Section : MachOObj->sections()) 379 Sections.push_back(Section); 380 381 bool BaseSegmentAddressSet = false; 382 for (const auto &Command : MachOObj->load_commands()) { 383 if (Command.C.cmd == MachO::LC_FUNCTION_STARTS) { 384 // We found a function starts segment, parse the addresses for later 385 // consumption. 386 MachO::linkedit_data_command LLC = 387 MachOObj->getLinkeditDataLoadCommand(Command); 388 389 MachOObj->ReadULEB128s(LLC.dataoff, FoundFns); 390 } else if (Command.C.cmd == MachO::LC_SEGMENT) { 391 MachO::segment_command SLC = MachOObj->getSegmentLoadCommand(Command); 392 StringRef SegName = SLC.segname; 393 if (!BaseSegmentAddressSet && SegName != "__PAGEZERO") { 394 BaseSegmentAddressSet = true; 395 BaseSegmentAddress = SLC.vmaddr; 396 } 397 } else if (Command.C.cmd == MachO::LC_SEGMENT_64) { 398 MachO::segment_command_64 SLC = MachOObj->getSegment64LoadCommand(Command); 399 StringRef SegName = SLC.segname; 400 if (!BaseSegmentAddressSet && SegName != "__PAGEZERO") { 401 BaseSegmentAddressSet = true; 402 BaseSegmentAddress = SLC.vmaddr; 403 } 404 } 405 } 406 } 407 408 static bool DumpAndSkipDataInCode(uint64_t PC, const uint8_t *bytes, 409 DiceTable &Dices, uint64_t &InstSize) { 410 // Check the data in code table here to see if this is data not an 411 // instruction to be disassembled. 412 DiceTable Dice; 413 Dice.push_back(std::make_pair(PC, DiceRef())); 414 dice_table_iterator DTI = 415 std::search(Dices.begin(), Dices.end(), Dice.begin(), Dice.end(), 416 compareDiceTableEntries); 417 if (DTI != Dices.end()) { 418 uint16_t Length; 419 DTI->second.getLength(Length); 420 uint16_t Kind; 421 DTI->second.getKind(Kind); 422 InstSize = DumpDataInCode(bytes, Length, Kind); 423 if ((Kind == MachO::DICE_KIND_JUMP_TABLE8) && 424 (PC == (DTI->first + Length - 1)) && (Length & 1)) 425 InstSize++; 426 return true; 427 } 428 return false; 429 } 430 431 static void printRelocationTargetName(const MachOObjectFile *O, 432 const MachO::any_relocation_info &RE, 433 raw_string_ostream &Fmt) { 434 // Target of a scattered relocation is an address. In the interest of 435 // generating pretty output, scan through the symbol table looking for a 436 // symbol that aligns with that address. If we find one, print it. 437 // Otherwise, we just print the hex address of the target. 438 const StringRef FileName = O->getFileName(); 439 if (O->isRelocationScattered(RE)) { 440 uint32_t Val = O->getPlainRelocationSymbolNum(RE); 441 442 for (const SymbolRef &Symbol : O->symbols()) { 443 uint64_t Addr = unwrapOrError(Symbol.getAddress(), FileName); 444 if (Addr != Val) 445 continue; 446 Fmt << unwrapOrError(Symbol.getName(), FileName); 447 return; 448 } 449 450 // If we couldn't find a symbol that this relocation refers to, try 451 // to find a section beginning instead. 452 for (const SectionRef &Section : ToolSectionFilter(*O)) { 453 uint64_t Addr = Section.getAddress(); 454 if (Addr != Val) 455 continue; 456 StringRef NameOrErr = unwrapOrError(Section.getName(), O->getFileName()); 457 Fmt << NameOrErr; 458 return; 459 } 460 461 Fmt << format("0x%x", Val); 462 return; 463 } 464 465 StringRef S; 466 bool isExtern = O->getPlainRelocationExternal(RE); 467 uint64_t Val = O->getPlainRelocationSymbolNum(RE); 468 469 if (O->getAnyRelocationType(RE) == MachO::ARM64_RELOC_ADDEND) { 470 Fmt << format("0x%0" PRIx64, Val); 471 return; 472 } 473 474 if (isExtern) { 475 symbol_iterator SI = O->symbol_begin(); 476 advance(SI, Val); 477 S = unwrapOrError(SI->getName(), FileName); 478 } else { 479 section_iterator SI = O->section_begin(); 480 // Adjust for the fact that sections are 1-indexed. 481 if (Val == 0) { 482 Fmt << "0 (?,?)"; 483 return; 484 } 485 uint32_t I = Val - 1; 486 while (I != 0 && SI != O->section_end()) { 487 --I; 488 advance(SI, 1); 489 } 490 if (SI == O->section_end()) { 491 Fmt << Val << " (?,?)"; 492 } else { 493 if (Expected<StringRef> NameOrErr = SI->getName()) 494 S = *NameOrErr; 495 else 496 consumeError(NameOrErr.takeError()); 497 } 498 } 499 500 Fmt << S; 501 } 502 503 Error getMachORelocationValueString(const MachOObjectFile *Obj, 504 const RelocationRef &RelRef, 505 SmallVectorImpl<char> &Result) { 506 DataRefImpl Rel = RelRef.getRawDataRefImpl(); 507 MachO::any_relocation_info RE = Obj->getRelocation(Rel); 508 509 unsigned Arch = Obj->getArch(); 510 511 std::string FmtBuf; 512 raw_string_ostream Fmt(FmtBuf); 513 unsigned Type = Obj->getAnyRelocationType(RE); 514 bool IsPCRel = Obj->getAnyRelocationPCRel(RE); 515 516 // Determine any addends that should be displayed with the relocation. 517 // These require decoding the relocation type, which is triple-specific. 518 519 // X86_64 has entirely custom relocation types. 520 if (Arch == Triple::x86_64) { 521 switch (Type) { 522 case MachO::X86_64_RELOC_GOT_LOAD: 523 case MachO::X86_64_RELOC_GOT: { 524 printRelocationTargetName(Obj, RE, Fmt); 525 Fmt << "@GOT"; 526 if (IsPCRel) 527 Fmt << "PCREL"; 528 break; 529 } 530 case MachO::X86_64_RELOC_SUBTRACTOR: { 531 DataRefImpl RelNext = Rel; 532 Obj->moveRelocationNext(RelNext); 533 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext); 534 535 // X86_64_RELOC_SUBTRACTOR must be followed by a relocation of type 536 // X86_64_RELOC_UNSIGNED. 537 // NOTE: Scattered relocations don't exist on x86_64. 538 unsigned RType = Obj->getAnyRelocationType(RENext); 539 if (RType != MachO::X86_64_RELOC_UNSIGNED) 540 reportError(Obj->getFileName(), "Expected X86_64_RELOC_UNSIGNED after " 541 "X86_64_RELOC_SUBTRACTOR."); 542 543 // The X86_64_RELOC_UNSIGNED contains the minuend symbol; 544 // X86_64_RELOC_SUBTRACTOR contains the subtrahend. 545 printRelocationTargetName(Obj, RENext, Fmt); 546 Fmt << "-"; 547 printRelocationTargetName(Obj, RE, Fmt); 548 break; 549 } 550 case MachO::X86_64_RELOC_TLV: 551 printRelocationTargetName(Obj, RE, Fmt); 552 Fmt << "@TLV"; 553 if (IsPCRel) 554 Fmt << "P"; 555 break; 556 case MachO::X86_64_RELOC_SIGNED_1: 557 printRelocationTargetName(Obj, RE, Fmt); 558 Fmt << "-1"; 559 break; 560 case MachO::X86_64_RELOC_SIGNED_2: 561 printRelocationTargetName(Obj, RE, Fmt); 562 Fmt << "-2"; 563 break; 564 case MachO::X86_64_RELOC_SIGNED_4: 565 printRelocationTargetName(Obj, RE, Fmt); 566 Fmt << "-4"; 567 break; 568 default: 569 printRelocationTargetName(Obj, RE, Fmt); 570 break; 571 } 572 // X86 and ARM share some relocation types in common. 573 } else if (Arch == Triple::x86 || Arch == Triple::arm || 574 Arch == Triple::ppc) { 575 // Generic relocation types... 576 switch (Type) { 577 case MachO::GENERIC_RELOC_PAIR: // prints no info 578 return Error::success(); 579 case MachO::GENERIC_RELOC_SECTDIFF: { 580 DataRefImpl RelNext = Rel; 581 Obj->moveRelocationNext(RelNext); 582 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext); 583 584 // X86 sect diff's must be followed by a relocation of type 585 // GENERIC_RELOC_PAIR. 586 unsigned RType = Obj->getAnyRelocationType(RENext); 587 588 if (RType != MachO::GENERIC_RELOC_PAIR) 589 reportError(Obj->getFileName(), "Expected GENERIC_RELOC_PAIR after " 590 "GENERIC_RELOC_SECTDIFF."); 591 592 printRelocationTargetName(Obj, RE, Fmt); 593 Fmt << "-"; 594 printRelocationTargetName(Obj, RENext, Fmt); 595 break; 596 } 597 } 598 599 if (Arch == Triple::x86 || Arch == Triple::ppc) { 600 switch (Type) { 601 case MachO::GENERIC_RELOC_LOCAL_SECTDIFF: { 602 DataRefImpl RelNext = Rel; 603 Obj->moveRelocationNext(RelNext); 604 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext); 605 606 // X86 sect diff's must be followed by a relocation of type 607 // GENERIC_RELOC_PAIR. 608 unsigned RType = Obj->getAnyRelocationType(RENext); 609 if (RType != MachO::GENERIC_RELOC_PAIR) 610 reportError(Obj->getFileName(), "Expected GENERIC_RELOC_PAIR after " 611 "GENERIC_RELOC_LOCAL_SECTDIFF."); 612 613 printRelocationTargetName(Obj, RE, Fmt); 614 Fmt << "-"; 615 printRelocationTargetName(Obj, RENext, Fmt); 616 break; 617 } 618 case MachO::GENERIC_RELOC_TLV: { 619 printRelocationTargetName(Obj, RE, Fmt); 620 Fmt << "@TLV"; 621 if (IsPCRel) 622 Fmt << "P"; 623 break; 624 } 625 default: 626 printRelocationTargetName(Obj, RE, Fmt); 627 } 628 } else { // ARM-specific relocations 629 switch (Type) { 630 case MachO::ARM_RELOC_HALF: 631 case MachO::ARM_RELOC_HALF_SECTDIFF: { 632 // Half relocations steal a bit from the length field to encode 633 // whether this is an upper16 or a lower16 relocation. 634 bool isUpper = (Obj->getAnyRelocationLength(RE) & 0x1) == 1; 635 636 if (isUpper) 637 Fmt << ":upper16:("; 638 else 639 Fmt << ":lower16:("; 640 printRelocationTargetName(Obj, RE, Fmt); 641 642 DataRefImpl RelNext = Rel; 643 Obj->moveRelocationNext(RelNext); 644 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext); 645 646 // ARM half relocs must be followed by a relocation of type 647 // ARM_RELOC_PAIR. 648 unsigned RType = Obj->getAnyRelocationType(RENext); 649 if (RType != MachO::ARM_RELOC_PAIR) 650 reportError(Obj->getFileName(), "Expected ARM_RELOC_PAIR after " 651 "ARM_RELOC_HALF"); 652 653 // NOTE: The half of the target virtual address is stashed in the 654 // address field of the secondary relocation, but we can't reverse 655 // engineer the constant offset from it without decoding the movw/movt 656 // instruction to find the other half in its immediate field. 657 658 // ARM_RELOC_HALF_SECTDIFF encodes the second section in the 659 // symbol/section pointer of the follow-on relocation. 660 if (Type == MachO::ARM_RELOC_HALF_SECTDIFF) { 661 Fmt << "-"; 662 printRelocationTargetName(Obj, RENext, Fmt); 663 } 664 665 Fmt << ")"; 666 break; 667 } 668 default: { 669 printRelocationTargetName(Obj, RE, Fmt); 670 } 671 } 672 } 673 } else 674 printRelocationTargetName(Obj, RE, Fmt); 675 676 Fmt.flush(); 677 Result.append(FmtBuf.begin(), FmtBuf.end()); 678 return Error::success(); 679 } 680 681 static void PrintIndirectSymbolTable(MachOObjectFile *O, bool verbose, 682 uint32_t n, uint32_t count, 683 uint32_t stride, uint64_t addr) { 684 MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand(); 685 uint32_t nindirectsyms = Dysymtab.nindirectsyms; 686 if (n > nindirectsyms) 687 outs() << " (entries start past the end of the indirect symbol " 688 "table) (reserved1 field greater than the table size)"; 689 else if (n + count > nindirectsyms) 690 outs() << " (entries extends past the end of the indirect symbol " 691 "table)"; 692 outs() << "\n"; 693 uint32_t cputype = O->getHeader().cputype; 694 if (cputype & MachO::CPU_ARCH_ABI64) 695 outs() << "address index"; 696 else 697 outs() << "address index"; 698 if (verbose) 699 outs() << " name\n"; 700 else 701 outs() << "\n"; 702 for (uint32_t j = 0; j < count && n + j < nindirectsyms; j++) { 703 if (cputype & MachO::CPU_ARCH_ABI64) 704 outs() << format("0x%016" PRIx64, addr + j * stride) << " "; 705 else 706 outs() << format("0x%08" PRIx32, (uint32_t)addr + j * stride) << " "; 707 MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand(); 708 uint32_t indirect_symbol = O->getIndirectSymbolTableEntry(Dysymtab, n + j); 709 if (indirect_symbol == MachO::INDIRECT_SYMBOL_LOCAL) { 710 outs() << "LOCAL\n"; 711 continue; 712 } 713 if (indirect_symbol == 714 (MachO::INDIRECT_SYMBOL_LOCAL | MachO::INDIRECT_SYMBOL_ABS)) { 715 outs() << "LOCAL ABSOLUTE\n"; 716 continue; 717 } 718 if (indirect_symbol == MachO::INDIRECT_SYMBOL_ABS) { 719 outs() << "ABSOLUTE\n"; 720 continue; 721 } 722 outs() << format("%5u ", indirect_symbol); 723 if (verbose) { 724 MachO::symtab_command Symtab = O->getSymtabLoadCommand(); 725 if (indirect_symbol < Symtab.nsyms) { 726 symbol_iterator Sym = O->getSymbolByIndex(indirect_symbol); 727 SymbolRef Symbol = *Sym; 728 outs() << unwrapOrError(Symbol.getName(), O->getFileName()); 729 } else { 730 outs() << "?"; 731 } 732 } 733 outs() << "\n"; 734 } 735 } 736 737 static void PrintIndirectSymbols(MachOObjectFile *O, bool verbose) { 738 for (const auto &Load : O->load_commands()) { 739 if (Load.C.cmd == MachO::LC_SEGMENT_64) { 740 MachO::segment_command_64 Seg = O->getSegment64LoadCommand(Load); 741 for (unsigned J = 0; J < Seg.nsects; ++J) { 742 MachO::section_64 Sec = O->getSection64(Load, J); 743 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE; 744 if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS || 745 section_type == MachO::S_LAZY_SYMBOL_POINTERS || 746 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS || 747 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS || 748 section_type == MachO::S_SYMBOL_STUBS) { 749 uint32_t stride; 750 if (section_type == MachO::S_SYMBOL_STUBS) 751 stride = Sec.reserved2; 752 else 753 stride = 8; 754 if (stride == 0) { 755 outs() << "Can't print indirect symbols for (" << Sec.segname << "," 756 << Sec.sectname << ") " 757 << "(size of stubs in reserved2 field is zero)\n"; 758 continue; 759 } 760 uint32_t count = Sec.size / stride; 761 outs() << "Indirect symbols for (" << Sec.segname << "," 762 << Sec.sectname << ") " << count << " entries"; 763 uint32_t n = Sec.reserved1; 764 PrintIndirectSymbolTable(O, verbose, n, count, stride, Sec.addr); 765 } 766 } 767 } else if (Load.C.cmd == MachO::LC_SEGMENT) { 768 MachO::segment_command Seg = O->getSegmentLoadCommand(Load); 769 for (unsigned J = 0; J < Seg.nsects; ++J) { 770 MachO::section Sec = O->getSection(Load, J); 771 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE; 772 if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS || 773 section_type == MachO::S_LAZY_SYMBOL_POINTERS || 774 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS || 775 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS || 776 section_type == MachO::S_SYMBOL_STUBS) { 777 uint32_t stride; 778 if (section_type == MachO::S_SYMBOL_STUBS) 779 stride = Sec.reserved2; 780 else 781 stride = 4; 782 if (stride == 0) { 783 outs() << "Can't print indirect symbols for (" << Sec.segname << "," 784 << Sec.sectname << ") " 785 << "(size of stubs in reserved2 field is zero)\n"; 786 continue; 787 } 788 uint32_t count = Sec.size / stride; 789 outs() << "Indirect symbols for (" << Sec.segname << "," 790 << Sec.sectname << ") " << count << " entries"; 791 uint32_t n = Sec.reserved1; 792 PrintIndirectSymbolTable(O, verbose, n, count, stride, Sec.addr); 793 } 794 } 795 } 796 } 797 } 798 799 static void PrintRType(const uint64_t cputype, const unsigned r_type) { 800 static char const *generic_r_types[] = { 801 "VANILLA ", "PAIR ", "SECTDIF ", "PBLAPTR ", "LOCSDIF ", "TLV ", 802 " 6 (?) ", " 7 (?) ", " 8 (?) ", " 9 (?) ", " 10 (?) ", " 11 (?) ", 803 " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) " 804 }; 805 static char const *x86_64_r_types[] = { 806 "UNSIGND ", "SIGNED ", "BRANCH ", "GOT_LD ", "GOT ", "SUB ", 807 "SIGNED1 ", "SIGNED2 ", "SIGNED4 ", "TLV ", " 10 (?) ", " 11 (?) ", 808 " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) " 809 }; 810 static char const *arm_r_types[] = { 811 "VANILLA ", "PAIR ", "SECTDIFF", "LOCSDIF ", "PBLAPTR ", 812 "BR24 ", "T_BR22 ", "T_BR32 ", "HALF ", "HALFDIF ", 813 " 10 (?) ", " 11 (?) ", " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) " 814 }; 815 static char const *arm64_r_types[] = { 816 "UNSIGND ", "SUB ", "BR26 ", "PAGE21 ", "PAGOF12 ", 817 "GOTLDP ", "GOTLDPOF", "PTRTGOT ", "TLVLDP ", "TLVLDPOF", 818 "ADDEND ", " 11 (?) ", " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) " 819 }; 820 821 if (r_type > 0xf){ 822 outs() << format("%-7u", r_type) << " "; 823 return; 824 } 825 switch (cputype) { 826 case MachO::CPU_TYPE_I386: 827 outs() << generic_r_types[r_type]; 828 break; 829 case MachO::CPU_TYPE_X86_64: 830 outs() << x86_64_r_types[r_type]; 831 break; 832 case MachO::CPU_TYPE_ARM: 833 outs() << arm_r_types[r_type]; 834 break; 835 case MachO::CPU_TYPE_ARM64: 836 case MachO::CPU_TYPE_ARM64_32: 837 outs() << arm64_r_types[r_type]; 838 break; 839 default: 840 outs() << format("%-7u ", r_type); 841 } 842 } 843 844 static void PrintRLength(const uint64_t cputype, const unsigned r_type, 845 const unsigned r_length, const bool previous_arm_half){ 846 if (cputype == MachO::CPU_TYPE_ARM && 847 (r_type == MachO::ARM_RELOC_HALF || 848 r_type == MachO::ARM_RELOC_HALF_SECTDIFF || previous_arm_half == true)) { 849 if ((r_length & 0x1) == 0) 850 outs() << "lo/"; 851 else 852 outs() << "hi/"; 853 if ((r_length & 0x1) == 0) 854 outs() << "arm "; 855 else 856 outs() << "thm "; 857 } else { 858 switch (r_length) { 859 case 0: 860 outs() << "byte "; 861 break; 862 case 1: 863 outs() << "word "; 864 break; 865 case 2: 866 outs() << "long "; 867 break; 868 case 3: 869 if (cputype == MachO::CPU_TYPE_X86_64) 870 outs() << "quad "; 871 else 872 outs() << format("?(%2d) ", r_length); 873 break; 874 default: 875 outs() << format("?(%2d) ", r_length); 876 } 877 } 878 } 879 880 static void PrintRelocationEntries(const MachOObjectFile *O, 881 const relocation_iterator Begin, 882 const relocation_iterator End, 883 const uint64_t cputype, 884 const bool verbose) { 885 const MachO::symtab_command Symtab = O->getSymtabLoadCommand(); 886 bool previous_arm_half = false; 887 bool previous_sectdiff = false; 888 uint32_t sectdiff_r_type = 0; 889 890 for (relocation_iterator Reloc = Begin; Reloc != End; ++Reloc) { 891 const DataRefImpl Rel = Reloc->getRawDataRefImpl(); 892 const MachO::any_relocation_info RE = O->getRelocation(Rel); 893 const unsigned r_type = O->getAnyRelocationType(RE); 894 const bool r_scattered = O->isRelocationScattered(RE); 895 const unsigned r_pcrel = O->getAnyRelocationPCRel(RE); 896 const unsigned r_length = O->getAnyRelocationLength(RE); 897 const unsigned r_address = O->getAnyRelocationAddress(RE); 898 const bool r_extern = (r_scattered ? false : 899 O->getPlainRelocationExternal(RE)); 900 const uint32_t r_value = (r_scattered ? 901 O->getScatteredRelocationValue(RE) : 0); 902 const unsigned r_symbolnum = (r_scattered ? 0 : 903 O->getPlainRelocationSymbolNum(RE)); 904 905 if (r_scattered && cputype != MachO::CPU_TYPE_X86_64) { 906 if (verbose) { 907 // scattered: address 908 if ((cputype == MachO::CPU_TYPE_I386 && 909 r_type == MachO::GENERIC_RELOC_PAIR) || 910 (cputype == MachO::CPU_TYPE_ARM && r_type == MachO::ARM_RELOC_PAIR)) 911 outs() << " "; 912 else 913 outs() << format("%08x ", (unsigned int)r_address); 914 915 // scattered: pcrel 916 if (r_pcrel) 917 outs() << "True "; 918 else 919 outs() << "False "; 920 921 // scattered: length 922 PrintRLength(cputype, r_type, r_length, previous_arm_half); 923 924 // scattered: extern & type 925 outs() << "n/a "; 926 PrintRType(cputype, r_type); 927 928 // scattered: scattered & value 929 outs() << format("True 0x%08x", (unsigned int)r_value); 930 if (previous_sectdiff == false) { 931 if ((cputype == MachO::CPU_TYPE_ARM && 932 r_type == MachO::ARM_RELOC_PAIR)) 933 outs() << format(" half = 0x%04x ", (unsigned int)r_address); 934 } else if (cputype == MachO::CPU_TYPE_ARM && 935 sectdiff_r_type == MachO::ARM_RELOC_HALF_SECTDIFF) 936 outs() << format(" other_half = 0x%04x ", (unsigned int)r_address); 937 if ((cputype == MachO::CPU_TYPE_I386 && 938 (r_type == MachO::GENERIC_RELOC_SECTDIFF || 939 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF)) || 940 (cputype == MachO::CPU_TYPE_ARM && 941 (sectdiff_r_type == MachO::ARM_RELOC_SECTDIFF || 942 sectdiff_r_type == MachO::ARM_RELOC_LOCAL_SECTDIFF || 943 sectdiff_r_type == MachO::ARM_RELOC_HALF_SECTDIFF))) { 944 previous_sectdiff = true; 945 sectdiff_r_type = r_type; 946 } else { 947 previous_sectdiff = false; 948 sectdiff_r_type = 0; 949 } 950 if (cputype == MachO::CPU_TYPE_ARM && 951 (r_type == MachO::ARM_RELOC_HALF || 952 r_type == MachO::ARM_RELOC_HALF_SECTDIFF)) 953 previous_arm_half = true; 954 else 955 previous_arm_half = false; 956 outs() << "\n"; 957 } 958 else { 959 // scattered: address pcrel length extern type scattered value 960 outs() << format("%08x %1d %-2d n/a %-7d 1 0x%08x\n", 961 (unsigned int)r_address, r_pcrel, r_length, r_type, 962 (unsigned int)r_value); 963 } 964 } 965 else { 966 if (verbose) { 967 // plain: address 968 if (cputype == MachO::CPU_TYPE_ARM && r_type == MachO::ARM_RELOC_PAIR) 969 outs() << " "; 970 else 971 outs() << format("%08x ", (unsigned int)r_address); 972 973 // plain: pcrel 974 if (r_pcrel) 975 outs() << "True "; 976 else 977 outs() << "False "; 978 979 // plain: length 980 PrintRLength(cputype, r_type, r_length, previous_arm_half); 981 982 if (r_extern) { 983 // plain: extern & type & scattered 984 outs() << "True "; 985 PrintRType(cputype, r_type); 986 outs() << "False "; 987 988 // plain: symbolnum/value 989 if (r_symbolnum > Symtab.nsyms) 990 outs() << format("?(%d)\n", r_symbolnum); 991 else { 992 SymbolRef Symbol = *O->getSymbolByIndex(r_symbolnum); 993 Expected<StringRef> SymNameNext = Symbol.getName(); 994 const char *name = NULL; 995 if (SymNameNext) 996 name = SymNameNext->data(); 997 if (name == NULL) 998 outs() << format("?(%d)\n", r_symbolnum); 999 else 1000 outs() << name << "\n"; 1001 } 1002 } 1003 else { 1004 // plain: extern & type & scattered 1005 outs() << "False "; 1006 PrintRType(cputype, r_type); 1007 outs() << "False "; 1008 1009 // plain: symbolnum/value 1010 if (cputype == MachO::CPU_TYPE_ARM && r_type == MachO::ARM_RELOC_PAIR) 1011 outs() << format("other_half = 0x%04x\n", (unsigned int)r_address); 1012 else if ((cputype == MachO::CPU_TYPE_ARM64 || 1013 cputype == MachO::CPU_TYPE_ARM64_32) && 1014 r_type == MachO::ARM64_RELOC_ADDEND) 1015 outs() << format("addend = 0x%06x\n", (unsigned int)r_symbolnum); 1016 else { 1017 outs() << format("%d ", r_symbolnum); 1018 if (r_symbolnum == MachO::R_ABS) 1019 outs() << "R_ABS\n"; 1020 else { 1021 // in this case, r_symbolnum is actually a 1-based section number 1022 uint32_t nsects = O->section_end()->getRawDataRefImpl().d.a; 1023 if (r_symbolnum > 0 && r_symbolnum <= nsects) { 1024 object::DataRefImpl DRI; 1025 DRI.d.a = r_symbolnum-1; 1026 StringRef SegName = O->getSectionFinalSegmentName(DRI); 1027 if (Expected<StringRef> NameOrErr = O->getSectionName(DRI)) 1028 outs() << "(" << SegName << "," << *NameOrErr << ")\n"; 1029 else 1030 outs() << "(?,?)\n"; 1031 } 1032 else { 1033 outs() << "(?,?)\n"; 1034 } 1035 } 1036 } 1037 } 1038 if (cputype == MachO::CPU_TYPE_ARM && 1039 (r_type == MachO::ARM_RELOC_HALF || 1040 r_type == MachO::ARM_RELOC_HALF_SECTDIFF)) 1041 previous_arm_half = true; 1042 else 1043 previous_arm_half = false; 1044 } 1045 else { 1046 // plain: address pcrel length extern type scattered symbolnum/section 1047 outs() << format("%08x %1d %-2d %1d %-7d 0 %d\n", 1048 (unsigned int)r_address, r_pcrel, r_length, r_extern, 1049 r_type, r_symbolnum); 1050 } 1051 } 1052 } 1053 } 1054 1055 static void PrintRelocations(const MachOObjectFile *O, const bool verbose) { 1056 const uint64_t cputype = O->getHeader().cputype; 1057 const MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand(); 1058 if (Dysymtab.nextrel != 0) { 1059 outs() << "External relocation information " << Dysymtab.nextrel 1060 << " entries"; 1061 outs() << "\naddress pcrel length extern type scattered " 1062 "symbolnum/value\n"; 1063 PrintRelocationEntries(O, O->extrel_begin(), O->extrel_end(), cputype, 1064 verbose); 1065 } 1066 if (Dysymtab.nlocrel != 0) { 1067 outs() << format("Local relocation information %u entries", 1068 Dysymtab.nlocrel); 1069 outs() << "\naddress pcrel length extern type scattered " 1070 "symbolnum/value\n"; 1071 PrintRelocationEntries(O, O->locrel_begin(), O->locrel_end(), cputype, 1072 verbose); 1073 } 1074 for (const auto &Load : O->load_commands()) { 1075 if (Load.C.cmd == MachO::LC_SEGMENT_64) { 1076 const MachO::segment_command_64 Seg = O->getSegment64LoadCommand(Load); 1077 for (unsigned J = 0; J < Seg.nsects; ++J) { 1078 const MachO::section_64 Sec = O->getSection64(Load, J); 1079 if (Sec.nreloc != 0) { 1080 DataRefImpl DRI; 1081 DRI.d.a = J; 1082 const StringRef SegName = O->getSectionFinalSegmentName(DRI); 1083 if (Expected<StringRef> NameOrErr = O->getSectionName(DRI)) 1084 outs() << "Relocation information (" << SegName << "," << *NameOrErr 1085 << format(") %u entries", Sec.nreloc); 1086 else 1087 outs() << "Relocation information (" << SegName << ",?) " 1088 << format("%u entries", Sec.nreloc); 1089 outs() << "\naddress pcrel length extern type scattered " 1090 "symbolnum/value\n"; 1091 PrintRelocationEntries(O, O->section_rel_begin(DRI), 1092 O->section_rel_end(DRI), cputype, verbose); 1093 } 1094 } 1095 } else if (Load.C.cmd == MachO::LC_SEGMENT) { 1096 const MachO::segment_command Seg = O->getSegmentLoadCommand(Load); 1097 for (unsigned J = 0; J < Seg.nsects; ++J) { 1098 const MachO::section Sec = O->getSection(Load, J); 1099 if (Sec.nreloc != 0) { 1100 DataRefImpl DRI; 1101 DRI.d.a = J; 1102 const StringRef SegName = O->getSectionFinalSegmentName(DRI); 1103 if (Expected<StringRef> NameOrErr = O->getSectionName(DRI)) 1104 outs() << "Relocation information (" << SegName << "," << *NameOrErr 1105 << format(") %u entries", Sec.nreloc); 1106 else 1107 outs() << "Relocation information (" << SegName << ",?) " 1108 << format("%u entries", Sec.nreloc); 1109 outs() << "\naddress pcrel length extern type scattered " 1110 "symbolnum/value\n"; 1111 PrintRelocationEntries(O, O->section_rel_begin(DRI), 1112 O->section_rel_end(DRI), cputype, verbose); 1113 } 1114 } 1115 } 1116 } 1117 } 1118 1119 static void PrintDataInCodeTable(MachOObjectFile *O, bool verbose) { 1120 MachO::linkedit_data_command DIC = O->getDataInCodeLoadCommand(); 1121 uint32_t nentries = DIC.datasize / sizeof(struct MachO::data_in_code_entry); 1122 outs() << "Data in code table (" << nentries << " entries)\n"; 1123 outs() << "offset length kind\n"; 1124 for (dice_iterator DI = O->begin_dices(), DE = O->end_dices(); DI != DE; 1125 ++DI) { 1126 uint32_t Offset; 1127 DI->getOffset(Offset); 1128 outs() << format("0x%08" PRIx32, Offset) << " "; 1129 uint16_t Length; 1130 DI->getLength(Length); 1131 outs() << format("%6u", Length) << " "; 1132 uint16_t Kind; 1133 DI->getKind(Kind); 1134 if (verbose) { 1135 switch (Kind) { 1136 case MachO::DICE_KIND_DATA: 1137 outs() << "DATA"; 1138 break; 1139 case MachO::DICE_KIND_JUMP_TABLE8: 1140 outs() << "JUMP_TABLE8"; 1141 break; 1142 case MachO::DICE_KIND_JUMP_TABLE16: 1143 outs() << "JUMP_TABLE16"; 1144 break; 1145 case MachO::DICE_KIND_JUMP_TABLE32: 1146 outs() << "JUMP_TABLE32"; 1147 break; 1148 case MachO::DICE_KIND_ABS_JUMP_TABLE32: 1149 outs() << "ABS_JUMP_TABLE32"; 1150 break; 1151 default: 1152 outs() << format("0x%04" PRIx32, Kind); 1153 break; 1154 } 1155 } else 1156 outs() << format("0x%04" PRIx32, Kind); 1157 outs() << "\n"; 1158 } 1159 } 1160 1161 static void PrintLinkOptHints(MachOObjectFile *O) { 1162 MachO::linkedit_data_command LohLC = O->getLinkOptHintsLoadCommand(); 1163 const char *loh = O->getData().substr(LohLC.dataoff, 1).data(); 1164 uint32_t nloh = LohLC.datasize; 1165 outs() << "Linker optimiztion hints (" << nloh << " total bytes)\n"; 1166 for (uint32_t i = 0; i < nloh;) { 1167 unsigned n; 1168 uint64_t identifier = decodeULEB128((const uint8_t *)(loh + i), &n); 1169 i += n; 1170 outs() << " identifier " << identifier << " "; 1171 if (i >= nloh) 1172 return; 1173 switch (identifier) { 1174 case 1: 1175 outs() << "AdrpAdrp\n"; 1176 break; 1177 case 2: 1178 outs() << "AdrpLdr\n"; 1179 break; 1180 case 3: 1181 outs() << "AdrpAddLdr\n"; 1182 break; 1183 case 4: 1184 outs() << "AdrpLdrGotLdr\n"; 1185 break; 1186 case 5: 1187 outs() << "AdrpAddStr\n"; 1188 break; 1189 case 6: 1190 outs() << "AdrpLdrGotStr\n"; 1191 break; 1192 case 7: 1193 outs() << "AdrpAdd\n"; 1194 break; 1195 case 8: 1196 outs() << "AdrpLdrGot\n"; 1197 break; 1198 default: 1199 outs() << "Unknown identifier value\n"; 1200 break; 1201 } 1202 uint64_t narguments = decodeULEB128((const uint8_t *)(loh + i), &n); 1203 i += n; 1204 outs() << " narguments " << narguments << "\n"; 1205 if (i >= nloh) 1206 return; 1207 1208 for (uint32_t j = 0; j < narguments; j++) { 1209 uint64_t value = decodeULEB128((const uint8_t *)(loh + i), &n); 1210 i += n; 1211 outs() << "\tvalue " << format("0x%" PRIx64, value) << "\n"; 1212 if (i >= nloh) 1213 return; 1214 } 1215 } 1216 } 1217 1218 static void PrintDylibs(MachOObjectFile *O, bool JustId) { 1219 unsigned Index = 0; 1220 for (const auto &Load : O->load_commands()) { 1221 if ((JustId && Load.C.cmd == MachO::LC_ID_DYLIB) || 1222 (!JustId && (Load.C.cmd == MachO::LC_ID_DYLIB || 1223 Load.C.cmd == MachO::LC_LOAD_DYLIB || 1224 Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB || 1225 Load.C.cmd == MachO::LC_REEXPORT_DYLIB || 1226 Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB || 1227 Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB))) { 1228 MachO::dylib_command dl = O->getDylibIDLoadCommand(Load); 1229 if (dl.dylib.name < dl.cmdsize) { 1230 const char *p = (const char *)(Load.Ptr) + dl.dylib.name; 1231 if (JustId) 1232 outs() << p << "\n"; 1233 else { 1234 outs() << "\t" << p; 1235 outs() << " (compatibility version " 1236 << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "." 1237 << ((dl.dylib.compatibility_version >> 8) & 0xff) << "." 1238 << (dl.dylib.compatibility_version & 0xff) << ","; 1239 outs() << " current version " 1240 << ((dl.dylib.current_version >> 16) & 0xffff) << "." 1241 << ((dl.dylib.current_version >> 8) & 0xff) << "." 1242 << (dl.dylib.current_version & 0xff); 1243 if (Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB) 1244 outs() << ", weak"; 1245 if (Load.C.cmd == MachO::LC_REEXPORT_DYLIB) 1246 outs() << ", reexport"; 1247 if (Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB) 1248 outs() << ", upward"; 1249 if (Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB) 1250 outs() << ", lazy"; 1251 outs() << ")\n"; 1252 } 1253 } else { 1254 outs() << "\tBad offset (" << dl.dylib.name << ") for name of "; 1255 if (Load.C.cmd == MachO::LC_ID_DYLIB) 1256 outs() << "LC_ID_DYLIB "; 1257 else if (Load.C.cmd == MachO::LC_LOAD_DYLIB) 1258 outs() << "LC_LOAD_DYLIB "; 1259 else if (Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB) 1260 outs() << "LC_LOAD_WEAK_DYLIB "; 1261 else if (Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB) 1262 outs() << "LC_LAZY_LOAD_DYLIB "; 1263 else if (Load.C.cmd == MachO::LC_REEXPORT_DYLIB) 1264 outs() << "LC_REEXPORT_DYLIB "; 1265 else if (Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB) 1266 outs() << "LC_LOAD_UPWARD_DYLIB "; 1267 else 1268 outs() << "LC_??? "; 1269 outs() << "command " << Index++ << "\n"; 1270 } 1271 } 1272 } 1273 } 1274 1275 typedef DenseMap<uint64_t, StringRef> SymbolAddressMap; 1276 1277 static void CreateSymbolAddressMap(MachOObjectFile *O, 1278 SymbolAddressMap *AddrMap) { 1279 // Create a map of symbol addresses to symbol names. 1280 const StringRef FileName = O->getFileName(); 1281 for (const SymbolRef &Symbol : O->symbols()) { 1282 SymbolRef::Type ST = unwrapOrError(Symbol.getType(), FileName); 1283 if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data || 1284 ST == SymbolRef::ST_Other) { 1285 uint64_t Address = Symbol.getValue(); 1286 StringRef SymName = unwrapOrError(Symbol.getName(), FileName); 1287 if (!SymName.startswith(".objc")) 1288 (*AddrMap)[Address] = SymName; 1289 } 1290 } 1291 } 1292 1293 // GuessSymbolName is passed the address of what might be a symbol and a 1294 // pointer to the SymbolAddressMap. It returns the name of a symbol 1295 // with that address or nullptr if no symbol is found with that address. 1296 static const char *GuessSymbolName(uint64_t value, SymbolAddressMap *AddrMap) { 1297 const char *SymbolName = nullptr; 1298 // A DenseMap can't lookup up some values. 1299 if (value != 0xffffffffffffffffULL && value != 0xfffffffffffffffeULL) { 1300 StringRef name = AddrMap->lookup(value); 1301 if (!name.empty()) 1302 SymbolName = name.data(); 1303 } 1304 return SymbolName; 1305 } 1306 1307 static void DumpCstringChar(const char c) { 1308 char p[2]; 1309 p[0] = c; 1310 p[1] = '\0'; 1311 outs().write_escaped(p); 1312 } 1313 1314 static void DumpCstringSection(MachOObjectFile *O, const char *sect, 1315 uint32_t sect_size, uint64_t sect_addr, 1316 bool print_addresses) { 1317 for (uint32_t i = 0; i < sect_size; i++) { 1318 if (print_addresses) { 1319 if (O->is64Bit()) 1320 outs() << format("%016" PRIx64, sect_addr + i) << " "; 1321 else 1322 outs() << format("%08" PRIx64, sect_addr + i) << " "; 1323 } 1324 for (; i < sect_size && sect[i] != '\0'; i++) 1325 DumpCstringChar(sect[i]); 1326 if (i < sect_size && sect[i] == '\0') 1327 outs() << "\n"; 1328 } 1329 } 1330 1331 static void DumpLiteral4(uint32_t l, float f) { 1332 outs() << format("0x%08" PRIx32, l); 1333 if ((l & 0x7f800000) != 0x7f800000) 1334 outs() << format(" (%.16e)\n", f); 1335 else { 1336 if (l == 0x7f800000) 1337 outs() << " (+Infinity)\n"; 1338 else if (l == 0xff800000) 1339 outs() << " (-Infinity)\n"; 1340 else if ((l & 0x00400000) == 0x00400000) 1341 outs() << " (non-signaling Not-a-Number)\n"; 1342 else 1343 outs() << " (signaling Not-a-Number)\n"; 1344 } 1345 } 1346 1347 static void DumpLiteral4Section(MachOObjectFile *O, const char *sect, 1348 uint32_t sect_size, uint64_t sect_addr, 1349 bool print_addresses) { 1350 for (uint32_t i = 0; i < sect_size; i += sizeof(float)) { 1351 if (print_addresses) { 1352 if (O->is64Bit()) 1353 outs() << format("%016" PRIx64, sect_addr + i) << " "; 1354 else 1355 outs() << format("%08" PRIx64, sect_addr + i) << " "; 1356 } 1357 float f; 1358 memcpy(&f, sect + i, sizeof(float)); 1359 if (O->isLittleEndian() != sys::IsLittleEndianHost) 1360 sys::swapByteOrder(f); 1361 uint32_t l; 1362 memcpy(&l, sect + i, sizeof(uint32_t)); 1363 if (O->isLittleEndian() != sys::IsLittleEndianHost) 1364 sys::swapByteOrder(l); 1365 DumpLiteral4(l, f); 1366 } 1367 } 1368 1369 static void DumpLiteral8(MachOObjectFile *O, uint32_t l0, uint32_t l1, 1370 double d) { 1371 outs() << format("0x%08" PRIx32, l0) << " " << format("0x%08" PRIx32, l1); 1372 uint32_t Hi, Lo; 1373 Hi = (O->isLittleEndian()) ? l1 : l0; 1374 Lo = (O->isLittleEndian()) ? l0 : l1; 1375 1376 // Hi is the high word, so this is equivalent to if(isfinite(d)) 1377 if ((Hi & 0x7ff00000) != 0x7ff00000) 1378 outs() << format(" (%.16e)\n", d); 1379 else { 1380 if (Hi == 0x7ff00000 && Lo == 0) 1381 outs() << " (+Infinity)\n"; 1382 else if (Hi == 0xfff00000 && Lo == 0) 1383 outs() << " (-Infinity)\n"; 1384 else if ((Hi & 0x00080000) == 0x00080000) 1385 outs() << " (non-signaling Not-a-Number)\n"; 1386 else 1387 outs() << " (signaling Not-a-Number)\n"; 1388 } 1389 } 1390 1391 static void DumpLiteral8Section(MachOObjectFile *O, const char *sect, 1392 uint32_t sect_size, uint64_t sect_addr, 1393 bool print_addresses) { 1394 for (uint32_t i = 0; i < sect_size; i += sizeof(double)) { 1395 if (print_addresses) { 1396 if (O->is64Bit()) 1397 outs() << format("%016" PRIx64, sect_addr + i) << " "; 1398 else 1399 outs() << format("%08" PRIx64, sect_addr + i) << " "; 1400 } 1401 double d; 1402 memcpy(&d, sect + i, sizeof(double)); 1403 if (O->isLittleEndian() != sys::IsLittleEndianHost) 1404 sys::swapByteOrder(d); 1405 uint32_t l0, l1; 1406 memcpy(&l0, sect + i, sizeof(uint32_t)); 1407 memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t)); 1408 if (O->isLittleEndian() != sys::IsLittleEndianHost) { 1409 sys::swapByteOrder(l0); 1410 sys::swapByteOrder(l1); 1411 } 1412 DumpLiteral8(O, l0, l1, d); 1413 } 1414 } 1415 1416 static void DumpLiteral16(uint32_t l0, uint32_t l1, uint32_t l2, uint32_t l3) { 1417 outs() << format("0x%08" PRIx32, l0) << " "; 1418 outs() << format("0x%08" PRIx32, l1) << " "; 1419 outs() << format("0x%08" PRIx32, l2) << " "; 1420 outs() << format("0x%08" PRIx32, l3) << "\n"; 1421 } 1422 1423 static void DumpLiteral16Section(MachOObjectFile *O, const char *sect, 1424 uint32_t sect_size, uint64_t sect_addr, 1425 bool print_addresses) { 1426 for (uint32_t i = 0; i < sect_size; i += 16) { 1427 if (print_addresses) { 1428 if (O->is64Bit()) 1429 outs() << format("%016" PRIx64, sect_addr + i) << " "; 1430 else 1431 outs() << format("%08" PRIx64, sect_addr + i) << " "; 1432 } 1433 uint32_t l0, l1, l2, l3; 1434 memcpy(&l0, sect + i, sizeof(uint32_t)); 1435 memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t)); 1436 memcpy(&l2, sect + i + 2 * sizeof(uint32_t), sizeof(uint32_t)); 1437 memcpy(&l3, sect + i + 3 * sizeof(uint32_t), sizeof(uint32_t)); 1438 if (O->isLittleEndian() != sys::IsLittleEndianHost) { 1439 sys::swapByteOrder(l0); 1440 sys::swapByteOrder(l1); 1441 sys::swapByteOrder(l2); 1442 sys::swapByteOrder(l3); 1443 } 1444 DumpLiteral16(l0, l1, l2, l3); 1445 } 1446 } 1447 1448 static void DumpLiteralPointerSection(MachOObjectFile *O, 1449 const SectionRef &Section, 1450 const char *sect, uint32_t sect_size, 1451 uint64_t sect_addr, 1452 bool print_addresses) { 1453 // Collect the literal sections in this Mach-O file. 1454 std::vector<SectionRef> LiteralSections; 1455 for (const SectionRef &Section : O->sections()) { 1456 DataRefImpl Ref = Section.getRawDataRefImpl(); 1457 uint32_t section_type; 1458 if (O->is64Bit()) { 1459 const MachO::section_64 Sec = O->getSection64(Ref); 1460 section_type = Sec.flags & MachO::SECTION_TYPE; 1461 } else { 1462 const MachO::section Sec = O->getSection(Ref); 1463 section_type = Sec.flags & MachO::SECTION_TYPE; 1464 } 1465 if (section_type == MachO::S_CSTRING_LITERALS || 1466 section_type == MachO::S_4BYTE_LITERALS || 1467 section_type == MachO::S_8BYTE_LITERALS || 1468 section_type == MachO::S_16BYTE_LITERALS) 1469 LiteralSections.push_back(Section); 1470 } 1471 1472 // Set the size of the literal pointer. 1473 uint32_t lp_size = O->is64Bit() ? 8 : 4; 1474 1475 // Collect the external relocation symbols for the literal pointers. 1476 std::vector<std::pair<uint64_t, SymbolRef>> Relocs; 1477 for (const RelocationRef &Reloc : Section.relocations()) { 1478 DataRefImpl Rel; 1479 MachO::any_relocation_info RE; 1480 bool isExtern = false; 1481 Rel = Reloc.getRawDataRefImpl(); 1482 RE = O->getRelocation(Rel); 1483 isExtern = O->getPlainRelocationExternal(RE); 1484 if (isExtern) { 1485 uint64_t RelocOffset = Reloc.getOffset(); 1486 symbol_iterator RelocSym = Reloc.getSymbol(); 1487 Relocs.push_back(std::make_pair(RelocOffset, *RelocSym)); 1488 } 1489 } 1490 array_pod_sort(Relocs.begin(), Relocs.end()); 1491 1492 // Dump each literal pointer. 1493 for (uint32_t i = 0; i < sect_size; i += lp_size) { 1494 if (print_addresses) { 1495 if (O->is64Bit()) 1496 outs() << format("%016" PRIx64, sect_addr + i) << " "; 1497 else 1498 outs() << format("%08" PRIx64, sect_addr + i) << " "; 1499 } 1500 uint64_t lp; 1501 if (O->is64Bit()) { 1502 memcpy(&lp, sect + i, sizeof(uint64_t)); 1503 if (O->isLittleEndian() != sys::IsLittleEndianHost) 1504 sys::swapByteOrder(lp); 1505 } else { 1506 uint32_t li; 1507 memcpy(&li, sect + i, sizeof(uint32_t)); 1508 if (O->isLittleEndian() != sys::IsLittleEndianHost) 1509 sys::swapByteOrder(li); 1510 lp = li; 1511 } 1512 1513 // First look for an external relocation entry for this literal pointer. 1514 auto Reloc = find_if(Relocs, [&](const std::pair<uint64_t, SymbolRef> &P) { 1515 return P.first == i; 1516 }); 1517 if (Reloc != Relocs.end()) { 1518 symbol_iterator RelocSym = Reloc->second; 1519 StringRef SymName = unwrapOrError(RelocSym->getName(), O->getFileName()); 1520 outs() << "external relocation entry for symbol:" << SymName << "\n"; 1521 continue; 1522 } 1523 1524 // For local references see what the section the literal pointer points to. 1525 auto Sect = find_if(LiteralSections, [&](const SectionRef &R) { 1526 return lp >= R.getAddress() && lp < R.getAddress() + R.getSize(); 1527 }); 1528 if (Sect == LiteralSections.end()) { 1529 outs() << format("0x%" PRIx64, lp) << " (not in a literal section)\n"; 1530 continue; 1531 } 1532 1533 uint64_t SectAddress = Sect->getAddress(); 1534 uint64_t SectSize = Sect->getSize(); 1535 1536 StringRef SectName; 1537 Expected<StringRef> SectNameOrErr = Sect->getName(); 1538 if (SectNameOrErr) 1539 SectName = *SectNameOrErr; 1540 else 1541 consumeError(SectNameOrErr.takeError()); 1542 1543 DataRefImpl Ref = Sect->getRawDataRefImpl(); 1544 StringRef SegmentName = O->getSectionFinalSegmentName(Ref); 1545 outs() << SegmentName << ":" << SectName << ":"; 1546 1547 uint32_t section_type; 1548 if (O->is64Bit()) { 1549 const MachO::section_64 Sec = O->getSection64(Ref); 1550 section_type = Sec.flags & MachO::SECTION_TYPE; 1551 } else { 1552 const MachO::section Sec = O->getSection(Ref); 1553 section_type = Sec.flags & MachO::SECTION_TYPE; 1554 } 1555 1556 StringRef BytesStr = unwrapOrError(Sect->getContents(), O->getFileName()); 1557 1558 const char *Contents = reinterpret_cast<const char *>(BytesStr.data()); 1559 1560 switch (section_type) { 1561 case MachO::S_CSTRING_LITERALS: 1562 for (uint64_t i = lp - SectAddress; i < SectSize && Contents[i] != '\0'; 1563 i++) { 1564 DumpCstringChar(Contents[i]); 1565 } 1566 outs() << "\n"; 1567 break; 1568 case MachO::S_4BYTE_LITERALS: 1569 float f; 1570 memcpy(&f, Contents + (lp - SectAddress), sizeof(float)); 1571 uint32_t l; 1572 memcpy(&l, Contents + (lp - SectAddress), sizeof(uint32_t)); 1573 if (O->isLittleEndian() != sys::IsLittleEndianHost) { 1574 sys::swapByteOrder(f); 1575 sys::swapByteOrder(l); 1576 } 1577 DumpLiteral4(l, f); 1578 break; 1579 case MachO::S_8BYTE_LITERALS: { 1580 double d; 1581 memcpy(&d, Contents + (lp - SectAddress), sizeof(double)); 1582 uint32_t l0, l1; 1583 memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t)); 1584 memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t), 1585 sizeof(uint32_t)); 1586 if (O->isLittleEndian() != sys::IsLittleEndianHost) { 1587 sys::swapByteOrder(f); 1588 sys::swapByteOrder(l0); 1589 sys::swapByteOrder(l1); 1590 } 1591 DumpLiteral8(O, l0, l1, d); 1592 break; 1593 } 1594 case MachO::S_16BYTE_LITERALS: { 1595 uint32_t l0, l1, l2, l3; 1596 memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t)); 1597 memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t), 1598 sizeof(uint32_t)); 1599 memcpy(&l2, Contents + (lp - SectAddress) + 2 * sizeof(uint32_t), 1600 sizeof(uint32_t)); 1601 memcpy(&l3, Contents + (lp - SectAddress) + 3 * sizeof(uint32_t), 1602 sizeof(uint32_t)); 1603 if (O->isLittleEndian() != sys::IsLittleEndianHost) { 1604 sys::swapByteOrder(l0); 1605 sys::swapByteOrder(l1); 1606 sys::swapByteOrder(l2); 1607 sys::swapByteOrder(l3); 1608 } 1609 DumpLiteral16(l0, l1, l2, l3); 1610 break; 1611 } 1612 } 1613 } 1614 } 1615 1616 static void DumpInitTermPointerSection(MachOObjectFile *O, 1617 const SectionRef &Section, 1618 const char *sect, 1619 uint32_t sect_size, uint64_t sect_addr, 1620 SymbolAddressMap *AddrMap, 1621 bool verbose) { 1622 uint32_t stride; 1623 stride = (O->is64Bit()) ? sizeof(uint64_t) : sizeof(uint32_t); 1624 1625 // Collect the external relocation symbols for the pointers. 1626 std::vector<std::pair<uint64_t, SymbolRef>> Relocs; 1627 for (const RelocationRef &Reloc : Section.relocations()) { 1628 DataRefImpl Rel; 1629 MachO::any_relocation_info RE; 1630 bool isExtern = false; 1631 Rel = Reloc.getRawDataRefImpl(); 1632 RE = O->getRelocation(Rel); 1633 isExtern = O->getPlainRelocationExternal(RE); 1634 if (isExtern) { 1635 uint64_t RelocOffset = Reloc.getOffset(); 1636 symbol_iterator RelocSym = Reloc.getSymbol(); 1637 Relocs.push_back(std::make_pair(RelocOffset, *RelocSym)); 1638 } 1639 } 1640 array_pod_sort(Relocs.begin(), Relocs.end()); 1641 1642 for (uint32_t i = 0; i < sect_size; i += stride) { 1643 const char *SymbolName = nullptr; 1644 uint64_t p; 1645 if (O->is64Bit()) { 1646 outs() << format("0x%016" PRIx64, sect_addr + i * stride) << " "; 1647 uint64_t pointer_value; 1648 memcpy(&pointer_value, sect + i, stride); 1649 if (O->isLittleEndian() != sys::IsLittleEndianHost) 1650 sys::swapByteOrder(pointer_value); 1651 outs() << format("0x%016" PRIx64, pointer_value); 1652 p = pointer_value; 1653 } else { 1654 outs() << format("0x%08" PRIx64, sect_addr + i * stride) << " "; 1655 uint32_t pointer_value; 1656 memcpy(&pointer_value, sect + i, stride); 1657 if (O->isLittleEndian() != sys::IsLittleEndianHost) 1658 sys::swapByteOrder(pointer_value); 1659 outs() << format("0x%08" PRIx32, pointer_value); 1660 p = pointer_value; 1661 } 1662 if (verbose) { 1663 // First look for an external relocation entry for this pointer. 1664 auto Reloc = find_if(Relocs, [&](const std::pair<uint64_t, SymbolRef> &P) { 1665 return P.first == i; 1666 }); 1667 if (Reloc != Relocs.end()) { 1668 symbol_iterator RelocSym = Reloc->second; 1669 outs() << " " << unwrapOrError(RelocSym->getName(), O->getFileName()); 1670 } else { 1671 SymbolName = GuessSymbolName(p, AddrMap); 1672 if (SymbolName) 1673 outs() << " " << SymbolName; 1674 } 1675 } 1676 outs() << "\n"; 1677 } 1678 } 1679 1680 static void DumpRawSectionContents(MachOObjectFile *O, const char *sect, 1681 uint32_t size, uint64_t addr) { 1682 uint32_t cputype = O->getHeader().cputype; 1683 if (cputype == MachO::CPU_TYPE_I386 || cputype == MachO::CPU_TYPE_X86_64) { 1684 uint32_t j; 1685 for (uint32_t i = 0; i < size; i += j, addr += j) { 1686 if (O->is64Bit()) 1687 outs() << format("%016" PRIx64, addr) << "\t"; 1688 else 1689 outs() << format("%08" PRIx64, addr) << "\t"; 1690 for (j = 0; j < 16 && i + j < size; j++) { 1691 uint8_t byte_word = *(sect + i + j); 1692 outs() << format("%02" PRIx32, (uint32_t)byte_word) << " "; 1693 } 1694 outs() << "\n"; 1695 } 1696 } else { 1697 uint32_t j; 1698 for (uint32_t i = 0; i < size; i += j, addr += j) { 1699 if (O->is64Bit()) 1700 outs() << format("%016" PRIx64, addr) << "\t"; 1701 else 1702 outs() << format("%08" PRIx64, addr) << "\t"; 1703 for (j = 0; j < 4 * sizeof(int32_t) && i + j < size; 1704 j += sizeof(int32_t)) { 1705 if (i + j + sizeof(int32_t) <= size) { 1706 uint32_t long_word; 1707 memcpy(&long_word, sect + i + j, sizeof(int32_t)); 1708 if (O->isLittleEndian() != sys::IsLittleEndianHost) 1709 sys::swapByteOrder(long_word); 1710 outs() << format("%08" PRIx32, long_word) << " "; 1711 } else { 1712 for (uint32_t k = 0; i + j + k < size; k++) { 1713 uint8_t byte_word = *(sect + i + j + k); 1714 outs() << format("%02" PRIx32, (uint32_t)byte_word) << " "; 1715 } 1716 } 1717 } 1718 outs() << "\n"; 1719 } 1720 } 1721 } 1722 1723 static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF, 1724 StringRef DisSegName, StringRef DisSectName); 1725 static void DumpProtocolSection(MachOObjectFile *O, const char *sect, 1726 uint32_t size, uint32_t addr); 1727 #ifdef HAVE_LIBXAR 1728 static void DumpBitcodeSection(MachOObjectFile *O, const char *sect, 1729 uint32_t size, bool verbose, 1730 bool PrintXarHeader, bool PrintXarFileHeaders, 1731 std::string XarMemberName); 1732 #endif // defined(HAVE_LIBXAR) 1733 1734 static void DumpSectionContents(StringRef Filename, MachOObjectFile *O, 1735 bool verbose) { 1736 SymbolAddressMap AddrMap; 1737 if (verbose) 1738 CreateSymbolAddressMap(O, &AddrMap); 1739 1740 for (unsigned i = 0; i < FilterSections.size(); ++i) { 1741 StringRef DumpSection = FilterSections[i]; 1742 std::pair<StringRef, StringRef> DumpSegSectName; 1743 DumpSegSectName = DumpSection.split(','); 1744 StringRef DumpSegName, DumpSectName; 1745 if (!DumpSegSectName.second.empty()) { 1746 DumpSegName = DumpSegSectName.first; 1747 DumpSectName = DumpSegSectName.second; 1748 } else { 1749 DumpSegName = ""; 1750 DumpSectName = DumpSegSectName.first; 1751 } 1752 for (const SectionRef &Section : O->sections()) { 1753 StringRef SectName; 1754 Expected<StringRef> SecNameOrErr = Section.getName(); 1755 if (SecNameOrErr) 1756 SectName = *SecNameOrErr; 1757 else 1758 consumeError(SecNameOrErr.takeError()); 1759 1760 if (!DumpSection.empty()) 1761 FoundSectionSet.insert(DumpSection); 1762 1763 DataRefImpl Ref = Section.getRawDataRefImpl(); 1764 StringRef SegName = O->getSectionFinalSegmentName(Ref); 1765 if ((DumpSegName.empty() || SegName == DumpSegName) && 1766 (SectName == DumpSectName)) { 1767 1768 uint32_t section_flags; 1769 if (O->is64Bit()) { 1770 const MachO::section_64 Sec = O->getSection64(Ref); 1771 section_flags = Sec.flags; 1772 1773 } else { 1774 const MachO::section Sec = O->getSection(Ref); 1775 section_flags = Sec.flags; 1776 } 1777 uint32_t section_type = section_flags & MachO::SECTION_TYPE; 1778 1779 StringRef BytesStr = 1780 unwrapOrError(Section.getContents(), O->getFileName()); 1781 const char *sect = reinterpret_cast<const char *>(BytesStr.data()); 1782 uint32_t sect_size = BytesStr.size(); 1783 uint64_t sect_addr = Section.getAddress(); 1784 1785 if (!NoLeadingHeaders) 1786 outs() << "Contents of (" << SegName << "," << SectName 1787 << ") section\n"; 1788 1789 if (verbose) { 1790 if ((section_flags & MachO::S_ATTR_PURE_INSTRUCTIONS) || 1791 (section_flags & MachO::S_ATTR_SOME_INSTRUCTIONS)) { 1792 DisassembleMachO(Filename, O, SegName, SectName); 1793 continue; 1794 } 1795 if (SegName == "__TEXT" && SectName == "__info_plist") { 1796 outs() << sect; 1797 continue; 1798 } 1799 if (SegName == "__OBJC" && SectName == "__protocol") { 1800 DumpProtocolSection(O, sect, sect_size, sect_addr); 1801 continue; 1802 } 1803 #ifdef HAVE_LIBXAR 1804 if (SegName == "__LLVM" && SectName == "__bundle") { 1805 DumpBitcodeSection(O, sect, sect_size, verbose, !NoSymbolicOperands, 1806 ArchiveHeaders, ""); 1807 continue; 1808 } 1809 #endif // defined(HAVE_LIBXAR) 1810 switch (section_type) { 1811 case MachO::S_REGULAR: 1812 DumpRawSectionContents(O, sect, sect_size, sect_addr); 1813 break; 1814 case MachO::S_ZEROFILL: 1815 outs() << "zerofill section and has no contents in the file\n"; 1816 break; 1817 case MachO::S_CSTRING_LITERALS: 1818 DumpCstringSection(O, sect, sect_size, sect_addr, !NoLeadingAddr); 1819 break; 1820 case MachO::S_4BYTE_LITERALS: 1821 DumpLiteral4Section(O, sect, sect_size, sect_addr, !NoLeadingAddr); 1822 break; 1823 case MachO::S_8BYTE_LITERALS: 1824 DumpLiteral8Section(O, sect, sect_size, sect_addr, !NoLeadingAddr); 1825 break; 1826 case MachO::S_16BYTE_LITERALS: 1827 DumpLiteral16Section(O, sect, sect_size, sect_addr, !NoLeadingAddr); 1828 break; 1829 case MachO::S_LITERAL_POINTERS: 1830 DumpLiteralPointerSection(O, Section, sect, sect_size, sect_addr, 1831 !NoLeadingAddr); 1832 break; 1833 case MachO::S_MOD_INIT_FUNC_POINTERS: 1834 case MachO::S_MOD_TERM_FUNC_POINTERS: 1835 DumpInitTermPointerSection(O, Section, sect, sect_size, sect_addr, 1836 &AddrMap, verbose); 1837 break; 1838 default: 1839 outs() << "Unknown section type (" 1840 << format("0x%08" PRIx32, section_type) << ")\n"; 1841 DumpRawSectionContents(O, sect, sect_size, sect_addr); 1842 break; 1843 } 1844 } else { 1845 if (section_type == MachO::S_ZEROFILL) 1846 outs() << "zerofill section and has no contents in the file\n"; 1847 else 1848 DumpRawSectionContents(O, sect, sect_size, sect_addr); 1849 } 1850 } 1851 } 1852 } 1853 } 1854 1855 static void DumpInfoPlistSectionContents(StringRef Filename, 1856 MachOObjectFile *O) { 1857 for (const SectionRef &Section : O->sections()) { 1858 StringRef SectName; 1859 Expected<StringRef> SecNameOrErr = Section.getName(); 1860 if (SecNameOrErr) 1861 SectName = *SecNameOrErr; 1862 else 1863 consumeError(SecNameOrErr.takeError()); 1864 1865 DataRefImpl Ref = Section.getRawDataRefImpl(); 1866 StringRef SegName = O->getSectionFinalSegmentName(Ref); 1867 if (SegName == "__TEXT" && SectName == "__info_plist") { 1868 if (!NoLeadingHeaders) 1869 outs() << "Contents of (" << SegName << "," << SectName << ") section\n"; 1870 StringRef BytesStr = 1871 unwrapOrError(Section.getContents(), O->getFileName()); 1872 const char *sect = reinterpret_cast<const char *>(BytesStr.data()); 1873 outs() << format("%.*s", BytesStr.size(), sect) << "\n"; 1874 return; 1875 } 1876 } 1877 } 1878 1879 // checkMachOAndArchFlags() checks to see if the ObjectFile is a Mach-O file 1880 // and if it is and there is a list of architecture flags is specified then 1881 // check to make sure this Mach-O file is one of those architectures or all 1882 // architectures were specified. If not then an error is generated and this 1883 // routine returns false. Else it returns true. 1884 static bool checkMachOAndArchFlags(ObjectFile *O, StringRef Filename) { 1885 auto *MachO = dyn_cast<MachOObjectFile>(O); 1886 1887 if (!MachO || ArchAll || ArchFlags.empty()) 1888 return true; 1889 1890 MachO::mach_header H; 1891 MachO::mach_header_64 H_64; 1892 Triple T; 1893 const char *McpuDefault, *ArchFlag; 1894 if (MachO->is64Bit()) { 1895 H_64 = MachO->MachOObjectFile::getHeader64(); 1896 T = MachOObjectFile::getArchTriple(H_64.cputype, H_64.cpusubtype, 1897 &McpuDefault, &ArchFlag); 1898 } else { 1899 H = MachO->MachOObjectFile::getHeader(); 1900 T = MachOObjectFile::getArchTriple(H.cputype, H.cpusubtype, 1901 &McpuDefault, &ArchFlag); 1902 } 1903 const std::string ArchFlagName(ArchFlag); 1904 if (none_of(ArchFlags, [&](const std::string &Name) { 1905 return Name == ArchFlagName; 1906 })) { 1907 WithColor::error(errs(), "llvm-objdump") 1908 << Filename << ": no architecture specified.\n"; 1909 return false; 1910 } 1911 return true; 1912 } 1913 1914 static void printObjcMetaData(MachOObjectFile *O, bool verbose); 1915 1916 // ProcessMachO() is passed a single opened Mach-O file, which may be an 1917 // archive member and or in a slice of a universal file. It prints the 1918 // the file name and header info and then processes it according to the 1919 // command line options. 1920 static void ProcessMachO(StringRef Name, MachOObjectFile *MachOOF, 1921 StringRef ArchiveMemberName = StringRef(), 1922 StringRef ArchitectureName = StringRef()) { 1923 // If we are doing some processing here on the Mach-O file print the header 1924 // info. And don't print it otherwise like in the case of printing the 1925 // UniversalHeaders or ArchiveHeaders. 1926 if (Disassemble || Relocations || PrivateHeaders || ExportsTrie || Rebase || 1927 Bind || SymbolTable || LazyBind || WeakBind || IndirectSymbols || 1928 DataInCode || LinkOptHints || DylibsUsed || DylibId || ObjcMetaData || 1929 (!FilterSections.empty())) { 1930 if (!NoLeadingHeaders) { 1931 outs() << Name; 1932 if (!ArchiveMemberName.empty()) 1933 outs() << '(' << ArchiveMemberName << ')'; 1934 if (!ArchitectureName.empty()) 1935 outs() << " (architecture " << ArchitectureName << ")"; 1936 outs() << ":\n"; 1937 } 1938 } 1939 // To use the report_error() form with an ArchiveName and FileName set 1940 // these up based on what is passed for Name and ArchiveMemberName. 1941 StringRef ArchiveName; 1942 StringRef FileName; 1943 if (!ArchiveMemberName.empty()) { 1944 ArchiveName = Name; 1945 FileName = ArchiveMemberName; 1946 } else { 1947 ArchiveName = StringRef(); 1948 FileName = Name; 1949 } 1950 1951 // If we need the symbol table to do the operation then check it here to 1952 // produce a good error message as to where the Mach-O file comes from in 1953 // the error message. 1954 if (Disassemble || IndirectSymbols || !FilterSections.empty() || UnwindInfo) 1955 if (Error Err = MachOOF->checkSymbolTable()) 1956 reportError(std::move(Err), FileName, ArchiveName, ArchitectureName); 1957 1958 if (DisassembleAll) { 1959 for (const SectionRef &Section : MachOOF->sections()) { 1960 StringRef SectName; 1961 if (Expected<StringRef> NameOrErr = Section.getName()) 1962 SectName = *NameOrErr; 1963 else 1964 consumeError(NameOrErr.takeError()); 1965 1966 if (SectName.equals("__text")) { 1967 DataRefImpl Ref = Section.getRawDataRefImpl(); 1968 StringRef SegName = MachOOF->getSectionFinalSegmentName(Ref); 1969 DisassembleMachO(FileName, MachOOF, SegName, SectName); 1970 } 1971 } 1972 } 1973 else if (Disassemble) { 1974 if (MachOOF->getHeader().filetype == MachO::MH_KEXT_BUNDLE && 1975 MachOOF->getHeader().cputype == MachO::CPU_TYPE_ARM64) 1976 DisassembleMachO(FileName, MachOOF, "__TEXT_EXEC", "__text"); 1977 else 1978 DisassembleMachO(FileName, MachOOF, "__TEXT", "__text"); 1979 } 1980 if (IndirectSymbols) 1981 PrintIndirectSymbols(MachOOF, !NonVerbose); 1982 if (DataInCode) 1983 PrintDataInCodeTable(MachOOF, !NonVerbose); 1984 if (LinkOptHints) 1985 PrintLinkOptHints(MachOOF); 1986 if (Relocations) 1987 PrintRelocations(MachOOF, !NonVerbose); 1988 if (SectionHeaders) 1989 printSectionHeaders(MachOOF); 1990 if (SectionContents) 1991 printSectionContents(MachOOF); 1992 if (!FilterSections.empty()) 1993 DumpSectionContents(FileName, MachOOF, !NonVerbose); 1994 if (InfoPlist) 1995 DumpInfoPlistSectionContents(FileName, MachOOF); 1996 if (DylibsUsed) 1997 PrintDylibs(MachOOF, false); 1998 if (DylibId) 1999 PrintDylibs(MachOOF, true); 2000 if (SymbolTable) 2001 printSymbolTable(MachOOF, ArchiveName, ArchitectureName); 2002 if (UnwindInfo) 2003 printMachOUnwindInfo(MachOOF); 2004 if (PrivateHeaders) { 2005 printMachOFileHeader(MachOOF); 2006 printMachOLoadCommands(MachOOF); 2007 } 2008 if (FirstPrivateHeader) 2009 printMachOFileHeader(MachOOF); 2010 if (ObjcMetaData) 2011 printObjcMetaData(MachOOF, !NonVerbose); 2012 if (ExportsTrie) 2013 printExportsTrie(MachOOF); 2014 if (Rebase) 2015 printRebaseTable(MachOOF); 2016 if (Bind) 2017 printBindTable(MachOOF); 2018 if (LazyBind) 2019 printLazyBindTable(MachOOF); 2020 if (WeakBind) 2021 printWeakBindTable(MachOOF); 2022 2023 if (DwarfDumpType != DIDT_Null) { 2024 std::unique_ptr<DIContext> DICtx = DWARFContext::create(*MachOOF); 2025 // Dump the complete DWARF structure. 2026 DIDumpOptions DumpOpts; 2027 DumpOpts.DumpType = DwarfDumpType; 2028 DICtx->dump(outs(), DumpOpts); 2029 } 2030 } 2031 2032 // printUnknownCPUType() helps print_fat_headers for unknown CPU's. 2033 static void printUnknownCPUType(uint32_t cputype, uint32_t cpusubtype) { 2034 outs() << " cputype (" << cputype << ")\n"; 2035 outs() << " cpusubtype (" << cpusubtype << ")\n"; 2036 } 2037 2038 // printCPUType() helps print_fat_headers by printing the cputype and 2039 // pusubtype (symbolically for the one's it knows about). 2040 static void printCPUType(uint32_t cputype, uint32_t cpusubtype) { 2041 switch (cputype) { 2042 case MachO::CPU_TYPE_I386: 2043 switch (cpusubtype) { 2044 case MachO::CPU_SUBTYPE_I386_ALL: 2045 outs() << " cputype CPU_TYPE_I386\n"; 2046 outs() << " cpusubtype CPU_SUBTYPE_I386_ALL\n"; 2047 break; 2048 default: 2049 printUnknownCPUType(cputype, cpusubtype); 2050 break; 2051 } 2052 break; 2053 case MachO::CPU_TYPE_X86_64: 2054 switch (cpusubtype) { 2055 case MachO::CPU_SUBTYPE_X86_64_ALL: 2056 outs() << " cputype CPU_TYPE_X86_64\n"; 2057 outs() << " cpusubtype CPU_SUBTYPE_X86_64_ALL\n"; 2058 break; 2059 case MachO::CPU_SUBTYPE_X86_64_H: 2060 outs() << " cputype CPU_TYPE_X86_64\n"; 2061 outs() << " cpusubtype CPU_SUBTYPE_X86_64_H\n"; 2062 break; 2063 default: 2064 printUnknownCPUType(cputype, cpusubtype); 2065 break; 2066 } 2067 break; 2068 case MachO::CPU_TYPE_ARM: 2069 switch (cpusubtype) { 2070 case MachO::CPU_SUBTYPE_ARM_ALL: 2071 outs() << " cputype CPU_TYPE_ARM\n"; 2072 outs() << " cpusubtype CPU_SUBTYPE_ARM_ALL\n"; 2073 break; 2074 case MachO::CPU_SUBTYPE_ARM_V4T: 2075 outs() << " cputype CPU_TYPE_ARM\n"; 2076 outs() << " cpusubtype CPU_SUBTYPE_ARM_V4T\n"; 2077 break; 2078 case MachO::CPU_SUBTYPE_ARM_V5TEJ: 2079 outs() << " cputype CPU_TYPE_ARM\n"; 2080 outs() << " cpusubtype CPU_SUBTYPE_ARM_V5TEJ\n"; 2081 break; 2082 case MachO::CPU_SUBTYPE_ARM_XSCALE: 2083 outs() << " cputype CPU_TYPE_ARM\n"; 2084 outs() << " cpusubtype CPU_SUBTYPE_ARM_XSCALE\n"; 2085 break; 2086 case MachO::CPU_SUBTYPE_ARM_V6: 2087 outs() << " cputype CPU_TYPE_ARM\n"; 2088 outs() << " cpusubtype CPU_SUBTYPE_ARM_V6\n"; 2089 break; 2090 case MachO::CPU_SUBTYPE_ARM_V6M: 2091 outs() << " cputype CPU_TYPE_ARM\n"; 2092 outs() << " cpusubtype CPU_SUBTYPE_ARM_V6M\n"; 2093 break; 2094 case MachO::CPU_SUBTYPE_ARM_V7: 2095 outs() << " cputype CPU_TYPE_ARM\n"; 2096 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7\n"; 2097 break; 2098 case MachO::CPU_SUBTYPE_ARM_V7EM: 2099 outs() << " cputype CPU_TYPE_ARM\n"; 2100 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7EM\n"; 2101 break; 2102 case MachO::CPU_SUBTYPE_ARM_V7K: 2103 outs() << " cputype CPU_TYPE_ARM\n"; 2104 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7K\n"; 2105 break; 2106 case MachO::CPU_SUBTYPE_ARM_V7M: 2107 outs() << " cputype CPU_TYPE_ARM\n"; 2108 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7M\n"; 2109 break; 2110 case MachO::CPU_SUBTYPE_ARM_V7S: 2111 outs() << " cputype CPU_TYPE_ARM\n"; 2112 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7S\n"; 2113 break; 2114 default: 2115 printUnknownCPUType(cputype, cpusubtype); 2116 break; 2117 } 2118 break; 2119 case MachO::CPU_TYPE_ARM64: 2120 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) { 2121 case MachO::CPU_SUBTYPE_ARM64_ALL: 2122 outs() << " cputype CPU_TYPE_ARM64\n"; 2123 outs() << " cpusubtype CPU_SUBTYPE_ARM64_ALL\n"; 2124 break; 2125 case MachO::CPU_SUBTYPE_ARM64E: 2126 outs() << " cputype CPU_TYPE_ARM64\n"; 2127 outs() << " cpusubtype CPU_SUBTYPE_ARM64E\n"; 2128 break; 2129 default: 2130 printUnknownCPUType(cputype, cpusubtype); 2131 break; 2132 } 2133 break; 2134 case MachO::CPU_TYPE_ARM64_32: 2135 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) { 2136 case MachO::CPU_SUBTYPE_ARM64_32_V8: 2137 outs() << " cputype CPU_TYPE_ARM64_32\n"; 2138 outs() << " cpusubtype CPU_SUBTYPE_ARM64_32_V8\n"; 2139 break; 2140 default: 2141 printUnknownCPUType(cputype, cpusubtype); 2142 break; 2143 } 2144 break; 2145 default: 2146 printUnknownCPUType(cputype, cpusubtype); 2147 break; 2148 } 2149 } 2150 2151 static void printMachOUniversalHeaders(const object::MachOUniversalBinary *UB, 2152 bool verbose) { 2153 outs() << "Fat headers\n"; 2154 if (verbose) { 2155 if (UB->getMagic() == MachO::FAT_MAGIC) 2156 outs() << "fat_magic FAT_MAGIC\n"; 2157 else // UB->getMagic() == MachO::FAT_MAGIC_64 2158 outs() << "fat_magic FAT_MAGIC_64\n"; 2159 } else 2160 outs() << "fat_magic " << format("0x%" PRIx32, MachO::FAT_MAGIC) << "\n"; 2161 2162 uint32_t nfat_arch = UB->getNumberOfObjects(); 2163 StringRef Buf = UB->getData(); 2164 uint64_t size = Buf.size(); 2165 uint64_t big_size = sizeof(struct MachO::fat_header) + 2166 nfat_arch * sizeof(struct MachO::fat_arch); 2167 outs() << "nfat_arch " << UB->getNumberOfObjects(); 2168 if (nfat_arch == 0) 2169 outs() << " (malformed, contains zero architecture types)\n"; 2170 else if (big_size > size) 2171 outs() << " (malformed, architectures past end of file)\n"; 2172 else 2173 outs() << "\n"; 2174 2175 for (uint32_t i = 0; i < nfat_arch; ++i) { 2176 MachOUniversalBinary::ObjectForArch OFA(UB, i); 2177 uint32_t cputype = OFA.getCPUType(); 2178 uint32_t cpusubtype = OFA.getCPUSubType(); 2179 outs() << "architecture "; 2180 for (uint32_t j = 0; i != 0 && j <= i - 1; j++) { 2181 MachOUniversalBinary::ObjectForArch other_OFA(UB, j); 2182 uint32_t other_cputype = other_OFA.getCPUType(); 2183 uint32_t other_cpusubtype = other_OFA.getCPUSubType(); 2184 if (cputype != 0 && cpusubtype != 0 && cputype == other_cputype && 2185 (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) == 2186 (other_cpusubtype & ~MachO::CPU_SUBTYPE_MASK)) { 2187 outs() << "(illegal duplicate architecture) "; 2188 break; 2189 } 2190 } 2191 if (verbose) { 2192 outs() << OFA.getArchFlagName() << "\n"; 2193 printCPUType(cputype, cpusubtype & ~MachO::CPU_SUBTYPE_MASK); 2194 } else { 2195 outs() << i << "\n"; 2196 outs() << " cputype " << cputype << "\n"; 2197 outs() << " cpusubtype " << (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) 2198 << "\n"; 2199 } 2200 if (verbose && 2201 (cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64) 2202 outs() << " capabilities CPU_SUBTYPE_LIB64\n"; 2203 else 2204 outs() << " capabilities " 2205 << format("0x%" PRIx32, 2206 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24) << "\n"; 2207 outs() << " offset " << OFA.getOffset(); 2208 if (OFA.getOffset() > size) 2209 outs() << " (past end of file)"; 2210 if (OFA.getOffset() % (1ull << OFA.getAlign()) != 0) 2211 outs() << " (not aligned on it's alignment (2^" << OFA.getAlign() << ")"; 2212 outs() << "\n"; 2213 outs() << " size " << OFA.getSize(); 2214 big_size = OFA.getOffset() + OFA.getSize(); 2215 if (big_size > size) 2216 outs() << " (past end of file)"; 2217 outs() << "\n"; 2218 outs() << " align 2^" << OFA.getAlign() << " (" << (1 << OFA.getAlign()) 2219 << ")\n"; 2220 } 2221 } 2222 2223 static void printArchiveChild(StringRef Filename, const Archive::Child &C, 2224 size_t ChildIndex, bool verbose, 2225 bool print_offset, 2226 StringRef ArchitectureName = StringRef()) { 2227 if (print_offset) 2228 outs() << C.getChildOffset() << "\t"; 2229 sys::fs::perms Mode = 2230 unwrapOrError(C.getAccessMode(), getFileNameForError(C, ChildIndex), 2231 Filename, ArchitectureName); 2232 if (verbose) { 2233 // FIXME: this first dash, "-", is for (Mode & S_IFMT) == S_IFREG. 2234 // But there is nothing in sys::fs::perms for S_IFMT or S_IFREG. 2235 outs() << "-"; 2236 outs() << ((Mode & sys::fs::owner_read) ? "r" : "-"); 2237 outs() << ((Mode & sys::fs::owner_write) ? "w" : "-"); 2238 outs() << ((Mode & sys::fs::owner_exe) ? "x" : "-"); 2239 outs() << ((Mode & sys::fs::group_read) ? "r" : "-"); 2240 outs() << ((Mode & sys::fs::group_write) ? "w" : "-"); 2241 outs() << ((Mode & sys::fs::group_exe) ? "x" : "-"); 2242 outs() << ((Mode & sys::fs::others_read) ? "r" : "-"); 2243 outs() << ((Mode & sys::fs::others_write) ? "w" : "-"); 2244 outs() << ((Mode & sys::fs::others_exe) ? "x" : "-"); 2245 } else { 2246 outs() << format("0%o ", Mode); 2247 } 2248 2249 outs() << format("%3d/%-3d %5" PRId64 " ", 2250 unwrapOrError(C.getUID(), getFileNameForError(C, ChildIndex), 2251 Filename, ArchitectureName), 2252 unwrapOrError(C.getGID(), getFileNameForError(C, ChildIndex), 2253 Filename, ArchitectureName), 2254 unwrapOrError(C.getRawSize(), 2255 getFileNameForError(C, ChildIndex), Filename, 2256 ArchitectureName)); 2257 2258 StringRef RawLastModified = C.getRawLastModified(); 2259 if (verbose) { 2260 unsigned Seconds; 2261 if (RawLastModified.getAsInteger(10, Seconds)) 2262 outs() << "(date: \"" << RawLastModified 2263 << "\" contains non-decimal chars) "; 2264 else { 2265 // Since cime(3) returns a 26 character string of the form: 2266 // "Sun Sep 16 01:03:52 1973\n\0" 2267 // just print 24 characters. 2268 time_t t = Seconds; 2269 outs() << format("%.24s ", ctime(&t)); 2270 } 2271 } else { 2272 outs() << RawLastModified << " "; 2273 } 2274 2275 if (verbose) { 2276 Expected<StringRef> NameOrErr = C.getName(); 2277 if (!NameOrErr) { 2278 consumeError(NameOrErr.takeError()); 2279 outs() << unwrapOrError(C.getRawName(), 2280 getFileNameForError(C, ChildIndex), Filename, 2281 ArchitectureName) 2282 << "\n"; 2283 } else { 2284 StringRef Name = NameOrErr.get(); 2285 outs() << Name << "\n"; 2286 } 2287 } else { 2288 outs() << unwrapOrError(C.getRawName(), getFileNameForError(C, ChildIndex), 2289 Filename, ArchitectureName) 2290 << "\n"; 2291 } 2292 } 2293 2294 static void printArchiveHeaders(StringRef Filename, Archive *A, bool verbose, 2295 bool print_offset, 2296 StringRef ArchitectureName = StringRef()) { 2297 Error Err = Error::success(); 2298 size_t I = 0; 2299 for (const auto &C : A->children(Err, false)) 2300 printArchiveChild(Filename, C, I++, verbose, print_offset, 2301 ArchitectureName); 2302 2303 if (Err) 2304 reportError(std::move(Err), Filename, "", ArchitectureName); 2305 } 2306 2307 static bool ValidateArchFlags() { 2308 // Check for -arch all and verifiy the -arch flags are valid. 2309 for (unsigned i = 0; i < ArchFlags.size(); ++i) { 2310 if (ArchFlags[i] == "all") { 2311 ArchAll = true; 2312 } else { 2313 if (!MachOObjectFile::isValidArch(ArchFlags[i])) { 2314 WithColor::error(errs(), "llvm-objdump") 2315 << "unknown architecture named '" + ArchFlags[i] + 2316 "'for the -arch option\n"; 2317 return false; 2318 } 2319 } 2320 } 2321 return true; 2322 } 2323 2324 // ParseInputMachO() parses the named Mach-O file in Filename and handles the 2325 // -arch flags selecting just those slices as specified by them and also parses 2326 // archive files. Then for each individual Mach-O file ProcessMachO() is 2327 // called to process the file based on the command line options. 2328 void parseInputMachO(StringRef Filename) { 2329 if (!ValidateArchFlags()) 2330 return; 2331 2332 // Attempt to open the binary. 2333 Expected<OwningBinary<Binary>> BinaryOrErr = createBinary(Filename); 2334 if (!BinaryOrErr) { 2335 if (Error E = isNotObjectErrorInvalidFileType(BinaryOrErr.takeError())) 2336 reportError(std::move(E), Filename); 2337 else 2338 outs() << Filename << ": is not an object file\n"; 2339 return; 2340 } 2341 Binary &Bin = *BinaryOrErr.get().getBinary(); 2342 2343 if (Archive *A = dyn_cast<Archive>(&Bin)) { 2344 outs() << "Archive : " << Filename << "\n"; 2345 if (ArchiveHeaders) 2346 printArchiveHeaders(Filename, A, !NonVerbose, ArchiveMemberOffsets); 2347 2348 Error Err = Error::success(); 2349 unsigned I = -1; 2350 for (auto &C : A->children(Err)) { 2351 ++I; 2352 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary(); 2353 if (!ChildOrErr) { 2354 if (Error E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError())) 2355 reportError(std::move(E), getFileNameForError(C, I), Filename); 2356 continue; 2357 } 2358 if (MachOObjectFile *O = dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) { 2359 if (!checkMachOAndArchFlags(O, Filename)) 2360 return; 2361 ProcessMachO(Filename, O, O->getFileName()); 2362 } 2363 } 2364 if (Err) 2365 reportError(std::move(Err), Filename); 2366 return; 2367 } 2368 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin)) { 2369 parseInputMachO(UB); 2370 return; 2371 } 2372 if (ObjectFile *O = dyn_cast<ObjectFile>(&Bin)) { 2373 if (!checkMachOAndArchFlags(O, Filename)) 2374 return; 2375 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&*O)) 2376 ProcessMachO(Filename, MachOOF); 2377 else 2378 WithColor::error(errs(), "llvm-objdump") 2379 << Filename << "': " 2380 << "object is not a Mach-O file type.\n"; 2381 return; 2382 } 2383 llvm_unreachable("Input object can't be invalid at this point"); 2384 } 2385 2386 void parseInputMachO(MachOUniversalBinary *UB) { 2387 if (!ValidateArchFlags()) 2388 return; 2389 2390 auto Filename = UB->getFileName(); 2391 2392 if (UniversalHeaders) 2393 printMachOUniversalHeaders(UB, !NonVerbose); 2394 2395 // If we have a list of architecture flags specified dump only those. 2396 if (!ArchAll && !ArchFlags.empty()) { 2397 // Look for a slice in the universal binary that matches each ArchFlag. 2398 bool ArchFound; 2399 for (unsigned i = 0; i < ArchFlags.size(); ++i) { 2400 ArchFound = false; 2401 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(), 2402 E = UB->end_objects(); 2403 I != E; ++I) { 2404 if (ArchFlags[i] == I->getArchFlagName()) { 2405 ArchFound = true; 2406 Expected<std::unique_ptr<ObjectFile>> ObjOrErr = 2407 I->getAsObjectFile(); 2408 std::string ArchitectureName = ""; 2409 if (ArchFlags.size() > 1) 2410 ArchitectureName = I->getArchFlagName(); 2411 if (ObjOrErr) { 2412 ObjectFile &O = *ObjOrErr.get(); 2413 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O)) 2414 ProcessMachO(Filename, MachOOF, "", ArchitectureName); 2415 } else if (Error E = isNotObjectErrorInvalidFileType( 2416 ObjOrErr.takeError())) { 2417 reportError(std::move(E), "", Filename, ArchitectureName); 2418 continue; 2419 } else if (Expected<std::unique_ptr<Archive>> AOrErr = 2420 I->getAsArchive()) { 2421 std::unique_ptr<Archive> &A = *AOrErr; 2422 outs() << "Archive : " << Filename; 2423 if (!ArchitectureName.empty()) 2424 outs() << " (architecture " << ArchitectureName << ")"; 2425 outs() << "\n"; 2426 if (ArchiveHeaders) 2427 printArchiveHeaders(Filename, A.get(), !NonVerbose, 2428 ArchiveMemberOffsets, ArchitectureName); 2429 Error Err = Error::success(); 2430 unsigned I = -1; 2431 for (auto &C : A->children(Err)) { 2432 ++I; 2433 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary(); 2434 if (!ChildOrErr) { 2435 if (Error E = 2436 isNotObjectErrorInvalidFileType(ChildOrErr.takeError())) 2437 reportError(std::move(E), getFileNameForError(C, I), Filename, 2438 ArchitectureName); 2439 continue; 2440 } 2441 if (MachOObjectFile *O = 2442 dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) 2443 ProcessMachO(Filename, O, O->getFileName(), ArchitectureName); 2444 } 2445 if (Err) 2446 reportError(std::move(Err), Filename); 2447 } else { 2448 consumeError(AOrErr.takeError()); 2449 reportError(Filename, 2450 "Mach-O universal file for architecture " + 2451 StringRef(I->getArchFlagName()) + 2452 " is not a Mach-O file or an archive file"); 2453 } 2454 } 2455 } 2456 if (!ArchFound) { 2457 WithColor::error(errs(), "llvm-objdump") 2458 << "file: " + Filename + " does not contain " 2459 << "architecture: " + ArchFlags[i] + "\n"; 2460 return; 2461 } 2462 } 2463 return; 2464 } 2465 // No architecture flags were specified so if this contains a slice that 2466 // matches the host architecture dump only that. 2467 if (!ArchAll) { 2468 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(), 2469 E = UB->end_objects(); 2470 I != E; ++I) { 2471 if (MachOObjectFile::getHostArch().getArchName() == 2472 I->getArchFlagName()) { 2473 Expected<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile(); 2474 std::string ArchiveName; 2475 ArchiveName.clear(); 2476 if (ObjOrErr) { 2477 ObjectFile &O = *ObjOrErr.get(); 2478 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O)) 2479 ProcessMachO(Filename, MachOOF); 2480 } else if (Error E = 2481 isNotObjectErrorInvalidFileType(ObjOrErr.takeError())) { 2482 reportError(std::move(E), Filename); 2483 } else if (Expected<std::unique_ptr<Archive>> AOrErr = 2484 I->getAsArchive()) { 2485 std::unique_ptr<Archive> &A = *AOrErr; 2486 outs() << "Archive : " << Filename << "\n"; 2487 if (ArchiveHeaders) 2488 printArchiveHeaders(Filename, A.get(), !NonVerbose, 2489 ArchiveMemberOffsets); 2490 Error Err = Error::success(); 2491 unsigned I = -1; 2492 for (auto &C : A->children(Err)) { 2493 ++I; 2494 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary(); 2495 if (!ChildOrErr) { 2496 if (Error E = 2497 isNotObjectErrorInvalidFileType(ChildOrErr.takeError())) 2498 reportError(std::move(E), getFileNameForError(C, I), Filename); 2499 continue; 2500 } 2501 if (MachOObjectFile *O = 2502 dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) 2503 ProcessMachO(Filename, O, O->getFileName()); 2504 } 2505 if (Err) 2506 reportError(std::move(Err), Filename); 2507 } else { 2508 consumeError(AOrErr.takeError()); 2509 reportError(Filename, "Mach-O universal file for architecture " + 2510 StringRef(I->getArchFlagName()) + 2511 " is not a Mach-O file or an archive file"); 2512 } 2513 return; 2514 } 2515 } 2516 } 2517 // Either all architectures have been specified or none have been specified 2518 // and this does not contain the host architecture so dump all the slices. 2519 bool moreThanOneArch = UB->getNumberOfObjects() > 1; 2520 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(), 2521 E = UB->end_objects(); 2522 I != E; ++I) { 2523 Expected<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile(); 2524 std::string ArchitectureName = ""; 2525 if (moreThanOneArch) 2526 ArchitectureName = I->getArchFlagName(); 2527 if (ObjOrErr) { 2528 ObjectFile &Obj = *ObjOrErr.get(); 2529 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&Obj)) 2530 ProcessMachO(Filename, MachOOF, "", ArchitectureName); 2531 } else if (Error E = 2532 isNotObjectErrorInvalidFileType(ObjOrErr.takeError())) { 2533 reportError(std::move(E), Filename, "", ArchitectureName); 2534 } else if (Expected<std::unique_ptr<Archive>> AOrErr = I->getAsArchive()) { 2535 std::unique_ptr<Archive> &A = *AOrErr; 2536 outs() << "Archive : " << Filename; 2537 if (!ArchitectureName.empty()) 2538 outs() << " (architecture " << ArchitectureName << ")"; 2539 outs() << "\n"; 2540 if (ArchiveHeaders) 2541 printArchiveHeaders(Filename, A.get(), !NonVerbose, 2542 ArchiveMemberOffsets, ArchitectureName); 2543 Error Err = Error::success(); 2544 unsigned I = -1; 2545 for (auto &C : A->children(Err)) { 2546 ++I; 2547 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary(); 2548 if (!ChildOrErr) { 2549 if (Error E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError())) 2550 reportError(std::move(E), getFileNameForError(C, I), Filename, 2551 ArchitectureName); 2552 continue; 2553 } 2554 if (MachOObjectFile *O = 2555 dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) { 2556 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(O)) 2557 ProcessMachO(Filename, MachOOF, MachOOF->getFileName(), 2558 ArchitectureName); 2559 } 2560 } 2561 if (Err) 2562 reportError(std::move(Err), Filename); 2563 } else { 2564 consumeError(AOrErr.takeError()); 2565 reportError(Filename, "Mach-O universal file for architecture " + 2566 StringRef(I->getArchFlagName()) + 2567 " is not a Mach-O file or an archive file"); 2568 } 2569 } 2570 } 2571 2572 // The block of info used by the Symbolizer call backs. 2573 struct DisassembleInfo { 2574 DisassembleInfo(MachOObjectFile *O, SymbolAddressMap *AddrMap, 2575 std::vector<SectionRef> *Sections, bool verbose) 2576 : verbose(verbose), O(O), AddrMap(AddrMap), Sections(Sections) {} 2577 bool verbose; 2578 MachOObjectFile *O; 2579 SectionRef S; 2580 SymbolAddressMap *AddrMap; 2581 std::vector<SectionRef> *Sections; 2582 const char *class_name = nullptr; 2583 const char *selector_name = nullptr; 2584 std::unique_ptr<char[]> method = nullptr; 2585 char *demangled_name = nullptr; 2586 uint64_t adrp_addr = 0; 2587 uint32_t adrp_inst = 0; 2588 std::unique_ptr<SymbolAddressMap> bindtable; 2589 uint32_t depth = 0; 2590 }; 2591 2592 // SymbolizerGetOpInfo() is the operand information call back function. 2593 // This is called to get the symbolic information for operand(s) of an 2594 // instruction when it is being done. This routine does this from 2595 // the relocation information, symbol table, etc. That block of information 2596 // is a pointer to the struct DisassembleInfo that was passed when the 2597 // disassembler context was created and passed to back to here when 2598 // called back by the disassembler for instruction operands that could have 2599 // relocation information. The address of the instruction containing operand is 2600 // at the Pc parameter. The immediate value the operand has is passed in 2601 // op_info->Value and is at Offset past the start of the instruction and has a 2602 // byte Size of 1, 2 or 4. The symbolc information is returned in TagBuf is the 2603 // LLVMOpInfo1 struct defined in the header "llvm-c/Disassembler.h" as symbol 2604 // names and addends of the symbolic expression to add for the operand. The 2605 // value of TagType is currently 1 (for the LLVMOpInfo1 struct). If symbolic 2606 // information is returned then this function returns 1 else it returns 0. 2607 static int SymbolizerGetOpInfo(void *DisInfo, uint64_t Pc, uint64_t Offset, 2608 uint64_t Size, int TagType, void *TagBuf) { 2609 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo; 2610 struct LLVMOpInfo1 *op_info = (struct LLVMOpInfo1 *)TagBuf; 2611 uint64_t value = op_info->Value; 2612 2613 // Make sure all fields returned are zero if we don't set them. 2614 memset((void *)op_info, '\0', sizeof(struct LLVMOpInfo1)); 2615 op_info->Value = value; 2616 2617 // If the TagType is not the value 1 which it code knows about or if no 2618 // verbose symbolic information is wanted then just return 0, indicating no 2619 // information is being returned. 2620 if (TagType != 1 || !info->verbose) 2621 return 0; 2622 2623 unsigned int Arch = info->O->getArch(); 2624 if (Arch == Triple::x86) { 2625 if (Size != 1 && Size != 2 && Size != 4 && Size != 0) 2626 return 0; 2627 if (info->O->getHeader().filetype != MachO::MH_OBJECT) { 2628 // TODO: 2629 // Search the external relocation entries of a fully linked image 2630 // (if any) for an entry that matches this segment offset. 2631 // uint32_t seg_offset = (Pc + Offset); 2632 return 0; 2633 } 2634 // In MH_OBJECT filetypes search the section's relocation entries (if any) 2635 // for an entry for this section offset. 2636 uint32_t sect_addr = info->S.getAddress(); 2637 uint32_t sect_offset = (Pc + Offset) - sect_addr; 2638 bool reloc_found = false; 2639 DataRefImpl Rel; 2640 MachO::any_relocation_info RE; 2641 bool isExtern = false; 2642 SymbolRef Symbol; 2643 bool r_scattered = false; 2644 uint32_t r_value, pair_r_value, r_type; 2645 for (const RelocationRef &Reloc : info->S.relocations()) { 2646 uint64_t RelocOffset = Reloc.getOffset(); 2647 if (RelocOffset == sect_offset) { 2648 Rel = Reloc.getRawDataRefImpl(); 2649 RE = info->O->getRelocation(Rel); 2650 r_type = info->O->getAnyRelocationType(RE); 2651 r_scattered = info->O->isRelocationScattered(RE); 2652 if (r_scattered) { 2653 r_value = info->O->getScatteredRelocationValue(RE); 2654 if (r_type == MachO::GENERIC_RELOC_SECTDIFF || 2655 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF) { 2656 DataRefImpl RelNext = Rel; 2657 info->O->moveRelocationNext(RelNext); 2658 MachO::any_relocation_info RENext; 2659 RENext = info->O->getRelocation(RelNext); 2660 if (info->O->isRelocationScattered(RENext)) 2661 pair_r_value = info->O->getScatteredRelocationValue(RENext); 2662 else 2663 return 0; 2664 } 2665 } else { 2666 isExtern = info->O->getPlainRelocationExternal(RE); 2667 if (isExtern) { 2668 symbol_iterator RelocSym = Reloc.getSymbol(); 2669 Symbol = *RelocSym; 2670 } 2671 } 2672 reloc_found = true; 2673 break; 2674 } 2675 } 2676 if (reloc_found && isExtern) { 2677 op_info->AddSymbol.Present = 1; 2678 op_info->AddSymbol.Name = 2679 unwrapOrError(Symbol.getName(), info->O->getFileName()).data(); 2680 // For i386 extern relocation entries the value in the instruction is 2681 // the offset from the symbol, and value is already set in op_info->Value. 2682 return 1; 2683 } 2684 if (reloc_found && (r_type == MachO::GENERIC_RELOC_SECTDIFF || 2685 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF)) { 2686 const char *add = GuessSymbolName(r_value, info->AddrMap); 2687 const char *sub = GuessSymbolName(pair_r_value, info->AddrMap); 2688 uint32_t offset = value - (r_value - pair_r_value); 2689 op_info->AddSymbol.Present = 1; 2690 if (add != nullptr) 2691 op_info->AddSymbol.Name = add; 2692 else 2693 op_info->AddSymbol.Value = r_value; 2694 op_info->SubtractSymbol.Present = 1; 2695 if (sub != nullptr) 2696 op_info->SubtractSymbol.Name = sub; 2697 else 2698 op_info->SubtractSymbol.Value = pair_r_value; 2699 op_info->Value = offset; 2700 return 1; 2701 } 2702 return 0; 2703 } 2704 if (Arch == Triple::x86_64) { 2705 if (Size != 1 && Size != 2 && Size != 4 && Size != 0) 2706 return 0; 2707 // For non MH_OBJECT types, like MH_KEXT_BUNDLE, Search the external 2708 // relocation entries of a linked image (if any) for an entry that matches 2709 // this segment offset. 2710 if (info->O->getHeader().filetype != MachO::MH_OBJECT) { 2711 uint64_t seg_offset = Pc + Offset; 2712 bool reloc_found = false; 2713 DataRefImpl Rel; 2714 MachO::any_relocation_info RE; 2715 bool isExtern = false; 2716 SymbolRef Symbol; 2717 for (const RelocationRef &Reloc : info->O->external_relocations()) { 2718 uint64_t RelocOffset = Reloc.getOffset(); 2719 if (RelocOffset == seg_offset) { 2720 Rel = Reloc.getRawDataRefImpl(); 2721 RE = info->O->getRelocation(Rel); 2722 // external relocation entries should always be external. 2723 isExtern = info->O->getPlainRelocationExternal(RE); 2724 if (isExtern) { 2725 symbol_iterator RelocSym = Reloc.getSymbol(); 2726 Symbol = *RelocSym; 2727 } 2728 reloc_found = true; 2729 break; 2730 } 2731 } 2732 if (reloc_found && isExtern) { 2733 // The Value passed in will be adjusted by the Pc if the instruction 2734 // adds the Pc. But for x86_64 external relocation entries the Value 2735 // is the offset from the external symbol. 2736 if (info->O->getAnyRelocationPCRel(RE)) 2737 op_info->Value -= Pc + Offset + Size; 2738 const char *name = 2739 unwrapOrError(Symbol.getName(), info->O->getFileName()).data(); 2740 op_info->AddSymbol.Present = 1; 2741 op_info->AddSymbol.Name = name; 2742 return 1; 2743 } 2744 return 0; 2745 } 2746 // In MH_OBJECT filetypes search the section's relocation entries (if any) 2747 // for an entry for this section offset. 2748 uint64_t sect_addr = info->S.getAddress(); 2749 uint64_t sect_offset = (Pc + Offset) - sect_addr; 2750 bool reloc_found = false; 2751 DataRefImpl Rel; 2752 MachO::any_relocation_info RE; 2753 bool isExtern = false; 2754 SymbolRef Symbol; 2755 for (const RelocationRef &Reloc : info->S.relocations()) { 2756 uint64_t RelocOffset = Reloc.getOffset(); 2757 if (RelocOffset == sect_offset) { 2758 Rel = Reloc.getRawDataRefImpl(); 2759 RE = info->O->getRelocation(Rel); 2760 // NOTE: Scattered relocations don't exist on x86_64. 2761 isExtern = info->O->getPlainRelocationExternal(RE); 2762 if (isExtern) { 2763 symbol_iterator RelocSym = Reloc.getSymbol(); 2764 Symbol = *RelocSym; 2765 } 2766 reloc_found = true; 2767 break; 2768 } 2769 } 2770 if (reloc_found && isExtern) { 2771 // The Value passed in will be adjusted by the Pc if the instruction 2772 // adds the Pc. But for x86_64 external relocation entries the Value 2773 // is the offset from the external symbol. 2774 if (info->O->getAnyRelocationPCRel(RE)) 2775 op_info->Value -= Pc + Offset + Size; 2776 const char *name = 2777 unwrapOrError(Symbol.getName(), info->O->getFileName()).data(); 2778 unsigned Type = info->O->getAnyRelocationType(RE); 2779 if (Type == MachO::X86_64_RELOC_SUBTRACTOR) { 2780 DataRefImpl RelNext = Rel; 2781 info->O->moveRelocationNext(RelNext); 2782 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext); 2783 unsigned TypeNext = info->O->getAnyRelocationType(RENext); 2784 bool isExternNext = info->O->getPlainRelocationExternal(RENext); 2785 unsigned SymbolNum = info->O->getPlainRelocationSymbolNum(RENext); 2786 if (TypeNext == MachO::X86_64_RELOC_UNSIGNED && isExternNext) { 2787 op_info->SubtractSymbol.Present = 1; 2788 op_info->SubtractSymbol.Name = name; 2789 symbol_iterator RelocSymNext = info->O->getSymbolByIndex(SymbolNum); 2790 Symbol = *RelocSymNext; 2791 name = unwrapOrError(Symbol.getName(), info->O->getFileName()).data(); 2792 } 2793 } 2794 // TODO: add the VariantKinds to op_info->VariantKind for relocation types 2795 // like: X86_64_RELOC_TLV, X86_64_RELOC_GOT_LOAD and X86_64_RELOC_GOT. 2796 op_info->AddSymbol.Present = 1; 2797 op_info->AddSymbol.Name = name; 2798 return 1; 2799 } 2800 return 0; 2801 } 2802 if (Arch == Triple::arm) { 2803 if (Offset != 0 || (Size != 4 && Size != 2)) 2804 return 0; 2805 if (info->O->getHeader().filetype != MachO::MH_OBJECT) { 2806 // TODO: 2807 // Search the external relocation entries of a fully linked image 2808 // (if any) for an entry that matches this segment offset. 2809 // uint32_t seg_offset = (Pc + Offset); 2810 return 0; 2811 } 2812 // In MH_OBJECT filetypes search the section's relocation entries (if any) 2813 // for an entry for this section offset. 2814 uint32_t sect_addr = info->S.getAddress(); 2815 uint32_t sect_offset = (Pc + Offset) - sect_addr; 2816 DataRefImpl Rel; 2817 MachO::any_relocation_info RE; 2818 bool isExtern = false; 2819 SymbolRef Symbol; 2820 bool r_scattered = false; 2821 uint32_t r_value, pair_r_value, r_type, r_length, other_half; 2822 auto Reloc = 2823 find_if(info->S.relocations(), [&](const RelocationRef &Reloc) { 2824 uint64_t RelocOffset = Reloc.getOffset(); 2825 return RelocOffset == sect_offset; 2826 }); 2827 2828 if (Reloc == info->S.relocations().end()) 2829 return 0; 2830 2831 Rel = Reloc->getRawDataRefImpl(); 2832 RE = info->O->getRelocation(Rel); 2833 r_length = info->O->getAnyRelocationLength(RE); 2834 r_scattered = info->O->isRelocationScattered(RE); 2835 if (r_scattered) { 2836 r_value = info->O->getScatteredRelocationValue(RE); 2837 r_type = info->O->getScatteredRelocationType(RE); 2838 } else { 2839 r_type = info->O->getAnyRelocationType(RE); 2840 isExtern = info->O->getPlainRelocationExternal(RE); 2841 if (isExtern) { 2842 symbol_iterator RelocSym = Reloc->getSymbol(); 2843 Symbol = *RelocSym; 2844 } 2845 } 2846 if (r_type == MachO::ARM_RELOC_HALF || 2847 r_type == MachO::ARM_RELOC_SECTDIFF || 2848 r_type == MachO::ARM_RELOC_LOCAL_SECTDIFF || 2849 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) { 2850 DataRefImpl RelNext = Rel; 2851 info->O->moveRelocationNext(RelNext); 2852 MachO::any_relocation_info RENext; 2853 RENext = info->O->getRelocation(RelNext); 2854 other_half = info->O->getAnyRelocationAddress(RENext) & 0xffff; 2855 if (info->O->isRelocationScattered(RENext)) 2856 pair_r_value = info->O->getScatteredRelocationValue(RENext); 2857 } 2858 2859 if (isExtern) { 2860 const char *name = 2861 unwrapOrError(Symbol.getName(), info->O->getFileName()).data(); 2862 op_info->AddSymbol.Present = 1; 2863 op_info->AddSymbol.Name = name; 2864 switch (r_type) { 2865 case MachO::ARM_RELOC_HALF: 2866 if ((r_length & 0x1) == 1) { 2867 op_info->Value = value << 16 | other_half; 2868 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16; 2869 } else { 2870 op_info->Value = other_half << 16 | value; 2871 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16; 2872 } 2873 break; 2874 default: 2875 break; 2876 } 2877 return 1; 2878 } 2879 // If we have a branch that is not an external relocation entry then 2880 // return 0 so the code in tryAddingSymbolicOperand() can use the 2881 // SymbolLookUp call back with the branch target address to look up the 2882 // symbol and possibility add an annotation for a symbol stub. 2883 if (isExtern == 0 && (r_type == MachO::ARM_RELOC_BR24 || 2884 r_type == MachO::ARM_THUMB_RELOC_BR22)) 2885 return 0; 2886 2887 uint32_t offset = 0; 2888 if (r_type == MachO::ARM_RELOC_HALF || 2889 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) { 2890 if ((r_length & 0x1) == 1) 2891 value = value << 16 | other_half; 2892 else 2893 value = other_half << 16 | value; 2894 } 2895 if (r_scattered && (r_type != MachO::ARM_RELOC_HALF && 2896 r_type != MachO::ARM_RELOC_HALF_SECTDIFF)) { 2897 offset = value - r_value; 2898 value = r_value; 2899 } 2900 2901 if (r_type == MachO::ARM_RELOC_HALF_SECTDIFF) { 2902 if ((r_length & 0x1) == 1) 2903 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16; 2904 else 2905 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16; 2906 const char *add = GuessSymbolName(r_value, info->AddrMap); 2907 const char *sub = GuessSymbolName(pair_r_value, info->AddrMap); 2908 int32_t offset = value - (r_value - pair_r_value); 2909 op_info->AddSymbol.Present = 1; 2910 if (add != nullptr) 2911 op_info->AddSymbol.Name = add; 2912 else 2913 op_info->AddSymbol.Value = r_value; 2914 op_info->SubtractSymbol.Present = 1; 2915 if (sub != nullptr) 2916 op_info->SubtractSymbol.Name = sub; 2917 else 2918 op_info->SubtractSymbol.Value = pair_r_value; 2919 op_info->Value = offset; 2920 return 1; 2921 } 2922 2923 op_info->AddSymbol.Present = 1; 2924 op_info->Value = offset; 2925 if (r_type == MachO::ARM_RELOC_HALF) { 2926 if ((r_length & 0x1) == 1) 2927 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16; 2928 else 2929 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16; 2930 } 2931 const char *add = GuessSymbolName(value, info->AddrMap); 2932 if (add != nullptr) { 2933 op_info->AddSymbol.Name = add; 2934 return 1; 2935 } 2936 op_info->AddSymbol.Value = value; 2937 return 1; 2938 } 2939 if (Arch == Triple::aarch64) { 2940 if (Offset != 0 || Size != 4) 2941 return 0; 2942 if (info->O->getHeader().filetype != MachO::MH_OBJECT) { 2943 // TODO: 2944 // Search the external relocation entries of a fully linked image 2945 // (if any) for an entry that matches this segment offset. 2946 // uint64_t seg_offset = (Pc + Offset); 2947 return 0; 2948 } 2949 // In MH_OBJECT filetypes search the section's relocation entries (if any) 2950 // for an entry for this section offset. 2951 uint64_t sect_addr = info->S.getAddress(); 2952 uint64_t sect_offset = (Pc + Offset) - sect_addr; 2953 auto Reloc = 2954 find_if(info->S.relocations(), [&](const RelocationRef &Reloc) { 2955 uint64_t RelocOffset = Reloc.getOffset(); 2956 return RelocOffset == sect_offset; 2957 }); 2958 2959 if (Reloc == info->S.relocations().end()) 2960 return 0; 2961 2962 DataRefImpl Rel = Reloc->getRawDataRefImpl(); 2963 MachO::any_relocation_info RE = info->O->getRelocation(Rel); 2964 uint32_t r_type = info->O->getAnyRelocationType(RE); 2965 if (r_type == MachO::ARM64_RELOC_ADDEND) { 2966 DataRefImpl RelNext = Rel; 2967 info->O->moveRelocationNext(RelNext); 2968 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext); 2969 if (value == 0) { 2970 value = info->O->getPlainRelocationSymbolNum(RENext); 2971 op_info->Value = value; 2972 } 2973 } 2974 // NOTE: Scattered relocations don't exist on arm64. 2975 if (!info->O->getPlainRelocationExternal(RE)) 2976 return 0; 2977 const char *name = 2978 unwrapOrError(Reloc->getSymbol()->getName(), info->O->getFileName()) 2979 .data(); 2980 op_info->AddSymbol.Present = 1; 2981 op_info->AddSymbol.Name = name; 2982 2983 switch (r_type) { 2984 case MachO::ARM64_RELOC_PAGE21: 2985 /* @page */ 2986 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGE; 2987 break; 2988 case MachO::ARM64_RELOC_PAGEOFF12: 2989 /* @pageoff */ 2990 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGEOFF; 2991 break; 2992 case MachO::ARM64_RELOC_GOT_LOAD_PAGE21: 2993 /* @gotpage */ 2994 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGE; 2995 break; 2996 case MachO::ARM64_RELOC_GOT_LOAD_PAGEOFF12: 2997 /* @gotpageoff */ 2998 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGEOFF; 2999 break; 3000 case MachO::ARM64_RELOC_TLVP_LOAD_PAGE21: 3001 /* @tvlppage is not implemented in llvm-mc */ 3002 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVP; 3003 break; 3004 case MachO::ARM64_RELOC_TLVP_LOAD_PAGEOFF12: 3005 /* @tvlppageoff is not implemented in llvm-mc */ 3006 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVOFF; 3007 break; 3008 default: 3009 case MachO::ARM64_RELOC_BRANCH26: 3010 op_info->VariantKind = LLVMDisassembler_VariantKind_None; 3011 break; 3012 } 3013 return 1; 3014 } 3015 return 0; 3016 } 3017 3018 // GuessCstringPointer is passed the address of what might be a pointer to a 3019 // literal string in a cstring section. If that address is in a cstring section 3020 // it returns a pointer to that string. Else it returns nullptr. 3021 static const char *GuessCstringPointer(uint64_t ReferenceValue, 3022 struct DisassembleInfo *info) { 3023 for (const auto &Load : info->O->load_commands()) { 3024 if (Load.C.cmd == MachO::LC_SEGMENT_64) { 3025 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load); 3026 for (unsigned J = 0; J < Seg.nsects; ++J) { 3027 MachO::section_64 Sec = info->O->getSection64(Load, J); 3028 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE; 3029 if (section_type == MachO::S_CSTRING_LITERALS && 3030 ReferenceValue >= Sec.addr && 3031 ReferenceValue < Sec.addr + Sec.size) { 3032 uint64_t sect_offset = ReferenceValue - Sec.addr; 3033 uint64_t object_offset = Sec.offset + sect_offset; 3034 StringRef MachOContents = info->O->getData(); 3035 uint64_t object_size = MachOContents.size(); 3036 const char *object_addr = (const char *)MachOContents.data(); 3037 if (object_offset < object_size) { 3038 const char *name = object_addr + object_offset; 3039 return name; 3040 } else { 3041 return nullptr; 3042 } 3043 } 3044 } 3045 } else if (Load.C.cmd == MachO::LC_SEGMENT) { 3046 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load); 3047 for (unsigned J = 0; J < Seg.nsects; ++J) { 3048 MachO::section Sec = info->O->getSection(Load, J); 3049 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE; 3050 if (section_type == MachO::S_CSTRING_LITERALS && 3051 ReferenceValue >= Sec.addr && 3052 ReferenceValue < Sec.addr + Sec.size) { 3053 uint64_t sect_offset = ReferenceValue - Sec.addr; 3054 uint64_t object_offset = Sec.offset + sect_offset; 3055 StringRef MachOContents = info->O->getData(); 3056 uint64_t object_size = MachOContents.size(); 3057 const char *object_addr = (const char *)MachOContents.data(); 3058 if (object_offset < object_size) { 3059 const char *name = object_addr + object_offset; 3060 return name; 3061 } else { 3062 return nullptr; 3063 } 3064 } 3065 } 3066 } 3067 } 3068 return nullptr; 3069 } 3070 3071 // GuessIndirectSymbol returns the name of the indirect symbol for the 3072 // ReferenceValue passed in or nullptr. This is used when ReferenceValue maybe 3073 // an address of a symbol stub or a lazy or non-lazy pointer to associate the 3074 // symbol name being referenced by the stub or pointer. 3075 static const char *GuessIndirectSymbol(uint64_t ReferenceValue, 3076 struct DisassembleInfo *info) { 3077 MachO::dysymtab_command Dysymtab = info->O->getDysymtabLoadCommand(); 3078 MachO::symtab_command Symtab = info->O->getSymtabLoadCommand(); 3079 for (const auto &Load : info->O->load_commands()) { 3080 if (Load.C.cmd == MachO::LC_SEGMENT_64) { 3081 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load); 3082 for (unsigned J = 0; J < Seg.nsects; ++J) { 3083 MachO::section_64 Sec = info->O->getSection64(Load, J); 3084 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE; 3085 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS || 3086 section_type == MachO::S_LAZY_SYMBOL_POINTERS || 3087 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS || 3088 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS || 3089 section_type == MachO::S_SYMBOL_STUBS) && 3090 ReferenceValue >= Sec.addr && 3091 ReferenceValue < Sec.addr + Sec.size) { 3092 uint32_t stride; 3093 if (section_type == MachO::S_SYMBOL_STUBS) 3094 stride = Sec.reserved2; 3095 else 3096 stride = 8; 3097 if (stride == 0) 3098 return nullptr; 3099 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride; 3100 if (index < Dysymtab.nindirectsyms) { 3101 uint32_t indirect_symbol = 3102 info->O->getIndirectSymbolTableEntry(Dysymtab, index); 3103 if (indirect_symbol < Symtab.nsyms) { 3104 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol); 3105 return unwrapOrError(Sym->getName(), info->O->getFileName()) 3106 .data(); 3107 } 3108 } 3109 } 3110 } 3111 } else if (Load.C.cmd == MachO::LC_SEGMENT) { 3112 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load); 3113 for (unsigned J = 0; J < Seg.nsects; ++J) { 3114 MachO::section Sec = info->O->getSection(Load, J); 3115 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE; 3116 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS || 3117 section_type == MachO::S_LAZY_SYMBOL_POINTERS || 3118 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS || 3119 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS || 3120 section_type == MachO::S_SYMBOL_STUBS) && 3121 ReferenceValue >= Sec.addr && 3122 ReferenceValue < Sec.addr + Sec.size) { 3123 uint32_t stride; 3124 if (section_type == MachO::S_SYMBOL_STUBS) 3125 stride = Sec.reserved2; 3126 else 3127 stride = 4; 3128 if (stride == 0) 3129 return nullptr; 3130 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride; 3131 if (index < Dysymtab.nindirectsyms) { 3132 uint32_t indirect_symbol = 3133 info->O->getIndirectSymbolTableEntry(Dysymtab, index); 3134 if (indirect_symbol < Symtab.nsyms) { 3135 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol); 3136 return unwrapOrError(Sym->getName(), info->O->getFileName()) 3137 .data(); 3138 } 3139 } 3140 } 3141 } 3142 } 3143 } 3144 return nullptr; 3145 } 3146 3147 // method_reference() is called passing it the ReferenceName that might be 3148 // a reference it to an Objective-C method call. If so then it allocates and 3149 // assembles a method call string with the values last seen and saved in 3150 // the DisassembleInfo's class_name and selector_name fields. This is saved 3151 // into the method field of the info and any previous string is free'ed. 3152 // Then the class_name field in the info is set to nullptr. The method call 3153 // string is set into ReferenceName and ReferenceType is set to 3154 // LLVMDisassembler_ReferenceType_Out_Objc_Message. If this not a method call 3155 // then both ReferenceType and ReferenceName are left unchanged. 3156 static void method_reference(struct DisassembleInfo *info, 3157 uint64_t *ReferenceType, 3158 const char **ReferenceName) { 3159 unsigned int Arch = info->O->getArch(); 3160 if (*ReferenceName != nullptr) { 3161 if (strcmp(*ReferenceName, "_objc_msgSend") == 0) { 3162 if (info->selector_name != nullptr) { 3163 if (info->class_name != nullptr) { 3164 info->method = std::make_unique<char[]>( 3165 5 + strlen(info->class_name) + strlen(info->selector_name)); 3166 char *method = info->method.get(); 3167 if (method != nullptr) { 3168 strcpy(method, "+["); 3169 strcat(method, info->class_name); 3170 strcat(method, " "); 3171 strcat(method, info->selector_name); 3172 strcat(method, "]"); 3173 *ReferenceName = method; 3174 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message; 3175 } 3176 } else { 3177 info->method = 3178 std::make_unique<char[]>(9 + strlen(info->selector_name)); 3179 char *method = info->method.get(); 3180 if (method != nullptr) { 3181 if (Arch == Triple::x86_64) 3182 strcpy(method, "-[%rdi "); 3183 else if (Arch == Triple::aarch64) 3184 strcpy(method, "-[x0 "); 3185 else 3186 strcpy(method, "-[r? "); 3187 strcat(method, info->selector_name); 3188 strcat(method, "]"); 3189 *ReferenceName = method; 3190 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message; 3191 } 3192 } 3193 info->class_name = nullptr; 3194 } 3195 } else if (strcmp(*ReferenceName, "_objc_msgSendSuper2") == 0) { 3196 if (info->selector_name != nullptr) { 3197 info->method = 3198 std::make_unique<char[]>(17 + strlen(info->selector_name)); 3199 char *method = info->method.get(); 3200 if (method != nullptr) { 3201 if (Arch == Triple::x86_64) 3202 strcpy(method, "-[[%rdi super] "); 3203 else if (Arch == Triple::aarch64) 3204 strcpy(method, "-[[x0 super] "); 3205 else 3206 strcpy(method, "-[[r? super] "); 3207 strcat(method, info->selector_name); 3208 strcat(method, "]"); 3209 *ReferenceName = method; 3210 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message; 3211 } 3212 info->class_name = nullptr; 3213 } 3214 } 3215 } 3216 } 3217 3218 // GuessPointerPointer() is passed the address of what might be a pointer to 3219 // a reference to an Objective-C class, selector, message ref or cfstring. 3220 // If so the value of the pointer is returned and one of the booleans are set 3221 // to true. If not zero is returned and all the booleans are set to false. 3222 static uint64_t GuessPointerPointer(uint64_t ReferenceValue, 3223 struct DisassembleInfo *info, 3224 bool &classref, bool &selref, bool &msgref, 3225 bool &cfstring) { 3226 classref = false; 3227 selref = false; 3228 msgref = false; 3229 cfstring = false; 3230 for (const auto &Load : info->O->load_commands()) { 3231 if (Load.C.cmd == MachO::LC_SEGMENT_64) { 3232 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load); 3233 for (unsigned J = 0; J < Seg.nsects; ++J) { 3234 MachO::section_64 Sec = info->O->getSection64(Load, J); 3235 if ((strncmp(Sec.sectname, "__objc_selrefs", 16) == 0 || 3236 strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 || 3237 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0 || 3238 strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 || 3239 strncmp(Sec.sectname, "__cfstring", 16) == 0) && 3240 ReferenceValue >= Sec.addr && 3241 ReferenceValue < Sec.addr + Sec.size) { 3242 uint64_t sect_offset = ReferenceValue - Sec.addr; 3243 uint64_t object_offset = Sec.offset + sect_offset; 3244 StringRef MachOContents = info->O->getData(); 3245 uint64_t object_size = MachOContents.size(); 3246 const char *object_addr = (const char *)MachOContents.data(); 3247 if (object_offset < object_size) { 3248 uint64_t pointer_value; 3249 memcpy(&pointer_value, object_addr + object_offset, 3250 sizeof(uint64_t)); 3251 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 3252 sys::swapByteOrder(pointer_value); 3253 if (strncmp(Sec.sectname, "__objc_selrefs", 16) == 0) 3254 selref = true; 3255 else if (strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 || 3256 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0) 3257 classref = true; 3258 else if (strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 && 3259 ReferenceValue + 8 < Sec.addr + Sec.size) { 3260 msgref = true; 3261 memcpy(&pointer_value, object_addr + object_offset + 8, 3262 sizeof(uint64_t)); 3263 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 3264 sys::swapByteOrder(pointer_value); 3265 } else if (strncmp(Sec.sectname, "__cfstring", 16) == 0) 3266 cfstring = true; 3267 return pointer_value; 3268 } else { 3269 return 0; 3270 } 3271 } 3272 } 3273 } 3274 // TODO: Look for LC_SEGMENT for 32-bit Mach-O files. 3275 } 3276 return 0; 3277 } 3278 3279 // get_pointer_64 returns a pointer to the bytes in the object file at the 3280 // Address from a section in the Mach-O file. And indirectly returns the 3281 // offset into the section, number of bytes left in the section past the offset 3282 // and which section is was being referenced. If the Address is not in a 3283 // section nullptr is returned. 3284 static const char *get_pointer_64(uint64_t Address, uint32_t &offset, 3285 uint32_t &left, SectionRef &S, 3286 DisassembleInfo *info, 3287 bool objc_only = false) { 3288 offset = 0; 3289 left = 0; 3290 S = SectionRef(); 3291 for (unsigned SectIdx = 0; SectIdx != info->Sections->size(); SectIdx++) { 3292 uint64_t SectAddress = ((*(info->Sections))[SectIdx]).getAddress(); 3293 uint64_t SectSize = ((*(info->Sections))[SectIdx]).getSize(); 3294 if (SectSize == 0) 3295 continue; 3296 if (objc_only) { 3297 StringRef SectName; 3298 Expected<StringRef> SecNameOrErr = 3299 ((*(info->Sections))[SectIdx]).getName(); 3300 if (SecNameOrErr) 3301 SectName = *SecNameOrErr; 3302 else 3303 consumeError(SecNameOrErr.takeError()); 3304 3305 DataRefImpl Ref = ((*(info->Sections))[SectIdx]).getRawDataRefImpl(); 3306 StringRef SegName = info->O->getSectionFinalSegmentName(Ref); 3307 if (SegName != "__OBJC" && SectName != "__cstring") 3308 continue; 3309 } 3310 if (Address >= SectAddress && Address < SectAddress + SectSize) { 3311 S = (*(info->Sections))[SectIdx]; 3312 offset = Address - SectAddress; 3313 left = SectSize - offset; 3314 StringRef SectContents = unwrapOrError( 3315 ((*(info->Sections))[SectIdx]).getContents(), info->O->getFileName()); 3316 return SectContents.data() + offset; 3317 } 3318 } 3319 return nullptr; 3320 } 3321 3322 static const char *get_pointer_32(uint32_t Address, uint32_t &offset, 3323 uint32_t &left, SectionRef &S, 3324 DisassembleInfo *info, 3325 bool objc_only = false) { 3326 return get_pointer_64(Address, offset, left, S, info, objc_only); 3327 } 3328 3329 // get_symbol_64() returns the name of a symbol (or nullptr) and the address of 3330 // the symbol indirectly through n_value. Based on the relocation information 3331 // for the specified section offset in the specified section reference. 3332 // If no relocation information is found and a non-zero ReferenceValue for the 3333 // symbol is passed, look up that address in the info's AddrMap. 3334 static const char *get_symbol_64(uint32_t sect_offset, SectionRef S, 3335 DisassembleInfo *info, uint64_t &n_value, 3336 uint64_t ReferenceValue = 0) { 3337 n_value = 0; 3338 if (!info->verbose) 3339 return nullptr; 3340 3341 // See if there is an external relocation entry at the sect_offset. 3342 bool reloc_found = false; 3343 DataRefImpl Rel; 3344 MachO::any_relocation_info RE; 3345 bool isExtern = false; 3346 SymbolRef Symbol; 3347 for (const RelocationRef &Reloc : S.relocations()) { 3348 uint64_t RelocOffset = Reloc.getOffset(); 3349 if (RelocOffset == sect_offset) { 3350 Rel = Reloc.getRawDataRefImpl(); 3351 RE = info->O->getRelocation(Rel); 3352 if (info->O->isRelocationScattered(RE)) 3353 continue; 3354 isExtern = info->O->getPlainRelocationExternal(RE); 3355 if (isExtern) { 3356 symbol_iterator RelocSym = Reloc.getSymbol(); 3357 Symbol = *RelocSym; 3358 } 3359 reloc_found = true; 3360 break; 3361 } 3362 } 3363 // If there is an external relocation entry for a symbol in this section 3364 // at this section_offset then use that symbol's value for the n_value 3365 // and return its name. 3366 const char *SymbolName = nullptr; 3367 if (reloc_found && isExtern) { 3368 n_value = Symbol.getValue(); 3369 StringRef Name = unwrapOrError(Symbol.getName(), info->O->getFileName()); 3370 if (!Name.empty()) { 3371 SymbolName = Name.data(); 3372 return SymbolName; 3373 } 3374 } 3375 3376 // TODO: For fully linked images, look through the external relocation 3377 // entries off the dynamic symtab command. For these the r_offset is from the 3378 // start of the first writeable segment in the Mach-O file. So the offset 3379 // to this section from that segment is passed to this routine by the caller, 3380 // as the database_offset. Which is the difference of the section's starting 3381 // address and the first writable segment. 3382 // 3383 // NOTE: need add passing the database_offset to this routine. 3384 3385 // We did not find an external relocation entry so look up the ReferenceValue 3386 // as an address of a symbol and if found return that symbol's name. 3387 SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap); 3388 3389 return SymbolName; 3390 } 3391 3392 static const char *get_symbol_32(uint32_t sect_offset, SectionRef S, 3393 DisassembleInfo *info, 3394 uint32_t ReferenceValue) { 3395 uint64_t n_value64; 3396 return get_symbol_64(sect_offset, S, info, n_value64, ReferenceValue); 3397 } 3398 3399 // These are structs in the Objective-C meta data and read to produce the 3400 // comments for disassembly. While these are part of the ABI they are no 3401 // public defintions. So the are here not in include/llvm/BinaryFormat/MachO.h 3402 // . 3403 3404 // The cfstring object in a 64-bit Mach-O file. 3405 struct cfstring64_t { 3406 uint64_t isa; // class64_t * (64-bit pointer) 3407 uint64_t flags; // flag bits 3408 uint64_t characters; // char * (64-bit pointer) 3409 uint64_t length; // number of non-NULL characters in above 3410 }; 3411 3412 // The class object in a 64-bit Mach-O file. 3413 struct class64_t { 3414 uint64_t isa; // class64_t * (64-bit pointer) 3415 uint64_t superclass; // class64_t * (64-bit pointer) 3416 uint64_t cache; // Cache (64-bit pointer) 3417 uint64_t vtable; // IMP * (64-bit pointer) 3418 uint64_t data; // class_ro64_t * (64-bit pointer) 3419 }; 3420 3421 struct class32_t { 3422 uint32_t isa; /* class32_t * (32-bit pointer) */ 3423 uint32_t superclass; /* class32_t * (32-bit pointer) */ 3424 uint32_t cache; /* Cache (32-bit pointer) */ 3425 uint32_t vtable; /* IMP * (32-bit pointer) */ 3426 uint32_t data; /* class_ro32_t * (32-bit pointer) */ 3427 }; 3428 3429 struct class_ro64_t { 3430 uint32_t flags; 3431 uint32_t instanceStart; 3432 uint32_t instanceSize; 3433 uint32_t reserved; 3434 uint64_t ivarLayout; // const uint8_t * (64-bit pointer) 3435 uint64_t name; // const char * (64-bit pointer) 3436 uint64_t baseMethods; // const method_list_t * (64-bit pointer) 3437 uint64_t baseProtocols; // const protocol_list_t * (64-bit pointer) 3438 uint64_t ivars; // const ivar_list_t * (64-bit pointer) 3439 uint64_t weakIvarLayout; // const uint8_t * (64-bit pointer) 3440 uint64_t baseProperties; // const struct objc_property_list (64-bit pointer) 3441 }; 3442 3443 struct class_ro32_t { 3444 uint32_t flags; 3445 uint32_t instanceStart; 3446 uint32_t instanceSize; 3447 uint32_t ivarLayout; /* const uint8_t * (32-bit pointer) */ 3448 uint32_t name; /* const char * (32-bit pointer) */ 3449 uint32_t baseMethods; /* const method_list_t * (32-bit pointer) */ 3450 uint32_t baseProtocols; /* const protocol_list_t * (32-bit pointer) */ 3451 uint32_t ivars; /* const ivar_list_t * (32-bit pointer) */ 3452 uint32_t weakIvarLayout; /* const uint8_t * (32-bit pointer) */ 3453 uint32_t baseProperties; /* const struct objc_property_list * 3454 (32-bit pointer) */ 3455 }; 3456 3457 /* Values for class_ro{64,32}_t->flags */ 3458 #define RO_META (1 << 0) 3459 #define RO_ROOT (1 << 1) 3460 #define RO_HAS_CXX_STRUCTORS (1 << 2) 3461 3462 struct method_list64_t { 3463 uint32_t entsize; 3464 uint32_t count; 3465 /* struct method64_t first; These structures follow inline */ 3466 }; 3467 3468 struct method_list32_t { 3469 uint32_t entsize; 3470 uint32_t count; 3471 /* struct method32_t first; These structures follow inline */ 3472 }; 3473 3474 struct method64_t { 3475 uint64_t name; /* SEL (64-bit pointer) */ 3476 uint64_t types; /* const char * (64-bit pointer) */ 3477 uint64_t imp; /* IMP (64-bit pointer) */ 3478 }; 3479 3480 struct method32_t { 3481 uint32_t name; /* SEL (32-bit pointer) */ 3482 uint32_t types; /* const char * (32-bit pointer) */ 3483 uint32_t imp; /* IMP (32-bit pointer) */ 3484 }; 3485 3486 struct protocol_list64_t { 3487 uint64_t count; /* uintptr_t (a 64-bit value) */ 3488 /* struct protocol64_t * list[0]; These pointers follow inline */ 3489 }; 3490 3491 struct protocol_list32_t { 3492 uint32_t count; /* uintptr_t (a 32-bit value) */ 3493 /* struct protocol32_t * list[0]; These pointers follow inline */ 3494 }; 3495 3496 struct protocol64_t { 3497 uint64_t isa; /* id * (64-bit pointer) */ 3498 uint64_t name; /* const char * (64-bit pointer) */ 3499 uint64_t protocols; /* struct protocol_list64_t * 3500 (64-bit pointer) */ 3501 uint64_t instanceMethods; /* method_list_t * (64-bit pointer) */ 3502 uint64_t classMethods; /* method_list_t * (64-bit pointer) */ 3503 uint64_t optionalInstanceMethods; /* method_list_t * (64-bit pointer) */ 3504 uint64_t optionalClassMethods; /* method_list_t * (64-bit pointer) */ 3505 uint64_t instanceProperties; /* struct objc_property_list * 3506 (64-bit pointer) */ 3507 }; 3508 3509 struct protocol32_t { 3510 uint32_t isa; /* id * (32-bit pointer) */ 3511 uint32_t name; /* const char * (32-bit pointer) */ 3512 uint32_t protocols; /* struct protocol_list_t * 3513 (32-bit pointer) */ 3514 uint32_t instanceMethods; /* method_list_t * (32-bit pointer) */ 3515 uint32_t classMethods; /* method_list_t * (32-bit pointer) */ 3516 uint32_t optionalInstanceMethods; /* method_list_t * (32-bit pointer) */ 3517 uint32_t optionalClassMethods; /* method_list_t * (32-bit pointer) */ 3518 uint32_t instanceProperties; /* struct objc_property_list * 3519 (32-bit pointer) */ 3520 }; 3521 3522 struct ivar_list64_t { 3523 uint32_t entsize; 3524 uint32_t count; 3525 /* struct ivar64_t first; These structures follow inline */ 3526 }; 3527 3528 struct ivar_list32_t { 3529 uint32_t entsize; 3530 uint32_t count; 3531 /* struct ivar32_t first; These structures follow inline */ 3532 }; 3533 3534 struct ivar64_t { 3535 uint64_t offset; /* uintptr_t * (64-bit pointer) */ 3536 uint64_t name; /* const char * (64-bit pointer) */ 3537 uint64_t type; /* const char * (64-bit pointer) */ 3538 uint32_t alignment; 3539 uint32_t size; 3540 }; 3541 3542 struct ivar32_t { 3543 uint32_t offset; /* uintptr_t * (32-bit pointer) */ 3544 uint32_t name; /* const char * (32-bit pointer) */ 3545 uint32_t type; /* const char * (32-bit pointer) */ 3546 uint32_t alignment; 3547 uint32_t size; 3548 }; 3549 3550 struct objc_property_list64 { 3551 uint32_t entsize; 3552 uint32_t count; 3553 /* struct objc_property64 first; These structures follow inline */ 3554 }; 3555 3556 struct objc_property_list32 { 3557 uint32_t entsize; 3558 uint32_t count; 3559 /* struct objc_property32 first; These structures follow inline */ 3560 }; 3561 3562 struct objc_property64 { 3563 uint64_t name; /* const char * (64-bit pointer) */ 3564 uint64_t attributes; /* const char * (64-bit pointer) */ 3565 }; 3566 3567 struct objc_property32 { 3568 uint32_t name; /* const char * (32-bit pointer) */ 3569 uint32_t attributes; /* const char * (32-bit pointer) */ 3570 }; 3571 3572 struct category64_t { 3573 uint64_t name; /* const char * (64-bit pointer) */ 3574 uint64_t cls; /* struct class_t * (64-bit pointer) */ 3575 uint64_t instanceMethods; /* struct method_list_t * (64-bit pointer) */ 3576 uint64_t classMethods; /* struct method_list_t * (64-bit pointer) */ 3577 uint64_t protocols; /* struct protocol_list_t * (64-bit pointer) */ 3578 uint64_t instanceProperties; /* struct objc_property_list * 3579 (64-bit pointer) */ 3580 }; 3581 3582 struct category32_t { 3583 uint32_t name; /* const char * (32-bit pointer) */ 3584 uint32_t cls; /* struct class_t * (32-bit pointer) */ 3585 uint32_t instanceMethods; /* struct method_list_t * (32-bit pointer) */ 3586 uint32_t classMethods; /* struct method_list_t * (32-bit pointer) */ 3587 uint32_t protocols; /* struct protocol_list_t * (32-bit pointer) */ 3588 uint32_t instanceProperties; /* struct objc_property_list * 3589 (32-bit pointer) */ 3590 }; 3591 3592 struct objc_image_info64 { 3593 uint32_t version; 3594 uint32_t flags; 3595 }; 3596 struct objc_image_info32 { 3597 uint32_t version; 3598 uint32_t flags; 3599 }; 3600 struct imageInfo_t { 3601 uint32_t version; 3602 uint32_t flags; 3603 }; 3604 /* masks for objc_image_info.flags */ 3605 #define OBJC_IMAGE_IS_REPLACEMENT (1 << 0) 3606 #define OBJC_IMAGE_SUPPORTS_GC (1 << 1) 3607 #define OBJC_IMAGE_IS_SIMULATED (1 << 5) 3608 #define OBJC_IMAGE_HAS_CATEGORY_CLASS_PROPERTIES (1 << 6) 3609 3610 struct message_ref64 { 3611 uint64_t imp; /* IMP (64-bit pointer) */ 3612 uint64_t sel; /* SEL (64-bit pointer) */ 3613 }; 3614 3615 struct message_ref32 { 3616 uint32_t imp; /* IMP (32-bit pointer) */ 3617 uint32_t sel; /* SEL (32-bit pointer) */ 3618 }; 3619 3620 // Objective-C 1 (32-bit only) meta data structs. 3621 3622 struct objc_module_t { 3623 uint32_t version; 3624 uint32_t size; 3625 uint32_t name; /* char * (32-bit pointer) */ 3626 uint32_t symtab; /* struct objc_symtab * (32-bit pointer) */ 3627 }; 3628 3629 struct objc_symtab_t { 3630 uint32_t sel_ref_cnt; 3631 uint32_t refs; /* SEL * (32-bit pointer) */ 3632 uint16_t cls_def_cnt; 3633 uint16_t cat_def_cnt; 3634 // uint32_t defs[1]; /* void * (32-bit pointer) variable size */ 3635 }; 3636 3637 struct objc_class_t { 3638 uint32_t isa; /* struct objc_class * (32-bit pointer) */ 3639 uint32_t super_class; /* struct objc_class * (32-bit pointer) */ 3640 uint32_t name; /* const char * (32-bit pointer) */ 3641 int32_t version; 3642 int32_t info; 3643 int32_t instance_size; 3644 uint32_t ivars; /* struct objc_ivar_list * (32-bit pointer) */ 3645 uint32_t methodLists; /* struct objc_method_list ** (32-bit pointer) */ 3646 uint32_t cache; /* struct objc_cache * (32-bit pointer) */ 3647 uint32_t protocols; /* struct objc_protocol_list * (32-bit pointer) */ 3648 }; 3649 3650 #define CLS_GETINFO(cls, infomask) ((cls)->info & (infomask)) 3651 // class is not a metaclass 3652 #define CLS_CLASS 0x1 3653 // class is a metaclass 3654 #define CLS_META 0x2 3655 3656 struct objc_category_t { 3657 uint32_t category_name; /* char * (32-bit pointer) */ 3658 uint32_t class_name; /* char * (32-bit pointer) */ 3659 uint32_t instance_methods; /* struct objc_method_list * (32-bit pointer) */ 3660 uint32_t class_methods; /* struct objc_method_list * (32-bit pointer) */ 3661 uint32_t protocols; /* struct objc_protocol_list * (32-bit ptr) */ 3662 }; 3663 3664 struct objc_ivar_t { 3665 uint32_t ivar_name; /* char * (32-bit pointer) */ 3666 uint32_t ivar_type; /* char * (32-bit pointer) */ 3667 int32_t ivar_offset; 3668 }; 3669 3670 struct objc_ivar_list_t { 3671 int32_t ivar_count; 3672 // struct objc_ivar_t ivar_list[1]; /* variable length structure */ 3673 }; 3674 3675 struct objc_method_list_t { 3676 uint32_t obsolete; /* struct objc_method_list * (32-bit pointer) */ 3677 int32_t method_count; 3678 // struct objc_method_t method_list[1]; /* variable length structure */ 3679 }; 3680 3681 struct objc_method_t { 3682 uint32_t method_name; /* SEL, aka struct objc_selector * (32-bit pointer) */ 3683 uint32_t method_types; /* char * (32-bit pointer) */ 3684 uint32_t method_imp; /* IMP, aka function pointer, (*IMP)(id, SEL, ...) 3685 (32-bit pointer) */ 3686 }; 3687 3688 struct objc_protocol_list_t { 3689 uint32_t next; /* struct objc_protocol_list * (32-bit pointer) */ 3690 int32_t count; 3691 // uint32_t list[1]; /* Protocol *, aka struct objc_protocol_t * 3692 // (32-bit pointer) */ 3693 }; 3694 3695 struct objc_protocol_t { 3696 uint32_t isa; /* struct objc_class * (32-bit pointer) */ 3697 uint32_t protocol_name; /* char * (32-bit pointer) */ 3698 uint32_t protocol_list; /* struct objc_protocol_list * (32-bit pointer) */ 3699 uint32_t instance_methods; /* struct objc_method_description_list * 3700 (32-bit pointer) */ 3701 uint32_t class_methods; /* struct objc_method_description_list * 3702 (32-bit pointer) */ 3703 }; 3704 3705 struct objc_method_description_list_t { 3706 int32_t count; 3707 // struct objc_method_description_t list[1]; 3708 }; 3709 3710 struct objc_method_description_t { 3711 uint32_t name; /* SEL, aka struct objc_selector * (32-bit pointer) */ 3712 uint32_t types; /* char * (32-bit pointer) */ 3713 }; 3714 3715 inline void swapStruct(struct cfstring64_t &cfs) { 3716 sys::swapByteOrder(cfs.isa); 3717 sys::swapByteOrder(cfs.flags); 3718 sys::swapByteOrder(cfs.characters); 3719 sys::swapByteOrder(cfs.length); 3720 } 3721 3722 inline void swapStruct(struct class64_t &c) { 3723 sys::swapByteOrder(c.isa); 3724 sys::swapByteOrder(c.superclass); 3725 sys::swapByteOrder(c.cache); 3726 sys::swapByteOrder(c.vtable); 3727 sys::swapByteOrder(c.data); 3728 } 3729 3730 inline void swapStruct(struct class32_t &c) { 3731 sys::swapByteOrder(c.isa); 3732 sys::swapByteOrder(c.superclass); 3733 sys::swapByteOrder(c.cache); 3734 sys::swapByteOrder(c.vtable); 3735 sys::swapByteOrder(c.data); 3736 } 3737 3738 inline void swapStruct(struct class_ro64_t &cro) { 3739 sys::swapByteOrder(cro.flags); 3740 sys::swapByteOrder(cro.instanceStart); 3741 sys::swapByteOrder(cro.instanceSize); 3742 sys::swapByteOrder(cro.reserved); 3743 sys::swapByteOrder(cro.ivarLayout); 3744 sys::swapByteOrder(cro.name); 3745 sys::swapByteOrder(cro.baseMethods); 3746 sys::swapByteOrder(cro.baseProtocols); 3747 sys::swapByteOrder(cro.ivars); 3748 sys::swapByteOrder(cro.weakIvarLayout); 3749 sys::swapByteOrder(cro.baseProperties); 3750 } 3751 3752 inline void swapStruct(struct class_ro32_t &cro) { 3753 sys::swapByteOrder(cro.flags); 3754 sys::swapByteOrder(cro.instanceStart); 3755 sys::swapByteOrder(cro.instanceSize); 3756 sys::swapByteOrder(cro.ivarLayout); 3757 sys::swapByteOrder(cro.name); 3758 sys::swapByteOrder(cro.baseMethods); 3759 sys::swapByteOrder(cro.baseProtocols); 3760 sys::swapByteOrder(cro.ivars); 3761 sys::swapByteOrder(cro.weakIvarLayout); 3762 sys::swapByteOrder(cro.baseProperties); 3763 } 3764 3765 inline void swapStruct(struct method_list64_t &ml) { 3766 sys::swapByteOrder(ml.entsize); 3767 sys::swapByteOrder(ml.count); 3768 } 3769 3770 inline void swapStruct(struct method_list32_t &ml) { 3771 sys::swapByteOrder(ml.entsize); 3772 sys::swapByteOrder(ml.count); 3773 } 3774 3775 inline void swapStruct(struct method64_t &m) { 3776 sys::swapByteOrder(m.name); 3777 sys::swapByteOrder(m.types); 3778 sys::swapByteOrder(m.imp); 3779 } 3780 3781 inline void swapStruct(struct method32_t &m) { 3782 sys::swapByteOrder(m.name); 3783 sys::swapByteOrder(m.types); 3784 sys::swapByteOrder(m.imp); 3785 } 3786 3787 inline void swapStruct(struct protocol_list64_t &pl) { 3788 sys::swapByteOrder(pl.count); 3789 } 3790 3791 inline void swapStruct(struct protocol_list32_t &pl) { 3792 sys::swapByteOrder(pl.count); 3793 } 3794 3795 inline void swapStruct(struct protocol64_t &p) { 3796 sys::swapByteOrder(p.isa); 3797 sys::swapByteOrder(p.name); 3798 sys::swapByteOrder(p.protocols); 3799 sys::swapByteOrder(p.instanceMethods); 3800 sys::swapByteOrder(p.classMethods); 3801 sys::swapByteOrder(p.optionalInstanceMethods); 3802 sys::swapByteOrder(p.optionalClassMethods); 3803 sys::swapByteOrder(p.instanceProperties); 3804 } 3805 3806 inline void swapStruct(struct protocol32_t &p) { 3807 sys::swapByteOrder(p.isa); 3808 sys::swapByteOrder(p.name); 3809 sys::swapByteOrder(p.protocols); 3810 sys::swapByteOrder(p.instanceMethods); 3811 sys::swapByteOrder(p.classMethods); 3812 sys::swapByteOrder(p.optionalInstanceMethods); 3813 sys::swapByteOrder(p.optionalClassMethods); 3814 sys::swapByteOrder(p.instanceProperties); 3815 } 3816 3817 inline void swapStruct(struct ivar_list64_t &il) { 3818 sys::swapByteOrder(il.entsize); 3819 sys::swapByteOrder(il.count); 3820 } 3821 3822 inline void swapStruct(struct ivar_list32_t &il) { 3823 sys::swapByteOrder(il.entsize); 3824 sys::swapByteOrder(il.count); 3825 } 3826 3827 inline void swapStruct(struct ivar64_t &i) { 3828 sys::swapByteOrder(i.offset); 3829 sys::swapByteOrder(i.name); 3830 sys::swapByteOrder(i.type); 3831 sys::swapByteOrder(i.alignment); 3832 sys::swapByteOrder(i.size); 3833 } 3834 3835 inline void swapStruct(struct ivar32_t &i) { 3836 sys::swapByteOrder(i.offset); 3837 sys::swapByteOrder(i.name); 3838 sys::swapByteOrder(i.type); 3839 sys::swapByteOrder(i.alignment); 3840 sys::swapByteOrder(i.size); 3841 } 3842 3843 inline void swapStruct(struct objc_property_list64 &pl) { 3844 sys::swapByteOrder(pl.entsize); 3845 sys::swapByteOrder(pl.count); 3846 } 3847 3848 inline void swapStruct(struct objc_property_list32 &pl) { 3849 sys::swapByteOrder(pl.entsize); 3850 sys::swapByteOrder(pl.count); 3851 } 3852 3853 inline void swapStruct(struct objc_property64 &op) { 3854 sys::swapByteOrder(op.name); 3855 sys::swapByteOrder(op.attributes); 3856 } 3857 3858 inline void swapStruct(struct objc_property32 &op) { 3859 sys::swapByteOrder(op.name); 3860 sys::swapByteOrder(op.attributes); 3861 } 3862 3863 inline void swapStruct(struct category64_t &c) { 3864 sys::swapByteOrder(c.name); 3865 sys::swapByteOrder(c.cls); 3866 sys::swapByteOrder(c.instanceMethods); 3867 sys::swapByteOrder(c.classMethods); 3868 sys::swapByteOrder(c.protocols); 3869 sys::swapByteOrder(c.instanceProperties); 3870 } 3871 3872 inline void swapStruct(struct category32_t &c) { 3873 sys::swapByteOrder(c.name); 3874 sys::swapByteOrder(c.cls); 3875 sys::swapByteOrder(c.instanceMethods); 3876 sys::swapByteOrder(c.classMethods); 3877 sys::swapByteOrder(c.protocols); 3878 sys::swapByteOrder(c.instanceProperties); 3879 } 3880 3881 inline void swapStruct(struct objc_image_info64 &o) { 3882 sys::swapByteOrder(o.version); 3883 sys::swapByteOrder(o.flags); 3884 } 3885 3886 inline void swapStruct(struct objc_image_info32 &o) { 3887 sys::swapByteOrder(o.version); 3888 sys::swapByteOrder(o.flags); 3889 } 3890 3891 inline void swapStruct(struct imageInfo_t &o) { 3892 sys::swapByteOrder(o.version); 3893 sys::swapByteOrder(o.flags); 3894 } 3895 3896 inline void swapStruct(struct message_ref64 &mr) { 3897 sys::swapByteOrder(mr.imp); 3898 sys::swapByteOrder(mr.sel); 3899 } 3900 3901 inline void swapStruct(struct message_ref32 &mr) { 3902 sys::swapByteOrder(mr.imp); 3903 sys::swapByteOrder(mr.sel); 3904 } 3905 3906 inline void swapStruct(struct objc_module_t &module) { 3907 sys::swapByteOrder(module.version); 3908 sys::swapByteOrder(module.size); 3909 sys::swapByteOrder(module.name); 3910 sys::swapByteOrder(module.symtab); 3911 } 3912 3913 inline void swapStruct(struct objc_symtab_t &symtab) { 3914 sys::swapByteOrder(symtab.sel_ref_cnt); 3915 sys::swapByteOrder(symtab.refs); 3916 sys::swapByteOrder(symtab.cls_def_cnt); 3917 sys::swapByteOrder(symtab.cat_def_cnt); 3918 } 3919 3920 inline void swapStruct(struct objc_class_t &objc_class) { 3921 sys::swapByteOrder(objc_class.isa); 3922 sys::swapByteOrder(objc_class.super_class); 3923 sys::swapByteOrder(objc_class.name); 3924 sys::swapByteOrder(objc_class.version); 3925 sys::swapByteOrder(objc_class.info); 3926 sys::swapByteOrder(objc_class.instance_size); 3927 sys::swapByteOrder(objc_class.ivars); 3928 sys::swapByteOrder(objc_class.methodLists); 3929 sys::swapByteOrder(objc_class.cache); 3930 sys::swapByteOrder(objc_class.protocols); 3931 } 3932 3933 inline void swapStruct(struct objc_category_t &objc_category) { 3934 sys::swapByteOrder(objc_category.category_name); 3935 sys::swapByteOrder(objc_category.class_name); 3936 sys::swapByteOrder(objc_category.instance_methods); 3937 sys::swapByteOrder(objc_category.class_methods); 3938 sys::swapByteOrder(objc_category.protocols); 3939 } 3940 3941 inline void swapStruct(struct objc_ivar_list_t &objc_ivar_list) { 3942 sys::swapByteOrder(objc_ivar_list.ivar_count); 3943 } 3944 3945 inline void swapStruct(struct objc_ivar_t &objc_ivar) { 3946 sys::swapByteOrder(objc_ivar.ivar_name); 3947 sys::swapByteOrder(objc_ivar.ivar_type); 3948 sys::swapByteOrder(objc_ivar.ivar_offset); 3949 } 3950 3951 inline void swapStruct(struct objc_method_list_t &method_list) { 3952 sys::swapByteOrder(method_list.obsolete); 3953 sys::swapByteOrder(method_list.method_count); 3954 } 3955 3956 inline void swapStruct(struct objc_method_t &method) { 3957 sys::swapByteOrder(method.method_name); 3958 sys::swapByteOrder(method.method_types); 3959 sys::swapByteOrder(method.method_imp); 3960 } 3961 3962 inline void swapStruct(struct objc_protocol_list_t &protocol_list) { 3963 sys::swapByteOrder(protocol_list.next); 3964 sys::swapByteOrder(protocol_list.count); 3965 } 3966 3967 inline void swapStruct(struct objc_protocol_t &protocol) { 3968 sys::swapByteOrder(protocol.isa); 3969 sys::swapByteOrder(protocol.protocol_name); 3970 sys::swapByteOrder(protocol.protocol_list); 3971 sys::swapByteOrder(protocol.instance_methods); 3972 sys::swapByteOrder(protocol.class_methods); 3973 } 3974 3975 inline void swapStruct(struct objc_method_description_list_t &mdl) { 3976 sys::swapByteOrder(mdl.count); 3977 } 3978 3979 inline void swapStruct(struct objc_method_description_t &md) { 3980 sys::swapByteOrder(md.name); 3981 sys::swapByteOrder(md.types); 3982 } 3983 3984 static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue, 3985 struct DisassembleInfo *info); 3986 3987 // get_objc2_64bit_class_name() is used for disassembly and is passed a pointer 3988 // to an Objective-C class and returns the class name. It is also passed the 3989 // address of the pointer, so when the pointer is zero as it can be in an .o 3990 // file, that is used to look for an external relocation entry with a symbol 3991 // name. 3992 static const char *get_objc2_64bit_class_name(uint64_t pointer_value, 3993 uint64_t ReferenceValue, 3994 struct DisassembleInfo *info) { 3995 const char *r; 3996 uint32_t offset, left; 3997 SectionRef S; 3998 3999 // The pointer_value can be 0 in an object file and have a relocation 4000 // entry for the class symbol at the ReferenceValue (the address of the 4001 // pointer). 4002 if (pointer_value == 0) { 4003 r = get_pointer_64(ReferenceValue, offset, left, S, info); 4004 if (r == nullptr || left < sizeof(uint64_t)) 4005 return nullptr; 4006 uint64_t n_value; 4007 const char *symbol_name = get_symbol_64(offset, S, info, n_value); 4008 if (symbol_name == nullptr) 4009 return nullptr; 4010 const char *class_name = strrchr(symbol_name, '$'); 4011 if (class_name != nullptr && class_name[1] == '_' && class_name[2] != '\0') 4012 return class_name + 2; 4013 else 4014 return nullptr; 4015 } 4016 4017 // The case were the pointer_value is non-zero and points to a class defined 4018 // in this Mach-O file. 4019 r = get_pointer_64(pointer_value, offset, left, S, info); 4020 if (r == nullptr || left < sizeof(struct class64_t)) 4021 return nullptr; 4022 struct class64_t c; 4023 memcpy(&c, r, sizeof(struct class64_t)); 4024 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 4025 swapStruct(c); 4026 if (c.data == 0) 4027 return nullptr; 4028 r = get_pointer_64(c.data, offset, left, S, info); 4029 if (r == nullptr || left < sizeof(struct class_ro64_t)) 4030 return nullptr; 4031 struct class_ro64_t cro; 4032 memcpy(&cro, r, sizeof(struct class_ro64_t)); 4033 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 4034 swapStruct(cro); 4035 if (cro.name == 0) 4036 return nullptr; 4037 const char *name = get_pointer_64(cro.name, offset, left, S, info); 4038 return name; 4039 } 4040 4041 // get_objc2_64bit_cfstring_name is used for disassembly and is passed a 4042 // pointer to a cfstring and returns its name or nullptr. 4043 static const char *get_objc2_64bit_cfstring_name(uint64_t ReferenceValue, 4044 struct DisassembleInfo *info) { 4045 const char *r, *name; 4046 uint32_t offset, left; 4047 SectionRef S; 4048 struct cfstring64_t cfs; 4049 uint64_t cfs_characters; 4050 4051 r = get_pointer_64(ReferenceValue, offset, left, S, info); 4052 if (r == nullptr || left < sizeof(struct cfstring64_t)) 4053 return nullptr; 4054 memcpy(&cfs, r, sizeof(struct cfstring64_t)); 4055 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 4056 swapStruct(cfs); 4057 if (cfs.characters == 0) { 4058 uint64_t n_value; 4059 const char *symbol_name = get_symbol_64( 4060 offset + offsetof(struct cfstring64_t, characters), S, info, n_value); 4061 if (symbol_name == nullptr) 4062 return nullptr; 4063 cfs_characters = n_value; 4064 } else 4065 cfs_characters = cfs.characters; 4066 name = get_pointer_64(cfs_characters, offset, left, S, info); 4067 4068 return name; 4069 } 4070 4071 // get_objc2_64bit_selref() is used for disassembly and is passed a the address 4072 // of a pointer to an Objective-C selector reference when the pointer value is 4073 // zero as in a .o file and is likely to have a external relocation entry with 4074 // who's symbol's n_value is the real pointer to the selector name. If that is 4075 // the case the real pointer to the selector name is returned else 0 is 4076 // returned 4077 static uint64_t get_objc2_64bit_selref(uint64_t ReferenceValue, 4078 struct DisassembleInfo *info) { 4079 uint32_t offset, left; 4080 SectionRef S; 4081 4082 const char *r = get_pointer_64(ReferenceValue, offset, left, S, info); 4083 if (r == nullptr || left < sizeof(uint64_t)) 4084 return 0; 4085 uint64_t n_value; 4086 const char *symbol_name = get_symbol_64(offset, S, info, n_value); 4087 if (symbol_name == nullptr) 4088 return 0; 4089 return n_value; 4090 } 4091 4092 static const SectionRef get_section(MachOObjectFile *O, const char *segname, 4093 const char *sectname) { 4094 for (const SectionRef &Section : O->sections()) { 4095 StringRef SectName; 4096 Expected<StringRef> SecNameOrErr = Section.getName(); 4097 if (SecNameOrErr) 4098 SectName = *SecNameOrErr; 4099 else 4100 consumeError(SecNameOrErr.takeError()); 4101 4102 DataRefImpl Ref = Section.getRawDataRefImpl(); 4103 StringRef SegName = O->getSectionFinalSegmentName(Ref); 4104 if (SegName == segname && SectName == sectname) 4105 return Section; 4106 } 4107 return SectionRef(); 4108 } 4109 4110 static void 4111 walk_pointer_list_64(const char *listname, const SectionRef S, 4112 MachOObjectFile *O, struct DisassembleInfo *info, 4113 void (*func)(uint64_t, struct DisassembleInfo *info)) { 4114 if (S == SectionRef()) 4115 return; 4116 4117 StringRef SectName; 4118 Expected<StringRef> SecNameOrErr = S.getName(); 4119 if (SecNameOrErr) 4120 SectName = *SecNameOrErr; 4121 else 4122 consumeError(SecNameOrErr.takeError()); 4123 4124 DataRefImpl Ref = S.getRawDataRefImpl(); 4125 StringRef SegName = O->getSectionFinalSegmentName(Ref); 4126 outs() << "Contents of (" << SegName << "," << SectName << ") section\n"; 4127 4128 StringRef BytesStr = unwrapOrError(S.getContents(), O->getFileName()); 4129 const char *Contents = reinterpret_cast<const char *>(BytesStr.data()); 4130 4131 for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint64_t)) { 4132 uint32_t left = S.getSize() - i; 4133 uint32_t size = left < sizeof(uint64_t) ? left : sizeof(uint64_t); 4134 uint64_t p = 0; 4135 memcpy(&p, Contents + i, size); 4136 if (i + sizeof(uint64_t) > S.getSize()) 4137 outs() << listname << " list pointer extends past end of (" << SegName 4138 << "," << SectName << ") section\n"; 4139 outs() << format("%016" PRIx64, S.getAddress() + i) << " "; 4140 4141 if (O->isLittleEndian() != sys::IsLittleEndianHost) 4142 sys::swapByteOrder(p); 4143 4144 uint64_t n_value = 0; 4145 const char *name = get_symbol_64(i, S, info, n_value, p); 4146 if (name == nullptr) 4147 name = get_dyld_bind_info_symbolname(S.getAddress() + i, info); 4148 4149 if (n_value != 0) { 4150 outs() << format("0x%" PRIx64, n_value); 4151 if (p != 0) 4152 outs() << " + " << format("0x%" PRIx64, p); 4153 } else 4154 outs() << format("0x%" PRIx64, p); 4155 if (name != nullptr) 4156 outs() << " " << name; 4157 outs() << "\n"; 4158 4159 p += n_value; 4160 if (func) 4161 func(p, info); 4162 } 4163 } 4164 4165 static void 4166 walk_pointer_list_32(const char *listname, const SectionRef S, 4167 MachOObjectFile *O, struct DisassembleInfo *info, 4168 void (*func)(uint32_t, struct DisassembleInfo *info)) { 4169 if (S == SectionRef()) 4170 return; 4171 4172 StringRef SectName = unwrapOrError(S.getName(), O->getFileName()); 4173 DataRefImpl Ref = S.getRawDataRefImpl(); 4174 StringRef SegName = O->getSectionFinalSegmentName(Ref); 4175 outs() << "Contents of (" << SegName << "," << SectName << ") section\n"; 4176 4177 StringRef BytesStr = unwrapOrError(S.getContents(), O->getFileName()); 4178 const char *Contents = reinterpret_cast<const char *>(BytesStr.data()); 4179 4180 for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint32_t)) { 4181 uint32_t left = S.getSize() - i; 4182 uint32_t size = left < sizeof(uint32_t) ? left : sizeof(uint32_t); 4183 uint32_t p = 0; 4184 memcpy(&p, Contents + i, size); 4185 if (i + sizeof(uint32_t) > S.getSize()) 4186 outs() << listname << " list pointer extends past end of (" << SegName 4187 << "," << SectName << ") section\n"; 4188 uint32_t Address = S.getAddress() + i; 4189 outs() << format("%08" PRIx32, Address) << " "; 4190 4191 if (O->isLittleEndian() != sys::IsLittleEndianHost) 4192 sys::swapByteOrder(p); 4193 outs() << format("0x%" PRIx32, p); 4194 4195 const char *name = get_symbol_32(i, S, info, p); 4196 if (name != nullptr) 4197 outs() << " " << name; 4198 outs() << "\n"; 4199 4200 if (func) 4201 func(p, info); 4202 } 4203 } 4204 4205 static void print_layout_map(const char *layout_map, uint32_t left) { 4206 if (layout_map == nullptr) 4207 return; 4208 outs() << " layout map: "; 4209 do { 4210 outs() << format("0x%02" PRIx32, (*layout_map) & 0xff) << " "; 4211 left--; 4212 layout_map++; 4213 } while (*layout_map != '\0' && left != 0); 4214 outs() << "\n"; 4215 } 4216 4217 static void print_layout_map64(uint64_t p, struct DisassembleInfo *info) { 4218 uint32_t offset, left; 4219 SectionRef S; 4220 const char *layout_map; 4221 4222 if (p == 0) 4223 return; 4224 layout_map = get_pointer_64(p, offset, left, S, info); 4225 print_layout_map(layout_map, left); 4226 } 4227 4228 static void print_layout_map32(uint32_t p, struct DisassembleInfo *info) { 4229 uint32_t offset, left; 4230 SectionRef S; 4231 const char *layout_map; 4232 4233 if (p == 0) 4234 return; 4235 layout_map = get_pointer_32(p, offset, left, S, info); 4236 print_layout_map(layout_map, left); 4237 } 4238 4239 static void print_method_list64_t(uint64_t p, struct DisassembleInfo *info, 4240 const char *indent) { 4241 struct method_list64_t ml; 4242 struct method64_t m; 4243 const char *r; 4244 uint32_t offset, xoffset, left, i; 4245 SectionRef S, xS; 4246 const char *name, *sym_name; 4247 uint64_t n_value; 4248 4249 r = get_pointer_64(p, offset, left, S, info); 4250 if (r == nullptr) 4251 return; 4252 memset(&ml, '\0', sizeof(struct method_list64_t)); 4253 if (left < sizeof(struct method_list64_t)) { 4254 memcpy(&ml, r, left); 4255 outs() << " (method_list_t entends past the end of the section)\n"; 4256 } else 4257 memcpy(&ml, r, sizeof(struct method_list64_t)); 4258 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 4259 swapStruct(ml); 4260 outs() << indent << "\t\t entsize " << ml.entsize << "\n"; 4261 outs() << indent << "\t\t count " << ml.count << "\n"; 4262 4263 p += sizeof(struct method_list64_t); 4264 offset += sizeof(struct method_list64_t); 4265 for (i = 0; i < ml.count; i++) { 4266 r = get_pointer_64(p, offset, left, S, info); 4267 if (r == nullptr) 4268 return; 4269 memset(&m, '\0', sizeof(struct method64_t)); 4270 if (left < sizeof(struct method64_t)) { 4271 memcpy(&m, r, left); 4272 outs() << indent << " (method_t extends past the end of the section)\n"; 4273 } else 4274 memcpy(&m, r, sizeof(struct method64_t)); 4275 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 4276 swapStruct(m); 4277 4278 outs() << indent << "\t\t name "; 4279 sym_name = get_symbol_64(offset + offsetof(struct method64_t, name), S, 4280 info, n_value, m.name); 4281 if (n_value != 0) { 4282 if (info->verbose && sym_name != nullptr) 4283 outs() << sym_name; 4284 else 4285 outs() << format("0x%" PRIx64, n_value); 4286 if (m.name != 0) 4287 outs() << " + " << format("0x%" PRIx64, m.name); 4288 } else 4289 outs() << format("0x%" PRIx64, m.name); 4290 name = get_pointer_64(m.name + n_value, xoffset, left, xS, info); 4291 if (name != nullptr) 4292 outs() << format(" %.*s", left, name); 4293 outs() << "\n"; 4294 4295 outs() << indent << "\t\t types "; 4296 sym_name = get_symbol_64(offset + offsetof(struct method64_t, types), S, 4297 info, n_value, m.types); 4298 if (n_value != 0) { 4299 if (info->verbose && sym_name != nullptr) 4300 outs() << sym_name; 4301 else 4302 outs() << format("0x%" PRIx64, n_value); 4303 if (m.types != 0) 4304 outs() << " + " << format("0x%" PRIx64, m.types); 4305 } else 4306 outs() << format("0x%" PRIx64, m.types); 4307 name = get_pointer_64(m.types + n_value, xoffset, left, xS, info); 4308 if (name != nullptr) 4309 outs() << format(" %.*s", left, name); 4310 outs() << "\n"; 4311 4312 outs() << indent << "\t\t imp "; 4313 name = get_symbol_64(offset + offsetof(struct method64_t, imp), S, info, 4314 n_value, m.imp); 4315 if (info->verbose && name == nullptr) { 4316 if (n_value != 0) { 4317 outs() << format("0x%" PRIx64, n_value) << " "; 4318 if (m.imp != 0) 4319 outs() << "+ " << format("0x%" PRIx64, m.imp) << " "; 4320 } else 4321 outs() << format("0x%" PRIx64, m.imp) << " "; 4322 } 4323 if (name != nullptr) 4324 outs() << name; 4325 outs() << "\n"; 4326 4327 p += sizeof(struct method64_t); 4328 offset += sizeof(struct method64_t); 4329 } 4330 } 4331 4332 static void print_method_list32_t(uint64_t p, struct DisassembleInfo *info, 4333 const char *indent) { 4334 struct method_list32_t ml; 4335 struct method32_t m; 4336 const char *r, *name; 4337 uint32_t offset, xoffset, left, i; 4338 SectionRef S, xS; 4339 4340 r = get_pointer_32(p, offset, left, S, info); 4341 if (r == nullptr) 4342 return; 4343 memset(&ml, '\0', sizeof(struct method_list32_t)); 4344 if (left < sizeof(struct method_list32_t)) { 4345 memcpy(&ml, r, left); 4346 outs() << " (method_list_t entends past the end of the section)\n"; 4347 } else 4348 memcpy(&ml, r, sizeof(struct method_list32_t)); 4349 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 4350 swapStruct(ml); 4351 outs() << indent << "\t\t entsize " << ml.entsize << "\n"; 4352 outs() << indent << "\t\t count " << ml.count << "\n"; 4353 4354 p += sizeof(struct method_list32_t); 4355 offset += sizeof(struct method_list32_t); 4356 for (i = 0; i < ml.count; i++) { 4357 r = get_pointer_32(p, offset, left, S, info); 4358 if (r == nullptr) 4359 return; 4360 memset(&m, '\0', sizeof(struct method32_t)); 4361 if (left < sizeof(struct method32_t)) { 4362 memcpy(&ml, r, left); 4363 outs() << indent << " (method_t entends past the end of the section)\n"; 4364 } else 4365 memcpy(&m, r, sizeof(struct method32_t)); 4366 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 4367 swapStruct(m); 4368 4369 outs() << indent << "\t\t name " << format("0x%" PRIx32, m.name); 4370 name = get_pointer_32(m.name, xoffset, left, xS, info); 4371 if (name != nullptr) 4372 outs() << format(" %.*s", left, name); 4373 outs() << "\n"; 4374 4375 outs() << indent << "\t\t types " << format("0x%" PRIx32, m.types); 4376 name = get_pointer_32(m.types, xoffset, left, xS, info); 4377 if (name != nullptr) 4378 outs() << format(" %.*s", left, name); 4379 outs() << "\n"; 4380 4381 outs() << indent << "\t\t imp " << format("0x%" PRIx32, m.imp); 4382 name = get_symbol_32(offset + offsetof(struct method32_t, imp), S, info, 4383 m.imp); 4384 if (name != nullptr) 4385 outs() << " " << name; 4386 outs() << "\n"; 4387 4388 p += sizeof(struct method32_t); 4389 offset += sizeof(struct method32_t); 4390 } 4391 } 4392 4393 static bool print_method_list(uint32_t p, struct DisassembleInfo *info) { 4394 uint32_t offset, left, xleft; 4395 SectionRef S; 4396 struct objc_method_list_t method_list; 4397 struct objc_method_t method; 4398 const char *r, *methods, *name, *SymbolName; 4399 int32_t i; 4400 4401 r = get_pointer_32(p, offset, left, S, info, true); 4402 if (r == nullptr) 4403 return true; 4404 4405 outs() << "\n"; 4406 if (left > sizeof(struct objc_method_list_t)) { 4407 memcpy(&method_list, r, sizeof(struct objc_method_list_t)); 4408 } else { 4409 outs() << "\t\t objc_method_list extends past end of the section\n"; 4410 memset(&method_list, '\0', sizeof(struct objc_method_list_t)); 4411 memcpy(&method_list, r, left); 4412 } 4413 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 4414 swapStruct(method_list); 4415 4416 outs() << "\t\t obsolete " 4417 << format("0x%08" PRIx32, method_list.obsolete) << "\n"; 4418 outs() << "\t\t method_count " << method_list.method_count << "\n"; 4419 4420 methods = r + sizeof(struct objc_method_list_t); 4421 for (i = 0; i < method_list.method_count; i++) { 4422 if ((i + 1) * sizeof(struct objc_method_t) > left) { 4423 outs() << "\t\t remaining method's extend past the of the section\n"; 4424 break; 4425 } 4426 memcpy(&method, methods + i * sizeof(struct objc_method_t), 4427 sizeof(struct objc_method_t)); 4428 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 4429 swapStruct(method); 4430 4431 outs() << "\t\t method_name " 4432 << format("0x%08" PRIx32, method.method_name); 4433 if (info->verbose) { 4434 name = get_pointer_32(method.method_name, offset, xleft, S, info, true); 4435 if (name != nullptr) 4436 outs() << format(" %.*s", xleft, name); 4437 else 4438 outs() << " (not in an __OBJC section)"; 4439 } 4440 outs() << "\n"; 4441 4442 outs() << "\t\t method_types " 4443 << format("0x%08" PRIx32, method.method_types); 4444 if (info->verbose) { 4445 name = get_pointer_32(method.method_types, offset, xleft, S, info, true); 4446 if (name != nullptr) 4447 outs() << format(" %.*s", xleft, name); 4448 else 4449 outs() << " (not in an __OBJC section)"; 4450 } 4451 outs() << "\n"; 4452 4453 outs() << "\t\t method_imp " 4454 << format("0x%08" PRIx32, method.method_imp) << " "; 4455 if (info->verbose) { 4456 SymbolName = GuessSymbolName(method.method_imp, info->AddrMap); 4457 if (SymbolName != nullptr) 4458 outs() << SymbolName; 4459 } 4460 outs() << "\n"; 4461 } 4462 return false; 4463 } 4464 4465 static void print_protocol_list64_t(uint64_t p, struct DisassembleInfo *info) { 4466 struct protocol_list64_t pl; 4467 uint64_t q, n_value; 4468 struct protocol64_t pc; 4469 const char *r; 4470 uint32_t offset, xoffset, left, i; 4471 SectionRef S, xS; 4472 const char *name, *sym_name; 4473 4474 r = get_pointer_64(p, offset, left, S, info); 4475 if (r == nullptr) 4476 return; 4477 memset(&pl, '\0', sizeof(struct protocol_list64_t)); 4478 if (left < sizeof(struct protocol_list64_t)) { 4479 memcpy(&pl, r, left); 4480 outs() << " (protocol_list_t entends past the end of the section)\n"; 4481 } else 4482 memcpy(&pl, r, sizeof(struct protocol_list64_t)); 4483 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 4484 swapStruct(pl); 4485 outs() << " count " << pl.count << "\n"; 4486 4487 p += sizeof(struct protocol_list64_t); 4488 offset += sizeof(struct protocol_list64_t); 4489 for (i = 0; i < pl.count; i++) { 4490 r = get_pointer_64(p, offset, left, S, info); 4491 if (r == nullptr) 4492 return; 4493 q = 0; 4494 if (left < sizeof(uint64_t)) { 4495 memcpy(&q, r, left); 4496 outs() << " (protocol_t * entends past the end of the section)\n"; 4497 } else 4498 memcpy(&q, r, sizeof(uint64_t)); 4499 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 4500 sys::swapByteOrder(q); 4501 4502 outs() << "\t\t list[" << i << "] "; 4503 sym_name = get_symbol_64(offset, S, info, n_value, q); 4504 if (n_value != 0) { 4505 if (info->verbose && sym_name != nullptr) 4506 outs() << sym_name; 4507 else 4508 outs() << format("0x%" PRIx64, n_value); 4509 if (q != 0) 4510 outs() << " + " << format("0x%" PRIx64, q); 4511 } else 4512 outs() << format("0x%" PRIx64, q); 4513 outs() << " (struct protocol_t *)\n"; 4514 4515 r = get_pointer_64(q + n_value, offset, left, S, info); 4516 if (r == nullptr) 4517 return; 4518 memset(&pc, '\0', sizeof(struct protocol64_t)); 4519 if (left < sizeof(struct protocol64_t)) { 4520 memcpy(&pc, r, left); 4521 outs() << " (protocol_t entends past the end of the section)\n"; 4522 } else 4523 memcpy(&pc, r, sizeof(struct protocol64_t)); 4524 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 4525 swapStruct(pc); 4526 4527 outs() << "\t\t\t isa " << format("0x%" PRIx64, pc.isa) << "\n"; 4528 4529 outs() << "\t\t\t name "; 4530 sym_name = get_symbol_64(offset + offsetof(struct protocol64_t, name), S, 4531 info, n_value, pc.name); 4532 if (n_value != 0) { 4533 if (info->verbose && sym_name != nullptr) 4534 outs() << sym_name; 4535 else 4536 outs() << format("0x%" PRIx64, n_value); 4537 if (pc.name != 0) 4538 outs() << " + " << format("0x%" PRIx64, pc.name); 4539 } else 4540 outs() << format("0x%" PRIx64, pc.name); 4541 name = get_pointer_64(pc.name + n_value, xoffset, left, xS, info); 4542 if (name != nullptr) 4543 outs() << format(" %.*s", left, name); 4544 outs() << "\n"; 4545 4546 outs() << "\t\t\tprotocols " << format("0x%" PRIx64, pc.protocols) << "\n"; 4547 4548 outs() << "\t\t instanceMethods "; 4549 sym_name = 4550 get_symbol_64(offset + offsetof(struct protocol64_t, instanceMethods), 4551 S, info, n_value, pc.instanceMethods); 4552 if (n_value != 0) { 4553 if (info->verbose && sym_name != nullptr) 4554 outs() << sym_name; 4555 else 4556 outs() << format("0x%" PRIx64, n_value); 4557 if (pc.instanceMethods != 0) 4558 outs() << " + " << format("0x%" PRIx64, pc.instanceMethods); 4559 } else 4560 outs() << format("0x%" PRIx64, pc.instanceMethods); 4561 outs() << " (struct method_list_t *)\n"; 4562 if (pc.instanceMethods + n_value != 0) 4563 print_method_list64_t(pc.instanceMethods + n_value, info, "\t"); 4564 4565 outs() << "\t\t classMethods "; 4566 sym_name = 4567 get_symbol_64(offset + offsetof(struct protocol64_t, classMethods), S, 4568 info, n_value, pc.classMethods); 4569 if (n_value != 0) { 4570 if (info->verbose && sym_name != nullptr) 4571 outs() << sym_name; 4572 else 4573 outs() << format("0x%" PRIx64, n_value); 4574 if (pc.classMethods != 0) 4575 outs() << " + " << format("0x%" PRIx64, pc.classMethods); 4576 } else 4577 outs() << format("0x%" PRIx64, pc.classMethods); 4578 outs() << " (struct method_list_t *)\n"; 4579 if (pc.classMethods + n_value != 0) 4580 print_method_list64_t(pc.classMethods + n_value, info, "\t"); 4581 4582 outs() << "\t optionalInstanceMethods " 4583 << format("0x%" PRIx64, pc.optionalInstanceMethods) << "\n"; 4584 outs() << "\t optionalClassMethods " 4585 << format("0x%" PRIx64, pc.optionalClassMethods) << "\n"; 4586 outs() << "\t instanceProperties " 4587 << format("0x%" PRIx64, pc.instanceProperties) << "\n"; 4588 4589 p += sizeof(uint64_t); 4590 offset += sizeof(uint64_t); 4591 } 4592 } 4593 4594 static void print_protocol_list32_t(uint32_t p, struct DisassembleInfo *info) { 4595 struct protocol_list32_t pl; 4596 uint32_t q; 4597 struct protocol32_t pc; 4598 const char *r; 4599 uint32_t offset, xoffset, left, i; 4600 SectionRef S, xS; 4601 const char *name; 4602 4603 r = get_pointer_32(p, offset, left, S, info); 4604 if (r == nullptr) 4605 return; 4606 memset(&pl, '\0', sizeof(struct protocol_list32_t)); 4607 if (left < sizeof(struct protocol_list32_t)) { 4608 memcpy(&pl, r, left); 4609 outs() << " (protocol_list_t entends past the end of the section)\n"; 4610 } else 4611 memcpy(&pl, r, sizeof(struct protocol_list32_t)); 4612 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 4613 swapStruct(pl); 4614 outs() << " count " << pl.count << "\n"; 4615 4616 p += sizeof(struct protocol_list32_t); 4617 offset += sizeof(struct protocol_list32_t); 4618 for (i = 0; i < pl.count; i++) { 4619 r = get_pointer_32(p, offset, left, S, info); 4620 if (r == nullptr) 4621 return; 4622 q = 0; 4623 if (left < sizeof(uint32_t)) { 4624 memcpy(&q, r, left); 4625 outs() << " (protocol_t * entends past the end of the section)\n"; 4626 } else 4627 memcpy(&q, r, sizeof(uint32_t)); 4628 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 4629 sys::swapByteOrder(q); 4630 outs() << "\t\t list[" << i << "] " << format("0x%" PRIx32, q) 4631 << " (struct protocol_t *)\n"; 4632 r = get_pointer_32(q, offset, left, S, info); 4633 if (r == nullptr) 4634 return; 4635 memset(&pc, '\0', sizeof(struct protocol32_t)); 4636 if (left < sizeof(struct protocol32_t)) { 4637 memcpy(&pc, r, left); 4638 outs() << " (protocol_t entends past the end of the section)\n"; 4639 } else 4640 memcpy(&pc, r, sizeof(struct protocol32_t)); 4641 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 4642 swapStruct(pc); 4643 outs() << "\t\t\t isa " << format("0x%" PRIx32, pc.isa) << "\n"; 4644 outs() << "\t\t\t name " << format("0x%" PRIx32, pc.name); 4645 name = get_pointer_32(pc.name, xoffset, left, xS, info); 4646 if (name != nullptr) 4647 outs() << format(" %.*s", left, name); 4648 outs() << "\n"; 4649 outs() << "\t\t\tprotocols " << format("0x%" PRIx32, pc.protocols) << "\n"; 4650 outs() << "\t\t instanceMethods " 4651 << format("0x%" PRIx32, pc.instanceMethods) 4652 << " (struct method_list_t *)\n"; 4653 if (pc.instanceMethods != 0) 4654 print_method_list32_t(pc.instanceMethods, info, "\t"); 4655 outs() << "\t\t classMethods " << format("0x%" PRIx32, pc.classMethods) 4656 << " (struct method_list_t *)\n"; 4657 if (pc.classMethods != 0) 4658 print_method_list32_t(pc.classMethods, info, "\t"); 4659 outs() << "\t optionalInstanceMethods " 4660 << format("0x%" PRIx32, pc.optionalInstanceMethods) << "\n"; 4661 outs() << "\t optionalClassMethods " 4662 << format("0x%" PRIx32, pc.optionalClassMethods) << "\n"; 4663 outs() << "\t instanceProperties " 4664 << format("0x%" PRIx32, pc.instanceProperties) << "\n"; 4665 p += sizeof(uint32_t); 4666 offset += sizeof(uint32_t); 4667 } 4668 } 4669 4670 static void print_indent(uint32_t indent) { 4671 for (uint32_t i = 0; i < indent;) { 4672 if (indent - i >= 8) { 4673 outs() << "\t"; 4674 i += 8; 4675 } else { 4676 for (uint32_t j = i; j < indent; j++) 4677 outs() << " "; 4678 return; 4679 } 4680 } 4681 } 4682 4683 static bool print_method_description_list(uint32_t p, uint32_t indent, 4684 struct DisassembleInfo *info) { 4685 uint32_t offset, left, xleft; 4686 SectionRef S; 4687 struct objc_method_description_list_t mdl; 4688 struct objc_method_description_t md; 4689 const char *r, *list, *name; 4690 int32_t i; 4691 4692 r = get_pointer_32(p, offset, left, S, info, true); 4693 if (r == nullptr) 4694 return true; 4695 4696 outs() << "\n"; 4697 if (left > sizeof(struct objc_method_description_list_t)) { 4698 memcpy(&mdl, r, sizeof(struct objc_method_description_list_t)); 4699 } else { 4700 print_indent(indent); 4701 outs() << " objc_method_description_list extends past end of the section\n"; 4702 memset(&mdl, '\0', sizeof(struct objc_method_description_list_t)); 4703 memcpy(&mdl, r, left); 4704 } 4705 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 4706 swapStruct(mdl); 4707 4708 print_indent(indent); 4709 outs() << " count " << mdl.count << "\n"; 4710 4711 list = r + sizeof(struct objc_method_description_list_t); 4712 for (i = 0; i < mdl.count; i++) { 4713 if ((i + 1) * sizeof(struct objc_method_description_t) > left) { 4714 print_indent(indent); 4715 outs() << " remaining list entries extend past the of the section\n"; 4716 break; 4717 } 4718 print_indent(indent); 4719 outs() << " list[" << i << "]\n"; 4720 memcpy(&md, list + i * sizeof(struct objc_method_description_t), 4721 sizeof(struct objc_method_description_t)); 4722 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 4723 swapStruct(md); 4724 4725 print_indent(indent); 4726 outs() << " name " << format("0x%08" PRIx32, md.name); 4727 if (info->verbose) { 4728 name = get_pointer_32(md.name, offset, xleft, S, info, true); 4729 if (name != nullptr) 4730 outs() << format(" %.*s", xleft, name); 4731 else 4732 outs() << " (not in an __OBJC section)"; 4733 } 4734 outs() << "\n"; 4735 4736 print_indent(indent); 4737 outs() << " types " << format("0x%08" PRIx32, md.types); 4738 if (info->verbose) { 4739 name = get_pointer_32(md.types, offset, xleft, S, info, true); 4740 if (name != nullptr) 4741 outs() << format(" %.*s", xleft, name); 4742 else 4743 outs() << " (not in an __OBJC section)"; 4744 } 4745 outs() << "\n"; 4746 } 4747 return false; 4748 } 4749 4750 static bool print_protocol_list(uint32_t p, uint32_t indent, 4751 struct DisassembleInfo *info); 4752 4753 static bool print_protocol(uint32_t p, uint32_t indent, 4754 struct DisassembleInfo *info) { 4755 uint32_t offset, left; 4756 SectionRef S; 4757 struct objc_protocol_t protocol; 4758 const char *r, *name; 4759 4760 r = get_pointer_32(p, offset, left, S, info, true); 4761 if (r == nullptr) 4762 return true; 4763 4764 outs() << "\n"; 4765 if (left >= sizeof(struct objc_protocol_t)) { 4766 memcpy(&protocol, r, sizeof(struct objc_protocol_t)); 4767 } else { 4768 print_indent(indent); 4769 outs() << " Protocol extends past end of the section\n"; 4770 memset(&protocol, '\0', sizeof(struct objc_protocol_t)); 4771 memcpy(&protocol, r, left); 4772 } 4773 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 4774 swapStruct(protocol); 4775 4776 print_indent(indent); 4777 outs() << " isa " << format("0x%08" PRIx32, protocol.isa) 4778 << "\n"; 4779 4780 print_indent(indent); 4781 outs() << " protocol_name " 4782 << format("0x%08" PRIx32, protocol.protocol_name); 4783 if (info->verbose) { 4784 name = get_pointer_32(protocol.protocol_name, offset, left, S, info, true); 4785 if (name != nullptr) 4786 outs() << format(" %.*s", left, name); 4787 else 4788 outs() << " (not in an __OBJC section)"; 4789 } 4790 outs() << "\n"; 4791 4792 print_indent(indent); 4793 outs() << " protocol_list " 4794 << format("0x%08" PRIx32, protocol.protocol_list); 4795 if (print_protocol_list(protocol.protocol_list, indent + 4, info)) 4796 outs() << " (not in an __OBJC section)\n"; 4797 4798 print_indent(indent); 4799 outs() << " instance_methods " 4800 << format("0x%08" PRIx32, protocol.instance_methods); 4801 if (print_method_description_list(protocol.instance_methods, indent, info)) 4802 outs() << " (not in an __OBJC section)\n"; 4803 4804 print_indent(indent); 4805 outs() << " class_methods " 4806 << format("0x%08" PRIx32, protocol.class_methods); 4807 if (print_method_description_list(protocol.class_methods, indent, info)) 4808 outs() << " (not in an __OBJC section)\n"; 4809 4810 return false; 4811 } 4812 4813 static bool print_protocol_list(uint32_t p, uint32_t indent, 4814 struct DisassembleInfo *info) { 4815 uint32_t offset, left, l; 4816 SectionRef S; 4817 struct objc_protocol_list_t protocol_list; 4818 const char *r, *list; 4819 int32_t i; 4820 4821 r = get_pointer_32(p, offset, left, S, info, true); 4822 if (r == nullptr) 4823 return true; 4824 4825 outs() << "\n"; 4826 if (left > sizeof(struct objc_protocol_list_t)) { 4827 memcpy(&protocol_list, r, sizeof(struct objc_protocol_list_t)); 4828 } else { 4829 outs() << "\t\t objc_protocol_list_t extends past end of the section\n"; 4830 memset(&protocol_list, '\0', sizeof(struct objc_protocol_list_t)); 4831 memcpy(&protocol_list, r, left); 4832 } 4833 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 4834 swapStruct(protocol_list); 4835 4836 print_indent(indent); 4837 outs() << " next " << format("0x%08" PRIx32, protocol_list.next) 4838 << "\n"; 4839 print_indent(indent); 4840 outs() << " count " << protocol_list.count << "\n"; 4841 4842 list = r + sizeof(struct objc_protocol_list_t); 4843 for (i = 0; i < protocol_list.count; i++) { 4844 if ((i + 1) * sizeof(uint32_t) > left) { 4845 outs() << "\t\t remaining list entries extend past the of the section\n"; 4846 break; 4847 } 4848 memcpy(&l, list + i * sizeof(uint32_t), sizeof(uint32_t)); 4849 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 4850 sys::swapByteOrder(l); 4851 4852 print_indent(indent); 4853 outs() << " list[" << i << "] " << format("0x%08" PRIx32, l); 4854 if (print_protocol(l, indent, info)) 4855 outs() << "(not in an __OBJC section)\n"; 4856 } 4857 return false; 4858 } 4859 4860 static void print_ivar_list64_t(uint64_t p, struct DisassembleInfo *info) { 4861 struct ivar_list64_t il; 4862 struct ivar64_t i; 4863 const char *r; 4864 uint32_t offset, xoffset, left, j; 4865 SectionRef S, xS; 4866 const char *name, *sym_name, *ivar_offset_p; 4867 uint64_t ivar_offset, n_value; 4868 4869 r = get_pointer_64(p, offset, left, S, info); 4870 if (r == nullptr) 4871 return; 4872 memset(&il, '\0', sizeof(struct ivar_list64_t)); 4873 if (left < sizeof(struct ivar_list64_t)) { 4874 memcpy(&il, r, left); 4875 outs() << " (ivar_list_t entends past the end of the section)\n"; 4876 } else 4877 memcpy(&il, r, sizeof(struct ivar_list64_t)); 4878 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 4879 swapStruct(il); 4880 outs() << " entsize " << il.entsize << "\n"; 4881 outs() << " count " << il.count << "\n"; 4882 4883 p += sizeof(struct ivar_list64_t); 4884 offset += sizeof(struct ivar_list64_t); 4885 for (j = 0; j < il.count; j++) { 4886 r = get_pointer_64(p, offset, left, S, info); 4887 if (r == nullptr) 4888 return; 4889 memset(&i, '\0', sizeof(struct ivar64_t)); 4890 if (left < sizeof(struct ivar64_t)) { 4891 memcpy(&i, r, left); 4892 outs() << " (ivar_t entends past the end of the section)\n"; 4893 } else 4894 memcpy(&i, r, sizeof(struct ivar64_t)); 4895 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 4896 swapStruct(i); 4897 4898 outs() << "\t\t\t offset "; 4899 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, offset), S, 4900 info, n_value, i.offset); 4901 if (n_value != 0) { 4902 if (info->verbose && sym_name != nullptr) 4903 outs() << sym_name; 4904 else 4905 outs() << format("0x%" PRIx64, n_value); 4906 if (i.offset != 0) 4907 outs() << " + " << format("0x%" PRIx64, i.offset); 4908 } else 4909 outs() << format("0x%" PRIx64, i.offset); 4910 ivar_offset_p = get_pointer_64(i.offset + n_value, xoffset, left, xS, info); 4911 if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) { 4912 memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset)); 4913 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 4914 sys::swapByteOrder(ivar_offset); 4915 outs() << " " << ivar_offset << "\n"; 4916 } else 4917 outs() << "\n"; 4918 4919 outs() << "\t\t\t name "; 4920 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, name), S, info, 4921 n_value, i.name); 4922 if (n_value != 0) { 4923 if (info->verbose && sym_name != nullptr) 4924 outs() << sym_name; 4925 else 4926 outs() << format("0x%" PRIx64, n_value); 4927 if (i.name != 0) 4928 outs() << " + " << format("0x%" PRIx64, i.name); 4929 } else 4930 outs() << format("0x%" PRIx64, i.name); 4931 name = get_pointer_64(i.name + n_value, xoffset, left, xS, info); 4932 if (name != nullptr) 4933 outs() << format(" %.*s", left, name); 4934 outs() << "\n"; 4935 4936 outs() << "\t\t\t type "; 4937 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, type), S, info, 4938 n_value, i.name); 4939 name = get_pointer_64(i.type + n_value, xoffset, left, xS, info); 4940 if (n_value != 0) { 4941 if (info->verbose && sym_name != nullptr) 4942 outs() << sym_name; 4943 else 4944 outs() << format("0x%" PRIx64, n_value); 4945 if (i.type != 0) 4946 outs() << " + " << format("0x%" PRIx64, i.type); 4947 } else 4948 outs() << format("0x%" PRIx64, i.type); 4949 if (name != nullptr) 4950 outs() << format(" %.*s", left, name); 4951 outs() << "\n"; 4952 4953 outs() << "\t\t\talignment " << i.alignment << "\n"; 4954 outs() << "\t\t\t size " << i.size << "\n"; 4955 4956 p += sizeof(struct ivar64_t); 4957 offset += sizeof(struct ivar64_t); 4958 } 4959 } 4960 4961 static void print_ivar_list32_t(uint32_t p, struct DisassembleInfo *info) { 4962 struct ivar_list32_t il; 4963 struct ivar32_t i; 4964 const char *r; 4965 uint32_t offset, xoffset, left, j; 4966 SectionRef S, xS; 4967 const char *name, *ivar_offset_p; 4968 uint32_t ivar_offset; 4969 4970 r = get_pointer_32(p, offset, left, S, info); 4971 if (r == nullptr) 4972 return; 4973 memset(&il, '\0', sizeof(struct ivar_list32_t)); 4974 if (left < sizeof(struct ivar_list32_t)) { 4975 memcpy(&il, r, left); 4976 outs() << " (ivar_list_t entends past the end of the section)\n"; 4977 } else 4978 memcpy(&il, r, sizeof(struct ivar_list32_t)); 4979 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 4980 swapStruct(il); 4981 outs() << " entsize " << il.entsize << "\n"; 4982 outs() << " count " << il.count << "\n"; 4983 4984 p += sizeof(struct ivar_list32_t); 4985 offset += sizeof(struct ivar_list32_t); 4986 for (j = 0; j < il.count; j++) { 4987 r = get_pointer_32(p, offset, left, S, info); 4988 if (r == nullptr) 4989 return; 4990 memset(&i, '\0', sizeof(struct ivar32_t)); 4991 if (left < sizeof(struct ivar32_t)) { 4992 memcpy(&i, r, left); 4993 outs() << " (ivar_t entends past the end of the section)\n"; 4994 } else 4995 memcpy(&i, r, sizeof(struct ivar32_t)); 4996 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 4997 swapStruct(i); 4998 4999 outs() << "\t\t\t offset " << format("0x%" PRIx32, i.offset); 5000 ivar_offset_p = get_pointer_32(i.offset, xoffset, left, xS, info); 5001 if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) { 5002 memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset)); 5003 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 5004 sys::swapByteOrder(ivar_offset); 5005 outs() << " " << ivar_offset << "\n"; 5006 } else 5007 outs() << "\n"; 5008 5009 outs() << "\t\t\t name " << format("0x%" PRIx32, i.name); 5010 name = get_pointer_32(i.name, xoffset, left, xS, info); 5011 if (name != nullptr) 5012 outs() << format(" %.*s", left, name); 5013 outs() << "\n"; 5014 5015 outs() << "\t\t\t type " << format("0x%" PRIx32, i.type); 5016 name = get_pointer_32(i.type, xoffset, left, xS, info); 5017 if (name != nullptr) 5018 outs() << format(" %.*s", left, name); 5019 outs() << "\n"; 5020 5021 outs() << "\t\t\talignment " << i.alignment << "\n"; 5022 outs() << "\t\t\t size " << i.size << "\n"; 5023 5024 p += sizeof(struct ivar32_t); 5025 offset += sizeof(struct ivar32_t); 5026 } 5027 } 5028 5029 static void print_objc_property_list64(uint64_t p, 5030 struct DisassembleInfo *info) { 5031 struct objc_property_list64 opl; 5032 struct objc_property64 op; 5033 const char *r; 5034 uint32_t offset, xoffset, left, j; 5035 SectionRef S, xS; 5036 const char *name, *sym_name; 5037 uint64_t n_value; 5038 5039 r = get_pointer_64(p, offset, left, S, info); 5040 if (r == nullptr) 5041 return; 5042 memset(&opl, '\0', sizeof(struct objc_property_list64)); 5043 if (left < sizeof(struct objc_property_list64)) { 5044 memcpy(&opl, r, left); 5045 outs() << " (objc_property_list entends past the end of the section)\n"; 5046 } else 5047 memcpy(&opl, r, sizeof(struct objc_property_list64)); 5048 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 5049 swapStruct(opl); 5050 outs() << " entsize " << opl.entsize << "\n"; 5051 outs() << " count " << opl.count << "\n"; 5052 5053 p += sizeof(struct objc_property_list64); 5054 offset += sizeof(struct objc_property_list64); 5055 for (j = 0; j < opl.count; j++) { 5056 r = get_pointer_64(p, offset, left, S, info); 5057 if (r == nullptr) 5058 return; 5059 memset(&op, '\0', sizeof(struct objc_property64)); 5060 if (left < sizeof(struct objc_property64)) { 5061 memcpy(&op, r, left); 5062 outs() << " (objc_property entends past the end of the section)\n"; 5063 } else 5064 memcpy(&op, r, sizeof(struct objc_property64)); 5065 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 5066 swapStruct(op); 5067 5068 outs() << "\t\t\t name "; 5069 sym_name = get_symbol_64(offset + offsetof(struct objc_property64, name), S, 5070 info, n_value, op.name); 5071 if (n_value != 0) { 5072 if (info->verbose && sym_name != nullptr) 5073 outs() << sym_name; 5074 else 5075 outs() << format("0x%" PRIx64, n_value); 5076 if (op.name != 0) 5077 outs() << " + " << format("0x%" PRIx64, op.name); 5078 } else 5079 outs() << format("0x%" PRIx64, op.name); 5080 name = get_pointer_64(op.name + n_value, xoffset, left, xS, info); 5081 if (name != nullptr) 5082 outs() << format(" %.*s", left, name); 5083 outs() << "\n"; 5084 5085 outs() << "\t\t\tattributes "; 5086 sym_name = 5087 get_symbol_64(offset + offsetof(struct objc_property64, attributes), S, 5088 info, n_value, op.attributes); 5089 if (n_value != 0) { 5090 if (info->verbose && sym_name != nullptr) 5091 outs() << sym_name; 5092 else 5093 outs() << format("0x%" PRIx64, n_value); 5094 if (op.attributes != 0) 5095 outs() << " + " << format("0x%" PRIx64, op.attributes); 5096 } else 5097 outs() << format("0x%" PRIx64, op.attributes); 5098 name = get_pointer_64(op.attributes + n_value, xoffset, left, xS, info); 5099 if (name != nullptr) 5100 outs() << format(" %.*s", left, name); 5101 outs() << "\n"; 5102 5103 p += sizeof(struct objc_property64); 5104 offset += sizeof(struct objc_property64); 5105 } 5106 } 5107 5108 static void print_objc_property_list32(uint32_t p, 5109 struct DisassembleInfo *info) { 5110 struct objc_property_list32 opl; 5111 struct objc_property32 op; 5112 const char *r; 5113 uint32_t offset, xoffset, left, j; 5114 SectionRef S, xS; 5115 const char *name; 5116 5117 r = get_pointer_32(p, offset, left, S, info); 5118 if (r == nullptr) 5119 return; 5120 memset(&opl, '\0', sizeof(struct objc_property_list32)); 5121 if (left < sizeof(struct objc_property_list32)) { 5122 memcpy(&opl, r, left); 5123 outs() << " (objc_property_list entends past the end of the section)\n"; 5124 } else 5125 memcpy(&opl, r, sizeof(struct objc_property_list32)); 5126 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 5127 swapStruct(opl); 5128 outs() << " entsize " << opl.entsize << "\n"; 5129 outs() << " count " << opl.count << "\n"; 5130 5131 p += sizeof(struct objc_property_list32); 5132 offset += sizeof(struct objc_property_list32); 5133 for (j = 0; j < opl.count; j++) { 5134 r = get_pointer_32(p, offset, left, S, info); 5135 if (r == nullptr) 5136 return; 5137 memset(&op, '\0', sizeof(struct objc_property32)); 5138 if (left < sizeof(struct objc_property32)) { 5139 memcpy(&op, r, left); 5140 outs() << " (objc_property entends past the end of the section)\n"; 5141 } else 5142 memcpy(&op, r, sizeof(struct objc_property32)); 5143 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 5144 swapStruct(op); 5145 5146 outs() << "\t\t\t name " << format("0x%" PRIx32, op.name); 5147 name = get_pointer_32(op.name, xoffset, left, xS, info); 5148 if (name != nullptr) 5149 outs() << format(" %.*s", left, name); 5150 outs() << "\n"; 5151 5152 outs() << "\t\t\tattributes " << format("0x%" PRIx32, op.attributes); 5153 name = get_pointer_32(op.attributes, xoffset, left, xS, info); 5154 if (name != nullptr) 5155 outs() << format(" %.*s", left, name); 5156 outs() << "\n"; 5157 5158 p += sizeof(struct objc_property32); 5159 offset += sizeof(struct objc_property32); 5160 } 5161 } 5162 5163 static bool print_class_ro64_t(uint64_t p, struct DisassembleInfo *info, 5164 bool &is_meta_class) { 5165 struct class_ro64_t cro; 5166 const char *r; 5167 uint32_t offset, xoffset, left; 5168 SectionRef S, xS; 5169 const char *name, *sym_name; 5170 uint64_t n_value; 5171 5172 r = get_pointer_64(p, offset, left, S, info); 5173 if (r == nullptr || left < sizeof(struct class_ro64_t)) 5174 return false; 5175 memcpy(&cro, r, sizeof(struct class_ro64_t)); 5176 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 5177 swapStruct(cro); 5178 outs() << " flags " << format("0x%" PRIx32, cro.flags); 5179 if (cro.flags & RO_META) 5180 outs() << " RO_META"; 5181 if (cro.flags & RO_ROOT) 5182 outs() << " RO_ROOT"; 5183 if (cro.flags & RO_HAS_CXX_STRUCTORS) 5184 outs() << " RO_HAS_CXX_STRUCTORS"; 5185 outs() << "\n"; 5186 outs() << " instanceStart " << cro.instanceStart << "\n"; 5187 outs() << " instanceSize " << cro.instanceSize << "\n"; 5188 outs() << " reserved " << format("0x%" PRIx32, cro.reserved) 5189 << "\n"; 5190 outs() << " ivarLayout " << format("0x%" PRIx64, cro.ivarLayout) 5191 << "\n"; 5192 print_layout_map64(cro.ivarLayout, info); 5193 5194 outs() << " name "; 5195 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, name), S, 5196 info, n_value, cro.name); 5197 if (n_value != 0) { 5198 if (info->verbose && sym_name != nullptr) 5199 outs() << sym_name; 5200 else 5201 outs() << format("0x%" PRIx64, n_value); 5202 if (cro.name != 0) 5203 outs() << " + " << format("0x%" PRIx64, cro.name); 5204 } else 5205 outs() << format("0x%" PRIx64, cro.name); 5206 name = get_pointer_64(cro.name + n_value, xoffset, left, xS, info); 5207 if (name != nullptr) 5208 outs() << format(" %.*s", left, name); 5209 outs() << "\n"; 5210 5211 outs() << " baseMethods "; 5212 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, baseMethods), 5213 S, info, n_value, cro.baseMethods); 5214 if (n_value != 0) { 5215 if (info->verbose && sym_name != nullptr) 5216 outs() << sym_name; 5217 else 5218 outs() << format("0x%" PRIx64, n_value); 5219 if (cro.baseMethods != 0) 5220 outs() << " + " << format("0x%" PRIx64, cro.baseMethods); 5221 } else 5222 outs() << format("0x%" PRIx64, cro.baseMethods); 5223 outs() << " (struct method_list_t *)\n"; 5224 if (cro.baseMethods + n_value != 0) 5225 print_method_list64_t(cro.baseMethods + n_value, info, ""); 5226 5227 outs() << " baseProtocols "; 5228 sym_name = 5229 get_symbol_64(offset + offsetof(struct class_ro64_t, baseProtocols), S, 5230 info, n_value, cro.baseProtocols); 5231 if (n_value != 0) { 5232 if (info->verbose && sym_name != nullptr) 5233 outs() << sym_name; 5234 else 5235 outs() << format("0x%" PRIx64, n_value); 5236 if (cro.baseProtocols != 0) 5237 outs() << " + " << format("0x%" PRIx64, cro.baseProtocols); 5238 } else 5239 outs() << format("0x%" PRIx64, cro.baseProtocols); 5240 outs() << "\n"; 5241 if (cro.baseProtocols + n_value != 0) 5242 print_protocol_list64_t(cro.baseProtocols + n_value, info); 5243 5244 outs() << " ivars "; 5245 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, ivars), S, 5246 info, n_value, cro.ivars); 5247 if (n_value != 0) { 5248 if (info->verbose && sym_name != nullptr) 5249 outs() << sym_name; 5250 else 5251 outs() << format("0x%" PRIx64, n_value); 5252 if (cro.ivars != 0) 5253 outs() << " + " << format("0x%" PRIx64, cro.ivars); 5254 } else 5255 outs() << format("0x%" PRIx64, cro.ivars); 5256 outs() << "\n"; 5257 if (cro.ivars + n_value != 0) 5258 print_ivar_list64_t(cro.ivars + n_value, info); 5259 5260 outs() << " weakIvarLayout "; 5261 sym_name = 5262 get_symbol_64(offset + offsetof(struct class_ro64_t, weakIvarLayout), S, 5263 info, n_value, cro.weakIvarLayout); 5264 if (n_value != 0) { 5265 if (info->verbose && sym_name != nullptr) 5266 outs() << sym_name; 5267 else 5268 outs() << format("0x%" PRIx64, n_value); 5269 if (cro.weakIvarLayout != 0) 5270 outs() << " + " << format("0x%" PRIx64, cro.weakIvarLayout); 5271 } else 5272 outs() << format("0x%" PRIx64, cro.weakIvarLayout); 5273 outs() << "\n"; 5274 print_layout_map64(cro.weakIvarLayout + n_value, info); 5275 5276 outs() << " baseProperties "; 5277 sym_name = 5278 get_symbol_64(offset + offsetof(struct class_ro64_t, baseProperties), S, 5279 info, n_value, cro.baseProperties); 5280 if (n_value != 0) { 5281 if (info->verbose && sym_name != nullptr) 5282 outs() << sym_name; 5283 else 5284 outs() << format("0x%" PRIx64, n_value); 5285 if (cro.baseProperties != 0) 5286 outs() << " + " << format("0x%" PRIx64, cro.baseProperties); 5287 } else 5288 outs() << format("0x%" PRIx64, cro.baseProperties); 5289 outs() << "\n"; 5290 if (cro.baseProperties + n_value != 0) 5291 print_objc_property_list64(cro.baseProperties + n_value, info); 5292 5293 is_meta_class = (cro.flags & RO_META) != 0; 5294 return true; 5295 } 5296 5297 static bool print_class_ro32_t(uint32_t p, struct DisassembleInfo *info, 5298 bool &is_meta_class) { 5299 struct class_ro32_t cro; 5300 const char *r; 5301 uint32_t offset, xoffset, left; 5302 SectionRef S, xS; 5303 const char *name; 5304 5305 r = get_pointer_32(p, offset, left, S, info); 5306 if (r == nullptr) 5307 return false; 5308 memset(&cro, '\0', sizeof(struct class_ro32_t)); 5309 if (left < sizeof(struct class_ro32_t)) { 5310 memcpy(&cro, r, left); 5311 outs() << " (class_ro_t entends past the end of the section)\n"; 5312 } else 5313 memcpy(&cro, r, sizeof(struct class_ro32_t)); 5314 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 5315 swapStruct(cro); 5316 outs() << " flags " << format("0x%" PRIx32, cro.flags); 5317 if (cro.flags & RO_META) 5318 outs() << " RO_META"; 5319 if (cro.flags & RO_ROOT) 5320 outs() << " RO_ROOT"; 5321 if (cro.flags & RO_HAS_CXX_STRUCTORS) 5322 outs() << " RO_HAS_CXX_STRUCTORS"; 5323 outs() << "\n"; 5324 outs() << " instanceStart " << cro.instanceStart << "\n"; 5325 outs() << " instanceSize " << cro.instanceSize << "\n"; 5326 outs() << " ivarLayout " << format("0x%" PRIx32, cro.ivarLayout) 5327 << "\n"; 5328 print_layout_map32(cro.ivarLayout, info); 5329 5330 outs() << " name " << format("0x%" PRIx32, cro.name); 5331 name = get_pointer_32(cro.name, xoffset, left, xS, info); 5332 if (name != nullptr) 5333 outs() << format(" %.*s", left, name); 5334 outs() << "\n"; 5335 5336 outs() << " baseMethods " 5337 << format("0x%" PRIx32, cro.baseMethods) 5338 << " (struct method_list_t *)\n"; 5339 if (cro.baseMethods != 0) 5340 print_method_list32_t(cro.baseMethods, info, ""); 5341 5342 outs() << " baseProtocols " 5343 << format("0x%" PRIx32, cro.baseProtocols) << "\n"; 5344 if (cro.baseProtocols != 0) 5345 print_protocol_list32_t(cro.baseProtocols, info); 5346 outs() << " ivars " << format("0x%" PRIx32, cro.ivars) 5347 << "\n"; 5348 if (cro.ivars != 0) 5349 print_ivar_list32_t(cro.ivars, info); 5350 outs() << " weakIvarLayout " 5351 << format("0x%" PRIx32, cro.weakIvarLayout) << "\n"; 5352 print_layout_map32(cro.weakIvarLayout, info); 5353 outs() << " baseProperties " 5354 << format("0x%" PRIx32, cro.baseProperties) << "\n"; 5355 if (cro.baseProperties != 0) 5356 print_objc_property_list32(cro.baseProperties, info); 5357 is_meta_class = (cro.flags & RO_META) != 0; 5358 return true; 5359 } 5360 5361 static void print_class64_t(uint64_t p, struct DisassembleInfo *info) { 5362 struct class64_t c; 5363 const char *r; 5364 uint32_t offset, left; 5365 SectionRef S; 5366 const char *name; 5367 uint64_t isa_n_value, n_value; 5368 5369 r = get_pointer_64(p, offset, left, S, info); 5370 if (r == nullptr || left < sizeof(struct class64_t)) 5371 return; 5372 memcpy(&c, r, sizeof(struct class64_t)); 5373 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 5374 swapStruct(c); 5375 5376 outs() << " isa " << format("0x%" PRIx64, c.isa); 5377 name = get_symbol_64(offset + offsetof(struct class64_t, isa), S, info, 5378 isa_n_value, c.isa); 5379 if (name != nullptr) 5380 outs() << " " << name; 5381 outs() << "\n"; 5382 5383 outs() << " superclass " << format("0x%" PRIx64, c.superclass); 5384 name = get_symbol_64(offset + offsetof(struct class64_t, superclass), S, info, 5385 n_value, c.superclass); 5386 if (name != nullptr) 5387 outs() << " " << name; 5388 else { 5389 name = get_dyld_bind_info_symbolname(S.getAddress() + 5390 offset + offsetof(struct class64_t, superclass), info); 5391 if (name != nullptr) 5392 outs() << " " << name; 5393 } 5394 outs() << "\n"; 5395 5396 outs() << " cache " << format("0x%" PRIx64, c.cache); 5397 name = get_symbol_64(offset + offsetof(struct class64_t, cache), S, info, 5398 n_value, c.cache); 5399 if (name != nullptr) 5400 outs() << " " << name; 5401 outs() << "\n"; 5402 5403 outs() << " vtable " << format("0x%" PRIx64, c.vtable); 5404 name = get_symbol_64(offset + offsetof(struct class64_t, vtable), S, info, 5405 n_value, c.vtable); 5406 if (name != nullptr) 5407 outs() << " " << name; 5408 outs() << "\n"; 5409 5410 name = get_symbol_64(offset + offsetof(struct class64_t, data), S, info, 5411 n_value, c.data); 5412 outs() << " data "; 5413 if (n_value != 0) { 5414 if (info->verbose && name != nullptr) 5415 outs() << name; 5416 else 5417 outs() << format("0x%" PRIx64, n_value); 5418 if (c.data != 0) 5419 outs() << " + " << format("0x%" PRIx64, c.data); 5420 } else 5421 outs() << format("0x%" PRIx64, c.data); 5422 outs() << " (struct class_ro_t *)"; 5423 5424 // This is a Swift class if some of the low bits of the pointer are set. 5425 if ((c.data + n_value) & 0x7) 5426 outs() << " Swift class"; 5427 outs() << "\n"; 5428 bool is_meta_class; 5429 if (!print_class_ro64_t((c.data + n_value) & ~0x7, info, is_meta_class)) 5430 return; 5431 5432 if (!is_meta_class && 5433 c.isa + isa_n_value != p && 5434 c.isa + isa_n_value != 0 && 5435 info->depth < 100) { 5436 info->depth++; 5437 outs() << "Meta Class\n"; 5438 print_class64_t(c.isa + isa_n_value, info); 5439 } 5440 } 5441 5442 static void print_class32_t(uint32_t p, struct DisassembleInfo *info) { 5443 struct class32_t c; 5444 const char *r; 5445 uint32_t offset, left; 5446 SectionRef S; 5447 const char *name; 5448 5449 r = get_pointer_32(p, offset, left, S, info); 5450 if (r == nullptr) 5451 return; 5452 memset(&c, '\0', sizeof(struct class32_t)); 5453 if (left < sizeof(struct class32_t)) { 5454 memcpy(&c, r, left); 5455 outs() << " (class_t entends past the end of the section)\n"; 5456 } else 5457 memcpy(&c, r, sizeof(struct class32_t)); 5458 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 5459 swapStruct(c); 5460 5461 outs() << " isa " << format("0x%" PRIx32, c.isa); 5462 name = 5463 get_symbol_32(offset + offsetof(struct class32_t, isa), S, info, c.isa); 5464 if (name != nullptr) 5465 outs() << " " << name; 5466 outs() << "\n"; 5467 5468 outs() << " superclass " << format("0x%" PRIx32, c.superclass); 5469 name = get_symbol_32(offset + offsetof(struct class32_t, superclass), S, info, 5470 c.superclass); 5471 if (name != nullptr) 5472 outs() << " " << name; 5473 outs() << "\n"; 5474 5475 outs() << " cache " << format("0x%" PRIx32, c.cache); 5476 name = get_symbol_32(offset + offsetof(struct class32_t, cache), S, info, 5477 c.cache); 5478 if (name != nullptr) 5479 outs() << " " << name; 5480 outs() << "\n"; 5481 5482 outs() << " vtable " << format("0x%" PRIx32, c.vtable); 5483 name = get_symbol_32(offset + offsetof(struct class32_t, vtable), S, info, 5484 c.vtable); 5485 if (name != nullptr) 5486 outs() << " " << name; 5487 outs() << "\n"; 5488 5489 name = 5490 get_symbol_32(offset + offsetof(struct class32_t, data), S, info, c.data); 5491 outs() << " data " << format("0x%" PRIx32, c.data) 5492 << " (struct class_ro_t *)"; 5493 5494 // This is a Swift class if some of the low bits of the pointer are set. 5495 if (c.data & 0x3) 5496 outs() << " Swift class"; 5497 outs() << "\n"; 5498 bool is_meta_class; 5499 if (!print_class_ro32_t(c.data & ~0x3, info, is_meta_class)) 5500 return; 5501 5502 if (!is_meta_class) { 5503 outs() << "Meta Class\n"; 5504 print_class32_t(c.isa, info); 5505 } 5506 } 5507 5508 static void print_objc_class_t(struct objc_class_t *objc_class, 5509 struct DisassembleInfo *info) { 5510 uint32_t offset, left, xleft; 5511 const char *name, *p, *ivar_list; 5512 SectionRef S; 5513 int32_t i; 5514 struct objc_ivar_list_t objc_ivar_list; 5515 struct objc_ivar_t ivar; 5516 5517 outs() << "\t\t isa " << format("0x%08" PRIx32, objc_class->isa); 5518 if (info->verbose && CLS_GETINFO(objc_class, CLS_META)) { 5519 name = get_pointer_32(objc_class->isa, offset, left, S, info, true); 5520 if (name != nullptr) 5521 outs() << format(" %.*s", left, name); 5522 else 5523 outs() << " (not in an __OBJC section)"; 5524 } 5525 outs() << "\n"; 5526 5527 outs() << "\t super_class " 5528 << format("0x%08" PRIx32, objc_class->super_class); 5529 if (info->verbose) { 5530 name = get_pointer_32(objc_class->super_class, offset, left, S, info, true); 5531 if (name != nullptr) 5532 outs() << format(" %.*s", left, name); 5533 else 5534 outs() << " (not in an __OBJC section)"; 5535 } 5536 outs() << "\n"; 5537 5538 outs() << "\t\t name " << format("0x%08" PRIx32, objc_class->name); 5539 if (info->verbose) { 5540 name = get_pointer_32(objc_class->name, offset, left, S, info, true); 5541 if (name != nullptr) 5542 outs() << format(" %.*s", left, name); 5543 else 5544 outs() << " (not in an __OBJC section)"; 5545 } 5546 outs() << "\n"; 5547 5548 outs() << "\t\t version " << format("0x%08" PRIx32, objc_class->version) 5549 << "\n"; 5550 5551 outs() << "\t\t info " << format("0x%08" PRIx32, objc_class->info); 5552 if (info->verbose) { 5553 if (CLS_GETINFO(objc_class, CLS_CLASS)) 5554 outs() << " CLS_CLASS"; 5555 else if (CLS_GETINFO(objc_class, CLS_META)) 5556 outs() << " CLS_META"; 5557 } 5558 outs() << "\n"; 5559 5560 outs() << "\t instance_size " 5561 << format("0x%08" PRIx32, objc_class->instance_size) << "\n"; 5562 5563 p = get_pointer_32(objc_class->ivars, offset, left, S, info, true); 5564 outs() << "\t\t ivars " << format("0x%08" PRIx32, objc_class->ivars); 5565 if (p != nullptr) { 5566 if (left > sizeof(struct objc_ivar_list_t)) { 5567 outs() << "\n"; 5568 memcpy(&objc_ivar_list, p, sizeof(struct objc_ivar_list_t)); 5569 } else { 5570 outs() << " (entends past the end of the section)\n"; 5571 memset(&objc_ivar_list, '\0', sizeof(struct objc_ivar_list_t)); 5572 memcpy(&objc_ivar_list, p, left); 5573 } 5574 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 5575 swapStruct(objc_ivar_list); 5576 outs() << "\t\t ivar_count " << objc_ivar_list.ivar_count << "\n"; 5577 ivar_list = p + sizeof(struct objc_ivar_list_t); 5578 for (i = 0; i < objc_ivar_list.ivar_count; i++) { 5579 if ((i + 1) * sizeof(struct objc_ivar_t) > left) { 5580 outs() << "\t\t remaining ivar's extend past the of the section\n"; 5581 break; 5582 } 5583 memcpy(&ivar, ivar_list + i * sizeof(struct objc_ivar_t), 5584 sizeof(struct objc_ivar_t)); 5585 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 5586 swapStruct(ivar); 5587 5588 outs() << "\t\t\tivar_name " << format("0x%08" PRIx32, ivar.ivar_name); 5589 if (info->verbose) { 5590 name = get_pointer_32(ivar.ivar_name, offset, xleft, S, info, true); 5591 if (name != nullptr) 5592 outs() << format(" %.*s", xleft, name); 5593 else 5594 outs() << " (not in an __OBJC section)"; 5595 } 5596 outs() << "\n"; 5597 5598 outs() << "\t\t\tivar_type " << format("0x%08" PRIx32, ivar.ivar_type); 5599 if (info->verbose) { 5600 name = get_pointer_32(ivar.ivar_type, offset, xleft, S, info, true); 5601 if (name != nullptr) 5602 outs() << format(" %.*s", xleft, name); 5603 else 5604 outs() << " (not in an __OBJC section)"; 5605 } 5606 outs() << "\n"; 5607 5608 outs() << "\t\t ivar_offset " 5609 << format("0x%08" PRIx32, ivar.ivar_offset) << "\n"; 5610 } 5611 } else { 5612 outs() << " (not in an __OBJC section)\n"; 5613 } 5614 5615 outs() << "\t\t methods " << format("0x%08" PRIx32, objc_class->methodLists); 5616 if (print_method_list(objc_class->methodLists, info)) 5617 outs() << " (not in an __OBJC section)\n"; 5618 5619 outs() << "\t\t cache " << format("0x%08" PRIx32, objc_class->cache) 5620 << "\n"; 5621 5622 outs() << "\t\tprotocols " << format("0x%08" PRIx32, objc_class->protocols); 5623 if (print_protocol_list(objc_class->protocols, 16, info)) 5624 outs() << " (not in an __OBJC section)\n"; 5625 } 5626 5627 static void print_objc_objc_category_t(struct objc_category_t *objc_category, 5628 struct DisassembleInfo *info) { 5629 uint32_t offset, left; 5630 const char *name; 5631 SectionRef S; 5632 5633 outs() << "\t category name " 5634 << format("0x%08" PRIx32, objc_category->category_name); 5635 if (info->verbose) { 5636 name = get_pointer_32(objc_category->category_name, offset, left, S, info, 5637 true); 5638 if (name != nullptr) 5639 outs() << format(" %.*s", left, name); 5640 else 5641 outs() << " (not in an __OBJC section)"; 5642 } 5643 outs() << "\n"; 5644 5645 outs() << "\t\t class name " 5646 << format("0x%08" PRIx32, objc_category->class_name); 5647 if (info->verbose) { 5648 name = 5649 get_pointer_32(objc_category->class_name, offset, left, S, info, true); 5650 if (name != nullptr) 5651 outs() << format(" %.*s", left, name); 5652 else 5653 outs() << " (not in an __OBJC section)"; 5654 } 5655 outs() << "\n"; 5656 5657 outs() << "\t instance methods " 5658 << format("0x%08" PRIx32, objc_category->instance_methods); 5659 if (print_method_list(objc_category->instance_methods, info)) 5660 outs() << " (not in an __OBJC section)\n"; 5661 5662 outs() << "\t class methods " 5663 << format("0x%08" PRIx32, objc_category->class_methods); 5664 if (print_method_list(objc_category->class_methods, info)) 5665 outs() << " (not in an __OBJC section)\n"; 5666 } 5667 5668 static void print_category64_t(uint64_t p, struct DisassembleInfo *info) { 5669 struct category64_t c; 5670 const char *r; 5671 uint32_t offset, xoffset, left; 5672 SectionRef S, xS; 5673 const char *name, *sym_name; 5674 uint64_t n_value; 5675 5676 r = get_pointer_64(p, offset, left, S, info); 5677 if (r == nullptr) 5678 return; 5679 memset(&c, '\0', sizeof(struct category64_t)); 5680 if (left < sizeof(struct category64_t)) { 5681 memcpy(&c, r, left); 5682 outs() << " (category_t entends past the end of the section)\n"; 5683 } else 5684 memcpy(&c, r, sizeof(struct category64_t)); 5685 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 5686 swapStruct(c); 5687 5688 outs() << " name "; 5689 sym_name = get_symbol_64(offset + offsetof(struct category64_t, name), S, 5690 info, n_value, c.name); 5691 if (n_value != 0) { 5692 if (info->verbose && sym_name != nullptr) 5693 outs() << sym_name; 5694 else 5695 outs() << format("0x%" PRIx64, n_value); 5696 if (c.name != 0) 5697 outs() << " + " << format("0x%" PRIx64, c.name); 5698 } else 5699 outs() << format("0x%" PRIx64, c.name); 5700 name = get_pointer_64(c.name + n_value, xoffset, left, xS, info); 5701 if (name != nullptr) 5702 outs() << format(" %.*s", left, name); 5703 outs() << "\n"; 5704 5705 outs() << " cls "; 5706 sym_name = get_symbol_64(offset + offsetof(struct category64_t, cls), S, info, 5707 n_value, c.cls); 5708 if (n_value != 0) { 5709 if (info->verbose && sym_name != nullptr) 5710 outs() << sym_name; 5711 else 5712 outs() << format("0x%" PRIx64, n_value); 5713 if (c.cls != 0) 5714 outs() << " + " << format("0x%" PRIx64, c.cls); 5715 } else 5716 outs() << format("0x%" PRIx64, c.cls); 5717 outs() << "\n"; 5718 if (c.cls + n_value != 0) 5719 print_class64_t(c.cls + n_value, info); 5720 5721 outs() << " instanceMethods "; 5722 sym_name = 5723 get_symbol_64(offset + offsetof(struct category64_t, instanceMethods), S, 5724 info, n_value, c.instanceMethods); 5725 if (n_value != 0) { 5726 if (info->verbose && sym_name != nullptr) 5727 outs() << sym_name; 5728 else 5729 outs() << format("0x%" PRIx64, n_value); 5730 if (c.instanceMethods != 0) 5731 outs() << " + " << format("0x%" PRIx64, c.instanceMethods); 5732 } else 5733 outs() << format("0x%" PRIx64, c.instanceMethods); 5734 outs() << "\n"; 5735 if (c.instanceMethods + n_value != 0) 5736 print_method_list64_t(c.instanceMethods + n_value, info, ""); 5737 5738 outs() << " classMethods "; 5739 sym_name = get_symbol_64(offset + offsetof(struct category64_t, classMethods), 5740 S, info, n_value, c.classMethods); 5741 if (n_value != 0) { 5742 if (info->verbose && sym_name != nullptr) 5743 outs() << sym_name; 5744 else 5745 outs() << format("0x%" PRIx64, n_value); 5746 if (c.classMethods != 0) 5747 outs() << " + " << format("0x%" PRIx64, c.classMethods); 5748 } else 5749 outs() << format("0x%" PRIx64, c.classMethods); 5750 outs() << "\n"; 5751 if (c.classMethods + n_value != 0) 5752 print_method_list64_t(c.classMethods + n_value, info, ""); 5753 5754 outs() << " protocols "; 5755 sym_name = get_symbol_64(offset + offsetof(struct category64_t, protocols), S, 5756 info, n_value, c.protocols); 5757 if (n_value != 0) { 5758 if (info->verbose && sym_name != nullptr) 5759 outs() << sym_name; 5760 else 5761 outs() << format("0x%" PRIx64, n_value); 5762 if (c.protocols != 0) 5763 outs() << " + " << format("0x%" PRIx64, c.protocols); 5764 } else 5765 outs() << format("0x%" PRIx64, c.protocols); 5766 outs() << "\n"; 5767 if (c.protocols + n_value != 0) 5768 print_protocol_list64_t(c.protocols + n_value, info); 5769 5770 outs() << "instanceProperties "; 5771 sym_name = 5772 get_symbol_64(offset + offsetof(struct category64_t, instanceProperties), 5773 S, info, n_value, c.instanceProperties); 5774 if (n_value != 0) { 5775 if (info->verbose && sym_name != nullptr) 5776 outs() << sym_name; 5777 else 5778 outs() << format("0x%" PRIx64, n_value); 5779 if (c.instanceProperties != 0) 5780 outs() << " + " << format("0x%" PRIx64, c.instanceProperties); 5781 } else 5782 outs() << format("0x%" PRIx64, c.instanceProperties); 5783 outs() << "\n"; 5784 if (c.instanceProperties + n_value != 0) 5785 print_objc_property_list64(c.instanceProperties + n_value, info); 5786 } 5787 5788 static void print_category32_t(uint32_t p, struct DisassembleInfo *info) { 5789 struct category32_t c; 5790 const char *r; 5791 uint32_t offset, left; 5792 SectionRef S, xS; 5793 const char *name; 5794 5795 r = get_pointer_32(p, offset, left, S, info); 5796 if (r == nullptr) 5797 return; 5798 memset(&c, '\0', sizeof(struct category32_t)); 5799 if (left < sizeof(struct category32_t)) { 5800 memcpy(&c, r, left); 5801 outs() << " (category_t entends past the end of the section)\n"; 5802 } else 5803 memcpy(&c, r, sizeof(struct category32_t)); 5804 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 5805 swapStruct(c); 5806 5807 outs() << " name " << format("0x%" PRIx32, c.name); 5808 name = get_symbol_32(offset + offsetof(struct category32_t, name), S, info, 5809 c.name); 5810 if (name) 5811 outs() << " " << name; 5812 outs() << "\n"; 5813 5814 outs() << " cls " << format("0x%" PRIx32, c.cls) << "\n"; 5815 if (c.cls != 0) 5816 print_class32_t(c.cls, info); 5817 outs() << " instanceMethods " << format("0x%" PRIx32, c.instanceMethods) 5818 << "\n"; 5819 if (c.instanceMethods != 0) 5820 print_method_list32_t(c.instanceMethods, info, ""); 5821 outs() << " classMethods " << format("0x%" PRIx32, c.classMethods) 5822 << "\n"; 5823 if (c.classMethods != 0) 5824 print_method_list32_t(c.classMethods, info, ""); 5825 outs() << " protocols " << format("0x%" PRIx32, c.protocols) << "\n"; 5826 if (c.protocols != 0) 5827 print_protocol_list32_t(c.protocols, info); 5828 outs() << "instanceProperties " << format("0x%" PRIx32, c.instanceProperties) 5829 << "\n"; 5830 if (c.instanceProperties != 0) 5831 print_objc_property_list32(c.instanceProperties, info); 5832 } 5833 5834 static void print_message_refs64(SectionRef S, struct DisassembleInfo *info) { 5835 uint32_t i, left, offset, xoffset; 5836 uint64_t p, n_value; 5837 struct message_ref64 mr; 5838 const char *name, *sym_name; 5839 const char *r; 5840 SectionRef xS; 5841 5842 if (S == SectionRef()) 5843 return; 5844 5845 StringRef SectName; 5846 Expected<StringRef> SecNameOrErr = S.getName(); 5847 if (SecNameOrErr) 5848 SectName = *SecNameOrErr; 5849 else 5850 consumeError(SecNameOrErr.takeError()); 5851 5852 DataRefImpl Ref = S.getRawDataRefImpl(); 5853 StringRef SegName = info->O->getSectionFinalSegmentName(Ref); 5854 outs() << "Contents of (" << SegName << "," << SectName << ") section\n"; 5855 offset = 0; 5856 for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) { 5857 p = S.getAddress() + i; 5858 r = get_pointer_64(p, offset, left, S, info); 5859 if (r == nullptr) 5860 return; 5861 memset(&mr, '\0', sizeof(struct message_ref64)); 5862 if (left < sizeof(struct message_ref64)) { 5863 memcpy(&mr, r, left); 5864 outs() << " (message_ref entends past the end of the section)\n"; 5865 } else 5866 memcpy(&mr, r, sizeof(struct message_ref64)); 5867 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 5868 swapStruct(mr); 5869 5870 outs() << " imp "; 5871 name = get_symbol_64(offset + offsetof(struct message_ref64, imp), S, info, 5872 n_value, mr.imp); 5873 if (n_value != 0) { 5874 outs() << format("0x%" PRIx64, n_value) << " "; 5875 if (mr.imp != 0) 5876 outs() << "+ " << format("0x%" PRIx64, mr.imp) << " "; 5877 } else 5878 outs() << format("0x%" PRIx64, mr.imp) << " "; 5879 if (name != nullptr) 5880 outs() << " " << name; 5881 outs() << "\n"; 5882 5883 outs() << " sel "; 5884 sym_name = get_symbol_64(offset + offsetof(struct message_ref64, sel), S, 5885 info, n_value, mr.sel); 5886 if (n_value != 0) { 5887 if (info->verbose && sym_name != nullptr) 5888 outs() << sym_name; 5889 else 5890 outs() << format("0x%" PRIx64, n_value); 5891 if (mr.sel != 0) 5892 outs() << " + " << format("0x%" PRIx64, mr.sel); 5893 } else 5894 outs() << format("0x%" PRIx64, mr.sel); 5895 name = get_pointer_64(mr.sel + n_value, xoffset, left, xS, info); 5896 if (name != nullptr) 5897 outs() << format(" %.*s", left, name); 5898 outs() << "\n"; 5899 5900 offset += sizeof(struct message_ref64); 5901 } 5902 } 5903 5904 static void print_message_refs32(SectionRef S, struct DisassembleInfo *info) { 5905 uint32_t i, left, offset, xoffset, p; 5906 struct message_ref32 mr; 5907 const char *name, *r; 5908 SectionRef xS; 5909 5910 if (S == SectionRef()) 5911 return; 5912 5913 StringRef SectName; 5914 Expected<StringRef> SecNameOrErr = S.getName(); 5915 if (SecNameOrErr) 5916 SectName = *SecNameOrErr; 5917 else 5918 consumeError(SecNameOrErr.takeError()); 5919 5920 DataRefImpl Ref = S.getRawDataRefImpl(); 5921 StringRef SegName = info->O->getSectionFinalSegmentName(Ref); 5922 outs() << "Contents of (" << SegName << "," << SectName << ") section\n"; 5923 offset = 0; 5924 for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) { 5925 p = S.getAddress() + i; 5926 r = get_pointer_32(p, offset, left, S, info); 5927 if (r == nullptr) 5928 return; 5929 memset(&mr, '\0', sizeof(struct message_ref32)); 5930 if (left < sizeof(struct message_ref32)) { 5931 memcpy(&mr, r, left); 5932 outs() << " (message_ref entends past the end of the section)\n"; 5933 } else 5934 memcpy(&mr, r, sizeof(struct message_ref32)); 5935 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 5936 swapStruct(mr); 5937 5938 outs() << " imp " << format("0x%" PRIx32, mr.imp); 5939 name = get_symbol_32(offset + offsetof(struct message_ref32, imp), S, info, 5940 mr.imp); 5941 if (name != nullptr) 5942 outs() << " " << name; 5943 outs() << "\n"; 5944 5945 outs() << " sel " << format("0x%" PRIx32, mr.sel); 5946 name = get_pointer_32(mr.sel, xoffset, left, xS, info); 5947 if (name != nullptr) 5948 outs() << " " << name; 5949 outs() << "\n"; 5950 5951 offset += sizeof(struct message_ref32); 5952 } 5953 } 5954 5955 static void print_image_info64(SectionRef S, struct DisassembleInfo *info) { 5956 uint32_t left, offset, swift_version; 5957 uint64_t p; 5958 struct objc_image_info64 o; 5959 const char *r; 5960 5961 if (S == SectionRef()) 5962 return; 5963 5964 StringRef SectName; 5965 Expected<StringRef> SecNameOrErr = S.getName(); 5966 if (SecNameOrErr) 5967 SectName = *SecNameOrErr; 5968 else 5969 consumeError(SecNameOrErr.takeError()); 5970 5971 DataRefImpl Ref = S.getRawDataRefImpl(); 5972 StringRef SegName = info->O->getSectionFinalSegmentName(Ref); 5973 outs() << "Contents of (" << SegName << "," << SectName << ") section\n"; 5974 p = S.getAddress(); 5975 r = get_pointer_64(p, offset, left, S, info); 5976 if (r == nullptr) 5977 return; 5978 memset(&o, '\0', sizeof(struct objc_image_info64)); 5979 if (left < sizeof(struct objc_image_info64)) { 5980 memcpy(&o, r, left); 5981 outs() << " (objc_image_info entends past the end of the section)\n"; 5982 } else 5983 memcpy(&o, r, sizeof(struct objc_image_info64)); 5984 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 5985 swapStruct(o); 5986 outs() << " version " << o.version << "\n"; 5987 outs() << " flags " << format("0x%" PRIx32, o.flags); 5988 if (o.flags & OBJC_IMAGE_IS_REPLACEMENT) 5989 outs() << " OBJC_IMAGE_IS_REPLACEMENT"; 5990 if (o.flags & OBJC_IMAGE_SUPPORTS_GC) 5991 outs() << " OBJC_IMAGE_SUPPORTS_GC"; 5992 if (o.flags & OBJC_IMAGE_IS_SIMULATED) 5993 outs() << " OBJC_IMAGE_IS_SIMULATED"; 5994 if (o.flags & OBJC_IMAGE_HAS_CATEGORY_CLASS_PROPERTIES) 5995 outs() << " OBJC_IMAGE_HAS_CATEGORY_CLASS_PROPERTIES"; 5996 swift_version = (o.flags >> 8) & 0xff; 5997 if (swift_version != 0) { 5998 if (swift_version == 1) 5999 outs() << " Swift 1.0"; 6000 else if (swift_version == 2) 6001 outs() << " Swift 1.1"; 6002 else if(swift_version == 3) 6003 outs() << " Swift 2.0"; 6004 else if(swift_version == 4) 6005 outs() << " Swift 3.0"; 6006 else if(swift_version == 5) 6007 outs() << " Swift 4.0"; 6008 else if(swift_version == 6) 6009 outs() << " Swift 4.1/Swift 4.2"; 6010 else if(swift_version == 7) 6011 outs() << " Swift 5 or later"; 6012 else 6013 outs() << " unknown future Swift version (" << swift_version << ")"; 6014 } 6015 outs() << "\n"; 6016 } 6017 6018 static void print_image_info32(SectionRef S, struct DisassembleInfo *info) { 6019 uint32_t left, offset, swift_version, p; 6020 struct objc_image_info32 o; 6021 const char *r; 6022 6023 if (S == SectionRef()) 6024 return; 6025 6026 StringRef SectName; 6027 Expected<StringRef> SecNameOrErr = S.getName(); 6028 if (SecNameOrErr) 6029 SectName = *SecNameOrErr; 6030 else 6031 consumeError(SecNameOrErr.takeError()); 6032 6033 DataRefImpl Ref = S.getRawDataRefImpl(); 6034 StringRef SegName = info->O->getSectionFinalSegmentName(Ref); 6035 outs() << "Contents of (" << SegName << "," << SectName << ") section\n"; 6036 p = S.getAddress(); 6037 r = get_pointer_32(p, offset, left, S, info); 6038 if (r == nullptr) 6039 return; 6040 memset(&o, '\0', sizeof(struct objc_image_info32)); 6041 if (left < sizeof(struct objc_image_info32)) { 6042 memcpy(&o, r, left); 6043 outs() << " (objc_image_info entends past the end of the section)\n"; 6044 } else 6045 memcpy(&o, r, sizeof(struct objc_image_info32)); 6046 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 6047 swapStruct(o); 6048 outs() << " version " << o.version << "\n"; 6049 outs() << " flags " << format("0x%" PRIx32, o.flags); 6050 if (o.flags & OBJC_IMAGE_IS_REPLACEMENT) 6051 outs() << " OBJC_IMAGE_IS_REPLACEMENT"; 6052 if (o.flags & OBJC_IMAGE_SUPPORTS_GC) 6053 outs() << " OBJC_IMAGE_SUPPORTS_GC"; 6054 swift_version = (o.flags >> 8) & 0xff; 6055 if (swift_version != 0) { 6056 if (swift_version == 1) 6057 outs() << " Swift 1.0"; 6058 else if (swift_version == 2) 6059 outs() << " Swift 1.1"; 6060 else if(swift_version == 3) 6061 outs() << " Swift 2.0"; 6062 else if(swift_version == 4) 6063 outs() << " Swift 3.0"; 6064 else if(swift_version == 5) 6065 outs() << " Swift 4.0"; 6066 else if(swift_version == 6) 6067 outs() << " Swift 4.1/Swift 4.2"; 6068 else if(swift_version == 7) 6069 outs() << " Swift 5 or later"; 6070 else 6071 outs() << " unknown future Swift version (" << swift_version << ")"; 6072 } 6073 outs() << "\n"; 6074 } 6075 6076 static void print_image_info(SectionRef S, struct DisassembleInfo *info) { 6077 uint32_t left, offset, p; 6078 struct imageInfo_t o; 6079 const char *r; 6080 6081 StringRef SectName; 6082 Expected<StringRef> SecNameOrErr = S.getName(); 6083 if (SecNameOrErr) 6084 SectName = *SecNameOrErr; 6085 else 6086 consumeError(SecNameOrErr.takeError()); 6087 6088 DataRefImpl Ref = S.getRawDataRefImpl(); 6089 StringRef SegName = info->O->getSectionFinalSegmentName(Ref); 6090 outs() << "Contents of (" << SegName << "," << SectName << ") section\n"; 6091 p = S.getAddress(); 6092 r = get_pointer_32(p, offset, left, S, info); 6093 if (r == nullptr) 6094 return; 6095 memset(&o, '\0', sizeof(struct imageInfo_t)); 6096 if (left < sizeof(struct imageInfo_t)) { 6097 memcpy(&o, r, left); 6098 outs() << " (imageInfo entends past the end of the section)\n"; 6099 } else 6100 memcpy(&o, r, sizeof(struct imageInfo_t)); 6101 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 6102 swapStruct(o); 6103 outs() << " version " << o.version << "\n"; 6104 outs() << " flags " << format("0x%" PRIx32, o.flags); 6105 if (o.flags & 0x1) 6106 outs() << " F&C"; 6107 if (o.flags & 0x2) 6108 outs() << " GC"; 6109 if (o.flags & 0x4) 6110 outs() << " GC-only"; 6111 else 6112 outs() << " RR"; 6113 outs() << "\n"; 6114 } 6115 6116 static void printObjc2_64bit_MetaData(MachOObjectFile *O, bool verbose) { 6117 SymbolAddressMap AddrMap; 6118 if (verbose) 6119 CreateSymbolAddressMap(O, &AddrMap); 6120 6121 std::vector<SectionRef> Sections; 6122 for (const SectionRef &Section : O->sections()) 6123 Sections.push_back(Section); 6124 6125 struct DisassembleInfo info(O, &AddrMap, &Sections, verbose); 6126 6127 SectionRef CL = get_section(O, "__OBJC2", "__class_list"); 6128 if (CL == SectionRef()) 6129 CL = get_section(O, "__DATA", "__objc_classlist"); 6130 if (CL == SectionRef()) 6131 CL = get_section(O, "__DATA_CONST", "__objc_classlist"); 6132 if (CL == SectionRef()) 6133 CL = get_section(O, "__DATA_DIRTY", "__objc_classlist"); 6134 info.S = CL; 6135 walk_pointer_list_64("class", CL, O, &info, print_class64_t); 6136 6137 SectionRef CR = get_section(O, "__OBJC2", "__class_refs"); 6138 if (CR == SectionRef()) 6139 CR = get_section(O, "__DATA", "__objc_classrefs"); 6140 if (CR == SectionRef()) 6141 CR = get_section(O, "__DATA_CONST", "__objc_classrefs"); 6142 if (CR == SectionRef()) 6143 CR = get_section(O, "__DATA_DIRTY", "__objc_classrefs"); 6144 info.S = CR; 6145 walk_pointer_list_64("class refs", CR, O, &info, nullptr); 6146 6147 SectionRef SR = get_section(O, "__OBJC2", "__super_refs"); 6148 if (SR == SectionRef()) 6149 SR = get_section(O, "__DATA", "__objc_superrefs"); 6150 if (SR == SectionRef()) 6151 SR = get_section(O, "__DATA_CONST", "__objc_superrefs"); 6152 if (SR == SectionRef()) 6153 SR = get_section(O, "__DATA_DIRTY", "__objc_superrefs"); 6154 info.S = SR; 6155 walk_pointer_list_64("super refs", SR, O, &info, nullptr); 6156 6157 SectionRef CA = get_section(O, "__OBJC2", "__category_list"); 6158 if (CA == SectionRef()) 6159 CA = get_section(O, "__DATA", "__objc_catlist"); 6160 if (CA == SectionRef()) 6161 CA = get_section(O, "__DATA_CONST", "__objc_catlist"); 6162 if (CA == SectionRef()) 6163 CA = get_section(O, "__DATA_DIRTY", "__objc_catlist"); 6164 info.S = CA; 6165 walk_pointer_list_64("category", CA, O, &info, print_category64_t); 6166 6167 SectionRef PL = get_section(O, "__OBJC2", "__protocol_list"); 6168 if (PL == SectionRef()) 6169 PL = get_section(O, "__DATA", "__objc_protolist"); 6170 if (PL == SectionRef()) 6171 PL = get_section(O, "__DATA_CONST", "__objc_protolist"); 6172 if (PL == SectionRef()) 6173 PL = get_section(O, "__DATA_DIRTY", "__objc_protolist"); 6174 info.S = PL; 6175 walk_pointer_list_64("protocol", PL, O, &info, nullptr); 6176 6177 SectionRef MR = get_section(O, "__OBJC2", "__message_refs"); 6178 if (MR == SectionRef()) 6179 MR = get_section(O, "__DATA", "__objc_msgrefs"); 6180 if (MR == SectionRef()) 6181 MR = get_section(O, "__DATA_CONST", "__objc_msgrefs"); 6182 if (MR == SectionRef()) 6183 MR = get_section(O, "__DATA_DIRTY", "__objc_msgrefs"); 6184 info.S = MR; 6185 print_message_refs64(MR, &info); 6186 6187 SectionRef II = get_section(O, "__OBJC2", "__image_info"); 6188 if (II == SectionRef()) 6189 II = get_section(O, "__DATA", "__objc_imageinfo"); 6190 if (II == SectionRef()) 6191 II = get_section(O, "__DATA_CONST", "__objc_imageinfo"); 6192 if (II == SectionRef()) 6193 II = get_section(O, "__DATA_DIRTY", "__objc_imageinfo"); 6194 info.S = II; 6195 print_image_info64(II, &info); 6196 } 6197 6198 static void printObjc2_32bit_MetaData(MachOObjectFile *O, bool verbose) { 6199 SymbolAddressMap AddrMap; 6200 if (verbose) 6201 CreateSymbolAddressMap(O, &AddrMap); 6202 6203 std::vector<SectionRef> Sections; 6204 for (const SectionRef &Section : O->sections()) 6205 Sections.push_back(Section); 6206 6207 struct DisassembleInfo info(O, &AddrMap, &Sections, verbose); 6208 6209 SectionRef CL = get_section(O, "__OBJC2", "__class_list"); 6210 if (CL == SectionRef()) 6211 CL = get_section(O, "__DATA", "__objc_classlist"); 6212 if (CL == SectionRef()) 6213 CL = get_section(O, "__DATA_CONST", "__objc_classlist"); 6214 if (CL == SectionRef()) 6215 CL = get_section(O, "__DATA_DIRTY", "__objc_classlist"); 6216 info.S = CL; 6217 walk_pointer_list_32("class", CL, O, &info, print_class32_t); 6218 6219 SectionRef CR = get_section(O, "__OBJC2", "__class_refs"); 6220 if (CR == SectionRef()) 6221 CR = get_section(O, "__DATA", "__objc_classrefs"); 6222 if (CR == SectionRef()) 6223 CR = get_section(O, "__DATA_CONST", "__objc_classrefs"); 6224 if (CR == SectionRef()) 6225 CR = get_section(O, "__DATA_DIRTY", "__objc_classrefs"); 6226 info.S = CR; 6227 walk_pointer_list_32("class refs", CR, O, &info, nullptr); 6228 6229 SectionRef SR = get_section(O, "__OBJC2", "__super_refs"); 6230 if (SR == SectionRef()) 6231 SR = get_section(O, "__DATA", "__objc_superrefs"); 6232 if (SR == SectionRef()) 6233 SR = get_section(O, "__DATA_CONST", "__objc_superrefs"); 6234 if (SR == SectionRef()) 6235 SR = get_section(O, "__DATA_DIRTY", "__objc_superrefs"); 6236 info.S = SR; 6237 walk_pointer_list_32("super refs", SR, O, &info, nullptr); 6238 6239 SectionRef CA = get_section(O, "__OBJC2", "__category_list"); 6240 if (CA == SectionRef()) 6241 CA = get_section(O, "__DATA", "__objc_catlist"); 6242 if (CA == SectionRef()) 6243 CA = get_section(O, "__DATA_CONST", "__objc_catlist"); 6244 if (CA == SectionRef()) 6245 CA = get_section(O, "__DATA_DIRTY", "__objc_catlist"); 6246 info.S = CA; 6247 walk_pointer_list_32("category", CA, O, &info, print_category32_t); 6248 6249 SectionRef PL = get_section(O, "__OBJC2", "__protocol_list"); 6250 if (PL == SectionRef()) 6251 PL = get_section(O, "__DATA", "__objc_protolist"); 6252 if (PL == SectionRef()) 6253 PL = get_section(O, "__DATA_CONST", "__objc_protolist"); 6254 if (PL == SectionRef()) 6255 PL = get_section(O, "__DATA_DIRTY", "__objc_protolist"); 6256 info.S = PL; 6257 walk_pointer_list_32("protocol", PL, O, &info, nullptr); 6258 6259 SectionRef MR = get_section(O, "__OBJC2", "__message_refs"); 6260 if (MR == SectionRef()) 6261 MR = get_section(O, "__DATA", "__objc_msgrefs"); 6262 if (MR == SectionRef()) 6263 MR = get_section(O, "__DATA_CONST", "__objc_msgrefs"); 6264 if (MR == SectionRef()) 6265 MR = get_section(O, "__DATA_DIRTY", "__objc_msgrefs"); 6266 info.S = MR; 6267 print_message_refs32(MR, &info); 6268 6269 SectionRef II = get_section(O, "__OBJC2", "__image_info"); 6270 if (II == SectionRef()) 6271 II = get_section(O, "__DATA", "__objc_imageinfo"); 6272 if (II == SectionRef()) 6273 II = get_section(O, "__DATA_CONST", "__objc_imageinfo"); 6274 if (II == SectionRef()) 6275 II = get_section(O, "__DATA_DIRTY", "__objc_imageinfo"); 6276 info.S = II; 6277 print_image_info32(II, &info); 6278 } 6279 6280 static bool printObjc1_32bit_MetaData(MachOObjectFile *O, bool verbose) { 6281 uint32_t i, j, p, offset, xoffset, left, defs_left, def; 6282 const char *r, *name, *defs; 6283 struct objc_module_t module; 6284 SectionRef S, xS; 6285 struct objc_symtab_t symtab; 6286 struct objc_class_t objc_class; 6287 struct objc_category_t objc_category; 6288 6289 outs() << "Objective-C segment\n"; 6290 S = get_section(O, "__OBJC", "__module_info"); 6291 if (S == SectionRef()) 6292 return false; 6293 6294 SymbolAddressMap AddrMap; 6295 if (verbose) 6296 CreateSymbolAddressMap(O, &AddrMap); 6297 6298 std::vector<SectionRef> Sections; 6299 for (const SectionRef &Section : O->sections()) 6300 Sections.push_back(Section); 6301 6302 struct DisassembleInfo info(O, &AddrMap, &Sections, verbose); 6303 6304 for (i = 0; i < S.getSize(); i += sizeof(struct objc_module_t)) { 6305 p = S.getAddress() + i; 6306 r = get_pointer_32(p, offset, left, S, &info, true); 6307 if (r == nullptr) 6308 return true; 6309 memset(&module, '\0', sizeof(struct objc_module_t)); 6310 if (left < sizeof(struct objc_module_t)) { 6311 memcpy(&module, r, left); 6312 outs() << " (module extends past end of __module_info section)\n"; 6313 } else 6314 memcpy(&module, r, sizeof(struct objc_module_t)); 6315 if (O->isLittleEndian() != sys::IsLittleEndianHost) 6316 swapStruct(module); 6317 6318 outs() << "Module " << format("0x%" PRIx32, p) << "\n"; 6319 outs() << " version " << module.version << "\n"; 6320 outs() << " size " << module.size << "\n"; 6321 outs() << " name "; 6322 name = get_pointer_32(module.name, xoffset, left, xS, &info, true); 6323 if (name != nullptr) 6324 outs() << format("%.*s", left, name); 6325 else 6326 outs() << format("0x%08" PRIx32, module.name) 6327 << "(not in an __OBJC section)"; 6328 outs() << "\n"; 6329 6330 r = get_pointer_32(module.symtab, xoffset, left, xS, &info, true); 6331 if (module.symtab == 0 || r == nullptr) { 6332 outs() << " symtab " << format("0x%08" PRIx32, module.symtab) 6333 << " (not in an __OBJC section)\n"; 6334 continue; 6335 } 6336 outs() << " symtab " << format("0x%08" PRIx32, module.symtab) << "\n"; 6337 memset(&symtab, '\0', sizeof(struct objc_symtab_t)); 6338 defs_left = 0; 6339 defs = nullptr; 6340 if (left < sizeof(struct objc_symtab_t)) { 6341 memcpy(&symtab, r, left); 6342 outs() << "\tsymtab extends past end of an __OBJC section)\n"; 6343 } else { 6344 memcpy(&symtab, r, sizeof(struct objc_symtab_t)); 6345 if (left > sizeof(struct objc_symtab_t)) { 6346 defs_left = left - sizeof(struct objc_symtab_t); 6347 defs = r + sizeof(struct objc_symtab_t); 6348 } 6349 } 6350 if (O->isLittleEndian() != sys::IsLittleEndianHost) 6351 swapStruct(symtab); 6352 6353 outs() << "\tsel_ref_cnt " << symtab.sel_ref_cnt << "\n"; 6354 r = get_pointer_32(symtab.refs, xoffset, left, xS, &info, true); 6355 outs() << "\trefs " << format("0x%08" PRIx32, symtab.refs); 6356 if (r == nullptr) 6357 outs() << " (not in an __OBJC section)"; 6358 outs() << "\n"; 6359 outs() << "\tcls_def_cnt " << symtab.cls_def_cnt << "\n"; 6360 outs() << "\tcat_def_cnt " << symtab.cat_def_cnt << "\n"; 6361 if (symtab.cls_def_cnt > 0) 6362 outs() << "\tClass Definitions\n"; 6363 for (j = 0; j < symtab.cls_def_cnt; j++) { 6364 if ((j + 1) * sizeof(uint32_t) > defs_left) { 6365 outs() << "\t(remaining class defs entries entends past the end of the " 6366 << "section)\n"; 6367 break; 6368 } 6369 memcpy(&def, defs + j * sizeof(uint32_t), sizeof(uint32_t)); 6370 if (O->isLittleEndian() != sys::IsLittleEndianHost) 6371 sys::swapByteOrder(def); 6372 6373 r = get_pointer_32(def, xoffset, left, xS, &info, true); 6374 outs() << "\tdefs[" << j << "] " << format("0x%08" PRIx32, def); 6375 if (r != nullptr) { 6376 if (left > sizeof(struct objc_class_t)) { 6377 outs() << "\n"; 6378 memcpy(&objc_class, r, sizeof(struct objc_class_t)); 6379 } else { 6380 outs() << " (entends past the end of the section)\n"; 6381 memset(&objc_class, '\0', sizeof(struct objc_class_t)); 6382 memcpy(&objc_class, r, left); 6383 } 6384 if (O->isLittleEndian() != sys::IsLittleEndianHost) 6385 swapStruct(objc_class); 6386 print_objc_class_t(&objc_class, &info); 6387 } else { 6388 outs() << "(not in an __OBJC section)\n"; 6389 } 6390 6391 if (CLS_GETINFO(&objc_class, CLS_CLASS)) { 6392 outs() << "\tMeta Class"; 6393 r = get_pointer_32(objc_class.isa, xoffset, left, xS, &info, true); 6394 if (r != nullptr) { 6395 if (left > sizeof(struct objc_class_t)) { 6396 outs() << "\n"; 6397 memcpy(&objc_class, r, sizeof(struct objc_class_t)); 6398 } else { 6399 outs() << " (entends past the end of the section)\n"; 6400 memset(&objc_class, '\0', sizeof(struct objc_class_t)); 6401 memcpy(&objc_class, r, left); 6402 } 6403 if (O->isLittleEndian() != sys::IsLittleEndianHost) 6404 swapStruct(objc_class); 6405 print_objc_class_t(&objc_class, &info); 6406 } else { 6407 outs() << "(not in an __OBJC section)\n"; 6408 } 6409 } 6410 } 6411 if (symtab.cat_def_cnt > 0) 6412 outs() << "\tCategory Definitions\n"; 6413 for (j = 0; j < symtab.cat_def_cnt; j++) { 6414 if ((j + symtab.cls_def_cnt + 1) * sizeof(uint32_t) > defs_left) { 6415 outs() << "\t(remaining category defs entries entends past the end of " 6416 << "the section)\n"; 6417 break; 6418 } 6419 memcpy(&def, defs + (j + symtab.cls_def_cnt) * sizeof(uint32_t), 6420 sizeof(uint32_t)); 6421 if (O->isLittleEndian() != sys::IsLittleEndianHost) 6422 sys::swapByteOrder(def); 6423 6424 r = get_pointer_32(def, xoffset, left, xS, &info, true); 6425 outs() << "\tdefs[" << j + symtab.cls_def_cnt << "] " 6426 << format("0x%08" PRIx32, def); 6427 if (r != nullptr) { 6428 if (left > sizeof(struct objc_category_t)) { 6429 outs() << "\n"; 6430 memcpy(&objc_category, r, sizeof(struct objc_category_t)); 6431 } else { 6432 outs() << " (entends past the end of the section)\n"; 6433 memset(&objc_category, '\0', sizeof(struct objc_category_t)); 6434 memcpy(&objc_category, r, left); 6435 } 6436 if (O->isLittleEndian() != sys::IsLittleEndianHost) 6437 swapStruct(objc_category); 6438 print_objc_objc_category_t(&objc_category, &info); 6439 } else { 6440 outs() << "(not in an __OBJC section)\n"; 6441 } 6442 } 6443 } 6444 const SectionRef II = get_section(O, "__OBJC", "__image_info"); 6445 if (II != SectionRef()) 6446 print_image_info(II, &info); 6447 6448 return true; 6449 } 6450 6451 static void DumpProtocolSection(MachOObjectFile *O, const char *sect, 6452 uint32_t size, uint32_t addr) { 6453 SymbolAddressMap AddrMap; 6454 CreateSymbolAddressMap(O, &AddrMap); 6455 6456 std::vector<SectionRef> Sections; 6457 for (const SectionRef &Section : O->sections()) 6458 Sections.push_back(Section); 6459 6460 struct DisassembleInfo info(O, &AddrMap, &Sections, true); 6461 6462 const char *p; 6463 struct objc_protocol_t protocol; 6464 uint32_t left, paddr; 6465 for (p = sect; p < sect + size; p += sizeof(struct objc_protocol_t)) { 6466 memset(&protocol, '\0', sizeof(struct objc_protocol_t)); 6467 left = size - (p - sect); 6468 if (left < sizeof(struct objc_protocol_t)) { 6469 outs() << "Protocol extends past end of __protocol section\n"; 6470 memcpy(&protocol, p, left); 6471 } else 6472 memcpy(&protocol, p, sizeof(struct objc_protocol_t)); 6473 if (O->isLittleEndian() != sys::IsLittleEndianHost) 6474 swapStruct(protocol); 6475 paddr = addr + (p - sect); 6476 outs() << "Protocol " << format("0x%" PRIx32, paddr); 6477 if (print_protocol(paddr, 0, &info)) 6478 outs() << "(not in an __OBJC section)\n"; 6479 } 6480 } 6481 6482 #ifdef HAVE_LIBXAR 6483 inline void swapStruct(struct xar_header &xar) { 6484 sys::swapByteOrder(xar.magic); 6485 sys::swapByteOrder(xar.size); 6486 sys::swapByteOrder(xar.version); 6487 sys::swapByteOrder(xar.toc_length_compressed); 6488 sys::swapByteOrder(xar.toc_length_uncompressed); 6489 sys::swapByteOrder(xar.cksum_alg); 6490 } 6491 6492 static void PrintModeVerbose(uint32_t mode) { 6493 switch(mode & S_IFMT){ 6494 case S_IFDIR: 6495 outs() << "d"; 6496 break; 6497 case S_IFCHR: 6498 outs() << "c"; 6499 break; 6500 case S_IFBLK: 6501 outs() << "b"; 6502 break; 6503 case S_IFREG: 6504 outs() << "-"; 6505 break; 6506 case S_IFLNK: 6507 outs() << "l"; 6508 break; 6509 case S_IFSOCK: 6510 outs() << "s"; 6511 break; 6512 default: 6513 outs() << "?"; 6514 break; 6515 } 6516 6517 /* owner permissions */ 6518 if(mode & S_IREAD) 6519 outs() << "r"; 6520 else 6521 outs() << "-"; 6522 if(mode & S_IWRITE) 6523 outs() << "w"; 6524 else 6525 outs() << "-"; 6526 if(mode & S_ISUID) 6527 outs() << "s"; 6528 else if(mode & S_IEXEC) 6529 outs() << "x"; 6530 else 6531 outs() << "-"; 6532 6533 /* group permissions */ 6534 if(mode & (S_IREAD >> 3)) 6535 outs() << "r"; 6536 else 6537 outs() << "-"; 6538 if(mode & (S_IWRITE >> 3)) 6539 outs() << "w"; 6540 else 6541 outs() << "-"; 6542 if(mode & S_ISGID) 6543 outs() << "s"; 6544 else if(mode & (S_IEXEC >> 3)) 6545 outs() << "x"; 6546 else 6547 outs() << "-"; 6548 6549 /* other permissions */ 6550 if(mode & (S_IREAD >> 6)) 6551 outs() << "r"; 6552 else 6553 outs() << "-"; 6554 if(mode & (S_IWRITE >> 6)) 6555 outs() << "w"; 6556 else 6557 outs() << "-"; 6558 if(mode & S_ISVTX) 6559 outs() << "t"; 6560 else if(mode & (S_IEXEC >> 6)) 6561 outs() << "x"; 6562 else 6563 outs() << "-"; 6564 } 6565 6566 static void PrintXarFilesSummary(const char *XarFilename, xar_t xar) { 6567 xar_file_t xf; 6568 const char *key, *type, *mode, *user, *group, *size, *mtime, *name, *m; 6569 char *endp; 6570 uint32_t mode_value; 6571 6572 ScopedXarIter xi; 6573 if (!xi) { 6574 WithColor::error(errs(), "llvm-objdump") 6575 << "can't obtain an xar iterator for xar archive " << XarFilename 6576 << "\n"; 6577 return; 6578 } 6579 6580 // Go through the xar's files. 6581 for (xf = xar_file_first(xar, xi); xf; xf = xar_file_next(xi)) { 6582 ScopedXarIter xp; 6583 if(!xp){ 6584 WithColor::error(errs(), "llvm-objdump") 6585 << "can't obtain an xar iterator for xar archive " << XarFilename 6586 << "\n"; 6587 return; 6588 } 6589 type = nullptr; 6590 mode = nullptr; 6591 user = nullptr; 6592 group = nullptr; 6593 size = nullptr; 6594 mtime = nullptr; 6595 name = nullptr; 6596 for(key = xar_prop_first(xf, xp); key; key = xar_prop_next(xp)){ 6597 const char *val = nullptr; 6598 xar_prop_get(xf, key, &val); 6599 #if 0 // Useful for debugging. 6600 outs() << "key: " << key << " value: " << val << "\n"; 6601 #endif 6602 if(strcmp(key, "type") == 0) 6603 type = val; 6604 if(strcmp(key, "mode") == 0) 6605 mode = val; 6606 if(strcmp(key, "user") == 0) 6607 user = val; 6608 if(strcmp(key, "group") == 0) 6609 group = val; 6610 if(strcmp(key, "data/size") == 0) 6611 size = val; 6612 if(strcmp(key, "mtime") == 0) 6613 mtime = val; 6614 if(strcmp(key, "name") == 0) 6615 name = val; 6616 } 6617 if(mode != nullptr){ 6618 mode_value = strtoul(mode, &endp, 8); 6619 if(*endp != '\0') 6620 outs() << "(mode: \"" << mode << "\" contains non-octal chars) "; 6621 if(strcmp(type, "file") == 0) 6622 mode_value |= S_IFREG; 6623 PrintModeVerbose(mode_value); 6624 outs() << " "; 6625 } 6626 if(user != nullptr) 6627 outs() << format("%10s/", user); 6628 if(group != nullptr) 6629 outs() << format("%-10s ", group); 6630 if(size != nullptr) 6631 outs() << format("%7s ", size); 6632 if(mtime != nullptr){ 6633 for(m = mtime; *m != 'T' && *m != '\0'; m++) 6634 outs() << *m; 6635 if(*m == 'T') 6636 m++; 6637 outs() << " "; 6638 for( ; *m != 'Z' && *m != '\0'; m++) 6639 outs() << *m; 6640 outs() << " "; 6641 } 6642 if(name != nullptr) 6643 outs() << name; 6644 outs() << "\n"; 6645 } 6646 } 6647 6648 static void DumpBitcodeSection(MachOObjectFile *O, const char *sect, 6649 uint32_t size, bool verbose, 6650 bool PrintXarHeader, bool PrintXarFileHeaders, 6651 std::string XarMemberName) { 6652 if(size < sizeof(struct xar_header)) { 6653 outs() << "size of (__LLVM,__bundle) section too small (smaller than size " 6654 "of struct xar_header)\n"; 6655 return; 6656 } 6657 struct xar_header XarHeader; 6658 memcpy(&XarHeader, sect, sizeof(struct xar_header)); 6659 if (sys::IsLittleEndianHost) 6660 swapStruct(XarHeader); 6661 if (PrintXarHeader) { 6662 if (!XarMemberName.empty()) 6663 outs() << "In xar member " << XarMemberName << ": "; 6664 else 6665 outs() << "For (__LLVM,__bundle) section: "; 6666 outs() << "xar header\n"; 6667 if (XarHeader.magic == XAR_HEADER_MAGIC) 6668 outs() << " magic XAR_HEADER_MAGIC\n"; 6669 else 6670 outs() << " magic " 6671 << format_hex(XarHeader.magic, 10, true) 6672 << " (not XAR_HEADER_MAGIC)\n"; 6673 outs() << " size " << XarHeader.size << "\n"; 6674 outs() << " version " << XarHeader.version << "\n"; 6675 outs() << " toc_length_compressed " << XarHeader.toc_length_compressed 6676 << "\n"; 6677 outs() << "toc_length_uncompressed " << XarHeader.toc_length_uncompressed 6678 << "\n"; 6679 outs() << " cksum_alg "; 6680 switch (XarHeader.cksum_alg) { 6681 case XAR_CKSUM_NONE: 6682 outs() << "XAR_CKSUM_NONE\n"; 6683 break; 6684 case XAR_CKSUM_SHA1: 6685 outs() << "XAR_CKSUM_SHA1\n"; 6686 break; 6687 case XAR_CKSUM_MD5: 6688 outs() << "XAR_CKSUM_MD5\n"; 6689 break; 6690 #ifdef XAR_CKSUM_SHA256 6691 case XAR_CKSUM_SHA256: 6692 outs() << "XAR_CKSUM_SHA256\n"; 6693 break; 6694 #endif 6695 #ifdef XAR_CKSUM_SHA512 6696 case XAR_CKSUM_SHA512: 6697 outs() << "XAR_CKSUM_SHA512\n"; 6698 break; 6699 #endif 6700 default: 6701 outs() << XarHeader.cksum_alg << "\n"; 6702 } 6703 } 6704 6705 SmallString<128> XarFilename; 6706 int FD; 6707 std::error_code XarEC = 6708 sys::fs::createTemporaryFile("llvm-objdump", "xar", FD, XarFilename); 6709 if (XarEC) { 6710 WithColor::error(errs(), "llvm-objdump") << XarEC.message() << "\n"; 6711 return; 6712 } 6713 ToolOutputFile XarFile(XarFilename, FD); 6714 raw_fd_ostream &XarOut = XarFile.os(); 6715 StringRef XarContents(sect, size); 6716 XarOut << XarContents; 6717 XarOut.close(); 6718 if (XarOut.has_error()) 6719 return; 6720 6721 ScopedXarFile xar(XarFilename.c_str(), READ); 6722 if (!xar) { 6723 WithColor::error(errs(), "llvm-objdump") 6724 << "can't create temporary xar archive " << XarFilename << "\n"; 6725 return; 6726 } 6727 6728 SmallString<128> TocFilename; 6729 std::error_code TocEC = 6730 sys::fs::createTemporaryFile("llvm-objdump", "toc", TocFilename); 6731 if (TocEC) { 6732 WithColor::error(errs(), "llvm-objdump") << TocEC.message() << "\n"; 6733 return; 6734 } 6735 xar_serialize(xar, TocFilename.c_str()); 6736 6737 if (PrintXarFileHeaders) { 6738 if (!XarMemberName.empty()) 6739 outs() << "In xar member " << XarMemberName << ": "; 6740 else 6741 outs() << "For (__LLVM,__bundle) section: "; 6742 outs() << "xar archive files:\n"; 6743 PrintXarFilesSummary(XarFilename.c_str(), xar); 6744 } 6745 6746 ErrorOr<std::unique_ptr<MemoryBuffer>> FileOrErr = 6747 MemoryBuffer::getFileOrSTDIN(TocFilename.c_str()); 6748 if (std::error_code EC = FileOrErr.getError()) { 6749 WithColor::error(errs(), "llvm-objdump") << EC.message() << "\n"; 6750 return; 6751 } 6752 std::unique_ptr<MemoryBuffer> &Buffer = FileOrErr.get(); 6753 6754 if (!XarMemberName.empty()) 6755 outs() << "In xar member " << XarMemberName << ": "; 6756 else 6757 outs() << "For (__LLVM,__bundle) section: "; 6758 outs() << "xar table of contents:\n"; 6759 outs() << Buffer->getBuffer() << "\n"; 6760 6761 // TODO: Go through the xar's files. 6762 ScopedXarIter xi; 6763 if(!xi){ 6764 WithColor::error(errs(), "llvm-objdump") 6765 << "can't obtain an xar iterator for xar archive " 6766 << XarFilename.c_str() << "\n"; 6767 return; 6768 } 6769 for(xar_file_t xf = xar_file_first(xar, xi); xf; xf = xar_file_next(xi)){ 6770 const char *key; 6771 const char *member_name, *member_type, *member_size_string; 6772 size_t member_size; 6773 6774 ScopedXarIter xp; 6775 if(!xp){ 6776 WithColor::error(errs(), "llvm-objdump") 6777 << "can't obtain an xar iterator for xar archive " 6778 << XarFilename.c_str() << "\n"; 6779 return; 6780 } 6781 member_name = NULL; 6782 member_type = NULL; 6783 member_size_string = NULL; 6784 for(key = xar_prop_first(xf, xp); key; key = xar_prop_next(xp)){ 6785 const char *val = nullptr; 6786 xar_prop_get(xf, key, &val); 6787 #if 0 // Useful for debugging. 6788 outs() << "key: " << key << " value: " << val << "\n"; 6789 #endif 6790 if (strcmp(key, "name") == 0) 6791 member_name = val; 6792 if (strcmp(key, "type") == 0) 6793 member_type = val; 6794 if (strcmp(key, "data/size") == 0) 6795 member_size_string = val; 6796 } 6797 /* 6798 * If we find a file with a name, date/size and type properties 6799 * and with the type being "file" see if that is a xar file. 6800 */ 6801 if (member_name != NULL && member_type != NULL && 6802 strcmp(member_type, "file") == 0 && 6803 member_size_string != NULL){ 6804 // Extract the file into a buffer. 6805 char *endptr; 6806 member_size = strtoul(member_size_string, &endptr, 10); 6807 if (*endptr == '\0' && member_size != 0) { 6808 char *buffer; 6809 if (xar_extract_tobuffersz(xar, xf, &buffer, &member_size) == 0) { 6810 #if 0 // Useful for debugging. 6811 outs() << "xar member: " << member_name << " extracted\n"; 6812 #endif 6813 // Set the XarMemberName we want to see printed in the header. 6814 std::string OldXarMemberName; 6815 // If XarMemberName is already set this is nested. So 6816 // save the old name and create the nested name. 6817 if (!XarMemberName.empty()) { 6818 OldXarMemberName = XarMemberName; 6819 XarMemberName = 6820 (Twine("[") + XarMemberName + "]" + member_name).str(); 6821 } else { 6822 OldXarMemberName = ""; 6823 XarMemberName = member_name; 6824 } 6825 // See if this is could be a xar file (nested). 6826 if (member_size >= sizeof(struct xar_header)) { 6827 #if 0 // Useful for debugging. 6828 outs() << "could be a xar file: " << member_name << "\n"; 6829 #endif 6830 memcpy((char *)&XarHeader, buffer, sizeof(struct xar_header)); 6831 if (sys::IsLittleEndianHost) 6832 swapStruct(XarHeader); 6833 if (XarHeader.magic == XAR_HEADER_MAGIC) 6834 DumpBitcodeSection(O, buffer, member_size, verbose, 6835 PrintXarHeader, PrintXarFileHeaders, 6836 XarMemberName); 6837 } 6838 XarMemberName = OldXarMemberName; 6839 delete buffer; 6840 } 6841 } 6842 } 6843 } 6844 } 6845 #endif // defined(HAVE_LIBXAR) 6846 6847 static void printObjcMetaData(MachOObjectFile *O, bool verbose) { 6848 if (O->is64Bit()) 6849 printObjc2_64bit_MetaData(O, verbose); 6850 else { 6851 MachO::mach_header H; 6852 H = O->getHeader(); 6853 if (H.cputype == MachO::CPU_TYPE_ARM) 6854 printObjc2_32bit_MetaData(O, verbose); 6855 else { 6856 // This is the 32-bit non-arm cputype case. Which is normally 6857 // the first Objective-C ABI. But it may be the case of a 6858 // binary for the iOS simulator which is the second Objective-C 6859 // ABI. In that case printObjc1_32bit_MetaData() will determine that 6860 // and return false. 6861 if (!printObjc1_32bit_MetaData(O, verbose)) 6862 printObjc2_32bit_MetaData(O, verbose); 6863 } 6864 } 6865 } 6866 6867 // GuessLiteralPointer returns a string which for the item in the Mach-O file 6868 // for the address passed in as ReferenceValue for printing as a comment with 6869 // the instruction and also returns the corresponding type of that item 6870 // indirectly through ReferenceType. 6871 // 6872 // If ReferenceValue is an address of literal cstring then a pointer to the 6873 // cstring is returned and ReferenceType is set to 6874 // LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr . 6875 // 6876 // If ReferenceValue is an address of an Objective-C CFString, Selector ref or 6877 // Class ref that name is returned and the ReferenceType is set accordingly. 6878 // 6879 // Lastly, literals which are Symbol address in a literal pool are looked for 6880 // and if found the symbol name is returned and ReferenceType is set to 6881 // LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr . 6882 // 6883 // If there is no item in the Mach-O file for the address passed in as 6884 // ReferenceValue nullptr is returned and ReferenceType is unchanged. 6885 static const char *GuessLiteralPointer(uint64_t ReferenceValue, 6886 uint64_t ReferencePC, 6887 uint64_t *ReferenceType, 6888 struct DisassembleInfo *info) { 6889 // First see if there is an external relocation entry at the ReferencePC. 6890 if (info->O->getHeader().filetype == MachO::MH_OBJECT) { 6891 uint64_t sect_addr = info->S.getAddress(); 6892 uint64_t sect_offset = ReferencePC - sect_addr; 6893 bool reloc_found = false; 6894 DataRefImpl Rel; 6895 MachO::any_relocation_info RE; 6896 bool isExtern = false; 6897 SymbolRef Symbol; 6898 for (const RelocationRef &Reloc : info->S.relocations()) { 6899 uint64_t RelocOffset = Reloc.getOffset(); 6900 if (RelocOffset == sect_offset) { 6901 Rel = Reloc.getRawDataRefImpl(); 6902 RE = info->O->getRelocation(Rel); 6903 if (info->O->isRelocationScattered(RE)) 6904 continue; 6905 isExtern = info->O->getPlainRelocationExternal(RE); 6906 if (isExtern) { 6907 symbol_iterator RelocSym = Reloc.getSymbol(); 6908 Symbol = *RelocSym; 6909 } 6910 reloc_found = true; 6911 break; 6912 } 6913 } 6914 // If there is an external relocation entry for a symbol in a section 6915 // then used that symbol's value for the value of the reference. 6916 if (reloc_found && isExtern) { 6917 if (info->O->getAnyRelocationPCRel(RE)) { 6918 unsigned Type = info->O->getAnyRelocationType(RE); 6919 if (Type == MachO::X86_64_RELOC_SIGNED) { 6920 ReferenceValue = Symbol.getValue(); 6921 } 6922 } 6923 } 6924 } 6925 6926 // Look for literals such as Objective-C CFStrings refs, Selector refs, 6927 // Message refs and Class refs. 6928 bool classref, selref, msgref, cfstring; 6929 uint64_t pointer_value = GuessPointerPointer(ReferenceValue, info, classref, 6930 selref, msgref, cfstring); 6931 if (classref && pointer_value == 0) { 6932 // Note the ReferenceValue is a pointer into the __objc_classrefs section. 6933 // And the pointer_value in that section is typically zero as it will be 6934 // set by dyld as part of the "bind information". 6935 const char *name = get_dyld_bind_info_symbolname(ReferenceValue, info); 6936 if (name != nullptr) { 6937 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref; 6938 const char *class_name = strrchr(name, '$'); 6939 if (class_name != nullptr && class_name[1] == '_' && 6940 class_name[2] != '\0') { 6941 info->class_name = class_name + 2; 6942 return name; 6943 } 6944 } 6945 } 6946 6947 if (classref) { 6948 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref; 6949 const char *name = 6950 get_objc2_64bit_class_name(pointer_value, ReferenceValue, info); 6951 if (name != nullptr) 6952 info->class_name = name; 6953 else 6954 name = "bad class ref"; 6955 return name; 6956 } 6957 6958 if (cfstring) { 6959 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_CFString_Ref; 6960 const char *name = get_objc2_64bit_cfstring_name(ReferenceValue, info); 6961 return name; 6962 } 6963 6964 if (selref && pointer_value == 0) 6965 pointer_value = get_objc2_64bit_selref(ReferenceValue, info); 6966 6967 if (pointer_value != 0) 6968 ReferenceValue = pointer_value; 6969 6970 const char *name = GuessCstringPointer(ReferenceValue, info); 6971 if (name) { 6972 if (pointer_value != 0 && selref) { 6973 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Selector_Ref; 6974 info->selector_name = name; 6975 } else if (pointer_value != 0 && msgref) { 6976 info->class_name = nullptr; 6977 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message_Ref; 6978 info->selector_name = name; 6979 } else 6980 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr; 6981 return name; 6982 } 6983 6984 // Lastly look for an indirect symbol with this ReferenceValue which is in 6985 // a literal pool. If found return that symbol name. 6986 name = GuessIndirectSymbol(ReferenceValue, info); 6987 if (name) { 6988 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr; 6989 return name; 6990 } 6991 6992 return nullptr; 6993 } 6994 6995 // SymbolizerSymbolLookUp is the symbol lookup function passed when creating 6996 // the Symbolizer. It looks up the ReferenceValue using the info passed via the 6997 // pointer to the struct DisassembleInfo that was passed when MCSymbolizer 6998 // is created and returns the symbol name that matches the ReferenceValue or 6999 // nullptr if none. The ReferenceType is passed in for the IN type of 7000 // reference the instruction is making from the values in defined in the header 7001 // "llvm-c/Disassembler.h". On return the ReferenceType can set to a specific 7002 // Out type and the ReferenceName will also be set which is added as a comment 7003 // to the disassembled instruction. 7004 // 7005 // If the symbol name is a C++ mangled name then the demangled name is 7006 // returned through ReferenceName and ReferenceType is set to 7007 // LLVMDisassembler_ReferenceType_DeMangled_Name . 7008 // 7009 // When this is called to get a symbol name for a branch target then the 7010 // ReferenceType will be LLVMDisassembler_ReferenceType_In_Branch and then 7011 // SymbolValue will be looked for in the indirect symbol table to determine if 7012 // it is an address for a symbol stub. If so then the symbol name for that 7013 // stub is returned indirectly through ReferenceName and then ReferenceType is 7014 // set to LLVMDisassembler_ReferenceType_Out_SymbolStub. 7015 // 7016 // When this is called with an value loaded via a PC relative load then 7017 // ReferenceType will be LLVMDisassembler_ReferenceType_In_PCrel_Load then the 7018 // SymbolValue is checked to be an address of literal pointer, symbol pointer, 7019 // or an Objective-C meta data reference. If so the output ReferenceType is 7020 // set to correspond to that as well as setting the ReferenceName. 7021 static const char *SymbolizerSymbolLookUp(void *DisInfo, 7022 uint64_t ReferenceValue, 7023 uint64_t *ReferenceType, 7024 uint64_t ReferencePC, 7025 const char **ReferenceName) { 7026 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo; 7027 // If no verbose symbolic information is wanted then just return nullptr. 7028 if (!info->verbose) { 7029 *ReferenceName = nullptr; 7030 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None; 7031 return nullptr; 7032 } 7033 7034 const char *SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap); 7035 7036 if (*ReferenceType == LLVMDisassembler_ReferenceType_In_Branch) { 7037 *ReferenceName = GuessIndirectSymbol(ReferenceValue, info); 7038 if (*ReferenceName != nullptr) { 7039 method_reference(info, ReferenceType, ReferenceName); 7040 if (*ReferenceType != LLVMDisassembler_ReferenceType_Out_Objc_Message) 7041 *ReferenceType = LLVMDisassembler_ReferenceType_Out_SymbolStub; 7042 } else if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) { 7043 if (info->demangled_name != nullptr) 7044 free(info->demangled_name); 7045 int status; 7046 info->demangled_name = 7047 itaniumDemangle(SymbolName + 1, nullptr, nullptr, &status); 7048 if (info->demangled_name != nullptr) { 7049 *ReferenceName = info->demangled_name; 7050 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name; 7051 } else 7052 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None; 7053 } else 7054 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None; 7055 } else if (*ReferenceType == LLVMDisassembler_ReferenceType_In_PCrel_Load) { 7056 *ReferenceName = 7057 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info); 7058 if (*ReferenceName) 7059 method_reference(info, ReferenceType, ReferenceName); 7060 else 7061 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None; 7062 // If this is arm64 and the reference is an adrp instruction save the 7063 // instruction, passed in ReferenceValue and the address of the instruction 7064 // for use later if we see and add immediate instruction. 7065 } else if (info->O->getArch() == Triple::aarch64 && 7066 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADRP) { 7067 info->adrp_inst = ReferenceValue; 7068 info->adrp_addr = ReferencePC; 7069 SymbolName = nullptr; 7070 *ReferenceName = nullptr; 7071 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None; 7072 // If this is arm64 and reference is an add immediate instruction and we 7073 // have 7074 // seen an adrp instruction just before it and the adrp's Xd register 7075 // matches 7076 // this add's Xn register reconstruct the value being referenced and look to 7077 // see if it is a literal pointer. Note the add immediate instruction is 7078 // passed in ReferenceValue. 7079 } else if (info->O->getArch() == Triple::aarch64 && 7080 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADDXri && 7081 ReferencePC - 4 == info->adrp_addr && 7082 (info->adrp_inst & 0x9f000000) == 0x90000000 && 7083 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) { 7084 uint32_t addxri_inst; 7085 uint64_t adrp_imm, addxri_imm; 7086 7087 adrp_imm = 7088 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3); 7089 if (info->adrp_inst & 0x0200000) 7090 adrp_imm |= 0xfffffffffc000000LL; 7091 7092 addxri_inst = ReferenceValue; 7093 addxri_imm = (addxri_inst >> 10) & 0xfff; 7094 if (((addxri_inst >> 22) & 0x3) == 1) 7095 addxri_imm <<= 12; 7096 7097 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) + 7098 (adrp_imm << 12) + addxri_imm; 7099 7100 *ReferenceName = 7101 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info); 7102 if (*ReferenceName == nullptr) 7103 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None; 7104 // If this is arm64 and the reference is a load register instruction and we 7105 // have seen an adrp instruction just before it and the adrp's Xd register 7106 // matches this add's Xn register reconstruct the value being referenced and 7107 // look to see if it is a literal pointer. Note the load register 7108 // instruction is passed in ReferenceValue. 7109 } else if (info->O->getArch() == Triple::aarch64 && 7110 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXui && 7111 ReferencePC - 4 == info->adrp_addr && 7112 (info->adrp_inst & 0x9f000000) == 0x90000000 && 7113 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) { 7114 uint32_t ldrxui_inst; 7115 uint64_t adrp_imm, ldrxui_imm; 7116 7117 adrp_imm = 7118 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3); 7119 if (info->adrp_inst & 0x0200000) 7120 adrp_imm |= 0xfffffffffc000000LL; 7121 7122 ldrxui_inst = ReferenceValue; 7123 ldrxui_imm = (ldrxui_inst >> 10) & 0xfff; 7124 7125 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) + 7126 (adrp_imm << 12) + (ldrxui_imm << 3); 7127 7128 *ReferenceName = 7129 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info); 7130 if (*ReferenceName == nullptr) 7131 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None; 7132 } 7133 // If this arm64 and is an load register (PC-relative) instruction the 7134 // ReferenceValue is the PC plus the immediate value. 7135 else if (info->O->getArch() == Triple::aarch64 && 7136 (*ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXl || 7137 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADR)) { 7138 *ReferenceName = 7139 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info); 7140 if (*ReferenceName == nullptr) 7141 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None; 7142 } else if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) { 7143 if (info->demangled_name != nullptr) 7144 free(info->demangled_name); 7145 int status; 7146 info->demangled_name = 7147 itaniumDemangle(SymbolName + 1, nullptr, nullptr, &status); 7148 if (info->demangled_name != nullptr) { 7149 *ReferenceName = info->demangled_name; 7150 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name; 7151 } 7152 } 7153 else { 7154 *ReferenceName = nullptr; 7155 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None; 7156 } 7157 7158 return SymbolName; 7159 } 7160 7161 /// Emits the comments that are stored in the CommentStream. 7162 /// Each comment in the CommentStream must end with a newline. 7163 static void emitComments(raw_svector_ostream &CommentStream, 7164 SmallString<128> &CommentsToEmit, 7165 formatted_raw_ostream &FormattedOS, 7166 const MCAsmInfo &MAI) { 7167 // Flush the stream before taking its content. 7168 StringRef Comments = CommentsToEmit.str(); 7169 // Get the default information for printing a comment. 7170 StringRef CommentBegin = MAI.getCommentString(); 7171 unsigned CommentColumn = MAI.getCommentColumn(); 7172 bool IsFirst = true; 7173 while (!Comments.empty()) { 7174 if (!IsFirst) 7175 FormattedOS << '\n'; 7176 // Emit a line of comments. 7177 FormattedOS.PadToColumn(CommentColumn); 7178 size_t Position = Comments.find('\n'); 7179 FormattedOS << CommentBegin << ' ' << Comments.substr(0, Position); 7180 // Move after the newline character. 7181 Comments = Comments.substr(Position + 1); 7182 IsFirst = false; 7183 } 7184 FormattedOS.flush(); 7185 7186 // Tell the comment stream that the vector changed underneath it. 7187 CommentsToEmit.clear(); 7188 } 7189 7190 static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF, 7191 StringRef DisSegName, StringRef DisSectName) { 7192 const char *McpuDefault = nullptr; 7193 const Target *ThumbTarget = nullptr; 7194 const Target *TheTarget = GetTarget(MachOOF, &McpuDefault, &ThumbTarget); 7195 if (!TheTarget) { 7196 // GetTarget prints out stuff. 7197 return; 7198 } 7199 std::string MachOMCPU; 7200 if (MCPU.empty() && McpuDefault) 7201 MachOMCPU = McpuDefault; 7202 else 7203 MachOMCPU = MCPU; 7204 7205 std::unique_ptr<const MCInstrInfo> InstrInfo(TheTarget->createMCInstrInfo()); 7206 std::unique_ptr<const MCInstrInfo> ThumbInstrInfo; 7207 if (ThumbTarget) 7208 ThumbInstrInfo.reset(ThumbTarget->createMCInstrInfo()); 7209 7210 // Package up features to be passed to target/subtarget 7211 std::string FeaturesStr; 7212 if (!MAttrs.empty()) { 7213 SubtargetFeatures Features; 7214 for (unsigned i = 0; i != MAttrs.size(); ++i) 7215 Features.AddFeature(MAttrs[i]); 7216 FeaturesStr = Features.getString(); 7217 } 7218 7219 MCTargetOptions MCOptions; 7220 // Set up disassembler. 7221 std::unique_ptr<const MCRegisterInfo> MRI( 7222 TheTarget->createMCRegInfo(TripleName)); 7223 std::unique_ptr<const MCAsmInfo> AsmInfo( 7224 TheTarget->createMCAsmInfo(*MRI, TripleName, MCOptions)); 7225 std::unique_ptr<const MCSubtargetInfo> STI( 7226 TheTarget->createMCSubtargetInfo(TripleName, MachOMCPU, FeaturesStr)); 7227 MCContext Ctx(AsmInfo.get(), MRI.get(), nullptr); 7228 std::unique_ptr<MCDisassembler> DisAsm( 7229 TheTarget->createMCDisassembler(*STI, Ctx)); 7230 std::unique_ptr<MCSymbolizer> Symbolizer; 7231 struct DisassembleInfo SymbolizerInfo(nullptr, nullptr, nullptr, false); 7232 std::unique_ptr<MCRelocationInfo> RelInfo( 7233 TheTarget->createMCRelocationInfo(TripleName, Ctx)); 7234 if (RelInfo) { 7235 Symbolizer.reset(TheTarget->createMCSymbolizer( 7236 TripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp, 7237 &SymbolizerInfo, &Ctx, std::move(RelInfo))); 7238 DisAsm->setSymbolizer(std::move(Symbolizer)); 7239 } 7240 int AsmPrinterVariant = AsmInfo->getAssemblerDialect(); 7241 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter( 7242 Triple(TripleName), AsmPrinterVariant, *AsmInfo, *InstrInfo, *MRI)); 7243 // Set the display preference for hex vs. decimal immediates. 7244 IP->setPrintImmHex(PrintImmHex); 7245 // Comment stream and backing vector. 7246 SmallString<128> CommentsToEmit; 7247 raw_svector_ostream CommentStream(CommentsToEmit); 7248 // FIXME: Setting the CommentStream in the InstPrinter is problematic in that 7249 // if it is done then arm64 comments for string literals don't get printed 7250 // and some constant get printed instead and not setting it causes intel 7251 // (32-bit and 64-bit) comments printed with different spacing before the 7252 // comment causing different diffs with the 'C' disassembler library API. 7253 // IP->setCommentStream(CommentStream); 7254 7255 if (!AsmInfo || !STI || !DisAsm || !IP) { 7256 WithColor::error(errs(), "llvm-objdump") 7257 << "couldn't initialize disassembler for target " << TripleName << '\n'; 7258 return; 7259 } 7260 7261 // Set up separate thumb disassembler if needed. 7262 std::unique_ptr<const MCRegisterInfo> ThumbMRI; 7263 std::unique_ptr<const MCAsmInfo> ThumbAsmInfo; 7264 std::unique_ptr<const MCSubtargetInfo> ThumbSTI; 7265 std::unique_ptr<MCDisassembler> ThumbDisAsm; 7266 std::unique_ptr<MCInstPrinter> ThumbIP; 7267 std::unique_ptr<MCContext> ThumbCtx; 7268 std::unique_ptr<MCSymbolizer> ThumbSymbolizer; 7269 struct DisassembleInfo ThumbSymbolizerInfo(nullptr, nullptr, nullptr, false); 7270 std::unique_ptr<MCRelocationInfo> ThumbRelInfo; 7271 if (ThumbTarget) { 7272 ThumbMRI.reset(ThumbTarget->createMCRegInfo(ThumbTripleName)); 7273 ThumbAsmInfo.reset( 7274 ThumbTarget->createMCAsmInfo(*ThumbMRI, ThumbTripleName, MCOptions)); 7275 ThumbSTI.reset( 7276 ThumbTarget->createMCSubtargetInfo(ThumbTripleName, MachOMCPU, 7277 FeaturesStr)); 7278 ThumbCtx.reset(new MCContext(ThumbAsmInfo.get(), ThumbMRI.get(), nullptr)); 7279 ThumbDisAsm.reset(ThumbTarget->createMCDisassembler(*ThumbSTI, *ThumbCtx)); 7280 MCContext *PtrThumbCtx = ThumbCtx.get(); 7281 ThumbRelInfo.reset( 7282 ThumbTarget->createMCRelocationInfo(ThumbTripleName, *PtrThumbCtx)); 7283 if (ThumbRelInfo) { 7284 ThumbSymbolizer.reset(ThumbTarget->createMCSymbolizer( 7285 ThumbTripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp, 7286 &ThumbSymbolizerInfo, PtrThumbCtx, std::move(ThumbRelInfo))); 7287 ThumbDisAsm->setSymbolizer(std::move(ThumbSymbolizer)); 7288 } 7289 int ThumbAsmPrinterVariant = ThumbAsmInfo->getAssemblerDialect(); 7290 ThumbIP.reset(ThumbTarget->createMCInstPrinter( 7291 Triple(ThumbTripleName), ThumbAsmPrinterVariant, *ThumbAsmInfo, 7292 *ThumbInstrInfo, *ThumbMRI)); 7293 // Set the display preference for hex vs. decimal immediates. 7294 ThumbIP->setPrintImmHex(PrintImmHex); 7295 } 7296 7297 if (ThumbTarget && (!ThumbAsmInfo || !ThumbSTI || !ThumbDisAsm || !ThumbIP)) { 7298 WithColor::error(errs(), "llvm-objdump") 7299 << "couldn't initialize disassembler for target " << ThumbTripleName 7300 << '\n'; 7301 return; 7302 } 7303 7304 MachO::mach_header Header = MachOOF->getHeader(); 7305 7306 // FIXME: Using the -cfg command line option, this code used to be able to 7307 // annotate relocations with the referenced symbol's name, and if this was 7308 // inside a __[cf]string section, the data it points to. This is now replaced 7309 // by the upcoming MCSymbolizer, which needs the appropriate setup done above. 7310 std::vector<SectionRef> Sections; 7311 std::vector<SymbolRef> Symbols; 7312 SmallVector<uint64_t, 8> FoundFns; 7313 uint64_t BaseSegmentAddress = 0; 7314 7315 getSectionsAndSymbols(MachOOF, Sections, Symbols, FoundFns, 7316 BaseSegmentAddress); 7317 7318 // Sort the symbols by address, just in case they didn't come in that way. 7319 llvm::sort(Symbols, SymbolSorter()); 7320 7321 // Build a data in code table that is sorted on by the address of each entry. 7322 uint64_t BaseAddress = 0; 7323 if (Header.filetype == MachO::MH_OBJECT) 7324 BaseAddress = Sections[0].getAddress(); 7325 else 7326 BaseAddress = BaseSegmentAddress; 7327 DiceTable Dices; 7328 for (dice_iterator DI = MachOOF->begin_dices(), DE = MachOOF->end_dices(); 7329 DI != DE; ++DI) { 7330 uint32_t Offset; 7331 DI->getOffset(Offset); 7332 Dices.push_back(std::make_pair(BaseAddress + Offset, *DI)); 7333 } 7334 array_pod_sort(Dices.begin(), Dices.end()); 7335 7336 // Try to find debug info and set up the DIContext for it. 7337 std::unique_ptr<DIContext> diContext; 7338 std::unique_ptr<Binary> DSYMBinary; 7339 std::unique_ptr<MemoryBuffer> DSYMBuf; 7340 if (UseDbg) { 7341 ObjectFile *DbgObj = MachOOF; 7342 7343 // A separate DSym file path was specified, parse it as a macho file, 7344 // get the sections and supply it to the section name parsing machinery. 7345 if (!DSYMFile.empty()) { 7346 std::string DSYMPath(DSYMFile); 7347 7348 // If DSYMPath is a .dSYM directory, append the Mach-O file. 7349 if (llvm::sys::fs::is_directory(DSYMPath) && 7350 llvm::sys::path::extension(DSYMPath) == ".dSYM") { 7351 SmallString<128> ShortName(llvm::sys::path::filename(DSYMPath)); 7352 llvm::sys::path::replace_extension(ShortName, ""); 7353 SmallString<1024> FullPath(DSYMPath); 7354 llvm::sys::path::append(FullPath, "Contents", "Resources", "DWARF", 7355 ShortName); 7356 DSYMPath = std::string(FullPath.str()); 7357 } 7358 7359 // Load the file. 7360 ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr = 7361 MemoryBuffer::getFileOrSTDIN(DSYMPath); 7362 if (std::error_code EC = BufOrErr.getError()) { 7363 reportError(errorCodeToError(EC), DSYMPath); 7364 return; 7365 } 7366 7367 // We need to keep the file alive, because we're replacing DbgObj with it. 7368 DSYMBuf = std::move(BufOrErr.get()); 7369 7370 Expected<std::unique_ptr<Binary>> BinaryOrErr = 7371 createBinary(DSYMBuf.get()->getMemBufferRef()); 7372 if (!BinaryOrErr) { 7373 reportError(BinaryOrErr.takeError(), DSYMPath); 7374 return; 7375 } 7376 7377 // We need to keep the Binary alive with the buffer 7378 DSYMBinary = std::move(BinaryOrErr.get()); 7379 if (ObjectFile *O = dyn_cast<ObjectFile>(DSYMBinary.get())) { 7380 // this is a Mach-O object file, use it 7381 if (MachOObjectFile *MachDSYM = dyn_cast<MachOObjectFile>(&*O)) { 7382 DbgObj = MachDSYM; 7383 } 7384 else { 7385 WithColor::error(errs(), "llvm-objdump") 7386 << DSYMPath << " is not a Mach-O file type.\n"; 7387 return; 7388 } 7389 } 7390 else if (auto UB = dyn_cast<MachOUniversalBinary>(DSYMBinary.get())){ 7391 // this is a Universal Binary, find a Mach-O for this architecture 7392 uint32_t CPUType, CPUSubType; 7393 const char *ArchFlag; 7394 if (MachOOF->is64Bit()) { 7395 const MachO::mach_header_64 H_64 = MachOOF->getHeader64(); 7396 CPUType = H_64.cputype; 7397 CPUSubType = H_64.cpusubtype; 7398 } else { 7399 const MachO::mach_header H = MachOOF->getHeader(); 7400 CPUType = H.cputype; 7401 CPUSubType = H.cpusubtype; 7402 } 7403 Triple T = MachOObjectFile::getArchTriple(CPUType, CPUSubType, nullptr, 7404 &ArchFlag); 7405 Expected<std::unique_ptr<MachOObjectFile>> MachDSYM = 7406 UB->getMachOObjectForArch(ArchFlag); 7407 if (!MachDSYM) { 7408 reportError(MachDSYM.takeError(), DSYMPath); 7409 return; 7410 } 7411 7412 // We need to keep the Binary alive with the buffer 7413 DbgObj = &*MachDSYM.get(); 7414 DSYMBinary = std::move(*MachDSYM); 7415 } 7416 else { 7417 WithColor::error(errs(), "llvm-objdump") 7418 << DSYMPath << " is not a Mach-O or Universal file type.\n"; 7419 return; 7420 } 7421 } 7422 7423 // Setup the DIContext 7424 diContext = DWARFContext::create(*DbgObj); 7425 } 7426 7427 if (FilterSections.empty()) 7428 outs() << "(" << DisSegName << "," << DisSectName << ") section\n"; 7429 7430 for (unsigned SectIdx = 0; SectIdx != Sections.size(); SectIdx++) { 7431 Expected<StringRef> SecNameOrErr = Sections[SectIdx].getName(); 7432 if (!SecNameOrErr) { 7433 consumeError(SecNameOrErr.takeError()); 7434 continue; 7435 } 7436 if (*SecNameOrErr != DisSectName) 7437 continue; 7438 7439 DataRefImpl DR = Sections[SectIdx].getRawDataRefImpl(); 7440 7441 StringRef SegmentName = MachOOF->getSectionFinalSegmentName(DR); 7442 if (SegmentName != DisSegName) 7443 continue; 7444 7445 StringRef BytesStr = 7446 unwrapOrError(Sections[SectIdx].getContents(), Filename); 7447 ArrayRef<uint8_t> Bytes = arrayRefFromStringRef(BytesStr); 7448 uint64_t SectAddress = Sections[SectIdx].getAddress(); 7449 7450 bool symbolTableWorked = false; 7451 7452 // Create a map of symbol addresses to symbol names for use by 7453 // the SymbolizerSymbolLookUp() routine. 7454 SymbolAddressMap AddrMap; 7455 bool DisSymNameFound = false; 7456 for (const SymbolRef &Symbol : MachOOF->symbols()) { 7457 SymbolRef::Type ST = 7458 unwrapOrError(Symbol.getType(), MachOOF->getFileName()); 7459 if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data || 7460 ST == SymbolRef::ST_Other) { 7461 uint64_t Address = Symbol.getValue(); 7462 StringRef SymName = 7463 unwrapOrError(Symbol.getName(), MachOOF->getFileName()); 7464 AddrMap[Address] = SymName; 7465 if (!DisSymName.empty() && DisSymName == SymName) 7466 DisSymNameFound = true; 7467 } 7468 } 7469 if (!DisSymName.empty() && !DisSymNameFound) { 7470 outs() << "Can't find -dis-symname: " << DisSymName << "\n"; 7471 return; 7472 } 7473 // Set up the block of info used by the Symbolizer call backs. 7474 SymbolizerInfo.verbose = !NoSymbolicOperands; 7475 SymbolizerInfo.O = MachOOF; 7476 SymbolizerInfo.S = Sections[SectIdx]; 7477 SymbolizerInfo.AddrMap = &AddrMap; 7478 SymbolizerInfo.Sections = &Sections; 7479 // Same for the ThumbSymbolizer 7480 ThumbSymbolizerInfo.verbose = !NoSymbolicOperands; 7481 ThumbSymbolizerInfo.O = MachOOF; 7482 ThumbSymbolizerInfo.S = Sections[SectIdx]; 7483 ThumbSymbolizerInfo.AddrMap = &AddrMap; 7484 ThumbSymbolizerInfo.Sections = &Sections; 7485 7486 unsigned int Arch = MachOOF->getArch(); 7487 7488 // Skip all symbols if this is a stubs file. 7489 if (Bytes.empty()) 7490 return; 7491 7492 // If the section has symbols but no symbol at the start of the section 7493 // these are used to make sure the bytes before the first symbol are 7494 // disassembled. 7495 bool FirstSymbol = true; 7496 bool FirstSymbolAtSectionStart = true; 7497 7498 // Disassemble symbol by symbol. 7499 for (unsigned SymIdx = 0; SymIdx != Symbols.size(); SymIdx++) { 7500 StringRef SymName = 7501 unwrapOrError(Symbols[SymIdx].getName(), MachOOF->getFileName()); 7502 SymbolRef::Type ST = 7503 unwrapOrError(Symbols[SymIdx].getType(), MachOOF->getFileName()); 7504 if (ST != SymbolRef::ST_Function && ST != SymbolRef::ST_Data) 7505 continue; 7506 7507 // Make sure the symbol is defined in this section. 7508 bool containsSym = Sections[SectIdx].containsSymbol(Symbols[SymIdx]); 7509 if (!containsSym) { 7510 if (!DisSymName.empty() && DisSymName == SymName) { 7511 outs() << "-dis-symname: " << DisSymName << " not in the section\n"; 7512 return; 7513 } 7514 continue; 7515 } 7516 // The __mh_execute_header is special and we need to deal with that fact 7517 // this symbol is before the start of the (__TEXT,__text) section and at the 7518 // address of the start of the __TEXT segment. This is because this symbol 7519 // is an N_SECT symbol in the (__TEXT,__text) but its address is before the 7520 // start of the section in a standard MH_EXECUTE filetype. 7521 if (!DisSymName.empty() && DisSymName == "__mh_execute_header") { 7522 outs() << "-dis-symname: __mh_execute_header not in any section\n"; 7523 return; 7524 } 7525 // When this code is trying to disassemble a symbol at a time and in the 7526 // case there is only the __mh_execute_header symbol left as in a stripped 7527 // executable, we need to deal with this by ignoring this symbol so the 7528 // whole section is disassembled and this symbol is then not displayed. 7529 if (SymName == "__mh_execute_header" || SymName == "__mh_dylib_header" || 7530 SymName == "__mh_bundle_header" || SymName == "__mh_object_header" || 7531 SymName == "__mh_preload_header" || SymName == "__mh_dylinker_header") 7532 continue; 7533 7534 // If we are only disassembling one symbol see if this is that symbol. 7535 if (!DisSymName.empty() && DisSymName != SymName) 7536 continue; 7537 7538 // Start at the address of the symbol relative to the section's address. 7539 uint64_t SectSize = Sections[SectIdx].getSize(); 7540 uint64_t Start = Symbols[SymIdx].getValue(); 7541 uint64_t SectionAddress = Sections[SectIdx].getAddress(); 7542 Start -= SectionAddress; 7543 7544 if (Start > SectSize) { 7545 outs() << "section data ends, " << SymName 7546 << " lies outside valid range\n"; 7547 return; 7548 } 7549 7550 // Stop disassembling either at the beginning of the next symbol or at 7551 // the end of the section. 7552 bool containsNextSym = false; 7553 uint64_t NextSym = 0; 7554 uint64_t NextSymIdx = SymIdx + 1; 7555 while (Symbols.size() > NextSymIdx) { 7556 SymbolRef::Type NextSymType = unwrapOrError( 7557 Symbols[NextSymIdx].getType(), MachOOF->getFileName()); 7558 if (NextSymType == SymbolRef::ST_Function) { 7559 containsNextSym = 7560 Sections[SectIdx].containsSymbol(Symbols[NextSymIdx]); 7561 NextSym = Symbols[NextSymIdx].getValue(); 7562 NextSym -= SectionAddress; 7563 break; 7564 } 7565 ++NextSymIdx; 7566 } 7567 7568 uint64_t End = containsNextSym ? std::min(NextSym, SectSize) : SectSize; 7569 uint64_t Size; 7570 7571 symbolTableWorked = true; 7572 7573 DataRefImpl Symb = Symbols[SymIdx].getRawDataRefImpl(); 7574 bool IsThumb = MachOOF->getSymbolFlags(Symb) & SymbolRef::SF_Thumb; 7575 7576 // We only need the dedicated Thumb target if there's a real choice 7577 // (i.e. we're not targeting M-class) and the function is Thumb. 7578 bool UseThumbTarget = IsThumb && ThumbTarget; 7579 7580 // If we are not specifying a symbol to start disassembly with and this 7581 // is the first symbol in the section but not at the start of the section 7582 // then move the disassembly index to the start of the section and 7583 // don't print the symbol name just yet. This is so the bytes before the 7584 // first symbol are disassembled. 7585 uint64_t SymbolStart = Start; 7586 if (DisSymName.empty() && FirstSymbol && Start != 0) { 7587 FirstSymbolAtSectionStart = false; 7588 Start = 0; 7589 } 7590 else 7591 outs() << SymName << ":\n"; 7592 7593 DILineInfo lastLine; 7594 for (uint64_t Index = Start; Index < End; Index += Size) { 7595 MCInst Inst; 7596 7597 // If this is the first symbol in the section and it was not at the 7598 // start of the section, see if we are at its Index now and if so print 7599 // the symbol name. 7600 if (FirstSymbol && !FirstSymbolAtSectionStart && Index == SymbolStart) 7601 outs() << SymName << ":\n"; 7602 7603 uint64_t PC = SectAddress + Index; 7604 if (!NoLeadingAddr) { 7605 if (FullLeadingAddr) { 7606 if (MachOOF->is64Bit()) 7607 outs() << format("%016" PRIx64, PC); 7608 else 7609 outs() << format("%08" PRIx64, PC); 7610 } else { 7611 outs() << format("%8" PRIx64 ":", PC); 7612 } 7613 } 7614 if (!NoShowRawInsn || Arch == Triple::arm) 7615 outs() << "\t"; 7616 7617 if (DumpAndSkipDataInCode(PC, Bytes.data() + Index, Dices, Size)) 7618 continue; 7619 7620 SmallVector<char, 64> AnnotationsBytes; 7621 raw_svector_ostream Annotations(AnnotationsBytes); 7622 7623 bool gotInst; 7624 if (UseThumbTarget) 7625 gotInst = ThumbDisAsm->getInstruction(Inst, Size, Bytes.slice(Index), 7626 PC, Annotations); 7627 else 7628 gotInst = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index), PC, 7629 Annotations); 7630 if (gotInst) { 7631 if (!NoShowRawInsn || Arch == Triple::arm) { 7632 dumpBytes(makeArrayRef(Bytes.data() + Index, Size), outs()); 7633 } 7634 formatted_raw_ostream FormattedOS(outs()); 7635 StringRef AnnotationsStr = Annotations.str(); 7636 if (UseThumbTarget) 7637 ThumbIP->printInst(&Inst, PC, AnnotationsStr, *ThumbSTI, 7638 FormattedOS); 7639 else 7640 IP->printInst(&Inst, PC, AnnotationsStr, *STI, FormattedOS); 7641 emitComments(CommentStream, CommentsToEmit, FormattedOS, *AsmInfo); 7642 7643 // Print debug info. 7644 if (diContext) { 7645 DILineInfo dli = diContext->getLineInfoForAddress({PC, SectIdx}); 7646 // Print valid line info if it changed. 7647 if (dli != lastLine && dli.Line != 0) 7648 outs() << "\t## " << dli.FileName << ':' << dli.Line << ':' 7649 << dli.Column; 7650 lastLine = dli; 7651 } 7652 outs() << "\n"; 7653 } else { 7654 if (MachOOF->getArchTriple().isX86()) { 7655 outs() << format("\t.byte 0x%02x #bad opcode\n", 7656 *(Bytes.data() + Index) & 0xff); 7657 Size = 1; // skip exactly one illegible byte and move on. 7658 } else if (Arch == Triple::aarch64 || 7659 (Arch == Triple::arm && !IsThumb)) { 7660 uint32_t opcode = (*(Bytes.data() + Index) & 0xff) | 7661 (*(Bytes.data() + Index + 1) & 0xff) << 8 | 7662 (*(Bytes.data() + Index + 2) & 0xff) << 16 | 7663 (*(Bytes.data() + Index + 3) & 0xff) << 24; 7664 outs() << format("\t.long\t0x%08x\n", opcode); 7665 Size = 4; 7666 } else if (Arch == Triple::arm) { 7667 assert(IsThumb && "ARM mode should have been dealt with above"); 7668 uint32_t opcode = (*(Bytes.data() + Index) & 0xff) | 7669 (*(Bytes.data() + Index + 1) & 0xff) << 8; 7670 outs() << format("\t.short\t0x%04x\n", opcode); 7671 Size = 2; 7672 } else{ 7673 WithColor::warning(errs(), "llvm-objdump") 7674 << "invalid instruction encoding\n"; 7675 if (Size == 0) 7676 Size = 1; // skip illegible bytes 7677 } 7678 } 7679 } 7680 // Now that we are done disassembled the first symbol set the bool that 7681 // were doing this to false. 7682 FirstSymbol = false; 7683 } 7684 if (!symbolTableWorked) { 7685 // Reading the symbol table didn't work, disassemble the whole section. 7686 uint64_t SectAddress = Sections[SectIdx].getAddress(); 7687 uint64_t SectSize = Sections[SectIdx].getSize(); 7688 uint64_t InstSize; 7689 for (uint64_t Index = 0; Index < SectSize; Index += InstSize) { 7690 MCInst Inst; 7691 7692 uint64_t PC = SectAddress + Index; 7693 7694 if (DumpAndSkipDataInCode(PC, Bytes.data() + Index, Dices, InstSize)) 7695 continue; 7696 7697 SmallVector<char, 64> AnnotationsBytes; 7698 raw_svector_ostream Annotations(AnnotationsBytes); 7699 if (DisAsm->getInstruction(Inst, InstSize, Bytes.slice(Index), PC, 7700 Annotations)) { 7701 if (!NoLeadingAddr) { 7702 if (FullLeadingAddr) { 7703 if (MachOOF->is64Bit()) 7704 outs() << format("%016" PRIx64, PC); 7705 else 7706 outs() << format("%08" PRIx64, PC); 7707 } else { 7708 outs() << format("%8" PRIx64 ":", PC); 7709 } 7710 } 7711 if (!NoShowRawInsn || Arch == Triple::arm) { 7712 outs() << "\t"; 7713 dumpBytes(makeArrayRef(Bytes.data() + Index, InstSize), outs()); 7714 } 7715 StringRef AnnotationsStr = Annotations.str(); 7716 IP->printInst(&Inst, PC, AnnotationsStr, *STI, outs()); 7717 outs() << "\n"; 7718 } else { 7719 if (MachOOF->getArchTriple().isX86()) { 7720 outs() << format("\t.byte 0x%02x #bad opcode\n", 7721 *(Bytes.data() + Index) & 0xff); 7722 InstSize = 1; // skip exactly one illegible byte and move on. 7723 } else { 7724 WithColor::warning(errs(), "llvm-objdump") 7725 << "invalid instruction encoding\n"; 7726 if (InstSize == 0) 7727 InstSize = 1; // skip illegible bytes 7728 } 7729 } 7730 } 7731 } 7732 // The TripleName's need to be reset if we are called again for a different 7733 // architecture. 7734 TripleName = ""; 7735 ThumbTripleName = ""; 7736 7737 if (SymbolizerInfo.demangled_name != nullptr) 7738 free(SymbolizerInfo.demangled_name); 7739 if (ThumbSymbolizerInfo.demangled_name != nullptr) 7740 free(ThumbSymbolizerInfo.demangled_name); 7741 } 7742 } 7743 7744 //===----------------------------------------------------------------------===// 7745 // __compact_unwind section dumping 7746 //===----------------------------------------------------------------------===// 7747 7748 namespace { 7749 7750 template <typename T> 7751 static uint64_t read(StringRef Contents, ptrdiff_t Offset) { 7752 using llvm::support::little; 7753 using llvm::support::unaligned; 7754 7755 if (Offset + sizeof(T) > Contents.size()) { 7756 outs() << "warning: attempt to read past end of buffer\n"; 7757 return T(); 7758 } 7759 7760 uint64_t Val = 7761 support::endian::read<T, little, unaligned>(Contents.data() + Offset); 7762 return Val; 7763 } 7764 7765 template <typename T> 7766 static uint64_t readNext(StringRef Contents, ptrdiff_t &Offset) { 7767 T Val = read<T>(Contents, Offset); 7768 Offset += sizeof(T); 7769 return Val; 7770 } 7771 7772 struct CompactUnwindEntry { 7773 uint32_t OffsetInSection; 7774 7775 uint64_t FunctionAddr; 7776 uint32_t Length; 7777 uint32_t CompactEncoding; 7778 uint64_t PersonalityAddr; 7779 uint64_t LSDAAddr; 7780 7781 RelocationRef FunctionReloc; 7782 RelocationRef PersonalityReloc; 7783 RelocationRef LSDAReloc; 7784 7785 CompactUnwindEntry(StringRef Contents, unsigned Offset, bool Is64) 7786 : OffsetInSection(Offset) { 7787 if (Is64) 7788 read<uint64_t>(Contents, Offset); 7789 else 7790 read<uint32_t>(Contents, Offset); 7791 } 7792 7793 private: 7794 template <typename UIntPtr> void read(StringRef Contents, ptrdiff_t Offset) { 7795 FunctionAddr = readNext<UIntPtr>(Contents, Offset); 7796 Length = readNext<uint32_t>(Contents, Offset); 7797 CompactEncoding = readNext<uint32_t>(Contents, Offset); 7798 PersonalityAddr = readNext<UIntPtr>(Contents, Offset); 7799 LSDAAddr = readNext<UIntPtr>(Contents, Offset); 7800 } 7801 }; 7802 } 7803 7804 /// Given a relocation from __compact_unwind, consisting of the RelocationRef 7805 /// and data being relocated, determine the best base Name and Addend to use for 7806 /// display purposes. 7807 /// 7808 /// 1. An Extern relocation will directly reference a symbol (and the data is 7809 /// then already an addend), so use that. 7810 /// 2. Otherwise the data is an offset in the object file's layout; try to find 7811 // a symbol before it in the same section, and use the offset from there. 7812 /// 3. Finally, if all that fails, fall back to an offset from the start of the 7813 /// referenced section. 7814 static void findUnwindRelocNameAddend(const MachOObjectFile *Obj, 7815 std::map<uint64_t, SymbolRef> &Symbols, 7816 const RelocationRef &Reloc, uint64_t Addr, 7817 StringRef &Name, uint64_t &Addend) { 7818 if (Reloc.getSymbol() != Obj->symbol_end()) { 7819 Name = unwrapOrError(Reloc.getSymbol()->getName(), Obj->getFileName()); 7820 Addend = Addr; 7821 return; 7822 } 7823 7824 auto RE = Obj->getRelocation(Reloc.getRawDataRefImpl()); 7825 SectionRef RelocSection = Obj->getAnyRelocationSection(RE); 7826 7827 uint64_t SectionAddr = RelocSection.getAddress(); 7828 7829 auto Sym = Symbols.upper_bound(Addr); 7830 if (Sym == Symbols.begin()) { 7831 // The first symbol in the object is after this reference, the best we can 7832 // do is section-relative notation. 7833 if (Expected<StringRef> NameOrErr = RelocSection.getName()) 7834 Name = *NameOrErr; 7835 else 7836 consumeError(NameOrErr.takeError()); 7837 7838 Addend = Addr - SectionAddr; 7839 return; 7840 } 7841 7842 // Go back one so that SymbolAddress <= Addr. 7843 --Sym; 7844 7845 section_iterator SymSection = 7846 unwrapOrError(Sym->second.getSection(), Obj->getFileName()); 7847 if (RelocSection == *SymSection) { 7848 // There's a valid symbol in the same section before this reference. 7849 Name = unwrapOrError(Sym->second.getName(), Obj->getFileName()); 7850 Addend = Addr - Sym->first; 7851 return; 7852 } 7853 7854 // There is a symbol before this reference, but it's in a different 7855 // section. Probably not helpful to mention it, so use the section name. 7856 if (Expected<StringRef> NameOrErr = RelocSection.getName()) 7857 Name = *NameOrErr; 7858 else 7859 consumeError(NameOrErr.takeError()); 7860 7861 Addend = Addr - SectionAddr; 7862 } 7863 7864 static void printUnwindRelocDest(const MachOObjectFile *Obj, 7865 std::map<uint64_t, SymbolRef> &Symbols, 7866 const RelocationRef &Reloc, uint64_t Addr) { 7867 StringRef Name; 7868 uint64_t Addend; 7869 7870 if (!Reloc.getObject()) 7871 return; 7872 7873 findUnwindRelocNameAddend(Obj, Symbols, Reloc, Addr, Name, Addend); 7874 7875 outs() << Name; 7876 if (Addend) 7877 outs() << " + " << format("0x%" PRIx64, Addend); 7878 } 7879 7880 static void 7881 printMachOCompactUnwindSection(const MachOObjectFile *Obj, 7882 std::map<uint64_t, SymbolRef> &Symbols, 7883 const SectionRef &CompactUnwind) { 7884 7885 if (!Obj->isLittleEndian()) { 7886 outs() << "Skipping big-endian __compact_unwind section\n"; 7887 return; 7888 } 7889 7890 bool Is64 = Obj->is64Bit(); 7891 uint32_t PointerSize = Is64 ? sizeof(uint64_t) : sizeof(uint32_t); 7892 uint32_t EntrySize = 3 * PointerSize + 2 * sizeof(uint32_t); 7893 7894 StringRef Contents = 7895 unwrapOrError(CompactUnwind.getContents(), Obj->getFileName()); 7896 SmallVector<CompactUnwindEntry, 4> CompactUnwinds; 7897 7898 // First populate the initial raw offsets, encodings and so on from the entry. 7899 for (unsigned Offset = 0; Offset < Contents.size(); Offset += EntrySize) { 7900 CompactUnwindEntry Entry(Contents, Offset, Is64); 7901 CompactUnwinds.push_back(Entry); 7902 } 7903 7904 // Next we need to look at the relocations to find out what objects are 7905 // actually being referred to. 7906 for (const RelocationRef &Reloc : CompactUnwind.relocations()) { 7907 uint64_t RelocAddress = Reloc.getOffset(); 7908 7909 uint32_t EntryIdx = RelocAddress / EntrySize; 7910 uint32_t OffsetInEntry = RelocAddress - EntryIdx * EntrySize; 7911 CompactUnwindEntry &Entry = CompactUnwinds[EntryIdx]; 7912 7913 if (OffsetInEntry == 0) 7914 Entry.FunctionReloc = Reloc; 7915 else if (OffsetInEntry == PointerSize + 2 * sizeof(uint32_t)) 7916 Entry.PersonalityReloc = Reloc; 7917 else if (OffsetInEntry == 2 * PointerSize + 2 * sizeof(uint32_t)) 7918 Entry.LSDAReloc = Reloc; 7919 else { 7920 outs() << "Invalid relocation in __compact_unwind section\n"; 7921 return; 7922 } 7923 } 7924 7925 // Finally, we're ready to print the data we've gathered. 7926 outs() << "Contents of __compact_unwind section:\n"; 7927 for (auto &Entry : CompactUnwinds) { 7928 outs() << " Entry at offset " 7929 << format("0x%" PRIx32, Entry.OffsetInSection) << ":\n"; 7930 7931 // 1. Start of the region this entry applies to. 7932 outs() << " start: " << format("0x%" PRIx64, 7933 Entry.FunctionAddr) << ' '; 7934 printUnwindRelocDest(Obj, Symbols, Entry.FunctionReloc, Entry.FunctionAddr); 7935 outs() << '\n'; 7936 7937 // 2. Length of the region this entry applies to. 7938 outs() << " length: " << format("0x%" PRIx32, Entry.Length) 7939 << '\n'; 7940 // 3. The 32-bit compact encoding. 7941 outs() << " compact encoding: " 7942 << format("0x%08" PRIx32, Entry.CompactEncoding) << '\n'; 7943 7944 // 4. The personality function, if present. 7945 if (Entry.PersonalityReloc.getObject()) { 7946 outs() << " personality function: " 7947 << format("0x%" PRIx64, Entry.PersonalityAddr) << ' '; 7948 printUnwindRelocDest(Obj, Symbols, Entry.PersonalityReloc, 7949 Entry.PersonalityAddr); 7950 outs() << '\n'; 7951 } 7952 7953 // 5. This entry's language-specific data area. 7954 if (Entry.LSDAReloc.getObject()) { 7955 outs() << " LSDA: " << format("0x%" PRIx64, 7956 Entry.LSDAAddr) << ' '; 7957 printUnwindRelocDest(Obj, Symbols, Entry.LSDAReloc, Entry.LSDAAddr); 7958 outs() << '\n'; 7959 } 7960 } 7961 } 7962 7963 //===----------------------------------------------------------------------===// 7964 // __unwind_info section dumping 7965 //===----------------------------------------------------------------------===// 7966 7967 static void printRegularSecondLevelUnwindPage(StringRef PageData) { 7968 ptrdiff_t Pos = 0; 7969 uint32_t Kind = readNext<uint32_t>(PageData, Pos); 7970 (void)Kind; 7971 assert(Kind == 2 && "kind for a regular 2nd level index should be 2"); 7972 7973 uint16_t EntriesStart = readNext<uint16_t>(PageData, Pos); 7974 uint16_t NumEntries = readNext<uint16_t>(PageData, Pos); 7975 7976 Pos = EntriesStart; 7977 for (unsigned i = 0; i < NumEntries; ++i) { 7978 uint32_t FunctionOffset = readNext<uint32_t>(PageData, Pos); 7979 uint32_t Encoding = readNext<uint32_t>(PageData, Pos); 7980 7981 outs() << " [" << i << "]: " 7982 << "function offset=" << format("0x%08" PRIx32, FunctionOffset) 7983 << ", " 7984 << "encoding=" << format("0x%08" PRIx32, Encoding) << '\n'; 7985 } 7986 } 7987 7988 static void printCompressedSecondLevelUnwindPage( 7989 StringRef PageData, uint32_t FunctionBase, 7990 const SmallVectorImpl<uint32_t> &CommonEncodings) { 7991 ptrdiff_t Pos = 0; 7992 uint32_t Kind = readNext<uint32_t>(PageData, Pos); 7993 (void)Kind; 7994 assert(Kind == 3 && "kind for a compressed 2nd level index should be 3"); 7995 7996 uint16_t EntriesStart = readNext<uint16_t>(PageData, Pos); 7997 uint16_t NumEntries = readNext<uint16_t>(PageData, Pos); 7998 7999 uint16_t EncodingsStart = readNext<uint16_t>(PageData, Pos); 8000 readNext<uint16_t>(PageData, Pos); 8001 StringRef PageEncodings = PageData.substr(EncodingsStart, StringRef::npos); 8002 8003 Pos = EntriesStart; 8004 for (unsigned i = 0; i < NumEntries; ++i) { 8005 uint32_t Entry = readNext<uint32_t>(PageData, Pos); 8006 uint32_t FunctionOffset = FunctionBase + (Entry & 0xffffff); 8007 uint32_t EncodingIdx = Entry >> 24; 8008 8009 uint32_t Encoding; 8010 if (EncodingIdx < CommonEncodings.size()) 8011 Encoding = CommonEncodings[EncodingIdx]; 8012 else 8013 Encoding = read<uint32_t>(PageEncodings, 8014 sizeof(uint32_t) * 8015 (EncodingIdx - CommonEncodings.size())); 8016 8017 outs() << " [" << i << "]: " 8018 << "function offset=" << format("0x%08" PRIx32, FunctionOffset) 8019 << ", " 8020 << "encoding[" << EncodingIdx 8021 << "]=" << format("0x%08" PRIx32, Encoding) << '\n'; 8022 } 8023 } 8024 8025 static void printMachOUnwindInfoSection(const MachOObjectFile *Obj, 8026 std::map<uint64_t, SymbolRef> &Symbols, 8027 const SectionRef &UnwindInfo) { 8028 8029 if (!Obj->isLittleEndian()) { 8030 outs() << "Skipping big-endian __unwind_info section\n"; 8031 return; 8032 } 8033 8034 outs() << "Contents of __unwind_info section:\n"; 8035 8036 StringRef Contents = 8037 unwrapOrError(UnwindInfo.getContents(), Obj->getFileName()); 8038 ptrdiff_t Pos = 0; 8039 8040 //===---------------------------------- 8041 // Section header 8042 //===---------------------------------- 8043 8044 uint32_t Version = readNext<uint32_t>(Contents, Pos); 8045 outs() << " Version: " 8046 << format("0x%" PRIx32, Version) << '\n'; 8047 if (Version != 1) { 8048 outs() << " Skipping section with unknown version\n"; 8049 return; 8050 } 8051 8052 uint32_t CommonEncodingsStart = readNext<uint32_t>(Contents, Pos); 8053 outs() << " Common encodings array section offset: " 8054 << format("0x%" PRIx32, CommonEncodingsStart) << '\n'; 8055 uint32_t NumCommonEncodings = readNext<uint32_t>(Contents, Pos); 8056 outs() << " Number of common encodings in array: " 8057 << format("0x%" PRIx32, NumCommonEncodings) << '\n'; 8058 8059 uint32_t PersonalitiesStart = readNext<uint32_t>(Contents, Pos); 8060 outs() << " Personality function array section offset: " 8061 << format("0x%" PRIx32, PersonalitiesStart) << '\n'; 8062 uint32_t NumPersonalities = readNext<uint32_t>(Contents, Pos); 8063 outs() << " Number of personality functions in array: " 8064 << format("0x%" PRIx32, NumPersonalities) << '\n'; 8065 8066 uint32_t IndicesStart = readNext<uint32_t>(Contents, Pos); 8067 outs() << " Index array section offset: " 8068 << format("0x%" PRIx32, IndicesStart) << '\n'; 8069 uint32_t NumIndices = readNext<uint32_t>(Contents, Pos); 8070 outs() << " Number of indices in array: " 8071 << format("0x%" PRIx32, NumIndices) << '\n'; 8072 8073 //===---------------------------------- 8074 // A shared list of common encodings 8075 //===---------------------------------- 8076 8077 // These occupy indices in the range [0, N] whenever an encoding is referenced 8078 // from a compressed 2nd level index table. In practice the linker only 8079 // creates ~128 of these, so that indices are available to embed encodings in 8080 // the 2nd level index. 8081 8082 SmallVector<uint32_t, 64> CommonEncodings; 8083 outs() << " Common encodings: (count = " << NumCommonEncodings << ")\n"; 8084 Pos = CommonEncodingsStart; 8085 for (unsigned i = 0; i < NumCommonEncodings; ++i) { 8086 uint32_t Encoding = readNext<uint32_t>(Contents, Pos); 8087 CommonEncodings.push_back(Encoding); 8088 8089 outs() << " encoding[" << i << "]: " << format("0x%08" PRIx32, Encoding) 8090 << '\n'; 8091 } 8092 8093 //===---------------------------------- 8094 // Personality functions used in this executable 8095 //===---------------------------------- 8096 8097 // There should be only a handful of these (one per source language, 8098 // roughly). Particularly since they only get 2 bits in the compact encoding. 8099 8100 outs() << " Personality functions: (count = " << NumPersonalities << ")\n"; 8101 Pos = PersonalitiesStart; 8102 for (unsigned i = 0; i < NumPersonalities; ++i) { 8103 uint32_t PersonalityFn = readNext<uint32_t>(Contents, Pos); 8104 outs() << " personality[" << i + 1 8105 << "]: " << format("0x%08" PRIx32, PersonalityFn) << '\n'; 8106 } 8107 8108 //===---------------------------------- 8109 // The level 1 index entries 8110 //===---------------------------------- 8111 8112 // These specify an approximate place to start searching for the more detailed 8113 // information, sorted by PC. 8114 8115 struct IndexEntry { 8116 uint32_t FunctionOffset; 8117 uint32_t SecondLevelPageStart; 8118 uint32_t LSDAStart; 8119 }; 8120 8121 SmallVector<IndexEntry, 4> IndexEntries; 8122 8123 outs() << " Top level indices: (count = " << NumIndices << ")\n"; 8124 Pos = IndicesStart; 8125 for (unsigned i = 0; i < NumIndices; ++i) { 8126 IndexEntry Entry; 8127 8128 Entry.FunctionOffset = readNext<uint32_t>(Contents, Pos); 8129 Entry.SecondLevelPageStart = readNext<uint32_t>(Contents, Pos); 8130 Entry.LSDAStart = readNext<uint32_t>(Contents, Pos); 8131 IndexEntries.push_back(Entry); 8132 8133 outs() << " [" << i << "]: " 8134 << "function offset=" << format("0x%08" PRIx32, Entry.FunctionOffset) 8135 << ", " 8136 << "2nd level page offset=" 8137 << format("0x%08" PRIx32, Entry.SecondLevelPageStart) << ", " 8138 << "LSDA offset=" << format("0x%08" PRIx32, Entry.LSDAStart) << '\n'; 8139 } 8140 8141 //===---------------------------------- 8142 // Next come the LSDA tables 8143 //===---------------------------------- 8144 8145 // The LSDA layout is rather implicit: it's a contiguous array of entries from 8146 // the first top-level index's LSDAOffset to the last (sentinel). 8147 8148 outs() << " LSDA descriptors:\n"; 8149 Pos = IndexEntries[0].LSDAStart; 8150 const uint32_t LSDASize = 2 * sizeof(uint32_t); 8151 int NumLSDAs = 8152 (IndexEntries.back().LSDAStart - IndexEntries[0].LSDAStart) / LSDASize; 8153 8154 for (int i = 0; i < NumLSDAs; ++i) { 8155 uint32_t FunctionOffset = readNext<uint32_t>(Contents, Pos); 8156 uint32_t LSDAOffset = readNext<uint32_t>(Contents, Pos); 8157 outs() << " [" << i << "]: " 8158 << "function offset=" << format("0x%08" PRIx32, FunctionOffset) 8159 << ", " 8160 << "LSDA offset=" << format("0x%08" PRIx32, LSDAOffset) << '\n'; 8161 } 8162 8163 //===---------------------------------- 8164 // Finally, the 2nd level indices 8165 //===---------------------------------- 8166 8167 // Generally these are 4K in size, and have 2 possible forms: 8168 // + Regular stores up to 511 entries with disparate encodings 8169 // + Compressed stores up to 1021 entries if few enough compact encoding 8170 // values are used. 8171 outs() << " Second level indices:\n"; 8172 for (unsigned i = 0; i < IndexEntries.size() - 1; ++i) { 8173 // The final sentinel top-level index has no associated 2nd level page 8174 if (IndexEntries[i].SecondLevelPageStart == 0) 8175 break; 8176 8177 outs() << " Second level index[" << i << "]: " 8178 << "offset in section=" 8179 << format("0x%08" PRIx32, IndexEntries[i].SecondLevelPageStart) 8180 << ", " 8181 << "base function offset=" 8182 << format("0x%08" PRIx32, IndexEntries[i].FunctionOffset) << '\n'; 8183 8184 Pos = IndexEntries[i].SecondLevelPageStart; 8185 if (Pos + sizeof(uint32_t) > Contents.size()) { 8186 outs() << "warning: invalid offset for second level page: " << Pos << '\n'; 8187 continue; 8188 } 8189 8190 uint32_t Kind = 8191 *reinterpret_cast<const support::ulittle32_t *>(Contents.data() + Pos); 8192 if (Kind == 2) 8193 printRegularSecondLevelUnwindPage(Contents.substr(Pos, 4096)); 8194 else if (Kind == 3) 8195 printCompressedSecondLevelUnwindPage(Contents.substr(Pos, 4096), 8196 IndexEntries[i].FunctionOffset, 8197 CommonEncodings); 8198 else 8199 outs() << " Skipping 2nd level page with unknown kind " << Kind 8200 << '\n'; 8201 } 8202 } 8203 8204 void printMachOUnwindInfo(const MachOObjectFile *Obj) { 8205 std::map<uint64_t, SymbolRef> Symbols; 8206 for (const SymbolRef &SymRef : Obj->symbols()) { 8207 // Discard any undefined or absolute symbols. They're not going to take part 8208 // in the convenience lookup for unwind info and just take up resources. 8209 auto SectOrErr = SymRef.getSection(); 8210 if (!SectOrErr) { 8211 // TODO: Actually report errors helpfully. 8212 consumeError(SectOrErr.takeError()); 8213 continue; 8214 } 8215 section_iterator Section = *SectOrErr; 8216 if (Section == Obj->section_end()) 8217 continue; 8218 8219 uint64_t Addr = SymRef.getValue(); 8220 Symbols.insert(std::make_pair(Addr, SymRef)); 8221 } 8222 8223 for (const SectionRef &Section : Obj->sections()) { 8224 StringRef SectName; 8225 if (Expected<StringRef> NameOrErr = Section.getName()) 8226 SectName = *NameOrErr; 8227 else 8228 consumeError(NameOrErr.takeError()); 8229 8230 if (SectName == "__compact_unwind") 8231 printMachOCompactUnwindSection(Obj, Symbols, Section); 8232 else if (SectName == "__unwind_info") 8233 printMachOUnwindInfoSection(Obj, Symbols, Section); 8234 } 8235 } 8236 8237 static void PrintMachHeader(uint32_t magic, uint32_t cputype, 8238 uint32_t cpusubtype, uint32_t filetype, 8239 uint32_t ncmds, uint32_t sizeofcmds, uint32_t flags, 8240 bool verbose) { 8241 outs() << "Mach header\n"; 8242 outs() << " magic cputype cpusubtype caps filetype ncmds " 8243 "sizeofcmds flags\n"; 8244 if (verbose) { 8245 if (magic == MachO::MH_MAGIC) 8246 outs() << " MH_MAGIC"; 8247 else if (magic == MachO::MH_MAGIC_64) 8248 outs() << "MH_MAGIC_64"; 8249 else 8250 outs() << format(" 0x%08" PRIx32, magic); 8251 switch (cputype) { 8252 case MachO::CPU_TYPE_I386: 8253 outs() << " I386"; 8254 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) { 8255 case MachO::CPU_SUBTYPE_I386_ALL: 8256 outs() << " ALL"; 8257 break; 8258 default: 8259 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK); 8260 break; 8261 } 8262 break; 8263 case MachO::CPU_TYPE_X86_64: 8264 outs() << " X86_64"; 8265 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) { 8266 case MachO::CPU_SUBTYPE_X86_64_ALL: 8267 outs() << " ALL"; 8268 break; 8269 case MachO::CPU_SUBTYPE_X86_64_H: 8270 outs() << " Haswell"; 8271 break; 8272 default: 8273 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK); 8274 break; 8275 } 8276 break; 8277 case MachO::CPU_TYPE_ARM: 8278 outs() << " ARM"; 8279 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) { 8280 case MachO::CPU_SUBTYPE_ARM_ALL: 8281 outs() << " ALL"; 8282 break; 8283 case MachO::CPU_SUBTYPE_ARM_V4T: 8284 outs() << " V4T"; 8285 break; 8286 case MachO::CPU_SUBTYPE_ARM_V5TEJ: 8287 outs() << " V5TEJ"; 8288 break; 8289 case MachO::CPU_SUBTYPE_ARM_XSCALE: 8290 outs() << " XSCALE"; 8291 break; 8292 case MachO::CPU_SUBTYPE_ARM_V6: 8293 outs() << " V6"; 8294 break; 8295 case MachO::CPU_SUBTYPE_ARM_V6M: 8296 outs() << " V6M"; 8297 break; 8298 case MachO::CPU_SUBTYPE_ARM_V7: 8299 outs() << " V7"; 8300 break; 8301 case MachO::CPU_SUBTYPE_ARM_V7EM: 8302 outs() << " V7EM"; 8303 break; 8304 case MachO::CPU_SUBTYPE_ARM_V7K: 8305 outs() << " V7K"; 8306 break; 8307 case MachO::CPU_SUBTYPE_ARM_V7M: 8308 outs() << " V7M"; 8309 break; 8310 case MachO::CPU_SUBTYPE_ARM_V7S: 8311 outs() << " V7S"; 8312 break; 8313 default: 8314 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK); 8315 break; 8316 } 8317 break; 8318 case MachO::CPU_TYPE_ARM64: 8319 outs() << " ARM64"; 8320 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) { 8321 case MachO::CPU_SUBTYPE_ARM64_ALL: 8322 outs() << " ALL"; 8323 break; 8324 case MachO::CPU_SUBTYPE_ARM64E: 8325 outs() << " E"; 8326 break; 8327 default: 8328 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK); 8329 break; 8330 } 8331 break; 8332 case MachO::CPU_TYPE_ARM64_32: 8333 outs() << " ARM64_32"; 8334 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) { 8335 case MachO::CPU_SUBTYPE_ARM64_32_V8: 8336 outs() << " V8"; 8337 break; 8338 default: 8339 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK); 8340 break; 8341 } 8342 break; 8343 case MachO::CPU_TYPE_POWERPC: 8344 outs() << " PPC"; 8345 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) { 8346 case MachO::CPU_SUBTYPE_POWERPC_ALL: 8347 outs() << " ALL"; 8348 break; 8349 default: 8350 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK); 8351 break; 8352 } 8353 break; 8354 case MachO::CPU_TYPE_POWERPC64: 8355 outs() << " PPC64"; 8356 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) { 8357 case MachO::CPU_SUBTYPE_POWERPC_ALL: 8358 outs() << " ALL"; 8359 break; 8360 default: 8361 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK); 8362 break; 8363 } 8364 break; 8365 default: 8366 outs() << format(" %7d", cputype); 8367 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK); 8368 break; 8369 } 8370 if ((cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64) { 8371 outs() << " LIB64"; 8372 } else { 8373 outs() << format(" 0x%02" PRIx32, 8374 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24); 8375 } 8376 switch (filetype) { 8377 case MachO::MH_OBJECT: 8378 outs() << " OBJECT"; 8379 break; 8380 case MachO::MH_EXECUTE: 8381 outs() << " EXECUTE"; 8382 break; 8383 case MachO::MH_FVMLIB: 8384 outs() << " FVMLIB"; 8385 break; 8386 case MachO::MH_CORE: 8387 outs() << " CORE"; 8388 break; 8389 case MachO::MH_PRELOAD: 8390 outs() << " PRELOAD"; 8391 break; 8392 case MachO::MH_DYLIB: 8393 outs() << " DYLIB"; 8394 break; 8395 case MachO::MH_DYLIB_STUB: 8396 outs() << " DYLIB_STUB"; 8397 break; 8398 case MachO::MH_DYLINKER: 8399 outs() << " DYLINKER"; 8400 break; 8401 case MachO::MH_BUNDLE: 8402 outs() << " BUNDLE"; 8403 break; 8404 case MachO::MH_DSYM: 8405 outs() << " DSYM"; 8406 break; 8407 case MachO::MH_KEXT_BUNDLE: 8408 outs() << " KEXTBUNDLE"; 8409 break; 8410 default: 8411 outs() << format(" %10u", filetype); 8412 break; 8413 } 8414 outs() << format(" %5u", ncmds); 8415 outs() << format(" %10u", sizeofcmds); 8416 uint32_t f = flags; 8417 if (f & MachO::MH_NOUNDEFS) { 8418 outs() << " NOUNDEFS"; 8419 f &= ~MachO::MH_NOUNDEFS; 8420 } 8421 if (f & MachO::MH_INCRLINK) { 8422 outs() << " INCRLINK"; 8423 f &= ~MachO::MH_INCRLINK; 8424 } 8425 if (f & MachO::MH_DYLDLINK) { 8426 outs() << " DYLDLINK"; 8427 f &= ~MachO::MH_DYLDLINK; 8428 } 8429 if (f & MachO::MH_BINDATLOAD) { 8430 outs() << " BINDATLOAD"; 8431 f &= ~MachO::MH_BINDATLOAD; 8432 } 8433 if (f & MachO::MH_PREBOUND) { 8434 outs() << " PREBOUND"; 8435 f &= ~MachO::MH_PREBOUND; 8436 } 8437 if (f & MachO::MH_SPLIT_SEGS) { 8438 outs() << " SPLIT_SEGS"; 8439 f &= ~MachO::MH_SPLIT_SEGS; 8440 } 8441 if (f & MachO::MH_LAZY_INIT) { 8442 outs() << " LAZY_INIT"; 8443 f &= ~MachO::MH_LAZY_INIT; 8444 } 8445 if (f & MachO::MH_TWOLEVEL) { 8446 outs() << " TWOLEVEL"; 8447 f &= ~MachO::MH_TWOLEVEL; 8448 } 8449 if (f & MachO::MH_FORCE_FLAT) { 8450 outs() << " FORCE_FLAT"; 8451 f &= ~MachO::MH_FORCE_FLAT; 8452 } 8453 if (f & MachO::MH_NOMULTIDEFS) { 8454 outs() << " NOMULTIDEFS"; 8455 f &= ~MachO::MH_NOMULTIDEFS; 8456 } 8457 if (f & MachO::MH_NOFIXPREBINDING) { 8458 outs() << " NOFIXPREBINDING"; 8459 f &= ~MachO::MH_NOFIXPREBINDING; 8460 } 8461 if (f & MachO::MH_PREBINDABLE) { 8462 outs() << " PREBINDABLE"; 8463 f &= ~MachO::MH_PREBINDABLE; 8464 } 8465 if (f & MachO::MH_ALLMODSBOUND) { 8466 outs() << " ALLMODSBOUND"; 8467 f &= ~MachO::MH_ALLMODSBOUND; 8468 } 8469 if (f & MachO::MH_SUBSECTIONS_VIA_SYMBOLS) { 8470 outs() << " SUBSECTIONS_VIA_SYMBOLS"; 8471 f &= ~MachO::MH_SUBSECTIONS_VIA_SYMBOLS; 8472 } 8473 if (f & MachO::MH_CANONICAL) { 8474 outs() << " CANONICAL"; 8475 f &= ~MachO::MH_CANONICAL; 8476 } 8477 if (f & MachO::MH_WEAK_DEFINES) { 8478 outs() << " WEAK_DEFINES"; 8479 f &= ~MachO::MH_WEAK_DEFINES; 8480 } 8481 if (f & MachO::MH_BINDS_TO_WEAK) { 8482 outs() << " BINDS_TO_WEAK"; 8483 f &= ~MachO::MH_BINDS_TO_WEAK; 8484 } 8485 if (f & MachO::MH_ALLOW_STACK_EXECUTION) { 8486 outs() << " ALLOW_STACK_EXECUTION"; 8487 f &= ~MachO::MH_ALLOW_STACK_EXECUTION; 8488 } 8489 if (f & MachO::MH_DEAD_STRIPPABLE_DYLIB) { 8490 outs() << " DEAD_STRIPPABLE_DYLIB"; 8491 f &= ~MachO::MH_DEAD_STRIPPABLE_DYLIB; 8492 } 8493 if (f & MachO::MH_PIE) { 8494 outs() << " PIE"; 8495 f &= ~MachO::MH_PIE; 8496 } 8497 if (f & MachO::MH_NO_REEXPORTED_DYLIBS) { 8498 outs() << " NO_REEXPORTED_DYLIBS"; 8499 f &= ~MachO::MH_NO_REEXPORTED_DYLIBS; 8500 } 8501 if (f & MachO::MH_HAS_TLV_DESCRIPTORS) { 8502 outs() << " MH_HAS_TLV_DESCRIPTORS"; 8503 f &= ~MachO::MH_HAS_TLV_DESCRIPTORS; 8504 } 8505 if (f & MachO::MH_NO_HEAP_EXECUTION) { 8506 outs() << " MH_NO_HEAP_EXECUTION"; 8507 f &= ~MachO::MH_NO_HEAP_EXECUTION; 8508 } 8509 if (f & MachO::MH_APP_EXTENSION_SAFE) { 8510 outs() << " APP_EXTENSION_SAFE"; 8511 f &= ~MachO::MH_APP_EXTENSION_SAFE; 8512 } 8513 if (f & MachO::MH_NLIST_OUTOFSYNC_WITH_DYLDINFO) { 8514 outs() << " NLIST_OUTOFSYNC_WITH_DYLDINFO"; 8515 f &= ~MachO::MH_NLIST_OUTOFSYNC_WITH_DYLDINFO; 8516 } 8517 if (f != 0 || flags == 0) 8518 outs() << format(" 0x%08" PRIx32, f); 8519 } else { 8520 outs() << format(" 0x%08" PRIx32, magic); 8521 outs() << format(" %7d", cputype); 8522 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK); 8523 outs() << format(" 0x%02" PRIx32, 8524 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24); 8525 outs() << format(" %10u", filetype); 8526 outs() << format(" %5u", ncmds); 8527 outs() << format(" %10u", sizeofcmds); 8528 outs() << format(" 0x%08" PRIx32, flags); 8529 } 8530 outs() << "\n"; 8531 } 8532 8533 static void PrintSegmentCommand(uint32_t cmd, uint32_t cmdsize, 8534 StringRef SegName, uint64_t vmaddr, 8535 uint64_t vmsize, uint64_t fileoff, 8536 uint64_t filesize, uint32_t maxprot, 8537 uint32_t initprot, uint32_t nsects, 8538 uint32_t flags, uint32_t object_size, 8539 bool verbose) { 8540 uint64_t expected_cmdsize; 8541 if (cmd == MachO::LC_SEGMENT) { 8542 outs() << " cmd LC_SEGMENT\n"; 8543 expected_cmdsize = nsects; 8544 expected_cmdsize *= sizeof(struct MachO::section); 8545 expected_cmdsize += sizeof(struct MachO::segment_command); 8546 } else { 8547 outs() << " cmd LC_SEGMENT_64\n"; 8548 expected_cmdsize = nsects; 8549 expected_cmdsize *= sizeof(struct MachO::section_64); 8550 expected_cmdsize += sizeof(struct MachO::segment_command_64); 8551 } 8552 outs() << " cmdsize " << cmdsize; 8553 if (cmdsize != expected_cmdsize) 8554 outs() << " Inconsistent size\n"; 8555 else 8556 outs() << "\n"; 8557 outs() << " segname " << SegName << "\n"; 8558 if (cmd == MachO::LC_SEGMENT_64) { 8559 outs() << " vmaddr " << format("0x%016" PRIx64, vmaddr) << "\n"; 8560 outs() << " vmsize " << format("0x%016" PRIx64, vmsize) << "\n"; 8561 } else { 8562 outs() << " vmaddr " << format("0x%08" PRIx64, vmaddr) << "\n"; 8563 outs() << " vmsize " << format("0x%08" PRIx64, vmsize) << "\n"; 8564 } 8565 outs() << " fileoff " << fileoff; 8566 if (fileoff > object_size) 8567 outs() << " (past end of file)\n"; 8568 else 8569 outs() << "\n"; 8570 outs() << " filesize " << filesize; 8571 if (fileoff + filesize > object_size) 8572 outs() << " (past end of file)\n"; 8573 else 8574 outs() << "\n"; 8575 if (verbose) { 8576 if ((maxprot & 8577 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE | 8578 MachO::VM_PROT_EXECUTE)) != 0) 8579 outs() << " maxprot ?" << format("0x%08" PRIx32, maxprot) << "\n"; 8580 else { 8581 outs() << " maxprot "; 8582 outs() << ((maxprot & MachO::VM_PROT_READ) ? "r" : "-"); 8583 outs() << ((maxprot & MachO::VM_PROT_WRITE) ? "w" : "-"); 8584 outs() << ((maxprot & MachO::VM_PROT_EXECUTE) ? "x\n" : "-\n"); 8585 } 8586 if ((initprot & 8587 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE | 8588 MachO::VM_PROT_EXECUTE)) != 0) 8589 outs() << " initprot ?" << format("0x%08" PRIx32, initprot) << "\n"; 8590 else { 8591 outs() << " initprot "; 8592 outs() << ((initprot & MachO::VM_PROT_READ) ? "r" : "-"); 8593 outs() << ((initprot & MachO::VM_PROT_WRITE) ? "w" : "-"); 8594 outs() << ((initprot & MachO::VM_PROT_EXECUTE) ? "x\n" : "-\n"); 8595 } 8596 } else { 8597 outs() << " maxprot " << format("0x%08" PRIx32, maxprot) << "\n"; 8598 outs() << " initprot " << format("0x%08" PRIx32, initprot) << "\n"; 8599 } 8600 outs() << " nsects " << nsects << "\n"; 8601 if (verbose) { 8602 outs() << " flags"; 8603 if (flags == 0) 8604 outs() << " (none)\n"; 8605 else { 8606 if (flags & MachO::SG_HIGHVM) { 8607 outs() << " HIGHVM"; 8608 flags &= ~MachO::SG_HIGHVM; 8609 } 8610 if (flags & MachO::SG_FVMLIB) { 8611 outs() << " FVMLIB"; 8612 flags &= ~MachO::SG_FVMLIB; 8613 } 8614 if (flags & MachO::SG_NORELOC) { 8615 outs() << " NORELOC"; 8616 flags &= ~MachO::SG_NORELOC; 8617 } 8618 if (flags & MachO::SG_PROTECTED_VERSION_1) { 8619 outs() << " PROTECTED_VERSION_1"; 8620 flags &= ~MachO::SG_PROTECTED_VERSION_1; 8621 } 8622 if (flags) 8623 outs() << format(" 0x%08" PRIx32, flags) << " (unknown flags)\n"; 8624 else 8625 outs() << "\n"; 8626 } 8627 } else { 8628 outs() << " flags " << format("0x%" PRIx32, flags) << "\n"; 8629 } 8630 } 8631 8632 static void PrintSection(const char *sectname, const char *segname, 8633 uint64_t addr, uint64_t size, uint32_t offset, 8634 uint32_t align, uint32_t reloff, uint32_t nreloc, 8635 uint32_t flags, uint32_t reserved1, uint32_t reserved2, 8636 uint32_t cmd, const char *sg_segname, 8637 uint32_t filetype, uint32_t object_size, 8638 bool verbose) { 8639 outs() << "Section\n"; 8640 outs() << " sectname " << format("%.16s\n", sectname); 8641 outs() << " segname " << format("%.16s", segname); 8642 if (filetype != MachO::MH_OBJECT && strncmp(sg_segname, segname, 16) != 0) 8643 outs() << " (does not match segment)\n"; 8644 else 8645 outs() << "\n"; 8646 if (cmd == MachO::LC_SEGMENT_64) { 8647 outs() << " addr " << format("0x%016" PRIx64, addr) << "\n"; 8648 outs() << " size " << format("0x%016" PRIx64, size); 8649 } else { 8650 outs() << " addr " << format("0x%08" PRIx64, addr) << "\n"; 8651 outs() << " size " << format("0x%08" PRIx64, size); 8652 } 8653 if ((flags & MachO::S_ZEROFILL) != 0 && offset + size > object_size) 8654 outs() << " (past end of file)\n"; 8655 else 8656 outs() << "\n"; 8657 outs() << " offset " << offset; 8658 if (offset > object_size) 8659 outs() << " (past end of file)\n"; 8660 else 8661 outs() << "\n"; 8662 uint32_t align_shifted = 1 << align; 8663 outs() << " align 2^" << align << " (" << align_shifted << ")\n"; 8664 outs() << " reloff " << reloff; 8665 if (reloff > object_size) 8666 outs() << " (past end of file)\n"; 8667 else 8668 outs() << "\n"; 8669 outs() << " nreloc " << nreloc; 8670 if (reloff + nreloc * sizeof(struct MachO::relocation_info) > object_size) 8671 outs() << " (past end of file)\n"; 8672 else 8673 outs() << "\n"; 8674 uint32_t section_type = flags & MachO::SECTION_TYPE; 8675 if (verbose) { 8676 outs() << " type"; 8677 if (section_type == MachO::S_REGULAR) 8678 outs() << " S_REGULAR\n"; 8679 else if (section_type == MachO::S_ZEROFILL) 8680 outs() << " S_ZEROFILL\n"; 8681 else if (section_type == MachO::S_CSTRING_LITERALS) 8682 outs() << " S_CSTRING_LITERALS\n"; 8683 else if (section_type == MachO::S_4BYTE_LITERALS) 8684 outs() << " S_4BYTE_LITERALS\n"; 8685 else if (section_type == MachO::S_8BYTE_LITERALS) 8686 outs() << " S_8BYTE_LITERALS\n"; 8687 else if (section_type == MachO::S_16BYTE_LITERALS) 8688 outs() << " S_16BYTE_LITERALS\n"; 8689 else if (section_type == MachO::S_LITERAL_POINTERS) 8690 outs() << " S_LITERAL_POINTERS\n"; 8691 else if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS) 8692 outs() << " S_NON_LAZY_SYMBOL_POINTERS\n"; 8693 else if (section_type == MachO::S_LAZY_SYMBOL_POINTERS) 8694 outs() << " S_LAZY_SYMBOL_POINTERS\n"; 8695 else if (section_type == MachO::S_SYMBOL_STUBS) 8696 outs() << " S_SYMBOL_STUBS\n"; 8697 else if (section_type == MachO::S_MOD_INIT_FUNC_POINTERS) 8698 outs() << " S_MOD_INIT_FUNC_POINTERS\n"; 8699 else if (section_type == MachO::S_MOD_TERM_FUNC_POINTERS) 8700 outs() << " S_MOD_TERM_FUNC_POINTERS\n"; 8701 else if (section_type == MachO::S_COALESCED) 8702 outs() << " S_COALESCED\n"; 8703 else if (section_type == MachO::S_INTERPOSING) 8704 outs() << " S_INTERPOSING\n"; 8705 else if (section_type == MachO::S_DTRACE_DOF) 8706 outs() << " S_DTRACE_DOF\n"; 8707 else if (section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS) 8708 outs() << " S_LAZY_DYLIB_SYMBOL_POINTERS\n"; 8709 else if (section_type == MachO::S_THREAD_LOCAL_REGULAR) 8710 outs() << " S_THREAD_LOCAL_REGULAR\n"; 8711 else if (section_type == MachO::S_THREAD_LOCAL_ZEROFILL) 8712 outs() << " S_THREAD_LOCAL_ZEROFILL\n"; 8713 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLES) 8714 outs() << " S_THREAD_LOCAL_VARIABLES\n"; 8715 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS) 8716 outs() << " S_THREAD_LOCAL_VARIABLE_POINTERS\n"; 8717 else if (section_type == MachO::S_THREAD_LOCAL_INIT_FUNCTION_POINTERS) 8718 outs() << " S_THREAD_LOCAL_INIT_FUNCTION_POINTERS\n"; 8719 else 8720 outs() << format("0x%08" PRIx32, section_type) << "\n"; 8721 outs() << "attributes"; 8722 uint32_t section_attributes = flags & MachO::SECTION_ATTRIBUTES; 8723 if (section_attributes & MachO::S_ATTR_PURE_INSTRUCTIONS) 8724 outs() << " PURE_INSTRUCTIONS"; 8725 if (section_attributes & MachO::S_ATTR_NO_TOC) 8726 outs() << " NO_TOC"; 8727 if (section_attributes & MachO::S_ATTR_STRIP_STATIC_SYMS) 8728 outs() << " STRIP_STATIC_SYMS"; 8729 if (section_attributes & MachO::S_ATTR_NO_DEAD_STRIP) 8730 outs() << " NO_DEAD_STRIP"; 8731 if (section_attributes & MachO::S_ATTR_LIVE_SUPPORT) 8732 outs() << " LIVE_SUPPORT"; 8733 if (section_attributes & MachO::S_ATTR_SELF_MODIFYING_CODE) 8734 outs() << " SELF_MODIFYING_CODE"; 8735 if (section_attributes & MachO::S_ATTR_DEBUG) 8736 outs() << " DEBUG"; 8737 if (section_attributes & MachO::S_ATTR_SOME_INSTRUCTIONS) 8738 outs() << " SOME_INSTRUCTIONS"; 8739 if (section_attributes & MachO::S_ATTR_EXT_RELOC) 8740 outs() << " EXT_RELOC"; 8741 if (section_attributes & MachO::S_ATTR_LOC_RELOC) 8742 outs() << " LOC_RELOC"; 8743 if (section_attributes == 0) 8744 outs() << " (none)"; 8745 outs() << "\n"; 8746 } else 8747 outs() << " flags " << format("0x%08" PRIx32, flags) << "\n"; 8748 outs() << " reserved1 " << reserved1; 8749 if (section_type == MachO::S_SYMBOL_STUBS || 8750 section_type == MachO::S_LAZY_SYMBOL_POINTERS || 8751 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS || 8752 section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS || 8753 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS) 8754 outs() << " (index into indirect symbol table)\n"; 8755 else 8756 outs() << "\n"; 8757 outs() << " reserved2 " << reserved2; 8758 if (section_type == MachO::S_SYMBOL_STUBS) 8759 outs() << " (size of stubs)\n"; 8760 else 8761 outs() << "\n"; 8762 } 8763 8764 static void PrintSymtabLoadCommand(MachO::symtab_command st, bool Is64Bit, 8765 uint32_t object_size) { 8766 outs() << " cmd LC_SYMTAB\n"; 8767 outs() << " cmdsize " << st.cmdsize; 8768 if (st.cmdsize != sizeof(struct MachO::symtab_command)) 8769 outs() << " Incorrect size\n"; 8770 else 8771 outs() << "\n"; 8772 outs() << " symoff " << st.symoff; 8773 if (st.symoff > object_size) 8774 outs() << " (past end of file)\n"; 8775 else 8776 outs() << "\n"; 8777 outs() << " nsyms " << st.nsyms; 8778 uint64_t big_size; 8779 if (Is64Bit) { 8780 big_size = st.nsyms; 8781 big_size *= sizeof(struct MachO::nlist_64); 8782 big_size += st.symoff; 8783 if (big_size > object_size) 8784 outs() << " (past end of file)\n"; 8785 else 8786 outs() << "\n"; 8787 } else { 8788 big_size = st.nsyms; 8789 big_size *= sizeof(struct MachO::nlist); 8790 big_size += st.symoff; 8791 if (big_size > object_size) 8792 outs() << " (past end of file)\n"; 8793 else 8794 outs() << "\n"; 8795 } 8796 outs() << " stroff " << st.stroff; 8797 if (st.stroff > object_size) 8798 outs() << " (past end of file)\n"; 8799 else 8800 outs() << "\n"; 8801 outs() << " strsize " << st.strsize; 8802 big_size = st.stroff; 8803 big_size += st.strsize; 8804 if (big_size > object_size) 8805 outs() << " (past end of file)\n"; 8806 else 8807 outs() << "\n"; 8808 } 8809 8810 static void PrintDysymtabLoadCommand(MachO::dysymtab_command dyst, 8811 uint32_t nsyms, uint32_t object_size, 8812 bool Is64Bit) { 8813 outs() << " cmd LC_DYSYMTAB\n"; 8814 outs() << " cmdsize " << dyst.cmdsize; 8815 if (dyst.cmdsize != sizeof(struct MachO::dysymtab_command)) 8816 outs() << " Incorrect size\n"; 8817 else 8818 outs() << "\n"; 8819 outs() << " ilocalsym " << dyst.ilocalsym; 8820 if (dyst.ilocalsym > nsyms) 8821 outs() << " (greater than the number of symbols)\n"; 8822 else 8823 outs() << "\n"; 8824 outs() << " nlocalsym " << dyst.nlocalsym; 8825 uint64_t big_size; 8826 big_size = dyst.ilocalsym; 8827 big_size += dyst.nlocalsym; 8828 if (big_size > nsyms) 8829 outs() << " (past the end of the symbol table)\n"; 8830 else 8831 outs() << "\n"; 8832 outs() << " iextdefsym " << dyst.iextdefsym; 8833 if (dyst.iextdefsym > nsyms) 8834 outs() << " (greater than the number of symbols)\n"; 8835 else 8836 outs() << "\n"; 8837 outs() << " nextdefsym " << dyst.nextdefsym; 8838 big_size = dyst.iextdefsym; 8839 big_size += dyst.nextdefsym; 8840 if (big_size > nsyms) 8841 outs() << " (past the end of the symbol table)\n"; 8842 else 8843 outs() << "\n"; 8844 outs() << " iundefsym " << dyst.iundefsym; 8845 if (dyst.iundefsym > nsyms) 8846 outs() << " (greater than the number of symbols)\n"; 8847 else 8848 outs() << "\n"; 8849 outs() << " nundefsym " << dyst.nundefsym; 8850 big_size = dyst.iundefsym; 8851 big_size += dyst.nundefsym; 8852 if (big_size > nsyms) 8853 outs() << " (past the end of the symbol table)\n"; 8854 else 8855 outs() << "\n"; 8856 outs() << " tocoff " << dyst.tocoff; 8857 if (dyst.tocoff > object_size) 8858 outs() << " (past end of file)\n"; 8859 else 8860 outs() << "\n"; 8861 outs() << " ntoc " << dyst.ntoc; 8862 big_size = dyst.ntoc; 8863 big_size *= sizeof(struct MachO::dylib_table_of_contents); 8864 big_size += dyst.tocoff; 8865 if (big_size > object_size) 8866 outs() << " (past end of file)\n"; 8867 else 8868 outs() << "\n"; 8869 outs() << " modtaboff " << dyst.modtaboff; 8870 if (dyst.modtaboff > object_size) 8871 outs() << " (past end of file)\n"; 8872 else 8873 outs() << "\n"; 8874 outs() << " nmodtab " << dyst.nmodtab; 8875 uint64_t modtabend; 8876 if (Is64Bit) { 8877 modtabend = dyst.nmodtab; 8878 modtabend *= sizeof(struct MachO::dylib_module_64); 8879 modtabend += dyst.modtaboff; 8880 } else { 8881 modtabend = dyst.nmodtab; 8882 modtabend *= sizeof(struct MachO::dylib_module); 8883 modtabend += dyst.modtaboff; 8884 } 8885 if (modtabend > object_size) 8886 outs() << " (past end of file)\n"; 8887 else 8888 outs() << "\n"; 8889 outs() << " extrefsymoff " << dyst.extrefsymoff; 8890 if (dyst.extrefsymoff > object_size) 8891 outs() << " (past end of file)\n"; 8892 else 8893 outs() << "\n"; 8894 outs() << " nextrefsyms " << dyst.nextrefsyms; 8895 big_size = dyst.nextrefsyms; 8896 big_size *= sizeof(struct MachO::dylib_reference); 8897 big_size += dyst.extrefsymoff; 8898 if (big_size > object_size) 8899 outs() << " (past end of file)\n"; 8900 else 8901 outs() << "\n"; 8902 outs() << " indirectsymoff " << dyst.indirectsymoff; 8903 if (dyst.indirectsymoff > object_size) 8904 outs() << " (past end of file)\n"; 8905 else 8906 outs() << "\n"; 8907 outs() << " nindirectsyms " << dyst.nindirectsyms; 8908 big_size = dyst.nindirectsyms; 8909 big_size *= sizeof(uint32_t); 8910 big_size += dyst.indirectsymoff; 8911 if (big_size > object_size) 8912 outs() << " (past end of file)\n"; 8913 else 8914 outs() << "\n"; 8915 outs() << " extreloff " << dyst.extreloff; 8916 if (dyst.extreloff > object_size) 8917 outs() << " (past end of file)\n"; 8918 else 8919 outs() << "\n"; 8920 outs() << " nextrel " << dyst.nextrel; 8921 big_size = dyst.nextrel; 8922 big_size *= sizeof(struct MachO::relocation_info); 8923 big_size += dyst.extreloff; 8924 if (big_size > object_size) 8925 outs() << " (past end of file)\n"; 8926 else 8927 outs() << "\n"; 8928 outs() << " locreloff " << dyst.locreloff; 8929 if (dyst.locreloff > object_size) 8930 outs() << " (past end of file)\n"; 8931 else 8932 outs() << "\n"; 8933 outs() << " nlocrel " << dyst.nlocrel; 8934 big_size = dyst.nlocrel; 8935 big_size *= sizeof(struct MachO::relocation_info); 8936 big_size += dyst.locreloff; 8937 if (big_size > object_size) 8938 outs() << " (past end of file)\n"; 8939 else 8940 outs() << "\n"; 8941 } 8942 8943 static void PrintDyldInfoLoadCommand(MachO::dyld_info_command dc, 8944 uint32_t object_size) { 8945 if (dc.cmd == MachO::LC_DYLD_INFO) 8946 outs() << " cmd LC_DYLD_INFO\n"; 8947 else 8948 outs() << " cmd LC_DYLD_INFO_ONLY\n"; 8949 outs() << " cmdsize " << dc.cmdsize; 8950 if (dc.cmdsize != sizeof(struct MachO::dyld_info_command)) 8951 outs() << " Incorrect size\n"; 8952 else 8953 outs() << "\n"; 8954 outs() << " rebase_off " << dc.rebase_off; 8955 if (dc.rebase_off > object_size) 8956 outs() << " (past end of file)\n"; 8957 else 8958 outs() << "\n"; 8959 outs() << " rebase_size " << dc.rebase_size; 8960 uint64_t big_size; 8961 big_size = dc.rebase_off; 8962 big_size += dc.rebase_size; 8963 if (big_size > object_size) 8964 outs() << " (past end of file)\n"; 8965 else 8966 outs() << "\n"; 8967 outs() << " bind_off " << dc.bind_off; 8968 if (dc.bind_off > object_size) 8969 outs() << " (past end of file)\n"; 8970 else 8971 outs() << "\n"; 8972 outs() << " bind_size " << dc.bind_size; 8973 big_size = dc.bind_off; 8974 big_size += dc.bind_size; 8975 if (big_size > object_size) 8976 outs() << " (past end of file)\n"; 8977 else 8978 outs() << "\n"; 8979 outs() << " weak_bind_off " << dc.weak_bind_off; 8980 if (dc.weak_bind_off > object_size) 8981 outs() << " (past end of file)\n"; 8982 else 8983 outs() << "\n"; 8984 outs() << " weak_bind_size " << dc.weak_bind_size; 8985 big_size = dc.weak_bind_off; 8986 big_size += dc.weak_bind_size; 8987 if (big_size > object_size) 8988 outs() << " (past end of file)\n"; 8989 else 8990 outs() << "\n"; 8991 outs() << " lazy_bind_off " << dc.lazy_bind_off; 8992 if (dc.lazy_bind_off > object_size) 8993 outs() << " (past end of file)\n"; 8994 else 8995 outs() << "\n"; 8996 outs() << " lazy_bind_size " << dc.lazy_bind_size; 8997 big_size = dc.lazy_bind_off; 8998 big_size += dc.lazy_bind_size; 8999 if (big_size > object_size) 9000 outs() << " (past end of file)\n"; 9001 else 9002 outs() << "\n"; 9003 outs() << " export_off " << dc.export_off; 9004 if (dc.export_off > object_size) 9005 outs() << " (past end of file)\n"; 9006 else 9007 outs() << "\n"; 9008 outs() << " export_size " << dc.export_size; 9009 big_size = dc.export_off; 9010 big_size += dc.export_size; 9011 if (big_size > object_size) 9012 outs() << " (past end of file)\n"; 9013 else 9014 outs() << "\n"; 9015 } 9016 9017 static void PrintDyldLoadCommand(MachO::dylinker_command dyld, 9018 const char *Ptr) { 9019 if (dyld.cmd == MachO::LC_ID_DYLINKER) 9020 outs() << " cmd LC_ID_DYLINKER\n"; 9021 else if (dyld.cmd == MachO::LC_LOAD_DYLINKER) 9022 outs() << " cmd LC_LOAD_DYLINKER\n"; 9023 else if (dyld.cmd == MachO::LC_DYLD_ENVIRONMENT) 9024 outs() << " cmd LC_DYLD_ENVIRONMENT\n"; 9025 else 9026 outs() << " cmd ?(" << dyld.cmd << ")\n"; 9027 outs() << " cmdsize " << dyld.cmdsize; 9028 if (dyld.cmdsize < sizeof(struct MachO::dylinker_command)) 9029 outs() << " Incorrect size\n"; 9030 else 9031 outs() << "\n"; 9032 if (dyld.name >= dyld.cmdsize) 9033 outs() << " name ?(bad offset " << dyld.name << ")\n"; 9034 else { 9035 const char *P = (const char *)(Ptr) + dyld.name; 9036 outs() << " name " << P << " (offset " << dyld.name << ")\n"; 9037 } 9038 } 9039 9040 static void PrintUuidLoadCommand(MachO::uuid_command uuid) { 9041 outs() << " cmd LC_UUID\n"; 9042 outs() << " cmdsize " << uuid.cmdsize; 9043 if (uuid.cmdsize != sizeof(struct MachO::uuid_command)) 9044 outs() << " Incorrect size\n"; 9045 else 9046 outs() << "\n"; 9047 outs() << " uuid "; 9048 for (int i = 0; i < 16; ++i) { 9049 outs() << format("%02" PRIX32, uuid.uuid[i]); 9050 if (i == 3 || i == 5 || i == 7 || i == 9) 9051 outs() << "-"; 9052 } 9053 outs() << "\n"; 9054 } 9055 9056 static void PrintRpathLoadCommand(MachO::rpath_command rpath, const char *Ptr) { 9057 outs() << " cmd LC_RPATH\n"; 9058 outs() << " cmdsize " << rpath.cmdsize; 9059 if (rpath.cmdsize < sizeof(struct MachO::rpath_command)) 9060 outs() << " Incorrect size\n"; 9061 else 9062 outs() << "\n"; 9063 if (rpath.path >= rpath.cmdsize) 9064 outs() << " path ?(bad offset " << rpath.path << ")\n"; 9065 else { 9066 const char *P = (const char *)(Ptr) + rpath.path; 9067 outs() << " path " << P << " (offset " << rpath.path << ")\n"; 9068 } 9069 } 9070 9071 static void PrintVersionMinLoadCommand(MachO::version_min_command vd) { 9072 StringRef LoadCmdName; 9073 switch (vd.cmd) { 9074 case MachO::LC_VERSION_MIN_MACOSX: 9075 LoadCmdName = "LC_VERSION_MIN_MACOSX"; 9076 break; 9077 case MachO::LC_VERSION_MIN_IPHONEOS: 9078 LoadCmdName = "LC_VERSION_MIN_IPHONEOS"; 9079 break; 9080 case MachO::LC_VERSION_MIN_TVOS: 9081 LoadCmdName = "LC_VERSION_MIN_TVOS"; 9082 break; 9083 case MachO::LC_VERSION_MIN_WATCHOS: 9084 LoadCmdName = "LC_VERSION_MIN_WATCHOS"; 9085 break; 9086 default: 9087 llvm_unreachable("Unknown version min load command"); 9088 } 9089 9090 outs() << " cmd " << LoadCmdName << '\n'; 9091 outs() << " cmdsize " << vd.cmdsize; 9092 if (vd.cmdsize != sizeof(struct MachO::version_min_command)) 9093 outs() << " Incorrect size\n"; 9094 else 9095 outs() << "\n"; 9096 outs() << " version " 9097 << MachOObjectFile::getVersionMinMajor(vd, false) << "." 9098 << MachOObjectFile::getVersionMinMinor(vd, false); 9099 uint32_t Update = MachOObjectFile::getVersionMinUpdate(vd, false); 9100 if (Update != 0) 9101 outs() << "." << Update; 9102 outs() << "\n"; 9103 if (vd.sdk == 0) 9104 outs() << " sdk n/a"; 9105 else { 9106 outs() << " sdk " 9107 << MachOObjectFile::getVersionMinMajor(vd, true) << "." 9108 << MachOObjectFile::getVersionMinMinor(vd, true); 9109 } 9110 Update = MachOObjectFile::getVersionMinUpdate(vd, true); 9111 if (Update != 0) 9112 outs() << "." << Update; 9113 outs() << "\n"; 9114 } 9115 9116 static void PrintNoteLoadCommand(MachO::note_command Nt) { 9117 outs() << " cmd LC_NOTE\n"; 9118 outs() << " cmdsize " << Nt.cmdsize; 9119 if (Nt.cmdsize != sizeof(struct MachO::note_command)) 9120 outs() << " Incorrect size\n"; 9121 else 9122 outs() << "\n"; 9123 const char *d = Nt.data_owner; 9124 outs() << "data_owner " << format("%.16s\n", d); 9125 outs() << " offset " << Nt.offset << "\n"; 9126 outs() << " size " << Nt.size << "\n"; 9127 } 9128 9129 static void PrintBuildToolVersion(MachO::build_tool_version bv) { 9130 outs() << " tool " << MachOObjectFile::getBuildTool(bv.tool) << "\n"; 9131 outs() << " version " << MachOObjectFile::getVersionString(bv.version) 9132 << "\n"; 9133 } 9134 9135 static void PrintBuildVersionLoadCommand(const MachOObjectFile *obj, 9136 MachO::build_version_command bd) { 9137 outs() << " cmd LC_BUILD_VERSION\n"; 9138 outs() << " cmdsize " << bd.cmdsize; 9139 if (bd.cmdsize != 9140 sizeof(struct MachO::build_version_command) + 9141 bd.ntools * sizeof(struct MachO::build_tool_version)) 9142 outs() << " Incorrect size\n"; 9143 else 9144 outs() << "\n"; 9145 outs() << " platform " << MachOObjectFile::getBuildPlatform(bd.platform) 9146 << "\n"; 9147 if (bd.sdk) 9148 outs() << " sdk " << MachOObjectFile::getVersionString(bd.sdk) 9149 << "\n"; 9150 else 9151 outs() << " sdk n/a\n"; 9152 outs() << " minos " << MachOObjectFile::getVersionString(bd.minos) 9153 << "\n"; 9154 outs() << " ntools " << bd.ntools << "\n"; 9155 for (unsigned i = 0; i < bd.ntools; ++i) { 9156 MachO::build_tool_version bv = obj->getBuildToolVersion(i); 9157 PrintBuildToolVersion(bv); 9158 } 9159 } 9160 9161 static void PrintSourceVersionCommand(MachO::source_version_command sd) { 9162 outs() << " cmd LC_SOURCE_VERSION\n"; 9163 outs() << " cmdsize " << sd.cmdsize; 9164 if (sd.cmdsize != sizeof(struct MachO::source_version_command)) 9165 outs() << " Incorrect size\n"; 9166 else 9167 outs() << "\n"; 9168 uint64_t a = (sd.version >> 40) & 0xffffff; 9169 uint64_t b = (sd.version >> 30) & 0x3ff; 9170 uint64_t c = (sd.version >> 20) & 0x3ff; 9171 uint64_t d = (sd.version >> 10) & 0x3ff; 9172 uint64_t e = sd.version & 0x3ff; 9173 outs() << " version " << a << "." << b; 9174 if (e != 0) 9175 outs() << "." << c << "." << d << "." << e; 9176 else if (d != 0) 9177 outs() << "." << c << "." << d; 9178 else if (c != 0) 9179 outs() << "." << c; 9180 outs() << "\n"; 9181 } 9182 9183 static void PrintEntryPointCommand(MachO::entry_point_command ep) { 9184 outs() << " cmd LC_MAIN\n"; 9185 outs() << " cmdsize " << ep.cmdsize; 9186 if (ep.cmdsize != sizeof(struct MachO::entry_point_command)) 9187 outs() << " Incorrect size\n"; 9188 else 9189 outs() << "\n"; 9190 outs() << " entryoff " << ep.entryoff << "\n"; 9191 outs() << " stacksize " << ep.stacksize << "\n"; 9192 } 9193 9194 static void PrintEncryptionInfoCommand(MachO::encryption_info_command ec, 9195 uint32_t object_size) { 9196 outs() << " cmd LC_ENCRYPTION_INFO\n"; 9197 outs() << " cmdsize " << ec.cmdsize; 9198 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command)) 9199 outs() << " Incorrect size\n"; 9200 else 9201 outs() << "\n"; 9202 outs() << " cryptoff " << ec.cryptoff; 9203 if (ec.cryptoff > object_size) 9204 outs() << " (past end of file)\n"; 9205 else 9206 outs() << "\n"; 9207 outs() << " cryptsize " << ec.cryptsize; 9208 if (ec.cryptsize > object_size) 9209 outs() << " (past end of file)\n"; 9210 else 9211 outs() << "\n"; 9212 outs() << " cryptid " << ec.cryptid << "\n"; 9213 } 9214 9215 static void PrintEncryptionInfoCommand64(MachO::encryption_info_command_64 ec, 9216 uint32_t object_size) { 9217 outs() << " cmd LC_ENCRYPTION_INFO_64\n"; 9218 outs() << " cmdsize " << ec.cmdsize; 9219 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command_64)) 9220 outs() << " Incorrect size\n"; 9221 else 9222 outs() << "\n"; 9223 outs() << " cryptoff " << ec.cryptoff; 9224 if (ec.cryptoff > object_size) 9225 outs() << " (past end of file)\n"; 9226 else 9227 outs() << "\n"; 9228 outs() << " cryptsize " << ec.cryptsize; 9229 if (ec.cryptsize > object_size) 9230 outs() << " (past end of file)\n"; 9231 else 9232 outs() << "\n"; 9233 outs() << " cryptid " << ec.cryptid << "\n"; 9234 outs() << " pad " << ec.pad << "\n"; 9235 } 9236 9237 static void PrintLinkerOptionCommand(MachO::linker_option_command lo, 9238 const char *Ptr) { 9239 outs() << " cmd LC_LINKER_OPTION\n"; 9240 outs() << " cmdsize " << lo.cmdsize; 9241 if (lo.cmdsize < sizeof(struct MachO::linker_option_command)) 9242 outs() << " Incorrect size\n"; 9243 else 9244 outs() << "\n"; 9245 outs() << " count " << lo.count << "\n"; 9246 const char *string = Ptr + sizeof(struct MachO::linker_option_command); 9247 uint32_t left = lo.cmdsize - sizeof(struct MachO::linker_option_command); 9248 uint32_t i = 0; 9249 while (left > 0) { 9250 while (*string == '\0' && left > 0) { 9251 string++; 9252 left--; 9253 } 9254 if (left > 0) { 9255 i++; 9256 outs() << " string #" << i << " " << format("%.*s\n", left, string); 9257 uint32_t NullPos = StringRef(string, left).find('\0'); 9258 uint32_t len = std::min(NullPos, left) + 1; 9259 string += len; 9260 left -= len; 9261 } 9262 } 9263 if (lo.count != i) 9264 outs() << " count " << lo.count << " does not match number of strings " 9265 << i << "\n"; 9266 } 9267 9268 static void PrintSubFrameworkCommand(MachO::sub_framework_command sub, 9269 const char *Ptr) { 9270 outs() << " cmd LC_SUB_FRAMEWORK\n"; 9271 outs() << " cmdsize " << sub.cmdsize; 9272 if (sub.cmdsize < sizeof(struct MachO::sub_framework_command)) 9273 outs() << " Incorrect size\n"; 9274 else 9275 outs() << "\n"; 9276 if (sub.umbrella < sub.cmdsize) { 9277 const char *P = Ptr + sub.umbrella; 9278 outs() << " umbrella " << P << " (offset " << sub.umbrella << ")\n"; 9279 } else { 9280 outs() << " umbrella ?(bad offset " << sub.umbrella << ")\n"; 9281 } 9282 } 9283 9284 static void PrintSubUmbrellaCommand(MachO::sub_umbrella_command sub, 9285 const char *Ptr) { 9286 outs() << " cmd LC_SUB_UMBRELLA\n"; 9287 outs() << " cmdsize " << sub.cmdsize; 9288 if (sub.cmdsize < sizeof(struct MachO::sub_umbrella_command)) 9289 outs() << " Incorrect size\n"; 9290 else 9291 outs() << "\n"; 9292 if (sub.sub_umbrella < sub.cmdsize) { 9293 const char *P = Ptr + sub.sub_umbrella; 9294 outs() << " sub_umbrella " << P << " (offset " << sub.sub_umbrella << ")\n"; 9295 } else { 9296 outs() << " sub_umbrella ?(bad offset " << sub.sub_umbrella << ")\n"; 9297 } 9298 } 9299 9300 static void PrintSubLibraryCommand(MachO::sub_library_command sub, 9301 const char *Ptr) { 9302 outs() << " cmd LC_SUB_LIBRARY\n"; 9303 outs() << " cmdsize " << sub.cmdsize; 9304 if (sub.cmdsize < sizeof(struct MachO::sub_library_command)) 9305 outs() << " Incorrect size\n"; 9306 else 9307 outs() << "\n"; 9308 if (sub.sub_library < sub.cmdsize) { 9309 const char *P = Ptr + sub.sub_library; 9310 outs() << " sub_library " << P << " (offset " << sub.sub_library << ")\n"; 9311 } else { 9312 outs() << " sub_library ?(bad offset " << sub.sub_library << ")\n"; 9313 } 9314 } 9315 9316 static void PrintSubClientCommand(MachO::sub_client_command sub, 9317 const char *Ptr) { 9318 outs() << " cmd LC_SUB_CLIENT\n"; 9319 outs() << " cmdsize " << sub.cmdsize; 9320 if (sub.cmdsize < sizeof(struct MachO::sub_client_command)) 9321 outs() << " Incorrect size\n"; 9322 else 9323 outs() << "\n"; 9324 if (sub.client < sub.cmdsize) { 9325 const char *P = Ptr + sub.client; 9326 outs() << " client " << P << " (offset " << sub.client << ")\n"; 9327 } else { 9328 outs() << " client ?(bad offset " << sub.client << ")\n"; 9329 } 9330 } 9331 9332 static void PrintRoutinesCommand(MachO::routines_command r) { 9333 outs() << " cmd LC_ROUTINES\n"; 9334 outs() << " cmdsize " << r.cmdsize; 9335 if (r.cmdsize != sizeof(struct MachO::routines_command)) 9336 outs() << " Incorrect size\n"; 9337 else 9338 outs() << "\n"; 9339 outs() << " init_address " << format("0x%08" PRIx32, r.init_address) << "\n"; 9340 outs() << " init_module " << r.init_module << "\n"; 9341 outs() << " reserved1 " << r.reserved1 << "\n"; 9342 outs() << " reserved2 " << r.reserved2 << "\n"; 9343 outs() << " reserved3 " << r.reserved3 << "\n"; 9344 outs() << " reserved4 " << r.reserved4 << "\n"; 9345 outs() << " reserved5 " << r.reserved5 << "\n"; 9346 outs() << " reserved6 " << r.reserved6 << "\n"; 9347 } 9348 9349 static void PrintRoutinesCommand64(MachO::routines_command_64 r) { 9350 outs() << " cmd LC_ROUTINES_64\n"; 9351 outs() << " cmdsize " << r.cmdsize; 9352 if (r.cmdsize != sizeof(struct MachO::routines_command_64)) 9353 outs() << " Incorrect size\n"; 9354 else 9355 outs() << "\n"; 9356 outs() << " init_address " << format("0x%016" PRIx64, r.init_address) << "\n"; 9357 outs() << " init_module " << r.init_module << "\n"; 9358 outs() << " reserved1 " << r.reserved1 << "\n"; 9359 outs() << " reserved2 " << r.reserved2 << "\n"; 9360 outs() << " reserved3 " << r.reserved3 << "\n"; 9361 outs() << " reserved4 " << r.reserved4 << "\n"; 9362 outs() << " reserved5 " << r.reserved5 << "\n"; 9363 outs() << " reserved6 " << r.reserved6 << "\n"; 9364 } 9365 9366 static void Print_x86_thread_state32_t(MachO::x86_thread_state32_t &cpu32) { 9367 outs() << "\t eax " << format("0x%08" PRIx32, cpu32.eax); 9368 outs() << " ebx " << format("0x%08" PRIx32, cpu32.ebx); 9369 outs() << " ecx " << format("0x%08" PRIx32, cpu32.ecx); 9370 outs() << " edx " << format("0x%08" PRIx32, cpu32.edx) << "\n"; 9371 outs() << "\t edi " << format("0x%08" PRIx32, cpu32.edi); 9372 outs() << " esi " << format("0x%08" PRIx32, cpu32.esi); 9373 outs() << " ebp " << format("0x%08" PRIx32, cpu32.ebp); 9374 outs() << " esp " << format("0x%08" PRIx32, cpu32.esp) << "\n"; 9375 outs() << "\t ss " << format("0x%08" PRIx32, cpu32.ss); 9376 outs() << " eflags " << format("0x%08" PRIx32, cpu32.eflags); 9377 outs() << " eip " << format("0x%08" PRIx32, cpu32.eip); 9378 outs() << " cs " << format("0x%08" PRIx32, cpu32.cs) << "\n"; 9379 outs() << "\t ds " << format("0x%08" PRIx32, cpu32.ds); 9380 outs() << " es " << format("0x%08" PRIx32, cpu32.es); 9381 outs() << " fs " << format("0x%08" PRIx32, cpu32.fs); 9382 outs() << " gs " << format("0x%08" PRIx32, cpu32.gs) << "\n"; 9383 } 9384 9385 static void Print_x86_thread_state64_t(MachO::x86_thread_state64_t &cpu64) { 9386 outs() << " rax " << format("0x%016" PRIx64, cpu64.rax); 9387 outs() << " rbx " << format("0x%016" PRIx64, cpu64.rbx); 9388 outs() << " rcx " << format("0x%016" PRIx64, cpu64.rcx) << "\n"; 9389 outs() << " rdx " << format("0x%016" PRIx64, cpu64.rdx); 9390 outs() << " rdi " << format("0x%016" PRIx64, cpu64.rdi); 9391 outs() << " rsi " << format("0x%016" PRIx64, cpu64.rsi) << "\n"; 9392 outs() << " rbp " << format("0x%016" PRIx64, cpu64.rbp); 9393 outs() << " rsp " << format("0x%016" PRIx64, cpu64.rsp); 9394 outs() << " r8 " << format("0x%016" PRIx64, cpu64.r8) << "\n"; 9395 outs() << " r9 " << format("0x%016" PRIx64, cpu64.r9); 9396 outs() << " r10 " << format("0x%016" PRIx64, cpu64.r10); 9397 outs() << " r11 " << format("0x%016" PRIx64, cpu64.r11) << "\n"; 9398 outs() << " r12 " << format("0x%016" PRIx64, cpu64.r12); 9399 outs() << " r13 " << format("0x%016" PRIx64, cpu64.r13); 9400 outs() << " r14 " << format("0x%016" PRIx64, cpu64.r14) << "\n"; 9401 outs() << " r15 " << format("0x%016" PRIx64, cpu64.r15); 9402 outs() << " rip " << format("0x%016" PRIx64, cpu64.rip) << "\n"; 9403 outs() << "rflags " << format("0x%016" PRIx64, cpu64.rflags); 9404 outs() << " cs " << format("0x%016" PRIx64, cpu64.cs); 9405 outs() << " fs " << format("0x%016" PRIx64, cpu64.fs) << "\n"; 9406 outs() << " gs " << format("0x%016" PRIx64, cpu64.gs) << "\n"; 9407 } 9408 9409 static void Print_mmst_reg(MachO::mmst_reg_t &r) { 9410 uint32_t f; 9411 outs() << "\t mmst_reg "; 9412 for (f = 0; f < 10; f++) 9413 outs() << format("%02" PRIx32, (r.mmst_reg[f] & 0xff)) << " "; 9414 outs() << "\n"; 9415 outs() << "\t mmst_rsrv "; 9416 for (f = 0; f < 6; f++) 9417 outs() << format("%02" PRIx32, (r.mmst_rsrv[f] & 0xff)) << " "; 9418 outs() << "\n"; 9419 } 9420 9421 static void Print_xmm_reg(MachO::xmm_reg_t &r) { 9422 uint32_t f; 9423 outs() << "\t xmm_reg "; 9424 for (f = 0; f < 16; f++) 9425 outs() << format("%02" PRIx32, (r.xmm_reg[f] & 0xff)) << " "; 9426 outs() << "\n"; 9427 } 9428 9429 static void Print_x86_float_state_t(MachO::x86_float_state64_t &fpu) { 9430 outs() << "\t fpu_reserved[0] " << fpu.fpu_reserved[0]; 9431 outs() << " fpu_reserved[1] " << fpu.fpu_reserved[1] << "\n"; 9432 outs() << "\t control: invalid " << fpu.fpu_fcw.invalid; 9433 outs() << " denorm " << fpu.fpu_fcw.denorm; 9434 outs() << " zdiv " << fpu.fpu_fcw.zdiv; 9435 outs() << " ovrfl " << fpu.fpu_fcw.ovrfl; 9436 outs() << " undfl " << fpu.fpu_fcw.undfl; 9437 outs() << " precis " << fpu.fpu_fcw.precis << "\n"; 9438 outs() << "\t\t pc "; 9439 if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_24B) 9440 outs() << "FP_PREC_24B "; 9441 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_53B) 9442 outs() << "FP_PREC_53B "; 9443 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_64B) 9444 outs() << "FP_PREC_64B "; 9445 else 9446 outs() << fpu.fpu_fcw.pc << " "; 9447 outs() << "rc "; 9448 if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_NEAR) 9449 outs() << "FP_RND_NEAR "; 9450 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_DOWN) 9451 outs() << "FP_RND_DOWN "; 9452 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_UP) 9453 outs() << "FP_RND_UP "; 9454 else if (fpu.fpu_fcw.rc == MachO::x86_FP_CHOP) 9455 outs() << "FP_CHOP "; 9456 outs() << "\n"; 9457 outs() << "\t status: invalid " << fpu.fpu_fsw.invalid; 9458 outs() << " denorm " << fpu.fpu_fsw.denorm; 9459 outs() << " zdiv " << fpu.fpu_fsw.zdiv; 9460 outs() << " ovrfl " << fpu.fpu_fsw.ovrfl; 9461 outs() << " undfl " << fpu.fpu_fsw.undfl; 9462 outs() << " precis " << fpu.fpu_fsw.precis; 9463 outs() << " stkflt " << fpu.fpu_fsw.stkflt << "\n"; 9464 outs() << "\t errsumm " << fpu.fpu_fsw.errsumm; 9465 outs() << " c0 " << fpu.fpu_fsw.c0; 9466 outs() << " c1 " << fpu.fpu_fsw.c1; 9467 outs() << " c2 " << fpu.fpu_fsw.c2; 9468 outs() << " tos " << fpu.fpu_fsw.tos; 9469 outs() << " c3 " << fpu.fpu_fsw.c3; 9470 outs() << " busy " << fpu.fpu_fsw.busy << "\n"; 9471 outs() << "\t fpu_ftw " << format("0x%02" PRIx32, fpu.fpu_ftw); 9472 outs() << " fpu_rsrv1 " << format("0x%02" PRIx32, fpu.fpu_rsrv1); 9473 outs() << " fpu_fop " << format("0x%04" PRIx32, fpu.fpu_fop); 9474 outs() << " fpu_ip " << format("0x%08" PRIx32, fpu.fpu_ip) << "\n"; 9475 outs() << "\t fpu_cs " << format("0x%04" PRIx32, fpu.fpu_cs); 9476 outs() << " fpu_rsrv2 " << format("0x%04" PRIx32, fpu.fpu_rsrv2); 9477 outs() << " fpu_dp " << format("0x%08" PRIx32, fpu.fpu_dp); 9478 outs() << " fpu_ds " << format("0x%04" PRIx32, fpu.fpu_ds) << "\n"; 9479 outs() << "\t fpu_rsrv3 " << format("0x%04" PRIx32, fpu.fpu_rsrv3); 9480 outs() << " fpu_mxcsr " << format("0x%08" PRIx32, fpu.fpu_mxcsr); 9481 outs() << " fpu_mxcsrmask " << format("0x%08" PRIx32, fpu.fpu_mxcsrmask); 9482 outs() << "\n"; 9483 outs() << "\t fpu_stmm0:\n"; 9484 Print_mmst_reg(fpu.fpu_stmm0); 9485 outs() << "\t fpu_stmm1:\n"; 9486 Print_mmst_reg(fpu.fpu_stmm1); 9487 outs() << "\t fpu_stmm2:\n"; 9488 Print_mmst_reg(fpu.fpu_stmm2); 9489 outs() << "\t fpu_stmm3:\n"; 9490 Print_mmst_reg(fpu.fpu_stmm3); 9491 outs() << "\t fpu_stmm4:\n"; 9492 Print_mmst_reg(fpu.fpu_stmm4); 9493 outs() << "\t fpu_stmm5:\n"; 9494 Print_mmst_reg(fpu.fpu_stmm5); 9495 outs() << "\t fpu_stmm6:\n"; 9496 Print_mmst_reg(fpu.fpu_stmm6); 9497 outs() << "\t fpu_stmm7:\n"; 9498 Print_mmst_reg(fpu.fpu_stmm7); 9499 outs() << "\t fpu_xmm0:\n"; 9500 Print_xmm_reg(fpu.fpu_xmm0); 9501 outs() << "\t fpu_xmm1:\n"; 9502 Print_xmm_reg(fpu.fpu_xmm1); 9503 outs() << "\t fpu_xmm2:\n"; 9504 Print_xmm_reg(fpu.fpu_xmm2); 9505 outs() << "\t fpu_xmm3:\n"; 9506 Print_xmm_reg(fpu.fpu_xmm3); 9507 outs() << "\t fpu_xmm4:\n"; 9508 Print_xmm_reg(fpu.fpu_xmm4); 9509 outs() << "\t fpu_xmm5:\n"; 9510 Print_xmm_reg(fpu.fpu_xmm5); 9511 outs() << "\t fpu_xmm6:\n"; 9512 Print_xmm_reg(fpu.fpu_xmm6); 9513 outs() << "\t fpu_xmm7:\n"; 9514 Print_xmm_reg(fpu.fpu_xmm7); 9515 outs() << "\t fpu_xmm8:\n"; 9516 Print_xmm_reg(fpu.fpu_xmm8); 9517 outs() << "\t fpu_xmm9:\n"; 9518 Print_xmm_reg(fpu.fpu_xmm9); 9519 outs() << "\t fpu_xmm10:\n"; 9520 Print_xmm_reg(fpu.fpu_xmm10); 9521 outs() << "\t fpu_xmm11:\n"; 9522 Print_xmm_reg(fpu.fpu_xmm11); 9523 outs() << "\t fpu_xmm12:\n"; 9524 Print_xmm_reg(fpu.fpu_xmm12); 9525 outs() << "\t fpu_xmm13:\n"; 9526 Print_xmm_reg(fpu.fpu_xmm13); 9527 outs() << "\t fpu_xmm14:\n"; 9528 Print_xmm_reg(fpu.fpu_xmm14); 9529 outs() << "\t fpu_xmm15:\n"; 9530 Print_xmm_reg(fpu.fpu_xmm15); 9531 outs() << "\t fpu_rsrv4:\n"; 9532 for (uint32_t f = 0; f < 6; f++) { 9533 outs() << "\t "; 9534 for (uint32_t g = 0; g < 16; g++) 9535 outs() << format("%02" PRIx32, fpu.fpu_rsrv4[f * g]) << " "; 9536 outs() << "\n"; 9537 } 9538 outs() << "\t fpu_reserved1 " << format("0x%08" PRIx32, fpu.fpu_reserved1); 9539 outs() << "\n"; 9540 } 9541 9542 static void Print_x86_exception_state_t(MachO::x86_exception_state64_t &exc64) { 9543 outs() << "\t trapno " << format("0x%08" PRIx32, exc64.trapno); 9544 outs() << " err " << format("0x%08" PRIx32, exc64.err); 9545 outs() << " faultvaddr " << format("0x%016" PRIx64, exc64.faultvaddr) << "\n"; 9546 } 9547 9548 static void Print_arm_thread_state32_t(MachO::arm_thread_state32_t &cpu32) { 9549 outs() << "\t r0 " << format("0x%08" PRIx32, cpu32.r[0]); 9550 outs() << " r1 " << format("0x%08" PRIx32, cpu32.r[1]); 9551 outs() << " r2 " << format("0x%08" PRIx32, cpu32.r[2]); 9552 outs() << " r3 " << format("0x%08" PRIx32, cpu32.r[3]) << "\n"; 9553 outs() << "\t r4 " << format("0x%08" PRIx32, cpu32.r[4]); 9554 outs() << " r5 " << format("0x%08" PRIx32, cpu32.r[5]); 9555 outs() << " r6 " << format("0x%08" PRIx32, cpu32.r[6]); 9556 outs() << " r7 " << format("0x%08" PRIx32, cpu32.r[7]) << "\n"; 9557 outs() << "\t r8 " << format("0x%08" PRIx32, cpu32.r[8]); 9558 outs() << " r9 " << format("0x%08" PRIx32, cpu32.r[9]); 9559 outs() << " r10 " << format("0x%08" PRIx32, cpu32.r[10]); 9560 outs() << " r11 " << format("0x%08" PRIx32, cpu32.r[11]) << "\n"; 9561 outs() << "\t r12 " << format("0x%08" PRIx32, cpu32.r[12]); 9562 outs() << " sp " << format("0x%08" PRIx32, cpu32.sp); 9563 outs() << " lr " << format("0x%08" PRIx32, cpu32.lr); 9564 outs() << " pc " << format("0x%08" PRIx32, cpu32.pc) << "\n"; 9565 outs() << "\t cpsr " << format("0x%08" PRIx32, cpu32.cpsr) << "\n"; 9566 } 9567 9568 static void Print_arm_thread_state64_t(MachO::arm_thread_state64_t &cpu64) { 9569 outs() << "\t x0 " << format("0x%016" PRIx64, cpu64.x[0]); 9570 outs() << " x1 " << format("0x%016" PRIx64, cpu64.x[1]); 9571 outs() << " x2 " << format("0x%016" PRIx64, cpu64.x[2]) << "\n"; 9572 outs() << "\t x3 " << format("0x%016" PRIx64, cpu64.x[3]); 9573 outs() << " x4 " << format("0x%016" PRIx64, cpu64.x[4]); 9574 outs() << " x5 " << format("0x%016" PRIx64, cpu64.x[5]) << "\n"; 9575 outs() << "\t x6 " << format("0x%016" PRIx64, cpu64.x[6]); 9576 outs() << " x7 " << format("0x%016" PRIx64, cpu64.x[7]); 9577 outs() << " x8 " << format("0x%016" PRIx64, cpu64.x[8]) << "\n"; 9578 outs() << "\t x9 " << format("0x%016" PRIx64, cpu64.x[9]); 9579 outs() << " x10 " << format("0x%016" PRIx64, cpu64.x[10]); 9580 outs() << " x11 " << format("0x%016" PRIx64, cpu64.x[11]) << "\n"; 9581 outs() << "\t x12 " << format("0x%016" PRIx64, cpu64.x[12]); 9582 outs() << " x13 " << format("0x%016" PRIx64, cpu64.x[13]); 9583 outs() << " x14 " << format("0x%016" PRIx64, cpu64.x[14]) << "\n"; 9584 outs() << "\t x15 " << format("0x%016" PRIx64, cpu64.x[15]); 9585 outs() << " x16 " << format("0x%016" PRIx64, cpu64.x[16]); 9586 outs() << " x17 " << format("0x%016" PRIx64, cpu64.x[17]) << "\n"; 9587 outs() << "\t x18 " << format("0x%016" PRIx64, cpu64.x[18]); 9588 outs() << " x19 " << format("0x%016" PRIx64, cpu64.x[19]); 9589 outs() << " x20 " << format("0x%016" PRIx64, cpu64.x[20]) << "\n"; 9590 outs() << "\t x21 " << format("0x%016" PRIx64, cpu64.x[21]); 9591 outs() << " x22 " << format("0x%016" PRIx64, cpu64.x[22]); 9592 outs() << " x23 " << format("0x%016" PRIx64, cpu64.x[23]) << "\n"; 9593 outs() << "\t x24 " << format("0x%016" PRIx64, cpu64.x[24]); 9594 outs() << " x25 " << format("0x%016" PRIx64, cpu64.x[25]); 9595 outs() << " x26 " << format("0x%016" PRIx64, cpu64.x[26]) << "\n"; 9596 outs() << "\t x27 " << format("0x%016" PRIx64, cpu64.x[27]); 9597 outs() << " x28 " << format("0x%016" PRIx64, cpu64.x[28]); 9598 outs() << " fp " << format("0x%016" PRIx64, cpu64.fp) << "\n"; 9599 outs() << "\t lr " << format("0x%016" PRIx64, cpu64.lr); 9600 outs() << " sp " << format("0x%016" PRIx64, cpu64.sp); 9601 outs() << " pc " << format("0x%016" PRIx64, cpu64.pc) << "\n"; 9602 outs() << "\t cpsr " << format("0x%08" PRIx32, cpu64.cpsr) << "\n"; 9603 } 9604 9605 static void PrintThreadCommand(MachO::thread_command t, const char *Ptr, 9606 bool isLittleEndian, uint32_t cputype) { 9607 if (t.cmd == MachO::LC_THREAD) 9608 outs() << " cmd LC_THREAD\n"; 9609 else if (t.cmd == MachO::LC_UNIXTHREAD) 9610 outs() << " cmd LC_UNIXTHREAD\n"; 9611 else 9612 outs() << " cmd " << t.cmd << " (unknown)\n"; 9613 outs() << " cmdsize " << t.cmdsize; 9614 if (t.cmdsize < sizeof(struct MachO::thread_command) + 2 * sizeof(uint32_t)) 9615 outs() << " Incorrect size\n"; 9616 else 9617 outs() << "\n"; 9618 9619 const char *begin = Ptr + sizeof(struct MachO::thread_command); 9620 const char *end = Ptr + t.cmdsize; 9621 uint32_t flavor, count, left; 9622 if (cputype == MachO::CPU_TYPE_I386) { 9623 while (begin < end) { 9624 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) { 9625 memcpy((char *)&flavor, begin, sizeof(uint32_t)); 9626 begin += sizeof(uint32_t); 9627 } else { 9628 flavor = 0; 9629 begin = end; 9630 } 9631 if (isLittleEndian != sys::IsLittleEndianHost) 9632 sys::swapByteOrder(flavor); 9633 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) { 9634 memcpy((char *)&count, begin, sizeof(uint32_t)); 9635 begin += sizeof(uint32_t); 9636 } else { 9637 count = 0; 9638 begin = end; 9639 } 9640 if (isLittleEndian != sys::IsLittleEndianHost) 9641 sys::swapByteOrder(count); 9642 if (flavor == MachO::x86_THREAD_STATE32) { 9643 outs() << " flavor i386_THREAD_STATE\n"; 9644 if (count == MachO::x86_THREAD_STATE32_COUNT) 9645 outs() << " count i386_THREAD_STATE_COUNT\n"; 9646 else 9647 outs() << " count " << count 9648 << " (not x86_THREAD_STATE32_COUNT)\n"; 9649 MachO::x86_thread_state32_t cpu32; 9650 left = end - begin; 9651 if (left >= sizeof(MachO::x86_thread_state32_t)) { 9652 memcpy(&cpu32, begin, sizeof(MachO::x86_thread_state32_t)); 9653 begin += sizeof(MachO::x86_thread_state32_t); 9654 } else { 9655 memset(&cpu32, '\0', sizeof(MachO::x86_thread_state32_t)); 9656 memcpy(&cpu32, begin, left); 9657 begin += left; 9658 } 9659 if (isLittleEndian != sys::IsLittleEndianHost) 9660 swapStruct(cpu32); 9661 Print_x86_thread_state32_t(cpu32); 9662 } else if (flavor == MachO::x86_THREAD_STATE) { 9663 outs() << " flavor x86_THREAD_STATE\n"; 9664 if (count == MachO::x86_THREAD_STATE_COUNT) 9665 outs() << " count x86_THREAD_STATE_COUNT\n"; 9666 else 9667 outs() << " count " << count 9668 << " (not x86_THREAD_STATE_COUNT)\n"; 9669 struct MachO::x86_thread_state_t ts; 9670 left = end - begin; 9671 if (left >= sizeof(MachO::x86_thread_state_t)) { 9672 memcpy(&ts, begin, sizeof(MachO::x86_thread_state_t)); 9673 begin += sizeof(MachO::x86_thread_state_t); 9674 } else { 9675 memset(&ts, '\0', sizeof(MachO::x86_thread_state_t)); 9676 memcpy(&ts, begin, left); 9677 begin += left; 9678 } 9679 if (isLittleEndian != sys::IsLittleEndianHost) 9680 swapStruct(ts); 9681 if (ts.tsh.flavor == MachO::x86_THREAD_STATE32) { 9682 outs() << "\t tsh.flavor x86_THREAD_STATE32 "; 9683 if (ts.tsh.count == MachO::x86_THREAD_STATE32_COUNT) 9684 outs() << "tsh.count x86_THREAD_STATE32_COUNT\n"; 9685 else 9686 outs() << "tsh.count " << ts.tsh.count 9687 << " (not x86_THREAD_STATE32_COUNT\n"; 9688 Print_x86_thread_state32_t(ts.uts.ts32); 9689 } else { 9690 outs() << "\t tsh.flavor " << ts.tsh.flavor << " tsh.count " 9691 << ts.tsh.count << "\n"; 9692 } 9693 } else { 9694 outs() << " flavor " << flavor << " (unknown)\n"; 9695 outs() << " count " << count << "\n"; 9696 outs() << " state (unknown)\n"; 9697 begin += count * sizeof(uint32_t); 9698 } 9699 } 9700 } else if (cputype == MachO::CPU_TYPE_X86_64) { 9701 while (begin < end) { 9702 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) { 9703 memcpy((char *)&flavor, begin, sizeof(uint32_t)); 9704 begin += sizeof(uint32_t); 9705 } else { 9706 flavor = 0; 9707 begin = end; 9708 } 9709 if (isLittleEndian != sys::IsLittleEndianHost) 9710 sys::swapByteOrder(flavor); 9711 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) { 9712 memcpy((char *)&count, begin, sizeof(uint32_t)); 9713 begin += sizeof(uint32_t); 9714 } else { 9715 count = 0; 9716 begin = end; 9717 } 9718 if (isLittleEndian != sys::IsLittleEndianHost) 9719 sys::swapByteOrder(count); 9720 if (flavor == MachO::x86_THREAD_STATE64) { 9721 outs() << " flavor x86_THREAD_STATE64\n"; 9722 if (count == MachO::x86_THREAD_STATE64_COUNT) 9723 outs() << " count x86_THREAD_STATE64_COUNT\n"; 9724 else 9725 outs() << " count " << count 9726 << " (not x86_THREAD_STATE64_COUNT)\n"; 9727 MachO::x86_thread_state64_t cpu64; 9728 left = end - begin; 9729 if (left >= sizeof(MachO::x86_thread_state64_t)) { 9730 memcpy(&cpu64, begin, sizeof(MachO::x86_thread_state64_t)); 9731 begin += sizeof(MachO::x86_thread_state64_t); 9732 } else { 9733 memset(&cpu64, '\0', sizeof(MachO::x86_thread_state64_t)); 9734 memcpy(&cpu64, begin, left); 9735 begin += left; 9736 } 9737 if (isLittleEndian != sys::IsLittleEndianHost) 9738 swapStruct(cpu64); 9739 Print_x86_thread_state64_t(cpu64); 9740 } else if (flavor == MachO::x86_THREAD_STATE) { 9741 outs() << " flavor x86_THREAD_STATE\n"; 9742 if (count == MachO::x86_THREAD_STATE_COUNT) 9743 outs() << " count x86_THREAD_STATE_COUNT\n"; 9744 else 9745 outs() << " count " << count 9746 << " (not x86_THREAD_STATE_COUNT)\n"; 9747 struct MachO::x86_thread_state_t ts; 9748 left = end - begin; 9749 if (left >= sizeof(MachO::x86_thread_state_t)) { 9750 memcpy(&ts, begin, sizeof(MachO::x86_thread_state_t)); 9751 begin += sizeof(MachO::x86_thread_state_t); 9752 } else { 9753 memset(&ts, '\0', sizeof(MachO::x86_thread_state_t)); 9754 memcpy(&ts, begin, left); 9755 begin += left; 9756 } 9757 if (isLittleEndian != sys::IsLittleEndianHost) 9758 swapStruct(ts); 9759 if (ts.tsh.flavor == MachO::x86_THREAD_STATE64) { 9760 outs() << "\t tsh.flavor x86_THREAD_STATE64 "; 9761 if (ts.tsh.count == MachO::x86_THREAD_STATE64_COUNT) 9762 outs() << "tsh.count x86_THREAD_STATE64_COUNT\n"; 9763 else 9764 outs() << "tsh.count " << ts.tsh.count 9765 << " (not x86_THREAD_STATE64_COUNT\n"; 9766 Print_x86_thread_state64_t(ts.uts.ts64); 9767 } else { 9768 outs() << "\t tsh.flavor " << ts.tsh.flavor << " tsh.count " 9769 << ts.tsh.count << "\n"; 9770 } 9771 } else if (flavor == MachO::x86_FLOAT_STATE) { 9772 outs() << " flavor x86_FLOAT_STATE\n"; 9773 if (count == MachO::x86_FLOAT_STATE_COUNT) 9774 outs() << " count x86_FLOAT_STATE_COUNT\n"; 9775 else 9776 outs() << " count " << count << " (not x86_FLOAT_STATE_COUNT)\n"; 9777 struct MachO::x86_float_state_t fs; 9778 left = end - begin; 9779 if (left >= sizeof(MachO::x86_float_state_t)) { 9780 memcpy(&fs, begin, sizeof(MachO::x86_float_state_t)); 9781 begin += sizeof(MachO::x86_float_state_t); 9782 } else { 9783 memset(&fs, '\0', sizeof(MachO::x86_float_state_t)); 9784 memcpy(&fs, begin, left); 9785 begin += left; 9786 } 9787 if (isLittleEndian != sys::IsLittleEndianHost) 9788 swapStruct(fs); 9789 if (fs.fsh.flavor == MachO::x86_FLOAT_STATE64) { 9790 outs() << "\t fsh.flavor x86_FLOAT_STATE64 "; 9791 if (fs.fsh.count == MachO::x86_FLOAT_STATE64_COUNT) 9792 outs() << "fsh.count x86_FLOAT_STATE64_COUNT\n"; 9793 else 9794 outs() << "fsh.count " << fs.fsh.count 9795 << " (not x86_FLOAT_STATE64_COUNT\n"; 9796 Print_x86_float_state_t(fs.ufs.fs64); 9797 } else { 9798 outs() << "\t fsh.flavor " << fs.fsh.flavor << " fsh.count " 9799 << fs.fsh.count << "\n"; 9800 } 9801 } else if (flavor == MachO::x86_EXCEPTION_STATE) { 9802 outs() << " flavor x86_EXCEPTION_STATE\n"; 9803 if (count == MachO::x86_EXCEPTION_STATE_COUNT) 9804 outs() << " count x86_EXCEPTION_STATE_COUNT\n"; 9805 else 9806 outs() << " count " << count 9807 << " (not x86_EXCEPTION_STATE_COUNT)\n"; 9808 struct MachO::x86_exception_state_t es; 9809 left = end - begin; 9810 if (left >= sizeof(MachO::x86_exception_state_t)) { 9811 memcpy(&es, begin, sizeof(MachO::x86_exception_state_t)); 9812 begin += sizeof(MachO::x86_exception_state_t); 9813 } else { 9814 memset(&es, '\0', sizeof(MachO::x86_exception_state_t)); 9815 memcpy(&es, begin, left); 9816 begin += left; 9817 } 9818 if (isLittleEndian != sys::IsLittleEndianHost) 9819 swapStruct(es); 9820 if (es.esh.flavor == MachO::x86_EXCEPTION_STATE64) { 9821 outs() << "\t esh.flavor x86_EXCEPTION_STATE64\n"; 9822 if (es.esh.count == MachO::x86_EXCEPTION_STATE64_COUNT) 9823 outs() << "\t esh.count x86_EXCEPTION_STATE64_COUNT\n"; 9824 else 9825 outs() << "\t esh.count " << es.esh.count 9826 << " (not x86_EXCEPTION_STATE64_COUNT\n"; 9827 Print_x86_exception_state_t(es.ues.es64); 9828 } else { 9829 outs() << "\t esh.flavor " << es.esh.flavor << " esh.count " 9830 << es.esh.count << "\n"; 9831 } 9832 } else if (flavor == MachO::x86_EXCEPTION_STATE64) { 9833 outs() << " flavor x86_EXCEPTION_STATE64\n"; 9834 if (count == MachO::x86_EXCEPTION_STATE64_COUNT) 9835 outs() << " count x86_EXCEPTION_STATE64_COUNT\n"; 9836 else 9837 outs() << " count " << count 9838 << " (not x86_EXCEPTION_STATE64_COUNT)\n"; 9839 struct MachO::x86_exception_state64_t es64; 9840 left = end - begin; 9841 if (left >= sizeof(MachO::x86_exception_state64_t)) { 9842 memcpy(&es64, begin, sizeof(MachO::x86_exception_state64_t)); 9843 begin += sizeof(MachO::x86_exception_state64_t); 9844 } else { 9845 memset(&es64, '\0', sizeof(MachO::x86_exception_state64_t)); 9846 memcpy(&es64, begin, left); 9847 begin += left; 9848 } 9849 if (isLittleEndian != sys::IsLittleEndianHost) 9850 swapStruct(es64); 9851 Print_x86_exception_state_t(es64); 9852 } else { 9853 outs() << " flavor " << flavor << " (unknown)\n"; 9854 outs() << " count " << count << "\n"; 9855 outs() << " state (unknown)\n"; 9856 begin += count * sizeof(uint32_t); 9857 } 9858 } 9859 } else if (cputype == MachO::CPU_TYPE_ARM) { 9860 while (begin < end) { 9861 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) { 9862 memcpy((char *)&flavor, begin, sizeof(uint32_t)); 9863 begin += sizeof(uint32_t); 9864 } else { 9865 flavor = 0; 9866 begin = end; 9867 } 9868 if (isLittleEndian != sys::IsLittleEndianHost) 9869 sys::swapByteOrder(flavor); 9870 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) { 9871 memcpy((char *)&count, begin, sizeof(uint32_t)); 9872 begin += sizeof(uint32_t); 9873 } else { 9874 count = 0; 9875 begin = end; 9876 } 9877 if (isLittleEndian != sys::IsLittleEndianHost) 9878 sys::swapByteOrder(count); 9879 if (flavor == MachO::ARM_THREAD_STATE) { 9880 outs() << " flavor ARM_THREAD_STATE\n"; 9881 if (count == MachO::ARM_THREAD_STATE_COUNT) 9882 outs() << " count ARM_THREAD_STATE_COUNT\n"; 9883 else 9884 outs() << " count " << count 9885 << " (not ARM_THREAD_STATE_COUNT)\n"; 9886 MachO::arm_thread_state32_t cpu32; 9887 left = end - begin; 9888 if (left >= sizeof(MachO::arm_thread_state32_t)) { 9889 memcpy(&cpu32, begin, sizeof(MachO::arm_thread_state32_t)); 9890 begin += sizeof(MachO::arm_thread_state32_t); 9891 } else { 9892 memset(&cpu32, '\0', sizeof(MachO::arm_thread_state32_t)); 9893 memcpy(&cpu32, begin, left); 9894 begin += left; 9895 } 9896 if (isLittleEndian != sys::IsLittleEndianHost) 9897 swapStruct(cpu32); 9898 Print_arm_thread_state32_t(cpu32); 9899 } else { 9900 outs() << " flavor " << flavor << " (unknown)\n"; 9901 outs() << " count " << count << "\n"; 9902 outs() << " state (unknown)\n"; 9903 begin += count * sizeof(uint32_t); 9904 } 9905 } 9906 } else if (cputype == MachO::CPU_TYPE_ARM64 || 9907 cputype == MachO::CPU_TYPE_ARM64_32) { 9908 while (begin < end) { 9909 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) { 9910 memcpy((char *)&flavor, begin, sizeof(uint32_t)); 9911 begin += sizeof(uint32_t); 9912 } else { 9913 flavor = 0; 9914 begin = end; 9915 } 9916 if (isLittleEndian != sys::IsLittleEndianHost) 9917 sys::swapByteOrder(flavor); 9918 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) { 9919 memcpy((char *)&count, begin, sizeof(uint32_t)); 9920 begin += sizeof(uint32_t); 9921 } else { 9922 count = 0; 9923 begin = end; 9924 } 9925 if (isLittleEndian != sys::IsLittleEndianHost) 9926 sys::swapByteOrder(count); 9927 if (flavor == MachO::ARM_THREAD_STATE64) { 9928 outs() << " flavor ARM_THREAD_STATE64\n"; 9929 if (count == MachO::ARM_THREAD_STATE64_COUNT) 9930 outs() << " count ARM_THREAD_STATE64_COUNT\n"; 9931 else 9932 outs() << " count " << count 9933 << " (not ARM_THREAD_STATE64_COUNT)\n"; 9934 MachO::arm_thread_state64_t cpu64; 9935 left = end - begin; 9936 if (left >= sizeof(MachO::arm_thread_state64_t)) { 9937 memcpy(&cpu64, begin, sizeof(MachO::arm_thread_state64_t)); 9938 begin += sizeof(MachO::arm_thread_state64_t); 9939 } else { 9940 memset(&cpu64, '\0', sizeof(MachO::arm_thread_state64_t)); 9941 memcpy(&cpu64, begin, left); 9942 begin += left; 9943 } 9944 if (isLittleEndian != sys::IsLittleEndianHost) 9945 swapStruct(cpu64); 9946 Print_arm_thread_state64_t(cpu64); 9947 } else { 9948 outs() << " flavor " << flavor << " (unknown)\n"; 9949 outs() << " count " << count << "\n"; 9950 outs() << " state (unknown)\n"; 9951 begin += count * sizeof(uint32_t); 9952 } 9953 } 9954 } else { 9955 while (begin < end) { 9956 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) { 9957 memcpy((char *)&flavor, begin, sizeof(uint32_t)); 9958 begin += sizeof(uint32_t); 9959 } else { 9960 flavor = 0; 9961 begin = end; 9962 } 9963 if (isLittleEndian != sys::IsLittleEndianHost) 9964 sys::swapByteOrder(flavor); 9965 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) { 9966 memcpy((char *)&count, begin, sizeof(uint32_t)); 9967 begin += sizeof(uint32_t); 9968 } else { 9969 count = 0; 9970 begin = end; 9971 } 9972 if (isLittleEndian != sys::IsLittleEndianHost) 9973 sys::swapByteOrder(count); 9974 outs() << " flavor " << flavor << "\n"; 9975 outs() << " count " << count << "\n"; 9976 outs() << " state (Unknown cputype/cpusubtype)\n"; 9977 begin += count * sizeof(uint32_t); 9978 } 9979 } 9980 } 9981 9982 static void PrintDylibCommand(MachO::dylib_command dl, const char *Ptr) { 9983 if (dl.cmd == MachO::LC_ID_DYLIB) 9984 outs() << " cmd LC_ID_DYLIB\n"; 9985 else if (dl.cmd == MachO::LC_LOAD_DYLIB) 9986 outs() << " cmd LC_LOAD_DYLIB\n"; 9987 else if (dl.cmd == MachO::LC_LOAD_WEAK_DYLIB) 9988 outs() << " cmd LC_LOAD_WEAK_DYLIB\n"; 9989 else if (dl.cmd == MachO::LC_REEXPORT_DYLIB) 9990 outs() << " cmd LC_REEXPORT_DYLIB\n"; 9991 else if (dl.cmd == MachO::LC_LAZY_LOAD_DYLIB) 9992 outs() << " cmd LC_LAZY_LOAD_DYLIB\n"; 9993 else if (dl.cmd == MachO::LC_LOAD_UPWARD_DYLIB) 9994 outs() << " cmd LC_LOAD_UPWARD_DYLIB\n"; 9995 else 9996 outs() << " cmd " << dl.cmd << " (unknown)\n"; 9997 outs() << " cmdsize " << dl.cmdsize; 9998 if (dl.cmdsize < sizeof(struct MachO::dylib_command)) 9999 outs() << " Incorrect size\n"; 10000 else 10001 outs() << "\n"; 10002 if (dl.dylib.name < dl.cmdsize) { 10003 const char *P = (const char *)(Ptr) + dl.dylib.name; 10004 outs() << " name " << P << " (offset " << dl.dylib.name << ")\n"; 10005 } else { 10006 outs() << " name ?(bad offset " << dl.dylib.name << ")\n"; 10007 } 10008 outs() << " time stamp " << dl.dylib.timestamp << " "; 10009 time_t t = dl.dylib.timestamp; 10010 outs() << ctime(&t); 10011 outs() << " current version "; 10012 if (dl.dylib.current_version == 0xffffffff) 10013 outs() << "n/a\n"; 10014 else 10015 outs() << ((dl.dylib.current_version >> 16) & 0xffff) << "." 10016 << ((dl.dylib.current_version >> 8) & 0xff) << "." 10017 << (dl.dylib.current_version & 0xff) << "\n"; 10018 outs() << "compatibility version "; 10019 if (dl.dylib.compatibility_version == 0xffffffff) 10020 outs() << "n/a\n"; 10021 else 10022 outs() << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "." 10023 << ((dl.dylib.compatibility_version >> 8) & 0xff) << "." 10024 << (dl.dylib.compatibility_version & 0xff) << "\n"; 10025 } 10026 10027 static void PrintLinkEditDataCommand(MachO::linkedit_data_command ld, 10028 uint32_t object_size) { 10029 if (ld.cmd == MachO::LC_CODE_SIGNATURE) 10030 outs() << " cmd LC_CODE_SIGNATURE\n"; 10031 else if (ld.cmd == MachO::LC_SEGMENT_SPLIT_INFO) 10032 outs() << " cmd LC_SEGMENT_SPLIT_INFO\n"; 10033 else if (ld.cmd == MachO::LC_FUNCTION_STARTS) 10034 outs() << " cmd LC_FUNCTION_STARTS\n"; 10035 else if (ld.cmd == MachO::LC_DATA_IN_CODE) 10036 outs() << " cmd LC_DATA_IN_CODE\n"; 10037 else if (ld.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS) 10038 outs() << " cmd LC_DYLIB_CODE_SIGN_DRS\n"; 10039 else if (ld.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT) 10040 outs() << " cmd LC_LINKER_OPTIMIZATION_HINT\n"; 10041 else 10042 outs() << " cmd " << ld.cmd << " (?)\n"; 10043 outs() << " cmdsize " << ld.cmdsize; 10044 if (ld.cmdsize != sizeof(struct MachO::linkedit_data_command)) 10045 outs() << " Incorrect size\n"; 10046 else 10047 outs() << "\n"; 10048 outs() << " dataoff " << ld.dataoff; 10049 if (ld.dataoff > object_size) 10050 outs() << " (past end of file)\n"; 10051 else 10052 outs() << "\n"; 10053 outs() << " datasize " << ld.datasize; 10054 uint64_t big_size = ld.dataoff; 10055 big_size += ld.datasize; 10056 if (big_size > object_size) 10057 outs() << " (past end of file)\n"; 10058 else 10059 outs() << "\n"; 10060 } 10061 10062 static void PrintLoadCommands(const MachOObjectFile *Obj, uint32_t filetype, 10063 uint32_t cputype, bool verbose) { 10064 StringRef Buf = Obj->getData(); 10065 unsigned Index = 0; 10066 for (const auto &Command : Obj->load_commands()) { 10067 outs() << "Load command " << Index++ << "\n"; 10068 if (Command.C.cmd == MachO::LC_SEGMENT) { 10069 MachO::segment_command SLC = Obj->getSegmentLoadCommand(Command); 10070 const char *sg_segname = SLC.segname; 10071 PrintSegmentCommand(SLC.cmd, SLC.cmdsize, SLC.segname, SLC.vmaddr, 10072 SLC.vmsize, SLC.fileoff, SLC.filesize, SLC.maxprot, 10073 SLC.initprot, SLC.nsects, SLC.flags, Buf.size(), 10074 verbose); 10075 for (unsigned j = 0; j < SLC.nsects; j++) { 10076 MachO::section S = Obj->getSection(Command, j); 10077 PrintSection(S.sectname, S.segname, S.addr, S.size, S.offset, S.align, 10078 S.reloff, S.nreloc, S.flags, S.reserved1, S.reserved2, 10079 SLC.cmd, sg_segname, filetype, Buf.size(), verbose); 10080 } 10081 } else if (Command.C.cmd == MachO::LC_SEGMENT_64) { 10082 MachO::segment_command_64 SLC_64 = Obj->getSegment64LoadCommand(Command); 10083 const char *sg_segname = SLC_64.segname; 10084 PrintSegmentCommand(SLC_64.cmd, SLC_64.cmdsize, SLC_64.segname, 10085 SLC_64.vmaddr, SLC_64.vmsize, SLC_64.fileoff, 10086 SLC_64.filesize, SLC_64.maxprot, SLC_64.initprot, 10087 SLC_64.nsects, SLC_64.flags, Buf.size(), verbose); 10088 for (unsigned j = 0; j < SLC_64.nsects; j++) { 10089 MachO::section_64 S_64 = Obj->getSection64(Command, j); 10090 PrintSection(S_64.sectname, S_64.segname, S_64.addr, S_64.size, 10091 S_64.offset, S_64.align, S_64.reloff, S_64.nreloc, 10092 S_64.flags, S_64.reserved1, S_64.reserved2, SLC_64.cmd, 10093 sg_segname, filetype, Buf.size(), verbose); 10094 } 10095 } else if (Command.C.cmd == MachO::LC_SYMTAB) { 10096 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand(); 10097 PrintSymtabLoadCommand(Symtab, Obj->is64Bit(), Buf.size()); 10098 } else if (Command.C.cmd == MachO::LC_DYSYMTAB) { 10099 MachO::dysymtab_command Dysymtab = Obj->getDysymtabLoadCommand(); 10100 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand(); 10101 PrintDysymtabLoadCommand(Dysymtab, Symtab.nsyms, Buf.size(), 10102 Obj->is64Bit()); 10103 } else if (Command.C.cmd == MachO::LC_DYLD_INFO || 10104 Command.C.cmd == MachO::LC_DYLD_INFO_ONLY) { 10105 MachO::dyld_info_command DyldInfo = Obj->getDyldInfoLoadCommand(Command); 10106 PrintDyldInfoLoadCommand(DyldInfo, Buf.size()); 10107 } else if (Command.C.cmd == MachO::LC_LOAD_DYLINKER || 10108 Command.C.cmd == MachO::LC_ID_DYLINKER || 10109 Command.C.cmd == MachO::LC_DYLD_ENVIRONMENT) { 10110 MachO::dylinker_command Dyld = Obj->getDylinkerCommand(Command); 10111 PrintDyldLoadCommand(Dyld, Command.Ptr); 10112 } else if (Command.C.cmd == MachO::LC_UUID) { 10113 MachO::uuid_command Uuid = Obj->getUuidCommand(Command); 10114 PrintUuidLoadCommand(Uuid); 10115 } else if (Command.C.cmd == MachO::LC_RPATH) { 10116 MachO::rpath_command Rpath = Obj->getRpathCommand(Command); 10117 PrintRpathLoadCommand(Rpath, Command.Ptr); 10118 } else if (Command.C.cmd == MachO::LC_VERSION_MIN_MACOSX || 10119 Command.C.cmd == MachO::LC_VERSION_MIN_IPHONEOS || 10120 Command.C.cmd == MachO::LC_VERSION_MIN_TVOS || 10121 Command.C.cmd == MachO::LC_VERSION_MIN_WATCHOS) { 10122 MachO::version_min_command Vd = Obj->getVersionMinLoadCommand(Command); 10123 PrintVersionMinLoadCommand(Vd); 10124 } else if (Command.C.cmd == MachO::LC_NOTE) { 10125 MachO::note_command Nt = Obj->getNoteLoadCommand(Command); 10126 PrintNoteLoadCommand(Nt); 10127 } else if (Command.C.cmd == MachO::LC_BUILD_VERSION) { 10128 MachO::build_version_command Bv = 10129 Obj->getBuildVersionLoadCommand(Command); 10130 PrintBuildVersionLoadCommand(Obj, Bv); 10131 } else if (Command.C.cmd == MachO::LC_SOURCE_VERSION) { 10132 MachO::source_version_command Sd = Obj->getSourceVersionCommand(Command); 10133 PrintSourceVersionCommand(Sd); 10134 } else if (Command.C.cmd == MachO::LC_MAIN) { 10135 MachO::entry_point_command Ep = Obj->getEntryPointCommand(Command); 10136 PrintEntryPointCommand(Ep); 10137 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO) { 10138 MachO::encryption_info_command Ei = 10139 Obj->getEncryptionInfoCommand(Command); 10140 PrintEncryptionInfoCommand(Ei, Buf.size()); 10141 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO_64) { 10142 MachO::encryption_info_command_64 Ei = 10143 Obj->getEncryptionInfoCommand64(Command); 10144 PrintEncryptionInfoCommand64(Ei, Buf.size()); 10145 } else if (Command.C.cmd == MachO::LC_LINKER_OPTION) { 10146 MachO::linker_option_command Lo = 10147 Obj->getLinkerOptionLoadCommand(Command); 10148 PrintLinkerOptionCommand(Lo, Command.Ptr); 10149 } else if (Command.C.cmd == MachO::LC_SUB_FRAMEWORK) { 10150 MachO::sub_framework_command Sf = Obj->getSubFrameworkCommand(Command); 10151 PrintSubFrameworkCommand(Sf, Command.Ptr); 10152 } else if (Command.C.cmd == MachO::LC_SUB_UMBRELLA) { 10153 MachO::sub_umbrella_command Sf = Obj->getSubUmbrellaCommand(Command); 10154 PrintSubUmbrellaCommand(Sf, Command.Ptr); 10155 } else if (Command.C.cmd == MachO::LC_SUB_LIBRARY) { 10156 MachO::sub_library_command Sl = Obj->getSubLibraryCommand(Command); 10157 PrintSubLibraryCommand(Sl, Command.Ptr); 10158 } else if (Command.C.cmd == MachO::LC_SUB_CLIENT) { 10159 MachO::sub_client_command Sc = Obj->getSubClientCommand(Command); 10160 PrintSubClientCommand(Sc, Command.Ptr); 10161 } else if (Command.C.cmd == MachO::LC_ROUTINES) { 10162 MachO::routines_command Rc = Obj->getRoutinesCommand(Command); 10163 PrintRoutinesCommand(Rc); 10164 } else if (Command.C.cmd == MachO::LC_ROUTINES_64) { 10165 MachO::routines_command_64 Rc = Obj->getRoutinesCommand64(Command); 10166 PrintRoutinesCommand64(Rc); 10167 } else if (Command.C.cmd == MachO::LC_THREAD || 10168 Command.C.cmd == MachO::LC_UNIXTHREAD) { 10169 MachO::thread_command Tc = Obj->getThreadCommand(Command); 10170 PrintThreadCommand(Tc, Command.Ptr, Obj->isLittleEndian(), cputype); 10171 } else if (Command.C.cmd == MachO::LC_LOAD_DYLIB || 10172 Command.C.cmd == MachO::LC_ID_DYLIB || 10173 Command.C.cmd == MachO::LC_LOAD_WEAK_DYLIB || 10174 Command.C.cmd == MachO::LC_REEXPORT_DYLIB || 10175 Command.C.cmd == MachO::LC_LAZY_LOAD_DYLIB || 10176 Command.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB) { 10177 MachO::dylib_command Dl = Obj->getDylibIDLoadCommand(Command); 10178 PrintDylibCommand(Dl, Command.Ptr); 10179 } else if (Command.C.cmd == MachO::LC_CODE_SIGNATURE || 10180 Command.C.cmd == MachO::LC_SEGMENT_SPLIT_INFO || 10181 Command.C.cmd == MachO::LC_FUNCTION_STARTS || 10182 Command.C.cmd == MachO::LC_DATA_IN_CODE || 10183 Command.C.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS || 10184 Command.C.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT) { 10185 MachO::linkedit_data_command Ld = 10186 Obj->getLinkeditDataLoadCommand(Command); 10187 PrintLinkEditDataCommand(Ld, Buf.size()); 10188 } else { 10189 outs() << " cmd ?(" << format("0x%08" PRIx32, Command.C.cmd) 10190 << ")\n"; 10191 outs() << " cmdsize " << Command.C.cmdsize << "\n"; 10192 // TODO: get and print the raw bytes of the load command. 10193 } 10194 // TODO: print all the other kinds of load commands. 10195 } 10196 } 10197 10198 static void PrintMachHeader(const MachOObjectFile *Obj, bool verbose) { 10199 if (Obj->is64Bit()) { 10200 MachO::mach_header_64 H_64; 10201 H_64 = Obj->getHeader64(); 10202 PrintMachHeader(H_64.magic, H_64.cputype, H_64.cpusubtype, H_64.filetype, 10203 H_64.ncmds, H_64.sizeofcmds, H_64.flags, verbose); 10204 } else { 10205 MachO::mach_header H; 10206 H = Obj->getHeader(); 10207 PrintMachHeader(H.magic, H.cputype, H.cpusubtype, H.filetype, H.ncmds, 10208 H.sizeofcmds, H.flags, verbose); 10209 } 10210 } 10211 10212 void printMachOFileHeader(const object::ObjectFile *Obj) { 10213 const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj); 10214 PrintMachHeader(file, !NonVerbose); 10215 } 10216 10217 void printMachOLoadCommands(const object::ObjectFile *Obj) { 10218 const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj); 10219 uint32_t filetype = 0; 10220 uint32_t cputype = 0; 10221 if (file->is64Bit()) { 10222 MachO::mach_header_64 H_64; 10223 H_64 = file->getHeader64(); 10224 filetype = H_64.filetype; 10225 cputype = H_64.cputype; 10226 } else { 10227 MachO::mach_header H; 10228 H = file->getHeader(); 10229 filetype = H.filetype; 10230 cputype = H.cputype; 10231 } 10232 PrintLoadCommands(file, filetype, cputype, !NonVerbose); 10233 } 10234 10235 //===----------------------------------------------------------------------===// 10236 // export trie dumping 10237 //===----------------------------------------------------------------------===// 10238 10239 void printMachOExportsTrie(const object::MachOObjectFile *Obj) { 10240 uint64_t BaseSegmentAddress = 0; 10241 for (const auto &Command : Obj->load_commands()) { 10242 if (Command.C.cmd == MachO::LC_SEGMENT) { 10243 MachO::segment_command Seg = Obj->getSegmentLoadCommand(Command); 10244 if (Seg.fileoff == 0 && Seg.filesize != 0) { 10245 BaseSegmentAddress = Seg.vmaddr; 10246 break; 10247 } 10248 } else if (Command.C.cmd == MachO::LC_SEGMENT_64) { 10249 MachO::segment_command_64 Seg = Obj->getSegment64LoadCommand(Command); 10250 if (Seg.fileoff == 0 && Seg.filesize != 0) { 10251 BaseSegmentAddress = Seg.vmaddr; 10252 break; 10253 } 10254 } 10255 } 10256 Error Err = Error::success(); 10257 for (const object::ExportEntry &Entry : Obj->exports(Err)) { 10258 uint64_t Flags = Entry.flags(); 10259 bool ReExport = (Flags & MachO::EXPORT_SYMBOL_FLAGS_REEXPORT); 10260 bool WeakDef = (Flags & MachO::EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION); 10261 bool ThreadLocal = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) == 10262 MachO::EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL); 10263 bool Abs = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) == 10264 MachO::EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE); 10265 bool Resolver = (Flags & MachO::EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER); 10266 if (ReExport) 10267 outs() << "[re-export] "; 10268 else 10269 outs() << format("0x%08llX ", 10270 Entry.address() + BaseSegmentAddress); 10271 outs() << Entry.name(); 10272 if (WeakDef || ThreadLocal || Resolver || Abs) { 10273 bool NeedsComma = false; 10274 outs() << " ["; 10275 if (WeakDef) { 10276 outs() << "weak_def"; 10277 NeedsComma = true; 10278 } 10279 if (ThreadLocal) { 10280 if (NeedsComma) 10281 outs() << ", "; 10282 outs() << "per-thread"; 10283 NeedsComma = true; 10284 } 10285 if (Abs) { 10286 if (NeedsComma) 10287 outs() << ", "; 10288 outs() << "absolute"; 10289 NeedsComma = true; 10290 } 10291 if (Resolver) { 10292 if (NeedsComma) 10293 outs() << ", "; 10294 outs() << format("resolver=0x%08llX", Entry.other()); 10295 NeedsComma = true; 10296 } 10297 outs() << "]"; 10298 } 10299 if (ReExport) { 10300 StringRef DylibName = "unknown"; 10301 int Ordinal = Entry.other() - 1; 10302 Obj->getLibraryShortNameByIndex(Ordinal, DylibName); 10303 if (Entry.otherName().empty()) 10304 outs() << " (from " << DylibName << ")"; 10305 else 10306 outs() << " (" << Entry.otherName() << " from " << DylibName << ")"; 10307 } 10308 outs() << "\n"; 10309 } 10310 if (Err) 10311 reportError(std::move(Err), Obj->getFileName()); 10312 } 10313 10314 //===----------------------------------------------------------------------===// 10315 // rebase table dumping 10316 //===----------------------------------------------------------------------===// 10317 10318 void printMachORebaseTable(object::MachOObjectFile *Obj) { 10319 outs() << "segment section address type\n"; 10320 Error Err = Error::success(); 10321 for (const object::MachORebaseEntry &Entry : Obj->rebaseTable(Err)) { 10322 StringRef SegmentName = Entry.segmentName(); 10323 StringRef SectionName = Entry.sectionName(); 10324 uint64_t Address = Entry.address(); 10325 10326 // Table lines look like: __DATA __nl_symbol_ptr 0x0000F00C pointer 10327 outs() << format("%-8s %-18s 0x%08" PRIX64 " %s\n", 10328 SegmentName.str().c_str(), SectionName.str().c_str(), 10329 Address, Entry.typeName().str().c_str()); 10330 } 10331 if (Err) 10332 reportError(std::move(Err), Obj->getFileName()); 10333 } 10334 10335 static StringRef ordinalName(const object::MachOObjectFile *Obj, int Ordinal) { 10336 StringRef DylibName; 10337 switch (Ordinal) { 10338 case MachO::BIND_SPECIAL_DYLIB_SELF: 10339 return "this-image"; 10340 case MachO::BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE: 10341 return "main-executable"; 10342 case MachO::BIND_SPECIAL_DYLIB_FLAT_LOOKUP: 10343 return "flat-namespace"; 10344 default: 10345 if (Ordinal > 0) { 10346 std::error_code EC = 10347 Obj->getLibraryShortNameByIndex(Ordinal - 1, DylibName); 10348 if (EC) 10349 return "<<bad library ordinal>>"; 10350 return DylibName; 10351 } 10352 } 10353 return "<<unknown special ordinal>>"; 10354 } 10355 10356 //===----------------------------------------------------------------------===// 10357 // bind table dumping 10358 //===----------------------------------------------------------------------===// 10359 10360 void printMachOBindTable(object::MachOObjectFile *Obj) { 10361 // Build table of sections so names can used in final output. 10362 outs() << "segment section address type " 10363 "addend dylib symbol\n"; 10364 Error Err = Error::success(); 10365 for (const object::MachOBindEntry &Entry : Obj->bindTable(Err)) { 10366 StringRef SegmentName = Entry.segmentName(); 10367 StringRef SectionName = Entry.sectionName(); 10368 uint64_t Address = Entry.address(); 10369 10370 // Table lines look like: 10371 // __DATA __got 0x00012010 pointer 0 libSystem ___stack_chk_guard 10372 StringRef Attr; 10373 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_WEAK_IMPORT) 10374 Attr = " (weak_import)"; 10375 outs() << left_justify(SegmentName, 8) << " " 10376 << left_justify(SectionName, 18) << " " 10377 << format_hex(Address, 10, true) << " " 10378 << left_justify(Entry.typeName(), 8) << " " 10379 << format_decimal(Entry.addend(), 8) << " " 10380 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " " 10381 << Entry.symbolName() << Attr << "\n"; 10382 } 10383 if (Err) 10384 reportError(std::move(Err), Obj->getFileName()); 10385 } 10386 10387 //===----------------------------------------------------------------------===// 10388 // lazy bind table dumping 10389 //===----------------------------------------------------------------------===// 10390 10391 void printMachOLazyBindTable(object::MachOObjectFile *Obj) { 10392 outs() << "segment section address " 10393 "dylib symbol\n"; 10394 Error Err = Error::success(); 10395 for (const object::MachOBindEntry &Entry : Obj->lazyBindTable(Err)) { 10396 StringRef SegmentName = Entry.segmentName(); 10397 StringRef SectionName = Entry.sectionName(); 10398 uint64_t Address = Entry.address(); 10399 10400 // Table lines look like: 10401 // __DATA __got 0x00012010 libSystem ___stack_chk_guard 10402 outs() << left_justify(SegmentName, 8) << " " 10403 << left_justify(SectionName, 18) << " " 10404 << format_hex(Address, 10, true) << " " 10405 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " " 10406 << Entry.symbolName() << "\n"; 10407 } 10408 if (Err) 10409 reportError(std::move(Err), Obj->getFileName()); 10410 } 10411 10412 //===----------------------------------------------------------------------===// 10413 // weak bind table dumping 10414 //===----------------------------------------------------------------------===// 10415 10416 void printMachOWeakBindTable(object::MachOObjectFile *Obj) { 10417 outs() << "segment section address " 10418 "type addend symbol\n"; 10419 Error Err = Error::success(); 10420 for (const object::MachOBindEntry &Entry : Obj->weakBindTable(Err)) { 10421 // Strong symbols don't have a location to update. 10422 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION) { 10423 outs() << " strong " 10424 << Entry.symbolName() << "\n"; 10425 continue; 10426 } 10427 StringRef SegmentName = Entry.segmentName(); 10428 StringRef SectionName = Entry.sectionName(); 10429 uint64_t Address = Entry.address(); 10430 10431 // Table lines look like: 10432 // __DATA __data 0x00001000 pointer 0 _foo 10433 outs() << left_justify(SegmentName, 8) << " " 10434 << left_justify(SectionName, 18) << " " 10435 << format_hex(Address, 10, true) << " " 10436 << left_justify(Entry.typeName(), 8) << " " 10437 << format_decimal(Entry.addend(), 8) << " " << Entry.symbolName() 10438 << "\n"; 10439 } 10440 if (Err) 10441 reportError(std::move(Err), Obj->getFileName()); 10442 } 10443 10444 // get_dyld_bind_info_symbolname() is used for disassembly and passed an 10445 // address, ReferenceValue, in the Mach-O file and looks in the dyld bind 10446 // information for that address. If the address is found its binding symbol 10447 // name is returned. If not nullptr is returned. 10448 static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue, 10449 struct DisassembleInfo *info) { 10450 if (info->bindtable == nullptr) { 10451 info->bindtable = std::make_unique<SymbolAddressMap>(); 10452 Error Err = Error::success(); 10453 for (const object::MachOBindEntry &Entry : info->O->bindTable(Err)) { 10454 uint64_t Address = Entry.address(); 10455 StringRef name = Entry.symbolName(); 10456 if (!name.empty()) 10457 (*info->bindtable)[Address] = name; 10458 } 10459 if (Err) 10460 reportError(std::move(Err), info->O->getFileName()); 10461 } 10462 auto name = info->bindtable->lookup(ReferenceValue); 10463 return !name.empty() ? name.data() : nullptr; 10464 } 10465 10466 void printLazyBindTable(ObjectFile *o) { 10467 outs() << "Lazy bind table:\n"; 10468 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o)) 10469 printMachOLazyBindTable(MachO); 10470 else 10471 WithColor::error() 10472 << "This operation is only currently supported " 10473 "for Mach-O executable files.\n"; 10474 } 10475 10476 void printWeakBindTable(ObjectFile *o) { 10477 outs() << "Weak bind table:\n"; 10478 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o)) 10479 printMachOWeakBindTable(MachO); 10480 else 10481 WithColor::error() 10482 << "This operation is only currently supported " 10483 "for Mach-O executable files.\n"; 10484 } 10485 10486 void printExportsTrie(const ObjectFile *o) { 10487 outs() << "Exports trie:\n"; 10488 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o)) 10489 printMachOExportsTrie(MachO); 10490 else 10491 WithColor::error() 10492 << "This operation is only currently supported " 10493 "for Mach-O executable files.\n"; 10494 } 10495 10496 void printRebaseTable(ObjectFile *o) { 10497 outs() << "Rebase table:\n"; 10498 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o)) 10499 printMachORebaseTable(MachO); 10500 else 10501 WithColor::error() 10502 << "This operation is only currently supported " 10503 "for Mach-O executable files.\n"; 10504 } 10505 10506 void printBindTable(ObjectFile *o) { 10507 outs() << "Bind table:\n"; 10508 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o)) 10509 printMachOBindTable(MachO); 10510 else 10511 WithColor::error() 10512 << "This operation is only currently supported " 10513 "for Mach-O executable files.\n"; 10514 } 10515 } // namespace llvm 10516