Home | History | Annotate | Download | only in llvm-objdump
      1 //===-- MachODump.cpp - Object file dumping utility for llvm --------------===//
      2 //
      3 //                     The LLVM Compiler Infrastructure
      4 //
      5 // This file is distributed under the University of Illinois Open Source
      6 // License. See LICENSE.TXT for details.
      7 //
      8 //===----------------------------------------------------------------------===//
      9 //
     10 // This file implements the MachO-specific dumper for llvm-objdump.
     11 //
     12 //===----------------------------------------------------------------------===//
     13 
     14 #include "llvm-objdump.h"
     15 #include "llvm-c/Disassembler.h"
     16 #include "llvm/ADT/Optional.h"
     17 #include "llvm/ADT/STLExtras.h"
     18 #include "llvm/ADT/StringExtras.h"
     19 #include "llvm/ADT/Triple.h"
     20 #include "llvm/Config/config.h"
     21 #include "llvm/DebugInfo/DIContext.h"
     22 #include "llvm/DebugInfo/DWARF/DWARFContext.h"
     23 #include "llvm/MC/MCAsmInfo.h"
     24 #include "llvm/MC/MCContext.h"
     25 #include "llvm/MC/MCDisassembler.h"
     26 #include "llvm/MC/MCInst.h"
     27 #include "llvm/MC/MCInstPrinter.h"
     28 #include "llvm/MC/MCInstrDesc.h"
     29 #include "llvm/MC/MCInstrInfo.h"
     30 #include "llvm/MC/MCRegisterInfo.h"
     31 #include "llvm/MC/MCSubtargetInfo.h"
     32 #include "llvm/Object/MachO.h"
     33 #include "llvm/Object/MachOUniversal.h"
     34 #include "llvm/Support/Casting.h"
     35 #include "llvm/Support/CommandLine.h"
     36 #include "llvm/Support/Debug.h"
     37 #include "llvm/Support/Endian.h"
     38 #include "llvm/Support/Format.h"
     39 #include "llvm/Support/FormattedStream.h"
     40 #include "llvm/Support/GraphWriter.h"
     41 #include "llvm/Support/LEB128.h"
     42 #include "llvm/Support/MachO.h"
     43 #include "llvm/Support/MemoryBuffer.h"
     44 #include "llvm/Support/TargetRegistry.h"
     45 #include "llvm/Support/TargetSelect.h"
     46 #include "llvm/Support/raw_ostream.h"
     47 #include <algorithm>
     48 #include <cstring>
     49 #include <system_error>
     50 
     51 #if HAVE_CXXABI_H
     52 #include <cxxabi.h>
     53 #endif
     54 
     55 using namespace llvm;
     56 using namespace object;
     57 
     58 static cl::opt<bool>
     59     UseDbg("g",
     60            cl::desc("Print line information from debug info if available"));
     61 
     62 static cl::opt<std::string> DSYMFile("dsym",
     63                                      cl::desc("Use .dSYM file for debug info"));
     64 
     65 static cl::opt<bool> FullLeadingAddr("full-leading-addr",
     66                                      cl::desc("Print full leading address"));
     67 
     68 static cl::opt<bool> NoLeadingAddr("no-leading-addr",
     69                                    cl::desc("Print no leading address"));
     70 
     71 cl::opt<bool> llvm::UniversalHeaders("universal-headers",
     72                                      cl::desc("Print Mach-O universal headers "
     73                                               "(requires -macho)"));
     74 
     75 cl::opt<bool>
     76     llvm::ArchiveHeaders("archive-headers",
     77                          cl::desc("Print archive headers for Mach-O archives "
     78                                   "(requires -macho)"));
     79 
     80 cl::opt<bool>
     81     ArchiveMemberOffsets("archive-member-offsets",
     82                          cl::desc("Print the offset to each archive member for "
     83                                   "Mach-O archives (requires -macho and "
     84                                   "-archive-headers)"));
     85 
     86 cl::opt<bool>
     87     llvm::IndirectSymbols("indirect-symbols",
     88                           cl::desc("Print indirect symbol table for Mach-O "
     89                                    "objects (requires -macho)"));
     90 
     91 cl::opt<bool>
     92     llvm::DataInCode("data-in-code",
     93                      cl::desc("Print the data in code table for Mach-O objects "
     94                               "(requires -macho)"));
     95 
     96 cl::opt<bool>
     97     llvm::LinkOptHints("link-opt-hints",
     98                        cl::desc("Print the linker optimization hints for "
     99                                 "Mach-O objects (requires -macho)"));
    100 
    101 cl::opt<bool>
    102     llvm::InfoPlist("info-plist",
    103                     cl::desc("Print the info plist section as strings for "
    104                              "Mach-O objects (requires -macho)"));
    105 
    106 cl::opt<bool>
    107     llvm::DylibsUsed("dylibs-used",
    108                      cl::desc("Print the shared libraries used for linked "
    109                               "Mach-O files (requires -macho)"));
    110 
    111 cl::opt<bool>
    112     llvm::DylibId("dylib-id",
    113                   cl::desc("Print the shared library's id for the dylib Mach-O "
    114                            "file (requires -macho)"));
    115 
    116 cl::opt<bool>
    117     llvm::NonVerbose("non-verbose",
    118                      cl::desc("Print the info for Mach-O objects in "
    119                               "non-verbose or numeric form (requires -macho)"));
    120 
    121 cl::opt<bool>
    122     llvm::ObjcMetaData("objc-meta-data",
    123                        cl::desc("Print the Objective-C runtime meta data for "
    124                                 "Mach-O files (requires -macho)"));
    125 
    126 cl::opt<std::string> llvm::DisSymName(
    127     "dis-symname",
    128     cl::desc("disassemble just this symbol's instructions (requires -macho"));
    129 
    130 static cl::opt<bool> NoSymbolicOperands(
    131     "no-symbolic-operands",
    132     cl::desc("do not symbolic operands when disassembling (requires -macho)"));
    133 
    134 static cl::list<std::string>
    135     ArchFlags("arch", cl::desc("architecture(s) from a Mach-O file to dump"),
    136               cl::ZeroOrMore);
    137 
    138 bool ArchAll = false;
    139 
    140 static std::string ThumbTripleName;
    141 
    142 static const Target *GetTarget(const MachOObjectFile *MachOObj,
    143                                const char **McpuDefault,
    144                                const Target **ThumbTarget) {
    145   // Figure out the target triple.
    146   if (TripleName.empty()) {
    147     llvm::Triple TT("unknown-unknown-unknown");
    148     llvm::Triple ThumbTriple = Triple();
    149     TT = MachOObj->getArch(McpuDefault, &ThumbTriple);
    150     TripleName = TT.str();
    151     ThumbTripleName = ThumbTriple.str();
    152   }
    153 
    154   // Get the target specific parser.
    155   std::string Error;
    156   const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error);
    157   if (TheTarget && ThumbTripleName.empty())
    158     return TheTarget;
    159 
    160   *ThumbTarget = TargetRegistry::lookupTarget(ThumbTripleName, Error);
    161   if (*ThumbTarget)
    162     return TheTarget;
    163 
    164   errs() << "llvm-objdump: error: unable to get target for '";
    165   if (!TheTarget)
    166     errs() << TripleName;
    167   else
    168     errs() << ThumbTripleName;
    169   errs() << "', see --version and --triple.\n";
    170   return nullptr;
    171 }
    172 
    173 struct SymbolSorter {
    174   bool operator()(const SymbolRef &A, const SymbolRef &B) {
    175     uint64_t AAddr = (A.getType() != SymbolRef::ST_Function) ? 0 : A.getValue();
    176     uint64_t BAddr = (B.getType() != SymbolRef::ST_Function) ? 0 : B.getValue();
    177     return AAddr < BAddr;
    178   }
    179 };
    180 
    181 // Types for the storted data in code table that is built before disassembly
    182 // and the predicate function to sort them.
    183 typedef std::pair<uint64_t, DiceRef> DiceTableEntry;
    184 typedef std::vector<DiceTableEntry> DiceTable;
    185 typedef DiceTable::iterator dice_table_iterator;
    186 
    187 // This is used to search for a data in code table entry for the PC being
    188 // disassembled.  The j parameter has the PC in j.first.  A single data in code
    189 // table entry can cover many bytes for each of its Kind's.  So if the offset,
    190 // aka the i.first value, of the data in code table entry plus its Length
    191 // covers the PC being searched for this will return true.  If not it will
    192 // return false.
    193 static bool compareDiceTableEntries(const DiceTableEntry &i,
    194                                     const DiceTableEntry &j) {
    195   uint16_t Length;
    196   i.second.getLength(Length);
    197 
    198   return j.first >= i.first && j.first < i.first + Length;
    199 }
    200 
    201 static uint64_t DumpDataInCode(const uint8_t *bytes, uint64_t Length,
    202                                unsigned short Kind) {
    203   uint32_t Value, Size = 1;
    204 
    205   switch (Kind) {
    206   default:
    207   case MachO::DICE_KIND_DATA:
    208     if (Length >= 4) {
    209       if (!NoShowRawInsn)
    210         dumpBytes(makeArrayRef(bytes, 4), outs());
    211       Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
    212       outs() << "\t.long " << Value;
    213       Size = 4;
    214     } else if (Length >= 2) {
    215       if (!NoShowRawInsn)
    216         dumpBytes(makeArrayRef(bytes, 2), outs());
    217       Value = bytes[1] << 8 | bytes[0];
    218       outs() << "\t.short " << Value;
    219       Size = 2;
    220     } else {
    221       if (!NoShowRawInsn)
    222         dumpBytes(makeArrayRef(bytes, 2), outs());
    223       Value = bytes[0];
    224       outs() << "\t.byte " << Value;
    225       Size = 1;
    226     }
    227     if (Kind == MachO::DICE_KIND_DATA)
    228       outs() << "\t@ KIND_DATA\n";
    229     else
    230       outs() << "\t@ data in code kind = " << Kind << "\n";
    231     break;
    232   case MachO::DICE_KIND_JUMP_TABLE8:
    233     if (!NoShowRawInsn)
    234       dumpBytes(makeArrayRef(bytes, 1), outs());
    235     Value = bytes[0];
    236     outs() << "\t.byte " << format("%3u", Value) << "\t@ KIND_JUMP_TABLE8\n";
    237     Size = 1;
    238     break;
    239   case MachO::DICE_KIND_JUMP_TABLE16:
    240     if (!NoShowRawInsn)
    241       dumpBytes(makeArrayRef(bytes, 2), outs());
    242     Value = bytes[1] << 8 | bytes[0];
    243     outs() << "\t.short " << format("%5u", Value & 0xffff)
    244            << "\t@ KIND_JUMP_TABLE16\n";
    245     Size = 2;
    246     break;
    247   case MachO::DICE_KIND_JUMP_TABLE32:
    248   case MachO::DICE_KIND_ABS_JUMP_TABLE32:
    249     if (!NoShowRawInsn)
    250       dumpBytes(makeArrayRef(bytes, 4), outs());
    251     Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
    252     outs() << "\t.long " << Value;
    253     if (Kind == MachO::DICE_KIND_JUMP_TABLE32)
    254       outs() << "\t@ KIND_JUMP_TABLE32\n";
    255     else
    256       outs() << "\t@ KIND_ABS_JUMP_TABLE32\n";
    257     Size = 4;
    258     break;
    259   }
    260   return Size;
    261 }
    262 
    263 static void getSectionsAndSymbols(MachOObjectFile *MachOObj,
    264                                   std::vector<SectionRef> &Sections,
    265                                   std::vector<SymbolRef> &Symbols,
    266                                   SmallVectorImpl<uint64_t> &FoundFns,
    267                                   uint64_t &BaseSegmentAddress) {
    268   for (const SymbolRef &Symbol : MachOObj->symbols()) {
    269     ErrorOr<StringRef> SymName = Symbol.getName();
    270     if (std::error_code EC = SymName.getError())
    271       report_fatal_error(EC.message());
    272     if (!SymName->startswith("ltmp"))
    273       Symbols.push_back(Symbol);
    274   }
    275 
    276   for (const SectionRef &Section : MachOObj->sections()) {
    277     StringRef SectName;
    278     Section.getName(SectName);
    279     Sections.push_back(Section);
    280   }
    281 
    282   bool BaseSegmentAddressSet = false;
    283   for (const auto &Command : MachOObj->load_commands()) {
    284     if (Command.C.cmd == MachO::LC_FUNCTION_STARTS) {
    285       // We found a function starts segment, parse the addresses for later
    286       // consumption.
    287       MachO::linkedit_data_command LLC =
    288           MachOObj->getLinkeditDataLoadCommand(Command);
    289 
    290       MachOObj->ReadULEB128s(LLC.dataoff, FoundFns);
    291     } else if (Command.C.cmd == MachO::LC_SEGMENT) {
    292       MachO::segment_command SLC = MachOObj->getSegmentLoadCommand(Command);
    293       StringRef SegName = SLC.segname;
    294       if (!BaseSegmentAddressSet && SegName != "__PAGEZERO") {
    295         BaseSegmentAddressSet = true;
    296         BaseSegmentAddress = SLC.vmaddr;
    297       }
    298     }
    299   }
    300 }
    301 
    302 static void PrintIndirectSymbolTable(MachOObjectFile *O, bool verbose,
    303                                      uint32_t n, uint32_t count,
    304                                      uint32_t stride, uint64_t addr) {
    305   MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
    306   uint32_t nindirectsyms = Dysymtab.nindirectsyms;
    307   if (n > nindirectsyms)
    308     outs() << " (entries start past the end of the indirect symbol "
    309               "table) (reserved1 field greater than the table size)";
    310   else if (n + count > nindirectsyms)
    311     outs() << " (entries extends past the end of the indirect symbol "
    312               "table)";
    313   outs() << "\n";
    314   uint32_t cputype = O->getHeader().cputype;
    315   if (cputype & MachO::CPU_ARCH_ABI64)
    316     outs() << "address            index";
    317   else
    318     outs() << "address    index";
    319   if (verbose)
    320     outs() << " name\n";
    321   else
    322     outs() << "\n";
    323   for (uint32_t j = 0; j < count && n + j < nindirectsyms; j++) {
    324     if (cputype & MachO::CPU_ARCH_ABI64)
    325       outs() << format("0x%016" PRIx64, addr + j * stride) << " ";
    326     else
    327       outs() << format("0x%08" PRIx32, addr + j * stride) << " ";
    328     MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
    329     uint32_t indirect_symbol = O->getIndirectSymbolTableEntry(Dysymtab, n + j);
    330     if (indirect_symbol == MachO::INDIRECT_SYMBOL_LOCAL) {
    331       outs() << "LOCAL\n";
    332       continue;
    333     }
    334     if (indirect_symbol ==
    335         (MachO::INDIRECT_SYMBOL_LOCAL | MachO::INDIRECT_SYMBOL_ABS)) {
    336       outs() << "LOCAL ABSOLUTE\n";
    337       continue;
    338     }
    339     if (indirect_symbol == MachO::INDIRECT_SYMBOL_ABS) {
    340       outs() << "ABSOLUTE\n";
    341       continue;
    342     }
    343     outs() << format("%5u ", indirect_symbol);
    344     if (verbose) {
    345       MachO::symtab_command Symtab = O->getSymtabLoadCommand();
    346       if (indirect_symbol < Symtab.nsyms) {
    347         symbol_iterator Sym = O->getSymbolByIndex(indirect_symbol);
    348         SymbolRef Symbol = *Sym;
    349         ErrorOr<StringRef> SymName = Symbol.getName();
    350         if (std::error_code EC = SymName.getError())
    351           report_fatal_error(EC.message());
    352         outs() << *SymName;
    353       } else {
    354         outs() << "?";
    355       }
    356     }
    357     outs() << "\n";
    358   }
    359 }
    360 
    361 static void PrintIndirectSymbols(MachOObjectFile *O, bool verbose) {
    362   for (const auto &Load : O->load_commands()) {
    363     if (Load.C.cmd == MachO::LC_SEGMENT_64) {
    364       MachO::segment_command_64 Seg = O->getSegment64LoadCommand(Load);
    365       for (unsigned J = 0; J < Seg.nsects; ++J) {
    366         MachO::section_64 Sec = O->getSection64(Load, J);
    367         uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
    368         if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
    369             section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
    370             section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
    371             section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
    372             section_type == MachO::S_SYMBOL_STUBS) {
    373           uint32_t stride;
    374           if (section_type == MachO::S_SYMBOL_STUBS)
    375             stride = Sec.reserved2;
    376           else
    377             stride = 8;
    378           if (stride == 0) {
    379             outs() << "Can't print indirect symbols for (" << Sec.segname << ","
    380                    << Sec.sectname << ") "
    381                    << "(size of stubs in reserved2 field is zero)\n";
    382             continue;
    383           }
    384           uint32_t count = Sec.size / stride;
    385           outs() << "Indirect symbols for (" << Sec.segname << ","
    386                  << Sec.sectname << ") " << count << " entries";
    387           uint32_t n = Sec.reserved1;
    388           PrintIndirectSymbolTable(O, verbose, n, count, stride, Sec.addr);
    389         }
    390       }
    391     } else if (Load.C.cmd == MachO::LC_SEGMENT) {
    392       MachO::segment_command Seg = O->getSegmentLoadCommand(Load);
    393       for (unsigned J = 0; J < Seg.nsects; ++J) {
    394         MachO::section Sec = O->getSection(Load, J);
    395         uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
    396         if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
    397             section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
    398             section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
    399             section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
    400             section_type == MachO::S_SYMBOL_STUBS) {
    401           uint32_t stride;
    402           if (section_type == MachO::S_SYMBOL_STUBS)
    403             stride = Sec.reserved2;
    404           else
    405             stride = 4;
    406           if (stride == 0) {
    407             outs() << "Can't print indirect symbols for (" << Sec.segname << ","
    408                    << Sec.sectname << ") "
    409                    << "(size of stubs in reserved2 field is zero)\n";
    410             continue;
    411           }
    412           uint32_t count = Sec.size / stride;
    413           outs() << "Indirect symbols for (" << Sec.segname << ","
    414                  << Sec.sectname << ") " << count << " entries";
    415           uint32_t n = Sec.reserved1;
    416           PrintIndirectSymbolTable(O, verbose, n, count, stride, Sec.addr);
    417         }
    418       }
    419     }
    420   }
    421 }
    422 
    423 static void PrintDataInCodeTable(MachOObjectFile *O, bool verbose) {
    424   MachO::linkedit_data_command DIC = O->getDataInCodeLoadCommand();
    425   uint32_t nentries = DIC.datasize / sizeof(struct MachO::data_in_code_entry);
    426   outs() << "Data in code table (" << nentries << " entries)\n";
    427   outs() << "offset     length kind\n";
    428   for (dice_iterator DI = O->begin_dices(), DE = O->end_dices(); DI != DE;
    429        ++DI) {
    430     uint32_t Offset;
    431     DI->getOffset(Offset);
    432     outs() << format("0x%08" PRIx32, Offset) << " ";
    433     uint16_t Length;
    434     DI->getLength(Length);
    435     outs() << format("%6u", Length) << " ";
    436     uint16_t Kind;
    437     DI->getKind(Kind);
    438     if (verbose) {
    439       switch (Kind) {
    440       case MachO::DICE_KIND_DATA:
    441         outs() << "DATA";
    442         break;
    443       case MachO::DICE_KIND_JUMP_TABLE8:
    444         outs() << "JUMP_TABLE8";
    445         break;
    446       case MachO::DICE_KIND_JUMP_TABLE16:
    447         outs() << "JUMP_TABLE16";
    448         break;
    449       case MachO::DICE_KIND_JUMP_TABLE32:
    450         outs() << "JUMP_TABLE32";
    451         break;
    452       case MachO::DICE_KIND_ABS_JUMP_TABLE32:
    453         outs() << "ABS_JUMP_TABLE32";
    454         break;
    455       default:
    456         outs() << format("0x%04" PRIx32, Kind);
    457         break;
    458       }
    459     } else
    460       outs() << format("0x%04" PRIx32, Kind);
    461     outs() << "\n";
    462   }
    463 }
    464 
    465 static void PrintLinkOptHints(MachOObjectFile *O) {
    466   MachO::linkedit_data_command LohLC = O->getLinkOptHintsLoadCommand();
    467   const char *loh = O->getData().substr(LohLC.dataoff, 1).data();
    468   uint32_t nloh = LohLC.datasize;
    469   outs() << "Linker optimiztion hints (" << nloh << " total bytes)\n";
    470   for (uint32_t i = 0; i < nloh;) {
    471     unsigned n;
    472     uint64_t identifier = decodeULEB128((const uint8_t *)(loh + i), &n);
    473     i += n;
    474     outs() << "    identifier " << identifier << " ";
    475     if (i >= nloh)
    476       return;
    477     switch (identifier) {
    478     case 1:
    479       outs() << "AdrpAdrp\n";
    480       break;
    481     case 2:
    482       outs() << "AdrpLdr\n";
    483       break;
    484     case 3:
    485       outs() << "AdrpAddLdr\n";
    486       break;
    487     case 4:
    488       outs() << "AdrpLdrGotLdr\n";
    489       break;
    490     case 5:
    491       outs() << "AdrpAddStr\n";
    492       break;
    493     case 6:
    494       outs() << "AdrpLdrGotStr\n";
    495       break;
    496     case 7:
    497       outs() << "AdrpAdd\n";
    498       break;
    499     case 8:
    500       outs() << "AdrpLdrGot\n";
    501       break;
    502     default:
    503       outs() << "Unknown identifier value\n";
    504       break;
    505     }
    506     uint64_t narguments = decodeULEB128((const uint8_t *)(loh + i), &n);
    507     i += n;
    508     outs() << "    narguments " << narguments << "\n";
    509     if (i >= nloh)
    510       return;
    511 
    512     for (uint32_t j = 0; j < narguments; j++) {
    513       uint64_t value = decodeULEB128((const uint8_t *)(loh + i), &n);
    514       i += n;
    515       outs() << "\tvalue " << format("0x%" PRIx64, value) << "\n";
    516       if (i >= nloh)
    517         return;
    518     }
    519   }
    520 }
    521 
    522 static void PrintDylibs(MachOObjectFile *O, bool JustId) {
    523   unsigned Index = 0;
    524   for (const auto &Load : O->load_commands()) {
    525     if ((JustId && Load.C.cmd == MachO::LC_ID_DYLIB) ||
    526         (!JustId && (Load.C.cmd == MachO::LC_ID_DYLIB ||
    527                      Load.C.cmd == MachO::LC_LOAD_DYLIB ||
    528                      Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
    529                      Load.C.cmd == MachO::LC_REEXPORT_DYLIB ||
    530                      Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
    531                      Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB))) {
    532       MachO::dylib_command dl = O->getDylibIDLoadCommand(Load);
    533       if (dl.dylib.name < dl.cmdsize) {
    534         const char *p = (const char *)(Load.Ptr) + dl.dylib.name;
    535         if (JustId)
    536           outs() << p << "\n";
    537         else {
    538           outs() << "\t" << p;
    539           outs() << " (compatibility version "
    540                  << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
    541                  << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
    542                  << (dl.dylib.compatibility_version & 0xff) << ",";
    543           outs() << " current version "
    544                  << ((dl.dylib.current_version >> 16) & 0xffff) << "."
    545                  << ((dl.dylib.current_version >> 8) & 0xff) << "."
    546                  << (dl.dylib.current_version & 0xff) << ")\n";
    547         }
    548       } else {
    549         outs() << "\tBad offset (" << dl.dylib.name << ") for name of ";
    550         if (Load.C.cmd == MachO::LC_ID_DYLIB)
    551           outs() << "LC_ID_DYLIB ";
    552         else if (Load.C.cmd == MachO::LC_LOAD_DYLIB)
    553           outs() << "LC_LOAD_DYLIB ";
    554         else if (Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB)
    555           outs() << "LC_LOAD_WEAK_DYLIB ";
    556         else if (Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB)
    557           outs() << "LC_LAZY_LOAD_DYLIB ";
    558         else if (Load.C.cmd == MachO::LC_REEXPORT_DYLIB)
    559           outs() << "LC_REEXPORT_DYLIB ";
    560         else if (Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
    561           outs() << "LC_LOAD_UPWARD_DYLIB ";
    562         else
    563           outs() << "LC_??? ";
    564         outs() << "command " << Index++ << "\n";
    565       }
    566     }
    567   }
    568 }
    569 
    570 typedef DenseMap<uint64_t, StringRef> SymbolAddressMap;
    571 
    572 static void CreateSymbolAddressMap(MachOObjectFile *O,
    573                                    SymbolAddressMap *AddrMap) {
    574   // Create a map of symbol addresses to symbol names.
    575   for (const SymbolRef &Symbol : O->symbols()) {
    576     SymbolRef::Type ST = Symbol.getType();
    577     if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
    578         ST == SymbolRef::ST_Other) {
    579       uint64_t Address = Symbol.getValue();
    580       ErrorOr<StringRef> SymNameOrErr = Symbol.getName();
    581       if (std::error_code EC = SymNameOrErr.getError())
    582         report_fatal_error(EC.message());
    583       StringRef SymName = *SymNameOrErr;
    584       if (!SymName.startswith(".objc"))
    585         (*AddrMap)[Address] = SymName;
    586     }
    587   }
    588 }
    589 
    590 // GuessSymbolName is passed the address of what might be a symbol and a
    591 // pointer to the SymbolAddressMap.  It returns the name of a symbol
    592 // with that address or nullptr if no symbol is found with that address.
    593 static const char *GuessSymbolName(uint64_t value, SymbolAddressMap *AddrMap) {
    594   const char *SymbolName = nullptr;
    595   // A DenseMap can't lookup up some values.
    596   if (value != 0xffffffffffffffffULL && value != 0xfffffffffffffffeULL) {
    597     StringRef name = AddrMap->lookup(value);
    598     if (!name.empty())
    599       SymbolName = name.data();
    600   }
    601   return SymbolName;
    602 }
    603 
    604 static void DumpCstringChar(const char c) {
    605   char p[2];
    606   p[0] = c;
    607   p[1] = '\0';
    608   outs().write_escaped(p);
    609 }
    610 
    611 static void DumpCstringSection(MachOObjectFile *O, const char *sect,
    612                                uint32_t sect_size, uint64_t sect_addr,
    613                                bool print_addresses) {
    614   for (uint32_t i = 0; i < sect_size; i++) {
    615     if (print_addresses) {
    616       if (O->is64Bit())
    617         outs() << format("%016" PRIx64, sect_addr + i) << "  ";
    618       else
    619         outs() << format("%08" PRIx64, sect_addr + i) << "  ";
    620     }
    621     for (; i < sect_size && sect[i] != '\0'; i++)
    622       DumpCstringChar(sect[i]);
    623     if (i < sect_size && sect[i] == '\0')
    624       outs() << "\n";
    625   }
    626 }
    627 
    628 static void DumpLiteral4(uint32_t l, float f) {
    629   outs() << format("0x%08" PRIx32, l);
    630   if ((l & 0x7f800000) != 0x7f800000)
    631     outs() << format(" (%.16e)\n", f);
    632   else {
    633     if (l == 0x7f800000)
    634       outs() << " (+Infinity)\n";
    635     else if (l == 0xff800000)
    636       outs() << " (-Infinity)\n";
    637     else if ((l & 0x00400000) == 0x00400000)
    638       outs() << " (non-signaling Not-a-Number)\n";
    639     else
    640       outs() << " (signaling Not-a-Number)\n";
    641   }
    642 }
    643 
    644 static void DumpLiteral4Section(MachOObjectFile *O, const char *sect,
    645                                 uint32_t sect_size, uint64_t sect_addr,
    646                                 bool print_addresses) {
    647   for (uint32_t i = 0; i < sect_size; i += sizeof(float)) {
    648     if (print_addresses) {
    649       if (O->is64Bit())
    650         outs() << format("%016" PRIx64, sect_addr + i) << "  ";
    651       else
    652         outs() << format("%08" PRIx64, sect_addr + i) << "  ";
    653     }
    654     float f;
    655     memcpy(&f, sect + i, sizeof(float));
    656     if (O->isLittleEndian() != sys::IsLittleEndianHost)
    657       sys::swapByteOrder(f);
    658     uint32_t l;
    659     memcpy(&l, sect + i, sizeof(uint32_t));
    660     if (O->isLittleEndian() != sys::IsLittleEndianHost)
    661       sys::swapByteOrder(l);
    662     DumpLiteral4(l, f);
    663   }
    664 }
    665 
    666 static void DumpLiteral8(MachOObjectFile *O, uint32_t l0, uint32_t l1,
    667                          double d) {
    668   outs() << format("0x%08" PRIx32, l0) << " " << format("0x%08" PRIx32, l1);
    669   uint32_t Hi, Lo;
    670   Hi = (O->isLittleEndian()) ? l1 : l0;
    671   Lo = (O->isLittleEndian()) ? l0 : l1;
    672 
    673   // Hi is the high word, so this is equivalent to if(isfinite(d))
    674   if ((Hi & 0x7ff00000) != 0x7ff00000)
    675     outs() << format(" (%.16e)\n", d);
    676   else {
    677     if (Hi == 0x7ff00000 && Lo == 0)
    678       outs() << " (+Infinity)\n";
    679     else if (Hi == 0xfff00000 && Lo == 0)
    680       outs() << " (-Infinity)\n";
    681     else if ((Hi & 0x00080000) == 0x00080000)
    682       outs() << " (non-signaling Not-a-Number)\n";
    683     else
    684       outs() << " (signaling Not-a-Number)\n";
    685   }
    686 }
    687 
    688 static void DumpLiteral8Section(MachOObjectFile *O, const char *sect,
    689                                 uint32_t sect_size, uint64_t sect_addr,
    690                                 bool print_addresses) {
    691   for (uint32_t i = 0; i < sect_size; i += sizeof(double)) {
    692     if (print_addresses) {
    693       if (O->is64Bit())
    694         outs() << format("%016" PRIx64, sect_addr + i) << "  ";
    695       else
    696         outs() << format("%08" PRIx64, sect_addr + i) << "  ";
    697     }
    698     double d;
    699     memcpy(&d, sect + i, sizeof(double));
    700     if (O->isLittleEndian() != sys::IsLittleEndianHost)
    701       sys::swapByteOrder(d);
    702     uint32_t l0, l1;
    703     memcpy(&l0, sect + i, sizeof(uint32_t));
    704     memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t));
    705     if (O->isLittleEndian() != sys::IsLittleEndianHost) {
    706       sys::swapByteOrder(l0);
    707       sys::swapByteOrder(l1);
    708     }
    709     DumpLiteral8(O, l0, l1, d);
    710   }
    711 }
    712 
    713 static void DumpLiteral16(uint32_t l0, uint32_t l1, uint32_t l2, uint32_t l3) {
    714   outs() << format("0x%08" PRIx32, l0) << " ";
    715   outs() << format("0x%08" PRIx32, l1) << " ";
    716   outs() << format("0x%08" PRIx32, l2) << " ";
    717   outs() << format("0x%08" PRIx32, l3) << "\n";
    718 }
    719 
    720 static void DumpLiteral16Section(MachOObjectFile *O, const char *sect,
    721                                  uint32_t sect_size, uint64_t sect_addr,
    722                                  bool print_addresses) {
    723   for (uint32_t i = 0; i < sect_size; i += 16) {
    724     if (print_addresses) {
    725       if (O->is64Bit())
    726         outs() << format("%016" PRIx64, sect_addr + i) << "  ";
    727       else
    728         outs() << format("%08" PRIx64, sect_addr + i) << "  ";
    729     }
    730     uint32_t l0, l1, l2, l3;
    731     memcpy(&l0, sect + i, sizeof(uint32_t));
    732     memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t));
    733     memcpy(&l2, sect + i + 2 * sizeof(uint32_t), sizeof(uint32_t));
    734     memcpy(&l3, sect + i + 3 * sizeof(uint32_t), sizeof(uint32_t));
    735     if (O->isLittleEndian() != sys::IsLittleEndianHost) {
    736       sys::swapByteOrder(l0);
    737       sys::swapByteOrder(l1);
    738       sys::swapByteOrder(l2);
    739       sys::swapByteOrder(l3);
    740     }
    741     DumpLiteral16(l0, l1, l2, l3);
    742   }
    743 }
    744 
    745 static void DumpLiteralPointerSection(MachOObjectFile *O,
    746                                       const SectionRef &Section,
    747                                       const char *sect, uint32_t sect_size,
    748                                       uint64_t sect_addr,
    749                                       bool print_addresses) {
    750   // Collect the literal sections in this Mach-O file.
    751   std::vector<SectionRef> LiteralSections;
    752   for (const SectionRef &Section : O->sections()) {
    753     DataRefImpl Ref = Section.getRawDataRefImpl();
    754     uint32_t section_type;
    755     if (O->is64Bit()) {
    756       const MachO::section_64 Sec = O->getSection64(Ref);
    757       section_type = Sec.flags & MachO::SECTION_TYPE;
    758     } else {
    759       const MachO::section Sec = O->getSection(Ref);
    760       section_type = Sec.flags & MachO::SECTION_TYPE;
    761     }
    762     if (section_type == MachO::S_CSTRING_LITERALS ||
    763         section_type == MachO::S_4BYTE_LITERALS ||
    764         section_type == MachO::S_8BYTE_LITERALS ||
    765         section_type == MachO::S_16BYTE_LITERALS)
    766       LiteralSections.push_back(Section);
    767   }
    768 
    769   // Set the size of the literal pointer.
    770   uint32_t lp_size = O->is64Bit() ? 8 : 4;
    771 
    772   // Collect the external relocation symbols for the literal pointers.
    773   std::vector<std::pair<uint64_t, SymbolRef>> Relocs;
    774   for (const RelocationRef &Reloc : Section.relocations()) {
    775     DataRefImpl Rel;
    776     MachO::any_relocation_info RE;
    777     bool isExtern = false;
    778     Rel = Reloc.getRawDataRefImpl();
    779     RE = O->getRelocation(Rel);
    780     isExtern = O->getPlainRelocationExternal(RE);
    781     if (isExtern) {
    782       uint64_t RelocOffset = Reloc.getOffset();
    783       symbol_iterator RelocSym = Reloc.getSymbol();
    784       Relocs.push_back(std::make_pair(RelocOffset, *RelocSym));
    785     }
    786   }
    787   array_pod_sort(Relocs.begin(), Relocs.end());
    788 
    789   // Dump each literal pointer.
    790   for (uint32_t i = 0; i < sect_size; i += lp_size) {
    791     if (print_addresses) {
    792       if (O->is64Bit())
    793         outs() << format("%016" PRIx64, sect_addr + i) << "  ";
    794       else
    795         outs() << format("%08" PRIx64, sect_addr + i) << "  ";
    796     }
    797     uint64_t lp;
    798     if (O->is64Bit()) {
    799       memcpy(&lp, sect + i, sizeof(uint64_t));
    800       if (O->isLittleEndian() != sys::IsLittleEndianHost)
    801         sys::swapByteOrder(lp);
    802     } else {
    803       uint32_t li;
    804       memcpy(&li, sect + i, sizeof(uint32_t));
    805       if (O->isLittleEndian() != sys::IsLittleEndianHost)
    806         sys::swapByteOrder(li);
    807       lp = li;
    808     }
    809 
    810     // First look for an external relocation entry for this literal pointer.
    811     auto Reloc = std::find_if(
    812         Relocs.begin(), Relocs.end(),
    813         [&](const std::pair<uint64_t, SymbolRef> &P) { return P.first == i; });
    814     if (Reloc != Relocs.end()) {
    815       symbol_iterator RelocSym = Reloc->second;
    816       ErrorOr<StringRef> SymName = RelocSym->getName();
    817       if (std::error_code EC = SymName.getError())
    818         report_fatal_error(EC.message());
    819       outs() << "external relocation entry for symbol:" << *SymName << "\n";
    820       continue;
    821     }
    822 
    823     // For local references see what the section the literal pointer points to.
    824     auto Sect = std::find_if(LiteralSections.begin(), LiteralSections.end(),
    825                              [&](const SectionRef &R) {
    826                                return lp >= R.getAddress() &&
    827                                       lp < R.getAddress() + R.getSize();
    828                              });
    829     if (Sect == LiteralSections.end()) {
    830       outs() << format("0x%" PRIx64, lp) << " (not in a literal section)\n";
    831       continue;
    832     }
    833 
    834     uint64_t SectAddress = Sect->getAddress();
    835     uint64_t SectSize = Sect->getSize();
    836 
    837     StringRef SectName;
    838     Sect->getName(SectName);
    839     DataRefImpl Ref = Sect->getRawDataRefImpl();
    840     StringRef SegmentName = O->getSectionFinalSegmentName(Ref);
    841     outs() << SegmentName << ":" << SectName << ":";
    842 
    843     uint32_t section_type;
    844     if (O->is64Bit()) {
    845       const MachO::section_64 Sec = O->getSection64(Ref);
    846       section_type = Sec.flags & MachO::SECTION_TYPE;
    847     } else {
    848       const MachO::section Sec = O->getSection(Ref);
    849       section_type = Sec.flags & MachO::SECTION_TYPE;
    850     }
    851 
    852     StringRef BytesStr;
    853     Sect->getContents(BytesStr);
    854     const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
    855 
    856     switch (section_type) {
    857     case MachO::S_CSTRING_LITERALS:
    858       for (uint64_t i = lp - SectAddress; i < SectSize && Contents[i] != '\0';
    859            i++) {
    860         DumpCstringChar(Contents[i]);
    861       }
    862       outs() << "\n";
    863       break;
    864     case MachO::S_4BYTE_LITERALS:
    865       float f;
    866       memcpy(&f, Contents + (lp - SectAddress), sizeof(float));
    867       uint32_t l;
    868       memcpy(&l, Contents + (lp - SectAddress), sizeof(uint32_t));
    869       if (O->isLittleEndian() != sys::IsLittleEndianHost) {
    870         sys::swapByteOrder(f);
    871         sys::swapByteOrder(l);
    872       }
    873       DumpLiteral4(l, f);
    874       break;
    875     case MachO::S_8BYTE_LITERALS: {
    876       double d;
    877       memcpy(&d, Contents + (lp - SectAddress), sizeof(double));
    878       uint32_t l0, l1;
    879       memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t));
    880       memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t),
    881              sizeof(uint32_t));
    882       if (O->isLittleEndian() != sys::IsLittleEndianHost) {
    883         sys::swapByteOrder(f);
    884         sys::swapByteOrder(l0);
    885         sys::swapByteOrder(l1);
    886       }
    887       DumpLiteral8(O, l0, l1, d);
    888       break;
    889     }
    890     case MachO::S_16BYTE_LITERALS: {
    891       uint32_t l0, l1, l2, l3;
    892       memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t));
    893       memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t),
    894              sizeof(uint32_t));
    895       memcpy(&l2, Contents + (lp - SectAddress) + 2 * sizeof(uint32_t),
    896              sizeof(uint32_t));
    897       memcpy(&l3, Contents + (lp - SectAddress) + 3 * sizeof(uint32_t),
    898              sizeof(uint32_t));
    899       if (O->isLittleEndian() != sys::IsLittleEndianHost) {
    900         sys::swapByteOrder(l0);
    901         sys::swapByteOrder(l1);
    902         sys::swapByteOrder(l2);
    903         sys::swapByteOrder(l3);
    904       }
    905       DumpLiteral16(l0, l1, l2, l3);
    906       break;
    907     }
    908     }
    909   }
    910 }
    911 
    912 static void DumpInitTermPointerSection(MachOObjectFile *O, const char *sect,
    913                                        uint32_t sect_size, uint64_t sect_addr,
    914                                        SymbolAddressMap *AddrMap,
    915                                        bool verbose) {
    916   uint32_t stride;
    917   stride = (O->is64Bit()) ? sizeof(uint64_t) : sizeof(uint32_t);
    918   for (uint32_t i = 0; i < sect_size; i += stride) {
    919     const char *SymbolName = nullptr;
    920     if (O->is64Bit()) {
    921       outs() << format("0x%016" PRIx64, sect_addr + i * stride) << " ";
    922       uint64_t pointer_value;
    923       memcpy(&pointer_value, sect + i, stride);
    924       if (O->isLittleEndian() != sys::IsLittleEndianHost)
    925         sys::swapByteOrder(pointer_value);
    926       outs() << format("0x%016" PRIx64, pointer_value);
    927       if (verbose)
    928         SymbolName = GuessSymbolName(pointer_value, AddrMap);
    929     } else {
    930       outs() << format("0x%08" PRIx64, sect_addr + i * stride) << " ";
    931       uint32_t pointer_value;
    932       memcpy(&pointer_value, sect + i, stride);
    933       if (O->isLittleEndian() != sys::IsLittleEndianHost)
    934         sys::swapByteOrder(pointer_value);
    935       outs() << format("0x%08" PRIx32, pointer_value);
    936       if (verbose)
    937         SymbolName = GuessSymbolName(pointer_value, AddrMap);
    938     }
    939     if (SymbolName)
    940       outs() << " " << SymbolName;
    941     outs() << "\n";
    942   }
    943 }
    944 
    945 static void DumpRawSectionContents(MachOObjectFile *O, const char *sect,
    946                                    uint32_t size, uint64_t addr) {
    947   uint32_t cputype = O->getHeader().cputype;
    948   if (cputype == MachO::CPU_TYPE_I386 || cputype == MachO::CPU_TYPE_X86_64) {
    949     uint32_t j;
    950     for (uint32_t i = 0; i < size; i += j, addr += j) {
    951       if (O->is64Bit())
    952         outs() << format("%016" PRIx64, addr) << "\t";
    953       else
    954         outs() << format("%08" PRIx64, addr) << "\t";
    955       for (j = 0; j < 16 && i + j < size; j++) {
    956         uint8_t byte_word = *(sect + i + j);
    957         outs() << format("%02" PRIx32, (uint32_t)byte_word) << " ";
    958       }
    959       outs() << "\n";
    960     }
    961   } else {
    962     uint32_t j;
    963     for (uint32_t i = 0; i < size; i += j, addr += j) {
    964       if (O->is64Bit())
    965         outs() << format("%016" PRIx64, addr) << "\t";
    966       else
    967         outs() << format("%08" PRIx64, sect) << "\t";
    968       for (j = 0; j < 4 * sizeof(int32_t) && i + j < size;
    969            j += sizeof(int32_t)) {
    970         if (i + j + sizeof(int32_t) < size) {
    971           uint32_t long_word;
    972           memcpy(&long_word, sect + i + j, sizeof(int32_t));
    973           if (O->isLittleEndian() != sys::IsLittleEndianHost)
    974             sys::swapByteOrder(long_word);
    975           outs() << format("%08" PRIx32, long_word) << " ";
    976         } else {
    977           for (uint32_t k = 0; i + j + k < size; k++) {
    978             uint8_t byte_word = *(sect + i + j);
    979             outs() << format("%02" PRIx32, (uint32_t)byte_word) << " ";
    980           }
    981         }
    982       }
    983       outs() << "\n";
    984     }
    985   }
    986 }
    987 
    988 static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
    989                              StringRef DisSegName, StringRef DisSectName);
    990 static void DumpProtocolSection(MachOObjectFile *O, const char *sect,
    991                                 uint32_t size, uint32_t addr);
    992 
    993 static void DumpSectionContents(StringRef Filename, MachOObjectFile *O,
    994                                 bool verbose) {
    995   SymbolAddressMap AddrMap;
    996   if (verbose)
    997     CreateSymbolAddressMap(O, &AddrMap);
    998 
    999   for (unsigned i = 0; i < FilterSections.size(); ++i) {
   1000     StringRef DumpSection = FilterSections[i];
   1001     std::pair<StringRef, StringRef> DumpSegSectName;
   1002     DumpSegSectName = DumpSection.split(',');
   1003     StringRef DumpSegName, DumpSectName;
   1004     if (DumpSegSectName.second.size()) {
   1005       DumpSegName = DumpSegSectName.first;
   1006       DumpSectName = DumpSegSectName.second;
   1007     } else {
   1008       DumpSegName = "";
   1009       DumpSectName = DumpSegSectName.first;
   1010     }
   1011     for (const SectionRef &Section : O->sections()) {
   1012       StringRef SectName;
   1013       Section.getName(SectName);
   1014       DataRefImpl Ref = Section.getRawDataRefImpl();
   1015       StringRef SegName = O->getSectionFinalSegmentName(Ref);
   1016       if ((DumpSegName.empty() || SegName == DumpSegName) &&
   1017           (SectName == DumpSectName)) {
   1018 
   1019         uint32_t section_flags;
   1020         if (O->is64Bit()) {
   1021           const MachO::section_64 Sec = O->getSection64(Ref);
   1022           section_flags = Sec.flags;
   1023 
   1024         } else {
   1025           const MachO::section Sec = O->getSection(Ref);
   1026           section_flags = Sec.flags;
   1027         }
   1028         uint32_t section_type = section_flags & MachO::SECTION_TYPE;
   1029 
   1030         StringRef BytesStr;
   1031         Section.getContents(BytesStr);
   1032         const char *sect = reinterpret_cast<const char *>(BytesStr.data());
   1033         uint32_t sect_size = BytesStr.size();
   1034         uint64_t sect_addr = Section.getAddress();
   1035 
   1036         outs() << "Contents of (" << SegName << "," << SectName
   1037                << ") section\n";
   1038 
   1039         if (verbose) {
   1040           if ((section_flags & MachO::S_ATTR_PURE_INSTRUCTIONS) ||
   1041               (section_flags & MachO::S_ATTR_SOME_INSTRUCTIONS)) {
   1042             DisassembleMachO(Filename, O, SegName, SectName);
   1043             continue;
   1044           }
   1045           if (SegName == "__TEXT" && SectName == "__info_plist") {
   1046             outs() << sect;
   1047             continue;
   1048           }
   1049           if (SegName == "__OBJC" && SectName == "__protocol") {
   1050             DumpProtocolSection(O, sect, sect_size, sect_addr);
   1051             continue;
   1052           }
   1053           switch (section_type) {
   1054           case MachO::S_REGULAR:
   1055             DumpRawSectionContents(O, sect, sect_size, sect_addr);
   1056             break;
   1057           case MachO::S_ZEROFILL:
   1058             outs() << "zerofill section and has no contents in the file\n";
   1059             break;
   1060           case MachO::S_CSTRING_LITERALS:
   1061             DumpCstringSection(O, sect, sect_size, sect_addr, !NoLeadingAddr);
   1062             break;
   1063           case MachO::S_4BYTE_LITERALS:
   1064             DumpLiteral4Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
   1065             break;
   1066           case MachO::S_8BYTE_LITERALS:
   1067             DumpLiteral8Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
   1068             break;
   1069           case MachO::S_16BYTE_LITERALS:
   1070             DumpLiteral16Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
   1071             break;
   1072           case MachO::S_LITERAL_POINTERS:
   1073             DumpLiteralPointerSection(O, Section, sect, sect_size, sect_addr,
   1074                                       !NoLeadingAddr);
   1075             break;
   1076           case MachO::S_MOD_INIT_FUNC_POINTERS:
   1077           case MachO::S_MOD_TERM_FUNC_POINTERS:
   1078             DumpInitTermPointerSection(O, sect, sect_size, sect_addr, &AddrMap,
   1079                                        verbose);
   1080             break;
   1081           default:
   1082             outs() << "Unknown section type ("
   1083                    << format("0x%08" PRIx32, section_type) << ")\n";
   1084             DumpRawSectionContents(O, sect, sect_size, sect_addr);
   1085             break;
   1086           }
   1087         } else {
   1088           if (section_type == MachO::S_ZEROFILL)
   1089             outs() << "zerofill section and has no contents in the file\n";
   1090           else
   1091             DumpRawSectionContents(O, sect, sect_size, sect_addr);
   1092         }
   1093       }
   1094     }
   1095   }
   1096 }
   1097 
   1098 static void DumpInfoPlistSectionContents(StringRef Filename,
   1099                                          MachOObjectFile *O) {
   1100   for (const SectionRef &Section : O->sections()) {
   1101     StringRef SectName;
   1102     Section.getName(SectName);
   1103     DataRefImpl Ref = Section.getRawDataRefImpl();
   1104     StringRef SegName = O->getSectionFinalSegmentName(Ref);
   1105     if (SegName == "__TEXT" && SectName == "__info_plist") {
   1106       outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
   1107       StringRef BytesStr;
   1108       Section.getContents(BytesStr);
   1109       const char *sect = reinterpret_cast<const char *>(BytesStr.data());
   1110       outs() << sect;
   1111       return;
   1112     }
   1113   }
   1114 }
   1115 
   1116 // checkMachOAndArchFlags() checks to see if the ObjectFile is a Mach-O file
   1117 // and if it is and there is a list of architecture flags is specified then
   1118 // check to make sure this Mach-O file is one of those architectures or all
   1119 // architectures were specified.  If not then an error is generated and this
   1120 // routine returns false.  Else it returns true.
   1121 static bool checkMachOAndArchFlags(ObjectFile *O, StringRef Filename) {
   1122   if (isa<MachOObjectFile>(O) && !ArchAll && ArchFlags.size() != 0) {
   1123     MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(O);
   1124     bool ArchFound = false;
   1125     MachO::mach_header H;
   1126     MachO::mach_header_64 H_64;
   1127     Triple T;
   1128     if (MachO->is64Bit()) {
   1129       H_64 = MachO->MachOObjectFile::getHeader64();
   1130       T = MachOObjectFile::getArch(H_64.cputype, H_64.cpusubtype);
   1131     } else {
   1132       H = MachO->MachOObjectFile::getHeader();
   1133       T = MachOObjectFile::getArch(H.cputype, H.cpusubtype);
   1134     }
   1135     unsigned i;
   1136     for (i = 0; i < ArchFlags.size(); ++i) {
   1137       if (ArchFlags[i] == T.getArchName())
   1138         ArchFound = true;
   1139       break;
   1140     }
   1141     if (!ArchFound) {
   1142       errs() << "llvm-objdump: file: " + Filename + " does not contain "
   1143              << "architecture: " + ArchFlags[i] + "\n";
   1144       return false;
   1145     }
   1146   }
   1147   return true;
   1148 }
   1149 
   1150 static void printObjcMetaData(MachOObjectFile *O, bool verbose);
   1151 
   1152 // ProcessMachO() is passed a single opened Mach-O file, which may be an
   1153 // archive member and or in a slice of a universal file.  It prints the
   1154 // the file name and header info and then processes it according to the
   1155 // command line options.
   1156 static void ProcessMachO(StringRef Filename, MachOObjectFile *MachOOF,
   1157                          StringRef ArchiveMemberName = StringRef(),
   1158                          StringRef ArchitectureName = StringRef()) {
   1159   // If we are doing some processing here on the Mach-O file print the header
   1160   // info.  And don't print it otherwise like in the case of printing the
   1161   // UniversalHeaders or ArchiveHeaders.
   1162   if (Disassemble || PrivateHeaders || ExportsTrie || Rebase || Bind ||
   1163       LazyBind || WeakBind || IndirectSymbols || DataInCode || LinkOptHints ||
   1164       DylibsUsed || DylibId || ObjcMetaData || (FilterSections.size() != 0)) {
   1165     outs() << Filename;
   1166     if (!ArchiveMemberName.empty())
   1167       outs() << '(' << ArchiveMemberName << ')';
   1168     if (!ArchitectureName.empty())
   1169       outs() << " (architecture " << ArchitectureName << ")";
   1170     outs() << ":\n";
   1171   }
   1172 
   1173   if (Disassemble)
   1174     DisassembleMachO(Filename, MachOOF, "__TEXT", "__text");
   1175   if (IndirectSymbols)
   1176     PrintIndirectSymbols(MachOOF, !NonVerbose);
   1177   if (DataInCode)
   1178     PrintDataInCodeTable(MachOOF, !NonVerbose);
   1179   if (LinkOptHints)
   1180     PrintLinkOptHints(MachOOF);
   1181   if (Relocations)
   1182     PrintRelocations(MachOOF);
   1183   if (SectionHeaders)
   1184     PrintSectionHeaders(MachOOF);
   1185   if (SectionContents)
   1186     PrintSectionContents(MachOOF);
   1187   if (FilterSections.size() != 0)
   1188     DumpSectionContents(Filename, MachOOF, !NonVerbose);
   1189   if (InfoPlist)
   1190     DumpInfoPlistSectionContents(Filename, MachOOF);
   1191   if (DylibsUsed)
   1192     PrintDylibs(MachOOF, false);
   1193   if (DylibId)
   1194     PrintDylibs(MachOOF, true);
   1195   if (SymbolTable)
   1196     PrintSymbolTable(MachOOF);
   1197   if (UnwindInfo)
   1198     printMachOUnwindInfo(MachOOF);
   1199   if (PrivateHeaders)
   1200     printMachOFileHeader(MachOOF);
   1201   if (ObjcMetaData)
   1202     printObjcMetaData(MachOOF, !NonVerbose);
   1203   if (ExportsTrie)
   1204     printExportsTrie(MachOOF);
   1205   if (Rebase)
   1206     printRebaseTable(MachOOF);
   1207   if (Bind)
   1208     printBindTable(MachOOF);
   1209   if (LazyBind)
   1210     printLazyBindTable(MachOOF);
   1211   if (WeakBind)
   1212     printWeakBindTable(MachOOF);
   1213 }
   1214 
   1215 // printUnknownCPUType() helps print_fat_headers for unknown CPU's.
   1216 static void printUnknownCPUType(uint32_t cputype, uint32_t cpusubtype) {
   1217   outs() << "    cputype (" << cputype << ")\n";
   1218   outs() << "    cpusubtype (" << cpusubtype << ")\n";
   1219 }
   1220 
   1221 // printCPUType() helps print_fat_headers by printing the cputype and
   1222 // pusubtype (symbolically for the one's it knows about).
   1223 static void printCPUType(uint32_t cputype, uint32_t cpusubtype) {
   1224   switch (cputype) {
   1225   case MachO::CPU_TYPE_I386:
   1226     switch (cpusubtype) {
   1227     case MachO::CPU_SUBTYPE_I386_ALL:
   1228       outs() << "    cputype CPU_TYPE_I386\n";
   1229       outs() << "    cpusubtype CPU_SUBTYPE_I386_ALL\n";
   1230       break;
   1231     default:
   1232       printUnknownCPUType(cputype, cpusubtype);
   1233       break;
   1234     }
   1235     break;
   1236   case MachO::CPU_TYPE_X86_64:
   1237     switch (cpusubtype) {
   1238     case MachO::CPU_SUBTYPE_X86_64_ALL:
   1239       outs() << "    cputype CPU_TYPE_X86_64\n";
   1240       outs() << "    cpusubtype CPU_SUBTYPE_X86_64_ALL\n";
   1241       break;
   1242     case MachO::CPU_SUBTYPE_X86_64_H:
   1243       outs() << "    cputype CPU_TYPE_X86_64\n";
   1244       outs() << "    cpusubtype CPU_SUBTYPE_X86_64_H\n";
   1245       break;
   1246     default:
   1247       printUnknownCPUType(cputype, cpusubtype);
   1248       break;
   1249     }
   1250     break;
   1251   case MachO::CPU_TYPE_ARM:
   1252     switch (cpusubtype) {
   1253     case MachO::CPU_SUBTYPE_ARM_ALL:
   1254       outs() << "    cputype CPU_TYPE_ARM\n";
   1255       outs() << "    cpusubtype CPU_SUBTYPE_ARM_ALL\n";
   1256       break;
   1257     case MachO::CPU_SUBTYPE_ARM_V4T:
   1258       outs() << "    cputype CPU_TYPE_ARM\n";
   1259       outs() << "    cpusubtype CPU_SUBTYPE_ARM_V4T\n";
   1260       break;
   1261     case MachO::CPU_SUBTYPE_ARM_V5TEJ:
   1262       outs() << "    cputype CPU_TYPE_ARM\n";
   1263       outs() << "    cpusubtype CPU_SUBTYPE_ARM_V5TEJ\n";
   1264       break;
   1265     case MachO::CPU_SUBTYPE_ARM_XSCALE:
   1266       outs() << "    cputype CPU_TYPE_ARM\n";
   1267       outs() << "    cpusubtype CPU_SUBTYPE_ARM_XSCALE\n";
   1268       break;
   1269     case MachO::CPU_SUBTYPE_ARM_V6:
   1270       outs() << "    cputype CPU_TYPE_ARM\n";
   1271       outs() << "    cpusubtype CPU_SUBTYPE_ARM_V6\n";
   1272       break;
   1273     case MachO::CPU_SUBTYPE_ARM_V6M:
   1274       outs() << "    cputype CPU_TYPE_ARM\n";
   1275       outs() << "    cpusubtype CPU_SUBTYPE_ARM_V6M\n";
   1276       break;
   1277     case MachO::CPU_SUBTYPE_ARM_V7:
   1278       outs() << "    cputype CPU_TYPE_ARM\n";
   1279       outs() << "    cpusubtype CPU_SUBTYPE_ARM_V7\n";
   1280       break;
   1281     case MachO::CPU_SUBTYPE_ARM_V7EM:
   1282       outs() << "    cputype CPU_TYPE_ARM\n";
   1283       outs() << "    cpusubtype CPU_SUBTYPE_ARM_V7EM\n";
   1284       break;
   1285     case MachO::CPU_SUBTYPE_ARM_V7K:
   1286       outs() << "    cputype CPU_TYPE_ARM\n";
   1287       outs() << "    cpusubtype CPU_SUBTYPE_ARM_V7K\n";
   1288       break;
   1289     case MachO::CPU_SUBTYPE_ARM_V7M:
   1290       outs() << "    cputype CPU_TYPE_ARM\n";
   1291       outs() << "    cpusubtype CPU_SUBTYPE_ARM_V7M\n";
   1292       break;
   1293     case MachO::CPU_SUBTYPE_ARM_V7S:
   1294       outs() << "    cputype CPU_TYPE_ARM\n";
   1295       outs() << "    cpusubtype CPU_SUBTYPE_ARM_V7S\n";
   1296       break;
   1297     default:
   1298       printUnknownCPUType(cputype, cpusubtype);
   1299       break;
   1300     }
   1301     break;
   1302   case MachO::CPU_TYPE_ARM64:
   1303     switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
   1304     case MachO::CPU_SUBTYPE_ARM64_ALL:
   1305       outs() << "    cputype CPU_TYPE_ARM64\n";
   1306       outs() << "    cpusubtype CPU_SUBTYPE_ARM64_ALL\n";
   1307       break;
   1308     default:
   1309       printUnknownCPUType(cputype, cpusubtype);
   1310       break;
   1311     }
   1312     break;
   1313   default:
   1314     printUnknownCPUType(cputype, cpusubtype);
   1315     break;
   1316   }
   1317 }
   1318 
   1319 static void printMachOUniversalHeaders(const object::MachOUniversalBinary *UB,
   1320                                        bool verbose) {
   1321   outs() << "Fat headers\n";
   1322   if (verbose)
   1323     outs() << "fat_magic FAT_MAGIC\n";
   1324   else
   1325     outs() << "fat_magic " << format("0x%" PRIx32, MachO::FAT_MAGIC) << "\n";
   1326 
   1327   uint32_t nfat_arch = UB->getNumberOfObjects();
   1328   StringRef Buf = UB->getData();
   1329   uint64_t size = Buf.size();
   1330   uint64_t big_size = sizeof(struct MachO::fat_header) +
   1331                       nfat_arch * sizeof(struct MachO::fat_arch);
   1332   outs() << "nfat_arch " << UB->getNumberOfObjects();
   1333   if (nfat_arch == 0)
   1334     outs() << " (malformed, contains zero architecture types)\n";
   1335   else if (big_size > size)
   1336     outs() << " (malformed, architectures past end of file)\n";
   1337   else
   1338     outs() << "\n";
   1339 
   1340   for (uint32_t i = 0; i < nfat_arch; ++i) {
   1341     MachOUniversalBinary::ObjectForArch OFA(UB, i);
   1342     uint32_t cputype = OFA.getCPUType();
   1343     uint32_t cpusubtype = OFA.getCPUSubType();
   1344     outs() << "architecture ";
   1345     for (uint32_t j = 0; i != 0 && j <= i - 1; j++) {
   1346       MachOUniversalBinary::ObjectForArch other_OFA(UB, j);
   1347       uint32_t other_cputype = other_OFA.getCPUType();
   1348       uint32_t other_cpusubtype = other_OFA.getCPUSubType();
   1349       if (cputype != 0 && cpusubtype != 0 && cputype == other_cputype &&
   1350           (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) ==
   1351               (other_cpusubtype & ~MachO::CPU_SUBTYPE_MASK)) {
   1352         outs() << "(illegal duplicate architecture) ";
   1353         break;
   1354       }
   1355     }
   1356     if (verbose) {
   1357       outs() << OFA.getArchTypeName() << "\n";
   1358       printCPUType(cputype, cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
   1359     } else {
   1360       outs() << i << "\n";
   1361       outs() << "    cputype " << cputype << "\n";
   1362       outs() << "    cpusubtype " << (cpusubtype & ~MachO::CPU_SUBTYPE_MASK)
   1363              << "\n";
   1364     }
   1365     if (verbose &&
   1366         (cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64)
   1367       outs() << "    capabilities CPU_SUBTYPE_LIB64\n";
   1368     else
   1369       outs() << "    capabilities "
   1370              << format("0x%" PRIx32,
   1371                        (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24) << "\n";
   1372     outs() << "    offset " << OFA.getOffset();
   1373     if (OFA.getOffset() > size)
   1374       outs() << " (past end of file)";
   1375     if (OFA.getOffset() % (1 << OFA.getAlign()) != 0)
   1376       outs() << " (not aligned on it's alignment (2^" << OFA.getAlign() << ")";
   1377     outs() << "\n";
   1378     outs() << "    size " << OFA.getSize();
   1379     big_size = OFA.getOffset() + OFA.getSize();
   1380     if (big_size > size)
   1381       outs() << " (past end of file)";
   1382     outs() << "\n";
   1383     outs() << "    align 2^" << OFA.getAlign() << " (" << (1 << OFA.getAlign())
   1384            << ")\n";
   1385   }
   1386 }
   1387 
   1388 static void printArchiveChild(const Archive::Child &C, bool verbose,
   1389                               bool print_offset) {
   1390   if (print_offset)
   1391     outs() << C.getChildOffset() << "\t";
   1392   sys::fs::perms Mode = C.getAccessMode();
   1393   if (verbose) {
   1394     // FIXME: this first dash, "-", is for (Mode & S_IFMT) == S_IFREG.
   1395     // But there is nothing in sys::fs::perms for S_IFMT or S_IFREG.
   1396     outs() << "-";
   1397     outs() << ((Mode & sys::fs::owner_read) ? "r" : "-");
   1398     outs() << ((Mode & sys::fs::owner_write) ? "w" : "-");
   1399     outs() << ((Mode & sys::fs::owner_exe) ? "x" : "-");
   1400     outs() << ((Mode & sys::fs::group_read) ? "r" : "-");
   1401     outs() << ((Mode & sys::fs::group_write) ? "w" : "-");
   1402     outs() << ((Mode & sys::fs::group_exe) ? "x" : "-");
   1403     outs() << ((Mode & sys::fs::others_read) ? "r" : "-");
   1404     outs() << ((Mode & sys::fs::others_write) ? "w" : "-");
   1405     outs() << ((Mode & sys::fs::others_exe) ? "x" : "-");
   1406   } else {
   1407     outs() << format("0%o ", Mode);
   1408   }
   1409 
   1410   unsigned UID = C.getUID();
   1411   outs() << format("%3d/", UID);
   1412   unsigned GID = C.getGID();
   1413   outs() << format("%-3d ", GID);
   1414   ErrorOr<uint64_t> Size = C.getRawSize();
   1415   if (std::error_code EC = Size.getError())
   1416     report_fatal_error(EC.message());
   1417   outs() << format("%5" PRId64, Size.get()) << " ";
   1418 
   1419   StringRef RawLastModified = C.getRawLastModified();
   1420   if (verbose) {
   1421     unsigned Seconds;
   1422     if (RawLastModified.getAsInteger(10, Seconds))
   1423       outs() << "(date: \"%s\" contains non-decimal chars) " << RawLastModified;
   1424     else {
   1425       // Since cime(3) returns a 26 character string of the form:
   1426       // "Sun Sep 16 01:03:52 1973\n\0"
   1427       // just print 24 characters.
   1428       time_t t = Seconds;
   1429       outs() << format("%.24s ", ctime(&t));
   1430     }
   1431   } else {
   1432     outs() << RawLastModified << " ";
   1433   }
   1434 
   1435   if (verbose) {
   1436     ErrorOr<StringRef> NameOrErr = C.getName();
   1437     if (NameOrErr.getError()) {
   1438       StringRef RawName = C.getRawName();
   1439       outs() << RawName << "\n";
   1440     } else {
   1441       StringRef Name = NameOrErr.get();
   1442       outs() << Name << "\n";
   1443     }
   1444   } else {
   1445     StringRef RawName = C.getRawName();
   1446     outs() << RawName << "\n";
   1447   }
   1448 }
   1449 
   1450 static void printArchiveHeaders(Archive *A, bool verbose, bool print_offset) {
   1451   for (Archive::child_iterator I = A->child_begin(false), E = A->child_end();
   1452        I != E; ++I) {
   1453     if (std::error_code EC = I->getError())
   1454       report_fatal_error(EC.message());
   1455     const Archive::Child &C = **I;
   1456     printArchiveChild(C, verbose, print_offset);
   1457   }
   1458 }
   1459 
   1460 // ParseInputMachO() parses the named Mach-O file in Filename and handles the
   1461 // -arch flags selecting just those slices as specified by them and also parses
   1462 // archive files.  Then for each individual Mach-O file ProcessMachO() is
   1463 // called to process the file based on the command line options.
   1464 void llvm::ParseInputMachO(StringRef Filename) {
   1465   // Check for -arch all and verifiy the -arch flags are valid.
   1466   for (unsigned i = 0; i < ArchFlags.size(); ++i) {
   1467     if (ArchFlags[i] == "all") {
   1468       ArchAll = true;
   1469     } else {
   1470       if (!MachOObjectFile::isValidArch(ArchFlags[i])) {
   1471         errs() << "llvm-objdump: Unknown architecture named '" + ArchFlags[i] +
   1472                       "'for the -arch option\n";
   1473         return;
   1474       }
   1475     }
   1476   }
   1477 
   1478   // Attempt to open the binary.
   1479   ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(Filename);
   1480   if (std::error_code EC = BinaryOrErr.getError()) {
   1481     errs() << "llvm-objdump: '" << Filename << "': " << EC.message() << ".\n";
   1482     return;
   1483   }
   1484   Binary &Bin = *BinaryOrErr.get().getBinary();
   1485 
   1486   if (Archive *A = dyn_cast<Archive>(&Bin)) {
   1487     outs() << "Archive : " << Filename << "\n";
   1488     if (ArchiveHeaders)
   1489       printArchiveHeaders(A, !NonVerbose, ArchiveMemberOffsets);
   1490     for (Archive::child_iterator I = A->child_begin(), E = A->child_end();
   1491          I != E; ++I) {
   1492       if (std::error_code EC = I->getError())
   1493         report_error(Filename, EC);
   1494       auto &C = I->get();
   1495       ErrorOr<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
   1496       if (ChildOrErr.getError())
   1497         continue;
   1498       if (MachOObjectFile *O = dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
   1499         if (!checkMachOAndArchFlags(O, Filename))
   1500           return;
   1501         ProcessMachO(Filename, O, O->getFileName());
   1502       }
   1503     }
   1504     return;
   1505   }
   1506   if (UniversalHeaders) {
   1507     if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin))
   1508       printMachOUniversalHeaders(UB, !NonVerbose);
   1509   }
   1510   if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin)) {
   1511     // If we have a list of architecture flags specified dump only those.
   1512     if (!ArchAll && ArchFlags.size() != 0) {
   1513       // Look for a slice in the universal binary that matches each ArchFlag.
   1514       bool ArchFound;
   1515       for (unsigned i = 0; i < ArchFlags.size(); ++i) {
   1516         ArchFound = false;
   1517         for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
   1518                                                    E = UB->end_objects();
   1519              I != E; ++I) {
   1520           if (ArchFlags[i] == I->getArchTypeName()) {
   1521             ArchFound = true;
   1522             ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr =
   1523                 I->getAsObjectFile();
   1524             std::string ArchitectureName = "";
   1525             if (ArchFlags.size() > 1)
   1526               ArchitectureName = I->getArchTypeName();
   1527             if (ObjOrErr) {
   1528               ObjectFile &O = *ObjOrErr.get();
   1529               if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
   1530                 ProcessMachO(Filename, MachOOF, "", ArchitectureName);
   1531             } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr =
   1532                            I->getAsArchive()) {
   1533               std::unique_ptr<Archive> &A = *AOrErr;
   1534               outs() << "Archive : " << Filename;
   1535               if (!ArchitectureName.empty())
   1536                 outs() << " (architecture " << ArchitectureName << ")";
   1537               outs() << "\n";
   1538               if (ArchiveHeaders)
   1539                 printArchiveHeaders(A.get(), !NonVerbose, ArchiveMemberOffsets);
   1540               for (Archive::child_iterator AI = A->child_begin(),
   1541                                            AE = A->child_end();
   1542                    AI != AE; ++AI) {
   1543                 if (std::error_code EC = AI->getError())
   1544                   report_error(Filename, EC);
   1545                 auto &C = AI->get();
   1546                 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
   1547                 if (ChildOrErr.getError())
   1548                   continue;
   1549                 if (MachOObjectFile *O =
   1550                         dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
   1551                   ProcessMachO(Filename, O, O->getFileName(), ArchitectureName);
   1552               }
   1553             }
   1554           }
   1555         }
   1556         if (!ArchFound) {
   1557           errs() << "llvm-objdump: file: " + Filename + " does not contain "
   1558                  << "architecture: " + ArchFlags[i] + "\n";
   1559           return;
   1560         }
   1561       }
   1562       return;
   1563     }
   1564     // No architecture flags were specified so if this contains a slice that
   1565     // matches the host architecture dump only that.
   1566     if (!ArchAll) {
   1567       for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
   1568                                                  E = UB->end_objects();
   1569            I != E; ++I) {
   1570         if (MachOObjectFile::getHostArch().getArchName() ==
   1571             I->getArchTypeName()) {
   1572           ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
   1573           std::string ArchiveName;
   1574           ArchiveName.clear();
   1575           if (ObjOrErr) {
   1576             ObjectFile &O = *ObjOrErr.get();
   1577             if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
   1578               ProcessMachO(Filename, MachOOF);
   1579           } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr =
   1580                          I->getAsArchive()) {
   1581             std::unique_ptr<Archive> &A = *AOrErr;
   1582             outs() << "Archive : " << Filename << "\n";
   1583             if (ArchiveHeaders)
   1584               printArchiveHeaders(A.get(), !NonVerbose, ArchiveMemberOffsets);
   1585             for (Archive::child_iterator AI = A->child_begin(),
   1586                                          AE = A->child_end();
   1587                  AI != AE; ++AI) {
   1588               if (std::error_code EC = AI->getError())
   1589                 report_error(Filename, EC);
   1590               auto &C = AI->get();
   1591               ErrorOr<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
   1592               if (ChildOrErr.getError())
   1593                 continue;
   1594               if (MachOObjectFile *O =
   1595                       dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
   1596                 ProcessMachO(Filename, O, O->getFileName());
   1597             }
   1598           }
   1599           return;
   1600         }
   1601       }
   1602     }
   1603     // Either all architectures have been specified or none have been specified
   1604     // and this does not contain the host architecture so dump all the slices.
   1605     bool moreThanOneArch = UB->getNumberOfObjects() > 1;
   1606     for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
   1607                                                E = UB->end_objects();
   1608          I != E; ++I) {
   1609       ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
   1610       std::string ArchitectureName = "";
   1611       if (moreThanOneArch)
   1612         ArchitectureName = I->getArchTypeName();
   1613       if (ObjOrErr) {
   1614         ObjectFile &Obj = *ObjOrErr.get();
   1615         if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&Obj))
   1616           ProcessMachO(Filename, MachOOF, "", ArchitectureName);
   1617       } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr = I->getAsArchive()) {
   1618         std::unique_ptr<Archive> &A = *AOrErr;
   1619         outs() << "Archive : " << Filename;
   1620         if (!ArchitectureName.empty())
   1621           outs() << " (architecture " << ArchitectureName << ")";
   1622         outs() << "\n";
   1623         if (ArchiveHeaders)
   1624           printArchiveHeaders(A.get(), !NonVerbose, ArchiveMemberOffsets);
   1625         for (Archive::child_iterator AI = A->child_begin(), AE = A->child_end();
   1626              AI != AE; ++AI) {
   1627           if (std::error_code EC = AI->getError())
   1628             report_error(Filename, EC);
   1629           auto &C = AI->get();
   1630           ErrorOr<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
   1631           if (ChildOrErr.getError())
   1632             continue;
   1633           if (MachOObjectFile *O =
   1634                   dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
   1635             if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(O))
   1636               ProcessMachO(Filename, MachOOF, MachOOF->getFileName(),
   1637                            ArchitectureName);
   1638           }
   1639         }
   1640       }
   1641     }
   1642     return;
   1643   }
   1644   if (ObjectFile *O = dyn_cast<ObjectFile>(&Bin)) {
   1645     if (!checkMachOAndArchFlags(O, Filename))
   1646       return;
   1647     if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&*O)) {
   1648       ProcessMachO(Filename, MachOOF);
   1649     } else
   1650       errs() << "llvm-objdump: '" << Filename << "': "
   1651              << "Object is not a Mach-O file type.\n";
   1652   } else
   1653     report_error(Filename, object_error::invalid_file_type);
   1654 }
   1655 
   1656 typedef std::pair<uint64_t, const char *> BindInfoEntry;
   1657 typedef std::vector<BindInfoEntry> BindTable;
   1658 typedef BindTable::iterator bind_table_iterator;
   1659 
   1660 // The block of info used by the Symbolizer call backs.
   1661 struct DisassembleInfo {
   1662   bool verbose;
   1663   MachOObjectFile *O;
   1664   SectionRef S;
   1665   SymbolAddressMap *AddrMap;
   1666   std::vector<SectionRef> *Sections;
   1667   const char *class_name;
   1668   const char *selector_name;
   1669   char *method;
   1670   char *demangled_name;
   1671   uint64_t adrp_addr;
   1672   uint32_t adrp_inst;
   1673   BindTable *bindtable;
   1674   uint32_t depth;
   1675 };
   1676 
   1677 // SymbolizerGetOpInfo() is the operand information call back function.
   1678 // This is called to get the symbolic information for operand(s) of an
   1679 // instruction when it is being done.  This routine does this from
   1680 // the relocation information, symbol table, etc. That block of information
   1681 // is a pointer to the struct DisassembleInfo that was passed when the
   1682 // disassembler context was created and passed to back to here when
   1683 // called back by the disassembler for instruction operands that could have
   1684 // relocation information. The address of the instruction containing operand is
   1685 // at the Pc parameter.  The immediate value the operand has is passed in
   1686 // op_info->Value and is at Offset past the start of the instruction and has a
   1687 // byte Size of 1, 2 or 4. The symbolc information is returned in TagBuf is the
   1688 // LLVMOpInfo1 struct defined in the header "llvm-c/Disassembler.h" as symbol
   1689 // names and addends of the symbolic expression to add for the operand.  The
   1690 // value of TagType is currently 1 (for the LLVMOpInfo1 struct). If symbolic
   1691 // information is returned then this function returns 1 else it returns 0.
   1692 static int SymbolizerGetOpInfo(void *DisInfo, uint64_t Pc, uint64_t Offset,
   1693                                uint64_t Size, int TagType, void *TagBuf) {
   1694   struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
   1695   struct LLVMOpInfo1 *op_info = (struct LLVMOpInfo1 *)TagBuf;
   1696   uint64_t value = op_info->Value;
   1697 
   1698   // Make sure all fields returned are zero if we don't set them.
   1699   memset((void *)op_info, '\0', sizeof(struct LLVMOpInfo1));
   1700   op_info->Value = value;
   1701 
   1702   // If the TagType is not the value 1 which it code knows about or if no
   1703   // verbose symbolic information is wanted then just return 0, indicating no
   1704   // information is being returned.
   1705   if (TagType != 1 || !info->verbose)
   1706     return 0;
   1707 
   1708   unsigned int Arch = info->O->getArch();
   1709   if (Arch == Triple::x86) {
   1710     if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
   1711       return 0;
   1712     if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
   1713       // TODO:
   1714       // Search the external relocation entries of a fully linked image
   1715       // (if any) for an entry that matches this segment offset.
   1716       // uint32_t seg_offset = (Pc + Offset);
   1717       return 0;
   1718     }
   1719     // In MH_OBJECT filetypes search the section's relocation entries (if any)
   1720     // for an entry for this section offset.
   1721     uint32_t sect_addr = info->S.getAddress();
   1722     uint32_t sect_offset = (Pc + Offset) - sect_addr;
   1723     bool reloc_found = false;
   1724     DataRefImpl Rel;
   1725     MachO::any_relocation_info RE;
   1726     bool isExtern = false;
   1727     SymbolRef Symbol;
   1728     bool r_scattered = false;
   1729     uint32_t r_value, pair_r_value, r_type;
   1730     for (const RelocationRef &Reloc : info->S.relocations()) {
   1731       uint64_t RelocOffset = Reloc.getOffset();
   1732       if (RelocOffset == sect_offset) {
   1733         Rel = Reloc.getRawDataRefImpl();
   1734         RE = info->O->getRelocation(Rel);
   1735         r_type = info->O->getAnyRelocationType(RE);
   1736         r_scattered = info->O->isRelocationScattered(RE);
   1737         if (r_scattered) {
   1738           r_value = info->O->getScatteredRelocationValue(RE);
   1739           if (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
   1740               r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF) {
   1741             DataRefImpl RelNext = Rel;
   1742             info->O->moveRelocationNext(RelNext);
   1743             MachO::any_relocation_info RENext;
   1744             RENext = info->O->getRelocation(RelNext);
   1745             if (info->O->isRelocationScattered(RENext))
   1746               pair_r_value = info->O->getScatteredRelocationValue(RENext);
   1747             else
   1748               return 0;
   1749           }
   1750         } else {
   1751           isExtern = info->O->getPlainRelocationExternal(RE);
   1752           if (isExtern) {
   1753             symbol_iterator RelocSym = Reloc.getSymbol();
   1754             Symbol = *RelocSym;
   1755           }
   1756         }
   1757         reloc_found = true;
   1758         break;
   1759       }
   1760     }
   1761     if (reloc_found && isExtern) {
   1762       ErrorOr<StringRef> SymName = Symbol.getName();
   1763       if (std::error_code EC = SymName.getError())
   1764         report_fatal_error(EC.message());
   1765       const char *name = SymName->data();
   1766       op_info->AddSymbol.Present = 1;
   1767       op_info->AddSymbol.Name = name;
   1768       // For i386 extern relocation entries the value in the instruction is
   1769       // the offset from the symbol, and value is already set in op_info->Value.
   1770       return 1;
   1771     }
   1772     if (reloc_found && (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
   1773                         r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF)) {
   1774       const char *add = GuessSymbolName(r_value, info->AddrMap);
   1775       const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
   1776       uint32_t offset = value - (r_value - pair_r_value);
   1777       op_info->AddSymbol.Present = 1;
   1778       if (add != nullptr)
   1779         op_info->AddSymbol.Name = add;
   1780       else
   1781         op_info->AddSymbol.Value = r_value;
   1782       op_info->SubtractSymbol.Present = 1;
   1783       if (sub != nullptr)
   1784         op_info->SubtractSymbol.Name = sub;
   1785       else
   1786         op_info->SubtractSymbol.Value = pair_r_value;
   1787       op_info->Value = offset;
   1788       return 1;
   1789     }
   1790     return 0;
   1791   }
   1792   if (Arch == Triple::x86_64) {
   1793     if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
   1794       return 0;
   1795     if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
   1796       // TODO:
   1797       // Search the external relocation entries of a fully linked image
   1798       // (if any) for an entry that matches this segment offset.
   1799       // uint64_t seg_offset = (Pc + Offset);
   1800       return 0;
   1801     }
   1802     // In MH_OBJECT filetypes search the section's relocation entries (if any)
   1803     // for an entry for this section offset.
   1804     uint64_t sect_addr = info->S.getAddress();
   1805     uint64_t sect_offset = (Pc + Offset) - sect_addr;
   1806     bool reloc_found = false;
   1807     DataRefImpl Rel;
   1808     MachO::any_relocation_info RE;
   1809     bool isExtern = false;
   1810     SymbolRef Symbol;
   1811     for (const RelocationRef &Reloc : info->S.relocations()) {
   1812       uint64_t RelocOffset = Reloc.getOffset();
   1813       if (RelocOffset == sect_offset) {
   1814         Rel = Reloc.getRawDataRefImpl();
   1815         RE = info->O->getRelocation(Rel);
   1816         // NOTE: Scattered relocations don't exist on x86_64.
   1817         isExtern = info->O->getPlainRelocationExternal(RE);
   1818         if (isExtern) {
   1819           symbol_iterator RelocSym = Reloc.getSymbol();
   1820           Symbol = *RelocSym;
   1821         }
   1822         reloc_found = true;
   1823         break;
   1824       }
   1825     }
   1826     if (reloc_found && isExtern) {
   1827       // The Value passed in will be adjusted by the Pc if the instruction
   1828       // adds the Pc.  But for x86_64 external relocation entries the Value
   1829       // is the offset from the external symbol.
   1830       if (info->O->getAnyRelocationPCRel(RE))
   1831         op_info->Value -= Pc + Offset + Size;
   1832       ErrorOr<StringRef> SymName = Symbol.getName();
   1833       if (std::error_code EC = SymName.getError())
   1834         report_fatal_error(EC.message());
   1835       const char *name = SymName->data();
   1836       unsigned Type = info->O->getAnyRelocationType(RE);
   1837       if (Type == MachO::X86_64_RELOC_SUBTRACTOR) {
   1838         DataRefImpl RelNext = Rel;
   1839         info->O->moveRelocationNext(RelNext);
   1840         MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
   1841         unsigned TypeNext = info->O->getAnyRelocationType(RENext);
   1842         bool isExternNext = info->O->getPlainRelocationExternal(RENext);
   1843         unsigned SymbolNum = info->O->getPlainRelocationSymbolNum(RENext);
   1844         if (TypeNext == MachO::X86_64_RELOC_UNSIGNED && isExternNext) {
   1845           op_info->SubtractSymbol.Present = 1;
   1846           op_info->SubtractSymbol.Name = name;
   1847           symbol_iterator RelocSymNext = info->O->getSymbolByIndex(SymbolNum);
   1848           Symbol = *RelocSymNext;
   1849           ErrorOr<StringRef> SymNameNext = Symbol.getName();
   1850           if (std::error_code EC = SymNameNext.getError())
   1851             report_fatal_error(EC.message());
   1852           name = SymNameNext->data();
   1853         }
   1854       }
   1855       // TODO: add the VariantKinds to op_info->VariantKind for relocation types
   1856       // like: X86_64_RELOC_TLV, X86_64_RELOC_GOT_LOAD and X86_64_RELOC_GOT.
   1857       op_info->AddSymbol.Present = 1;
   1858       op_info->AddSymbol.Name = name;
   1859       return 1;
   1860     }
   1861     return 0;
   1862   }
   1863   if (Arch == Triple::arm) {
   1864     if (Offset != 0 || (Size != 4 && Size != 2))
   1865       return 0;
   1866     if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
   1867       // TODO:
   1868       // Search the external relocation entries of a fully linked image
   1869       // (if any) for an entry that matches this segment offset.
   1870       // uint32_t seg_offset = (Pc + Offset);
   1871       return 0;
   1872     }
   1873     // In MH_OBJECT filetypes search the section's relocation entries (if any)
   1874     // for an entry for this section offset.
   1875     uint32_t sect_addr = info->S.getAddress();
   1876     uint32_t sect_offset = (Pc + Offset) - sect_addr;
   1877     DataRefImpl Rel;
   1878     MachO::any_relocation_info RE;
   1879     bool isExtern = false;
   1880     SymbolRef Symbol;
   1881     bool r_scattered = false;
   1882     uint32_t r_value, pair_r_value, r_type, r_length, other_half;
   1883     auto Reloc =
   1884         std::find_if(info->S.relocations().begin(), info->S.relocations().end(),
   1885                      [&](const RelocationRef &Reloc) {
   1886                        uint64_t RelocOffset = Reloc.getOffset();
   1887                        return RelocOffset == sect_offset;
   1888                      });
   1889 
   1890     if (Reloc == info->S.relocations().end())
   1891       return 0;
   1892 
   1893     Rel = Reloc->getRawDataRefImpl();
   1894     RE = info->O->getRelocation(Rel);
   1895     r_length = info->O->getAnyRelocationLength(RE);
   1896     r_scattered = info->O->isRelocationScattered(RE);
   1897     if (r_scattered) {
   1898       r_value = info->O->getScatteredRelocationValue(RE);
   1899       r_type = info->O->getScatteredRelocationType(RE);
   1900     } else {
   1901       r_type = info->O->getAnyRelocationType(RE);
   1902       isExtern = info->O->getPlainRelocationExternal(RE);
   1903       if (isExtern) {
   1904         symbol_iterator RelocSym = Reloc->getSymbol();
   1905         Symbol = *RelocSym;
   1906       }
   1907     }
   1908     if (r_type == MachO::ARM_RELOC_HALF ||
   1909         r_type == MachO::ARM_RELOC_SECTDIFF ||
   1910         r_type == MachO::ARM_RELOC_LOCAL_SECTDIFF ||
   1911         r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
   1912       DataRefImpl RelNext = Rel;
   1913       info->O->moveRelocationNext(RelNext);
   1914       MachO::any_relocation_info RENext;
   1915       RENext = info->O->getRelocation(RelNext);
   1916       other_half = info->O->getAnyRelocationAddress(RENext) & 0xffff;
   1917       if (info->O->isRelocationScattered(RENext))
   1918         pair_r_value = info->O->getScatteredRelocationValue(RENext);
   1919     }
   1920 
   1921     if (isExtern) {
   1922       ErrorOr<StringRef> SymName = Symbol.getName();
   1923       if (std::error_code EC = SymName.getError())
   1924         report_fatal_error(EC.message());
   1925       const char *name = SymName->data();
   1926       op_info->AddSymbol.Present = 1;
   1927       op_info->AddSymbol.Name = name;
   1928       switch (r_type) {
   1929       case MachO::ARM_RELOC_HALF:
   1930         if ((r_length & 0x1) == 1) {
   1931           op_info->Value = value << 16 | other_half;
   1932           op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
   1933         } else {
   1934           op_info->Value = other_half << 16 | value;
   1935           op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
   1936         }
   1937         break;
   1938       default:
   1939         break;
   1940       }
   1941       return 1;
   1942     }
   1943     // If we have a branch that is not an external relocation entry then
   1944     // return 0 so the code in tryAddingSymbolicOperand() can use the
   1945     // SymbolLookUp call back with the branch target address to look up the
   1946     // symbol and possiblity add an annotation for a symbol stub.
   1947     if (isExtern == 0 && (r_type == MachO::ARM_RELOC_BR24 ||
   1948                           r_type == MachO::ARM_THUMB_RELOC_BR22))
   1949       return 0;
   1950 
   1951     uint32_t offset = 0;
   1952     if (r_type == MachO::ARM_RELOC_HALF ||
   1953         r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
   1954       if ((r_length & 0x1) == 1)
   1955         value = value << 16 | other_half;
   1956       else
   1957         value = other_half << 16 | value;
   1958     }
   1959     if (r_scattered && (r_type != MachO::ARM_RELOC_HALF &&
   1960                         r_type != MachO::ARM_RELOC_HALF_SECTDIFF)) {
   1961       offset = value - r_value;
   1962       value = r_value;
   1963     }
   1964 
   1965     if (r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
   1966       if ((r_length & 0x1) == 1)
   1967         op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
   1968       else
   1969         op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
   1970       const char *add = GuessSymbolName(r_value, info->AddrMap);
   1971       const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
   1972       int32_t offset = value - (r_value - pair_r_value);
   1973       op_info->AddSymbol.Present = 1;
   1974       if (add != nullptr)
   1975         op_info->AddSymbol.Name = add;
   1976       else
   1977         op_info->AddSymbol.Value = r_value;
   1978       op_info->SubtractSymbol.Present = 1;
   1979       if (sub != nullptr)
   1980         op_info->SubtractSymbol.Name = sub;
   1981       else
   1982         op_info->SubtractSymbol.Value = pair_r_value;
   1983       op_info->Value = offset;
   1984       return 1;
   1985     }
   1986 
   1987     op_info->AddSymbol.Present = 1;
   1988     op_info->Value = offset;
   1989     if (r_type == MachO::ARM_RELOC_HALF) {
   1990       if ((r_length & 0x1) == 1)
   1991         op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
   1992       else
   1993         op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
   1994     }
   1995     const char *add = GuessSymbolName(value, info->AddrMap);
   1996     if (add != nullptr) {
   1997       op_info->AddSymbol.Name = add;
   1998       return 1;
   1999     }
   2000     op_info->AddSymbol.Value = value;
   2001     return 1;
   2002   }
   2003   if (Arch == Triple::aarch64) {
   2004     if (Offset != 0 || Size != 4)
   2005       return 0;
   2006     if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
   2007       // TODO:
   2008       // Search the external relocation entries of a fully linked image
   2009       // (if any) for an entry that matches this segment offset.
   2010       // uint64_t seg_offset = (Pc + Offset);
   2011       return 0;
   2012     }
   2013     // In MH_OBJECT filetypes search the section's relocation entries (if any)
   2014     // for an entry for this section offset.
   2015     uint64_t sect_addr = info->S.getAddress();
   2016     uint64_t sect_offset = (Pc + Offset) - sect_addr;
   2017     auto Reloc =
   2018         std::find_if(info->S.relocations().begin(), info->S.relocations().end(),
   2019                      [&](const RelocationRef &Reloc) {
   2020                        uint64_t RelocOffset = Reloc.getOffset();
   2021                        return RelocOffset == sect_offset;
   2022                      });
   2023 
   2024     if (Reloc == info->S.relocations().end())
   2025       return 0;
   2026 
   2027     DataRefImpl Rel = Reloc->getRawDataRefImpl();
   2028     MachO::any_relocation_info RE = info->O->getRelocation(Rel);
   2029     uint32_t r_type = info->O->getAnyRelocationType(RE);
   2030     if (r_type == MachO::ARM64_RELOC_ADDEND) {
   2031       DataRefImpl RelNext = Rel;
   2032       info->O->moveRelocationNext(RelNext);
   2033       MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
   2034       if (value == 0) {
   2035         value = info->O->getPlainRelocationSymbolNum(RENext);
   2036         op_info->Value = value;
   2037       }
   2038     }
   2039     // NOTE: Scattered relocations don't exist on arm64.
   2040     if (!info->O->getPlainRelocationExternal(RE))
   2041       return 0;
   2042     ErrorOr<StringRef> SymName = Reloc->getSymbol()->getName();
   2043     if (std::error_code EC = SymName.getError())
   2044       report_fatal_error(EC.message());
   2045     const char *name = SymName->data();
   2046     op_info->AddSymbol.Present = 1;
   2047     op_info->AddSymbol.Name = name;
   2048 
   2049     switch (r_type) {
   2050     case MachO::ARM64_RELOC_PAGE21:
   2051       /* @page */
   2052       op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGE;
   2053       break;
   2054     case MachO::ARM64_RELOC_PAGEOFF12:
   2055       /* @pageoff */
   2056       op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGEOFF;
   2057       break;
   2058     case MachO::ARM64_RELOC_GOT_LOAD_PAGE21:
   2059       /* @gotpage */
   2060       op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGE;
   2061       break;
   2062     case MachO::ARM64_RELOC_GOT_LOAD_PAGEOFF12:
   2063       /* @gotpageoff */
   2064       op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGEOFF;
   2065       break;
   2066     case MachO::ARM64_RELOC_TLVP_LOAD_PAGE21:
   2067       /* @tvlppage is not implemented in llvm-mc */
   2068       op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVP;
   2069       break;
   2070     case MachO::ARM64_RELOC_TLVP_LOAD_PAGEOFF12:
   2071       /* @tvlppageoff is not implemented in llvm-mc */
   2072       op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVOFF;
   2073       break;
   2074     default:
   2075     case MachO::ARM64_RELOC_BRANCH26:
   2076       op_info->VariantKind = LLVMDisassembler_VariantKind_None;
   2077       break;
   2078     }
   2079     return 1;
   2080   }
   2081   return 0;
   2082 }
   2083 
   2084 // GuessCstringPointer is passed the address of what might be a pointer to a
   2085 // literal string in a cstring section.  If that address is in a cstring section
   2086 // it returns a pointer to that string.  Else it returns nullptr.
   2087 static const char *GuessCstringPointer(uint64_t ReferenceValue,
   2088                                        struct DisassembleInfo *info) {
   2089   for (const auto &Load : info->O->load_commands()) {
   2090     if (Load.C.cmd == MachO::LC_SEGMENT_64) {
   2091       MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
   2092       for (unsigned J = 0; J < Seg.nsects; ++J) {
   2093         MachO::section_64 Sec = info->O->getSection64(Load, J);
   2094         uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
   2095         if (section_type == MachO::S_CSTRING_LITERALS &&
   2096             ReferenceValue >= Sec.addr &&
   2097             ReferenceValue < Sec.addr + Sec.size) {
   2098           uint64_t sect_offset = ReferenceValue - Sec.addr;
   2099           uint64_t object_offset = Sec.offset + sect_offset;
   2100           StringRef MachOContents = info->O->getData();
   2101           uint64_t object_size = MachOContents.size();
   2102           const char *object_addr = (const char *)MachOContents.data();
   2103           if (object_offset < object_size) {
   2104             const char *name = object_addr + object_offset;
   2105             return name;
   2106           } else {
   2107             return nullptr;
   2108           }
   2109         }
   2110       }
   2111     } else if (Load.C.cmd == MachO::LC_SEGMENT) {
   2112       MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
   2113       for (unsigned J = 0; J < Seg.nsects; ++J) {
   2114         MachO::section Sec = info->O->getSection(Load, J);
   2115         uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
   2116         if (section_type == MachO::S_CSTRING_LITERALS &&
   2117             ReferenceValue >= Sec.addr &&
   2118             ReferenceValue < Sec.addr + Sec.size) {
   2119           uint64_t sect_offset = ReferenceValue - Sec.addr;
   2120           uint64_t object_offset = Sec.offset + sect_offset;
   2121           StringRef MachOContents = info->O->getData();
   2122           uint64_t object_size = MachOContents.size();
   2123           const char *object_addr = (const char *)MachOContents.data();
   2124           if (object_offset < object_size) {
   2125             const char *name = object_addr + object_offset;
   2126             return name;
   2127           } else {
   2128             return nullptr;
   2129           }
   2130         }
   2131       }
   2132     }
   2133   }
   2134   return nullptr;
   2135 }
   2136 
   2137 // GuessIndirectSymbol returns the name of the indirect symbol for the
   2138 // ReferenceValue passed in or nullptr.  This is used when ReferenceValue maybe
   2139 // an address of a symbol stub or a lazy or non-lazy pointer to associate the
   2140 // symbol name being referenced by the stub or pointer.
   2141 static const char *GuessIndirectSymbol(uint64_t ReferenceValue,
   2142                                        struct DisassembleInfo *info) {
   2143   MachO::dysymtab_command Dysymtab = info->O->getDysymtabLoadCommand();
   2144   MachO::symtab_command Symtab = info->O->getSymtabLoadCommand();
   2145   for (const auto &Load : info->O->load_commands()) {
   2146     if (Load.C.cmd == MachO::LC_SEGMENT_64) {
   2147       MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
   2148       for (unsigned J = 0; J < Seg.nsects; ++J) {
   2149         MachO::section_64 Sec = info->O->getSection64(Load, J);
   2150         uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
   2151         if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
   2152              section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
   2153              section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
   2154              section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
   2155              section_type == MachO::S_SYMBOL_STUBS) &&
   2156             ReferenceValue >= Sec.addr &&
   2157             ReferenceValue < Sec.addr + Sec.size) {
   2158           uint32_t stride;
   2159           if (section_type == MachO::S_SYMBOL_STUBS)
   2160             stride = Sec.reserved2;
   2161           else
   2162             stride = 8;
   2163           if (stride == 0)
   2164             return nullptr;
   2165           uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
   2166           if (index < Dysymtab.nindirectsyms) {
   2167             uint32_t indirect_symbol =
   2168                 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
   2169             if (indirect_symbol < Symtab.nsyms) {
   2170               symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
   2171               SymbolRef Symbol = *Sym;
   2172               ErrorOr<StringRef> SymName = Symbol.getName();
   2173               if (std::error_code EC = SymName.getError())
   2174                 report_fatal_error(EC.message());
   2175               const char *name = SymName->data();
   2176               return name;
   2177             }
   2178           }
   2179         }
   2180       }
   2181     } else if (Load.C.cmd == MachO::LC_SEGMENT) {
   2182       MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
   2183       for (unsigned J = 0; J < Seg.nsects; ++J) {
   2184         MachO::section Sec = info->O->getSection(Load, J);
   2185         uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
   2186         if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
   2187              section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
   2188              section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
   2189              section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
   2190              section_type == MachO::S_SYMBOL_STUBS) &&
   2191             ReferenceValue >= Sec.addr &&
   2192             ReferenceValue < Sec.addr + Sec.size) {
   2193           uint32_t stride;
   2194           if (section_type == MachO::S_SYMBOL_STUBS)
   2195             stride = Sec.reserved2;
   2196           else
   2197             stride = 4;
   2198           if (stride == 0)
   2199             return nullptr;
   2200           uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
   2201           if (index < Dysymtab.nindirectsyms) {
   2202             uint32_t indirect_symbol =
   2203                 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
   2204             if (indirect_symbol < Symtab.nsyms) {
   2205               symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
   2206               SymbolRef Symbol = *Sym;
   2207               ErrorOr<StringRef> SymName = Symbol.getName();
   2208               if (std::error_code EC = SymName.getError())
   2209                 report_fatal_error(EC.message());
   2210               const char *name = SymName->data();
   2211               return name;
   2212             }
   2213           }
   2214         }
   2215       }
   2216     }
   2217   }
   2218   return nullptr;
   2219 }
   2220 
   2221 // method_reference() is called passing it the ReferenceName that might be
   2222 // a reference it to an Objective-C method call.  If so then it allocates and
   2223 // assembles a method call string with the values last seen and saved in
   2224 // the DisassembleInfo's class_name and selector_name fields.  This is saved
   2225 // into the method field of the info and any previous string is free'ed.
   2226 // Then the class_name field in the info is set to nullptr.  The method call
   2227 // string is set into ReferenceName and ReferenceType is set to
   2228 // LLVMDisassembler_ReferenceType_Out_Objc_Message.  If this not a method call
   2229 // then both ReferenceType and ReferenceName are left unchanged.
   2230 static void method_reference(struct DisassembleInfo *info,
   2231                              uint64_t *ReferenceType,
   2232                              const char **ReferenceName) {
   2233   unsigned int Arch = info->O->getArch();
   2234   if (*ReferenceName != nullptr) {
   2235     if (strcmp(*ReferenceName, "_objc_msgSend") == 0) {
   2236       if (info->selector_name != nullptr) {
   2237         if (info->method != nullptr)
   2238           free(info->method);
   2239         if (info->class_name != nullptr) {
   2240           info->method = (char *)malloc(5 + strlen(info->class_name) +
   2241                                         strlen(info->selector_name));
   2242           if (info->method != nullptr) {
   2243             strcpy(info->method, "+[");
   2244             strcat(info->method, info->class_name);
   2245             strcat(info->method, " ");
   2246             strcat(info->method, info->selector_name);
   2247             strcat(info->method, "]");
   2248             *ReferenceName = info->method;
   2249             *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
   2250           }
   2251         } else {
   2252           info->method = (char *)malloc(9 + strlen(info->selector_name));
   2253           if (info->method != nullptr) {
   2254             if (Arch == Triple::x86_64)
   2255               strcpy(info->method, "-[%rdi ");
   2256             else if (Arch == Triple::aarch64)
   2257               strcpy(info->method, "-[x0 ");
   2258             else
   2259               strcpy(info->method, "-[r? ");
   2260             strcat(info->method, info->selector_name);
   2261             strcat(info->method, "]");
   2262             *ReferenceName = info->method;
   2263             *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
   2264           }
   2265         }
   2266         info->class_name = nullptr;
   2267       }
   2268     } else if (strcmp(*ReferenceName, "_objc_msgSendSuper2") == 0) {
   2269       if (info->selector_name != nullptr) {
   2270         if (info->method != nullptr)
   2271           free(info->method);
   2272         info->method = (char *)malloc(17 + strlen(info->selector_name));
   2273         if (info->method != nullptr) {
   2274           if (Arch == Triple::x86_64)
   2275             strcpy(info->method, "-[[%rdi super] ");
   2276           else if (Arch == Triple::aarch64)
   2277             strcpy(info->method, "-[[x0 super] ");
   2278           else
   2279             strcpy(info->method, "-[[r? super] ");
   2280           strcat(info->method, info->selector_name);
   2281           strcat(info->method, "]");
   2282           *ReferenceName = info->method;
   2283           *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
   2284         }
   2285         info->class_name = nullptr;
   2286       }
   2287     }
   2288   }
   2289 }
   2290 
   2291 // GuessPointerPointer() is passed the address of what might be a pointer to
   2292 // a reference to an Objective-C class, selector, message ref or cfstring.
   2293 // If so the value of the pointer is returned and one of the booleans are set
   2294 // to true.  If not zero is returned and all the booleans are set to false.
   2295 static uint64_t GuessPointerPointer(uint64_t ReferenceValue,
   2296                                     struct DisassembleInfo *info,
   2297                                     bool &classref, bool &selref, bool &msgref,
   2298                                     bool &cfstring) {
   2299   classref = false;
   2300   selref = false;
   2301   msgref = false;
   2302   cfstring = false;
   2303   for (const auto &Load : info->O->load_commands()) {
   2304     if (Load.C.cmd == MachO::LC_SEGMENT_64) {
   2305       MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
   2306       for (unsigned J = 0; J < Seg.nsects; ++J) {
   2307         MachO::section_64 Sec = info->O->getSection64(Load, J);
   2308         if ((strncmp(Sec.sectname, "__objc_selrefs", 16) == 0 ||
   2309              strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
   2310              strncmp(Sec.sectname, "__objc_superrefs", 16) == 0 ||
   2311              strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 ||
   2312              strncmp(Sec.sectname, "__cfstring", 16) == 0) &&
   2313             ReferenceValue >= Sec.addr &&
   2314             ReferenceValue < Sec.addr + Sec.size) {
   2315           uint64_t sect_offset = ReferenceValue - Sec.addr;
   2316           uint64_t object_offset = Sec.offset + sect_offset;
   2317           StringRef MachOContents = info->O->getData();
   2318           uint64_t object_size = MachOContents.size();
   2319           const char *object_addr = (const char *)MachOContents.data();
   2320           if (object_offset < object_size) {
   2321             uint64_t pointer_value;
   2322             memcpy(&pointer_value, object_addr + object_offset,
   2323                    sizeof(uint64_t));
   2324             if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
   2325               sys::swapByteOrder(pointer_value);
   2326             if (strncmp(Sec.sectname, "__objc_selrefs", 16) == 0)
   2327               selref = true;
   2328             else if (strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
   2329                      strncmp(Sec.sectname, "__objc_superrefs", 16) == 0)
   2330               classref = true;
   2331             else if (strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 &&
   2332                      ReferenceValue + 8 < Sec.addr + Sec.size) {
   2333               msgref = true;
   2334               memcpy(&pointer_value, object_addr + object_offset + 8,
   2335                      sizeof(uint64_t));
   2336               if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
   2337                 sys::swapByteOrder(pointer_value);
   2338             } else if (strncmp(Sec.sectname, "__cfstring", 16) == 0)
   2339               cfstring = true;
   2340             return pointer_value;
   2341           } else {
   2342             return 0;
   2343           }
   2344         }
   2345       }
   2346     }
   2347     // TODO: Look for LC_SEGMENT for 32-bit Mach-O files.
   2348   }
   2349   return 0;
   2350 }
   2351 
   2352 // get_pointer_64 returns a pointer to the bytes in the object file at the
   2353 // Address from a section in the Mach-O file.  And indirectly returns the
   2354 // offset into the section, number of bytes left in the section past the offset
   2355 // and which section is was being referenced.  If the Address is not in a
   2356 // section nullptr is returned.
   2357 static const char *get_pointer_64(uint64_t Address, uint32_t &offset,
   2358                                   uint32_t &left, SectionRef &S,
   2359                                   DisassembleInfo *info,
   2360                                   bool objc_only = false) {
   2361   offset = 0;
   2362   left = 0;
   2363   S = SectionRef();
   2364   for (unsigned SectIdx = 0; SectIdx != info->Sections->size(); SectIdx++) {
   2365     uint64_t SectAddress = ((*(info->Sections))[SectIdx]).getAddress();
   2366     uint64_t SectSize = ((*(info->Sections))[SectIdx]).getSize();
   2367     if (SectSize == 0)
   2368       continue;
   2369     if (objc_only) {
   2370       StringRef SectName;
   2371       ((*(info->Sections))[SectIdx]).getName(SectName);
   2372       DataRefImpl Ref = ((*(info->Sections))[SectIdx]).getRawDataRefImpl();
   2373       StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
   2374       if (SegName != "__OBJC" && SectName != "__cstring")
   2375         continue;
   2376     }
   2377     if (Address >= SectAddress && Address < SectAddress + SectSize) {
   2378       S = (*(info->Sections))[SectIdx];
   2379       offset = Address - SectAddress;
   2380       left = SectSize - offset;
   2381       StringRef SectContents;
   2382       ((*(info->Sections))[SectIdx]).getContents(SectContents);
   2383       return SectContents.data() + offset;
   2384     }
   2385   }
   2386   return nullptr;
   2387 }
   2388 
   2389 static const char *get_pointer_32(uint32_t Address, uint32_t &offset,
   2390                                   uint32_t &left, SectionRef &S,
   2391                                   DisassembleInfo *info,
   2392                                   bool objc_only = false) {
   2393   return get_pointer_64(Address, offset, left, S, info, objc_only);
   2394 }
   2395 
   2396 // get_symbol_64() returns the name of a symbol (or nullptr) and the address of
   2397 // the symbol indirectly through n_value. Based on the relocation information
   2398 // for the specified section offset in the specified section reference.
   2399 // If no relocation information is found and a non-zero ReferenceValue for the
   2400 // symbol is passed, look up that address in the info's AddrMap.
   2401 static const char *get_symbol_64(uint32_t sect_offset, SectionRef S,
   2402                                  DisassembleInfo *info, uint64_t &n_value,
   2403                                  uint64_t ReferenceValue = 0) {
   2404   n_value = 0;
   2405   if (!info->verbose)
   2406     return nullptr;
   2407 
   2408   // See if there is an external relocation entry at the sect_offset.
   2409   bool reloc_found = false;
   2410   DataRefImpl Rel;
   2411   MachO::any_relocation_info RE;
   2412   bool isExtern = false;
   2413   SymbolRef Symbol;
   2414   for (const RelocationRef &Reloc : S.relocations()) {
   2415     uint64_t RelocOffset = Reloc.getOffset();
   2416     if (RelocOffset == sect_offset) {
   2417       Rel = Reloc.getRawDataRefImpl();
   2418       RE = info->O->getRelocation(Rel);
   2419       if (info->O->isRelocationScattered(RE))
   2420         continue;
   2421       isExtern = info->O->getPlainRelocationExternal(RE);
   2422       if (isExtern) {
   2423         symbol_iterator RelocSym = Reloc.getSymbol();
   2424         Symbol = *RelocSym;
   2425       }
   2426       reloc_found = true;
   2427       break;
   2428     }
   2429   }
   2430   // If there is an external relocation entry for a symbol in this section
   2431   // at this section_offset then use that symbol's value for the n_value
   2432   // and return its name.
   2433   const char *SymbolName = nullptr;
   2434   if (reloc_found && isExtern) {
   2435     n_value = Symbol.getValue();
   2436     ErrorOr<StringRef> NameOrError = Symbol.getName();
   2437     if (std::error_code EC = NameOrError.getError())
   2438       report_fatal_error(EC.message());
   2439     StringRef Name = *NameOrError;
   2440     if (!Name.empty()) {
   2441       SymbolName = Name.data();
   2442       return SymbolName;
   2443     }
   2444   }
   2445 
   2446   // TODO: For fully linked images, look through the external relocation
   2447   // entries off the dynamic symtab command. For these the r_offset is from the
   2448   // start of the first writeable segment in the Mach-O file.  So the offset
   2449   // to this section from that segment is passed to this routine by the caller,
   2450   // as the database_offset. Which is the difference of the section's starting
   2451   // address and the first writable segment.
   2452   //
   2453   // NOTE: need add passing the database_offset to this routine.
   2454 
   2455   // We did not find an external relocation entry so look up the ReferenceValue
   2456   // as an address of a symbol and if found return that symbol's name.
   2457   SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
   2458 
   2459   return SymbolName;
   2460 }
   2461 
   2462 static const char *get_symbol_32(uint32_t sect_offset, SectionRef S,
   2463                                  DisassembleInfo *info,
   2464                                  uint32_t ReferenceValue) {
   2465   uint64_t n_value64;
   2466   return get_symbol_64(sect_offset, S, info, n_value64, ReferenceValue);
   2467 }
   2468 
   2469 // These are structs in the Objective-C meta data and read to produce the
   2470 // comments for disassembly.  While these are part of the ABI they are no
   2471 // public defintions.  So the are here not in include/llvm/Support/MachO.h .
   2472 
   2473 // The cfstring object in a 64-bit Mach-O file.
   2474 struct cfstring64_t {
   2475   uint64_t isa;        // class64_t * (64-bit pointer)
   2476   uint64_t flags;      // flag bits
   2477   uint64_t characters; // char * (64-bit pointer)
   2478   uint64_t length;     // number of non-NULL characters in above
   2479 };
   2480 
   2481 // The class object in a 64-bit Mach-O file.
   2482 struct class64_t {
   2483   uint64_t isa;        // class64_t * (64-bit pointer)
   2484   uint64_t superclass; // class64_t * (64-bit pointer)
   2485   uint64_t cache;      // Cache (64-bit pointer)
   2486   uint64_t vtable;     // IMP * (64-bit pointer)
   2487   uint64_t data;       // class_ro64_t * (64-bit pointer)
   2488 };
   2489 
   2490 struct class32_t {
   2491   uint32_t isa;        /* class32_t * (32-bit pointer) */
   2492   uint32_t superclass; /* class32_t * (32-bit pointer) */
   2493   uint32_t cache;      /* Cache (32-bit pointer) */
   2494   uint32_t vtable;     /* IMP * (32-bit pointer) */
   2495   uint32_t data;       /* class_ro32_t * (32-bit pointer) */
   2496 };
   2497 
   2498 struct class_ro64_t {
   2499   uint32_t flags;
   2500   uint32_t instanceStart;
   2501   uint32_t instanceSize;
   2502   uint32_t reserved;
   2503   uint64_t ivarLayout;     // const uint8_t * (64-bit pointer)
   2504   uint64_t name;           // const char * (64-bit pointer)
   2505   uint64_t baseMethods;    // const method_list_t * (64-bit pointer)
   2506   uint64_t baseProtocols;  // const protocol_list_t * (64-bit pointer)
   2507   uint64_t ivars;          // const ivar_list_t * (64-bit pointer)
   2508   uint64_t weakIvarLayout; // const uint8_t * (64-bit pointer)
   2509   uint64_t baseProperties; // const struct objc_property_list (64-bit pointer)
   2510 };
   2511 
   2512 struct class_ro32_t {
   2513   uint32_t flags;
   2514   uint32_t instanceStart;
   2515   uint32_t instanceSize;
   2516   uint32_t ivarLayout;     /* const uint8_t * (32-bit pointer) */
   2517   uint32_t name;           /* const char * (32-bit pointer) */
   2518   uint32_t baseMethods;    /* const method_list_t * (32-bit pointer) */
   2519   uint32_t baseProtocols;  /* const protocol_list_t * (32-bit pointer) */
   2520   uint32_t ivars;          /* const ivar_list_t * (32-bit pointer) */
   2521   uint32_t weakIvarLayout; /* const uint8_t * (32-bit pointer) */
   2522   uint32_t baseProperties; /* const struct objc_property_list *
   2523                                                    (32-bit pointer) */
   2524 };
   2525 
   2526 /* Values for class_ro{64,32}_t->flags */
   2527 #define RO_META (1 << 0)
   2528 #define RO_ROOT (1 << 1)
   2529 #define RO_HAS_CXX_STRUCTORS (1 << 2)
   2530 
   2531 struct method_list64_t {
   2532   uint32_t entsize;
   2533   uint32_t count;
   2534   /* struct method64_t first;  These structures follow inline */
   2535 };
   2536 
   2537 struct method_list32_t {
   2538   uint32_t entsize;
   2539   uint32_t count;
   2540   /* struct method32_t first;  These structures follow inline */
   2541 };
   2542 
   2543 struct method64_t {
   2544   uint64_t name;  /* SEL (64-bit pointer) */
   2545   uint64_t types; /* const char * (64-bit pointer) */
   2546   uint64_t imp;   /* IMP (64-bit pointer) */
   2547 };
   2548 
   2549 struct method32_t {
   2550   uint32_t name;  /* SEL (32-bit pointer) */
   2551   uint32_t types; /* const char * (32-bit pointer) */
   2552   uint32_t imp;   /* IMP (32-bit pointer) */
   2553 };
   2554 
   2555 struct protocol_list64_t {
   2556   uint64_t count; /* uintptr_t (a 64-bit value) */
   2557   /* struct protocol64_t * list[0];  These pointers follow inline */
   2558 };
   2559 
   2560 struct protocol_list32_t {
   2561   uint32_t count; /* uintptr_t (a 32-bit value) */
   2562   /* struct protocol32_t * list[0];  These pointers follow inline */
   2563 };
   2564 
   2565 struct protocol64_t {
   2566   uint64_t isa;                     /* id * (64-bit pointer) */
   2567   uint64_t name;                    /* const char * (64-bit pointer) */
   2568   uint64_t protocols;               /* struct protocol_list64_t *
   2569                                                     (64-bit pointer) */
   2570   uint64_t instanceMethods;         /* method_list_t * (64-bit pointer) */
   2571   uint64_t classMethods;            /* method_list_t * (64-bit pointer) */
   2572   uint64_t optionalInstanceMethods; /* method_list_t * (64-bit pointer) */
   2573   uint64_t optionalClassMethods;    /* method_list_t * (64-bit pointer) */
   2574   uint64_t instanceProperties;      /* struct objc_property_list *
   2575                                                        (64-bit pointer) */
   2576 };
   2577 
   2578 struct protocol32_t {
   2579   uint32_t isa;                     /* id * (32-bit pointer) */
   2580   uint32_t name;                    /* const char * (32-bit pointer) */
   2581   uint32_t protocols;               /* struct protocol_list_t *
   2582                                                     (32-bit pointer) */
   2583   uint32_t instanceMethods;         /* method_list_t * (32-bit pointer) */
   2584   uint32_t classMethods;            /* method_list_t * (32-bit pointer) */
   2585   uint32_t optionalInstanceMethods; /* method_list_t * (32-bit pointer) */
   2586   uint32_t optionalClassMethods;    /* method_list_t * (32-bit pointer) */
   2587   uint32_t instanceProperties;      /* struct objc_property_list *
   2588                                                        (32-bit pointer) */
   2589 };
   2590 
   2591 struct ivar_list64_t {
   2592   uint32_t entsize;
   2593   uint32_t count;
   2594   /* struct ivar64_t first;  These structures follow inline */
   2595 };
   2596 
   2597 struct ivar_list32_t {
   2598   uint32_t entsize;
   2599   uint32_t count;
   2600   /* struct ivar32_t first;  These structures follow inline */
   2601 };
   2602 
   2603 struct ivar64_t {
   2604   uint64_t offset; /* uintptr_t * (64-bit pointer) */
   2605   uint64_t name;   /* const char * (64-bit pointer) */
   2606   uint64_t type;   /* const char * (64-bit pointer) */
   2607   uint32_t alignment;
   2608   uint32_t size;
   2609 };
   2610 
   2611 struct ivar32_t {
   2612   uint32_t offset; /* uintptr_t * (32-bit pointer) */
   2613   uint32_t name;   /* const char * (32-bit pointer) */
   2614   uint32_t type;   /* const char * (32-bit pointer) */
   2615   uint32_t alignment;
   2616   uint32_t size;
   2617 };
   2618 
   2619 struct objc_property_list64 {
   2620   uint32_t entsize;
   2621   uint32_t count;
   2622   /* struct objc_property64 first;  These structures follow inline */
   2623 };
   2624 
   2625 struct objc_property_list32 {
   2626   uint32_t entsize;
   2627   uint32_t count;
   2628   /* struct objc_property32 first;  These structures follow inline */
   2629 };
   2630 
   2631 struct objc_property64 {
   2632   uint64_t name;       /* const char * (64-bit pointer) */
   2633   uint64_t attributes; /* const char * (64-bit pointer) */
   2634 };
   2635 
   2636 struct objc_property32 {
   2637   uint32_t name;       /* const char * (32-bit pointer) */
   2638   uint32_t attributes; /* const char * (32-bit pointer) */
   2639 };
   2640 
   2641 struct category64_t {
   2642   uint64_t name;               /* const char * (64-bit pointer) */
   2643   uint64_t cls;                /* struct class_t * (64-bit pointer) */
   2644   uint64_t instanceMethods;    /* struct method_list_t * (64-bit pointer) */
   2645   uint64_t classMethods;       /* struct method_list_t * (64-bit pointer) */
   2646   uint64_t protocols;          /* struct protocol_list_t * (64-bit pointer) */
   2647   uint64_t instanceProperties; /* struct objc_property_list *
   2648                                   (64-bit pointer) */
   2649 };
   2650 
   2651 struct category32_t {
   2652   uint32_t name;               /* const char * (32-bit pointer) */
   2653   uint32_t cls;                /* struct class_t * (32-bit pointer) */
   2654   uint32_t instanceMethods;    /* struct method_list_t * (32-bit pointer) */
   2655   uint32_t classMethods;       /* struct method_list_t * (32-bit pointer) */
   2656   uint32_t protocols;          /* struct protocol_list_t * (32-bit pointer) */
   2657   uint32_t instanceProperties; /* struct objc_property_list *
   2658                                   (32-bit pointer) */
   2659 };
   2660 
   2661 struct objc_image_info64 {
   2662   uint32_t version;
   2663   uint32_t flags;
   2664 };
   2665 struct objc_image_info32 {
   2666   uint32_t version;
   2667   uint32_t flags;
   2668 };
   2669 struct imageInfo_t {
   2670   uint32_t version;
   2671   uint32_t flags;
   2672 };
   2673 /* masks for objc_image_info.flags */
   2674 #define OBJC_IMAGE_IS_REPLACEMENT (1 << 0)
   2675 #define OBJC_IMAGE_SUPPORTS_GC (1 << 1)
   2676 
   2677 struct message_ref64 {
   2678   uint64_t imp; /* IMP (64-bit pointer) */
   2679   uint64_t sel; /* SEL (64-bit pointer) */
   2680 };
   2681 
   2682 struct message_ref32 {
   2683   uint32_t imp; /* IMP (32-bit pointer) */
   2684   uint32_t sel; /* SEL (32-bit pointer) */
   2685 };
   2686 
   2687 // Objective-C 1 (32-bit only) meta data structs.
   2688 
   2689 struct objc_module_t {
   2690   uint32_t version;
   2691   uint32_t size;
   2692   uint32_t name;   /* char * (32-bit pointer) */
   2693   uint32_t symtab; /* struct objc_symtab * (32-bit pointer) */
   2694 };
   2695 
   2696 struct objc_symtab_t {
   2697   uint32_t sel_ref_cnt;
   2698   uint32_t refs; /* SEL * (32-bit pointer) */
   2699   uint16_t cls_def_cnt;
   2700   uint16_t cat_def_cnt;
   2701   // uint32_t defs[1];        /* void * (32-bit pointer) variable size */
   2702 };
   2703 
   2704 struct objc_class_t {
   2705   uint32_t isa;         /* struct objc_class * (32-bit pointer) */
   2706   uint32_t super_class; /* struct objc_class * (32-bit pointer) */
   2707   uint32_t name;        /* const char * (32-bit pointer) */
   2708   int32_t version;
   2709   int32_t info;
   2710   int32_t instance_size;
   2711   uint32_t ivars;       /* struct objc_ivar_list * (32-bit pointer) */
   2712   uint32_t methodLists; /* struct objc_method_list ** (32-bit pointer) */
   2713   uint32_t cache;       /* struct objc_cache * (32-bit pointer) */
   2714   uint32_t protocols;   /* struct objc_protocol_list * (32-bit pointer) */
   2715 };
   2716 
   2717 #define CLS_GETINFO(cls, infomask) ((cls)->info & (infomask))
   2718 // class is not a metaclass
   2719 #define CLS_CLASS 0x1
   2720 // class is a metaclass
   2721 #define CLS_META 0x2
   2722 
   2723 struct objc_category_t {
   2724   uint32_t category_name;    /* char * (32-bit pointer) */
   2725   uint32_t class_name;       /* char * (32-bit pointer) */
   2726   uint32_t instance_methods; /* struct objc_method_list * (32-bit pointer) */
   2727   uint32_t class_methods;    /* struct objc_method_list * (32-bit pointer) */
   2728   uint32_t protocols;        /* struct objc_protocol_list * (32-bit ptr) */
   2729 };
   2730 
   2731 struct objc_ivar_t {
   2732   uint32_t ivar_name; /* char * (32-bit pointer) */
   2733   uint32_t ivar_type; /* char * (32-bit pointer) */
   2734   int32_t ivar_offset;
   2735 };
   2736 
   2737 struct objc_ivar_list_t {
   2738   int32_t ivar_count;
   2739   // struct objc_ivar_t ivar_list[1];          /* variable length structure */
   2740 };
   2741 
   2742 struct objc_method_list_t {
   2743   uint32_t obsolete; /* struct objc_method_list * (32-bit pointer) */
   2744   int32_t method_count;
   2745   // struct objc_method_t method_list[1];      /* variable length structure */
   2746 };
   2747 
   2748 struct objc_method_t {
   2749   uint32_t method_name;  /* SEL, aka struct objc_selector * (32-bit pointer) */
   2750   uint32_t method_types; /* char * (32-bit pointer) */
   2751   uint32_t method_imp;   /* IMP, aka function pointer, (*IMP)(id, SEL, ...)
   2752                             (32-bit pointer) */
   2753 };
   2754 
   2755 struct objc_protocol_list_t {
   2756   uint32_t next; /* struct objc_protocol_list * (32-bit pointer) */
   2757   int32_t count;
   2758   // uint32_t list[1];   /* Protocol *, aka struct objc_protocol_t *
   2759   //                        (32-bit pointer) */
   2760 };
   2761 
   2762 struct objc_protocol_t {
   2763   uint32_t isa;              /* struct objc_class * (32-bit pointer) */
   2764   uint32_t protocol_name;    /* char * (32-bit pointer) */
   2765   uint32_t protocol_list;    /* struct objc_protocol_list * (32-bit pointer) */
   2766   uint32_t instance_methods; /* struct objc_method_description_list *
   2767                                 (32-bit pointer) */
   2768   uint32_t class_methods;    /* struct objc_method_description_list *
   2769                                 (32-bit pointer) */
   2770 };
   2771 
   2772 struct objc_method_description_list_t {
   2773   int32_t count;
   2774   // struct objc_method_description_t list[1];
   2775 };
   2776 
   2777 struct objc_method_description_t {
   2778   uint32_t name;  /* SEL, aka struct objc_selector * (32-bit pointer) */
   2779   uint32_t types; /* char * (32-bit pointer) */
   2780 };
   2781 
   2782 inline void swapStruct(struct cfstring64_t &cfs) {
   2783   sys::swapByteOrder(cfs.isa);
   2784   sys::swapByteOrder(cfs.flags);
   2785   sys::swapByteOrder(cfs.characters);
   2786   sys::swapByteOrder(cfs.length);
   2787 }
   2788 
   2789 inline void swapStruct(struct class64_t &c) {
   2790   sys::swapByteOrder(c.isa);
   2791   sys::swapByteOrder(c.superclass);
   2792   sys::swapByteOrder(c.cache);
   2793   sys::swapByteOrder(c.vtable);
   2794   sys::swapByteOrder(c.data);
   2795 }
   2796 
   2797 inline void swapStruct(struct class32_t &c) {
   2798   sys::swapByteOrder(c.isa);
   2799   sys::swapByteOrder(c.superclass);
   2800   sys::swapByteOrder(c.cache);
   2801   sys::swapByteOrder(c.vtable);
   2802   sys::swapByteOrder(c.data);
   2803 }
   2804 
   2805 inline void swapStruct(struct class_ro64_t &cro) {
   2806   sys::swapByteOrder(cro.flags);
   2807   sys::swapByteOrder(cro.instanceStart);
   2808   sys::swapByteOrder(cro.instanceSize);
   2809   sys::swapByteOrder(cro.reserved);
   2810   sys::swapByteOrder(cro.ivarLayout);
   2811   sys::swapByteOrder(cro.name);
   2812   sys::swapByteOrder(cro.baseMethods);
   2813   sys::swapByteOrder(cro.baseProtocols);
   2814   sys::swapByteOrder(cro.ivars);
   2815   sys::swapByteOrder(cro.weakIvarLayout);
   2816   sys::swapByteOrder(cro.baseProperties);
   2817 }
   2818 
   2819 inline void swapStruct(struct class_ro32_t &cro) {
   2820   sys::swapByteOrder(cro.flags);
   2821   sys::swapByteOrder(cro.instanceStart);
   2822   sys::swapByteOrder(cro.instanceSize);
   2823   sys::swapByteOrder(cro.ivarLayout);
   2824   sys::swapByteOrder(cro.name);
   2825   sys::swapByteOrder(cro.baseMethods);
   2826   sys::swapByteOrder(cro.baseProtocols);
   2827   sys::swapByteOrder(cro.ivars);
   2828   sys::swapByteOrder(cro.weakIvarLayout);
   2829   sys::swapByteOrder(cro.baseProperties);
   2830 }
   2831 
   2832 inline void swapStruct(struct method_list64_t &ml) {
   2833   sys::swapByteOrder(ml.entsize);
   2834   sys::swapByteOrder(ml.count);
   2835 }
   2836 
   2837 inline void swapStruct(struct method_list32_t &ml) {
   2838   sys::swapByteOrder(ml.entsize);
   2839   sys::swapByteOrder(ml.count);
   2840 }
   2841 
   2842 inline void swapStruct(struct method64_t &m) {
   2843   sys::swapByteOrder(m.name);
   2844   sys::swapByteOrder(m.types);
   2845   sys::swapByteOrder(m.imp);
   2846 }
   2847 
   2848 inline void swapStruct(struct method32_t &m) {
   2849   sys::swapByteOrder(m.name);
   2850   sys::swapByteOrder(m.types);
   2851   sys::swapByteOrder(m.imp);
   2852 }
   2853 
   2854 inline void swapStruct(struct protocol_list64_t &pl) {
   2855   sys::swapByteOrder(pl.count);
   2856 }
   2857 
   2858 inline void swapStruct(struct protocol_list32_t &pl) {
   2859   sys::swapByteOrder(pl.count);
   2860 }
   2861 
   2862 inline void swapStruct(struct protocol64_t &p) {
   2863   sys::swapByteOrder(p.isa);
   2864   sys::swapByteOrder(p.name);
   2865   sys::swapByteOrder(p.protocols);
   2866   sys::swapByteOrder(p.instanceMethods);
   2867   sys::swapByteOrder(p.classMethods);
   2868   sys::swapByteOrder(p.optionalInstanceMethods);
   2869   sys::swapByteOrder(p.optionalClassMethods);
   2870   sys::swapByteOrder(p.instanceProperties);
   2871 }
   2872 
   2873 inline void swapStruct(struct protocol32_t &p) {
   2874   sys::swapByteOrder(p.isa);
   2875   sys::swapByteOrder(p.name);
   2876   sys::swapByteOrder(p.protocols);
   2877   sys::swapByteOrder(p.instanceMethods);
   2878   sys::swapByteOrder(p.classMethods);
   2879   sys::swapByteOrder(p.optionalInstanceMethods);
   2880   sys::swapByteOrder(p.optionalClassMethods);
   2881   sys::swapByteOrder(p.instanceProperties);
   2882 }
   2883 
   2884 inline void swapStruct(struct ivar_list64_t &il) {
   2885   sys::swapByteOrder(il.entsize);
   2886   sys::swapByteOrder(il.count);
   2887 }
   2888 
   2889 inline void swapStruct(struct ivar_list32_t &il) {
   2890   sys::swapByteOrder(il.entsize);
   2891   sys::swapByteOrder(il.count);
   2892 }
   2893 
   2894 inline void swapStruct(struct ivar64_t &i) {
   2895   sys::swapByteOrder(i.offset);
   2896   sys::swapByteOrder(i.name);
   2897   sys::swapByteOrder(i.type);
   2898   sys::swapByteOrder(i.alignment);
   2899   sys::swapByteOrder(i.size);
   2900 }
   2901 
   2902 inline void swapStruct(struct ivar32_t &i) {
   2903   sys::swapByteOrder(i.offset);
   2904   sys::swapByteOrder(i.name);
   2905   sys::swapByteOrder(i.type);
   2906   sys::swapByteOrder(i.alignment);
   2907   sys::swapByteOrder(i.size);
   2908 }
   2909 
   2910 inline void swapStruct(struct objc_property_list64 &pl) {
   2911   sys::swapByteOrder(pl.entsize);
   2912   sys::swapByteOrder(pl.count);
   2913 }
   2914 
   2915 inline void swapStruct(struct objc_property_list32 &pl) {
   2916   sys::swapByteOrder(pl.entsize);
   2917   sys::swapByteOrder(pl.count);
   2918 }
   2919 
   2920 inline void swapStruct(struct objc_property64 &op) {
   2921   sys::swapByteOrder(op.name);
   2922   sys::swapByteOrder(op.attributes);
   2923 }
   2924 
   2925 inline void swapStruct(struct objc_property32 &op) {
   2926   sys::swapByteOrder(op.name);
   2927   sys::swapByteOrder(op.attributes);
   2928 }
   2929 
   2930 inline void swapStruct(struct category64_t &c) {
   2931   sys::swapByteOrder(c.name);
   2932   sys::swapByteOrder(c.cls);
   2933   sys::swapByteOrder(c.instanceMethods);
   2934   sys::swapByteOrder(c.classMethods);
   2935   sys::swapByteOrder(c.protocols);
   2936   sys::swapByteOrder(c.instanceProperties);
   2937 }
   2938 
   2939 inline void swapStruct(struct category32_t &c) {
   2940   sys::swapByteOrder(c.name);
   2941   sys::swapByteOrder(c.cls);
   2942   sys::swapByteOrder(c.instanceMethods);
   2943   sys::swapByteOrder(c.classMethods);
   2944   sys::swapByteOrder(c.protocols);
   2945   sys::swapByteOrder(c.instanceProperties);
   2946 }
   2947 
   2948 inline void swapStruct(struct objc_image_info64 &o) {
   2949   sys::swapByteOrder(o.version);
   2950   sys::swapByteOrder(o.flags);
   2951 }
   2952 
   2953 inline void swapStruct(struct objc_image_info32 &o) {
   2954   sys::swapByteOrder(o.version);
   2955   sys::swapByteOrder(o.flags);
   2956 }
   2957 
   2958 inline void swapStruct(struct imageInfo_t &o) {
   2959   sys::swapByteOrder(o.version);
   2960   sys::swapByteOrder(o.flags);
   2961 }
   2962 
   2963 inline void swapStruct(struct message_ref64 &mr) {
   2964   sys::swapByteOrder(mr.imp);
   2965   sys::swapByteOrder(mr.sel);
   2966 }
   2967 
   2968 inline void swapStruct(struct message_ref32 &mr) {
   2969   sys::swapByteOrder(mr.imp);
   2970   sys::swapByteOrder(mr.sel);
   2971 }
   2972 
   2973 inline void swapStruct(struct objc_module_t &module) {
   2974   sys::swapByteOrder(module.version);
   2975   sys::swapByteOrder(module.size);
   2976   sys::swapByteOrder(module.name);
   2977   sys::swapByteOrder(module.symtab);
   2978 }
   2979 
   2980 inline void swapStruct(struct objc_symtab_t &symtab) {
   2981   sys::swapByteOrder(symtab.sel_ref_cnt);
   2982   sys::swapByteOrder(symtab.refs);
   2983   sys::swapByteOrder(symtab.cls_def_cnt);
   2984   sys::swapByteOrder(symtab.cat_def_cnt);
   2985 }
   2986 
   2987 inline void swapStruct(struct objc_class_t &objc_class) {
   2988   sys::swapByteOrder(objc_class.isa);
   2989   sys::swapByteOrder(objc_class.super_class);
   2990   sys::swapByteOrder(objc_class.name);
   2991   sys::swapByteOrder(objc_class.version);
   2992   sys::swapByteOrder(objc_class.info);
   2993   sys::swapByteOrder(objc_class.instance_size);
   2994   sys::swapByteOrder(objc_class.ivars);
   2995   sys::swapByteOrder(objc_class.methodLists);
   2996   sys::swapByteOrder(objc_class.cache);
   2997   sys::swapByteOrder(objc_class.protocols);
   2998 }
   2999 
   3000 inline void swapStruct(struct objc_category_t &objc_category) {
   3001   sys::swapByteOrder(objc_category.category_name);
   3002   sys::swapByteOrder(objc_category.class_name);
   3003   sys::swapByteOrder(objc_category.instance_methods);
   3004   sys::swapByteOrder(objc_category.class_methods);
   3005   sys::swapByteOrder(objc_category.protocols);
   3006 }
   3007 
   3008 inline void swapStruct(struct objc_ivar_list_t &objc_ivar_list) {
   3009   sys::swapByteOrder(objc_ivar_list.ivar_count);
   3010 }
   3011 
   3012 inline void swapStruct(struct objc_ivar_t &objc_ivar) {
   3013   sys::swapByteOrder(objc_ivar.ivar_name);
   3014   sys::swapByteOrder(objc_ivar.ivar_type);
   3015   sys::swapByteOrder(objc_ivar.ivar_offset);
   3016 }
   3017 
   3018 inline void swapStruct(struct objc_method_list_t &method_list) {
   3019   sys::swapByteOrder(method_list.obsolete);
   3020   sys::swapByteOrder(method_list.method_count);
   3021 }
   3022 
   3023 inline void swapStruct(struct objc_method_t &method) {
   3024   sys::swapByteOrder(method.method_name);
   3025   sys::swapByteOrder(method.method_types);
   3026   sys::swapByteOrder(method.method_imp);
   3027 }
   3028 
   3029 inline void swapStruct(struct objc_protocol_list_t &protocol_list) {
   3030   sys::swapByteOrder(protocol_list.next);
   3031   sys::swapByteOrder(protocol_list.count);
   3032 }
   3033 
   3034 inline void swapStruct(struct objc_protocol_t &protocol) {
   3035   sys::swapByteOrder(protocol.isa);
   3036   sys::swapByteOrder(protocol.protocol_name);
   3037   sys::swapByteOrder(protocol.protocol_list);
   3038   sys::swapByteOrder(protocol.instance_methods);
   3039   sys::swapByteOrder(protocol.class_methods);
   3040 }
   3041 
   3042 inline void swapStruct(struct objc_method_description_list_t &mdl) {
   3043   sys::swapByteOrder(mdl.count);
   3044 }
   3045 
   3046 inline void swapStruct(struct objc_method_description_t &md) {
   3047   sys::swapByteOrder(md.name);
   3048   sys::swapByteOrder(md.types);
   3049 }
   3050 
   3051 static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
   3052                                                  struct DisassembleInfo *info);
   3053 
   3054 // get_objc2_64bit_class_name() is used for disassembly and is passed a pointer
   3055 // to an Objective-C class and returns the class name.  It is also passed the
   3056 // address of the pointer, so when the pointer is zero as it can be in an .o
   3057 // file, that is used to look for an external relocation entry with a symbol
   3058 // name.
   3059 static const char *get_objc2_64bit_class_name(uint64_t pointer_value,
   3060                                               uint64_t ReferenceValue,
   3061                                               struct DisassembleInfo *info) {
   3062   const char *r;
   3063   uint32_t offset, left;
   3064   SectionRef S;
   3065 
   3066   // The pointer_value can be 0 in an object file and have a relocation
   3067   // entry for the class symbol at the ReferenceValue (the address of the
   3068   // pointer).
   3069   if (pointer_value == 0) {
   3070     r = get_pointer_64(ReferenceValue, offset, left, S, info);
   3071     if (r == nullptr || left < sizeof(uint64_t))
   3072       return nullptr;
   3073     uint64_t n_value;
   3074     const char *symbol_name = get_symbol_64(offset, S, info, n_value);
   3075     if (symbol_name == nullptr)
   3076       return nullptr;
   3077     const char *class_name = strrchr(symbol_name, '$');
   3078     if (class_name != nullptr && class_name[1] == '_' && class_name[2] != '\0')
   3079       return class_name + 2;
   3080     else
   3081       return nullptr;
   3082   }
   3083 
   3084   // The case were the pointer_value is non-zero and points to a class defined
   3085   // in this Mach-O file.
   3086   r = get_pointer_64(pointer_value, offset, left, S, info);
   3087   if (r == nullptr || left < sizeof(struct class64_t))
   3088     return nullptr;
   3089   struct class64_t c;
   3090   memcpy(&c, r, sizeof(struct class64_t));
   3091   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
   3092     swapStruct(c);
   3093   if (c.data == 0)
   3094     return nullptr;
   3095   r = get_pointer_64(c.data, offset, left, S, info);
   3096   if (r == nullptr || left < sizeof(struct class_ro64_t))
   3097     return nullptr;
   3098   struct class_ro64_t cro;
   3099   memcpy(&cro, r, sizeof(struct class_ro64_t));
   3100   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
   3101     swapStruct(cro);
   3102   if (cro.name == 0)
   3103     return nullptr;
   3104   const char *name = get_pointer_64(cro.name, offset, left, S, info);
   3105   return name;
   3106 }
   3107 
   3108 // get_objc2_64bit_cfstring_name is used for disassembly and is passed a
   3109 // pointer to a cfstring and returns its name or nullptr.
   3110 static const char *get_objc2_64bit_cfstring_name(uint64_t ReferenceValue,
   3111                                                  struct DisassembleInfo *info) {
   3112   const char *r, *name;
   3113   uint32_t offset, left;
   3114   SectionRef S;
   3115   struct cfstring64_t cfs;
   3116   uint64_t cfs_characters;
   3117 
   3118   r = get_pointer_64(ReferenceValue, offset, left, S, info);
   3119   if (r == nullptr || left < sizeof(struct cfstring64_t))
   3120     return nullptr;
   3121   memcpy(&cfs, r, sizeof(struct cfstring64_t));
   3122   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
   3123     swapStruct(cfs);
   3124   if (cfs.characters == 0) {
   3125     uint64_t n_value;
   3126     const char *symbol_name = get_symbol_64(
   3127         offset + offsetof(struct cfstring64_t, characters), S, info, n_value);
   3128     if (symbol_name == nullptr)
   3129       return nullptr;
   3130     cfs_characters = n_value;
   3131   } else
   3132     cfs_characters = cfs.characters;
   3133   name = get_pointer_64(cfs_characters, offset, left, S, info);
   3134 
   3135   return name;
   3136 }
   3137 
   3138 // get_objc2_64bit_selref() is used for disassembly and is passed a the address
   3139 // of a pointer to an Objective-C selector reference when the pointer value is
   3140 // zero as in a .o file and is likely to have a external relocation entry with
   3141 // who's symbol's n_value is the real pointer to the selector name.  If that is
   3142 // the case the real pointer to the selector name is returned else 0 is
   3143 // returned
   3144 static uint64_t get_objc2_64bit_selref(uint64_t ReferenceValue,
   3145                                        struct DisassembleInfo *info) {
   3146   uint32_t offset, left;
   3147   SectionRef S;
   3148 
   3149   const char *r = get_pointer_64(ReferenceValue, offset, left, S, info);
   3150   if (r == nullptr || left < sizeof(uint64_t))
   3151     return 0;
   3152   uint64_t n_value;
   3153   const char *symbol_name = get_symbol_64(offset, S, info, n_value);
   3154   if (symbol_name == nullptr)
   3155     return 0;
   3156   return n_value;
   3157 }
   3158 
   3159 static const SectionRef get_section(MachOObjectFile *O, const char *segname,
   3160                                     const char *sectname) {
   3161   for (const SectionRef &Section : O->sections()) {
   3162     StringRef SectName;
   3163     Section.getName(SectName);
   3164     DataRefImpl Ref = Section.getRawDataRefImpl();
   3165     StringRef SegName = O->getSectionFinalSegmentName(Ref);
   3166     if (SegName == segname && SectName == sectname)
   3167       return Section;
   3168   }
   3169   return SectionRef();
   3170 }
   3171 
   3172 static void
   3173 walk_pointer_list_64(const char *listname, const SectionRef S,
   3174                      MachOObjectFile *O, struct DisassembleInfo *info,
   3175                      void (*func)(uint64_t, struct DisassembleInfo *info)) {
   3176   if (S == SectionRef())
   3177     return;
   3178 
   3179   StringRef SectName;
   3180   S.getName(SectName);
   3181   DataRefImpl Ref = S.getRawDataRefImpl();
   3182   StringRef SegName = O->getSectionFinalSegmentName(Ref);
   3183   outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
   3184 
   3185   StringRef BytesStr;
   3186   S.getContents(BytesStr);
   3187   const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
   3188 
   3189   for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint64_t)) {
   3190     uint32_t left = S.getSize() - i;
   3191     uint32_t size = left < sizeof(uint64_t) ? left : sizeof(uint64_t);
   3192     uint64_t p = 0;
   3193     memcpy(&p, Contents + i, size);
   3194     if (i + sizeof(uint64_t) > S.getSize())
   3195       outs() << listname << " list pointer extends past end of (" << SegName
   3196              << "," << SectName << ") section\n";
   3197     outs() << format("%016" PRIx64, S.getAddress() + i) << " ";
   3198 
   3199     if (O->isLittleEndian() != sys::IsLittleEndianHost)
   3200       sys::swapByteOrder(p);
   3201 
   3202     uint64_t n_value = 0;
   3203     const char *name = get_symbol_64(i, S, info, n_value, p);
   3204     if (name == nullptr)
   3205       name = get_dyld_bind_info_symbolname(S.getAddress() + i, info);
   3206 
   3207     if (n_value != 0) {
   3208       outs() << format("0x%" PRIx64, n_value);
   3209       if (p != 0)
   3210         outs() << " + " << format("0x%" PRIx64, p);
   3211     } else
   3212       outs() << format("0x%" PRIx64, p);
   3213     if (name != nullptr)
   3214       outs() << " " << name;
   3215     outs() << "\n";
   3216 
   3217     p += n_value;
   3218     if (func)
   3219       func(p, info);
   3220   }
   3221 }
   3222 
   3223 static void
   3224 walk_pointer_list_32(const char *listname, const SectionRef S,
   3225                      MachOObjectFile *O, struct DisassembleInfo *info,
   3226                      void (*func)(uint32_t, struct DisassembleInfo *info)) {
   3227   if (S == SectionRef())
   3228     return;
   3229 
   3230   StringRef SectName;
   3231   S.getName(SectName);
   3232   DataRefImpl Ref = S.getRawDataRefImpl();
   3233   StringRef SegName = O->getSectionFinalSegmentName(Ref);
   3234   outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
   3235 
   3236   StringRef BytesStr;
   3237   S.getContents(BytesStr);
   3238   const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
   3239 
   3240   for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint32_t)) {
   3241     uint32_t left = S.getSize() - i;
   3242     uint32_t size = left < sizeof(uint32_t) ? left : sizeof(uint32_t);
   3243     uint32_t p = 0;
   3244     memcpy(&p, Contents + i, size);
   3245     if (i + sizeof(uint32_t) > S.getSize())
   3246       outs() << listname << " list pointer extends past end of (" << SegName
   3247              << "," << SectName << ") section\n";
   3248     uint32_t Address = S.getAddress() + i;
   3249     outs() << format("%08" PRIx32, Address) << " ";
   3250 
   3251     if (O->isLittleEndian() != sys::IsLittleEndianHost)
   3252       sys::swapByteOrder(p);
   3253     outs() << format("0x%" PRIx32, p);
   3254 
   3255     const char *name = get_symbol_32(i, S, info, p);
   3256     if (name != nullptr)
   3257       outs() << " " << name;
   3258     outs() << "\n";
   3259 
   3260     if (func)
   3261       func(p, info);
   3262   }
   3263 }
   3264 
   3265 static void print_layout_map(const char *layout_map, uint32_t left) {
   3266   if (layout_map == nullptr)
   3267     return;
   3268   outs() << "                layout map: ";
   3269   do {
   3270     outs() << format("0x%02" PRIx32, (*layout_map) & 0xff) << " ";
   3271     left--;
   3272     layout_map++;
   3273   } while (*layout_map != '\0' && left != 0);
   3274   outs() << "\n";
   3275 }
   3276 
   3277 static void print_layout_map64(uint64_t p, struct DisassembleInfo *info) {
   3278   uint32_t offset, left;
   3279   SectionRef S;
   3280   const char *layout_map;
   3281 
   3282   if (p == 0)
   3283     return;
   3284   layout_map = get_pointer_64(p, offset, left, S, info);
   3285   print_layout_map(layout_map, left);
   3286 }
   3287 
   3288 static void print_layout_map32(uint32_t p, struct DisassembleInfo *info) {
   3289   uint32_t offset, left;
   3290   SectionRef S;
   3291   const char *layout_map;
   3292 
   3293   if (p == 0)
   3294     return;
   3295   layout_map = get_pointer_32(p, offset, left, S, info);
   3296   print_layout_map(layout_map, left);
   3297 }
   3298 
   3299 static void print_method_list64_t(uint64_t p, struct DisassembleInfo *info,
   3300                                   const char *indent) {
   3301   struct method_list64_t ml;
   3302   struct method64_t m;
   3303   const char *r;
   3304   uint32_t offset, xoffset, left, i;
   3305   SectionRef S, xS;
   3306   const char *name, *sym_name;
   3307   uint64_t n_value;
   3308 
   3309   r = get_pointer_64(p, offset, left, S, info);
   3310   if (r == nullptr)
   3311     return;
   3312   memset(&ml, '\0', sizeof(struct method_list64_t));
   3313   if (left < sizeof(struct method_list64_t)) {
   3314     memcpy(&ml, r, left);
   3315     outs() << "   (method_list_t entends past the end of the section)\n";
   3316   } else
   3317     memcpy(&ml, r, sizeof(struct method_list64_t));
   3318   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
   3319     swapStruct(ml);
   3320   outs() << indent << "\t\t   entsize " << ml.entsize << "\n";
   3321   outs() << indent << "\t\t     count " << ml.count << "\n";
   3322 
   3323   p += sizeof(struct method_list64_t);
   3324   offset += sizeof(struct method_list64_t);
   3325   for (i = 0; i < ml.count; i++) {
   3326     r = get_pointer_64(p, offset, left, S, info);
   3327     if (r == nullptr)
   3328       return;
   3329     memset(&m, '\0', sizeof(struct method64_t));
   3330     if (left < sizeof(struct method64_t)) {
   3331       memcpy(&m, r, left);
   3332       outs() << indent << "   (method_t extends past the end of the section)\n";
   3333     } else
   3334       memcpy(&m, r, sizeof(struct method64_t));
   3335     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
   3336       swapStruct(m);
   3337 
   3338     outs() << indent << "\t\t      name ";
   3339     sym_name = get_symbol_64(offset + offsetof(struct method64_t, name), S,
   3340                              info, n_value, m.name);
   3341     if (n_value != 0) {
   3342       if (info->verbose && sym_name != nullptr)
   3343         outs() << sym_name;
   3344       else
   3345         outs() << format("0x%" PRIx64, n_value);
   3346       if (m.name != 0)
   3347         outs() << " + " << format("0x%" PRIx64, m.name);
   3348     } else
   3349       outs() << format("0x%" PRIx64, m.name);
   3350     name = get_pointer_64(m.name + n_value, xoffset, left, xS, info);
   3351     if (name != nullptr)
   3352       outs() << format(" %.*s", left, name);
   3353     outs() << "\n";
   3354 
   3355     outs() << indent << "\t\t     types ";
   3356     sym_name = get_symbol_64(offset + offsetof(struct method64_t, types), S,
   3357                              info, n_value, m.types);
   3358     if (n_value != 0) {
   3359       if (info->verbose && sym_name != nullptr)
   3360         outs() << sym_name;
   3361       else
   3362         outs() << format("0x%" PRIx64, n_value);
   3363       if (m.types != 0)
   3364         outs() << " + " << format("0x%" PRIx64, m.types);
   3365     } else
   3366       outs() << format("0x%" PRIx64, m.types);
   3367     name = get_pointer_64(m.types + n_value, xoffset, left, xS, info);
   3368     if (name != nullptr)
   3369       outs() << format(" %.*s", left, name);
   3370     outs() << "\n";
   3371 
   3372     outs() << indent << "\t\t       imp ";
   3373     name = get_symbol_64(offset + offsetof(struct method64_t, imp), S, info,
   3374                          n_value, m.imp);
   3375     if (info->verbose && name == nullptr) {
   3376       if (n_value != 0) {
   3377         outs() << format("0x%" PRIx64, n_value) << " ";
   3378         if (m.imp != 0)
   3379           outs() << "+ " << format("0x%" PRIx64, m.imp) << " ";
   3380       } else
   3381         outs() << format("0x%" PRIx64, m.imp) << " ";
   3382     }
   3383     if (name != nullptr)
   3384       outs() << name;
   3385     outs() << "\n";
   3386 
   3387     p += sizeof(struct method64_t);
   3388     offset += sizeof(struct method64_t);
   3389   }
   3390 }
   3391 
   3392 static void print_method_list32_t(uint64_t p, struct DisassembleInfo *info,
   3393                                   const char *indent) {
   3394   struct method_list32_t ml;
   3395   struct method32_t m;
   3396   const char *r, *name;
   3397   uint32_t offset, xoffset, left, i;
   3398   SectionRef S, xS;
   3399 
   3400   r = get_pointer_32(p, offset, left, S, info);
   3401   if (r == nullptr)
   3402     return;
   3403   memset(&ml, '\0', sizeof(struct method_list32_t));
   3404   if (left < sizeof(struct method_list32_t)) {
   3405     memcpy(&ml, r, left);
   3406     outs() << "   (method_list_t entends past the end of the section)\n";
   3407   } else
   3408     memcpy(&ml, r, sizeof(struct method_list32_t));
   3409   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
   3410     swapStruct(ml);
   3411   outs() << indent << "\t\t   entsize " << ml.entsize << "\n";
   3412   outs() << indent << "\t\t     count " << ml.count << "\n";
   3413 
   3414   p += sizeof(struct method_list32_t);
   3415   offset += sizeof(struct method_list32_t);
   3416   for (i = 0; i < ml.count; i++) {
   3417     r = get_pointer_32(p, offset, left, S, info);
   3418     if (r == nullptr)
   3419       return;
   3420     memset(&m, '\0', sizeof(struct method32_t));
   3421     if (left < sizeof(struct method32_t)) {
   3422       memcpy(&ml, r, left);
   3423       outs() << indent << "   (method_t entends past the end of the section)\n";
   3424     } else
   3425       memcpy(&m, r, sizeof(struct method32_t));
   3426     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
   3427       swapStruct(m);
   3428 
   3429     outs() << indent << "\t\t      name " << format("0x%" PRIx32, m.name);
   3430     name = get_pointer_32(m.name, xoffset, left, xS, info);
   3431     if (name != nullptr)
   3432       outs() << format(" %.*s", left, name);
   3433     outs() << "\n";
   3434 
   3435     outs() << indent << "\t\t     types " << format("0x%" PRIx32, m.types);
   3436     name = get_pointer_32(m.types, xoffset, left, xS, info);
   3437     if (name != nullptr)
   3438       outs() << format(" %.*s", left, name);
   3439     outs() << "\n";
   3440 
   3441     outs() << indent << "\t\t       imp " << format("0x%" PRIx32, m.imp);
   3442     name = get_symbol_32(offset + offsetof(struct method32_t, imp), S, info,
   3443                          m.imp);
   3444     if (name != nullptr)
   3445       outs() << " " << name;
   3446     outs() << "\n";
   3447 
   3448     p += sizeof(struct method32_t);
   3449     offset += sizeof(struct method32_t);
   3450   }
   3451 }
   3452 
   3453 static bool print_method_list(uint32_t p, struct DisassembleInfo *info) {
   3454   uint32_t offset, left, xleft;
   3455   SectionRef S;
   3456   struct objc_method_list_t method_list;
   3457   struct objc_method_t method;
   3458   const char *r, *methods, *name, *SymbolName;
   3459   int32_t i;
   3460 
   3461   r = get_pointer_32(p, offset, left, S, info, true);
   3462   if (r == nullptr)
   3463     return true;
   3464 
   3465   outs() << "\n";
   3466   if (left > sizeof(struct objc_method_list_t)) {
   3467     memcpy(&method_list, r, sizeof(struct objc_method_list_t));
   3468   } else {
   3469     outs() << "\t\t objc_method_list extends past end of the section\n";
   3470     memset(&method_list, '\0', sizeof(struct objc_method_list_t));
   3471     memcpy(&method_list, r, left);
   3472   }
   3473   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
   3474     swapStruct(method_list);
   3475 
   3476   outs() << "\t\t         obsolete "
   3477          << format("0x%08" PRIx32, method_list.obsolete) << "\n";
   3478   outs() << "\t\t     method_count " << method_list.method_count << "\n";
   3479 
   3480   methods = r + sizeof(struct objc_method_list_t);
   3481   for (i = 0; i < method_list.method_count; i++) {
   3482     if ((i + 1) * sizeof(struct objc_method_t) > left) {
   3483       outs() << "\t\t remaining method's extend past the of the section\n";
   3484       break;
   3485     }
   3486     memcpy(&method, methods + i * sizeof(struct objc_method_t),
   3487            sizeof(struct objc_method_t));
   3488     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
   3489       swapStruct(method);
   3490 
   3491     outs() << "\t\t      method_name "
   3492            << format("0x%08" PRIx32, method.method_name);
   3493     if (info->verbose) {
   3494       name = get_pointer_32(method.method_name, offset, xleft, S, info, true);
   3495       if (name != nullptr)
   3496         outs() << format(" %.*s", xleft, name);
   3497       else
   3498         outs() << " (not in an __OBJC section)";
   3499     }
   3500     outs() << "\n";
   3501 
   3502     outs() << "\t\t     method_types "
   3503            << format("0x%08" PRIx32, method.method_types);
   3504     if (info->verbose) {
   3505       name = get_pointer_32(method.method_types, offset, xleft, S, info, true);
   3506       if (name != nullptr)
   3507         outs() << format(" %.*s", xleft, name);
   3508       else
   3509         outs() << " (not in an __OBJC section)";
   3510     }
   3511     outs() << "\n";
   3512 
   3513     outs() << "\t\t       method_imp "
   3514            << format("0x%08" PRIx32, method.method_imp) << " ";
   3515     if (info->verbose) {
   3516       SymbolName = GuessSymbolName(method.method_imp, info->AddrMap);
   3517       if (SymbolName != nullptr)
   3518         outs() << SymbolName;
   3519     }
   3520     outs() << "\n";
   3521   }
   3522   return false;
   3523 }
   3524 
   3525 static void print_protocol_list64_t(uint64_t p, struct DisassembleInfo *info) {
   3526   struct protocol_list64_t pl;
   3527   uint64_t q, n_value;
   3528   struct protocol64_t pc;
   3529   const char *r;
   3530   uint32_t offset, xoffset, left, i;
   3531   SectionRef S, xS;
   3532   const char *name, *sym_name;
   3533 
   3534   r = get_pointer_64(p, offset, left, S, info);
   3535   if (r == nullptr)
   3536     return;
   3537   memset(&pl, '\0', sizeof(struct protocol_list64_t));
   3538   if (left < sizeof(struct protocol_list64_t)) {
   3539     memcpy(&pl, r, left);
   3540     outs() << "   (protocol_list_t entends past the end of the section)\n";
   3541   } else
   3542     memcpy(&pl, r, sizeof(struct protocol_list64_t));
   3543   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
   3544     swapStruct(pl);
   3545   outs() << "                      count " << pl.count << "\n";
   3546 
   3547   p += sizeof(struct protocol_list64_t);
   3548   offset += sizeof(struct protocol_list64_t);
   3549   for (i = 0; i < pl.count; i++) {
   3550     r = get_pointer_64(p, offset, left, S, info);
   3551     if (r == nullptr)
   3552       return;
   3553     q = 0;
   3554     if (left < sizeof(uint64_t)) {
   3555       memcpy(&q, r, left);
   3556       outs() << "   (protocol_t * entends past the end of the section)\n";
   3557     } else
   3558       memcpy(&q, r, sizeof(uint64_t));
   3559     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
   3560       sys::swapByteOrder(q);
   3561 
   3562     outs() << "\t\t      list[" << i << "] ";
   3563     sym_name = get_symbol_64(offset, S, info, n_value, q);
   3564     if (n_value != 0) {
   3565       if (info->verbose && sym_name != nullptr)
   3566         outs() << sym_name;
   3567       else
   3568         outs() << format("0x%" PRIx64, n_value);
   3569       if (q != 0)
   3570         outs() << " + " << format("0x%" PRIx64, q);
   3571     } else
   3572       outs() << format("0x%" PRIx64, q);
   3573     outs() << " (struct protocol_t *)\n";
   3574 
   3575     r = get_pointer_64(q + n_value, offset, left, S, info);
   3576     if (r == nullptr)
   3577       return;
   3578     memset(&pc, '\0', sizeof(struct protocol64_t));
   3579     if (left < sizeof(struct protocol64_t)) {
   3580       memcpy(&pc, r, left);
   3581       outs() << "   (protocol_t entends past the end of the section)\n";
   3582     } else
   3583       memcpy(&pc, r, sizeof(struct protocol64_t));
   3584     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
   3585       swapStruct(pc);
   3586 
   3587     outs() << "\t\t\t      isa " << format("0x%" PRIx64, pc.isa) << "\n";
   3588 
   3589     outs() << "\t\t\t     name ";
   3590     sym_name = get_symbol_64(offset + offsetof(struct protocol64_t, name), S,
   3591                              info, n_value, pc.name);
   3592     if (n_value != 0) {
   3593       if (info->verbose && sym_name != nullptr)
   3594         outs() << sym_name;
   3595       else
   3596         outs() << format("0x%" PRIx64, n_value);
   3597       if (pc.name != 0)
   3598         outs() << " + " << format("0x%" PRIx64, pc.name);
   3599     } else
   3600       outs() << format("0x%" PRIx64, pc.name);
   3601     name = get_pointer_64(pc.name + n_value, xoffset, left, xS, info);
   3602     if (name != nullptr)
   3603       outs() << format(" %.*s", left, name);
   3604     outs() << "\n";
   3605 
   3606     outs() << "\t\t\tprotocols " << format("0x%" PRIx64, pc.protocols) << "\n";
   3607 
   3608     outs() << "\t\t  instanceMethods ";
   3609     sym_name =
   3610         get_symbol_64(offset + offsetof(struct protocol64_t, instanceMethods),
   3611                       S, info, n_value, pc.instanceMethods);
   3612     if (n_value != 0) {
   3613       if (info->verbose && sym_name != nullptr)
   3614         outs() << sym_name;
   3615       else
   3616         outs() << format("0x%" PRIx64, n_value);
   3617       if (pc.instanceMethods != 0)
   3618         outs() << " + " << format("0x%" PRIx64, pc.instanceMethods);
   3619     } else
   3620       outs() << format("0x%" PRIx64, pc.instanceMethods);
   3621     outs() << " (struct method_list_t *)\n";
   3622     if (pc.instanceMethods + n_value != 0)
   3623       print_method_list64_t(pc.instanceMethods + n_value, info, "\t");
   3624 
   3625     outs() << "\t\t     classMethods ";
   3626     sym_name =
   3627         get_symbol_64(offset + offsetof(struct protocol64_t, classMethods), S,
   3628                       info, n_value, pc.classMethods);
   3629     if (n_value != 0) {
   3630       if (info->verbose && sym_name != nullptr)
   3631         outs() << sym_name;
   3632       else
   3633         outs() << format("0x%" PRIx64, n_value);
   3634       if (pc.classMethods != 0)
   3635         outs() << " + " << format("0x%" PRIx64, pc.classMethods);
   3636     } else
   3637       outs() << format("0x%" PRIx64, pc.classMethods);
   3638     outs() << " (struct method_list_t *)\n";
   3639     if (pc.classMethods + n_value != 0)
   3640       print_method_list64_t(pc.classMethods + n_value, info, "\t");
   3641 
   3642     outs() << "\t  optionalInstanceMethods "
   3643            << format("0x%" PRIx64, pc.optionalInstanceMethods) << "\n";
   3644     outs() << "\t     optionalClassMethods "
   3645            << format("0x%" PRIx64, pc.optionalClassMethods) << "\n";
   3646     outs() << "\t       instanceProperties "
   3647            << format("0x%" PRIx64, pc.instanceProperties) << "\n";
   3648 
   3649     p += sizeof(uint64_t);
   3650     offset += sizeof(uint64_t);
   3651   }
   3652 }
   3653 
   3654 static void print_protocol_list32_t(uint32_t p, struct DisassembleInfo *info) {
   3655   struct protocol_list32_t pl;
   3656   uint32_t q;
   3657   struct protocol32_t pc;
   3658   const char *r;
   3659   uint32_t offset, xoffset, left, i;
   3660   SectionRef S, xS;
   3661   const char *name;
   3662 
   3663   r = get_pointer_32(p, offset, left, S, info);
   3664   if (r == nullptr)
   3665     return;
   3666   memset(&pl, '\0', sizeof(struct protocol_list32_t));
   3667   if (left < sizeof(struct protocol_list32_t)) {
   3668     memcpy(&pl, r, left);
   3669     outs() << "   (protocol_list_t entends past the end of the section)\n";
   3670   } else
   3671     memcpy(&pl, r, sizeof(struct protocol_list32_t));
   3672   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
   3673     swapStruct(pl);
   3674   outs() << "                      count " << pl.count << "\n";
   3675 
   3676   p += sizeof(struct protocol_list32_t);
   3677   offset += sizeof(struct protocol_list32_t);
   3678   for (i = 0; i < pl.count; i++) {
   3679     r = get_pointer_32(p, offset, left, S, info);
   3680     if (r == nullptr)
   3681       return;
   3682     q = 0;
   3683     if (left < sizeof(uint32_t)) {
   3684       memcpy(&q, r, left);
   3685       outs() << "   (protocol_t * entends past the end of the section)\n";
   3686     } else
   3687       memcpy(&q, r, sizeof(uint32_t));
   3688     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
   3689       sys::swapByteOrder(q);
   3690     outs() << "\t\t      list[" << i << "] " << format("0x%" PRIx32, q)
   3691            << " (struct protocol_t *)\n";
   3692     r = get_pointer_32(q, offset, left, S, info);
   3693     if (r == nullptr)
   3694       return;
   3695     memset(&pc, '\0', sizeof(struct protocol32_t));
   3696     if (left < sizeof(struct protocol32_t)) {
   3697       memcpy(&pc, r, left);
   3698       outs() << "   (protocol_t entends past the end of the section)\n";
   3699     } else
   3700       memcpy(&pc, r, sizeof(struct protocol32_t));
   3701     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
   3702       swapStruct(pc);
   3703     outs() << "\t\t\t      isa " << format("0x%" PRIx32, pc.isa) << "\n";
   3704     outs() << "\t\t\t     name " << format("0x%" PRIx32, pc.name);
   3705     name = get_pointer_32(pc.name, xoffset, left, xS, info);
   3706     if (name != nullptr)
   3707       outs() << format(" %.*s", left, name);
   3708     outs() << "\n";
   3709     outs() << "\t\t\tprotocols " << format("0x%" PRIx32, pc.protocols) << "\n";
   3710     outs() << "\t\t  instanceMethods "
   3711            << format("0x%" PRIx32, pc.instanceMethods)
   3712            << " (struct method_list_t *)\n";
   3713     if (pc.instanceMethods != 0)
   3714       print_method_list32_t(pc.instanceMethods, info, "\t");
   3715     outs() << "\t\t     classMethods " << format("0x%" PRIx32, pc.classMethods)
   3716            << " (struct method_list_t *)\n";
   3717     if (pc.classMethods != 0)
   3718       print_method_list32_t(pc.classMethods, info, "\t");
   3719     outs() << "\t  optionalInstanceMethods "
   3720            << format("0x%" PRIx32, pc.optionalInstanceMethods) << "\n";
   3721     outs() << "\t     optionalClassMethods "
   3722            << format("0x%" PRIx32, pc.optionalClassMethods) << "\n";
   3723     outs() << "\t       instanceProperties "
   3724            << format("0x%" PRIx32, pc.instanceProperties) << "\n";
   3725     p += sizeof(uint32_t);
   3726     offset += sizeof(uint32_t);
   3727   }
   3728 }
   3729 
   3730 static void print_indent(uint32_t indent) {
   3731   for (uint32_t i = 0; i < indent;) {
   3732     if (indent - i >= 8) {
   3733       outs() << "\t";
   3734       i += 8;
   3735     } else {
   3736       for (uint32_t j = i; j < indent; j++)
   3737         outs() << " ";
   3738       return;
   3739     }
   3740   }
   3741 }
   3742 
   3743 static bool print_method_description_list(uint32_t p, uint32_t indent,
   3744                                           struct DisassembleInfo *info) {
   3745   uint32_t offset, left, xleft;
   3746   SectionRef S;
   3747   struct objc_method_description_list_t mdl;
   3748   struct objc_method_description_t md;
   3749   const char *r, *list, *name;
   3750   int32_t i;
   3751 
   3752   r = get_pointer_32(p, offset, left, S, info, true);
   3753   if (r == nullptr)
   3754     return true;
   3755 
   3756   outs() << "\n";
   3757   if (left > sizeof(struct objc_method_description_list_t)) {
   3758     memcpy(&mdl, r, sizeof(struct objc_method_description_list_t));
   3759   } else {
   3760     print_indent(indent);
   3761     outs() << " objc_method_description_list extends past end of the section\n";
   3762     memset(&mdl, '\0', sizeof(struct objc_method_description_list_t));
   3763     memcpy(&mdl, r, left);
   3764   }
   3765   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
   3766     swapStruct(mdl);
   3767 
   3768   print_indent(indent);
   3769   outs() << "        count " << mdl.count << "\n";
   3770 
   3771   list = r + sizeof(struct objc_method_description_list_t);
   3772   for (i = 0; i < mdl.count; i++) {
   3773     if ((i + 1) * sizeof(struct objc_method_description_t) > left) {
   3774       print_indent(indent);
   3775       outs() << " remaining list entries extend past the of the section\n";
   3776       break;
   3777     }
   3778     print_indent(indent);
   3779     outs() << "        list[" << i << "]\n";
   3780     memcpy(&md, list + i * sizeof(struct objc_method_description_t),
   3781            sizeof(struct objc_method_description_t));
   3782     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
   3783       swapStruct(md);
   3784 
   3785     print_indent(indent);
   3786     outs() << "             name " << format("0x%08" PRIx32, md.name);
   3787     if (info->verbose) {
   3788       name = get_pointer_32(md.name, offset, xleft, S, info, true);
   3789       if (name != nullptr)
   3790         outs() << format(" %.*s", xleft, name);
   3791       else
   3792         outs() << " (not in an __OBJC section)";
   3793     }
   3794     outs() << "\n";
   3795 
   3796     print_indent(indent);
   3797     outs() << "            types " << format("0x%08" PRIx32, md.types);
   3798     if (info->verbose) {
   3799       name = get_pointer_32(md.types, offset, xleft, S, info, true);
   3800       if (name != nullptr)
   3801         outs() << format(" %.*s", xleft, name);
   3802       else
   3803         outs() << " (not in an __OBJC section)";
   3804     }
   3805     outs() << "\n";
   3806   }
   3807   return false;
   3808 }
   3809 
   3810 static bool print_protocol_list(uint32_t p, uint32_t indent,
   3811                                 struct DisassembleInfo *info);
   3812 
   3813 static bool print_protocol(uint32_t p, uint32_t indent,
   3814                            struct DisassembleInfo *info) {
   3815   uint32_t offset, left;
   3816   SectionRef S;
   3817   struct objc_protocol_t protocol;
   3818   const char *r, *name;
   3819 
   3820   r = get_pointer_32(p, offset, left, S, info, true);
   3821   if (r == nullptr)
   3822     return true;
   3823 
   3824   outs() << "\n";
   3825   if (left >= sizeof(struct objc_protocol_t)) {
   3826     memcpy(&protocol, r, sizeof(struct objc_protocol_t));
   3827   } else {
   3828     print_indent(indent);
   3829     outs() << "            Protocol extends past end of the section\n";
   3830     memset(&protocol, '\0', sizeof(struct objc_protocol_t));
   3831     memcpy(&protocol, r, left);
   3832   }
   3833   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
   3834     swapStruct(protocol);
   3835 
   3836   print_indent(indent);
   3837   outs() << "              isa " << format("0x%08" PRIx32, protocol.isa)
   3838          << "\n";
   3839 
   3840   print_indent(indent);
   3841   outs() << "    protocol_name "
   3842          << format("0x%08" PRIx32, protocol.protocol_name);
   3843   if (info->verbose) {
   3844     name = get_pointer_32(protocol.protocol_name, offset, left, S, info, true);
   3845     if (name != nullptr)
   3846       outs() << format(" %.*s", left, name);
   3847     else
   3848       outs() << " (not in an __OBJC section)";
   3849   }
   3850   outs() << "\n";
   3851 
   3852   print_indent(indent);
   3853   outs() << "    protocol_list "
   3854          << format("0x%08" PRIx32, protocol.protocol_list);
   3855   if (print_protocol_list(protocol.protocol_list, indent + 4, info))
   3856     outs() << " (not in an __OBJC section)\n";
   3857 
   3858   print_indent(indent);
   3859   outs() << " instance_methods "
   3860          << format("0x%08" PRIx32, protocol.instance_methods);
   3861   if (print_method_description_list(protocol.instance_methods, indent, info))
   3862     outs() << " (not in an __OBJC section)\n";
   3863 
   3864   print_indent(indent);
   3865   outs() << "    class_methods "
   3866          << format("0x%08" PRIx32, protocol.class_methods);
   3867   if (print_method_description_list(protocol.class_methods, indent, info))
   3868     outs() << " (not in an __OBJC section)\n";
   3869 
   3870   return false;
   3871 }
   3872 
   3873 static bool print_protocol_list(uint32_t p, uint32_t indent,
   3874                                 struct DisassembleInfo *info) {
   3875   uint32_t offset, left, l;
   3876   SectionRef S;
   3877   struct objc_protocol_list_t protocol_list;
   3878   const char *r, *list;
   3879   int32_t i;
   3880 
   3881   r = get_pointer_32(p, offset, left, S, info, true);
   3882   if (r == nullptr)
   3883     return true;
   3884 
   3885   outs() << "\n";
   3886   if (left > sizeof(struct objc_protocol_list_t)) {
   3887     memcpy(&protocol_list, r, sizeof(struct objc_protocol_list_t));
   3888   } else {
   3889     outs() << "\t\t objc_protocol_list_t extends past end of the section\n";
   3890     memset(&protocol_list, '\0', sizeof(struct objc_protocol_list_t));
   3891     memcpy(&protocol_list, r, left);
   3892   }
   3893   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
   3894     swapStruct(protocol_list);
   3895 
   3896   print_indent(indent);
   3897   outs() << "         next " << format("0x%08" PRIx32, protocol_list.next)
   3898          << "\n";
   3899   print_indent(indent);
   3900   outs() << "        count " << protocol_list.count << "\n";
   3901 
   3902   list = r + sizeof(struct objc_protocol_list_t);
   3903   for (i = 0; i < protocol_list.count; i++) {
   3904     if ((i + 1) * sizeof(uint32_t) > left) {
   3905       outs() << "\t\t remaining list entries extend past the of the section\n";
   3906       break;
   3907     }
   3908     memcpy(&l, list + i * sizeof(uint32_t), sizeof(uint32_t));
   3909     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
   3910       sys::swapByteOrder(l);
   3911 
   3912     print_indent(indent);
   3913     outs() << "      list[" << i << "] " << format("0x%08" PRIx32, l);
   3914     if (print_protocol(l, indent, info))
   3915       outs() << "(not in an __OBJC section)\n";
   3916   }
   3917   return false;
   3918 }
   3919 
   3920 static void print_ivar_list64_t(uint64_t p, struct DisassembleInfo *info) {
   3921   struct ivar_list64_t il;
   3922   struct ivar64_t i;
   3923   const char *r;
   3924   uint32_t offset, xoffset, left, j;
   3925   SectionRef S, xS;
   3926   const char *name, *sym_name, *ivar_offset_p;
   3927   uint64_t ivar_offset, n_value;
   3928 
   3929   r = get_pointer_64(p, offset, left, S, info);
   3930   if (r == nullptr)
   3931     return;
   3932   memset(&il, '\0', sizeof(struct ivar_list64_t));
   3933   if (left < sizeof(struct ivar_list64_t)) {
   3934     memcpy(&il, r, left);
   3935     outs() << "   (ivar_list_t entends past the end of the section)\n";
   3936   } else
   3937     memcpy(&il, r, sizeof(struct ivar_list64_t));
   3938   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
   3939     swapStruct(il);
   3940   outs() << "                    entsize " << il.entsize << "\n";
   3941   outs() << "                      count " << il.count << "\n";
   3942 
   3943   p += sizeof(struct ivar_list64_t);
   3944   offset += sizeof(struct ivar_list64_t);
   3945   for (j = 0; j < il.count; j++) {
   3946     r = get_pointer_64(p, offset, left, S, info);
   3947     if (r == nullptr)
   3948       return;
   3949     memset(&i, '\0', sizeof(struct ivar64_t));
   3950     if (left < sizeof(struct ivar64_t)) {
   3951       memcpy(&i, r, left);
   3952       outs() << "   (ivar_t entends past the end of the section)\n";
   3953     } else
   3954       memcpy(&i, r, sizeof(struct ivar64_t));
   3955     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
   3956       swapStruct(i);
   3957 
   3958     outs() << "\t\t\t   offset ";
   3959     sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, offset), S,
   3960                              info, n_value, i.offset);
   3961     if (n_value != 0) {
   3962       if (info->verbose && sym_name != nullptr)
   3963         outs() << sym_name;
   3964       else
   3965         outs() << format("0x%" PRIx64, n_value);
   3966       if (i.offset != 0)
   3967         outs() << " + " << format("0x%" PRIx64, i.offset);
   3968     } else
   3969       outs() << format("0x%" PRIx64, i.offset);
   3970     ivar_offset_p = get_pointer_64(i.offset + n_value, xoffset, left, xS, info);
   3971     if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
   3972       memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset));
   3973       if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
   3974         sys::swapByteOrder(ivar_offset);
   3975       outs() << " " << ivar_offset << "\n";
   3976     } else
   3977       outs() << "\n";
   3978 
   3979     outs() << "\t\t\t     name ";
   3980     sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, name), S, info,
   3981                              n_value, i.name);
   3982     if (n_value != 0) {
   3983       if (info->verbose && sym_name != nullptr)
   3984         outs() << sym_name;
   3985       else
   3986         outs() << format("0x%" PRIx64, n_value);
   3987       if (i.name != 0)
   3988         outs() << " + " << format("0x%" PRIx64, i.name);
   3989     } else
   3990       outs() << format("0x%" PRIx64, i.name);
   3991     name = get_pointer_64(i.name + n_value, xoffset, left, xS, info);
   3992     if (name != nullptr)
   3993       outs() << format(" %.*s", left, name);
   3994     outs() << "\n";
   3995 
   3996     outs() << "\t\t\t     type ";
   3997     sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, type), S, info,
   3998                              n_value, i.name);
   3999     name = get_pointer_64(i.type + n_value, xoffset, left, xS, info);
   4000     if (n_value != 0) {
   4001       if (info->verbose && sym_name != nullptr)
   4002         outs() << sym_name;
   4003       else
   4004         outs() << format("0x%" PRIx64, n_value);
   4005       if (i.type != 0)
   4006         outs() << " + " << format("0x%" PRIx64, i.type);
   4007     } else
   4008       outs() << format("0x%" PRIx64, i.type);
   4009     if (name != nullptr)
   4010       outs() << format(" %.*s", left, name);
   4011     outs() << "\n";
   4012 
   4013     outs() << "\t\t\talignment " << i.alignment << "\n";
   4014     outs() << "\t\t\t     size " << i.size << "\n";
   4015 
   4016     p += sizeof(struct ivar64_t);
   4017     offset += sizeof(struct ivar64_t);
   4018   }
   4019 }
   4020 
   4021 static void print_ivar_list32_t(uint32_t p, struct DisassembleInfo *info) {
   4022   struct ivar_list32_t il;
   4023   struct ivar32_t i;
   4024   const char *r;
   4025   uint32_t offset, xoffset, left, j;
   4026   SectionRef S, xS;
   4027   const char *name, *ivar_offset_p;
   4028   uint32_t ivar_offset;
   4029 
   4030   r = get_pointer_32(p, offset, left, S, info);
   4031   if (r == nullptr)
   4032     return;
   4033   memset(&il, '\0', sizeof(struct ivar_list32_t));
   4034   if (left < sizeof(struct ivar_list32_t)) {
   4035     memcpy(&il, r, left);
   4036     outs() << "   (ivar_list_t entends past the end of the section)\n";
   4037   } else
   4038     memcpy(&il, r, sizeof(struct ivar_list32_t));
   4039   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
   4040     swapStruct(il);
   4041   outs() << "                    entsize " << il.entsize << "\n";
   4042   outs() << "                      count " << il.count << "\n";
   4043 
   4044   p += sizeof(struct ivar_list32_t);
   4045   offset += sizeof(struct ivar_list32_t);
   4046   for (j = 0; j < il.count; j++) {
   4047     r = get_pointer_32(p, offset, left, S, info);
   4048     if (r == nullptr)
   4049       return;
   4050     memset(&i, '\0', sizeof(struct ivar32_t));
   4051     if (left < sizeof(struct ivar32_t)) {
   4052       memcpy(&i, r, left);
   4053       outs() << "   (ivar_t entends past the end of the section)\n";
   4054     } else
   4055       memcpy(&i, r, sizeof(struct ivar32_t));
   4056     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
   4057       swapStruct(i);
   4058 
   4059     outs() << "\t\t\t   offset " << format("0x%" PRIx32, i.offset);
   4060     ivar_offset_p = get_pointer_32(i.offset, xoffset, left, xS, info);
   4061     if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
   4062       memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset));
   4063       if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
   4064         sys::swapByteOrder(ivar_offset);
   4065       outs() << " " << ivar_offset << "\n";
   4066     } else
   4067       outs() << "\n";
   4068 
   4069     outs() << "\t\t\t     name " << format("0x%" PRIx32, i.name);
   4070     name = get_pointer_32(i.name, xoffset, left, xS, info);
   4071     if (name != nullptr)
   4072       outs() << format(" %.*s", left, name);
   4073     outs() << "\n";
   4074 
   4075     outs() << "\t\t\t     type " << format("0x%" PRIx32, i.type);
   4076     name = get_pointer_32(i.type, xoffset, left, xS, info);
   4077     if (name != nullptr)
   4078       outs() << format(" %.*s", left, name);
   4079     outs() << "\n";
   4080 
   4081     outs() << "\t\t\talignment " << i.alignment << "\n";
   4082     outs() << "\t\t\t     size " << i.size << "\n";
   4083 
   4084     p += sizeof(struct ivar32_t);
   4085     offset += sizeof(struct ivar32_t);
   4086   }
   4087 }
   4088 
   4089 static void print_objc_property_list64(uint64_t p,
   4090                                        struct DisassembleInfo *info) {
   4091   struct objc_property_list64 opl;
   4092   struct objc_property64 op;
   4093   const char *r;
   4094   uint32_t offset, xoffset, left, j;
   4095   SectionRef S, xS;
   4096   const char *name, *sym_name;
   4097   uint64_t n_value;
   4098 
   4099   r = get_pointer_64(p, offset, left, S, info);
   4100   if (r == nullptr)
   4101     return;
   4102   memset(&opl, '\0', sizeof(struct objc_property_list64));
   4103   if (left < sizeof(struct objc_property_list64)) {
   4104     memcpy(&opl, r, left);
   4105     outs() << "   (objc_property_list entends past the end of the section)\n";
   4106   } else
   4107     memcpy(&opl, r, sizeof(struct objc_property_list64));
   4108   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
   4109     swapStruct(opl);
   4110   outs() << "                    entsize " << opl.entsize << "\n";
   4111   outs() << "                      count " << opl.count << "\n";
   4112 
   4113   p += sizeof(struct objc_property_list64);
   4114   offset += sizeof(struct objc_property_list64);
   4115   for (j = 0; j < opl.count; j++) {
   4116     r = get_pointer_64(p, offset, left, S, info);
   4117     if (r == nullptr)
   4118       return;
   4119     memset(&op, '\0', sizeof(struct objc_property64));
   4120     if (left < sizeof(struct objc_property64)) {
   4121       memcpy(&op, r, left);
   4122       outs() << "   (objc_property entends past the end of the section)\n";
   4123     } else
   4124       memcpy(&op, r, sizeof(struct objc_property64));
   4125     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
   4126       swapStruct(op);
   4127 
   4128     outs() << "\t\t\t     name ";
   4129     sym_name = get_symbol_64(offset + offsetof(struct objc_property64, name), S,
   4130                              info, n_value, op.name);
   4131     if (n_value != 0) {
   4132       if (info->verbose && sym_name != nullptr)
   4133         outs() << sym_name;
   4134       else
   4135         outs() << format("0x%" PRIx64, n_value);
   4136       if (op.name != 0)
   4137         outs() << " + " << format("0x%" PRIx64, op.name);
   4138     } else
   4139       outs() << format("0x%" PRIx64, op.name);
   4140     name = get_pointer_64(op.name + n_value, xoffset, left, xS, info);
   4141     if (name != nullptr)
   4142       outs() << format(" %.*s", left, name);
   4143     outs() << "\n";
   4144 
   4145     outs() << "\t\t\tattributes ";
   4146     sym_name =
   4147         get_symbol_64(offset + offsetof(struct objc_property64, attributes), S,
   4148                       info, n_value, op.attributes);
   4149     if (n_value != 0) {
   4150       if (info->verbose && sym_name != nullptr)
   4151         outs() << sym_name;
   4152       else
   4153         outs() << format("0x%" PRIx64, n_value);
   4154       if (op.attributes != 0)
   4155         outs() << " + " << format("0x%" PRIx64, op.attributes);
   4156     } else
   4157       outs() << format("0x%" PRIx64, op.attributes);
   4158     name = get_pointer_64(op.attributes + n_value, xoffset, left, xS, info);
   4159     if (name != nullptr)
   4160       outs() << format(" %.*s", left, name);
   4161     outs() << "\n";
   4162 
   4163     p += sizeof(struct objc_property64);
   4164     offset += sizeof(struct objc_property64);
   4165   }
   4166 }
   4167 
   4168 static void print_objc_property_list32(uint32_t p,
   4169                                        struct DisassembleInfo *info) {
   4170   struct objc_property_list32 opl;
   4171   struct objc_property32 op;
   4172   const char *r;
   4173   uint32_t offset, xoffset, left, j;
   4174   SectionRef S, xS;
   4175   const char *name;
   4176 
   4177   r = get_pointer_32(p, offset, left, S, info);
   4178   if (r == nullptr)
   4179     return;
   4180   memset(&opl, '\0', sizeof(struct objc_property_list32));
   4181   if (left < sizeof(struct objc_property_list32)) {
   4182     memcpy(&opl, r, left);
   4183     outs() << "   (objc_property_list entends past the end of the section)\n";
   4184   } else
   4185     memcpy(&opl, r, sizeof(struct objc_property_list32));
   4186   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
   4187     swapStruct(opl);
   4188   outs() << "                    entsize " << opl.entsize << "\n";
   4189   outs() << "                      count " << opl.count << "\n";
   4190 
   4191   p += sizeof(struct objc_property_list32);
   4192   offset += sizeof(struct objc_property_list32);
   4193   for (j = 0; j < opl.count; j++) {
   4194     r = get_pointer_32(p, offset, left, S, info);
   4195     if (r == nullptr)
   4196       return;
   4197     memset(&op, '\0', sizeof(struct objc_property32));
   4198     if (left < sizeof(struct objc_property32)) {
   4199       memcpy(&op, r, left);
   4200       outs() << "   (objc_property entends past the end of the section)\n";
   4201     } else
   4202       memcpy(&op, r, sizeof(struct objc_property32));
   4203     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
   4204       swapStruct(op);
   4205 
   4206     outs() << "\t\t\t     name " << format("0x%" PRIx32, op.name);
   4207     name = get_pointer_32(op.name, xoffset, left, xS, info);
   4208     if (name != nullptr)
   4209       outs() << format(" %.*s", left, name);
   4210     outs() << "\n";
   4211 
   4212     outs() << "\t\t\tattributes " << format("0x%" PRIx32, op.attributes);
   4213     name = get_pointer_32(op.attributes, xoffset, left, xS, info);
   4214     if (name != nullptr)
   4215       outs() << format(" %.*s", left, name);
   4216     outs() << "\n";
   4217 
   4218     p += sizeof(struct objc_property32);
   4219     offset += sizeof(struct objc_property32);
   4220   }
   4221 }
   4222 
   4223 static bool print_class_ro64_t(uint64_t p, struct DisassembleInfo *info,
   4224                                bool &is_meta_class) {
   4225   struct class_ro64_t cro;
   4226   const char *r;
   4227   uint32_t offset, xoffset, left;
   4228   SectionRef S, xS;
   4229   const char *name, *sym_name;
   4230   uint64_t n_value;
   4231 
   4232   r = get_pointer_64(p, offset, left, S, info);
   4233   if (r == nullptr || left < sizeof(struct class_ro64_t))
   4234     return false;
   4235   memset(&cro, '\0', sizeof(struct class_ro64_t));
   4236   if (left < sizeof(struct class_ro64_t)) {
   4237     memcpy(&cro, r, left);
   4238     outs() << "   (class_ro_t entends past the end of the section)\n";
   4239   } else
   4240     memcpy(&cro, r, sizeof(struct class_ro64_t));
   4241   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
   4242     swapStruct(cro);
   4243   outs() << "                    flags " << format("0x%" PRIx32, cro.flags);
   4244   if (cro.flags & RO_META)
   4245     outs() << " RO_META";
   4246   if (cro.flags & RO_ROOT)
   4247     outs() << " RO_ROOT";
   4248   if (cro.flags & RO_HAS_CXX_STRUCTORS)
   4249     outs() << " RO_HAS_CXX_STRUCTORS";
   4250   outs() << "\n";
   4251   outs() << "            instanceStart " << cro.instanceStart << "\n";
   4252   outs() << "             instanceSize " << cro.instanceSize << "\n";
   4253   outs() << "                 reserved " << format("0x%" PRIx32, cro.reserved)
   4254          << "\n";
   4255   outs() << "               ivarLayout " << format("0x%" PRIx64, cro.ivarLayout)
   4256          << "\n";
   4257   print_layout_map64(cro.ivarLayout, info);
   4258 
   4259   outs() << "                     name ";
   4260   sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, name), S,
   4261                            info, n_value, cro.name);
   4262   if (n_value != 0) {
   4263     if (info->verbose && sym_name != nullptr)
   4264       outs() << sym_name;
   4265     else
   4266       outs() << format("0x%" PRIx64, n_value);
   4267     if (cro.name != 0)
   4268       outs() << " + " << format("0x%" PRIx64, cro.name);
   4269   } else
   4270     outs() << format("0x%" PRIx64, cro.name);
   4271   name = get_pointer_64(cro.name + n_value, xoffset, left, xS, info);
   4272   if (name != nullptr)
   4273     outs() << format(" %.*s", left, name);
   4274   outs() << "\n";
   4275 
   4276   outs() << "              baseMethods ";
   4277   sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, baseMethods),
   4278                            S, info, n_value, cro.baseMethods);
   4279   if (n_value != 0) {
   4280     if (info->verbose && sym_name != nullptr)
   4281       outs() << sym_name;
   4282     else
   4283       outs() << format("0x%" PRIx64, n_value);
   4284     if (cro.baseMethods != 0)
   4285       outs() << " + " << format("0x%" PRIx64, cro.baseMethods);
   4286   } else
   4287     outs() << format("0x%" PRIx64, cro.baseMethods);
   4288   outs() << " (struct method_list_t *)\n";
   4289   if (cro.baseMethods + n_value != 0)
   4290     print_method_list64_t(cro.baseMethods + n_value, info, "");
   4291 
   4292   outs() << "            baseProtocols ";
   4293   sym_name =
   4294       get_symbol_64(offset + offsetof(struct class_ro64_t, baseProtocols), S,
   4295                     info, n_value, cro.baseProtocols);
   4296   if (n_value != 0) {
   4297     if (info->verbose && sym_name != nullptr)
   4298       outs() << sym_name;
   4299     else
   4300       outs() << format("0x%" PRIx64, n_value);
   4301     if (cro.baseProtocols != 0)
   4302       outs() << " + " << format("0x%" PRIx64, cro.baseProtocols);
   4303   } else
   4304     outs() << format("0x%" PRIx64, cro.baseProtocols);
   4305   outs() << "\n";
   4306   if (cro.baseProtocols + n_value != 0)
   4307     print_protocol_list64_t(cro.baseProtocols + n_value, info);
   4308 
   4309   outs() << "                    ivars ";
   4310   sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, ivars), S,
   4311                            info, n_value, cro.ivars);
   4312   if (n_value != 0) {
   4313     if (info->verbose && sym_name != nullptr)
   4314       outs() << sym_name;
   4315     else
   4316       outs() << format("0x%" PRIx64, n_value);
   4317     if (cro.ivars != 0)
   4318       outs() << " + " << format("0x%" PRIx64, cro.ivars);
   4319   } else
   4320     outs() << format("0x%" PRIx64, cro.ivars);
   4321   outs() << "\n";
   4322   if (cro.ivars + n_value != 0)
   4323     print_ivar_list64_t(cro.ivars + n_value, info);
   4324 
   4325   outs() << "           weakIvarLayout ";
   4326   sym_name =
   4327       get_symbol_64(offset + offsetof(struct class_ro64_t, weakIvarLayout), S,
   4328                     info, n_value, cro.weakIvarLayout);
   4329   if (n_value != 0) {
   4330     if (info->verbose && sym_name != nullptr)
   4331       outs() << sym_name;
   4332     else
   4333       outs() << format("0x%" PRIx64, n_value);
   4334     if (cro.weakIvarLayout != 0)
   4335       outs() << " + " << format("0x%" PRIx64, cro.weakIvarLayout);
   4336   } else
   4337     outs() << format("0x%" PRIx64, cro.weakIvarLayout);
   4338   outs() << "\n";
   4339   print_layout_map64(cro.weakIvarLayout + n_value, info);
   4340 
   4341   outs() << "           baseProperties ";
   4342   sym_name =
   4343       get_symbol_64(offset + offsetof(struct class_ro64_t, baseProperties), S,
   4344                     info, n_value, cro.baseProperties);
   4345   if (n_value != 0) {
   4346     if (info->verbose && sym_name != nullptr)
   4347       outs() << sym_name;
   4348     else
   4349       outs() << format("0x%" PRIx64, n_value);
   4350     if (cro.baseProperties != 0)
   4351       outs() << " + " << format("0x%" PRIx64, cro.baseProperties);
   4352   } else
   4353     outs() << format("0x%" PRIx64, cro.baseProperties);
   4354   outs() << "\n";
   4355   if (cro.baseProperties + n_value != 0)
   4356     print_objc_property_list64(cro.baseProperties + n_value, info);
   4357 
   4358   is_meta_class = (cro.flags & RO_META) != 0;
   4359   return true;
   4360 }
   4361 
   4362 static bool print_class_ro32_t(uint32_t p, struct DisassembleInfo *info,
   4363                                bool &is_meta_class) {
   4364   struct class_ro32_t cro;
   4365   const char *r;
   4366   uint32_t offset, xoffset, left;
   4367   SectionRef S, xS;
   4368   const char *name;
   4369 
   4370   r = get_pointer_32(p, offset, left, S, info);
   4371   if (r == nullptr)
   4372     return false;
   4373   memset(&cro, '\0', sizeof(struct class_ro32_t));
   4374   if (left < sizeof(struct class_ro32_t)) {
   4375     memcpy(&cro, r, left);
   4376     outs() << "   (class_ro_t entends past the end of the section)\n";
   4377   } else
   4378     memcpy(&cro, r, sizeof(struct class_ro32_t));
   4379   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
   4380     swapStruct(cro);
   4381   outs() << "                    flags " << format("0x%" PRIx32, cro.flags);
   4382   if (cro.flags & RO_META)
   4383     outs() << " RO_META";
   4384   if (cro.flags & RO_ROOT)
   4385     outs() << " RO_ROOT";
   4386   if (cro.flags & RO_HAS_CXX_STRUCTORS)
   4387     outs() << " RO_HAS_CXX_STRUCTORS";
   4388   outs() << "\n";
   4389   outs() << "            instanceStart " << cro.instanceStart << "\n";
   4390   outs() << "             instanceSize " << cro.instanceSize << "\n";
   4391   outs() << "               ivarLayout " << format("0x%" PRIx32, cro.ivarLayout)
   4392          << "\n";
   4393   print_layout_map32(cro.ivarLayout, info);
   4394 
   4395   outs() << "                     name " << format("0x%" PRIx32, cro.name);
   4396   name = get_pointer_32(cro.name, xoffset, left, xS, info);
   4397   if (name != nullptr)
   4398     outs() << format(" %.*s", left, name);
   4399   outs() << "\n";
   4400 
   4401   outs() << "              baseMethods "
   4402          << format("0x%" PRIx32, cro.baseMethods)
   4403          << " (struct method_list_t *)\n";
   4404   if (cro.baseMethods != 0)
   4405     print_method_list32_t(cro.baseMethods, info, "");
   4406 
   4407   outs() << "            baseProtocols "
   4408          << format("0x%" PRIx32, cro.baseProtocols) << "\n";
   4409   if (cro.baseProtocols != 0)
   4410     print_protocol_list32_t(cro.baseProtocols, info);
   4411   outs() << "                    ivars " << format("0x%" PRIx32, cro.ivars)
   4412          << "\n";
   4413   if (cro.ivars != 0)
   4414     print_ivar_list32_t(cro.ivars, info);
   4415   outs() << "           weakIvarLayout "
   4416          << format("0x%" PRIx32, cro.weakIvarLayout) << "\n";
   4417   print_layout_map32(cro.weakIvarLayout, info);
   4418   outs() << "           baseProperties "
   4419          << format("0x%" PRIx32, cro.baseProperties) << "\n";
   4420   if (cro.baseProperties != 0)
   4421     print_objc_property_list32(cro.baseProperties, info);
   4422   is_meta_class = (cro.flags & RO_META) != 0;
   4423   return true;
   4424 }
   4425 
   4426 static void print_class64_t(uint64_t p, struct DisassembleInfo *info) {
   4427   struct class64_t c;
   4428   const char *r;
   4429   uint32_t offset, left;
   4430   SectionRef S;
   4431   const char *name;
   4432   uint64_t isa_n_value, n_value;
   4433 
   4434   r = get_pointer_64(p, offset, left, S, info);
   4435   if (r == nullptr || left < sizeof(struct class64_t))
   4436     return;
   4437   memset(&c, '\0', sizeof(struct class64_t));
   4438   if (left < sizeof(struct class64_t)) {
   4439     memcpy(&c, r, left);
   4440     outs() << "   (class_t entends past the end of the section)\n";
   4441   } else
   4442     memcpy(&c, r, sizeof(struct class64_t));
   4443   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
   4444     swapStruct(c);
   4445 
   4446   outs() << "           isa " << format("0x%" PRIx64, c.isa);
   4447   name = get_symbol_64(offset + offsetof(struct class64_t, isa), S, info,
   4448                        isa_n_value, c.isa);
   4449   if (name != nullptr)
   4450     outs() << " " << name;
   4451   outs() << "\n";
   4452 
   4453   outs() << "    superclass " << format("0x%" PRIx64, c.superclass);
   4454   name = get_symbol_64(offset + offsetof(struct class64_t, superclass), S, info,
   4455                        n_value, c.superclass);
   4456   if (name != nullptr)
   4457     outs() << " " << name;
   4458   outs() << "\n";
   4459 
   4460   outs() << "         cache " << format("0x%" PRIx64, c.cache);
   4461   name = get_symbol_64(offset + offsetof(struct class64_t, cache), S, info,
   4462                        n_value, c.cache);
   4463   if (name != nullptr)
   4464     outs() << " " << name;
   4465   outs() << "\n";
   4466 
   4467   outs() << "        vtable " << format("0x%" PRIx64, c.vtable);
   4468   name = get_symbol_64(offset + offsetof(struct class64_t, vtable), S, info,
   4469                        n_value, c.vtable);
   4470   if (name != nullptr)
   4471     outs() << " " << name;
   4472   outs() << "\n";
   4473 
   4474   name = get_symbol_64(offset + offsetof(struct class64_t, data), S, info,
   4475                        n_value, c.data);
   4476   outs() << "          data ";
   4477   if (n_value != 0) {
   4478     if (info->verbose && name != nullptr)
   4479       outs() << name;
   4480     else
   4481       outs() << format("0x%" PRIx64, n_value);
   4482     if (c.data != 0)
   4483       outs() << " + " << format("0x%" PRIx64, c.data);
   4484   } else
   4485     outs() << format("0x%" PRIx64, c.data);
   4486   outs() << " (struct class_ro_t *)";
   4487 
   4488   // This is a Swift class if some of the low bits of the pointer are set.
   4489   if ((c.data + n_value) & 0x7)
   4490     outs() << " Swift class";
   4491   outs() << "\n";
   4492   bool is_meta_class;
   4493   if (!print_class_ro64_t((c.data + n_value) & ~0x7, info, is_meta_class))
   4494     return;
   4495 
   4496   if (!is_meta_class &&
   4497       c.isa + isa_n_value != p &&
   4498       c.isa + isa_n_value != 0 &&
   4499       info->depth < 100) {
   4500       info->depth++;
   4501       outs() << "Meta Class\n";
   4502       print_class64_t(c.isa + isa_n_value, info);
   4503   }
   4504 }
   4505 
   4506 static void print_class32_t(uint32_t p, struct DisassembleInfo *info) {
   4507   struct class32_t c;
   4508   const char *r;
   4509   uint32_t offset, left;
   4510   SectionRef S;
   4511   const char *name;
   4512 
   4513   r = get_pointer_32(p, offset, left, S, info);
   4514   if (r == nullptr)
   4515     return;
   4516   memset(&c, '\0', sizeof(struct class32_t));
   4517   if (left < sizeof(struct class32_t)) {
   4518     memcpy(&c, r, left);
   4519     outs() << "   (class_t entends past the end of the section)\n";
   4520   } else
   4521     memcpy(&c, r, sizeof(struct class32_t));
   4522   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
   4523     swapStruct(c);
   4524 
   4525   outs() << "           isa " << format("0x%" PRIx32, c.isa);
   4526   name =
   4527       get_symbol_32(offset + offsetof(struct class32_t, isa), S, info, c.isa);
   4528   if (name != nullptr)
   4529     outs() << " " << name;
   4530   outs() << "\n";
   4531 
   4532   outs() << "    superclass " << format("0x%" PRIx32, c.superclass);
   4533   name = get_symbol_32(offset + offsetof(struct class32_t, superclass), S, info,
   4534                        c.superclass);
   4535   if (name != nullptr)
   4536     outs() << " " << name;
   4537   outs() << "\n";
   4538 
   4539   outs() << "         cache " << format("0x%" PRIx32, c.cache);
   4540   name = get_symbol_32(offset + offsetof(struct class32_t, cache), S, info,
   4541                        c.cache);
   4542   if (name != nullptr)
   4543     outs() << " " << name;
   4544   outs() << "\n";
   4545 
   4546   outs() << "        vtable " << format("0x%" PRIx32, c.vtable);
   4547   name = get_symbol_32(offset + offsetof(struct class32_t, vtable), S, info,
   4548                        c.vtable);
   4549   if (name != nullptr)
   4550     outs() << " " << name;
   4551   outs() << "\n";
   4552 
   4553   name =
   4554       get_symbol_32(offset + offsetof(struct class32_t, data), S, info, c.data);
   4555   outs() << "          data " << format("0x%" PRIx32, c.data)
   4556          << " (struct class_ro_t *)";
   4557 
   4558   // This is a Swift class if some of the low bits of the pointer are set.
   4559   if (c.data & 0x3)
   4560     outs() << " Swift class";
   4561   outs() << "\n";
   4562   bool is_meta_class;
   4563   if (!print_class_ro32_t(c.data & ~0x3, info, is_meta_class))
   4564     return;
   4565 
   4566   if (!is_meta_class) {
   4567     outs() << "Meta Class\n";
   4568     print_class32_t(c.isa, info);
   4569   }
   4570 }
   4571 
   4572 static void print_objc_class_t(struct objc_class_t *objc_class,
   4573                                struct DisassembleInfo *info) {
   4574   uint32_t offset, left, xleft;
   4575   const char *name, *p, *ivar_list;
   4576   SectionRef S;
   4577   int32_t i;
   4578   struct objc_ivar_list_t objc_ivar_list;
   4579   struct objc_ivar_t ivar;
   4580 
   4581   outs() << "\t\t      isa " << format("0x%08" PRIx32, objc_class->isa);
   4582   if (info->verbose && CLS_GETINFO(objc_class, CLS_META)) {
   4583     name = get_pointer_32(objc_class->isa, offset, left, S, info, true);
   4584     if (name != nullptr)
   4585       outs() << format(" %.*s", left, name);
   4586     else
   4587       outs() << " (not in an __OBJC section)";
   4588   }
   4589   outs() << "\n";
   4590 
   4591   outs() << "\t      super_class "
   4592          << format("0x%08" PRIx32, objc_class->super_class);
   4593   if (info->verbose) {
   4594     name = get_pointer_32(objc_class->super_class, offset, left, S, info, true);
   4595     if (name != nullptr)
   4596       outs() << format(" %.*s", left, name);
   4597     else
   4598       outs() << " (not in an __OBJC section)";
   4599   }
   4600   outs() << "\n";
   4601 
   4602   outs() << "\t\t     name " << format("0x%08" PRIx32, objc_class->name);
   4603   if (info->verbose) {
   4604     name = get_pointer_32(objc_class->name, offset, left, S, info, true);
   4605     if (name != nullptr)
   4606       outs() << format(" %.*s", left, name);
   4607     else
   4608       outs() << " (not in an __OBJC section)";
   4609   }
   4610   outs() << "\n";
   4611 
   4612   outs() << "\t\t  version " << format("0x%08" PRIx32, objc_class->version)
   4613          << "\n";
   4614 
   4615   outs() << "\t\t     info " << format("0x%08" PRIx32, objc_class->info);
   4616   if (info->verbose) {
   4617     if (CLS_GETINFO(objc_class, CLS_CLASS))
   4618       outs() << " CLS_CLASS";
   4619     else if (CLS_GETINFO(objc_class, CLS_META))
   4620       outs() << " CLS_META";
   4621   }
   4622   outs() << "\n";
   4623 
   4624   outs() << "\t    instance_size "
   4625          << format("0x%08" PRIx32, objc_class->instance_size) << "\n";
   4626 
   4627   p = get_pointer_32(objc_class->ivars, offset, left, S, info, true);
   4628   outs() << "\t\t    ivars " << format("0x%08" PRIx32, objc_class->ivars);
   4629   if (p != nullptr) {
   4630     if (left > sizeof(struct objc_ivar_list_t)) {
   4631       outs() << "\n";
   4632       memcpy(&objc_ivar_list, p, sizeof(struct objc_ivar_list_t));
   4633     } else {
   4634       outs() << " (entends past the end of the section)\n";
   4635       memset(&objc_ivar_list, '\0', sizeof(struct objc_ivar_list_t));
   4636       memcpy(&objc_ivar_list, p, left);
   4637     }
   4638     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
   4639       swapStruct(objc_ivar_list);
   4640     outs() << "\t\t       ivar_count " << objc_ivar_list.ivar_count << "\n";
   4641     ivar_list = p + sizeof(struct objc_ivar_list_t);
   4642     for (i = 0; i < objc_ivar_list.ivar_count; i++) {
   4643       if ((i + 1) * sizeof(struct objc_ivar_t) > left) {
   4644         outs() << "\t\t remaining ivar's extend past the of the section\n";
   4645         break;
   4646       }
   4647       memcpy(&ivar, ivar_list + i * sizeof(struct objc_ivar_t),
   4648              sizeof(struct objc_ivar_t));
   4649       if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
   4650         swapStruct(ivar);
   4651 
   4652       outs() << "\t\t\tivar_name " << format("0x%08" PRIx32, ivar.ivar_name);
   4653       if (info->verbose) {
   4654         name = get_pointer_32(ivar.ivar_name, offset, xleft, S, info, true);
   4655         if (name != nullptr)
   4656           outs() << format(" %.*s", xleft, name);
   4657         else
   4658           outs() << " (not in an __OBJC section)";
   4659       }
   4660       outs() << "\n";
   4661 
   4662       outs() << "\t\t\tivar_type " << format("0x%08" PRIx32, ivar.ivar_type);
   4663       if (info->verbose) {
   4664         name = get_pointer_32(ivar.ivar_type, offset, xleft, S, info, true);
   4665         if (name != nullptr)
   4666           outs() << format(" %.*s", xleft, name);
   4667         else
   4668           outs() << " (not in an __OBJC section)";
   4669       }
   4670       outs() << "\n";
   4671 
   4672       outs() << "\t\t      ivar_offset "
   4673              << format("0x%08" PRIx32, ivar.ivar_offset) << "\n";
   4674     }
   4675   } else {
   4676     outs() << " (not in an __OBJC section)\n";
   4677   }
   4678 
   4679   outs() << "\t\t  methods " << format("0x%08" PRIx32, objc_class->methodLists);
   4680   if (print_method_list(objc_class->methodLists, info))
   4681     outs() << " (not in an __OBJC section)\n";
   4682 
   4683   outs() << "\t\t    cache " << format("0x%08" PRIx32, objc_class->cache)
   4684          << "\n";
   4685 
   4686   outs() << "\t\tprotocols " << format("0x%08" PRIx32, objc_class->protocols);
   4687   if (print_protocol_list(objc_class->protocols, 16, info))
   4688     outs() << " (not in an __OBJC section)\n";
   4689 }
   4690 
   4691 static void print_objc_objc_category_t(struct objc_category_t *objc_category,
   4692                                        struct DisassembleInfo *info) {
   4693   uint32_t offset, left;
   4694   const char *name;
   4695   SectionRef S;
   4696 
   4697   outs() << "\t       category name "
   4698          << format("0x%08" PRIx32, objc_category->category_name);
   4699   if (info->verbose) {
   4700     name = get_pointer_32(objc_category->category_name, offset, left, S, info,
   4701                           true);
   4702     if (name != nullptr)
   4703       outs() << format(" %.*s", left, name);
   4704     else
   4705       outs() << " (not in an __OBJC section)";
   4706   }
   4707   outs() << "\n";
   4708 
   4709   outs() << "\t\t  class name "
   4710          << format("0x%08" PRIx32, objc_category->class_name);
   4711   if (info->verbose) {
   4712     name =
   4713         get_pointer_32(objc_category->class_name, offset, left, S, info, true);
   4714     if (name != nullptr)
   4715       outs() << format(" %.*s", left, name);
   4716     else
   4717       outs() << " (not in an __OBJC section)";
   4718   }
   4719   outs() << "\n";
   4720 
   4721   outs() << "\t    instance methods "
   4722          << format("0x%08" PRIx32, objc_category->instance_methods);
   4723   if (print_method_list(objc_category->instance_methods, info))
   4724     outs() << " (not in an __OBJC section)\n";
   4725 
   4726   outs() << "\t       class methods "
   4727          << format("0x%08" PRIx32, objc_category->class_methods);
   4728   if (print_method_list(objc_category->class_methods, info))
   4729     outs() << " (not in an __OBJC section)\n";
   4730 }
   4731 
   4732 static void print_category64_t(uint64_t p, struct DisassembleInfo *info) {
   4733   struct category64_t c;
   4734   const char *r;
   4735   uint32_t offset, xoffset, left;
   4736   SectionRef S, xS;
   4737   const char *name, *sym_name;
   4738   uint64_t n_value;
   4739 
   4740   r = get_pointer_64(p, offset, left, S, info);
   4741   if (r == nullptr)
   4742     return;
   4743   memset(&c, '\0', sizeof(struct category64_t));
   4744   if (left < sizeof(struct category64_t)) {
   4745     memcpy(&c, r, left);
   4746     outs() << "   (category_t entends past the end of the section)\n";
   4747   } else
   4748     memcpy(&c, r, sizeof(struct category64_t));
   4749   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
   4750     swapStruct(c);
   4751 
   4752   outs() << "              name ";
   4753   sym_name = get_symbol_64(offset + offsetof(struct category64_t, name), S,
   4754                            info, n_value, c.name);
   4755   if (n_value != 0) {
   4756     if (info->verbose && sym_name != nullptr)
   4757       outs() << sym_name;
   4758     else
   4759       outs() << format("0x%" PRIx64, n_value);
   4760     if (c.name != 0)
   4761       outs() << " + " << format("0x%" PRIx64, c.name);
   4762   } else
   4763     outs() << format("0x%" PRIx64, c.name);
   4764   name = get_pointer_64(c.name + n_value, xoffset, left, xS, info);
   4765   if (name != nullptr)
   4766     outs() << format(" %.*s", left, name);
   4767   outs() << "\n";
   4768 
   4769   outs() << "               cls ";
   4770   sym_name = get_symbol_64(offset + offsetof(struct category64_t, cls), S, info,
   4771                            n_value, c.cls);
   4772   if (n_value != 0) {
   4773     if (info->verbose && sym_name != nullptr)
   4774       outs() << sym_name;
   4775     else
   4776       outs() << format("0x%" PRIx64, n_value);
   4777     if (c.cls != 0)
   4778       outs() << " + " << format("0x%" PRIx64, c.cls);
   4779   } else
   4780     outs() << format("0x%" PRIx64, c.cls);
   4781   outs() << "\n";
   4782   if (c.cls + n_value != 0)
   4783     print_class64_t(c.cls + n_value, info);
   4784 
   4785   outs() << "   instanceMethods ";
   4786   sym_name =
   4787       get_symbol_64(offset + offsetof(struct category64_t, instanceMethods), S,
   4788                     info, n_value, c.instanceMethods);
   4789   if (n_value != 0) {
   4790     if (info->verbose && sym_name != nullptr)
   4791       outs() << sym_name;
   4792     else
   4793       outs() << format("0x%" PRIx64, n_value);
   4794     if (c.instanceMethods != 0)
   4795       outs() << " + " << format("0x%" PRIx64, c.instanceMethods);
   4796   } else
   4797     outs() << format("0x%" PRIx64, c.instanceMethods);
   4798   outs() << "\n";
   4799   if (c.instanceMethods + n_value != 0)
   4800     print_method_list64_t(c.instanceMethods + n_value, info, "");
   4801 
   4802   outs() << "      classMethods ";
   4803   sym_name = get_symbol_64(offset + offsetof(struct category64_t, classMethods),
   4804                            S, info, n_value, c.classMethods);
   4805   if (n_value != 0) {
   4806     if (info->verbose && sym_name != nullptr)
   4807       outs() << sym_name;
   4808     else
   4809       outs() << format("0x%" PRIx64, n_value);
   4810     if (c.classMethods != 0)
   4811       outs() << " + " << format("0x%" PRIx64, c.classMethods);
   4812   } else
   4813     outs() << format("0x%" PRIx64, c.classMethods);
   4814   outs() << "\n";
   4815   if (c.classMethods + n_value != 0)
   4816     print_method_list64_t(c.classMethods + n_value, info, "");
   4817 
   4818   outs() << "         protocols ";
   4819   sym_name = get_symbol_64(offset + offsetof(struct category64_t, protocols), S,
   4820                            info, n_value, c.protocols);
   4821   if (n_value != 0) {
   4822     if (info->verbose && sym_name != nullptr)
   4823       outs() << sym_name;
   4824     else
   4825       outs() << format("0x%" PRIx64, n_value);
   4826     if (c.protocols != 0)
   4827       outs() << " + " << format("0x%" PRIx64, c.protocols);
   4828   } else
   4829     outs() << format("0x%" PRIx64, c.protocols);
   4830   outs() << "\n";
   4831   if (c.protocols + n_value != 0)
   4832     print_protocol_list64_t(c.protocols + n_value, info);
   4833 
   4834   outs() << "instanceProperties ";
   4835   sym_name =
   4836       get_symbol_64(offset + offsetof(struct category64_t, instanceProperties),
   4837                     S, info, n_value, c.instanceProperties);
   4838   if (n_value != 0) {
   4839     if (info->verbose && sym_name != nullptr)
   4840       outs() << sym_name;
   4841     else
   4842       outs() << format("0x%" PRIx64, n_value);
   4843     if (c.instanceProperties != 0)
   4844       outs() << " + " << format("0x%" PRIx64, c.instanceProperties);
   4845   } else
   4846     outs() << format("0x%" PRIx64, c.instanceProperties);
   4847   outs() << "\n";
   4848   if (c.instanceProperties + n_value != 0)
   4849     print_objc_property_list64(c.instanceProperties + n_value, info);
   4850 }
   4851 
   4852 static void print_category32_t(uint32_t p, struct DisassembleInfo *info) {
   4853   struct category32_t c;
   4854   const char *r;
   4855   uint32_t offset, left;
   4856   SectionRef S, xS;
   4857   const char *name;
   4858 
   4859   r = get_pointer_32(p, offset, left, S, info);
   4860   if (r == nullptr)
   4861     return;
   4862   memset(&c, '\0', sizeof(struct category32_t));
   4863   if (left < sizeof(struct category32_t)) {
   4864     memcpy(&c, r, left);
   4865     outs() << "   (category_t entends past the end of the section)\n";
   4866   } else
   4867     memcpy(&c, r, sizeof(struct category32_t));
   4868   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
   4869     swapStruct(c);
   4870 
   4871   outs() << "              name " << format("0x%" PRIx32, c.name);
   4872   name = get_symbol_32(offset + offsetof(struct category32_t, name), S, info,
   4873                        c.name);
   4874   if (name)
   4875     outs() << " " << name;
   4876   outs() << "\n";
   4877 
   4878   outs() << "               cls " << format("0x%" PRIx32, c.cls) << "\n";
   4879   if (c.cls != 0)
   4880     print_class32_t(c.cls, info);
   4881   outs() << "   instanceMethods " << format("0x%" PRIx32, c.instanceMethods)
   4882          << "\n";
   4883   if (c.instanceMethods != 0)
   4884     print_method_list32_t(c.instanceMethods, info, "");
   4885   outs() << "      classMethods " << format("0x%" PRIx32, c.classMethods)
   4886          << "\n";
   4887   if (c.classMethods != 0)
   4888     print_method_list32_t(c.classMethods, info, "");
   4889   outs() << "         protocols " << format("0x%" PRIx32, c.protocols) << "\n";
   4890   if (c.protocols != 0)
   4891     print_protocol_list32_t(c.protocols, info);
   4892   outs() << "instanceProperties " << format("0x%" PRIx32, c.instanceProperties)
   4893          << "\n";
   4894   if (c.instanceProperties != 0)
   4895     print_objc_property_list32(c.instanceProperties, info);
   4896 }
   4897 
   4898 static void print_message_refs64(SectionRef S, struct DisassembleInfo *info) {
   4899   uint32_t i, left, offset, xoffset;
   4900   uint64_t p, n_value;
   4901   struct message_ref64 mr;
   4902   const char *name, *sym_name;
   4903   const char *r;
   4904   SectionRef xS;
   4905 
   4906   if (S == SectionRef())
   4907     return;
   4908 
   4909   StringRef SectName;
   4910   S.getName(SectName);
   4911   DataRefImpl Ref = S.getRawDataRefImpl();
   4912   StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
   4913   outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
   4914   offset = 0;
   4915   for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) {
   4916     p = S.getAddress() + i;
   4917     r = get_pointer_64(p, offset, left, S, info);
   4918     if (r == nullptr)
   4919       return;
   4920     memset(&mr, '\0', sizeof(struct message_ref64));
   4921     if (left < sizeof(struct message_ref64)) {
   4922       memcpy(&mr, r, left);
   4923       outs() << "   (message_ref entends past the end of the section)\n";
   4924     } else
   4925       memcpy(&mr, r, sizeof(struct message_ref64));
   4926     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
   4927       swapStruct(mr);
   4928 
   4929     outs() << "  imp ";
   4930     name = get_symbol_64(offset + offsetof(struct message_ref64, imp), S, info,
   4931                          n_value, mr.imp);
   4932     if (n_value != 0) {
   4933       outs() << format("0x%" PRIx64, n_value) << " ";
   4934       if (mr.imp != 0)
   4935         outs() << "+ " << format("0x%" PRIx64, mr.imp) << " ";
   4936     } else
   4937       outs() << format("0x%" PRIx64, mr.imp) << " ";
   4938     if (name != nullptr)
   4939       outs() << " " << name;
   4940     outs() << "\n";
   4941 
   4942     outs() << "  sel ";
   4943     sym_name = get_symbol_64(offset + offsetof(struct message_ref64, sel), S,
   4944                              info, n_value, mr.sel);
   4945     if (n_value != 0) {
   4946       if (info->verbose && sym_name != nullptr)
   4947         outs() << sym_name;
   4948       else
   4949         outs() << format("0x%" PRIx64, n_value);
   4950       if (mr.sel != 0)
   4951         outs() << " + " << format("0x%" PRIx64, mr.sel);
   4952     } else
   4953       outs() << format("0x%" PRIx64, mr.sel);
   4954     name = get_pointer_64(mr.sel + n_value, xoffset, left, xS, info);
   4955     if (name != nullptr)
   4956       outs() << format(" %.*s", left, name);
   4957     outs() << "\n";
   4958 
   4959     offset += sizeof(struct message_ref64);
   4960   }
   4961 }
   4962 
   4963 static void print_message_refs32(SectionRef S, struct DisassembleInfo *info) {
   4964   uint32_t i, left, offset, xoffset, p;
   4965   struct message_ref32 mr;
   4966   const char *name, *r;
   4967   SectionRef xS;
   4968 
   4969   if (S == SectionRef())
   4970     return;
   4971 
   4972   StringRef SectName;
   4973   S.getName(SectName);
   4974   DataRefImpl Ref = S.getRawDataRefImpl();
   4975   StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
   4976   outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
   4977   offset = 0;
   4978   for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) {
   4979     p = S.getAddress() + i;
   4980     r = get_pointer_32(p, offset, left, S, info);
   4981     if (r == nullptr)
   4982       return;
   4983     memset(&mr, '\0', sizeof(struct message_ref32));
   4984     if (left < sizeof(struct message_ref32)) {
   4985       memcpy(&mr, r, left);
   4986       outs() << "   (message_ref entends past the end of the section)\n";
   4987     } else
   4988       memcpy(&mr, r, sizeof(struct message_ref32));
   4989     if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
   4990       swapStruct(mr);
   4991 
   4992     outs() << "  imp " << format("0x%" PRIx32, mr.imp);
   4993     name = get_symbol_32(offset + offsetof(struct message_ref32, imp), S, info,
   4994                          mr.imp);
   4995     if (name != nullptr)
   4996       outs() << " " << name;
   4997     outs() << "\n";
   4998 
   4999     outs() << "  sel " << format("0x%" PRIx32, mr.sel);
   5000     name = get_pointer_32(mr.sel, xoffset, left, xS, info);
   5001     if (name != nullptr)
   5002       outs() << " " << name;
   5003     outs() << "\n";
   5004 
   5005     offset += sizeof(struct message_ref32);
   5006   }
   5007 }
   5008 
   5009 static void print_image_info64(SectionRef S, struct DisassembleInfo *info) {
   5010   uint32_t left, offset, swift_version;
   5011   uint64_t p;
   5012   struct objc_image_info64 o;
   5013   const char *r;
   5014 
   5015   if (S == SectionRef())
   5016     return;
   5017 
   5018   StringRef SectName;
   5019   S.getName(SectName);
   5020   DataRefImpl Ref = S.getRawDataRefImpl();
   5021   StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
   5022   outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
   5023   p = S.getAddress();
   5024   r = get_pointer_64(p, offset, left, S, info);
   5025   if (r == nullptr)
   5026     return;
   5027   memset(&o, '\0', sizeof(struct objc_image_info64));
   5028   if (left < sizeof(struct objc_image_info64)) {
   5029     memcpy(&o, r, left);
   5030     outs() << "   (objc_image_info entends past the end of the section)\n";
   5031   } else
   5032     memcpy(&o, r, sizeof(struct objc_image_info64));
   5033   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
   5034     swapStruct(o);
   5035   outs() << "  version " << o.version << "\n";
   5036   outs() << "    flags " << format("0x%" PRIx32, o.flags);
   5037   if (o.flags & OBJC_IMAGE_IS_REPLACEMENT)
   5038     outs() << " OBJC_IMAGE_IS_REPLACEMENT";
   5039   if (o.flags & OBJC_IMAGE_SUPPORTS_GC)
   5040     outs() << " OBJC_IMAGE_SUPPORTS_GC";
   5041   swift_version = (o.flags >> 8) & 0xff;
   5042   if (swift_version != 0) {
   5043     if (swift_version == 1)
   5044       outs() << " Swift 1.0";
   5045     else if (swift_version == 2)
   5046       outs() << " Swift 1.1";
   5047     else
   5048       outs() << " unknown future Swift version (" << swift_version << ")";
   5049   }
   5050   outs() << "\n";
   5051 }
   5052 
   5053 static void print_image_info32(SectionRef S, struct DisassembleInfo *info) {
   5054   uint32_t left, offset, swift_version, p;
   5055   struct objc_image_info32 o;
   5056   const char *r;
   5057 
   5058   StringRef SectName;
   5059   S.getName(SectName);
   5060   DataRefImpl Ref = S.getRawDataRefImpl();
   5061   StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
   5062   outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
   5063   p = S.getAddress();
   5064   r = get_pointer_32(p, offset, left, S, info);
   5065   if (r == nullptr)
   5066     return;
   5067   memset(&o, '\0', sizeof(struct objc_image_info32));
   5068   if (left < sizeof(struct objc_image_info32)) {
   5069     memcpy(&o, r, left);
   5070     outs() << "   (objc_image_info entends past the end of the section)\n";
   5071   } else
   5072     memcpy(&o, r, sizeof(struct objc_image_info32));
   5073   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
   5074     swapStruct(o);
   5075   outs() << "  version " << o.version << "\n";
   5076   outs() << "    flags " << format("0x%" PRIx32, o.flags);
   5077   if (o.flags & OBJC_IMAGE_IS_REPLACEMENT)
   5078     outs() << " OBJC_IMAGE_IS_REPLACEMENT";
   5079   if (o.flags & OBJC_IMAGE_SUPPORTS_GC)
   5080     outs() << " OBJC_IMAGE_SUPPORTS_GC";
   5081   swift_version = (o.flags >> 8) & 0xff;
   5082   if (swift_version != 0) {
   5083     if (swift_version == 1)
   5084       outs() << " Swift 1.0";
   5085     else if (swift_version == 2)
   5086       outs() << " Swift 1.1";
   5087     else
   5088       outs() << " unknown future Swift version (" << swift_version << ")";
   5089   }
   5090   outs() << "\n";
   5091 }
   5092 
   5093 static void print_image_info(SectionRef S, struct DisassembleInfo *info) {
   5094   uint32_t left, offset, p;
   5095   struct imageInfo_t o;
   5096   const char *r;
   5097 
   5098   StringRef SectName;
   5099   S.getName(SectName);
   5100   DataRefImpl Ref = S.getRawDataRefImpl();
   5101   StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
   5102   outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
   5103   p = S.getAddress();
   5104   r = get_pointer_32(p, offset, left, S, info);
   5105   if (r == nullptr)
   5106     return;
   5107   memset(&o, '\0', sizeof(struct imageInfo_t));
   5108   if (left < sizeof(struct imageInfo_t)) {
   5109     memcpy(&o, r, left);
   5110     outs() << " (imageInfo entends past the end of the section)\n";
   5111   } else
   5112     memcpy(&o, r, sizeof(struct imageInfo_t));
   5113   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
   5114     swapStruct(o);
   5115   outs() << "  version " << o.version << "\n";
   5116   outs() << "    flags " << format("0x%" PRIx32, o.flags);
   5117   if (o.flags & 0x1)
   5118     outs() << "  F&C";
   5119   if (o.flags & 0x2)
   5120     outs() << " GC";
   5121   if (o.flags & 0x4)
   5122     outs() << " GC-only";
   5123   else
   5124     outs() << " RR";
   5125   outs() << "\n";
   5126 }
   5127 
   5128 static void printObjc2_64bit_MetaData(MachOObjectFile *O, bool verbose) {
   5129   SymbolAddressMap AddrMap;
   5130   if (verbose)
   5131     CreateSymbolAddressMap(O, &AddrMap);
   5132 
   5133   std::vector<SectionRef> Sections;
   5134   for (const SectionRef &Section : O->sections()) {
   5135     StringRef SectName;
   5136     Section.getName(SectName);
   5137     Sections.push_back(Section);
   5138   }
   5139 
   5140   struct DisassembleInfo info;
   5141   // Set up the block of info used by the Symbolizer call backs.
   5142   info.verbose = verbose;
   5143   info.O = O;
   5144   info.AddrMap = &AddrMap;
   5145   info.Sections = &Sections;
   5146   info.class_name = nullptr;
   5147   info.selector_name = nullptr;
   5148   info.method = nullptr;
   5149   info.demangled_name = nullptr;
   5150   info.bindtable = nullptr;
   5151   info.adrp_addr = 0;
   5152   info.adrp_inst = 0;
   5153 
   5154   info.depth = 0;
   5155   SectionRef CL = get_section(O, "__OBJC2", "__class_list");
   5156   if (CL == SectionRef())
   5157     CL = get_section(O, "__DATA", "__objc_classlist");
   5158   info.S = CL;
   5159   walk_pointer_list_64("class", CL, O, &info, print_class64_t);
   5160 
   5161   SectionRef CR = get_section(O, "__OBJC2", "__class_refs");
   5162   if (CR == SectionRef())
   5163     CR = get_section(O, "__DATA", "__objc_classrefs");
   5164   info.S = CR;
   5165   walk_pointer_list_64("class refs", CR, O, &info, nullptr);
   5166 
   5167   SectionRef SR = get_section(O, "__OBJC2", "__super_refs");
   5168   if (SR == SectionRef())
   5169     SR = get_section(O, "__DATA", "__objc_superrefs");
   5170   info.S = SR;
   5171   walk_pointer_list_64("super refs", SR, O, &info, nullptr);
   5172 
   5173   SectionRef CA = get_section(O, "__OBJC2", "__category_list");
   5174   if (CA == SectionRef())
   5175     CA = get_section(O, "__DATA", "__objc_catlist");
   5176   info.S = CA;
   5177   walk_pointer_list_64("category", CA, O, &info, print_category64_t);
   5178 
   5179   SectionRef PL = get_section(O, "__OBJC2", "__protocol_list");
   5180   if (PL == SectionRef())
   5181     PL = get_section(O, "__DATA", "__objc_protolist");
   5182   info.S = PL;
   5183   walk_pointer_list_64("protocol", PL, O, &info, nullptr);
   5184 
   5185   SectionRef MR = get_section(O, "__OBJC2", "__message_refs");
   5186   if (MR == SectionRef())
   5187     MR = get_section(O, "__DATA", "__objc_msgrefs");
   5188   info.S = MR;
   5189   print_message_refs64(MR, &info);
   5190 
   5191   SectionRef II = get_section(O, "__OBJC2", "__image_info");
   5192   if (II == SectionRef())
   5193     II = get_section(O, "__DATA", "__objc_imageinfo");
   5194   info.S = II;
   5195   print_image_info64(II, &info);
   5196 
   5197   if (info.bindtable != nullptr)
   5198     delete info.bindtable;
   5199 }
   5200 
   5201 static void printObjc2_32bit_MetaData(MachOObjectFile *O, bool verbose) {
   5202   SymbolAddressMap AddrMap;
   5203   if (verbose)
   5204     CreateSymbolAddressMap(O, &AddrMap);
   5205 
   5206   std::vector<SectionRef> Sections;
   5207   for (const SectionRef &Section : O->sections()) {
   5208     StringRef SectName;
   5209     Section.getName(SectName);
   5210     Sections.push_back(Section);
   5211   }
   5212 
   5213   struct DisassembleInfo info;
   5214   // Set up the block of info used by the Symbolizer call backs.
   5215   info.verbose = verbose;
   5216   info.O = O;
   5217   info.AddrMap = &AddrMap;
   5218   info.Sections = &Sections;
   5219   info.class_name = nullptr;
   5220   info.selector_name = nullptr;
   5221   info.method = nullptr;
   5222   info.demangled_name = nullptr;
   5223   info.bindtable = nullptr;
   5224   info.adrp_addr = 0;
   5225   info.adrp_inst = 0;
   5226 
   5227   const SectionRef CL = get_section(O, "__OBJC2", "__class_list");
   5228   if (CL != SectionRef()) {
   5229     info.S = CL;
   5230     walk_pointer_list_32("class", CL, O, &info, print_class32_t);
   5231   } else {
   5232     const SectionRef CL = get_section(O, "__DATA", "__objc_classlist");
   5233     info.S = CL;
   5234     walk_pointer_list_32("class", CL, O, &info, print_class32_t);
   5235   }
   5236 
   5237   const SectionRef CR = get_section(O, "__OBJC2", "__class_refs");
   5238   if (CR != SectionRef()) {
   5239     info.S = CR;
   5240     walk_pointer_list_32("class refs", CR, O, &info, nullptr);
   5241   } else {
   5242     const SectionRef CR = get_section(O, "__DATA", "__objc_classrefs");
   5243     info.S = CR;
   5244     walk_pointer_list_32("class refs", CR, O, &info, nullptr);
   5245   }
   5246 
   5247   const SectionRef SR = get_section(O, "__OBJC2", "__super_refs");
   5248   if (SR != SectionRef()) {
   5249     info.S = SR;
   5250     walk_pointer_list_32("super refs", SR, O, &info, nullptr);
   5251   } else {
   5252     const SectionRef SR = get_section(O, "__DATA", "__objc_superrefs");
   5253     info.S = SR;
   5254     walk_pointer_list_32("super refs", SR, O, &info, nullptr);
   5255   }
   5256 
   5257   const SectionRef CA = get_section(O, "__OBJC2", "__category_list");
   5258   if (CA != SectionRef()) {
   5259     info.S = CA;
   5260     walk_pointer_list_32("category", CA, O, &info, print_category32_t);
   5261   } else {
   5262     const SectionRef CA = get_section(O, "__DATA", "__objc_catlist");
   5263     info.S = CA;
   5264     walk_pointer_list_32("category", CA, O, &info, print_category32_t);
   5265   }
   5266 
   5267   const SectionRef PL = get_section(O, "__OBJC2", "__protocol_list");
   5268   if (PL != SectionRef()) {
   5269     info.S = PL;
   5270     walk_pointer_list_32("protocol", PL, O, &info, nullptr);
   5271   } else {
   5272     const SectionRef PL = get_section(O, "__DATA", "__objc_protolist");
   5273     info.S = PL;
   5274     walk_pointer_list_32("protocol", PL, O, &info, nullptr);
   5275   }
   5276 
   5277   const SectionRef MR = get_section(O, "__OBJC2", "__message_refs");
   5278   if (MR != SectionRef()) {
   5279     info.S = MR;
   5280     print_message_refs32(MR, &info);
   5281   } else {
   5282     const SectionRef MR = get_section(O, "__DATA", "__objc_msgrefs");
   5283     info.S = MR;
   5284     print_message_refs32(MR, &info);
   5285   }
   5286 
   5287   const SectionRef II = get_section(O, "__OBJC2", "__image_info");
   5288   if (II != SectionRef()) {
   5289     info.S = II;
   5290     print_image_info32(II, &info);
   5291   } else {
   5292     const SectionRef II = get_section(O, "__DATA", "__objc_imageinfo");
   5293     info.S = II;
   5294     print_image_info32(II, &info);
   5295   }
   5296 }
   5297 
   5298 static bool printObjc1_32bit_MetaData(MachOObjectFile *O, bool verbose) {
   5299   uint32_t i, j, p, offset, xoffset, left, defs_left, def;
   5300   const char *r, *name, *defs;
   5301   struct objc_module_t module;
   5302   SectionRef S, xS;
   5303   struct objc_symtab_t symtab;
   5304   struct objc_class_t objc_class;
   5305   struct objc_category_t objc_category;
   5306 
   5307   outs() << "Objective-C segment\n";
   5308   S = get_section(O, "__OBJC", "__module_info");
   5309   if (S == SectionRef())
   5310     return false;
   5311 
   5312   SymbolAddressMap AddrMap;
   5313   if (verbose)
   5314     CreateSymbolAddressMap(O, &AddrMap);
   5315 
   5316   std::vector<SectionRef> Sections;
   5317   for (const SectionRef &Section : O->sections()) {
   5318     StringRef SectName;
   5319     Section.getName(SectName);
   5320     Sections.push_back(Section);
   5321   }
   5322 
   5323   struct DisassembleInfo info;
   5324   // Set up the block of info used by the Symbolizer call backs.
   5325   info.verbose = verbose;
   5326   info.O = O;
   5327   info.AddrMap = &AddrMap;
   5328   info.Sections = &Sections;
   5329   info.class_name = nullptr;
   5330   info.selector_name = nullptr;
   5331   info.method = nullptr;
   5332   info.demangled_name = nullptr;
   5333   info.bindtable = nullptr;
   5334   info.adrp_addr = 0;
   5335   info.adrp_inst = 0;
   5336 
   5337   for (i = 0; i < S.getSize(); i += sizeof(struct objc_module_t)) {
   5338     p = S.getAddress() + i;
   5339     r = get_pointer_32(p, offset, left, S, &info, true);
   5340     if (r == nullptr)
   5341       return true;
   5342     memset(&module, '\0', sizeof(struct objc_module_t));
   5343     if (left < sizeof(struct objc_module_t)) {
   5344       memcpy(&module, r, left);
   5345       outs() << "   (module extends past end of __module_info section)\n";
   5346     } else
   5347       memcpy(&module, r, sizeof(struct objc_module_t));
   5348     if (O->isLittleEndian() != sys::IsLittleEndianHost)
   5349       swapStruct(module);
   5350 
   5351     outs() << "Module " << format("0x%" PRIx32, p) << "\n";
   5352     outs() << "    version " << module.version << "\n";
   5353     outs() << "       size " << module.size << "\n";
   5354     outs() << "       name ";
   5355     name = get_pointer_32(module.name, xoffset, left, xS, &info, true);
   5356     if (name != nullptr)
   5357       outs() << format("%.*s", left, name);
   5358     else
   5359       outs() << format("0x%08" PRIx32, module.name)
   5360              << "(not in an __OBJC section)";
   5361     outs() << "\n";
   5362 
   5363     r = get_pointer_32(module.symtab, xoffset, left, xS, &info, true);
   5364     if (module.symtab == 0 || r == nullptr) {
   5365       outs() << "     symtab " << format("0x%08" PRIx32, module.symtab)
   5366              << " (not in an __OBJC section)\n";
   5367       continue;
   5368     }
   5369     outs() << "     symtab " << format("0x%08" PRIx32, module.symtab) << "\n";
   5370     memset(&symtab, '\0', sizeof(struct objc_symtab_t));
   5371     defs_left = 0;
   5372     defs = nullptr;
   5373     if (left < sizeof(struct objc_symtab_t)) {
   5374       memcpy(&symtab, r, left);
   5375       outs() << "\tsymtab extends past end of an __OBJC section)\n";
   5376     } else {
   5377       memcpy(&symtab, r, sizeof(struct objc_symtab_t));
   5378       if (left > sizeof(struct objc_symtab_t)) {
   5379         defs_left = left - sizeof(struct objc_symtab_t);
   5380         defs = r + sizeof(struct objc_symtab_t);
   5381       }
   5382     }
   5383     if (O->isLittleEndian() != sys::IsLittleEndianHost)
   5384       swapStruct(symtab);
   5385 
   5386     outs() << "\tsel_ref_cnt " << symtab.sel_ref_cnt << "\n";
   5387     r = get_pointer_32(symtab.refs, xoffset, left, xS, &info, true);
   5388     outs() << "\trefs " << format("0x%08" PRIx32, symtab.refs);
   5389     if (r == nullptr)
   5390       outs() << " (not in an __OBJC section)";
   5391     outs() << "\n";
   5392     outs() << "\tcls_def_cnt " << symtab.cls_def_cnt << "\n";
   5393     outs() << "\tcat_def_cnt " << symtab.cat_def_cnt << "\n";
   5394     if (symtab.cls_def_cnt > 0)
   5395       outs() << "\tClass Definitions\n";
   5396     for (j = 0; j < symtab.cls_def_cnt; j++) {
   5397       if ((j + 1) * sizeof(uint32_t) > defs_left) {
   5398         outs() << "\t(remaining class defs entries entends past the end of the "
   5399                << "section)\n";
   5400         break;
   5401       }
   5402       memcpy(&def, defs + j * sizeof(uint32_t), sizeof(uint32_t));
   5403       if (O->isLittleEndian() != sys::IsLittleEndianHost)
   5404         sys::swapByteOrder(def);
   5405 
   5406       r = get_pointer_32(def, xoffset, left, xS, &info, true);
   5407       outs() << "\tdefs[" << j << "] " << format("0x%08" PRIx32, def);
   5408       if (r != nullptr) {
   5409         if (left > sizeof(struct objc_class_t)) {
   5410           outs() << "\n";
   5411           memcpy(&objc_class, r, sizeof(struct objc_class_t));
   5412         } else {
   5413           outs() << " (entends past the end of the section)\n";
   5414           memset(&objc_class, '\0', sizeof(struct objc_class_t));
   5415           memcpy(&objc_class, r, left);
   5416         }
   5417         if (O->isLittleEndian() != sys::IsLittleEndianHost)
   5418           swapStruct(objc_class);
   5419         print_objc_class_t(&objc_class, &info);
   5420       } else {
   5421         outs() << "(not in an __OBJC section)\n";
   5422       }
   5423 
   5424       if (CLS_GETINFO(&objc_class, CLS_CLASS)) {
   5425         outs() << "\tMeta Class";
   5426         r = get_pointer_32(objc_class.isa, xoffset, left, xS, &info, true);
   5427         if (r != nullptr) {
   5428           if (left > sizeof(struct objc_class_t)) {
   5429             outs() << "\n";
   5430             memcpy(&objc_class, r, sizeof(struct objc_class_t));
   5431           } else {
   5432             outs() << " (entends past the end of the section)\n";
   5433             memset(&objc_class, '\0', sizeof(struct objc_class_t));
   5434             memcpy(&objc_class, r, left);
   5435           }
   5436           if (O->isLittleEndian() != sys::IsLittleEndianHost)
   5437             swapStruct(objc_class);
   5438           print_objc_class_t(&objc_class, &info);
   5439         } else {
   5440           outs() << "(not in an __OBJC section)\n";
   5441         }
   5442       }
   5443     }
   5444     if (symtab.cat_def_cnt > 0)
   5445       outs() << "\tCategory Definitions\n";
   5446     for (j = 0; j < symtab.cat_def_cnt; j++) {
   5447       if ((j + symtab.cls_def_cnt + 1) * sizeof(uint32_t) > defs_left) {
   5448         outs() << "\t(remaining category defs entries entends past the end of "
   5449                << "the section)\n";
   5450         break;
   5451       }
   5452       memcpy(&def, defs + (j + symtab.cls_def_cnt) * sizeof(uint32_t),
   5453              sizeof(uint32_t));
   5454       if (O->isLittleEndian() != sys::IsLittleEndianHost)
   5455         sys::swapByteOrder(def);
   5456 
   5457       r = get_pointer_32(def, xoffset, left, xS, &info, true);
   5458       outs() << "\tdefs[" << j + symtab.cls_def_cnt << "] "
   5459              << format("0x%08" PRIx32, def);
   5460       if (r != nullptr) {
   5461         if (left > sizeof(struct objc_category_t)) {
   5462           outs() << "\n";
   5463           memcpy(&objc_category, r, sizeof(struct objc_category_t));
   5464         } else {
   5465           outs() << " (entends past the end of the section)\n";
   5466           memset(&objc_category, '\0', sizeof(struct objc_category_t));
   5467           memcpy(&objc_category, r, left);
   5468         }
   5469         if (O->isLittleEndian() != sys::IsLittleEndianHost)
   5470           swapStruct(objc_category);
   5471         print_objc_objc_category_t(&objc_category, &info);
   5472       } else {
   5473         outs() << "(not in an __OBJC section)\n";
   5474       }
   5475     }
   5476   }
   5477   const SectionRef II = get_section(O, "__OBJC", "__image_info");
   5478   if (II != SectionRef())
   5479     print_image_info(II, &info);
   5480 
   5481   return true;
   5482 }
   5483 
   5484 static void DumpProtocolSection(MachOObjectFile *O, const char *sect,
   5485                                 uint32_t size, uint32_t addr) {
   5486   SymbolAddressMap AddrMap;
   5487   CreateSymbolAddressMap(O, &AddrMap);
   5488 
   5489   std::vector<SectionRef> Sections;
   5490   for (const SectionRef &Section : O->sections()) {
   5491     StringRef SectName;
   5492     Section.getName(SectName);
   5493     Sections.push_back(Section);
   5494   }
   5495 
   5496   struct DisassembleInfo info;
   5497   // Set up the block of info used by the Symbolizer call backs.
   5498   info.verbose = true;
   5499   info.O = O;
   5500   info.AddrMap = &AddrMap;
   5501   info.Sections = &Sections;
   5502   info.class_name = nullptr;
   5503   info.selector_name = nullptr;
   5504   info.method = nullptr;
   5505   info.demangled_name = nullptr;
   5506   info.bindtable = nullptr;
   5507   info.adrp_addr = 0;
   5508   info.adrp_inst = 0;
   5509 
   5510   const char *p;
   5511   struct objc_protocol_t protocol;
   5512   uint32_t left, paddr;
   5513   for (p = sect; p < sect + size; p += sizeof(struct objc_protocol_t)) {
   5514     memset(&protocol, '\0', sizeof(struct objc_protocol_t));
   5515     left = size - (p - sect);
   5516     if (left < sizeof(struct objc_protocol_t)) {
   5517       outs() << "Protocol extends past end of __protocol section\n";
   5518       memcpy(&protocol, p, left);
   5519     } else
   5520       memcpy(&protocol, p, sizeof(struct objc_protocol_t));
   5521     if (O->isLittleEndian() != sys::IsLittleEndianHost)
   5522       swapStruct(protocol);
   5523     paddr = addr + (p - sect);
   5524     outs() << "Protocol " << format("0x%" PRIx32, paddr);
   5525     if (print_protocol(paddr, 0, &info))
   5526       outs() << "(not in an __OBJC section)\n";
   5527   }
   5528 }
   5529 
   5530 static void printObjcMetaData(MachOObjectFile *O, bool verbose) {
   5531   if (O->is64Bit())
   5532     printObjc2_64bit_MetaData(O, verbose);
   5533   else {
   5534     MachO::mach_header H;
   5535     H = O->getHeader();
   5536     if (H.cputype == MachO::CPU_TYPE_ARM)
   5537       printObjc2_32bit_MetaData(O, verbose);
   5538     else {
   5539       // This is the 32-bit non-arm cputype case.  Which is normally
   5540       // the first Objective-C ABI.  But it may be the case of a
   5541       // binary for the iOS simulator which is the second Objective-C
   5542       // ABI.  In that case printObjc1_32bit_MetaData() will determine that
   5543       // and return false.
   5544       if (!printObjc1_32bit_MetaData(O, verbose))
   5545         printObjc2_32bit_MetaData(O, verbose);
   5546     }
   5547   }
   5548 }
   5549 
   5550 // GuessLiteralPointer returns a string which for the item in the Mach-O file
   5551 // for the address passed in as ReferenceValue for printing as a comment with
   5552 // the instruction and also returns the corresponding type of that item
   5553 // indirectly through ReferenceType.
   5554 //
   5555 // If ReferenceValue is an address of literal cstring then a pointer to the
   5556 // cstring is returned and ReferenceType is set to
   5557 // LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr .
   5558 //
   5559 // If ReferenceValue is an address of an Objective-C CFString, Selector ref or
   5560 // Class ref that name is returned and the ReferenceType is set accordingly.
   5561 //
   5562 // Lastly, literals which are Symbol address in a literal pool are looked for
   5563 // and if found the symbol name is returned and ReferenceType is set to
   5564 // LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr .
   5565 //
   5566 // If there is no item in the Mach-O file for the address passed in as
   5567 // ReferenceValue nullptr is returned and ReferenceType is unchanged.
   5568 static const char *GuessLiteralPointer(uint64_t ReferenceValue,
   5569                                        uint64_t ReferencePC,
   5570                                        uint64_t *ReferenceType,
   5571                                        struct DisassembleInfo *info) {
   5572   // First see if there is an external relocation entry at the ReferencePC.
   5573   if (info->O->getHeader().filetype == MachO::MH_OBJECT) {
   5574     uint64_t sect_addr = info->S.getAddress();
   5575     uint64_t sect_offset = ReferencePC - sect_addr;
   5576     bool reloc_found = false;
   5577     DataRefImpl Rel;
   5578     MachO::any_relocation_info RE;
   5579     bool isExtern = false;
   5580     SymbolRef Symbol;
   5581     for (const RelocationRef &Reloc : info->S.relocations()) {
   5582       uint64_t RelocOffset = Reloc.getOffset();
   5583       if (RelocOffset == sect_offset) {
   5584         Rel = Reloc.getRawDataRefImpl();
   5585         RE = info->O->getRelocation(Rel);
   5586         if (info->O->isRelocationScattered(RE))
   5587           continue;
   5588         isExtern = info->O->getPlainRelocationExternal(RE);
   5589         if (isExtern) {
   5590           symbol_iterator RelocSym = Reloc.getSymbol();
   5591           Symbol = *RelocSym;
   5592         }
   5593         reloc_found = true;
   5594         break;
   5595       }
   5596     }
   5597     // If there is an external relocation entry for a symbol in a section
   5598     // then used that symbol's value for the value of the reference.
   5599     if (reloc_found && isExtern) {
   5600       if (info->O->getAnyRelocationPCRel(RE)) {
   5601         unsigned Type = info->O->getAnyRelocationType(RE);
   5602         if (Type == MachO::X86_64_RELOC_SIGNED) {
   5603           ReferenceValue = Symbol.getValue();
   5604         }
   5605       }
   5606     }
   5607   }
   5608 
   5609   // Look for literals such as Objective-C CFStrings refs, Selector refs,
   5610   // Message refs and Class refs.
   5611   bool classref, selref, msgref, cfstring;
   5612   uint64_t pointer_value = GuessPointerPointer(ReferenceValue, info, classref,
   5613                                                selref, msgref, cfstring);
   5614   if (classref && pointer_value == 0) {
   5615     // Note the ReferenceValue is a pointer into the __objc_classrefs section.
   5616     // And the pointer_value in that section is typically zero as it will be
   5617     // set by dyld as part of the "bind information".
   5618     const char *name = get_dyld_bind_info_symbolname(ReferenceValue, info);
   5619     if (name != nullptr) {
   5620       *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
   5621       const char *class_name = strrchr(name, '$');
   5622       if (class_name != nullptr && class_name[1] == '_' &&
   5623           class_name[2] != '\0') {
   5624         info->class_name = class_name + 2;
   5625         return name;
   5626       }
   5627     }
   5628   }
   5629 
   5630   if (classref) {
   5631     *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
   5632     const char *name =
   5633         get_objc2_64bit_class_name(pointer_value, ReferenceValue, info);
   5634     if (name != nullptr)
   5635       info->class_name = name;
   5636     else
   5637       name = "bad class ref";
   5638     return name;
   5639   }
   5640 
   5641   if (cfstring) {
   5642     *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_CFString_Ref;
   5643     const char *name = get_objc2_64bit_cfstring_name(ReferenceValue, info);
   5644     return name;
   5645   }
   5646 
   5647   if (selref && pointer_value == 0)
   5648     pointer_value = get_objc2_64bit_selref(ReferenceValue, info);
   5649 
   5650   if (pointer_value != 0)
   5651     ReferenceValue = pointer_value;
   5652 
   5653   const char *name = GuessCstringPointer(ReferenceValue, info);
   5654   if (name) {
   5655     if (pointer_value != 0 && selref) {
   5656       *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Selector_Ref;
   5657       info->selector_name = name;
   5658     } else if (pointer_value != 0 && msgref) {
   5659       info->class_name = nullptr;
   5660       *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message_Ref;
   5661       info->selector_name = name;
   5662     } else
   5663       *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr;
   5664     return name;
   5665   }
   5666 
   5667   // Lastly look for an indirect symbol with this ReferenceValue which is in
   5668   // a literal pool.  If found return that symbol name.
   5669   name = GuessIndirectSymbol(ReferenceValue, info);
   5670   if (name) {
   5671     *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr;
   5672     return name;
   5673   }
   5674 
   5675   return nullptr;
   5676 }
   5677 
   5678 // SymbolizerSymbolLookUp is the symbol lookup function passed when creating
   5679 // the Symbolizer.  It looks up the ReferenceValue using the info passed via the
   5680 // pointer to the struct DisassembleInfo that was passed when MCSymbolizer
   5681 // is created and returns the symbol name that matches the ReferenceValue or
   5682 // nullptr if none.  The ReferenceType is passed in for the IN type of
   5683 // reference the instruction is making from the values in defined in the header
   5684 // "llvm-c/Disassembler.h".  On return the ReferenceType can set to a specific
   5685 // Out type and the ReferenceName will also be set which is added as a comment
   5686 // to the disassembled instruction.
   5687 //
   5688 #if HAVE_CXXABI_H
   5689 // If the symbol name is a C++ mangled name then the demangled name is
   5690 // returned through ReferenceName and ReferenceType is set to
   5691 // LLVMDisassembler_ReferenceType_DeMangled_Name .
   5692 #endif
   5693 //
   5694 // When this is called to get a symbol name for a branch target then the
   5695 // ReferenceType will be LLVMDisassembler_ReferenceType_In_Branch and then
   5696 // SymbolValue will be looked for in the indirect symbol table to determine if
   5697 // it is an address for a symbol stub.  If so then the symbol name for that
   5698 // stub is returned indirectly through ReferenceName and then ReferenceType is
   5699 // set to LLVMDisassembler_ReferenceType_Out_SymbolStub.
   5700 //
   5701 // When this is called with an value loaded via a PC relative load then
   5702 // ReferenceType will be LLVMDisassembler_ReferenceType_In_PCrel_Load then the
   5703 // SymbolValue is checked to be an address of literal pointer, symbol pointer,
   5704 // or an Objective-C meta data reference.  If so the output ReferenceType is
   5705 // set to correspond to that as well as setting the ReferenceName.
   5706 static const char *SymbolizerSymbolLookUp(void *DisInfo,
   5707                                           uint64_t ReferenceValue,
   5708                                           uint64_t *ReferenceType,
   5709                                           uint64_t ReferencePC,
   5710                                           const char **ReferenceName) {
   5711   struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
   5712   // If no verbose symbolic information is wanted then just return nullptr.
   5713   if (!info->verbose) {
   5714     *ReferenceName = nullptr;
   5715     *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
   5716     return nullptr;
   5717   }
   5718 
   5719   const char *SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
   5720 
   5721   if (*ReferenceType == LLVMDisassembler_ReferenceType_In_Branch) {
   5722     *ReferenceName = GuessIndirectSymbol(ReferenceValue, info);
   5723     if (*ReferenceName != nullptr) {
   5724       method_reference(info, ReferenceType, ReferenceName);
   5725       if (*ReferenceType != LLVMDisassembler_ReferenceType_Out_Objc_Message)
   5726         *ReferenceType = LLVMDisassembler_ReferenceType_Out_SymbolStub;
   5727     } else
   5728 #if HAVE_CXXABI_H
   5729         if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
   5730       if (info->demangled_name != nullptr)
   5731         free(info->demangled_name);
   5732       int status;
   5733       info->demangled_name =
   5734           abi::__cxa_demangle(SymbolName + 1, nullptr, nullptr, &status);
   5735       if (info->demangled_name != nullptr) {
   5736         *ReferenceName = info->demangled_name;
   5737         *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
   5738       } else
   5739         *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
   5740     } else
   5741 #endif
   5742       *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
   5743   } else if (*ReferenceType == LLVMDisassembler_ReferenceType_In_PCrel_Load) {
   5744     *ReferenceName =
   5745         GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
   5746     if (*ReferenceName)
   5747       method_reference(info, ReferenceType, ReferenceName);
   5748     else
   5749       *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
   5750     // If this is arm64 and the reference is an adrp instruction save the
   5751     // instruction, passed in ReferenceValue and the address of the instruction
   5752     // for use later if we see and add immediate instruction.
   5753   } else if (info->O->getArch() == Triple::aarch64 &&
   5754              *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADRP) {
   5755     info->adrp_inst = ReferenceValue;
   5756     info->adrp_addr = ReferencePC;
   5757     SymbolName = nullptr;
   5758     *ReferenceName = nullptr;
   5759     *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
   5760     // If this is arm64 and reference is an add immediate instruction and we
   5761     // have
   5762     // seen an adrp instruction just before it and the adrp's Xd register
   5763     // matches
   5764     // this add's Xn register reconstruct the value being referenced and look to
   5765     // see if it is a literal pointer.  Note the add immediate instruction is
   5766     // passed in ReferenceValue.
   5767   } else if (info->O->getArch() == Triple::aarch64 &&
   5768              *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADDXri &&
   5769              ReferencePC - 4 == info->adrp_addr &&
   5770              (info->adrp_inst & 0x9f000000) == 0x90000000 &&
   5771              (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
   5772     uint32_t addxri_inst;
   5773     uint64_t adrp_imm, addxri_imm;
   5774 
   5775     adrp_imm =
   5776         ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
   5777     if (info->adrp_inst & 0x0200000)
   5778       adrp_imm |= 0xfffffffffc000000LL;
   5779 
   5780     addxri_inst = ReferenceValue;
   5781     addxri_imm = (addxri_inst >> 10) & 0xfff;
   5782     if (((addxri_inst >> 22) & 0x3) == 1)
   5783       addxri_imm <<= 12;
   5784 
   5785     ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
   5786                      (adrp_imm << 12) + addxri_imm;
   5787 
   5788     *ReferenceName =
   5789         GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
   5790     if (*ReferenceName == nullptr)
   5791       *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
   5792     // If this is arm64 and the reference is a load register instruction and we
   5793     // have seen an adrp instruction just before it and the adrp's Xd register
   5794     // matches this add's Xn register reconstruct the value being referenced and
   5795     // look to see if it is a literal pointer.  Note the load register
   5796     // instruction is passed in ReferenceValue.
   5797   } else if (info->O->getArch() == Triple::aarch64 &&
   5798              *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXui &&
   5799              ReferencePC - 4 == info->adrp_addr &&
   5800              (info->adrp_inst & 0x9f000000) == 0x90000000 &&
   5801              (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
   5802     uint32_t ldrxui_inst;
   5803     uint64_t adrp_imm, ldrxui_imm;
   5804 
   5805     adrp_imm =
   5806         ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
   5807     if (info->adrp_inst & 0x0200000)
   5808       adrp_imm |= 0xfffffffffc000000LL;
   5809 
   5810     ldrxui_inst = ReferenceValue;
   5811     ldrxui_imm = (ldrxui_inst >> 10) & 0xfff;
   5812 
   5813     ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
   5814                      (adrp_imm << 12) + (ldrxui_imm << 3);
   5815 
   5816     *ReferenceName =
   5817         GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
   5818     if (*ReferenceName == nullptr)
   5819       *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
   5820   }
   5821   // If this arm64 and is an load register (PC-relative) instruction the
   5822   // ReferenceValue is the PC plus the immediate value.
   5823   else if (info->O->getArch() == Triple::aarch64 &&
   5824            (*ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXl ||
   5825             *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADR)) {
   5826     *ReferenceName =
   5827         GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
   5828     if (*ReferenceName == nullptr)
   5829       *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
   5830   }
   5831 #if HAVE_CXXABI_H
   5832   else if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
   5833     if (info->demangled_name != nullptr)
   5834       free(info->demangled_name);
   5835     int status;
   5836     info->demangled_name =
   5837         abi::__cxa_demangle(SymbolName + 1, nullptr, nullptr, &status);
   5838     if (info->demangled_name != nullptr) {
   5839       *ReferenceName = info->demangled_name;
   5840       *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
   5841     }
   5842   }
   5843 #endif
   5844   else {
   5845     *ReferenceName = nullptr;
   5846     *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
   5847   }
   5848 
   5849   return SymbolName;
   5850 }
   5851 
   5852 /// \brief Emits the comments that are stored in the CommentStream.
   5853 /// Each comment in the CommentStream must end with a newline.
   5854 static void emitComments(raw_svector_ostream &CommentStream,
   5855                          SmallString<128> &CommentsToEmit,
   5856                          formatted_raw_ostream &FormattedOS,
   5857                          const MCAsmInfo &MAI) {
   5858   // Flush the stream before taking its content.
   5859   StringRef Comments = CommentsToEmit.str();
   5860   // Get the default information for printing a comment.
   5861   const char *CommentBegin = MAI.getCommentString();
   5862   unsigned CommentColumn = MAI.getCommentColumn();
   5863   bool IsFirst = true;
   5864   while (!Comments.empty()) {
   5865     if (!IsFirst)
   5866       FormattedOS << '\n';
   5867     // Emit a line of comments.
   5868     FormattedOS.PadToColumn(CommentColumn);
   5869     size_t Position = Comments.find('\n');
   5870     FormattedOS << CommentBegin << ' ' << Comments.substr(0, Position);
   5871     // Move after the newline character.
   5872     Comments = Comments.substr(Position + 1);
   5873     IsFirst = false;
   5874   }
   5875   FormattedOS.flush();
   5876 
   5877   // Tell the comment stream that the vector changed underneath it.
   5878   CommentsToEmit.clear();
   5879 }
   5880 
   5881 static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
   5882                              StringRef DisSegName, StringRef DisSectName) {
   5883   const char *McpuDefault = nullptr;
   5884   const Target *ThumbTarget = nullptr;
   5885   const Target *TheTarget = GetTarget(MachOOF, &McpuDefault, &ThumbTarget);
   5886   if (!TheTarget) {
   5887     // GetTarget prints out stuff.
   5888     return;
   5889   }
   5890   if (MCPU.empty() && McpuDefault)
   5891     MCPU = McpuDefault;
   5892 
   5893   std::unique_ptr<const MCInstrInfo> InstrInfo(TheTarget->createMCInstrInfo());
   5894   std::unique_ptr<const MCInstrInfo> ThumbInstrInfo;
   5895   if (ThumbTarget)
   5896     ThumbInstrInfo.reset(ThumbTarget->createMCInstrInfo());
   5897 
   5898   // Package up features to be passed to target/subtarget
   5899   std::string FeaturesStr;
   5900   if (MAttrs.size()) {
   5901     SubtargetFeatures Features;
   5902     for (unsigned i = 0; i != MAttrs.size(); ++i)
   5903       Features.AddFeature(MAttrs[i]);
   5904     FeaturesStr = Features.getString();
   5905   }
   5906 
   5907   // Set up disassembler.
   5908   std::unique_ptr<const MCRegisterInfo> MRI(
   5909       TheTarget->createMCRegInfo(TripleName));
   5910   std::unique_ptr<const MCAsmInfo> AsmInfo(
   5911       TheTarget->createMCAsmInfo(*MRI, TripleName));
   5912   std::unique_ptr<const MCSubtargetInfo> STI(
   5913       TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
   5914   MCContext Ctx(AsmInfo.get(), MRI.get(), nullptr);
   5915   std::unique_ptr<MCDisassembler> DisAsm(
   5916       TheTarget->createMCDisassembler(*STI, Ctx));
   5917   std::unique_ptr<MCSymbolizer> Symbolizer;
   5918   struct DisassembleInfo SymbolizerInfo;
   5919   std::unique_ptr<MCRelocationInfo> RelInfo(
   5920       TheTarget->createMCRelocationInfo(TripleName, Ctx));
   5921   if (RelInfo) {
   5922     Symbolizer.reset(TheTarget->createMCSymbolizer(
   5923         TripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
   5924         &SymbolizerInfo, &Ctx, std::move(RelInfo)));
   5925     DisAsm->setSymbolizer(std::move(Symbolizer));
   5926   }
   5927   int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
   5928   std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
   5929       Triple(TripleName), AsmPrinterVariant, *AsmInfo, *InstrInfo, *MRI));
   5930   // Set the display preference for hex vs. decimal immediates.
   5931   IP->setPrintImmHex(PrintImmHex);
   5932   // Comment stream and backing vector.
   5933   SmallString<128> CommentsToEmit;
   5934   raw_svector_ostream CommentStream(CommentsToEmit);
   5935   // FIXME: Setting the CommentStream in the InstPrinter is problematic in that
   5936   // if it is done then arm64 comments for string literals don't get printed
   5937   // and some constant get printed instead and not setting it causes intel
   5938   // (32-bit and 64-bit) comments printed with different spacing before the
   5939   // comment causing different diffs with the 'C' disassembler library API.
   5940   // IP->setCommentStream(CommentStream);
   5941 
   5942   if (!AsmInfo || !STI || !DisAsm || !IP) {
   5943     errs() << "error: couldn't initialize disassembler for target "
   5944            << TripleName << '\n';
   5945     return;
   5946   }
   5947 
   5948   // Set up thumb disassembler.
   5949   std::unique_ptr<const MCRegisterInfo> ThumbMRI;
   5950   std::unique_ptr<const MCAsmInfo> ThumbAsmInfo;
   5951   std::unique_ptr<const MCSubtargetInfo> ThumbSTI;
   5952   std::unique_ptr<MCDisassembler> ThumbDisAsm;
   5953   std::unique_ptr<MCInstPrinter> ThumbIP;
   5954   std::unique_ptr<MCContext> ThumbCtx;
   5955   std::unique_ptr<MCSymbolizer> ThumbSymbolizer;
   5956   struct DisassembleInfo ThumbSymbolizerInfo;
   5957   std::unique_ptr<MCRelocationInfo> ThumbRelInfo;
   5958   if (ThumbTarget) {
   5959     ThumbMRI.reset(ThumbTarget->createMCRegInfo(ThumbTripleName));
   5960     ThumbAsmInfo.reset(
   5961         ThumbTarget->createMCAsmInfo(*ThumbMRI, ThumbTripleName));
   5962     ThumbSTI.reset(
   5963         ThumbTarget->createMCSubtargetInfo(ThumbTripleName, MCPU, FeaturesStr));
   5964     ThumbCtx.reset(new MCContext(ThumbAsmInfo.get(), ThumbMRI.get(), nullptr));
   5965     ThumbDisAsm.reset(ThumbTarget->createMCDisassembler(*ThumbSTI, *ThumbCtx));
   5966     MCContext *PtrThumbCtx = ThumbCtx.get();
   5967     ThumbRelInfo.reset(
   5968         ThumbTarget->createMCRelocationInfo(ThumbTripleName, *PtrThumbCtx));
   5969     if (ThumbRelInfo) {
   5970       ThumbSymbolizer.reset(ThumbTarget->createMCSymbolizer(
   5971           ThumbTripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
   5972           &ThumbSymbolizerInfo, PtrThumbCtx, std::move(ThumbRelInfo)));
   5973       ThumbDisAsm->setSymbolizer(std::move(ThumbSymbolizer));
   5974     }
   5975     int ThumbAsmPrinterVariant = ThumbAsmInfo->getAssemblerDialect();
   5976     ThumbIP.reset(ThumbTarget->createMCInstPrinter(
   5977         Triple(ThumbTripleName), ThumbAsmPrinterVariant, *ThumbAsmInfo,
   5978         *ThumbInstrInfo, *ThumbMRI));
   5979     // Set the display preference for hex vs. decimal immediates.
   5980     ThumbIP->setPrintImmHex(PrintImmHex);
   5981   }
   5982 
   5983   if (ThumbTarget && (!ThumbAsmInfo || !ThumbSTI || !ThumbDisAsm || !ThumbIP)) {
   5984     errs() << "error: couldn't initialize disassembler for target "
   5985            << ThumbTripleName << '\n';
   5986     return;
   5987   }
   5988 
   5989   MachO::mach_header Header = MachOOF->getHeader();
   5990 
   5991   // FIXME: Using the -cfg command line option, this code used to be able to
   5992   // annotate relocations with the referenced symbol's name, and if this was
   5993   // inside a __[cf]string section, the data it points to. This is now replaced
   5994   // by the upcoming MCSymbolizer, which needs the appropriate setup done above.
   5995   std::vector<SectionRef> Sections;
   5996   std::vector<SymbolRef> Symbols;
   5997   SmallVector<uint64_t, 8> FoundFns;
   5998   uint64_t BaseSegmentAddress;
   5999 
   6000   getSectionsAndSymbols(MachOOF, Sections, Symbols, FoundFns,
   6001                         BaseSegmentAddress);
   6002 
   6003   // Sort the symbols by address, just in case they didn't come in that way.
   6004   std::sort(Symbols.begin(), Symbols.end(), SymbolSorter());
   6005 
   6006   // Build a data in code table that is sorted on by the address of each entry.
   6007   uint64_t BaseAddress = 0;
   6008   if (Header.filetype == MachO::MH_OBJECT)
   6009     BaseAddress = Sections[0].getAddress();
   6010   else
   6011     BaseAddress = BaseSegmentAddress;
   6012   DiceTable Dices;
   6013   for (dice_iterator DI = MachOOF->begin_dices(), DE = MachOOF->end_dices();
   6014        DI != DE; ++DI) {
   6015     uint32_t Offset;
   6016     DI->getOffset(Offset);
   6017     Dices.push_back(std::make_pair(BaseAddress + Offset, *DI));
   6018   }
   6019   array_pod_sort(Dices.begin(), Dices.end());
   6020 
   6021 #ifndef NDEBUG
   6022   raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
   6023 #else
   6024   raw_ostream &DebugOut = nulls();
   6025 #endif
   6026 
   6027   std::unique_ptr<DIContext> diContext;
   6028   ObjectFile *DbgObj = MachOOF;
   6029   // Try to find debug info and set up the DIContext for it.
   6030   if (UseDbg) {
   6031     // A separate DSym file path was specified, parse it as a macho file,
   6032     // get the sections and supply it to the section name parsing machinery.
   6033     if (!DSYMFile.empty()) {
   6034       ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
   6035           MemoryBuffer::getFileOrSTDIN(DSYMFile);
   6036       if (std::error_code EC = BufOrErr.getError()) {
   6037         errs() << "llvm-objdump: " << Filename << ": " << EC.message() << '\n';
   6038         return;
   6039       }
   6040       DbgObj =
   6041           ObjectFile::createMachOObjectFile(BufOrErr.get()->getMemBufferRef())
   6042               .get()
   6043               .release();
   6044     }
   6045 
   6046     // Setup the DIContext
   6047     diContext.reset(new DWARFContextInMemory(*DbgObj));
   6048   }
   6049 
   6050   if (FilterSections.size() == 0)
   6051     outs() << "(" << DisSegName << "," << DisSectName << ") section\n";
   6052 
   6053   for (unsigned SectIdx = 0; SectIdx != Sections.size(); SectIdx++) {
   6054     StringRef SectName;
   6055     if (Sections[SectIdx].getName(SectName) || SectName != DisSectName)
   6056       continue;
   6057 
   6058     DataRefImpl DR = Sections[SectIdx].getRawDataRefImpl();
   6059 
   6060     StringRef SegmentName = MachOOF->getSectionFinalSegmentName(DR);
   6061     if (SegmentName != DisSegName)
   6062       continue;
   6063 
   6064     StringRef BytesStr;
   6065     Sections[SectIdx].getContents(BytesStr);
   6066     ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
   6067                             BytesStr.size());
   6068     uint64_t SectAddress = Sections[SectIdx].getAddress();
   6069 
   6070     bool symbolTableWorked = false;
   6071 
   6072     // Create a map of symbol addresses to symbol names for use by
   6073     // the SymbolizerSymbolLookUp() routine.
   6074     SymbolAddressMap AddrMap;
   6075     bool DisSymNameFound = false;
   6076     for (const SymbolRef &Symbol : MachOOF->symbols()) {
   6077       SymbolRef::Type ST = Symbol.getType();
   6078       if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
   6079           ST == SymbolRef::ST_Other) {
   6080         uint64_t Address = Symbol.getValue();
   6081         ErrorOr<StringRef> SymNameOrErr = Symbol.getName();
   6082         if (std::error_code EC = SymNameOrErr.getError())
   6083           report_fatal_error(EC.message());
   6084         StringRef SymName = *SymNameOrErr;
   6085         AddrMap[Address] = SymName;
   6086         if (!DisSymName.empty() && DisSymName == SymName)
   6087           DisSymNameFound = true;
   6088       }
   6089     }
   6090     if (!DisSymName.empty() && !DisSymNameFound) {
   6091       outs() << "Can't find -dis-symname: " << DisSymName << "\n";
   6092       return;
   6093     }
   6094     // Set up the block of info used by the Symbolizer call backs.
   6095     SymbolizerInfo.verbose = !NoSymbolicOperands;
   6096     SymbolizerInfo.O = MachOOF;
   6097     SymbolizerInfo.S = Sections[SectIdx];
   6098     SymbolizerInfo.AddrMap = &AddrMap;
   6099     SymbolizerInfo.Sections = &Sections;
   6100     SymbolizerInfo.class_name = nullptr;
   6101     SymbolizerInfo.selector_name = nullptr;
   6102     SymbolizerInfo.method = nullptr;
   6103     SymbolizerInfo.demangled_name = nullptr;
   6104     SymbolizerInfo.bindtable = nullptr;
   6105     SymbolizerInfo.adrp_addr = 0;
   6106     SymbolizerInfo.adrp_inst = 0;
   6107     // Same for the ThumbSymbolizer
   6108     ThumbSymbolizerInfo.verbose = !NoSymbolicOperands;
   6109     ThumbSymbolizerInfo.O = MachOOF;
   6110     ThumbSymbolizerInfo.S = Sections[SectIdx];
   6111     ThumbSymbolizerInfo.AddrMap = &AddrMap;
   6112     ThumbSymbolizerInfo.Sections = &Sections;
   6113     ThumbSymbolizerInfo.class_name = nullptr;
   6114     ThumbSymbolizerInfo.selector_name = nullptr;
   6115     ThumbSymbolizerInfo.method = nullptr;
   6116     ThumbSymbolizerInfo.demangled_name = nullptr;
   6117     ThumbSymbolizerInfo.bindtable = nullptr;
   6118     ThumbSymbolizerInfo.adrp_addr = 0;
   6119     ThumbSymbolizerInfo.adrp_inst = 0;
   6120 
   6121     // Disassemble symbol by symbol.
   6122     for (unsigned SymIdx = 0; SymIdx != Symbols.size(); SymIdx++) {
   6123       ErrorOr<StringRef> SymNameOrErr = Symbols[SymIdx].getName();
   6124       if (std::error_code EC = SymNameOrErr.getError())
   6125         report_fatal_error(EC.message());
   6126       StringRef SymName = *SymNameOrErr;
   6127 
   6128       SymbolRef::Type ST = Symbols[SymIdx].getType();
   6129       if (ST != SymbolRef::ST_Function && ST != SymbolRef::ST_Data)
   6130         continue;
   6131 
   6132       // Make sure the symbol is defined in this section.
   6133       bool containsSym = Sections[SectIdx].containsSymbol(Symbols[SymIdx]);
   6134       if (!containsSym)
   6135         continue;
   6136 
   6137       // If we are only disassembling one symbol see if this is that symbol.
   6138       if (!DisSymName.empty() && DisSymName != SymName)
   6139         continue;
   6140 
   6141       // Start at the address of the symbol relative to the section's address.
   6142       uint64_t Start = Symbols[SymIdx].getValue();
   6143       uint64_t SectionAddress = Sections[SectIdx].getAddress();
   6144       Start -= SectionAddress;
   6145 
   6146       // Stop disassembling either at the beginning of the next symbol or at
   6147       // the end of the section.
   6148       bool containsNextSym = false;
   6149       uint64_t NextSym = 0;
   6150       uint64_t NextSymIdx = SymIdx + 1;
   6151       while (Symbols.size() > NextSymIdx) {
   6152         SymbolRef::Type NextSymType = Symbols[NextSymIdx].getType();
   6153         if (NextSymType == SymbolRef::ST_Function) {
   6154           containsNextSym =
   6155               Sections[SectIdx].containsSymbol(Symbols[NextSymIdx]);
   6156           NextSym = Symbols[NextSymIdx].getValue();
   6157           NextSym -= SectionAddress;
   6158           break;
   6159         }
   6160         ++NextSymIdx;
   6161       }
   6162 
   6163       uint64_t SectSize = Sections[SectIdx].getSize();
   6164       uint64_t End = containsNextSym ? NextSym : SectSize;
   6165       uint64_t Size;
   6166 
   6167       symbolTableWorked = true;
   6168 
   6169       DataRefImpl Symb = Symbols[SymIdx].getRawDataRefImpl();
   6170       bool isThumb =
   6171           (MachOOF->getSymbolFlags(Symb) & SymbolRef::SF_Thumb) && ThumbTarget;
   6172 
   6173       outs() << SymName << ":\n";
   6174       DILineInfo lastLine;
   6175       for (uint64_t Index = Start; Index < End; Index += Size) {
   6176         MCInst Inst;
   6177 
   6178         uint64_t PC = SectAddress + Index;
   6179         if (!NoLeadingAddr) {
   6180           if (FullLeadingAddr) {
   6181             if (MachOOF->is64Bit())
   6182               outs() << format("%016" PRIx64, PC);
   6183             else
   6184               outs() << format("%08" PRIx64, PC);
   6185           } else {
   6186             outs() << format("%8" PRIx64 ":", PC);
   6187           }
   6188         }
   6189         if (!NoShowRawInsn)
   6190           outs() << "\t";
   6191 
   6192         // Check the data in code table here to see if this is data not an
   6193         // instruction to be disassembled.
   6194         DiceTable Dice;
   6195         Dice.push_back(std::make_pair(PC, DiceRef()));
   6196         dice_table_iterator DTI =
   6197             std::search(Dices.begin(), Dices.end(), Dice.begin(), Dice.end(),
   6198                         compareDiceTableEntries);
   6199         if (DTI != Dices.end()) {
   6200           uint16_t Length;
   6201           DTI->second.getLength(Length);
   6202           uint16_t Kind;
   6203           DTI->second.getKind(Kind);
   6204           Size = DumpDataInCode(Bytes.data() + Index, Length, Kind);
   6205           if ((Kind == MachO::DICE_KIND_JUMP_TABLE8) &&
   6206               (PC == (DTI->first + Length - 1)) && (Length & 1))
   6207             Size++;
   6208           continue;
   6209         }
   6210 
   6211         SmallVector<char, 64> AnnotationsBytes;
   6212         raw_svector_ostream Annotations(AnnotationsBytes);
   6213 
   6214         bool gotInst;
   6215         if (isThumb)
   6216           gotInst = ThumbDisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
   6217                                                 PC, DebugOut, Annotations);
   6218         else
   6219           gotInst = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index), PC,
   6220                                            DebugOut, Annotations);
   6221         if (gotInst) {
   6222           if (!NoShowRawInsn) {
   6223             dumpBytes(makeArrayRef(Bytes.data() + Index, Size), outs());
   6224           }
   6225           formatted_raw_ostream FormattedOS(outs());
   6226           StringRef AnnotationsStr = Annotations.str();
   6227           if (isThumb)
   6228             ThumbIP->printInst(&Inst, FormattedOS, AnnotationsStr, *ThumbSTI);
   6229           else
   6230             IP->printInst(&Inst, FormattedOS, AnnotationsStr, *STI);
   6231           emitComments(CommentStream, CommentsToEmit, FormattedOS, *AsmInfo);
   6232 
   6233           // Print debug info.
   6234           if (diContext) {
   6235             DILineInfo dli = diContext->getLineInfoForAddress(PC);
   6236             // Print valid line info if it changed.
   6237             if (dli != lastLine && dli.Line != 0)
   6238               outs() << "\t## " << dli.FileName << ':' << dli.Line << ':'
   6239                      << dli.Column;
   6240             lastLine = dli;
   6241           }
   6242           outs() << "\n";
   6243         } else {
   6244           unsigned int Arch = MachOOF->getArch();
   6245           if (Arch == Triple::x86_64 || Arch == Triple::x86) {
   6246             outs() << format("\t.byte 0x%02x #bad opcode\n",
   6247                              *(Bytes.data() + Index) & 0xff);
   6248             Size = 1; // skip exactly one illegible byte and move on.
   6249           } else if (Arch == Triple::aarch64) {
   6250             uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
   6251                               (*(Bytes.data() + Index + 1) & 0xff) << 8 |
   6252                               (*(Bytes.data() + Index + 2) & 0xff) << 16 |
   6253                               (*(Bytes.data() + Index + 3) & 0xff) << 24;
   6254             outs() << format("\t.long\t0x%08x\n", opcode);
   6255             Size = 4;
   6256           } else {
   6257             errs() << "llvm-objdump: warning: invalid instruction encoding\n";
   6258             if (Size == 0)
   6259               Size = 1; // skip illegible bytes
   6260           }
   6261         }
   6262       }
   6263     }
   6264     if (!symbolTableWorked) {
   6265       // Reading the symbol table didn't work, disassemble the whole section.
   6266       uint64_t SectAddress = Sections[SectIdx].getAddress();
   6267       uint64_t SectSize = Sections[SectIdx].getSize();
   6268       uint64_t InstSize;
   6269       for (uint64_t Index = 0; Index < SectSize; Index += InstSize) {
   6270         MCInst Inst;
   6271 
   6272         uint64_t PC = SectAddress + Index;
   6273         if (DisAsm->getInstruction(Inst, InstSize, Bytes.slice(Index), PC,
   6274                                    DebugOut, nulls())) {
   6275           if (!NoLeadingAddr) {
   6276             if (FullLeadingAddr) {
   6277               if (MachOOF->is64Bit())
   6278                 outs() << format("%016" PRIx64, PC);
   6279               else
   6280                 outs() << format("%08" PRIx64, PC);
   6281             } else {
   6282               outs() << format("%8" PRIx64 ":", PC);
   6283             }
   6284           }
   6285           if (!NoShowRawInsn) {
   6286             outs() << "\t";
   6287             dumpBytes(makeArrayRef(Bytes.data() + Index, InstSize), outs());
   6288           }
   6289           IP->printInst(&Inst, outs(), "", *STI);
   6290           outs() << "\n";
   6291         } else {
   6292           unsigned int Arch = MachOOF->getArch();
   6293           if (Arch == Triple::x86_64 || Arch == Triple::x86) {
   6294             outs() << format("\t.byte 0x%02x #bad opcode\n",
   6295                              *(Bytes.data() + Index) & 0xff);
   6296             InstSize = 1; // skip exactly one illegible byte and move on.
   6297           } else {
   6298             errs() << "llvm-objdump: warning: invalid instruction encoding\n";
   6299             if (InstSize == 0)
   6300               InstSize = 1; // skip illegible bytes
   6301           }
   6302         }
   6303       }
   6304     }
   6305     // The TripleName's need to be reset if we are called again for a different
   6306     // archtecture.
   6307     TripleName = "";
   6308     ThumbTripleName = "";
   6309 
   6310     if (SymbolizerInfo.method != nullptr)
   6311       free(SymbolizerInfo.method);
   6312     if (SymbolizerInfo.demangled_name != nullptr)
   6313       free(SymbolizerInfo.demangled_name);
   6314     if (SymbolizerInfo.bindtable != nullptr)
   6315       delete SymbolizerInfo.bindtable;
   6316     if (ThumbSymbolizerInfo.method != nullptr)
   6317       free(ThumbSymbolizerInfo.method);
   6318     if (ThumbSymbolizerInfo.demangled_name != nullptr)
   6319       free(ThumbSymbolizerInfo.demangled_name);
   6320     if (ThumbSymbolizerInfo.bindtable != nullptr)
   6321       delete ThumbSymbolizerInfo.bindtable;
   6322   }
   6323 }
   6324 
   6325 //===----------------------------------------------------------------------===//
   6326 // __compact_unwind section dumping
   6327 //===----------------------------------------------------------------------===//
   6328 
   6329 namespace {
   6330 
   6331 template <typename T> static uint64_t readNext(const char *&Buf) {
   6332   using llvm::support::little;
   6333   using llvm::support::unaligned;
   6334 
   6335   uint64_t Val = support::endian::read<T, little, unaligned>(Buf);
   6336   Buf += sizeof(T);
   6337   return Val;
   6338 }
   6339 
   6340 struct CompactUnwindEntry {
   6341   uint32_t OffsetInSection;
   6342 
   6343   uint64_t FunctionAddr;
   6344   uint32_t Length;
   6345   uint32_t CompactEncoding;
   6346   uint64_t PersonalityAddr;
   6347   uint64_t LSDAAddr;
   6348 
   6349   RelocationRef FunctionReloc;
   6350   RelocationRef PersonalityReloc;
   6351   RelocationRef LSDAReloc;
   6352 
   6353   CompactUnwindEntry(StringRef Contents, unsigned Offset, bool Is64)
   6354       : OffsetInSection(Offset) {
   6355     if (Is64)
   6356       read<uint64_t>(Contents.data() + Offset);
   6357     else
   6358       read<uint32_t>(Contents.data() + Offset);
   6359   }
   6360 
   6361 private:
   6362   template <typename UIntPtr> void read(const char *Buf) {
   6363     FunctionAddr = readNext<UIntPtr>(Buf);
   6364     Length = readNext<uint32_t>(Buf);
   6365     CompactEncoding = readNext<uint32_t>(Buf);
   6366     PersonalityAddr = readNext<UIntPtr>(Buf);
   6367     LSDAAddr = readNext<UIntPtr>(Buf);
   6368   }
   6369 };
   6370 }
   6371 
   6372 /// Given a relocation from __compact_unwind, consisting of the RelocationRef
   6373 /// and data being relocated, determine the best base Name and Addend to use for
   6374 /// display purposes.
   6375 ///
   6376 /// 1. An Extern relocation will directly reference a symbol (and the data is
   6377 ///    then already an addend), so use that.
   6378 /// 2. Otherwise the data is an offset in the object file's layout; try to find
   6379 //     a symbol before it in the same section, and use the offset from there.
   6380 /// 3. Finally, if all that fails, fall back to an offset from the start of the
   6381 ///    referenced section.
   6382 static void findUnwindRelocNameAddend(const MachOObjectFile *Obj,
   6383                                       std::map<uint64_t, SymbolRef> &Symbols,
   6384                                       const RelocationRef &Reloc, uint64_t Addr,
   6385                                       StringRef &Name, uint64_t &Addend) {
   6386   if (Reloc.getSymbol() != Obj->symbol_end()) {
   6387     ErrorOr<StringRef> NameOrErr = Reloc.getSymbol()->getName();
   6388     if (std::error_code EC = NameOrErr.getError())
   6389       report_fatal_error(EC.message());
   6390     Name = *NameOrErr;
   6391     Addend = Addr;
   6392     return;
   6393   }
   6394 
   6395   auto RE = Obj->getRelocation(Reloc.getRawDataRefImpl());
   6396   SectionRef RelocSection = Obj->getAnyRelocationSection(RE);
   6397 
   6398   uint64_t SectionAddr = RelocSection.getAddress();
   6399 
   6400   auto Sym = Symbols.upper_bound(Addr);
   6401   if (Sym == Symbols.begin()) {
   6402     // The first symbol in the object is after this reference, the best we can
   6403     // do is section-relative notation.
   6404     RelocSection.getName(Name);
   6405     Addend = Addr - SectionAddr;
   6406     return;
   6407   }
   6408 
   6409   // Go back one so that SymbolAddress <= Addr.
   6410   --Sym;
   6411 
   6412   section_iterator SymSection = *Sym->second.getSection();
   6413   if (RelocSection == *SymSection) {
   6414     // There's a valid symbol in the same section before this reference.
   6415     ErrorOr<StringRef> NameOrErr = Sym->second.getName();
   6416     if (std::error_code EC = NameOrErr.getError())
   6417       report_fatal_error(EC.message());
   6418     Name = *NameOrErr;
   6419     Addend = Addr - Sym->first;
   6420     return;
   6421   }
   6422 
   6423   // There is a symbol before this reference, but it's in a different
   6424   // section. Probably not helpful to mention it, so use the section name.
   6425   RelocSection.getName(Name);
   6426   Addend = Addr - SectionAddr;
   6427 }
   6428 
   6429 static void printUnwindRelocDest(const MachOObjectFile *Obj,
   6430                                  std::map<uint64_t, SymbolRef> &Symbols,
   6431                                  const RelocationRef &Reloc, uint64_t Addr) {
   6432   StringRef Name;
   6433   uint64_t Addend;
   6434 
   6435   if (!Reloc.getObject())
   6436     return;
   6437 
   6438   findUnwindRelocNameAddend(Obj, Symbols, Reloc, Addr, Name, Addend);
   6439 
   6440   outs() << Name;
   6441   if (Addend)
   6442     outs() << " + " << format("0x%" PRIx64, Addend);
   6443 }
   6444 
   6445 static void
   6446 printMachOCompactUnwindSection(const MachOObjectFile *Obj,
   6447                                std::map<uint64_t, SymbolRef> &Symbols,
   6448                                const SectionRef &CompactUnwind) {
   6449 
   6450   assert(Obj->isLittleEndian() &&
   6451          "There should not be a big-endian .o with __compact_unwind");
   6452 
   6453   bool Is64 = Obj->is64Bit();
   6454   uint32_t PointerSize = Is64 ? sizeof(uint64_t) : sizeof(uint32_t);
   6455   uint32_t EntrySize = 3 * PointerSize + 2 * sizeof(uint32_t);
   6456 
   6457   StringRef Contents;
   6458   CompactUnwind.getContents(Contents);
   6459 
   6460   SmallVector<CompactUnwindEntry, 4> CompactUnwinds;
   6461 
   6462   // First populate the initial raw offsets, encodings and so on from the entry.
   6463   for (unsigned Offset = 0; Offset < Contents.size(); Offset += EntrySize) {
   6464     CompactUnwindEntry Entry(Contents.data(), Offset, Is64);
   6465     CompactUnwinds.push_back(Entry);
   6466   }
   6467 
   6468   // Next we need to look at the relocations to find out what objects are
   6469   // actually being referred to.
   6470   for (const RelocationRef &Reloc : CompactUnwind.relocations()) {
   6471     uint64_t RelocAddress = Reloc.getOffset();
   6472 
   6473     uint32_t EntryIdx = RelocAddress / EntrySize;
   6474     uint32_t OffsetInEntry = RelocAddress - EntryIdx * EntrySize;
   6475     CompactUnwindEntry &Entry = CompactUnwinds[EntryIdx];
   6476 
   6477     if (OffsetInEntry == 0)
   6478       Entry.FunctionReloc = Reloc;
   6479     else if (OffsetInEntry == PointerSize + 2 * sizeof(uint32_t))
   6480       Entry.PersonalityReloc = Reloc;
   6481     else if (OffsetInEntry == 2 * PointerSize + 2 * sizeof(uint32_t))
   6482       Entry.LSDAReloc = Reloc;
   6483     else
   6484       llvm_unreachable("Unexpected relocation in __compact_unwind section");
   6485   }
   6486 
   6487   // Finally, we're ready to print the data we've gathered.
   6488   outs() << "Contents of __compact_unwind section:\n";
   6489   for (auto &Entry : CompactUnwinds) {
   6490     outs() << "  Entry at offset "
   6491            << format("0x%" PRIx32, Entry.OffsetInSection) << ":\n";
   6492 
   6493     // 1. Start of the region this entry applies to.
   6494     outs() << "    start:                " << format("0x%" PRIx64,
   6495                                                      Entry.FunctionAddr) << ' ';
   6496     printUnwindRelocDest(Obj, Symbols, Entry.FunctionReloc, Entry.FunctionAddr);
   6497     outs() << '\n';
   6498 
   6499     // 2. Length of the region this entry applies to.
   6500     outs() << "    length:               " << format("0x%" PRIx32, Entry.Length)
   6501            << '\n';
   6502     // 3. The 32-bit compact encoding.
   6503     outs() << "    compact encoding:     "
   6504            << format("0x%08" PRIx32, Entry.CompactEncoding) << '\n';
   6505 
   6506     // 4. The personality function, if present.
   6507     if (Entry.PersonalityReloc.getObject()) {
   6508       outs() << "    personality function: "
   6509              << format("0x%" PRIx64, Entry.PersonalityAddr) << ' ';
   6510       printUnwindRelocDest(Obj, Symbols, Entry.PersonalityReloc,
   6511                            Entry.PersonalityAddr);
   6512       outs() << '\n';
   6513     }
   6514 
   6515     // 5. This entry's language-specific data area.
   6516     if (Entry.LSDAReloc.getObject()) {
   6517       outs() << "    LSDA:                 " << format("0x%" PRIx64,
   6518                                                        Entry.LSDAAddr) << ' ';
   6519       printUnwindRelocDest(Obj, Symbols, Entry.LSDAReloc, Entry.LSDAAddr);
   6520       outs() << '\n';
   6521     }
   6522   }
   6523 }
   6524 
   6525 //===----------------------------------------------------------------------===//
   6526 // __unwind_info section dumping
   6527 //===----------------------------------------------------------------------===//
   6528 
   6529 static void printRegularSecondLevelUnwindPage(const char *PageStart) {
   6530   const char *Pos = PageStart;
   6531   uint32_t Kind = readNext<uint32_t>(Pos);
   6532   (void)Kind;
   6533   assert(Kind == 2 && "kind for a regular 2nd level index should be 2");
   6534 
   6535   uint16_t EntriesStart = readNext<uint16_t>(Pos);
   6536   uint16_t NumEntries = readNext<uint16_t>(Pos);
   6537 
   6538   Pos = PageStart + EntriesStart;
   6539   for (unsigned i = 0; i < NumEntries; ++i) {
   6540     uint32_t FunctionOffset = readNext<uint32_t>(Pos);
   6541     uint32_t Encoding = readNext<uint32_t>(Pos);
   6542 
   6543     outs() << "      [" << i << "]: "
   6544            << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
   6545            << ", "
   6546            << "encoding=" << format("0x%08" PRIx32, Encoding) << '\n';
   6547   }
   6548 }
   6549 
   6550 static void printCompressedSecondLevelUnwindPage(
   6551     const char *PageStart, uint32_t FunctionBase,
   6552     const SmallVectorImpl<uint32_t> &CommonEncodings) {
   6553   const char *Pos = PageStart;
   6554   uint32_t Kind = readNext<uint32_t>(Pos);
   6555   (void)Kind;
   6556   assert(Kind == 3 && "kind for a compressed 2nd level index should be 3");
   6557 
   6558   uint16_t EntriesStart = readNext<uint16_t>(Pos);
   6559   uint16_t NumEntries = readNext<uint16_t>(Pos);
   6560 
   6561   uint16_t EncodingsStart = readNext<uint16_t>(Pos);
   6562   readNext<uint16_t>(Pos);
   6563   const auto *PageEncodings = reinterpret_cast<const support::ulittle32_t *>(
   6564       PageStart + EncodingsStart);
   6565 
   6566   Pos = PageStart + EntriesStart;
   6567   for (unsigned i = 0; i < NumEntries; ++i) {
   6568     uint32_t Entry = readNext<uint32_t>(Pos);
   6569     uint32_t FunctionOffset = FunctionBase + (Entry & 0xffffff);
   6570     uint32_t EncodingIdx = Entry >> 24;
   6571 
   6572     uint32_t Encoding;
   6573     if (EncodingIdx < CommonEncodings.size())
   6574       Encoding = CommonEncodings[EncodingIdx];
   6575     else
   6576       Encoding = PageEncodings[EncodingIdx - CommonEncodings.size()];
   6577 
   6578     outs() << "      [" << i << "]: "
   6579            << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
   6580            << ", "
   6581            << "encoding[" << EncodingIdx
   6582            << "]=" << format("0x%08" PRIx32, Encoding) << '\n';
   6583   }
   6584 }
   6585 
   6586 static void printMachOUnwindInfoSection(const MachOObjectFile *Obj,
   6587                                         std::map<uint64_t, SymbolRef> &Symbols,
   6588                                         const SectionRef &UnwindInfo) {
   6589 
   6590   assert(Obj->isLittleEndian() &&
   6591          "There should not be a big-endian .o with __unwind_info");
   6592 
   6593   outs() << "Contents of __unwind_info section:\n";
   6594 
   6595   StringRef Contents;
   6596   UnwindInfo.getContents(Contents);
   6597   const char *Pos = Contents.data();
   6598 
   6599   //===----------------------------------
   6600   // Section header
   6601   //===----------------------------------
   6602 
   6603   uint32_t Version = readNext<uint32_t>(Pos);
   6604   outs() << "  Version:                                   "
   6605          << format("0x%" PRIx32, Version) << '\n';
   6606   assert(Version == 1 && "only understand version 1");
   6607 
   6608   uint32_t CommonEncodingsStart = readNext<uint32_t>(Pos);
   6609   outs() << "  Common encodings array section offset:     "
   6610          << format("0x%" PRIx32, CommonEncodingsStart) << '\n';
   6611   uint32_t NumCommonEncodings = readNext<uint32_t>(Pos);
   6612   outs() << "  Number of common encodings in array:       "
   6613          << format("0x%" PRIx32, NumCommonEncodings) << '\n';
   6614 
   6615   uint32_t PersonalitiesStart = readNext<uint32_t>(Pos);
   6616   outs() << "  Personality function array section offset: "
   6617          << format("0x%" PRIx32, PersonalitiesStart) << '\n';
   6618   uint32_t NumPersonalities = readNext<uint32_t>(Pos);
   6619   outs() << "  Number of personality functions in array:  "
   6620          << format("0x%" PRIx32, NumPersonalities) << '\n';
   6621 
   6622   uint32_t IndicesStart = readNext<uint32_t>(Pos);
   6623   outs() << "  Index array section offset:                "
   6624          << format("0x%" PRIx32, IndicesStart) << '\n';
   6625   uint32_t NumIndices = readNext<uint32_t>(Pos);
   6626   outs() << "  Number of indices in array:                "
   6627          << format("0x%" PRIx32, NumIndices) << '\n';
   6628 
   6629   //===----------------------------------
   6630   // A shared list of common encodings
   6631   //===----------------------------------
   6632 
   6633   // These occupy indices in the range [0, N] whenever an encoding is referenced
   6634   // from a compressed 2nd level index table. In practice the linker only
   6635   // creates ~128 of these, so that indices are available to embed encodings in
   6636   // the 2nd level index.
   6637 
   6638   SmallVector<uint32_t, 64> CommonEncodings;
   6639   outs() << "  Common encodings: (count = " << NumCommonEncodings << ")\n";
   6640   Pos = Contents.data() + CommonEncodingsStart;
   6641   for (unsigned i = 0; i < NumCommonEncodings; ++i) {
   6642     uint32_t Encoding = readNext<uint32_t>(Pos);
   6643     CommonEncodings.push_back(Encoding);
   6644 
   6645     outs() << "    encoding[" << i << "]: " << format("0x%08" PRIx32, Encoding)
   6646            << '\n';
   6647   }
   6648 
   6649   //===----------------------------------
   6650   // Personality functions used in this executable
   6651   //===----------------------------------
   6652 
   6653   // There should be only a handful of these (one per source language,
   6654   // roughly). Particularly since they only get 2 bits in the compact encoding.
   6655 
   6656   outs() << "  Personality functions: (count = " << NumPersonalities << ")\n";
   6657   Pos = Contents.data() + PersonalitiesStart;
   6658   for (unsigned i = 0; i < NumPersonalities; ++i) {
   6659     uint32_t PersonalityFn = readNext<uint32_t>(Pos);
   6660     outs() << "    personality[" << i + 1
   6661            << "]: " << format("0x%08" PRIx32, PersonalityFn) << '\n';
   6662   }
   6663 
   6664   //===----------------------------------
   6665   // The level 1 index entries
   6666   //===----------------------------------
   6667 
   6668   // These specify an approximate place to start searching for the more detailed
   6669   // information, sorted by PC.
   6670 
   6671   struct IndexEntry {
   6672     uint32_t FunctionOffset;
   6673     uint32_t SecondLevelPageStart;
   6674     uint32_t LSDAStart;
   6675   };
   6676 
   6677   SmallVector<IndexEntry, 4> IndexEntries;
   6678 
   6679   outs() << "  Top level indices: (count = " << NumIndices << ")\n";
   6680   Pos = Contents.data() + IndicesStart;
   6681   for (unsigned i = 0; i < NumIndices; ++i) {
   6682     IndexEntry Entry;
   6683 
   6684     Entry.FunctionOffset = readNext<uint32_t>(Pos);
   6685     Entry.SecondLevelPageStart = readNext<uint32_t>(Pos);
   6686     Entry.LSDAStart = readNext<uint32_t>(Pos);
   6687     IndexEntries.push_back(Entry);
   6688 
   6689     outs() << "    [" << i << "]: "
   6690            << "function offset=" << format("0x%08" PRIx32, Entry.FunctionOffset)
   6691            << ", "
   6692            << "2nd level page offset="
   6693            << format("0x%08" PRIx32, Entry.SecondLevelPageStart) << ", "
   6694            << "LSDA offset=" << format("0x%08" PRIx32, Entry.LSDAStart) << '\n';
   6695   }
   6696 
   6697   //===----------------------------------
   6698   // Next come the LSDA tables
   6699   //===----------------------------------
   6700 
   6701   // The LSDA layout is rather implicit: it's a contiguous array of entries from
   6702   // the first top-level index's LSDAOffset to the last (sentinel).
   6703 
   6704   outs() << "  LSDA descriptors:\n";
   6705   Pos = Contents.data() + IndexEntries[0].LSDAStart;
   6706   int NumLSDAs = (IndexEntries.back().LSDAStart - IndexEntries[0].LSDAStart) /
   6707                  (2 * sizeof(uint32_t));
   6708   for (int i = 0; i < NumLSDAs; ++i) {
   6709     uint32_t FunctionOffset = readNext<uint32_t>(Pos);
   6710     uint32_t LSDAOffset = readNext<uint32_t>(Pos);
   6711     outs() << "    [" << i << "]: "
   6712            << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
   6713            << ", "
   6714            << "LSDA offset=" << format("0x%08" PRIx32, LSDAOffset) << '\n';
   6715   }
   6716 
   6717   //===----------------------------------
   6718   // Finally, the 2nd level indices
   6719   //===----------------------------------
   6720 
   6721   // Generally these are 4K in size, and have 2 possible forms:
   6722   //   + Regular stores up to 511 entries with disparate encodings
   6723   //   + Compressed stores up to 1021 entries if few enough compact encoding
   6724   //     values are used.
   6725   outs() << "  Second level indices:\n";
   6726   for (unsigned i = 0; i < IndexEntries.size() - 1; ++i) {
   6727     // The final sentinel top-level index has no associated 2nd level page
   6728     if (IndexEntries[i].SecondLevelPageStart == 0)
   6729       break;
   6730 
   6731     outs() << "    Second level index[" << i << "]: "
   6732            << "offset in section="
   6733            << format("0x%08" PRIx32, IndexEntries[i].SecondLevelPageStart)
   6734            << ", "
   6735            << "base function offset="
   6736            << format("0x%08" PRIx32, IndexEntries[i].FunctionOffset) << '\n';
   6737 
   6738     Pos = Contents.data() + IndexEntries[i].SecondLevelPageStart;
   6739     uint32_t Kind = *reinterpret_cast<const support::ulittle32_t *>(Pos);
   6740     if (Kind == 2)
   6741       printRegularSecondLevelUnwindPage(Pos);
   6742     else if (Kind == 3)
   6743       printCompressedSecondLevelUnwindPage(Pos, IndexEntries[i].FunctionOffset,
   6744                                            CommonEncodings);
   6745     else
   6746       llvm_unreachable("Do not know how to print this kind of 2nd level page");
   6747   }
   6748 }
   6749 
   6750 static unsigned getSizeForEncoding(bool is64Bit,
   6751                                    unsigned symbolEncoding) {
   6752   unsigned format = symbolEncoding & 0x0f;
   6753   switch (format) {
   6754     default: llvm_unreachable("Unknown Encoding");
   6755     case dwarf::DW_EH_PE_absptr:
   6756     case dwarf::DW_EH_PE_signed:
   6757       return is64Bit ? 8 : 4;
   6758     case dwarf::DW_EH_PE_udata2:
   6759     case dwarf::DW_EH_PE_sdata2:
   6760       return 2;
   6761     case dwarf::DW_EH_PE_udata4:
   6762     case dwarf::DW_EH_PE_sdata4:
   6763       return 4;
   6764     case dwarf::DW_EH_PE_udata8:
   6765     case dwarf::DW_EH_PE_sdata8:
   6766       return 8;
   6767   }
   6768 }
   6769 
   6770 static uint64_t readPointer(const char *&Pos, bool is64Bit, unsigned Encoding) {
   6771   switch (getSizeForEncoding(is64Bit, Encoding)) {
   6772     case 2:
   6773       return readNext<uint16_t>(Pos);
   6774       break;
   6775     case 4:
   6776       return readNext<uint32_t>(Pos);
   6777       break;
   6778     case 8:
   6779       return readNext<uint64_t>(Pos);
   6780       break;
   6781     default:
   6782       llvm_unreachable("Illegal data size");
   6783   }
   6784 }
   6785 
   6786 static void printMachOEHFrameSection(const MachOObjectFile *Obj,
   6787                                      std::map<uint64_t, SymbolRef> &Symbols,
   6788                                      const SectionRef &EHFrame) {
   6789   if (!Obj->isLittleEndian()) {
   6790     outs() << "warning: cannot handle big endian __eh_frame section\n";
   6791     return;
   6792   }
   6793 
   6794   bool is64Bit = Obj->is64Bit();
   6795 
   6796   outs() << "Contents of __eh_frame section:\n";
   6797 
   6798   StringRef Contents;
   6799   EHFrame.getContents(Contents);
   6800 
   6801   /// A few fields of the CIE are used when decoding the FDE's.  This struct
   6802   /// will cache those fields we need so that we don't have to decode it
   6803   /// repeatedly for each FDE that references it.
   6804   struct DecodedCIE {
   6805     Optional<uint32_t> FDEPointerEncoding;
   6806     Optional<uint32_t> LSDAPointerEncoding;
   6807     bool hasAugmentationLength;
   6808   };
   6809 
   6810   // Map from the start offset of the CIE to the cached data for that CIE.
   6811   DenseMap<uint64_t, DecodedCIE> CachedCIEs;
   6812 
   6813   for (const char *Pos = Contents.data(), *End = Contents.end(); Pos != End; ) {
   6814 
   6815     const char *EntryStartPos = Pos;
   6816 
   6817     uint64_t Length = readNext<uint32_t>(Pos);
   6818     if (Length == 0xffffffff)
   6819       Length = readNext<uint64_t>(Pos);
   6820 
   6821     // Save the Pos so that we can check the length we encoded against what we
   6822     // end up decoding.
   6823     const char *PosAfterLength = Pos;
   6824     const char *EntryEndPos = PosAfterLength + Length;
   6825 
   6826     assert(EntryEndPos <= End &&
   6827            "__eh_frame entry length exceeds section size");
   6828 
   6829     uint32_t ID = readNext<uint32_t>(Pos);
   6830     if (ID == 0) {
   6831       // This is a CIE.
   6832 
   6833       uint32_t Version = readNext<uint8_t>(Pos);
   6834 
   6835       // Parse a null terminated augmentation string
   6836       SmallString<8> AugmentationString;
   6837       for (uint8_t Char = readNext<uint8_t>(Pos); Char;
   6838            Char = readNext<uint8_t>(Pos))
   6839         AugmentationString.push_back(Char);
   6840 
   6841       // Optionally parse the EH data if the augmentation string says it's there.
   6842       Optional<uint64_t> EHData;
   6843       if (StringRef(AugmentationString).count("eh"))
   6844         EHData = is64Bit ? readNext<uint64_t>(Pos) : readNext<uint32_t>(Pos);
   6845 
   6846       unsigned ULEBByteCount;
   6847       uint64_t CodeAlignmentFactor = decodeULEB128((const uint8_t *)Pos,
   6848                                                    &ULEBByteCount);
   6849       Pos += ULEBByteCount;
   6850 
   6851       int64_t DataAlignmentFactor = decodeSLEB128((const uint8_t *)Pos,
   6852                                                    &ULEBByteCount);
   6853       Pos += ULEBByteCount;
   6854 
   6855       uint32_t ReturnAddressRegister = readNext<uint8_t>(Pos);
   6856 
   6857       Optional<uint64_t> AugmentationLength;
   6858       Optional<uint32_t> LSDAPointerEncoding;
   6859       Optional<uint32_t> PersonalityEncoding;
   6860       Optional<uint64_t> Personality;
   6861       Optional<uint32_t> FDEPointerEncoding;
   6862       if (!AugmentationString.empty() && AugmentationString.front() == 'z') {
   6863         AugmentationLength = decodeULEB128((const uint8_t *)Pos,
   6864                                            &ULEBByteCount);
   6865         Pos += ULEBByteCount;
   6866 
   6867         // Walk the augmentation string to get all the augmentation data.
   6868         for (unsigned i = 1, e = AugmentationString.size(); i != e; ++i) {
   6869           char Char = AugmentationString[i];
   6870           switch (Char) {
   6871             case 'e':
   6872               assert((i + 1) != e && AugmentationString[i + 1] == 'h' &&
   6873                      "Expected 'eh' in augmentation string");
   6874               break;
   6875             case 'L':
   6876               assert(!LSDAPointerEncoding && "Duplicate LSDA encoding");
   6877               LSDAPointerEncoding = readNext<uint8_t>(Pos);
   6878               break;
   6879             case 'P': {
   6880               assert(!Personality && "Duplicate personality");
   6881               PersonalityEncoding = readNext<uint8_t>(Pos);
   6882               Personality = readPointer(Pos, is64Bit, *PersonalityEncoding);
   6883               break;
   6884             }
   6885             case 'R':
   6886               assert(!FDEPointerEncoding && "Duplicate FDE encoding");
   6887               FDEPointerEncoding = readNext<uint8_t>(Pos);
   6888               break;
   6889             case 'z':
   6890               llvm_unreachable("'z' must be first in the augmentation string");
   6891           }
   6892         }
   6893       }
   6894 
   6895       outs() << "CIE:\n";
   6896       outs() << "  Length: " << Length << "\n";
   6897       outs() << "  CIE ID: " << ID << "\n";
   6898       outs() << "  Version: " << Version << "\n";
   6899       outs() << "  Augmentation String: " << AugmentationString << "\n";
   6900       if (EHData)
   6901         outs() << "  EHData: " << *EHData << "\n";
   6902       outs() << "  Code Alignment Factor: " << CodeAlignmentFactor << "\n";
   6903       outs() << "  Data Alignment Factor: " << DataAlignmentFactor << "\n";
   6904       outs() << "  Return Address Register: " << ReturnAddressRegister << "\n";
   6905       if (AugmentationLength) {
   6906         outs() << "  Augmentation Data Length: " << *AugmentationLength << "\n";
   6907         if (LSDAPointerEncoding) {
   6908           outs() << "  FDE LSDA Pointer Encoding: "
   6909                  << *LSDAPointerEncoding << "\n";
   6910         }
   6911         if (Personality) {
   6912           outs() << "  Personality Encoding: " << *PersonalityEncoding << "\n";
   6913           outs() << "  Personality: " << *Personality << "\n";
   6914         }
   6915         if (FDEPointerEncoding) {
   6916           outs() << "  FDE Address Pointer Encoding: "
   6917                  << *FDEPointerEncoding << "\n";
   6918         }
   6919       }
   6920       // FIXME: Handle instructions.
   6921       // For now just emit some bytes
   6922       outs() << "  Instructions:\n  ";
   6923       dumpBytes(makeArrayRef((const uint8_t*)Pos, (const uint8_t*)EntryEndPos),
   6924                 outs());
   6925       outs() << "\n";
   6926       Pos = EntryEndPos;
   6927 
   6928       // Cache this entry.
   6929       uint64_t Offset = EntryStartPos - Contents.data();
   6930       CachedCIEs[Offset] = { FDEPointerEncoding, LSDAPointerEncoding,
   6931                              AugmentationLength.hasValue() };
   6932       continue;
   6933     }
   6934 
   6935     // This is an FDE.
   6936     // The CIE pointer for an FDE is the same location as the ID which we
   6937     // already read.
   6938     uint32_t CIEPointer = ID;
   6939 
   6940     const char *CIEStart = PosAfterLength - CIEPointer;
   6941     assert(CIEStart >= Contents.data() &&
   6942            "FDE points to CIE before the __eh_frame start");
   6943 
   6944     uint64_t CIEOffset = CIEStart - Contents.data();
   6945     auto CIEIt = CachedCIEs.find(CIEOffset);
   6946     if (CIEIt == CachedCIEs.end())
   6947       llvm_unreachable("Couldn't find CIE at offset in to __eh_frame section");
   6948 
   6949     const DecodedCIE &CIE = CIEIt->getSecond();
   6950     assert(CIE.FDEPointerEncoding &&
   6951            "FDE references CIE which did not set pointer encoding");
   6952 
   6953     uint64_t PCPointerSize = getSizeForEncoding(is64Bit,
   6954                                                 *CIE.FDEPointerEncoding);
   6955 
   6956     uint64_t PCBegin = readPointer(Pos, is64Bit, *CIE.FDEPointerEncoding);
   6957     uint64_t PCRange = readPointer(Pos, is64Bit, *CIE.FDEPointerEncoding);
   6958 
   6959     Optional<uint64_t> AugmentationLength;
   6960     uint32_t LSDAPointerSize;
   6961     Optional<uint64_t> LSDAPointer;
   6962     if (CIE.hasAugmentationLength) {
   6963       unsigned ULEBByteCount;
   6964       AugmentationLength = decodeULEB128((const uint8_t *)Pos,
   6965                                          &ULEBByteCount);
   6966       Pos += ULEBByteCount;
   6967 
   6968       // Decode the LSDA if the CIE augmentation string said we should.
   6969       if (CIE.LSDAPointerEncoding) {
   6970         LSDAPointerSize = getSizeForEncoding(is64Bit, *CIE.LSDAPointerEncoding);
   6971         LSDAPointer = readPointer(Pos, is64Bit, *CIE.LSDAPointerEncoding);
   6972       }
   6973     }
   6974 
   6975     outs() << "FDE:\n";
   6976     outs() << "  Length: " << Length << "\n";
   6977     outs() << "  CIE Offset: " << CIEOffset << "\n";
   6978 
   6979     if (PCPointerSize == 8) {
   6980       outs() << format("  PC Begin: %016" PRIx64, PCBegin) << "\n";
   6981       outs() << format("  PC Range: %016" PRIx64, PCRange) << "\n";
   6982     } else {
   6983       outs() << format("  PC Begin: %08" PRIx64, PCBegin) << "\n";
   6984       outs() << format("  PC Range: %08" PRIx64, PCRange) << "\n";
   6985     }
   6986     if (AugmentationLength) {
   6987       outs() << "  Augmentation Data Length: " << *AugmentationLength << "\n";
   6988       if (LSDAPointer) {
   6989         if (LSDAPointerSize == 8)
   6990           outs() << format("  LSDA Pointer: %016\n" PRIx64, *LSDAPointer);
   6991         else
   6992           outs() << format("  LSDA Pointer: %08\n" PRIx64, *LSDAPointer);
   6993       }
   6994     }
   6995 
   6996     // FIXME: Handle instructions.
   6997     // For now just emit some bytes
   6998     outs() << "  Instructions:\n  ";
   6999     dumpBytes(makeArrayRef((const uint8_t*)Pos, (const uint8_t*)EntryEndPos),
   7000               outs());
   7001     outs() << "\n";
   7002     Pos = EntryEndPos;
   7003   }
   7004 }
   7005 
   7006 void llvm::printMachOUnwindInfo(const MachOObjectFile *Obj) {
   7007   std::map<uint64_t, SymbolRef> Symbols;
   7008   for (const SymbolRef &SymRef : Obj->symbols()) {
   7009     // Discard any undefined or absolute symbols. They're not going to take part
   7010     // in the convenience lookup for unwind info and just take up resources.
   7011     section_iterator Section = *SymRef.getSection();
   7012     if (Section == Obj->section_end())
   7013       continue;
   7014 
   7015     uint64_t Addr = SymRef.getValue();
   7016     Symbols.insert(std::make_pair(Addr, SymRef));
   7017   }
   7018 
   7019   for (const SectionRef &Section : Obj->sections()) {
   7020     StringRef SectName;
   7021     Section.getName(SectName);
   7022     if (SectName == "__compact_unwind")
   7023       printMachOCompactUnwindSection(Obj, Symbols, Section);
   7024     else if (SectName == "__unwind_info")
   7025       printMachOUnwindInfoSection(Obj, Symbols, Section);
   7026     else if (SectName == "__eh_frame")
   7027       printMachOEHFrameSection(Obj, Symbols, Section);
   7028   }
   7029 }
   7030 
   7031 static void PrintMachHeader(uint32_t magic, uint32_t cputype,
   7032                             uint32_t cpusubtype, uint32_t filetype,
   7033                             uint32_t ncmds, uint32_t sizeofcmds, uint32_t flags,
   7034                             bool verbose) {
   7035   outs() << "Mach header\n";
   7036   outs() << "      magic cputype cpusubtype  caps    filetype ncmds "
   7037             "sizeofcmds      flags\n";
   7038   if (verbose) {
   7039     if (magic == MachO::MH_MAGIC)
   7040       outs() << "   MH_MAGIC";
   7041     else if (magic == MachO::MH_MAGIC_64)
   7042       outs() << "MH_MAGIC_64";
   7043     else
   7044       outs() << format(" 0x%08" PRIx32, magic);
   7045     switch (cputype) {
   7046     case MachO::CPU_TYPE_I386:
   7047       outs() << "    I386";
   7048       switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
   7049       case MachO::CPU_SUBTYPE_I386_ALL:
   7050         outs() << "        ALL";
   7051         break;
   7052       default:
   7053         outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
   7054         break;
   7055       }
   7056       break;
   7057     case MachO::CPU_TYPE_X86_64:
   7058       outs() << "  X86_64";
   7059       switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
   7060       case MachO::CPU_SUBTYPE_X86_64_ALL:
   7061         outs() << "        ALL";
   7062         break;
   7063       case MachO::CPU_SUBTYPE_X86_64_H:
   7064         outs() << "    Haswell";
   7065         break;
   7066       default:
   7067         outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
   7068         break;
   7069       }
   7070       break;
   7071     case MachO::CPU_TYPE_ARM:
   7072       outs() << "     ARM";
   7073       switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
   7074       case MachO::CPU_SUBTYPE_ARM_ALL:
   7075         outs() << "        ALL";
   7076         break;
   7077       case MachO::CPU_SUBTYPE_ARM_V4T:
   7078         outs() << "        V4T";
   7079         break;
   7080       case MachO::CPU_SUBTYPE_ARM_V5TEJ:
   7081         outs() << "      V5TEJ";
   7082         break;
   7083       case MachO::CPU_SUBTYPE_ARM_XSCALE:
   7084         outs() << "     XSCALE";
   7085         break;
   7086       case MachO::CPU_SUBTYPE_ARM_V6:
   7087         outs() << "         V6";
   7088         break;
   7089       case MachO::CPU_SUBTYPE_ARM_V6M:
   7090         outs() << "        V6M";
   7091         break;
   7092       case MachO::CPU_SUBTYPE_ARM_V7:
   7093         outs() << "         V7";
   7094         break;
   7095       case MachO::CPU_SUBTYPE_ARM_V7EM:
   7096         outs() << "       V7EM";
   7097         break;
   7098       case MachO::CPU_SUBTYPE_ARM_V7K:
   7099         outs() << "        V7K";
   7100         break;
   7101       case MachO::CPU_SUBTYPE_ARM_V7M:
   7102         outs() << "        V7M";
   7103         break;
   7104       case MachO::CPU_SUBTYPE_ARM_V7S:
   7105         outs() << "        V7S";
   7106         break;
   7107       default:
   7108         outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
   7109         break;
   7110       }
   7111       break;
   7112     case MachO::CPU_TYPE_ARM64:
   7113       outs() << "   ARM64";
   7114       switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
   7115       case MachO::CPU_SUBTYPE_ARM64_ALL:
   7116         outs() << "        ALL";
   7117         break;
   7118       default:
   7119         outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
   7120         break;
   7121       }
   7122       break;
   7123     case MachO::CPU_TYPE_POWERPC:
   7124       outs() << "     PPC";
   7125       switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
   7126       case MachO::CPU_SUBTYPE_POWERPC_ALL:
   7127         outs() << "        ALL";
   7128         break;
   7129       default:
   7130         outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
   7131         break;
   7132       }
   7133       break;
   7134     case MachO::CPU_TYPE_POWERPC64:
   7135       outs() << "   PPC64";
   7136       switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
   7137       case MachO::CPU_SUBTYPE_POWERPC_ALL:
   7138         outs() << "        ALL";
   7139         break;
   7140       default:
   7141         outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
   7142         break;
   7143       }
   7144       break;
   7145     }
   7146     if ((cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64) {
   7147       outs() << " LIB64";
   7148     } else {
   7149       outs() << format("  0x%02" PRIx32,
   7150                        (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
   7151     }
   7152     switch (filetype) {
   7153     case MachO::MH_OBJECT:
   7154       outs() << "      OBJECT";
   7155       break;
   7156     case MachO::MH_EXECUTE:
   7157       outs() << "     EXECUTE";
   7158       break;
   7159     case MachO::MH_FVMLIB:
   7160       outs() << "      FVMLIB";
   7161       break;
   7162     case MachO::MH_CORE:
   7163       outs() << "        CORE";
   7164       break;
   7165     case MachO::MH_PRELOAD:
   7166       outs() << "     PRELOAD";
   7167       break;
   7168     case MachO::MH_DYLIB:
   7169       outs() << "       DYLIB";
   7170       break;
   7171     case MachO::MH_DYLIB_STUB:
   7172       outs() << "  DYLIB_STUB";
   7173       break;
   7174     case MachO::MH_DYLINKER:
   7175       outs() << "    DYLINKER";
   7176       break;
   7177     case MachO::MH_BUNDLE:
   7178       outs() << "      BUNDLE";
   7179       break;
   7180     case MachO::MH_DSYM:
   7181       outs() << "        DSYM";
   7182       break;
   7183     case MachO::MH_KEXT_BUNDLE:
   7184       outs() << "  KEXTBUNDLE";
   7185       break;
   7186     default:
   7187       outs() << format("  %10u", filetype);
   7188       break;
   7189     }
   7190     outs() << format(" %5u", ncmds);
   7191     outs() << format(" %10u", sizeofcmds);
   7192     uint32_t f = flags;
   7193     if (f & MachO::MH_NOUNDEFS) {
   7194       outs() << "   NOUNDEFS";
   7195       f &= ~MachO::MH_NOUNDEFS;
   7196     }
   7197     if (f & MachO::MH_INCRLINK) {
   7198       outs() << " INCRLINK";
   7199       f &= ~MachO::MH_INCRLINK;
   7200     }
   7201     if (f & MachO::MH_DYLDLINK) {
   7202       outs() << " DYLDLINK";
   7203       f &= ~MachO::MH_DYLDLINK;
   7204     }
   7205     if (f & MachO::MH_BINDATLOAD) {
   7206       outs() << " BINDATLOAD";
   7207       f &= ~MachO::MH_BINDATLOAD;
   7208     }
   7209     if (f & MachO::MH_PREBOUND) {
   7210       outs() << " PREBOUND";
   7211       f &= ~MachO::MH_PREBOUND;
   7212     }
   7213     if (f & MachO::MH_SPLIT_SEGS) {
   7214       outs() << " SPLIT_SEGS";
   7215       f &= ~MachO::MH_SPLIT_SEGS;
   7216     }
   7217     if (f & MachO::MH_LAZY_INIT) {
   7218       outs() << " LAZY_INIT";
   7219       f &= ~MachO::MH_LAZY_INIT;
   7220     }
   7221     if (f & MachO::MH_TWOLEVEL) {
   7222       outs() << " TWOLEVEL";
   7223       f &= ~MachO::MH_TWOLEVEL;
   7224     }
   7225     if (f & MachO::MH_FORCE_FLAT) {
   7226       outs() << " FORCE_FLAT";
   7227       f &= ~MachO::MH_FORCE_FLAT;
   7228     }
   7229     if (f & MachO::MH_NOMULTIDEFS) {
   7230       outs() << " NOMULTIDEFS";
   7231       f &= ~MachO::MH_NOMULTIDEFS;
   7232     }
   7233     if (f & MachO::MH_NOFIXPREBINDING) {
   7234       outs() << " NOFIXPREBINDING";
   7235       f &= ~MachO::MH_NOFIXPREBINDING;
   7236     }
   7237     if (f & MachO::MH_PREBINDABLE) {
   7238       outs() << " PREBINDABLE";
   7239       f &= ~MachO::MH_PREBINDABLE;
   7240     }
   7241     if (f & MachO::MH_ALLMODSBOUND) {
   7242       outs() << " ALLMODSBOUND";
   7243       f &= ~MachO::MH_ALLMODSBOUND;
   7244     }
   7245     if (f & MachO::MH_SUBSECTIONS_VIA_SYMBOLS) {
   7246       outs() << " SUBSECTIONS_VIA_SYMBOLS";
   7247       f &= ~MachO::MH_SUBSECTIONS_VIA_SYMBOLS;
   7248     }
   7249     if (f & MachO::MH_CANONICAL) {
   7250       outs() << " CANONICAL";
   7251       f &= ~MachO::MH_CANONICAL;
   7252     }
   7253     if (f & MachO::MH_WEAK_DEFINES) {
   7254       outs() << " WEAK_DEFINES";
   7255       f &= ~MachO::MH_WEAK_DEFINES;
   7256     }
   7257     if (f & MachO::MH_BINDS_TO_WEAK) {
   7258       outs() << " BINDS_TO_WEAK";
   7259       f &= ~MachO::MH_BINDS_TO_WEAK;
   7260     }
   7261     if (f & MachO::MH_ALLOW_STACK_EXECUTION) {
   7262       outs() << " ALLOW_STACK_EXECUTION";
   7263       f &= ~MachO::MH_ALLOW_STACK_EXECUTION;
   7264     }
   7265     if (f & MachO::MH_DEAD_STRIPPABLE_DYLIB) {
   7266       outs() << " DEAD_STRIPPABLE_DYLIB";
   7267       f &= ~MachO::MH_DEAD_STRIPPABLE_DYLIB;
   7268     }
   7269     if (f & MachO::MH_PIE) {
   7270       outs() << " PIE";
   7271       f &= ~MachO::MH_PIE;
   7272     }
   7273     if (f & MachO::MH_NO_REEXPORTED_DYLIBS) {
   7274       outs() << " NO_REEXPORTED_DYLIBS";
   7275       f &= ~MachO::MH_NO_REEXPORTED_DYLIBS;
   7276     }
   7277     if (f & MachO::MH_HAS_TLV_DESCRIPTORS) {
   7278       outs() << " MH_HAS_TLV_DESCRIPTORS";
   7279       f &= ~MachO::MH_HAS_TLV_DESCRIPTORS;
   7280     }
   7281     if (f & MachO::MH_NO_HEAP_EXECUTION) {
   7282       outs() << " MH_NO_HEAP_EXECUTION";
   7283       f &= ~MachO::MH_NO_HEAP_EXECUTION;
   7284     }
   7285     if (f & MachO::MH_APP_EXTENSION_SAFE) {
   7286       outs() << " APP_EXTENSION_SAFE";
   7287       f &= ~MachO::MH_APP_EXTENSION_SAFE;
   7288     }
   7289     if (f != 0 || flags == 0)
   7290       outs() << format(" 0x%08" PRIx32, f);
   7291   } else {
   7292     outs() << format(" 0x%08" PRIx32, magic);
   7293     outs() << format(" %7d", cputype);
   7294     outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
   7295     outs() << format("  0x%02" PRIx32,
   7296                      (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
   7297     outs() << format("  %10u", filetype);
   7298     outs() << format(" %5u", ncmds);
   7299     outs() << format(" %10u", sizeofcmds);
   7300     outs() << format(" 0x%08" PRIx32, flags);
   7301   }
   7302   outs() << "\n";
   7303 }
   7304 
   7305 static void PrintSegmentCommand(uint32_t cmd, uint32_t cmdsize,
   7306                                 StringRef SegName, uint64_t vmaddr,
   7307                                 uint64_t vmsize, uint64_t fileoff,
   7308                                 uint64_t filesize, uint32_t maxprot,
   7309                                 uint32_t initprot, uint32_t nsects,
   7310                                 uint32_t flags, uint32_t object_size,
   7311                                 bool verbose) {
   7312   uint64_t expected_cmdsize;
   7313   if (cmd == MachO::LC_SEGMENT) {
   7314     outs() << "      cmd LC_SEGMENT\n";
   7315     expected_cmdsize = nsects;
   7316     expected_cmdsize *= sizeof(struct MachO::section);
   7317     expected_cmdsize += sizeof(struct MachO::segment_command);
   7318   } else {
   7319     outs() << "      cmd LC_SEGMENT_64\n";
   7320     expected_cmdsize = nsects;
   7321     expected_cmdsize *= sizeof(struct MachO::section_64);
   7322     expected_cmdsize += sizeof(struct MachO::segment_command_64);
   7323   }
   7324   outs() << "  cmdsize " << cmdsize;
   7325   if (cmdsize != expected_cmdsize)
   7326     outs() << " Inconsistent size\n";
   7327   else
   7328     outs() << "\n";
   7329   outs() << "  segname " << SegName << "\n";
   7330   if (cmd == MachO::LC_SEGMENT_64) {
   7331     outs() << "   vmaddr " << format("0x%016" PRIx64, vmaddr) << "\n";
   7332     outs() << "   vmsize " << format("0x%016" PRIx64, vmsize) << "\n";
   7333   } else {
   7334     outs() << "   vmaddr " << format("0x%08" PRIx64, vmaddr) << "\n";
   7335     outs() << "   vmsize " << format("0x%08" PRIx64, vmsize) << "\n";
   7336   }
   7337   outs() << "  fileoff " << fileoff;
   7338   if (fileoff > object_size)
   7339     outs() << " (past end of file)\n";
   7340   else
   7341     outs() << "\n";
   7342   outs() << " filesize " << filesize;
   7343   if (fileoff + filesize > object_size)
   7344     outs() << " (past end of file)\n";
   7345   else
   7346     outs() << "\n";
   7347   if (verbose) {
   7348     if ((maxprot &
   7349          ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
   7350            MachO::VM_PROT_EXECUTE)) != 0)
   7351       outs() << "  maxprot ?" << format("0x%08" PRIx32, maxprot) << "\n";
   7352     else {
   7353       outs() << "  maxprot ";
   7354       outs() << ((maxprot & MachO::VM_PROT_READ) ? "r" : "-");
   7355       outs() << ((maxprot & MachO::VM_PROT_WRITE) ? "w" : "-");
   7356       outs() << ((maxprot & MachO::VM_PROT_EXECUTE) ? "x\n" : "-\n");
   7357     }
   7358     if ((initprot &
   7359          ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
   7360            MachO::VM_PROT_EXECUTE)) != 0)
   7361       outs() << "  initprot ?" << format("0x%08" PRIx32, initprot) << "\n";
   7362     else {
   7363       outs() << "  initprot ";
   7364       outs() << ((initprot & MachO::VM_PROT_READ) ? "r" : "-");
   7365       outs() << ((initprot & MachO::VM_PROT_WRITE) ? "w" : "-");
   7366       outs() << ((initprot & MachO::VM_PROT_EXECUTE) ? "x\n" : "-\n");
   7367     }
   7368   } else {
   7369     outs() << "  maxprot " << format("0x%08" PRIx32, maxprot) << "\n";
   7370     outs() << " initprot " << format("0x%08" PRIx32, initprot) << "\n";
   7371   }
   7372   outs() << "   nsects " << nsects << "\n";
   7373   if (verbose) {
   7374     outs() << "    flags";
   7375     if (flags == 0)
   7376       outs() << " (none)\n";
   7377     else {
   7378       if (flags & MachO::SG_HIGHVM) {
   7379         outs() << " HIGHVM";
   7380         flags &= ~MachO::SG_HIGHVM;
   7381       }
   7382       if (flags & MachO::SG_FVMLIB) {
   7383         outs() << " FVMLIB";
   7384         flags &= ~MachO::SG_FVMLIB;
   7385       }
   7386       if (flags & MachO::SG_NORELOC) {
   7387         outs() << " NORELOC";
   7388         flags &= ~MachO::SG_NORELOC;
   7389       }
   7390       if (flags & MachO::SG_PROTECTED_VERSION_1) {
   7391         outs() << " PROTECTED_VERSION_1";
   7392         flags &= ~MachO::SG_PROTECTED_VERSION_1;
   7393       }
   7394       if (flags)
   7395         outs() << format(" 0x%08" PRIx32, flags) << " (unknown flags)\n";
   7396       else
   7397         outs() << "\n";
   7398     }
   7399   } else {
   7400     outs() << "    flags " << format("0x%" PRIx32, flags) << "\n";
   7401   }
   7402 }
   7403 
   7404 static void PrintSection(const char *sectname, const char *segname,
   7405                          uint64_t addr, uint64_t size, uint32_t offset,
   7406                          uint32_t align, uint32_t reloff, uint32_t nreloc,
   7407                          uint32_t flags, uint32_t reserved1, uint32_t reserved2,
   7408                          uint32_t cmd, const char *sg_segname,
   7409                          uint32_t filetype, uint32_t object_size,
   7410                          bool verbose) {
   7411   outs() << "Section\n";
   7412   outs() << "  sectname " << format("%.16s\n", sectname);
   7413   outs() << "   segname " << format("%.16s", segname);
   7414   if (filetype != MachO::MH_OBJECT && strncmp(sg_segname, segname, 16) != 0)
   7415     outs() << " (does not match segment)\n";
   7416   else
   7417     outs() << "\n";
   7418   if (cmd == MachO::LC_SEGMENT_64) {
   7419     outs() << "      addr " << format("0x%016" PRIx64, addr) << "\n";
   7420     outs() << "      size " << format("0x%016" PRIx64, size);
   7421   } else {
   7422     outs() << "      addr " << format("0x%08" PRIx64, addr) << "\n";
   7423     outs() << "      size " << format("0x%08" PRIx64, size);
   7424   }
   7425   if ((flags & MachO::S_ZEROFILL) != 0 && offset + size > object_size)
   7426     outs() << " (past end of file)\n";
   7427   else
   7428     outs() << "\n";
   7429   outs() << "    offset " << offset;
   7430   if (offset > object_size)
   7431     outs() << " (past end of file)\n";
   7432   else
   7433     outs() << "\n";
   7434   uint32_t align_shifted = 1 << align;
   7435   outs() << "     align 2^" << align << " (" << align_shifted << ")\n";
   7436   outs() << "    reloff " << reloff;
   7437   if (reloff > object_size)
   7438     outs() << " (past end of file)\n";
   7439   else
   7440     outs() << "\n";
   7441   outs() << "    nreloc " << nreloc;
   7442   if (reloff + nreloc * sizeof(struct MachO::relocation_info) > object_size)
   7443     outs() << " (past end of file)\n";
   7444   else
   7445     outs() << "\n";
   7446   uint32_t section_type = flags & MachO::SECTION_TYPE;
   7447   if (verbose) {
   7448     outs() << "      type";
   7449     if (section_type == MachO::S_REGULAR)
   7450       outs() << " S_REGULAR\n";
   7451     else if (section_type == MachO::S_ZEROFILL)
   7452       outs() << " S_ZEROFILL\n";
   7453     else if (section_type == MachO::S_CSTRING_LITERALS)
   7454       outs() << " S_CSTRING_LITERALS\n";
   7455     else if (section_type == MachO::S_4BYTE_LITERALS)
   7456       outs() << " S_4BYTE_LITERALS\n";
   7457     else if (section_type == MachO::S_8BYTE_LITERALS)
   7458       outs() << " S_8BYTE_LITERALS\n";
   7459     else if (section_type == MachO::S_16BYTE_LITERALS)
   7460       outs() << " S_16BYTE_LITERALS\n";
   7461     else if (section_type == MachO::S_LITERAL_POINTERS)
   7462       outs() << " S_LITERAL_POINTERS\n";
   7463     else if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS)
   7464       outs() << " S_NON_LAZY_SYMBOL_POINTERS\n";
   7465     else if (section_type == MachO::S_LAZY_SYMBOL_POINTERS)
   7466       outs() << " S_LAZY_SYMBOL_POINTERS\n";
   7467     else if (section_type == MachO::S_SYMBOL_STUBS)
   7468       outs() << " S_SYMBOL_STUBS\n";
   7469     else if (section_type == MachO::S_MOD_INIT_FUNC_POINTERS)
   7470       outs() << " S_MOD_INIT_FUNC_POINTERS\n";
   7471     else if (section_type == MachO::S_MOD_TERM_FUNC_POINTERS)
   7472       outs() << " S_MOD_TERM_FUNC_POINTERS\n";
   7473     else if (section_type == MachO::S_COALESCED)
   7474       outs() << " S_COALESCED\n";
   7475     else if (section_type == MachO::S_INTERPOSING)
   7476       outs() << " S_INTERPOSING\n";
   7477     else if (section_type == MachO::S_DTRACE_DOF)
   7478       outs() << " S_DTRACE_DOF\n";
   7479     else if (section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS)
   7480       outs() << " S_LAZY_DYLIB_SYMBOL_POINTERS\n";
   7481     else if (section_type == MachO::S_THREAD_LOCAL_REGULAR)
   7482       outs() << " S_THREAD_LOCAL_REGULAR\n";
   7483     else if (section_type == MachO::S_THREAD_LOCAL_ZEROFILL)
   7484       outs() << " S_THREAD_LOCAL_ZEROFILL\n";
   7485     else if (section_type == MachO::S_THREAD_LOCAL_VARIABLES)
   7486       outs() << " S_THREAD_LOCAL_VARIABLES\n";
   7487     else if (section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
   7488       outs() << " S_THREAD_LOCAL_VARIABLE_POINTERS\n";
   7489     else if (section_type == MachO::S_THREAD_LOCAL_INIT_FUNCTION_POINTERS)
   7490       outs() << " S_THREAD_LOCAL_INIT_FUNCTION_POINTERS\n";
   7491     else
   7492       outs() << format("0x%08" PRIx32, section_type) << "\n";
   7493     outs() << "attributes";
   7494     uint32_t section_attributes = flags & MachO::SECTION_ATTRIBUTES;
   7495     if (section_attributes & MachO::S_ATTR_PURE_INSTRUCTIONS)
   7496       outs() << " PURE_INSTRUCTIONS";
   7497     if (section_attributes & MachO::S_ATTR_NO_TOC)
   7498       outs() << " NO_TOC";
   7499     if (section_attributes & MachO::S_ATTR_STRIP_STATIC_SYMS)
   7500       outs() << " STRIP_STATIC_SYMS";
   7501     if (section_attributes & MachO::S_ATTR_NO_DEAD_STRIP)
   7502       outs() << " NO_DEAD_STRIP";
   7503     if (section_attributes & MachO::S_ATTR_LIVE_SUPPORT)
   7504       outs() << " LIVE_SUPPORT";
   7505     if (section_attributes & MachO::S_ATTR_SELF_MODIFYING_CODE)
   7506       outs() << " SELF_MODIFYING_CODE";
   7507     if (section_attributes & MachO::S_ATTR_DEBUG)
   7508       outs() << " DEBUG";
   7509     if (section_attributes & MachO::S_ATTR_SOME_INSTRUCTIONS)
   7510       outs() << " SOME_INSTRUCTIONS";
   7511     if (section_attributes & MachO::S_ATTR_EXT_RELOC)
   7512       outs() << " EXT_RELOC";
   7513     if (section_attributes & MachO::S_ATTR_LOC_RELOC)
   7514       outs() << " LOC_RELOC";
   7515     if (section_attributes == 0)
   7516       outs() << " (none)";
   7517     outs() << "\n";
   7518   } else
   7519     outs() << "     flags " << format("0x%08" PRIx32, flags) << "\n";
   7520   outs() << " reserved1 " << reserved1;
   7521   if (section_type == MachO::S_SYMBOL_STUBS ||
   7522       section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
   7523       section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
   7524       section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
   7525       section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
   7526     outs() << " (index into indirect symbol table)\n";
   7527   else
   7528     outs() << "\n";
   7529   outs() << " reserved2 " << reserved2;
   7530   if (section_type == MachO::S_SYMBOL_STUBS)
   7531     outs() << " (size of stubs)\n";
   7532   else
   7533     outs() << "\n";
   7534 }
   7535 
   7536 static void PrintSymtabLoadCommand(MachO::symtab_command st, bool Is64Bit,
   7537                                    uint32_t object_size) {
   7538   outs() << "     cmd LC_SYMTAB\n";
   7539   outs() << " cmdsize " << st.cmdsize;
   7540   if (st.cmdsize != sizeof(struct MachO::symtab_command))
   7541     outs() << " Incorrect size\n";
   7542   else
   7543     outs() << "\n";
   7544   outs() << "  symoff " << st.symoff;
   7545   if (st.symoff > object_size)
   7546     outs() << " (past end of file)\n";
   7547   else
   7548     outs() << "\n";
   7549   outs() << "   nsyms " << st.nsyms;
   7550   uint64_t big_size;
   7551   if (Is64Bit) {
   7552     big_size = st.nsyms;
   7553     big_size *= sizeof(struct MachO::nlist_64);
   7554     big_size += st.symoff;
   7555     if (big_size > object_size)
   7556       outs() << " (past end of file)\n";
   7557     else
   7558       outs() << "\n";
   7559   } else {
   7560     big_size = st.nsyms;
   7561     big_size *= sizeof(struct MachO::nlist);
   7562     big_size += st.symoff;
   7563     if (big_size > object_size)
   7564       outs() << " (past end of file)\n";
   7565     else
   7566       outs() << "\n";
   7567   }
   7568   outs() << "  stroff " << st.stroff;
   7569   if (st.stroff > object_size)
   7570     outs() << " (past end of file)\n";
   7571   else
   7572     outs() << "\n";
   7573   outs() << " strsize " << st.strsize;
   7574   big_size = st.stroff;
   7575   big_size += st.strsize;
   7576   if (big_size > object_size)
   7577     outs() << " (past end of file)\n";
   7578   else
   7579     outs() << "\n";
   7580 }
   7581 
   7582 static void PrintDysymtabLoadCommand(MachO::dysymtab_command dyst,
   7583                                      uint32_t nsyms, uint32_t object_size,
   7584                                      bool Is64Bit) {
   7585   outs() << "            cmd LC_DYSYMTAB\n";
   7586   outs() << "        cmdsize " << dyst.cmdsize;
   7587   if (dyst.cmdsize != sizeof(struct MachO::dysymtab_command))
   7588     outs() << " Incorrect size\n";
   7589   else
   7590     outs() << "\n";
   7591   outs() << "      ilocalsym " << dyst.ilocalsym;
   7592   if (dyst.ilocalsym > nsyms)
   7593     outs() << " (greater than the number of symbols)\n";
   7594   else
   7595     outs() << "\n";
   7596   outs() << "      nlocalsym " << dyst.nlocalsym;
   7597   uint64_t big_size;
   7598   big_size = dyst.ilocalsym;
   7599   big_size += dyst.nlocalsym;
   7600   if (big_size > nsyms)
   7601     outs() << " (past the end of the symbol table)\n";
   7602   else
   7603     outs() << "\n";
   7604   outs() << "     iextdefsym " << dyst.iextdefsym;
   7605   if (dyst.iextdefsym > nsyms)
   7606     outs() << " (greater than the number of symbols)\n";
   7607   else
   7608     outs() << "\n";
   7609   outs() << "     nextdefsym " << dyst.nextdefsym;
   7610   big_size = dyst.iextdefsym;
   7611   big_size += dyst.nextdefsym;
   7612   if (big_size > nsyms)
   7613     outs() << " (past the end of the symbol table)\n";
   7614   else
   7615     outs() << "\n";
   7616   outs() << "      iundefsym " << dyst.iundefsym;
   7617   if (dyst.iundefsym > nsyms)
   7618     outs() << " (greater than the number of symbols)\n";
   7619   else
   7620     outs() << "\n";
   7621   outs() << "      nundefsym " << dyst.nundefsym;
   7622   big_size = dyst.iundefsym;
   7623   big_size += dyst.nundefsym;
   7624   if (big_size > nsyms)
   7625     outs() << " (past the end of the symbol table)\n";
   7626   else
   7627     outs() << "\n";
   7628   outs() << "         tocoff " << dyst.tocoff;
   7629   if (dyst.tocoff > object_size)
   7630     outs() << " (past end of file)\n";
   7631   else
   7632     outs() << "\n";
   7633   outs() << "           ntoc " << dyst.ntoc;
   7634   big_size = dyst.ntoc;
   7635   big_size *= sizeof(struct MachO::dylib_table_of_contents);
   7636   big_size += dyst.tocoff;
   7637   if (big_size > object_size)
   7638     outs() << " (past end of file)\n";
   7639   else
   7640     outs() << "\n";
   7641   outs() << "      modtaboff " << dyst.modtaboff;
   7642   if (dyst.modtaboff > object_size)
   7643     outs() << " (past end of file)\n";
   7644   else
   7645     outs() << "\n";
   7646   outs() << "        nmodtab " << dyst.nmodtab;
   7647   uint64_t modtabend;
   7648   if (Is64Bit) {
   7649     modtabend = dyst.nmodtab;
   7650     modtabend *= sizeof(struct MachO::dylib_module_64);
   7651     modtabend += dyst.modtaboff;
   7652   } else {
   7653     modtabend = dyst.nmodtab;
   7654     modtabend *= sizeof(struct MachO::dylib_module);
   7655     modtabend += dyst.modtaboff;
   7656   }
   7657   if (modtabend > object_size)
   7658     outs() << " (past end of file)\n";
   7659   else
   7660     outs() << "\n";
   7661   outs() << "   extrefsymoff " << dyst.extrefsymoff;
   7662   if (dyst.extrefsymoff > object_size)
   7663     outs() << " (past end of file)\n";
   7664   else
   7665     outs() << "\n";
   7666   outs() << "    nextrefsyms " << dyst.nextrefsyms;
   7667   big_size = dyst.nextrefsyms;
   7668   big_size *= sizeof(struct MachO::dylib_reference);
   7669   big_size += dyst.extrefsymoff;
   7670   if (big_size > object_size)
   7671     outs() << " (past end of file)\n";
   7672   else
   7673     outs() << "\n";
   7674   outs() << " indirectsymoff " << dyst.indirectsymoff;
   7675   if (dyst.indirectsymoff > object_size)
   7676     outs() << " (past end of file)\n";
   7677   else
   7678     outs() << "\n";
   7679   outs() << "  nindirectsyms " << dyst.nindirectsyms;
   7680   big_size = dyst.nindirectsyms;
   7681   big_size *= sizeof(uint32_t);
   7682   big_size += dyst.indirectsymoff;
   7683   if (big_size > object_size)
   7684     outs() << " (past end of file)\n";
   7685   else
   7686     outs() << "\n";
   7687   outs() << "      extreloff " << dyst.extreloff;
   7688   if (dyst.extreloff > object_size)
   7689     outs() << " (past end of file)\n";
   7690   else
   7691     outs() << "\n";
   7692   outs() << "        nextrel " << dyst.nextrel;
   7693   big_size = dyst.nextrel;
   7694   big_size *= sizeof(struct MachO::relocation_info);
   7695   big_size += dyst.extreloff;
   7696   if (big_size > object_size)
   7697     outs() << " (past end of file)\n";
   7698   else
   7699     outs() << "\n";
   7700   outs() << "      locreloff " << dyst.locreloff;
   7701   if (dyst.locreloff > object_size)
   7702     outs() << " (past end of file)\n";
   7703   else
   7704     outs() << "\n";
   7705   outs() << "        nlocrel " << dyst.nlocrel;
   7706   big_size = dyst.nlocrel;
   7707   big_size *= sizeof(struct MachO::relocation_info);
   7708   big_size += dyst.locreloff;
   7709   if (big_size > object_size)
   7710     outs() << " (past end of file)\n";
   7711   else
   7712     outs() << "\n";
   7713 }
   7714 
   7715 static void PrintDyldInfoLoadCommand(MachO::dyld_info_command dc,
   7716                                      uint32_t object_size) {
   7717   if (dc.cmd == MachO::LC_DYLD_INFO)
   7718     outs() << "            cmd LC_DYLD_INFO\n";
   7719   else
   7720     outs() << "            cmd LC_DYLD_INFO_ONLY\n";
   7721   outs() << "        cmdsize " << dc.cmdsize;
   7722   if (dc.cmdsize != sizeof(struct MachO::dyld_info_command))
   7723     outs() << " Incorrect size\n";
   7724   else
   7725     outs() << "\n";
   7726   outs() << "     rebase_off " << dc.rebase_off;
   7727   if (dc.rebase_off > object_size)
   7728     outs() << " (past end of file)\n";
   7729   else
   7730     outs() << "\n";
   7731   outs() << "    rebase_size " << dc.rebase_size;
   7732   uint64_t big_size;
   7733   big_size = dc.rebase_off;
   7734   big_size += dc.rebase_size;
   7735   if (big_size > object_size)
   7736     outs() << " (past end of file)\n";
   7737   else
   7738     outs() << "\n";
   7739   outs() << "       bind_off " << dc.bind_off;
   7740   if (dc.bind_off > object_size)
   7741     outs() << " (past end of file)\n";
   7742   else
   7743     outs() << "\n";
   7744   outs() << "      bind_size " << dc.bind_size;
   7745   big_size = dc.bind_off;
   7746   big_size += dc.bind_size;
   7747   if (big_size > object_size)
   7748     outs() << " (past end of file)\n";
   7749   else
   7750     outs() << "\n";
   7751   outs() << "  weak_bind_off " << dc.weak_bind_off;
   7752   if (dc.weak_bind_off > object_size)
   7753     outs() << " (past end of file)\n";
   7754   else
   7755     outs() << "\n";
   7756   outs() << " weak_bind_size " << dc.weak_bind_size;
   7757   big_size = dc.weak_bind_off;
   7758   big_size += dc.weak_bind_size;
   7759   if (big_size > object_size)
   7760     outs() << " (past end of file)\n";
   7761   else
   7762     outs() << "\n";
   7763   outs() << "  lazy_bind_off " << dc.lazy_bind_off;
   7764   if (dc.lazy_bind_off > object_size)
   7765     outs() << " (past end of file)\n";
   7766   else
   7767     outs() << "\n";
   7768   outs() << " lazy_bind_size " << dc.lazy_bind_size;
   7769   big_size = dc.lazy_bind_off;
   7770   big_size += dc.lazy_bind_size;
   7771   if (big_size > object_size)
   7772     outs() << " (past end of file)\n";
   7773   else
   7774     outs() << "\n";
   7775   outs() << "     export_off " << dc.export_off;
   7776   if (dc.export_off > object_size)
   7777     outs() << " (past end of file)\n";
   7778   else
   7779     outs() << "\n";
   7780   outs() << "    export_size " << dc.export_size;
   7781   big_size = dc.export_off;
   7782   big_size += dc.export_size;
   7783   if (big_size > object_size)
   7784     outs() << " (past end of file)\n";
   7785   else
   7786     outs() << "\n";
   7787 }
   7788 
   7789 static void PrintDyldLoadCommand(MachO::dylinker_command dyld,
   7790                                  const char *Ptr) {
   7791   if (dyld.cmd == MachO::LC_ID_DYLINKER)
   7792     outs() << "          cmd LC_ID_DYLINKER\n";
   7793   else if (dyld.cmd == MachO::LC_LOAD_DYLINKER)
   7794     outs() << "          cmd LC_LOAD_DYLINKER\n";
   7795   else if (dyld.cmd == MachO::LC_DYLD_ENVIRONMENT)
   7796     outs() << "          cmd LC_DYLD_ENVIRONMENT\n";
   7797   else
   7798     outs() << "          cmd ?(" << dyld.cmd << ")\n";
   7799   outs() << "      cmdsize " << dyld.cmdsize;
   7800   if (dyld.cmdsize < sizeof(struct MachO::dylinker_command))
   7801     outs() << " Incorrect size\n";
   7802   else
   7803     outs() << "\n";
   7804   if (dyld.name >= dyld.cmdsize)
   7805     outs() << "         name ?(bad offset " << dyld.name << ")\n";
   7806   else {
   7807     const char *P = (const char *)(Ptr) + dyld.name;
   7808     outs() << "         name " << P << " (offset " << dyld.name << ")\n";
   7809   }
   7810 }
   7811 
   7812 static void PrintUuidLoadCommand(MachO::uuid_command uuid) {
   7813   outs() << "     cmd LC_UUID\n";
   7814   outs() << " cmdsize " << uuid.cmdsize;
   7815   if (uuid.cmdsize != sizeof(struct MachO::uuid_command))
   7816     outs() << " Incorrect size\n";
   7817   else
   7818     outs() << "\n";
   7819   outs() << "    uuid ";
   7820   for (int i = 0; i < 16; ++i) {
   7821     outs() << format("%02" PRIX32, uuid.uuid[i]);
   7822     if (i == 3 || i == 5 || i == 7 || i == 9)
   7823       outs() << "-";
   7824   }
   7825   outs() << "\n";
   7826 }
   7827 
   7828 static void PrintRpathLoadCommand(MachO::rpath_command rpath, const char *Ptr) {
   7829   outs() << "          cmd LC_RPATH\n";
   7830   outs() << "      cmdsize " << rpath.cmdsize;
   7831   if (rpath.cmdsize < sizeof(struct MachO::rpath_command))
   7832     outs() << " Incorrect size\n";
   7833   else
   7834     outs() << "\n";
   7835   if (rpath.path >= rpath.cmdsize)
   7836     outs() << "         path ?(bad offset " << rpath.path << ")\n";
   7837   else {
   7838     const char *P = (const char *)(Ptr) + rpath.path;
   7839     outs() << "         path " << P << " (offset " << rpath.path << ")\n";
   7840   }
   7841 }
   7842 
   7843 static void PrintVersionMinLoadCommand(MachO::version_min_command vd) {
   7844   StringRef LoadCmdName;
   7845   switch (vd.cmd) {
   7846   case MachO::LC_VERSION_MIN_MACOSX:
   7847     LoadCmdName = "LC_VERSION_MIN_MACOSX";
   7848     break;
   7849   case MachO::LC_VERSION_MIN_IPHONEOS:
   7850     LoadCmdName = "LC_VERSION_MIN_IPHONEOS";
   7851     break;
   7852   case MachO::LC_VERSION_MIN_TVOS:
   7853     LoadCmdName = "LC_VERSION_MIN_TVOS";
   7854     break;
   7855   case MachO::LC_VERSION_MIN_WATCHOS:
   7856     LoadCmdName = "LC_VERSION_MIN_WATCHOS";
   7857     break;
   7858   default:
   7859     llvm_unreachable("Unknown version min load command");
   7860   }
   7861 
   7862   outs() << "      cmd " << LoadCmdName << '\n';
   7863   outs() << "  cmdsize " << vd.cmdsize;
   7864   if (vd.cmdsize != sizeof(struct MachO::version_min_command))
   7865     outs() << " Incorrect size\n";
   7866   else
   7867     outs() << "\n";
   7868   outs() << "  version "
   7869          << MachOObjectFile::getVersionMinMajor(vd, false) << "."
   7870          << MachOObjectFile::getVersionMinMinor(vd, false);
   7871   uint32_t Update = MachOObjectFile::getVersionMinUpdate(vd, false);
   7872   if (Update != 0)
   7873     outs() << "." << Update;
   7874   outs() << "\n";
   7875   if (vd.sdk == 0)
   7876     outs() << "      sdk n/a";
   7877   else {
   7878     outs() << "      sdk "
   7879            << MachOObjectFile::getVersionMinMajor(vd, true) << "."
   7880            << MachOObjectFile::getVersionMinMinor(vd, true);
   7881   }
   7882   Update = MachOObjectFile::getVersionMinUpdate(vd, true);
   7883   if (Update != 0)
   7884     outs() << "." << Update;
   7885   outs() << "\n";
   7886 }
   7887 
   7888 static void PrintSourceVersionCommand(MachO::source_version_command sd) {
   7889   outs() << "      cmd LC_SOURCE_VERSION\n";
   7890   outs() << "  cmdsize " << sd.cmdsize;
   7891   if (sd.cmdsize != sizeof(struct MachO::source_version_command))
   7892     outs() << " Incorrect size\n";
   7893   else
   7894     outs() << "\n";
   7895   uint64_t a = (sd.version >> 40) & 0xffffff;
   7896   uint64_t b = (sd.version >> 30) & 0x3ff;
   7897   uint64_t c = (sd.version >> 20) & 0x3ff;
   7898   uint64_t d = (sd.version >> 10) & 0x3ff;
   7899   uint64_t e = sd.version & 0x3ff;
   7900   outs() << "  version " << a << "." << b;
   7901   if (e != 0)
   7902     outs() << "." << c << "." << d << "." << e;
   7903   else if (d != 0)
   7904     outs() << "." << c << "." << d;
   7905   else if (c != 0)
   7906     outs() << "." << c;
   7907   outs() << "\n";
   7908 }
   7909 
   7910 static void PrintEntryPointCommand(MachO::entry_point_command ep) {
   7911   outs() << "       cmd LC_MAIN\n";
   7912   outs() << "   cmdsize " << ep.cmdsize;
   7913   if (ep.cmdsize != sizeof(struct MachO::entry_point_command))
   7914     outs() << " Incorrect size\n";
   7915   else
   7916     outs() << "\n";
   7917   outs() << "  entryoff " << ep.entryoff << "\n";
   7918   outs() << " stacksize " << ep.stacksize << "\n";
   7919 }
   7920 
   7921 static void PrintEncryptionInfoCommand(MachO::encryption_info_command ec,
   7922                                        uint32_t object_size) {
   7923   outs() << "          cmd LC_ENCRYPTION_INFO\n";
   7924   outs() << "      cmdsize " << ec.cmdsize;
   7925   if (ec.cmdsize != sizeof(struct MachO::encryption_info_command))
   7926     outs() << " Incorrect size\n";
   7927   else
   7928     outs() << "\n";
   7929   outs() << "     cryptoff " << ec.cryptoff;
   7930   if (ec.cryptoff > object_size)
   7931     outs() << " (past end of file)\n";
   7932   else
   7933     outs() << "\n";
   7934   outs() << "    cryptsize " << ec.cryptsize;
   7935   if (ec.cryptsize > object_size)
   7936     outs() << " (past end of file)\n";
   7937   else
   7938     outs() << "\n";
   7939   outs() << "      cryptid " << ec.cryptid << "\n";
   7940 }
   7941 
   7942 static void PrintEncryptionInfoCommand64(MachO::encryption_info_command_64 ec,
   7943                                          uint32_t object_size) {
   7944   outs() << "          cmd LC_ENCRYPTION_INFO_64\n";
   7945   outs() << "      cmdsize " << ec.cmdsize;
   7946   if (ec.cmdsize != sizeof(struct MachO::encryption_info_command_64))
   7947     outs() << " Incorrect size\n";
   7948   else
   7949     outs() << "\n";
   7950   outs() << "     cryptoff " << ec.cryptoff;
   7951   if (ec.cryptoff > object_size)
   7952     outs() << " (past end of file)\n";
   7953   else
   7954     outs() << "\n";
   7955   outs() << "    cryptsize " << ec.cryptsize;
   7956   if (ec.cryptsize > object_size)
   7957     outs() << " (past end of file)\n";
   7958   else
   7959     outs() << "\n";
   7960   outs() << "      cryptid " << ec.cryptid << "\n";
   7961   outs() << "          pad " << ec.pad << "\n";
   7962 }
   7963 
   7964 static void PrintLinkerOptionCommand(MachO::linker_option_command lo,
   7965                                      const char *Ptr) {
   7966   outs() << "     cmd LC_LINKER_OPTION\n";
   7967   outs() << " cmdsize " << lo.cmdsize;
   7968   if (lo.cmdsize < sizeof(struct MachO::linker_option_command))
   7969     outs() << " Incorrect size\n";
   7970   else
   7971     outs() << "\n";
   7972   outs() << "   count " << lo.count << "\n";
   7973   const char *string = Ptr + sizeof(struct MachO::linker_option_command);
   7974   uint32_t left = lo.cmdsize - sizeof(struct MachO::linker_option_command);
   7975   uint32_t i = 0;
   7976   while (left > 0) {
   7977     while (*string == '\0' && left > 0) {
   7978       string++;
   7979       left--;
   7980     }
   7981     if (left > 0) {
   7982       i++;
   7983       outs() << "  string #" << i << " " << format("%.*s\n", left, string);
   7984       uint32_t NullPos = StringRef(string, left).find('\0');
   7985       uint32_t len = std::min(NullPos, left) + 1;
   7986       string += len;
   7987       left -= len;
   7988     }
   7989   }
   7990   if (lo.count != i)
   7991     outs() << "   count " << lo.count << " does not match number of strings "
   7992            << i << "\n";
   7993 }
   7994 
   7995 static void PrintSubFrameworkCommand(MachO::sub_framework_command sub,
   7996                                      const char *Ptr) {
   7997   outs() << "          cmd LC_SUB_FRAMEWORK\n";
   7998   outs() << "      cmdsize " << sub.cmdsize;
   7999   if (sub.cmdsize < sizeof(struct MachO::sub_framework_command))
   8000     outs() << " Incorrect size\n";
   8001   else
   8002     outs() << "\n";
   8003   if (sub.umbrella < sub.cmdsize) {
   8004     const char *P = Ptr + sub.umbrella;
   8005     outs() << "     umbrella " << P << " (offset " << sub.umbrella << ")\n";
   8006   } else {
   8007     outs() << "     umbrella ?(bad offset " << sub.umbrella << ")\n";
   8008   }
   8009 }
   8010 
   8011 static void PrintSubUmbrellaCommand(MachO::sub_umbrella_command sub,
   8012                                     const char *Ptr) {
   8013   outs() << "          cmd LC_SUB_UMBRELLA\n";
   8014   outs() << "      cmdsize " << sub.cmdsize;
   8015   if (sub.cmdsize < sizeof(struct MachO::sub_umbrella_command))
   8016     outs() << " Incorrect size\n";
   8017   else
   8018     outs() << "\n";
   8019   if (sub.sub_umbrella < sub.cmdsize) {
   8020     const char *P = Ptr + sub.sub_umbrella;
   8021     outs() << " sub_umbrella " << P << " (offset " << sub.sub_umbrella << ")\n";
   8022   } else {
   8023     outs() << " sub_umbrella ?(bad offset " << sub.sub_umbrella << ")\n";
   8024   }
   8025 }
   8026 
   8027 static void PrintSubLibraryCommand(MachO::sub_library_command sub,
   8028                                    const char *Ptr) {
   8029   outs() << "          cmd LC_SUB_LIBRARY\n";
   8030   outs() << "      cmdsize " << sub.cmdsize;
   8031   if (sub.cmdsize < sizeof(struct MachO::sub_library_command))
   8032     outs() << " Incorrect size\n";
   8033   else
   8034     outs() << "\n";
   8035   if (sub.sub_library < sub.cmdsize) {
   8036     const char *P = Ptr + sub.sub_library;
   8037     outs() << "  sub_library " << P << " (offset " << sub.sub_library << ")\n";
   8038   } else {
   8039     outs() << "  sub_library ?(bad offset " << sub.sub_library << ")\n";
   8040   }
   8041 }
   8042 
   8043 static void PrintSubClientCommand(MachO::sub_client_command sub,
   8044                                   const char *Ptr) {
   8045   outs() << "          cmd LC_SUB_CLIENT\n";
   8046   outs() << "      cmdsize " << sub.cmdsize;
   8047   if (sub.cmdsize < sizeof(struct MachO::sub_client_command))
   8048     outs() << " Incorrect size\n";
   8049   else
   8050     outs() << "\n";
   8051   if (sub.client < sub.cmdsize) {
   8052     const char *P = Ptr + sub.client;
   8053     outs() << "       client " << P << " (offset " << sub.client << ")\n";
   8054   } else {
   8055     outs() << "       client ?(bad offset " << sub.client << ")\n";
   8056   }
   8057 }
   8058 
   8059 static void PrintRoutinesCommand(MachO::routines_command r) {
   8060   outs() << "          cmd LC_ROUTINES\n";
   8061   outs() << "      cmdsize " << r.cmdsize;
   8062   if (r.cmdsize != sizeof(struct MachO::routines_command))
   8063     outs() << " Incorrect size\n";
   8064   else
   8065     outs() << "\n";
   8066   outs() << " init_address " << format("0x%08" PRIx32, r.init_address) << "\n";
   8067   outs() << "  init_module " << r.init_module << "\n";
   8068   outs() << "    reserved1 " << r.reserved1 << "\n";
   8069   outs() << "    reserved2 " << r.reserved2 << "\n";
   8070   outs() << "    reserved3 " << r.reserved3 << "\n";
   8071   outs() << "    reserved4 " << r.reserved4 << "\n";
   8072   outs() << "    reserved5 " << r.reserved5 << "\n";
   8073   outs() << "    reserved6 " << r.reserved6 << "\n";
   8074 }
   8075 
   8076 static void PrintRoutinesCommand64(MachO::routines_command_64 r) {
   8077   outs() << "          cmd LC_ROUTINES_64\n";
   8078   outs() << "      cmdsize " << r.cmdsize;
   8079   if (r.cmdsize != sizeof(struct MachO::routines_command_64))
   8080     outs() << " Incorrect size\n";
   8081   else
   8082     outs() << "\n";
   8083   outs() << " init_address " << format("0x%016" PRIx64, r.init_address) << "\n";
   8084   outs() << "  init_module " << r.init_module << "\n";
   8085   outs() << "    reserved1 " << r.reserved1 << "\n";
   8086   outs() << "    reserved2 " << r.reserved2 << "\n";
   8087   outs() << "    reserved3 " << r.reserved3 << "\n";
   8088   outs() << "    reserved4 " << r.reserved4 << "\n";
   8089   outs() << "    reserved5 " << r.reserved5 << "\n";
   8090   outs() << "    reserved6 " << r.reserved6 << "\n";
   8091 }
   8092 
   8093 static void Print_x86_thread_state64_t(MachO::x86_thread_state64_t &cpu64) {
   8094   outs() << "   rax  " << format("0x%016" PRIx64, cpu64.rax);
   8095   outs() << " rbx " << format("0x%016" PRIx64, cpu64.rbx);
   8096   outs() << " rcx  " << format("0x%016" PRIx64, cpu64.rcx) << "\n";
   8097   outs() << "   rdx  " << format("0x%016" PRIx64, cpu64.rdx);
   8098   outs() << " rdi " << format("0x%016" PRIx64, cpu64.rdi);
   8099   outs() << " rsi  " << format("0x%016" PRIx64, cpu64.rsi) << "\n";
   8100   outs() << "   rbp  " << format("0x%016" PRIx64, cpu64.rbp);
   8101   outs() << " rsp " << format("0x%016" PRIx64, cpu64.rsp);
   8102   outs() << " r8   " << format("0x%016" PRIx64, cpu64.r8) << "\n";
   8103   outs() << "    r9  " << format("0x%016" PRIx64, cpu64.r9);
   8104   outs() << " r10 " << format("0x%016" PRIx64, cpu64.r10);
   8105   outs() << " r11  " << format("0x%016" PRIx64, cpu64.r11) << "\n";
   8106   outs() << "   r12  " << format("0x%016" PRIx64, cpu64.r12);
   8107   outs() << " r13 " << format("0x%016" PRIx64, cpu64.r13);
   8108   outs() << " r14  " << format("0x%016" PRIx64, cpu64.r14) << "\n";
   8109   outs() << "   r15  " << format("0x%016" PRIx64, cpu64.r15);
   8110   outs() << " rip " << format("0x%016" PRIx64, cpu64.rip) << "\n";
   8111   outs() << "rflags  " << format("0x%016" PRIx64, cpu64.rflags);
   8112   outs() << " cs  " << format("0x%016" PRIx64, cpu64.cs);
   8113   outs() << " fs   " << format("0x%016" PRIx64, cpu64.fs) << "\n";
   8114   outs() << "    gs  " << format("0x%016" PRIx64, cpu64.gs) << "\n";
   8115 }
   8116 
   8117 static void Print_mmst_reg(MachO::mmst_reg_t &r) {
   8118   uint32_t f;
   8119   outs() << "\t      mmst_reg  ";
   8120   for (f = 0; f < 10; f++)
   8121     outs() << format("%02" PRIx32, (r.mmst_reg[f] & 0xff)) << " ";
   8122   outs() << "\n";
   8123   outs() << "\t      mmst_rsrv ";
   8124   for (f = 0; f < 6; f++)
   8125     outs() << format("%02" PRIx32, (r.mmst_rsrv[f] & 0xff)) << " ";
   8126   outs() << "\n";
   8127 }
   8128 
   8129 static void Print_xmm_reg(MachO::xmm_reg_t &r) {
   8130   uint32_t f;
   8131   outs() << "\t      xmm_reg ";
   8132   for (f = 0; f < 16; f++)
   8133     outs() << format("%02" PRIx32, (r.xmm_reg[f] & 0xff)) << " ";
   8134   outs() << "\n";
   8135 }
   8136 
   8137 static void Print_x86_float_state_t(MachO::x86_float_state64_t &fpu) {
   8138   outs() << "\t    fpu_reserved[0] " << fpu.fpu_reserved[0];
   8139   outs() << " fpu_reserved[1] " << fpu.fpu_reserved[1] << "\n";
   8140   outs() << "\t    control: invalid " << fpu.fpu_fcw.invalid;
   8141   outs() << " denorm " << fpu.fpu_fcw.denorm;
   8142   outs() << " zdiv " << fpu.fpu_fcw.zdiv;
   8143   outs() << " ovrfl " << fpu.fpu_fcw.ovrfl;
   8144   outs() << " undfl " << fpu.fpu_fcw.undfl;
   8145   outs() << " precis " << fpu.fpu_fcw.precis << "\n";
   8146   outs() << "\t\t     pc ";
   8147   if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_24B)
   8148     outs() << "FP_PREC_24B ";
   8149   else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_53B)
   8150     outs() << "FP_PREC_53B ";
   8151   else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_64B)
   8152     outs() << "FP_PREC_64B ";
   8153   else
   8154     outs() << fpu.fpu_fcw.pc << " ";
   8155   outs() << "rc ";
   8156   if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_NEAR)
   8157     outs() << "FP_RND_NEAR ";
   8158   else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_DOWN)
   8159     outs() << "FP_RND_DOWN ";
   8160   else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_UP)
   8161     outs() << "FP_RND_UP ";
   8162   else if (fpu.fpu_fcw.rc == MachO::x86_FP_CHOP)
   8163     outs() << "FP_CHOP ";
   8164   outs() << "\n";
   8165   outs() << "\t    status: invalid " << fpu.fpu_fsw.invalid;
   8166   outs() << " denorm " << fpu.fpu_fsw.denorm;
   8167   outs() << " zdiv " << fpu.fpu_fsw.zdiv;
   8168   outs() << " ovrfl " << fpu.fpu_fsw.ovrfl;
   8169   outs() << " undfl " << fpu.fpu_fsw.undfl;
   8170   outs() << " precis " << fpu.fpu_fsw.precis;
   8171   outs() << " stkflt " << fpu.fpu_fsw.stkflt << "\n";
   8172   outs() << "\t            errsumm " << fpu.fpu_fsw.errsumm;
   8173   outs() << " c0 " << fpu.fpu_fsw.c0;
   8174   outs() << " c1 " << fpu.fpu_fsw.c1;
   8175   outs() << " c2 " << fpu.fpu_fsw.c2;
   8176   outs() << " tos " << fpu.fpu_fsw.tos;
   8177   outs() << " c3 " << fpu.fpu_fsw.c3;
   8178   outs() << " busy " << fpu.fpu_fsw.busy << "\n";
   8179   outs() << "\t    fpu_ftw " << format("0x%02" PRIx32, fpu.fpu_ftw);
   8180   outs() << " fpu_rsrv1 " << format("0x%02" PRIx32, fpu.fpu_rsrv1);
   8181   outs() << " fpu_fop " << format("0x%04" PRIx32, fpu.fpu_fop);
   8182   outs() << " fpu_ip " << format("0x%08" PRIx32, fpu.fpu_ip) << "\n";
   8183   outs() << "\t    fpu_cs " << format("0x%04" PRIx32, fpu.fpu_cs);
   8184   outs() << " fpu_rsrv2 " << format("0x%04" PRIx32, fpu.fpu_rsrv2);
   8185   outs() << " fpu_dp " << format("0x%08" PRIx32, fpu.fpu_dp);
   8186   outs() << " fpu_ds " << format("0x%04" PRIx32, fpu.fpu_ds) << "\n";
   8187   outs() << "\t    fpu_rsrv3 " << format("0x%04" PRIx32, fpu.fpu_rsrv3);
   8188   outs() << " fpu_mxcsr " << format("0x%08" PRIx32, fpu.fpu_mxcsr);
   8189   outs() << " fpu_mxcsrmask " << format("0x%08" PRIx32, fpu.fpu_mxcsrmask);
   8190   outs() << "\n";
   8191   outs() << "\t    fpu_stmm0:\n";
   8192   Print_mmst_reg(fpu.fpu_stmm0);
   8193   outs() << "\t    fpu_stmm1:\n";
   8194   Print_mmst_reg(fpu.fpu_stmm1);
   8195   outs() << "\t    fpu_stmm2:\n";
   8196   Print_mmst_reg(fpu.fpu_stmm2);
   8197   outs() << "\t    fpu_stmm3:\n";
   8198   Print_mmst_reg(fpu.fpu_stmm3);
   8199   outs() << "\t    fpu_stmm4:\n";
   8200   Print_mmst_reg(fpu.fpu_stmm4);
   8201   outs() << "\t    fpu_stmm5:\n";
   8202   Print_mmst_reg(fpu.fpu_stmm5);
   8203   outs() << "\t    fpu_stmm6:\n";
   8204   Print_mmst_reg(fpu.fpu_stmm6);
   8205   outs() << "\t    fpu_stmm7:\n";
   8206   Print_mmst_reg(fpu.fpu_stmm7);
   8207   outs() << "\t    fpu_xmm0:\n";
   8208   Print_xmm_reg(fpu.fpu_xmm0);
   8209   outs() << "\t    fpu_xmm1:\n";
   8210   Print_xmm_reg(fpu.fpu_xmm1);
   8211   outs() << "\t    fpu_xmm2:\n";
   8212   Print_xmm_reg(fpu.fpu_xmm2);
   8213   outs() << "\t    fpu_xmm3:\n";
   8214   Print_xmm_reg(fpu.fpu_xmm3);
   8215   outs() << "\t    fpu_xmm4:\n";
   8216   Print_xmm_reg(fpu.fpu_xmm4);
   8217   outs() << "\t    fpu_xmm5:\n";
   8218   Print_xmm_reg(fpu.fpu_xmm5);
   8219   outs() << "\t    fpu_xmm6:\n";
   8220   Print_xmm_reg(fpu.fpu_xmm6);
   8221   outs() << "\t    fpu_xmm7:\n";
   8222   Print_xmm_reg(fpu.fpu_xmm7);
   8223   outs() << "\t    fpu_xmm8:\n";
   8224   Print_xmm_reg(fpu.fpu_xmm8);
   8225   outs() << "\t    fpu_xmm9:\n";
   8226   Print_xmm_reg(fpu.fpu_xmm9);
   8227   outs() << "\t    fpu_xmm10:\n";
   8228   Print_xmm_reg(fpu.fpu_xmm10);
   8229   outs() << "\t    fpu_xmm11:\n";
   8230   Print_xmm_reg(fpu.fpu_xmm11);
   8231   outs() << "\t    fpu_xmm12:\n";
   8232   Print_xmm_reg(fpu.fpu_xmm12);
   8233   outs() << "\t    fpu_xmm13:\n";
   8234   Print_xmm_reg(fpu.fpu_xmm13);
   8235   outs() << "\t    fpu_xmm14:\n";
   8236   Print_xmm_reg(fpu.fpu_xmm14);
   8237   outs() << "\t    fpu_xmm15:\n";
   8238   Print_xmm_reg(fpu.fpu_xmm15);
   8239   outs() << "\t    fpu_rsrv4:\n";
   8240   for (uint32_t f = 0; f < 6; f++) {
   8241     outs() << "\t            ";
   8242     for (uint32_t g = 0; g < 16; g++)
   8243       outs() << format("%02" PRIx32, fpu.fpu_rsrv4[f * g]) << " ";
   8244     outs() << "\n";
   8245   }
   8246   outs() << "\t    fpu_reserved1 " << format("0x%08" PRIx32, fpu.fpu_reserved1);
   8247   outs() << "\n";
   8248 }
   8249 
   8250 static void Print_x86_exception_state_t(MachO::x86_exception_state64_t &exc64) {
   8251   outs() << "\t    trapno " << format("0x%08" PRIx32, exc64.trapno);
   8252   outs() << " err " << format("0x%08" PRIx32, exc64.err);
   8253   outs() << " faultvaddr " << format("0x%016" PRIx64, exc64.faultvaddr) << "\n";
   8254 }
   8255 
   8256 static void PrintThreadCommand(MachO::thread_command t, const char *Ptr,
   8257                                bool isLittleEndian, uint32_t cputype) {
   8258   if (t.cmd == MachO::LC_THREAD)
   8259     outs() << "        cmd LC_THREAD\n";
   8260   else if (t.cmd == MachO::LC_UNIXTHREAD)
   8261     outs() << "        cmd LC_UNIXTHREAD\n";
   8262   else
   8263     outs() << "        cmd " << t.cmd << " (unknown)\n";
   8264   outs() << "    cmdsize " << t.cmdsize;
   8265   if (t.cmdsize < sizeof(struct MachO::thread_command) + 2 * sizeof(uint32_t))
   8266     outs() << " Incorrect size\n";
   8267   else
   8268     outs() << "\n";
   8269 
   8270   const char *begin = Ptr + sizeof(struct MachO::thread_command);
   8271   const char *end = Ptr + t.cmdsize;
   8272   uint32_t flavor, count, left;
   8273   if (cputype == MachO::CPU_TYPE_X86_64) {
   8274     while (begin < end) {
   8275       if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
   8276         memcpy((char *)&flavor, begin, sizeof(uint32_t));
   8277         begin += sizeof(uint32_t);
   8278       } else {
   8279         flavor = 0;
   8280         begin = end;
   8281       }
   8282       if (isLittleEndian != sys::IsLittleEndianHost)
   8283         sys::swapByteOrder(flavor);
   8284       if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
   8285         memcpy((char *)&count, begin, sizeof(uint32_t));
   8286         begin += sizeof(uint32_t);
   8287       } else {
   8288         count = 0;
   8289         begin = end;
   8290       }
   8291       if (isLittleEndian != sys::IsLittleEndianHost)
   8292         sys::swapByteOrder(count);
   8293       if (flavor == MachO::x86_THREAD_STATE64) {
   8294         outs() << "     flavor x86_THREAD_STATE64\n";
   8295         if (count == MachO::x86_THREAD_STATE64_COUNT)
   8296           outs() << "      count x86_THREAD_STATE64_COUNT\n";
   8297         else
   8298           outs() << "      count " << count
   8299                  << " (not x86_THREAD_STATE64_COUNT)\n";
   8300         MachO::x86_thread_state64_t cpu64;
   8301         left = end - begin;
   8302         if (left >= sizeof(MachO::x86_thread_state64_t)) {
   8303           memcpy(&cpu64, begin, sizeof(MachO::x86_thread_state64_t));
   8304           begin += sizeof(MachO::x86_thread_state64_t);
   8305         } else {
   8306           memset(&cpu64, '\0', sizeof(MachO::x86_thread_state64_t));
   8307           memcpy(&cpu64, begin, left);
   8308           begin += left;
   8309         }
   8310         if (isLittleEndian != sys::IsLittleEndianHost)
   8311           swapStruct(cpu64);
   8312         Print_x86_thread_state64_t(cpu64);
   8313       } else if (flavor == MachO::x86_THREAD_STATE) {
   8314         outs() << "     flavor x86_THREAD_STATE\n";
   8315         if (count == MachO::x86_THREAD_STATE_COUNT)
   8316           outs() << "      count x86_THREAD_STATE_COUNT\n";
   8317         else
   8318           outs() << "      count " << count
   8319                  << " (not x86_THREAD_STATE_COUNT)\n";
   8320         struct MachO::x86_thread_state_t ts;
   8321         left = end - begin;
   8322         if (left >= sizeof(MachO::x86_thread_state_t)) {
   8323           memcpy(&ts, begin, sizeof(MachO::x86_thread_state_t));
   8324           begin += sizeof(MachO::x86_thread_state_t);
   8325         } else {
   8326           memset(&ts, '\0', sizeof(MachO::x86_thread_state_t));
   8327           memcpy(&ts, begin, left);
   8328           begin += left;
   8329         }
   8330         if (isLittleEndian != sys::IsLittleEndianHost)
   8331           swapStruct(ts);
   8332         if (ts.tsh.flavor == MachO::x86_THREAD_STATE64) {
   8333           outs() << "\t    tsh.flavor x86_THREAD_STATE64 ";
   8334           if (ts.tsh.count == MachO::x86_THREAD_STATE64_COUNT)
   8335             outs() << "tsh.count x86_THREAD_STATE64_COUNT\n";
   8336           else
   8337             outs() << "tsh.count " << ts.tsh.count
   8338                    << " (not x86_THREAD_STATE64_COUNT\n";
   8339           Print_x86_thread_state64_t(ts.uts.ts64);
   8340         } else {
   8341           outs() << "\t    tsh.flavor " << ts.tsh.flavor << "  tsh.count "
   8342                  << ts.tsh.count << "\n";
   8343         }
   8344       } else if (flavor == MachO::x86_FLOAT_STATE) {
   8345         outs() << "     flavor x86_FLOAT_STATE\n";
   8346         if (count == MachO::x86_FLOAT_STATE_COUNT)
   8347           outs() << "      count x86_FLOAT_STATE_COUNT\n";
   8348         else
   8349           outs() << "      count " << count << " (not x86_FLOAT_STATE_COUNT)\n";
   8350         struct MachO::x86_float_state_t fs;
   8351         left = end - begin;
   8352         if (left >= sizeof(MachO::x86_float_state_t)) {
   8353           memcpy(&fs, begin, sizeof(MachO::x86_float_state_t));
   8354           begin += sizeof(MachO::x86_float_state_t);
   8355         } else {
   8356           memset(&fs, '\0', sizeof(MachO::x86_float_state_t));
   8357           memcpy(&fs, begin, left);
   8358           begin += left;
   8359         }
   8360         if (isLittleEndian != sys::IsLittleEndianHost)
   8361           swapStruct(fs);
   8362         if (fs.fsh.flavor == MachO::x86_FLOAT_STATE64) {
   8363           outs() << "\t    fsh.flavor x86_FLOAT_STATE64 ";
   8364           if (fs.fsh.count == MachO::x86_FLOAT_STATE64_COUNT)
   8365             outs() << "fsh.count x86_FLOAT_STATE64_COUNT\n";
   8366           else
   8367             outs() << "fsh.count " << fs.fsh.count
   8368                    << " (not x86_FLOAT_STATE64_COUNT\n";
   8369           Print_x86_float_state_t(fs.ufs.fs64);
   8370         } else {
   8371           outs() << "\t    fsh.flavor " << fs.fsh.flavor << "  fsh.count "
   8372                  << fs.fsh.count << "\n";
   8373         }
   8374       } else if (flavor == MachO::x86_EXCEPTION_STATE) {
   8375         outs() << "     flavor x86_EXCEPTION_STATE\n";
   8376         if (count == MachO::x86_EXCEPTION_STATE_COUNT)
   8377           outs() << "      count x86_EXCEPTION_STATE_COUNT\n";
   8378         else
   8379           outs() << "      count " << count
   8380                  << " (not x86_EXCEPTION_STATE_COUNT)\n";
   8381         struct MachO::x86_exception_state_t es;
   8382         left = end - begin;
   8383         if (left >= sizeof(MachO::x86_exception_state_t)) {
   8384           memcpy(&es, begin, sizeof(MachO::x86_exception_state_t));
   8385           begin += sizeof(MachO::x86_exception_state_t);
   8386         } else {
   8387           memset(&es, '\0', sizeof(MachO::x86_exception_state_t));
   8388           memcpy(&es, begin, left);
   8389           begin += left;
   8390         }
   8391         if (isLittleEndian != sys::IsLittleEndianHost)
   8392           swapStruct(es);
   8393         if (es.esh.flavor == MachO::x86_EXCEPTION_STATE64) {
   8394           outs() << "\t    esh.flavor x86_EXCEPTION_STATE64\n";
   8395           if (es.esh.count == MachO::x86_EXCEPTION_STATE64_COUNT)
   8396             outs() << "\t    esh.count x86_EXCEPTION_STATE64_COUNT\n";
   8397           else
   8398             outs() << "\t    esh.count " << es.esh.count
   8399                    << " (not x86_EXCEPTION_STATE64_COUNT\n";
   8400           Print_x86_exception_state_t(es.ues.es64);
   8401         } else {
   8402           outs() << "\t    esh.flavor " << es.esh.flavor << "  esh.count "
   8403                  << es.esh.count << "\n";
   8404         }
   8405       } else {
   8406         outs() << "     flavor " << flavor << " (unknown)\n";
   8407         outs() << "      count " << count << "\n";
   8408         outs() << "      state (unknown)\n";
   8409         begin += count * sizeof(uint32_t);
   8410       }
   8411     }
   8412   } else {
   8413     while (begin < end) {
   8414       if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
   8415         memcpy((char *)&flavor, begin, sizeof(uint32_t));
   8416         begin += sizeof(uint32_t);
   8417       } else {
   8418         flavor = 0;
   8419         begin = end;
   8420       }
   8421       if (isLittleEndian != sys::IsLittleEndianHost)
   8422         sys::swapByteOrder(flavor);
   8423       if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
   8424         memcpy((char *)&count, begin, sizeof(uint32_t));
   8425         begin += sizeof(uint32_t);
   8426       } else {
   8427         count = 0;
   8428         begin = end;
   8429       }
   8430       if (isLittleEndian != sys::IsLittleEndianHost)
   8431         sys::swapByteOrder(count);
   8432       outs() << "     flavor " << flavor << "\n";
   8433       outs() << "      count " << count << "\n";
   8434       outs() << "      state (Unknown cputype/cpusubtype)\n";
   8435       begin += count * sizeof(uint32_t);
   8436     }
   8437   }
   8438 }
   8439 
   8440 static void PrintDylibCommand(MachO::dylib_command dl, const char *Ptr) {
   8441   if (dl.cmd == MachO::LC_ID_DYLIB)
   8442     outs() << "          cmd LC_ID_DYLIB\n";
   8443   else if (dl.cmd == MachO::LC_LOAD_DYLIB)
   8444     outs() << "          cmd LC_LOAD_DYLIB\n";
   8445   else if (dl.cmd == MachO::LC_LOAD_WEAK_DYLIB)
   8446     outs() << "          cmd LC_LOAD_WEAK_DYLIB\n";
   8447   else if (dl.cmd == MachO::LC_REEXPORT_DYLIB)
   8448     outs() << "          cmd LC_REEXPORT_DYLIB\n";
   8449   else if (dl.cmd == MachO::LC_LAZY_LOAD_DYLIB)
   8450     outs() << "          cmd LC_LAZY_LOAD_DYLIB\n";
   8451   else if (dl.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
   8452     outs() << "          cmd LC_LOAD_UPWARD_DYLIB\n";
   8453   else
   8454     outs() << "          cmd " << dl.cmd << " (unknown)\n";
   8455   outs() << "      cmdsize " << dl.cmdsize;
   8456   if (dl.cmdsize < sizeof(struct MachO::dylib_command))
   8457     outs() << " Incorrect size\n";
   8458   else
   8459     outs() << "\n";
   8460   if (dl.dylib.name < dl.cmdsize) {
   8461     const char *P = (const char *)(Ptr) + dl.dylib.name;
   8462     outs() << "         name " << P << " (offset " << dl.dylib.name << ")\n";
   8463   } else {
   8464     outs() << "         name ?(bad offset " << dl.dylib.name << ")\n";
   8465   }
   8466   outs() << "   time stamp " << dl.dylib.timestamp << " ";
   8467   time_t t = dl.dylib.timestamp;
   8468   outs() << ctime(&t);
   8469   outs() << "      current version ";
   8470   if (dl.dylib.current_version == 0xffffffff)
   8471     outs() << "n/a\n";
   8472   else
   8473     outs() << ((dl.dylib.current_version >> 16) & 0xffff) << "."
   8474            << ((dl.dylib.current_version >> 8) & 0xff) << "."
   8475            << (dl.dylib.current_version & 0xff) << "\n";
   8476   outs() << "compatibility version ";
   8477   if (dl.dylib.compatibility_version == 0xffffffff)
   8478     outs() << "n/a\n";
   8479   else
   8480     outs() << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
   8481            << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
   8482            << (dl.dylib.compatibility_version & 0xff) << "\n";
   8483 }
   8484 
   8485 static void PrintLinkEditDataCommand(MachO::linkedit_data_command ld,
   8486                                      uint32_t object_size) {
   8487   if (ld.cmd == MachO::LC_CODE_SIGNATURE)
   8488     outs() << "      cmd LC_FUNCTION_STARTS\n";
   8489   else if (ld.cmd == MachO::LC_SEGMENT_SPLIT_INFO)
   8490     outs() << "      cmd LC_SEGMENT_SPLIT_INFO\n";
   8491   else if (ld.cmd == MachO::LC_FUNCTION_STARTS)
   8492     outs() << "      cmd LC_FUNCTION_STARTS\n";
   8493   else if (ld.cmd == MachO::LC_DATA_IN_CODE)
   8494     outs() << "      cmd LC_DATA_IN_CODE\n";
   8495   else if (ld.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS)
   8496     outs() << "      cmd LC_DYLIB_CODE_SIGN_DRS\n";
   8497   else if (ld.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT)
   8498     outs() << "      cmd LC_LINKER_OPTIMIZATION_HINT\n";
   8499   else
   8500     outs() << "      cmd " << ld.cmd << " (?)\n";
   8501   outs() << "  cmdsize " << ld.cmdsize;
   8502   if (ld.cmdsize != sizeof(struct MachO::linkedit_data_command))
   8503     outs() << " Incorrect size\n";
   8504   else
   8505     outs() << "\n";
   8506   outs() << "  dataoff " << ld.dataoff;
   8507   if (ld.dataoff > object_size)
   8508     outs() << " (past end of file)\n";
   8509   else
   8510     outs() << "\n";
   8511   outs() << " datasize " << ld.datasize;
   8512   uint64_t big_size = ld.dataoff;
   8513   big_size += ld.datasize;
   8514   if (big_size > object_size)
   8515     outs() << " (past end of file)\n";
   8516   else
   8517     outs() << "\n";
   8518 }
   8519 
   8520 static void PrintLoadCommands(const MachOObjectFile *Obj, uint32_t filetype,
   8521                               uint32_t cputype, bool verbose) {
   8522   StringRef Buf = Obj->getData();
   8523   unsigned Index = 0;
   8524   for (const auto &Command : Obj->load_commands()) {
   8525     outs() << "Load command " << Index++ << "\n";
   8526     if (Command.C.cmd == MachO::LC_SEGMENT) {
   8527       MachO::segment_command SLC = Obj->getSegmentLoadCommand(Command);
   8528       const char *sg_segname = SLC.segname;
   8529       PrintSegmentCommand(SLC.cmd, SLC.cmdsize, SLC.segname, SLC.vmaddr,
   8530                           SLC.vmsize, SLC.fileoff, SLC.filesize, SLC.maxprot,
   8531                           SLC.initprot, SLC.nsects, SLC.flags, Buf.size(),
   8532                           verbose);
   8533       for (unsigned j = 0; j < SLC.nsects; j++) {
   8534         MachO::section S = Obj->getSection(Command, j);
   8535         PrintSection(S.sectname, S.segname, S.addr, S.size, S.offset, S.align,
   8536                      S.reloff, S.nreloc, S.flags, S.reserved1, S.reserved2,
   8537                      SLC.cmd, sg_segname, filetype, Buf.size(), verbose);
   8538       }
   8539     } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
   8540       MachO::segment_command_64 SLC_64 = Obj->getSegment64LoadCommand(Command);
   8541       const char *sg_segname = SLC_64.segname;
   8542       PrintSegmentCommand(SLC_64.cmd, SLC_64.cmdsize, SLC_64.segname,
   8543                           SLC_64.vmaddr, SLC_64.vmsize, SLC_64.fileoff,
   8544                           SLC_64.filesize, SLC_64.maxprot, SLC_64.initprot,
   8545                           SLC_64.nsects, SLC_64.flags, Buf.size(), verbose);
   8546       for (unsigned j = 0; j < SLC_64.nsects; j++) {
   8547         MachO::section_64 S_64 = Obj->getSection64(Command, j);
   8548         PrintSection(S_64.sectname, S_64.segname, S_64.addr, S_64.size,
   8549                      S_64.offset, S_64.align, S_64.reloff, S_64.nreloc,
   8550                      S_64.flags, S_64.reserved1, S_64.reserved2, SLC_64.cmd,
   8551                      sg_segname, filetype, Buf.size(), verbose);
   8552       }
   8553     } else if (Command.C.cmd == MachO::LC_SYMTAB) {
   8554       MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
   8555       PrintSymtabLoadCommand(Symtab, Obj->is64Bit(), Buf.size());
   8556     } else if (Command.C.cmd == MachO::LC_DYSYMTAB) {
   8557       MachO::dysymtab_command Dysymtab = Obj->getDysymtabLoadCommand();
   8558       MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
   8559       PrintDysymtabLoadCommand(Dysymtab, Symtab.nsyms, Buf.size(),
   8560                                Obj->is64Bit());
   8561     } else if (Command.C.cmd == MachO::LC_DYLD_INFO ||
   8562                Command.C.cmd == MachO::LC_DYLD_INFO_ONLY) {
   8563       MachO::dyld_info_command DyldInfo = Obj->getDyldInfoLoadCommand(Command);
   8564       PrintDyldInfoLoadCommand(DyldInfo, Buf.size());
   8565     } else if (Command.C.cmd == MachO::LC_LOAD_DYLINKER ||
   8566                Command.C.cmd == MachO::LC_ID_DYLINKER ||
   8567                Command.C.cmd == MachO::LC_DYLD_ENVIRONMENT) {
   8568       MachO::dylinker_command Dyld = Obj->getDylinkerCommand(Command);
   8569       PrintDyldLoadCommand(Dyld, Command.Ptr);
   8570     } else if (Command.C.cmd == MachO::LC_UUID) {
   8571       MachO::uuid_command Uuid = Obj->getUuidCommand(Command);
   8572       PrintUuidLoadCommand(Uuid);
   8573     } else if (Command.C.cmd == MachO::LC_RPATH) {
   8574       MachO::rpath_command Rpath = Obj->getRpathCommand(Command);
   8575       PrintRpathLoadCommand(Rpath, Command.Ptr);
   8576     } else if (Command.C.cmd == MachO::LC_VERSION_MIN_MACOSX ||
   8577                Command.C.cmd == MachO::LC_VERSION_MIN_IPHONEOS ||
   8578                Command.C.cmd == MachO::LC_VERSION_MIN_TVOS ||
   8579                Command.C.cmd == MachO::LC_VERSION_MIN_WATCHOS) {
   8580       MachO::version_min_command Vd = Obj->getVersionMinLoadCommand(Command);
   8581       PrintVersionMinLoadCommand(Vd);
   8582     } else if (Command.C.cmd == MachO::LC_SOURCE_VERSION) {
   8583       MachO::source_version_command Sd = Obj->getSourceVersionCommand(Command);
   8584       PrintSourceVersionCommand(Sd);
   8585     } else if (Command.C.cmd == MachO::LC_MAIN) {
   8586       MachO::entry_point_command Ep = Obj->getEntryPointCommand(Command);
   8587       PrintEntryPointCommand(Ep);
   8588     } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO) {
   8589       MachO::encryption_info_command Ei =
   8590           Obj->getEncryptionInfoCommand(Command);
   8591       PrintEncryptionInfoCommand(Ei, Buf.size());
   8592     } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO_64) {
   8593       MachO::encryption_info_command_64 Ei =
   8594           Obj->getEncryptionInfoCommand64(Command);
   8595       PrintEncryptionInfoCommand64(Ei, Buf.size());
   8596     } else if (Command.C.cmd == MachO::LC_LINKER_OPTION) {
   8597       MachO::linker_option_command Lo =
   8598           Obj->getLinkerOptionLoadCommand(Command);
   8599       PrintLinkerOptionCommand(Lo, Command.Ptr);
   8600     } else if (Command.C.cmd == MachO::LC_SUB_FRAMEWORK) {
   8601       MachO::sub_framework_command Sf = Obj->getSubFrameworkCommand(Command);
   8602       PrintSubFrameworkCommand(Sf, Command.Ptr);
   8603     } else if (Command.C.cmd == MachO::LC_SUB_UMBRELLA) {
   8604       MachO::sub_umbrella_command Sf = Obj->getSubUmbrellaCommand(Command);
   8605       PrintSubUmbrellaCommand(Sf, Command.Ptr);
   8606     } else if (Command.C.cmd == MachO::LC_SUB_LIBRARY) {
   8607       MachO::sub_library_command Sl = Obj->getSubLibraryCommand(Command);
   8608       PrintSubLibraryCommand(Sl, Command.Ptr);
   8609     } else if (Command.C.cmd == MachO::LC_SUB_CLIENT) {
   8610       MachO::sub_client_command Sc = Obj->getSubClientCommand(Command);
   8611       PrintSubClientCommand(Sc, Command.Ptr);
   8612     } else if (Command.C.cmd == MachO::LC_ROUTINES) {
   8613       MachO::routines_command Rc = Obj->getRoutinesCommand(Command);
   8614       PrintRoutinesCommand(Rc);
   8615     } else if (Command.C.cmd == MachO::LC_ROUTINES_64) {
   8616       MachO::routines_command_64 Rc = Obj->getRoutinesCommand64(Command);
   8617       PrintRoutinesCommand64(Rc);
   8618     } else if (Command.C.cmd == MachO::LC_THREAD ||
   8619                Command.C.cmd == MachO::LC_UNIXTHREAD) {
   8620       MachO::thread_command Tc = Obj->getThreadCommand(Command);
   8621       PrintThreadCommand(Tc, Command.Ptr, Obj->isLittleEndian(), cputype);
   8622     } else if (Command.C.cmd == MachO::LC_LOAD_DYLIB ||
   8623                Command.C.cmd == MachO::LC_ID_DYLIB ||
   8624                Command.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
   8625                Command.C.cmd == MachO::LC_REEXPORT_DYLIB ||
   8626                Command.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
   8627                Command.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB) {
   8628       MachO::dylib_command Dl = Obj->getDylibIDLoadCommand(Command);
   8629       PrintDylibCommand(Dl, Command.Ptr);
   8630     } else if (Command.C.cmd == MachO::LC_CODE_SIGNATURE ||
   8631                Command.C.cmd == MachO::LC_SEGMENT_SPLIT_INFO ||
   8632                Command.C.cmd == MachO::LC_FUNCTION_STARTS ||
   8633                Command.C.cmd == MachO::LC_DATA_IN_CODE ||
   8634                Command.C.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS ||
   8635                Command.C.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT) {
   8636       MachO::linkedit_data_command Ld =
   8637           Obj->getLinkeditDataLoadCommand(Command);
   8638       PrintLinkEditDataCommand(Ld, Buf.size());
   8639     } else {
   8640       outs() << "      cmd ?(" << format("0x%08" PRIx32, Command.C.cmd)
   8641              << ")\n";
   8642       outs() << "  cmdsize " << Command.C.cmdsize << "\n";
   8643       // TODO: get and print the raw bytes of the load command.
   8644     }
   8645     // TODO: print all the other kinds of load commands.
   8646   }
   8647 }
   8648 
   8649 static void getAndPrintMachHeader(const MachOObjectFile *Obj,
   8650                                   uint32_t &filetype, uint32_t &cputype,
   8651                                   bool verbose) {
   8652   if (Obj->is64Bit()) {
   8653     MachO::mach_header_64 H_64;
   8654     H_64 = Obj->getHeader64();
   8655     PrintMachHeader(H_64.magic, H_64.cputype, H_64.cpusubtype, H_64.filetype,
   8656                     H_64.ncmds, H_64.sizeofcmds, H_64.flags, verbose);
   8657     filetype = H_64.filetype;
   8658     cputype = H_64.cputype;
   8659   } else {
   8660     MachO::mach_header H;
   8661     H = Obj->getHeader();
   8662     PrintMachHeader(H.magic, H.cputype, H.cpusubtype, H.filetype, H.ncmds,
   8663                     H.sizeofcmds, H.flags, verbose);
   8664     filetype = H.filetype;
   8665     cputype = H.cputype;
   8666   }
   8667 }
   8668 
   8669 void llvm::printMachOFileHeader(const object::ObjectFile *Obj) {
   8670   const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
   8671   uint32_t filetype = 0;
   8672   uint32_t cputype = 0;
   8673   getAndPrintMachHeader(file, filetype, cputype, !NonVerbose);
   8674   PrintLoadCommands(file, filetype, cputype, !NonVerbose);
   8675 }
   8676 
   8677 //===----------------------------------------------------------------------===//
   8678 // export trie dumping
   8679 //===----------------------------------------------------------------------===//
   8680 
   8681 void llvm::printMachOExportsTrie(const object::MachOObjectFile *Obj) {
   8682   for (const llvm::object::ExportEntry &Entry : Obj->exports()) {
   8683     uint64_t Flags = Entry.flags();
   8684     bool ReExport = (Flags & MachO::EXPORT_SYMBOL_FLAGS_REEXPORT);
   8685     bool WeakDef = (Flags & MachO::EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION);
   8686     bool ThreadLocal = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
   8687                         MachO::EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL);
   8688     bool Abs = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
   8689                 MachO::EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE);
   8690     bool Resolver = (Flags & MachO::EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER);
   8691     if (ReExport)
   8692       outs() << "[re-export] ";
   8693     else
   8694       outs() << format("0x%08llX  ",
   8695                        Entry.address()); // FIXME:add in base address
   8696     outs() << Entry.name();
   8697     if (WeakDef || ThreadLocal || Resolver || Abs) {
   8698       bool NeedsComma = false;
   8699       outs() << " [";
   8700       if (WeakDef) {
   8701         outs() << "weak_def";
   8702         NeedsComma = true;
   8703       }
   8704       if (ThreadLocal) {
   8705         if (NeedsComma)
   8706           outs() << ", ";
   8707         outs() << "per-thread";
   8708         NeedsComma = true;
   8709       }
   8710       if (Abs) {
   8711         if (NeedsComma)
   8712           outs() << ", ";
   8713         outs() << "absolute";
   8714         NeedsComma = true;
   8715       }
   8716       if (Resolver) {
   8717         if (NeedsComma)
   8718           outs() << ", ";
   8719         outs() << format("resolver=0x%08llX", Entry.other());
   8720         NeedsComma = true;
   8721       }
   8722       outs() << "]";
   8723     }
   8724     if (ReExport) {
   8725       StringRef DylibName = "unknown";
   8726       int Ordinal = Entry.other() - 1;
   8727       Obj->getLibraryShortNameByIndex(Ordinal, DylibName);
   8728       if (Entry.otherName().empty())
   8729         outs() << " (from " << DylibName << ")";
   8730       else
   8731         outs() << " (" << Entry.otherName() << " from " << DylibName << ")";
   8732     }
   8733     outs() << "\n";
   8734   }
   8735 }
   8736 
   8737 //===----------------------------------------------------------------------===//
   8738 // rebase table dumping
   8739 //===----------------------------------------------------------------------===//
   8740 
   8741 namespace {
   8742 class SegInfo {
   8743 public:
   8744   SegInfo(const object::MachOObjectFile *Obj);
   8745 
   8746   StringRef segmentName(uint32_t SegIndex);
   8747   StringRef sectionName(uint32_t SegIndex, uint64_t SegOffset);
   8748   uint64_t address(uint32_t SegIndex, uint64_t SegOffset);
   8749   bool isValidSegIndexAndOffset(uint32_t SegIndex, uint64_t SegOffset);
   8750 
   8751 private:
   8752   struct SectionInfo {
   8753     uint64_t Address;
   8754     uint64_t Size;
   8755     StringRef SectionName;
   8756     StringRef SegmentName;
   8757     uint64_t OffsetInSegment;
   8758     uint64_t SegmentStartAddress;
   8759     uint32_t SegmentIndex;
   8760   };
   8761   const SectionInfo &findSection(uint32_t SegIndex, uint64_t SegOffset);
   8762   SmallVector<SectionInfo, 32> Sections;
   8763 };
   8764 }
   8765 
   8766 SegInfo::SegInfo(const object::MachOObjectFile *Obj) {
   8767   // Build table of sections so segIndex/offset pairs can be translated.
   8768   uint32_t CurSegIndex = Obj->hasPageZeroSegment() ? 1 : 0;
   8769   StringRef CurSegName;
   8770   uint64_t CurSegAddress;
   8771   for (const SectionRef &Section : Obj->sections()) {
   8772     SectionInfo Info;
   8773     error(Section.getName(Info.SectionName));
   8774     Info.Address = Section.getAddress();
   8775     Info.Size = Section.getSize();
   8776     Info.SegmentName =
   8777         Obj->getSectionFinalSegmentName(Section.getRawDataRefImpl());
   8778     if (!Info.SegmentName.equals(CurSegName)) {
   8779       ++CurSegIndex;
   8780       CurSegName = Info.SegmentName;
   8781       CurSegAddress = Info.Address;
   8782     }
   8783     Info.SegmentIndex = CurSegIndex - 1;
   8784     Info.OffsetInSegment = Info.Address - CurSegAddress;
   8785     Info.SegmentStartAddress = CurSegAddress;
   8786     Sections.push_back(Info);
   8787   }
   8788 }
   8789 
   8790 StringRef SegInfo::segmentName(uint32_t SegIndex) {
   8791   for (const SectionInfo &SI : Sections) {
   8792     if (SI.SegmentIndex == SegIndex)
   8793       return SI.SegmentName;
   8794   }
   8795   llvm_unreachable("invalid segIndex");
   8796 }
   8797 
   8798 bool SegInfo::isValidSegIndexAndOffset(uint32_t SegIndex,
   8799                                        uint64_t OffsetInSeg) {
   8800   for (const SectionInfo &SI : Sections) {
   8801     if (SI.SegmentIndex != SegIndex)
   8802       continue;
   8803     if (SI.OffsetInSegment > OffsetInSeg)
   8804       continue;
   8805     if (OffsetInSeg >= (SI.OffsetInSegment + SI.Size))
   8806       continue;
   8807     return true;
   8808   }
   8809   return false;
   8810 }
   8811 
   8812 const SegInfo::SectionInfo &SegInfo::findSection(uint32_t SegIndex,
   8813                                                  uint64_t OffsetInSeg) {
   8814   for (const SectionInfo &SI : Sections) {
   8815     if (SI.SegmentIndex != SegIndex)
   8816       continue;
   8817     if (SI.OffsetInSegment > OffsetInSeg)
   8818       continue;
   8819     if (OffsetInSeg >= (SI.OffsetInSegment + SI.Size))
   8820       continue;
   8821     return SI;
   8822   }
   8823   llvm_unreachable("segIndex and offset not in any section");
   8824 }
   8825 
   8826 StringRef SegInfo::sectionName(uint32_t SegIndex, uint64_t OffsetInSeg) {
   8827   return findSection(SegIndex, OffsetInSeg).SectionName;
   8828 }
   8829 
   8830 uint64_t SegInfo::address(uint32_t SegIndex, uint64_t OffsetInSeg) {
   8831   const SectionInfo &SI = findSection(SegIndex, OffsetInSeg);
   8832   return SI.SegmentStartAddress + OffsetInSeg;
   8833 }
   8834 
   8835 void llvm::printMachORebaseTable(const object::MachOObjectFile *Obj) {
   8836   // Build table of sections so names can used in final output.
   8837   SegInfo sectionTable(Obj);
   8838 
   8839   outs() << "segment  section            address     type\n";
   8840   for (const llvm::object::MachORebaseEntry &Entry : Obj->rebaseTable()) {
   8841     uint32_t SegIndex = Entry.segmentIndex();
   8842     uint64_t OffsetInSeg = Entry.segmentOffset();
   8843     StringRef SegmentName = sectionTable.segmentName(SegIndex);
   8844     StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
   8845     uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
   8846 
   8847     // Table lines look like: __DATA  __nl_symbol_ptr  0x0000F00C  pointer
   8848     outs() << format("%-8s %-18s 0x%08" PRIX64 "  %s\n",
   8849                      SegmentName.str().c_str(), SectionName.str().c_str(),
   8850                      Address, Entry.typeName().str().c_str());
   8851   }
   8852 }
   8853 
   8854 static StringRef ordinalName(const object::MachOObjectFile *Obj, int Ordinal) {
   8855   StringRef DylibName;
   8856   switch (Ordinal) {
   8857   case MachO::BIND_SPECIAL_DYLIB_SELF:
   8858     return "this-image";
   8859   case MachO::BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE:
   8860     return "main-executable";
   8861   case MachO::BIND_SPECIAL_DYLIB_FLAT_LOOKUP:
   8862     return "flat-namespace";
   8863   default:
   8864     if (Ordinal > 0) {
   8865       std::error_code EC =
   8866           Obj->getLibraryShortNameByIndex(Ordinal - 1, DylibName);
   8867       if (EC)
   8868         return "<<bad library ordinal>>";
   8869       return DylibName;
   8870     }
   8871   }
   8872   return "<<unknown special ordinal>>";
   8873 }
   8874 
   8875 //===----------------------------------------------------------------------===//
   8876 // bind table dumping
   8877 //===----------------------------------------------------------------------===//
   8878 
   8879 void llvm::printMachOBindTable(const object::MachOObjectFile *Obj) {
   8880   // Build table of sections so names can used in final output.
   8881   SegInfo sectionTable(Obj);
   8882 
   8883   outs() << "segment  section            address    type       "
   8884             "addend dylib            symbol\n";
   8885   for (const llvm::object::MachOBindEntry &Entry : Obj->bindTable()) {
   8886     uint32_t SegIndex = Entry.segmentIndex();
   8887     uint64_t OffsetInSeg = Entry.segmentOffset();
   8888     StringRef SegmentName = sectionTable.segmentName(SegIndex);
   8889     StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
   8890     uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
   8891 
   8892     // Table lines look like:
   8893     //  __DATA  __got  0x00012010    pointer   0 libSystem ___stack_chk_guard
   8894     StringRef Attr;
   8895     if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_WEAK_IMPORT)
   8896       Attr = " (weak_import)";
   8897     outs() << left_justify(SegmentName, 8) << " "
   8898            << left_justify(SectionName, 18) << " "
   8899            << format_hex(Address, 10, true) << " "
   8900            << left_justify(Entry.typeName(), 8) << " "
   8901            << format_decimal(Entry.addend(), 8) << " "
   8902            << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
   8903            << Entry.symbolName() << Attr << "\n";
   8904   }
   8905 }
   8906 
   8907 //===----------------------------------------------------------------------===//
   8908 // lazy bind table dumping
   8909 //===----------------------------------------------------------------------===//
   8910 
   8911 void llvm::printMachOLazyBindTable(const object::MachOObjectFile *Obj) {
   8912   // Build table of sections so names can used in final output.
   8913   SegInfo sectionTable(Obj);
   8914 
   8915   outs() << "segment  section            address     "
   8916             "dylib            symbol\n";
   8917   for (const llvm::object::MachOBindEntry &Entry : Obj->lazyBindTable()) {
   8918     uint32_t SegIndex = Entry.segmentIndex();
   8919     uint64_t OffsetInSeg = Entry.segmentOffset();
   8920     StringRef SegmentName = sectionTable.segmentName(SegIndex);
   8921     StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
   8922     uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
   8923 
   8924     // Table lines look like:
   8925     //  __DATA  __got  0x00012010 libSystem ___stack_chk_guard
   8926     outs() << left_justify(SegmentName, 8) << " "
   8927            << left_justify(SectionName, 18) << " "
   8928            << format_hex(Address, 10, true) << " "
   8929            << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
   8930            << Entry.symbolName() << "\n";
   8931   }
   8932 }
   8933 
   8934 //===----------------------------------------------------------------------===//
   8935 // weak bind table dumping
   8936 //===----------------------------------------------------------------------===//
   8937 
   8938 void llvm::printMachOWeakBindTable(const object::MachOObjectFile *Obj) {
   8939   // Build table of sections so names can used in final output.
   8940   SegInfo sectionTable(Obj);
   8941 
   8942   outs() << "segment  section            address     "
   8943             "type       addend   symbol\n";
   8944   for (const llvm::object::MachOBindEntry &Entry : Obj->weakBindTable()) {
   8945     // Strong symbols don't have a location to update.
   8946     if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION) {
   8947       outs() << "                                        strong              "
   8948              << Entry.symbolName() << "\n";
   8949       continue;
   8950     }
   8951     uint32_t SegIndex = Entry.segmentIndex();
   8952     uint64_t OffsetInSeg = Entry.segmentOffset();
   8953     StringRef SegmentName = sectionTable.segmentName(SegIndex);
   8954     StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
   8955     uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
   8956 
   8957     // Table lines look like:
   8958     // __DATA  __data  0x00001000  pointer    0   _foo
   8959     outs() << left_justify(SegmentName, 8) << " "
   8960            << left_justify(SectionName, 18) << " "
   8961            << format_hex(Address, 10, true) << " "
   8962            << left_justify(Entry.typeName(), 8) << " "
   8963            << format_decimal(Entry.addend(), 8) << "   " << Entry.symbolName()
   8964            << "\n";
   8965   }
   8966 }
   8967 
   8968 // get_dyld_bind_info_symbolname() is used for disassembly and passed an
   8969 // address, ReferenceValue, in the Mach-O file and looks in the dyld bind
   8970 // information for that address. If the address is found its binding symbol
   8971 // name is returned.  If not nullptr is returned.
   8972 static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
   8973                                                  struct DisassembleInfo *info) {
   8974   if (info->bindtable == nullptr) {
   8975     info->bindtable = new (BindTable);
   8976     SegInfo sectionTable(info->O);
   8977     for (const llvm::object::MachOBindEntry &Entry : info->O->bindTable()) {
   8978       uint32_t SegIndex = Entry.segmentIndex();
   8979       uint64_t OffsetInSeg = Entry.segmentOffset();
   8980       if (!sectionTable.isValidSegIndexAndOffset(SegIndex, OffsetInSeg))
   8981         continue;
   8982       uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
   8983       const char *SymbolName = nullptr;
   8984       StringRef name = Entry.symbolName();
   8985       if (!name.empty())
   8986         SymbolName = name.data();
   8987       info->bindtable->push_back(std::make_pair(Address, SymbolName));
   8988     }
   8989   }
   8990   for (bind_table_iterator BI = info->bindtable->begin(),
   8991                            BE = info->bindtable->end();
   8992        BI != BE; ++BI) {
   8993     uint64_t Address = BI->first;
   8994     if (ReferenceValue == Address) {
   8995       const char *SymbolName = BI->second;
   8996       return SymbolName;
   8997     }
   8998   }
   8999   return nullptr;
   9000 }
   9001