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