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